From 593b0e0e251565dfc674db8c8d1e23f35dfd5b98 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?King=20K=C3=A9vin?= Date: Tue, 3 Apr 2018 16:59:02 +0200 Subject: [PATCH] take changes from busvoodoo branch --- Rakefile | 12 +- bootloader.c | 9 +- global.c | 82 +++++- global.h | 73 ++--- lib/i2c_master.c | 708 +++++++++++++++++++++++++++++++---------------- lib/i2c_master.h | 108 ++++++-- lib/menu.c | 10 +- lib/menu.h | 4 +- lib/print.c | 3 + lib/terminal.h | 4 +- lib/uart.c | 10 +- lib/usb_cdcacm.c | 163 ++++++----- lib/usb_cdcacm.h | 3 + lib/usb_dfu.c | 17 +- 14 files changed, 801 insertions(+), 405 deletions(-) diff --git a/Rakefile b/Rakefile index 22c6a12..db969f1 100644 --- a/Rakefile +++ b/Rakefile @@ -14,7 +14,7 @@ APPLICATION = "application" FIRMWARES = [BOOTLOADER, APPLICATION] # which development board is used -# supported are: SYSTEM_BOARD, MAPLE_MINI, BLUE_PILL, CORE_BOARD +# supported are: SYSTEM_BOARD, MAPLE_MINI, BLUE_PILL, CORE_BOARD, BUSVOODOO BOARD = ENV["BOARD"] || "CORE_BOARD" # libopencm3 definitions @@ -72,7 +72,7 @@ ldflags << "-nostartfiles" # only keep used sections ldflags << "--gc-sections" # add standard libraries (for libc, libm, libnosys, libgcc) because we don't use arm-none-eabi-gcc to locate them -library_paths = ["/usr/arm-none-eabi/lib/armv7-m/", "/usr/lib/gcc/arm-none-eabi/*/armv7-m/"] +library_paths = ["/usr/arm-none-eabi/lib/armv7-m/", "/usr/lib/arm-none-eabi/lib/armv7-m/", "/usr/lib/gcc/arm-none-eabi/*/armv7-m/"] # add libopencm3 library_paths += [LIBOPENCM3_LIB] # include libraries in flags @@ -144,7 +144,7 @@ task :doc => ["Doxyfile", "README.md"] do |t| end desc "compile source into object" -rule '.o' => ['.c', proc{|f| File.file?(f.ext("h")) ? f.ext("h") : []}, "#{LIBOPENCM3_LIB}/lib#{STM32F1_LIB}.a"] do |t| +rule '.o' => ['.c', proc{|f| File.file?(f.ext("h")) ? f.ext("h") : []}, proc{|f| dependencies(f).collect{|d| File.file?(d.ext("h")) ? d.ext("h") : []}}, "#{LIBOPENCM3_LIB}/lib#{STM32F1_LIB}.a"] do |t| sh "#{CC} #{cflags} #{archflags} -o #{t.name} -c #{t.prerequisites[0]}" end @@ -154,7 +154,7 @@ rule '.d' => ['.c', "#{LIBOPENCM3_LIB}/lib#{STM32F1_LIB}.a"] do |t| end desc "link binary" -rule '.elf' => [proc{|f| dependencies(f)}, '.ld', "#{LIBOPENCM3_LIB}/lib#{STM32F1_LIB}.a"] do |t| +rule '.elf' => ['.o', proc{|f| dependencies(f)}, '.ld', "#{LIBOPENCM3_LIB}/lib#{STM32F1_LIB}.a"] do |t| sh "#{LD} #{ldflags} --script #{t.name.ext('ld')} #{t.prerequisites[0..-3].join(' ')} #{ldlibs} -o #{t.name}" sh "size #{t.name}" end @@ -198,7 +198,7 @@ BMP_PORT = ENV["BMP_PORT"] || "/dev/ttyACM0" desc "flash application using USB DFU" task :flash => APPLICATION+".bin" do |t| - sh "dfu-util -d c440:0d00 -D #{t.source}" + sh "dfu-util -d 1209:4356 -D #{t.source}" end desc "flash bootloader using SWD" @@ -227,7 +227,7 @@ task :debug => APPLICATION+".elf" do |t| case SWD_ADAPTER when "STLINKV2" # for GDB to work with openOCD the firmware needs to be reloaded - exec("#{GDB} --eval-command='target remote | #{OOCD} --file interface/#{OOCD_INTERFACE}.cfg --file target/#{OOCD_TARGET}.cfg --command \"gdb_port pipe; log_output /dev/null; init\"' --eval-command='monitor reset halt' --eval-command='load' --eval-command='monitor reset init' #{t.source}") + excec("#{GDB} --eval-command='target remote | #{OOCD} --file interface/#{OOCD_INTERFACE}.cfg --file target/#{OOCD_TARGET}.cfg --command \"gdb_port pipe; log_output /dev/null; init\"' --eval-command='monitor reset halt' --eval-command='load' --eval-command='monitor reset init' #{t.source}") when "BMP" exec("#{GDB} --eval-command='target extended-remote #{BMP_PORT}' --eval-command='monitor version' --eval-command='monitor swdp_scan' --eval-command='attach 1' #{t.source}") end diff --git a/bootloader.c b/bootloader.c index b322e06..0087d5a 100644 --- a/bootloader.c +++ b/bootloader.c @@ -39,16 +39,13 @@ void main(void) // check if a soft boot has been used if (0==(RCC_CSR&0xfc000000)) { // no reset flag present -> this was a soft reset using scb_reset_core() after clearing the flags using RCC_CSR_RMVF, very probably to start the DFU mode dfu_force = true; - } else { // check if + } else { // check if the force DFU mode input is set // disable SWJ pin to use as GPIO #if (GPIO(B)==GPIO(DFU_FORCE_PORT)) && (GPIO(4)==GPIO(DFU_FORCE_PIN)) - rcc_periph_clock_enable(RCC_AFIO); // enable clock for alternate function domain (SWJ) gpio_primary_remap(AFIO_MAPR_SWJ_CFG_FULL_SWJ_NO_JNTRST, 0); #elif ((GPIO(B)==GPIO(DFU_FORCE_PORT)) && (GPIO(3)==GPIO(DFU_FORCE_PIN))) || ((GPIO(A)==GPIO(DFU_FORCE_PORT)) && (GPIO(15)==GPIO(DFU_FORCE_PIN))) - rcc_periph_clock_enable(RCC_AFIO); // enable clock for alternate function domain (SWJ) gpio_primary_remap(AFIO_MAPR_SWJ_CFG_JTAG_OFF_SW_ON, 0); #elif ((GPIO(A)==GPIO(DFU_FORCE_PORT)) && (GPIO(14)==GPIO(DFU_FORCE_PIN))) || ((GPIO(A)==GPIO(DFU_FORCE_PORT)) && (GPIO(13)==GPIO(DFU_FORCE_PIN))) - rcc_periph_clock_enable(RCC_AFIO); // enable clock for alternate function domain (SWJ) gpio_primary_remap(AFIO_MAPR_SWJ_CFG_JTAG_OFF_SW_OFF, 0); #endif rcc_periph_clock_enable(RCC_GPIO(DFU_FORCE_PORT)); // enable clock for GPIO domain @@ -83,7 +80,11 @@ void main(void) rcc_clock_setup_in_hse_8mhz_out_72mhz(); // start main clock board_setup(); // setup board to control LED +#if defined(BUSVOODOO) + led_red(); // switch red LED to indicate bootloader started +#else led_on(); // indicate bootloader started +#endif usb_dfu_setup(); // setup USB DFU for firmware upload usb_dfu_start(); // run DFU mode } diff --git a/global.c b/global.c index a3c083f..5adad39 100644 --- a/global.c +++ b/global.c @@ -34,13 +34,14 @@ #include "global.h" // common methods volatile bool button_flag = false; -volatile uint32_t sleep_duration = 0; /**< sleep duration count down (in SysTick interrupts) */ volatile bool user_input_available = false; static volatile uint8_t user_input_buffer[64] = {0}; /**< ring buffer for received data */ static volatile uint8_t user_input_i = 0; /**< current position of read received data */ static volatile uint8_t user_input_used = 0; /**< how much data has been received and not red */ +static volatile uint32_t sleep_duration = 0; /**< sleep duration count down (in SysTick interrupts) */ + char* b2s(uint64_t binary, uint8_t rjust) { static char string[64+1] = {0}; // the string representation to return @@ -66,6 +67,10 @@ char* b2s(uint64_t binary, uint8_t rjust) /** switch on board LED */ void led_on(void) { +#if defined(BUSVOODOO) + timer_disable_counter(TIM1); // disable timer for PWM + gpio_set_mode(GPIO(LED_PORT), GPIO_MODE_OUTPUT_2_MHZ, GPIO_CNF_OUTPUT_PUSHPULL, GPIO(LED_PIN)); // set LED pin to 'output push-pull' +#endif #if defined(LED_ON) && LED_ON gpio_set(GPIO(LED_PORT), GPIO(LED_PIN)); #else @@ -76,28 +81,77 @@ void led_on(void) /** switch off board LED */ void led_off(void) { +#if defined(BUSVOODOO) + timer_disable_counter(TIM1); // disable timer for PWM + gpio_set_mode(GPIO(LED_PORT), GPIO_MODE_INPUT, GPIO_CNF_INPUT_FLOAT, GPIO(LED_PIN)); // set LED pin to 'output push-pull' +#else #if defined(LED_ON) && LED_ON gpio_clear(GPIO(LED_PORT), GPIO(LED_PIN)); #else gpio_set(GPIO(LED_PORT), GPIO(LED_PIN)); #endif +#endif } /** toggle board LED */ void led_toggle(void) { +#if defined(BUSVOODOO) + timer_disable_counter(TIM1); // disable timer for PWM + gpio_set_mode(GPIO(LED_PORT), GPIO_MODE_OUTPUT_2_MHZ, GPIO_CNF_OUTPUT_PUSHPULL, GPIO(LED_PIN)); // set LED pin to 'output push-pull' +#endif gpio_toggle(GPIO(LED_PORT), GPIO(LED_PIN)); } +#if defined(BUSVOODOO) +void led_blink(double period, double duty) +{ + if (period<0.0 || period>6.0 || duty<0.0 || duty>1.0) { // input argument out of bounds + return; // do nothing + } + timer_disable_counter(TIM1); // disable timer for PWM before resetting it + if (0.0==period) { // no blinking + gpio_set_mode(GPIO(LED_PORT), GPIO_MODE_OUTPUT_2_MHZ, GPIO_CNF_OUTPUT_PUSHPULL, GPIO(LED_PIN)); // set LED pin as normal output + if (duty>0.5) { // LED should be on + gpio_set(GPIO(LED_PORT), GPIO(LED_PIN)); // switch LED on + } else { // LED should be off + gpio_clear(GPIO(LED_PORT), GPIO(LED_PIN)); // switch LED off + } + } else { + gpio_set_mode(GPIO(LED_PORT), GPIO_MODE_OUTPUT_2_MHZ, GPIO_CNF_OUTPUT_ALTFN_PUSHPULL, GPIO(LED_PIN)); // set LED pin to alternate function for PWM + timer_set_counter(TIM1, 0); // reset counter + timer_set_period(TIM1, 0xffff*(period/6.0)); // set period + timer_set_oc_value(TIM1, TIM_OC1, 0xffff*(period/6.0)*duty); // PWM duty cycle + timer_enable_counter(TIM1); // enable timer to start blinking + } +} + +void led_blue(void) +{ + timer_disable_counter(TIM1); // disable timer for PWM + gpio_set_mode(GPIO(LED_PORT), GPIO_MODE_OUTPUT_2_MHZ, GPIO_CNF_OUTPUT_PUSHPULL, GPIO(LED_PIN)); // set LED pin to 'output push-pull' + gpio_set(GPIO(LED_PORT), GPIO(LED_PIN)); +} + +void led_red(void) +{ + timer_disable_counter(TIM1); // disable timer for PWM + gpio_set_mode(GPIO(LED_PORT), GPIO_MODE_OUTPUT_2_MHZ, GPIO_CNF_OUTPUT_PUSHPULL, GPIO(LED_PIN)); // set LED pin to 'output push-pull' + gpio_clear(GPIO(LED_PORT), GPIO(LED_PIN)); +} +#endif + void sleep_us(uint32_t duration) { systick_counter_disable(); // disable SysTick to reconfigure it + if (!systick_set_frequency(1000000,rcc_ahb_frequency)) { // set SysTick frequency to microseconds + while (true); // unhandled error + } systick_clear(); // reset SysTick - systick_set_frequency(1000000,rcc_ahb_frequency); // set SysTick frequency to microseconds systick_interrupt_enable(); // enable interrupt to count duration sleep_duration = duration; // save sleep duration for count down systick_counter_enable(); // start counting - while (sleep_duration) { // wait for count down to complete + while (sleep_duration>0) { // wait for count down to complete __WFI(); // go to sleep } } @@ -105,25 +159,28 @@ void sleep_us(uint32_t duration) void sleep_ms(uint32_t duration) { systick_counter_disable(); // disable SysTick to reconfigure it + if (!systick_set_frequency(1000,rcc_ahb_frequency)) { // set SysTick frequency to milliseconds + while (true); // unhandled error + } systick_clear(); // reset SysTick - systick_set_frequency(1000,rcc_ahb_frequency); // set SysTick frequency to milliseconds systick_interrupt_enable(); // enable interrupt to count duration sleep_duration = duration; // save sleep duration for count down systick_counter_enable(); // start counting - while (sleep_duration) { // wait for count down to complete - __WFI(); // go to sleep + while (sleep_duration>0) { // wait for count down to complete +// __WFI(); // go to sleep } } /** SysTick interrupt handler */ void sys_tick_handler(void) { - if (sleep_duration) { + if (sleep_duration>0) { sleep_duration--; // decrement duration } if (0==sleep_duration) { // sleep complete systick_counter_disable(); // stop systick systick_interrupt_disable(); // stop interrupting + sleep_duration = 0; // ensure it still is at 0 } } @@ -155,7 +212,18 @@ void board_setup(void) { // setup LED rcc_periph_clock_enable(RCC_GPIO(LED_PORT)); // enable clock for LED +#if defined(BUSVOODOO) + // LED is connected to TIM1_CH1, allowing to used the PWM output so to display patterns + rcc_periph_clock_enable(RCC_TIM1); // enable clock for timer domain + timer_reset(TIM1); // reset timer configuration + timer_set_mode(TIM1, TIM_CR1_CKD_CK_INT, TIM_CR1_CMS_CENTER_1, TIM_CR1_DIR_UP); // configure timer to up counting mode (center aligned for more precise duty cycle control) + timer_set_oc_mode(TIM1, TIM_OC1, TIM_OCM_PWM1); // use PWM output compare mode + timer_enable_oc_output(TIM1, TIM_OC1); // enable output compare output + timer_enable_break_main_output(TIM1); // required to enable timer, even when no dead time is used + timer_set_prescaler(TIM1, 3296-1); // set prescaler to allow 3/3 seconds PWM output (72MHz/2^16/3296=0.33Hz) +#else gpio_set_mode(GPIO(LED_PORT), GPIO_MODE_OUTPUT_2_MHZ, GPIO_CNF_OUTPUT_PUSHPULL, GPIO(LED_PIN)); // set LED pin to 'output push-pull' +#endif led_off(); // switch off LED per default // setup button diff --git a/global.h b/global.h index f4fb894..689e70b 100644 --- a/global.h +++ b/global.h @@ -20,7 +20,7 @@ #pragma once /** enable debugging functionalities */ -#define DEBUG true +#define DEBUG false /** get the length of an array */ #define LENGTH(x) (sizeof(x) / sizeof((x)[0])) @@ -181,25 +181,32 @@ /** get USART based on USART identifier */ #define USART(x) CAT2(USART,x) /** get RCC for USART based on USART identifier */ -#define USART_RCC(x) CAT2(RCC_USART,x) +#define RCC_USART(x) CAT2(RCC_USART,x) /** get NVIC IRQ for USART based on USART identifier */ #define USART_IRQ(x) CAT3(NVIC_USART,x,_IRQ) /** get interrupt service routine for USART based on USART identifier */ #define USART_ISR(x) CAT3(usart,x,_isr) -/** get port for USART based on USART identifier */ -#define USART_PORT(x) CAT2(USART_PORT,x) -#define USART_PORT1 GPIOA /**< USART 1 is on port A */ -#define USART_PORT2 GPIOA /**< USART 2 is on port A */ -#define USART_PORT3 GPIOB /**< USART 3 is on port B */ +/** get port for USART transmit pin based on USART identifier */ +#define USART_TX_PORT(x) CAT3(GPIO_BANK_USART,x,_TX) +/** get port for USART receive pin based on USART identifier */ +#define USART_RX_PORT(x) CAT3(GPIO_BANK_USART,x,_RX) +/** get port for USART RTS pin based on USART identifier */ +#define USART_RTS_PORT(x) CAT3(GPIO_BANK_USART,x,_RTS) +/** get port for USART CTS pin based on USART identifier */ +#define USART_CTS_PORT(x) CAT3(GPIO_BANK_USART,x,_CTS) +/** get pin for USART transmit pin based on USART identifier */ +#define USART_TX_PIN(x) CAT3(GPIO_USART,x,_TX) +/** get pin for USART receive pin based on USART identifier */ +#define USART_RX_PIN(x) CAT3(GPIO_USART,x,_RX) +/** get pin for USART RTS pin based on USART identifier */ +#define USART_RTS_PIN(x) CAT3(GPIO_USART,x,_RTS) +/** get pin for USART CTS pin based on USART identifier */ +#define USART_CTS_PIN(x) CAT3(GPIO_USART,x,_CTS) /** get RCC for USART port based on USART identifier */ -#define USART_PORT_RCC(x) CAT2(RCC_USART_PORT,x) +#define RCC_USART_PORT(x) CAT2(RCC_USART_PORT,x) #define RCC_USART_PORT1 RCC_GPIOA /**< USART 1 is on port A */ #define RCC_USART_PORT2 RCC_GPIOA /**< USART 2 is on port A */ #define RCC_USART_PORT3 RCC_GPIOB /**< USART 3 is on port B */ -/** get transmit pin for USART based on USART identifier */ -#define USART_PIN_TX(x) CAT3(GPIO_USART,x,_TX) -/** get receive pin for USART based on USART identifier */ -#define USART_PIN_RX(x) CAT3(GPIO_USART,x,_RX) /** get port based on ADC12_IN identifier */ #define ADC12_IN_PORT(x) CAT3(ADC12_IN,x,_PORT) #define ADC12_IN0_PORT GPIOA /**< ADC12_IN0 is on PA0 */ @@ -256,26 +263,6 @@ #define RCC_ADC12_IN15 RCC_GPIOC /**< ADC12_IN15 is on PC5 */ /** get channel based on ADC12_IN identifier */ #define ADC_CHANNEL(x) CAT2(ADC_CHANNEL,x) -/** get I2C based on I2C identifier */ -#define I2C(x) CAT2(I2C,x) -/** get RCC for I2C based on I2C identifier */ -#define RCC_I2C(x) CAT2(RCC_I2C,x) -/** get RCC for GPIO port for SCL based on I2C identifier */ -#define RCC_I2C_SCL_PORT(x) CAT3(RCC_I2C,x,_PORT) -#define RCC_I2C1_PORT RCC_GPIOB /**< RCC for GPIO port for SCL for I2C1 */ -#define RCC_I2C2_PORT RCC_GPIOB /**< RCC for GPIO port for SCL for I2C2 */ -/** get RCC for GPIO port for SCL based on I2C identifier */ -#define RCC_I2C_SDA_PORT(x) CAT3(RCC_I2C,x,_PORT) -#define RCC_I2C1_SDA_PORT RCC_GPIOB /**< RCC for GPIO port for SDA for I2C1 */ -#define RCC_I2C2_SDA_PORT RCC_GPIOB /**< RCC for GPIO port for SDA for I2C2 */ -/** get I2C port for SCL pin based on I2C identifier */ -#define I2C_SCL_PORT(x) CAT3(GPIO_BANK_I2C,x,_SCL) -/** get I2C port for SDA pin based on I2C identifier */ -#define I2C_SDA_PORT(x) CAT3(GPIO_BANK_I2C,x,_SDA) -/** get I2C pin for SCL pin based on I2C identifier */ -#define I2C_SCL_PIN(x) CAT3(GPIO_I2C,x,_SCL) -/** get I2C port for SDA pin based on I2C identifier */ -#define I2C_SDA_PIN(x) CAT3(GPIO_I2C,x,_SDA) /** get SPI based on SPI identifier */ #define SPI(x) CAT2(SPI,x) /** get RCC for SPI based on SPI identifier */ @@ -382,6 +369,11 @@ #define LED_PORT B /**< GPIO port (port B on maple mini) */ #define LED_PIN 1 /**< GPIO pin (pin PB1 on maple mini) */ #define LED_ON 1 /**< LED is on when pin is high */ +#elif defined (BUSVOODOO) + /* on BusVoodoo LED is on pin PA8 */ + #define LED_PORT A /**< GPIO port (port A) */ + #define LED_PIN 8 /**< GPIO pin (pin PA8) */ + #define LED_ON 1 /**< LED is on when pin is high */ #endif /** @} */ @@ -414,6 +406,11 @@ #define DFU_FORCE_PORT BUTTON_PORT /**< button port */ #define DFU_FORCE_PIN BUTTON_PIN /**< button pin */ #define DFU_FORCE_VALUE 0 /**< button floating unpressed, connected to ground pressed to force DFU mode */ +#elif defined(BUSVOODOO) + /* on BusVoodoo DFU input is on PC4 */ + #define DFU_FORCE_PORT C /**< GPIO port (port C) */ + #define DFU_FORCE_PIN 4 /**< GPIO pin (pin PC4) */ + #define DFU_FORCE_VALUE 1 /**< pin floating, set high when shorted with nearby VCC */ #else /* use the JNTRST pin as GPIO (this will disable the SWJ function, but we are not using it) */ #define DFU_FORCE_PORT B /**< JNTRST port (needs to be remapped to become PB4) */ @@ -447,7 +444,17 @@ void led_on(void); void led_off(void); /** toggle board LED */ void led_toggle(void); - +#if defined(BUSVOODOO) +/** set LED blinking pattern + * @param[in] period blue+red pattern duration in seconds (up to 3+3) + * @param[in] duty blue LED on duty cycle, before switching to red (0-1) + */ +void led_blink(double period, double duty); +/** switch on blue LED */ +void led_blue(void); +/** switch on red LED */ +void led_red(void); +#endif /** go to sleep for some microseconds * @param[in] duration sleep duration in us */ diff --git a/lib/i2c_master.c b/lib/i2c_master.c index 317ec84..fc392da 100644 --- a/lib/i2c_master.c +++ b/lib/i2c_master.c @@ -16,376 +16,618 @@ * @file i2c_master.c * @author King Kévin * @date 2017-2018 - * @note peripherals used: I2C @ref i2c_master_i2c, timer @ref i2c_master_timer + * @note peripherals used: I2C */ /* standard libraries */ #include // standard integer types -//#include // standard I/O facilities #include // general utilities /* STM32 (including CM3) libraries */ #include // real-time control clock library #include // general purpose input output library #include // I2C library -#include // timer utilities /* own libraries */ #include "global.h" // global utilities #include "i2c_master.h" // I2C header and definitions -/** @defgroup i2c_master_i2c I2C peripheral used to communicate - * @{ +/** get RCC for I2C based on I2C identifier + * @param[in] i2c I2C base address + * @return RCC address for I2C peripheral */ -#define I2C_MASTER_I2C 1 /**< I2C peripheral */ -/** @} */ - -/** @defgroup i2c_master_timer timer peripheral used for timeouts - * @{ - */ -#define I2C_MASTER_TIMER 4 /**< timer peripheral */ -#define I2C_MASTER_TIMEOUT 4 /**< timeout factor (compared to expected time) */ -/** @} */ - -void i2c_master_setup(bool fast) +static uint32_t RCC_I2C(uint32_t i2c) { + switch (i2c) { + case I2C1: + return RCC_I2C1; + break; + case I2C2: + return RCC_I2C2; + break; + default: + while (true); + } +} + +/** get RCC for GPIO port for SCL pin based on I2C identifier + * @param[in] i2c I2C base address + * @return RCC GPIO address + */ +static uint32_t RCC_GPIO_PORT_SCL(uint32_t i2c) +{ + switch (i2c) { + case I2C1: + case I2C2: + return RCC_GPIOB; + break; + default: + while (true); + } +} + +/** get RCC for GPIO port for SDA pin based on I2C identifier + * @param[in] i2c I2C base address + * @return RCC GPIO address + */ +static uint32_t RCC_GPIO_PORT_SDA(uint32_t i2c) +{ + switch (i2c) { + case I2C1: + case I2C2: + return RCC_GPIOB; + break; + default: + while (true); + } +} + +/** get GPIO port for SCL pin based on I2C identifier + * @param[in] i2c I2C base address + * @return GPIO address + */ +static uint32_t GPIO_PORT_SCL(uint32_t i2c) +{ + switch (i2c) { + case I2C1: + if (AFIO_MAPR & AFIO_MAPR_I2C1_REMAP) { + return GPIO_BANK_I2C1_RE_SCL; + } else { + return GPIO_BANK_I2C1_SCL; + } + break; + case I2C2: + return GPIO_BANK_I2C2_SCL; + break; + default: + while (true); + } +} + +/** get GPIO port for SDA pin based on I2C identifier + * @param[in] i2c I2C base address + * @return GPIO address + */ +static uint32_t GPIO_PORT_SDA(uint32_t i2c) +{ + switch (i2c) { + case I2C1: + if (AFIO_MAPR & AFIO_MAPR_I2C1_REMAP) { + return GPIO_BANK_I2C1_RE_SDA; + } else { + return GPIO_BANK_I2C1_SDA; + } + break; + case I2C2: + return GPIO_BANK_I2C2_SDA; + break; + default: + while (true); + } +} + +/** get GPIO pin for SCL pin based on I2C identifier + * @param[in] i2c I2C base address + * @return GPIO address + */ +static uint32_t GPIO_PIN_SCL(uint32_t i2c) +{ + switch (i2c) { + case I2C1: + if (AFIO_MAPR & AFIO_MAPR_I2C1_REMAP) { + return GPIO_I2C1_RE_SCL; + } else { + return GPIO_I2C1_SCL; + } + break; + case I2C2: + return GPIO_I2C2_SCL; + break; + default: + while (true); + } +} + +/** get GPIO pin for SDA pin based on I2C identifier + * @param[in] i2c I2C base address + * @return GPIO address + */ +static uint32_t GPIO_PIN_SDA(uint32_t i2c) +{ + switch (i2c) { + case I2C1: + if (AFIO_MAPR & AFIO_MAPR_I2C1_REMAP) { + return GPIO_I2C1_RE_SDA; + } else { + return GPIO_I2C1_SDA; + } + break; + case I2C2: + return GPIO_I2C2_SDA; + break; + default: + while (true); + } +} + +void i2c_master_setup(uint32_t i2c, uint16_t frequency) +{ + // check I2C peripheral + if (I2C1!=i2c && I2C2!=i2c) { + while (true); + } + // configure I2C peripheral - rcc_periph_clock_enable(RCC_I2C_SCL_PORT(I2C_MASTER_I2C)); // enable clock for I2C I/O peripheral - gpio_set(I2C_SCL_PORT(I2C_MASTER_I2C), I2C_SCL_PIN(I2C_MASTER_I2C)); // already put signal high to avoid small pulse - gpio_set_mode(I2C_SCL_PORT(I2C_MASTER_I2C), GPIO_MODE_OUTPUT_2_MHZ, GPIO_CNF_OUTPUT_ALTFN_OPENDRAIN, I2C_SCL_PIN(I2C_MASTER_I2C)); // setup I2C I/O pins - rcc_periph_clock_enable(RCC_I2C_SCL_PORT(I2C_MASTER_I2C)); // enable clock for I2C I/O peripheral - gpio_set(I2C_SDA_PORT(I2C_MASTER_I2C), I2C_SDA_PIN(I2C_MASTER_I2C)); // already put signal high to avoid small pulse - gpio_set_mode(I2C_SDA_PORT(I2C_MASTER_I2C), GPIO_MODE_OUTPUT_2_MHZ, GPIO_CNF_OUTPUT_ALTFN_OPENDRAIN, I2C_SDA_PIN(I2C_MASTER_I2C)); // setup I2C I/O pins + rcc_periph_clock_enable(RCC_GPIO_PORT_SCL(i2c)); // enable clock for I2C I/O peripheral + gpio_set(GPIO_PORT_SCL(i2c), GPIO_PIN_SCL(i2c)); // already put signal high to avoid small pulse + gpio_set_mode(GPIO_PORT_SCL(i2c), GPIO_MODE_OUTPUT_10_MHZ, GPIO_CNF_OUTPUT_ALTFN_OPENDRAIN, GPIO_PIN_SCL(i2c)); // setup I2C I/O pins + rcc_periph_clock_enable(RCC_GPIO_PORT_SDA(i2c)); // enable clock for I2C I/O peripheral + gpio_set(GPIO_PORT_SDA(i2c), GPIO_PIN_SDA(i2c)); // already put signal high to avoid small pulse + gpio_set_mode(GPIO_PORT_SDA(i2c), GPIO_MODE_OUTPUT_10_MHZ, GPIO_CNF_OUTPUT_ALTFN_OPENDRAIN, GPIO_PIN_SDA(i2c)); // setup I2C I/O pins rcc_periph_clock_enable(RCC_AFIO); // enable clock for alternate function - rcc_periph_clock_enable(RCC_I2C(I2C_MASTER_I2C)); // enable clock for I2C peripheral - i2c_reset(I2C(I2C_MASTER_I2C)); // reset configuration - i2c_peripheral_disable(I2C(I2C_MASTER_I2C)); // I2C needs to be disable to be configured - i2c_set_clock_frequency(I2C(I2C_MASTER_I2C), rcc_apb1_frequency/1000000); // configure the peripheral clock to the APB1 freq (where it is connected to) - if (fast) { - i2c_set_fast_mode(I2C(I2C_MASTER_I2C)); - i2c_set_ccr(I2C(I2C_MASTER_I2C), rcc_apb1_frequency/(400000*2)); // set Thigh/Tlow to generate frequency of 400 kHz - i2c_set_trise(I2C(I2C_MASTER_I2C), (300/(1000/(rcc_apb1_frequency/1000000)))+1); // max rise time for 300 kHz is 300 ns - } else { - i2c_set_standard_mode(I2C(I2C_MASTER_I2C)); // the DS1307 has a maximum I2C SCL freq if 100 kHz (corresponding to the standard mode) - i2c_set_ccr(I2C(I2C_MASTER_I2C), rcc_apb1_frequency/(100000*2)); // set Thigh/Tlow to generate frequency of 100 kHz - i2c_set_trise(I2C(I2C_MASTER_I2C), (1000/(1000/(rcc_apb1_frequency/1000000)))+1); // max rise time for 100 kHz is 1000 ns (~1 MHz) + rcc_periph_clock_enable(RCC_I2C(i2c)); // enable clock for I2C peripheral + i2c_reset(i2c); // reset peripheral domain + i2c_peripheral_disable(i2c); // I2C needs to be disable to be configured + I2C_CR1(i2c) |= I2C_CR1_SWRST; // reset peripheral + I2C_CR1(i2c) &= ~I2C_CR1_SWRST; // clear peripheral reset + if (0==frequency) { // don't allow null frequency + frequency = 1; + } else if (frequency>400) { // limit frequency to 400 kHz + frequency = 400; } - i2c_peripheral_enable(I2C(I2C_MASTER_I2C)); // enable I2C after configuration completed - - // configure time for timeouts - rcc_periph_clock_enable(RCC_TIM(I2C_MASTER_TIMER)); // enable clock for timer block - timer_reset(TIM(I2C_MASTER_TIMER)); // reset timer state - timer_set_mode(TIM(I2C_MASTER_TIMER), TIM_CR1_CKD_CK_INT, TIM_CR1_CMS_EDGE, TIM_CR1_DIR_UP); // set timer mode, use undivided timer clock, edge alignment (simple count), and count up - timer_one_shot_mode(TIM(I2C_MASTER_TIMER)); // stop counter after update event (we only need to one timeout and reset before next operation) - if (fast) { - timer_set_prescaler(TIM(I2C_MASTER_TIMER), rcc_ahb_frequency/400000-1); // set the prescaler so one tick is also one I2C bit (used I2C frequency) - } else { - timer_set_prescaler(TIM(I2C_MASTER_TIMER), rcc_ahb_frequency/100000-1); // set the prescaler so one tick is also one I2C bit (used I2C frequency) + i2c_set_clock_frequency(i2c, rcc_apb1_frequency/1000000); // configure the peripheral clock to the APB1 freq (where it is connected to) + if (frequency>100) { // use fast mode for frequencies over 100 kHz + i2c_set_fast_mode(i2c); // set fast mode (Fm) + i2c_set_ccr(i2c, rcc_apb1_frequency/(frequency*1000*2)); // set Thigh/Tlow to generate frequency (fast duty not used) + i2c_set_trise(i2c, (300/(1000/(rcc_apb1_frequency/1000000)))+1); // max rise time for Fm mode (< 400) kHz is 300 ns + } else { // use fast mode for frequencies below 100 kHz + i2c_set_standard_mode(i2c); // set standard mode (Sm) + i2c_set_ccr(i2c, rcc_apb1_frequency/(frequency*1000*2)); // set Thigh/Tlow to generate frequency of 100 kHz + i2c_set_trise(i2c, (1000/(1000/(rcc_apb1_frequency/1000000)))+1); // max rise time for Sm mode (< 100 kHz) is 1000 ns (~1 MHz) } - timer_set_period(TIM(I2C_MASTER_TIMER), I2C_MASTER_TIMEOUT*9); // use factor to wait for all 9 bits to be transmitted - timer_update_on_overflow(TIM(I2C_MASTER_TIMER)); // only use counter overflow as UEV source (use overflow as timeout) - - // wait one transaction for the signal to be stable (some slave have issues when an I2C transaction immediately follows) - timer_set_counter(TIM(I2C_MASTER_TIMER),0); // restart timer - timer_clear_flag(TIM(I2C_MASTER_TIMER), TIM_SR_UIF); // clear flag - timer_enable_counter(TIM(I2C_MASTER_TIMER)); // enable timer for timeouts - while ( !timer_get_flag(TIM(I2C_MASTER_TIMER), TIM_SR_UIF)); - timer_disable_counter(TIM(I2C_MASTER_TIMER)); // disable timer for timeouts - timer_clear_flag(TIM(I2C_MASTER_TIMER), TIM_SR_UIF); // clear flag + i2c_peripheral_enable(i2c); // enable I2C after configuration completed } -bool i2c_master_start(void) +void i2c_master_release(uint32_t i2c) { + // check I2C peripheral + if (I2C1!=i2c && I2C2!=i2c) { + while (true); + } + + i2c_reset(i2c); // reset I2C peripheral configuration + i2c_peripheral_disable(i2c); // disable I2C peripheral + rcc_periph_clock_disable(RCC_I2C(i2c)); // disable clock for I2C peripheral + gpio_set_mode(GPIO_PORT_SCL(i2c), GPIO_MODE_INPUT, GPIO_CNF_INPUT_FLOAT, GPIO_PIN_SCL(i2c)); // put I2C I/O pins back to floating + gpio_set_mode(GPIO_PORT_SDA(i2c), GPIO_MODE_INPUT, GPIO_CNF_INPUT_FLOAT, GPIO_PIN_SDA(i2c)); // put I2C I/O pins back to floating +} + +bool i2c_master_check_signals(uint32_t i2c) +{ + // check I2C peripheral + if (I2C1!=i2c && I2C2!=i2c) { + while (true); + } + + // pull SDA and SDC low to check if there are pull-up resistors + uint32_t sda_crl = GPIO_CRL(GPIO_PORT_SDA(i2c)); // backup port configuration + uint32_t sda_crh = GPIO_CRH(GPIO_PORT_SDA(i2c)); // backup port configuration + uint32_t sda_bsrr = GPIO_BSRR(GPIO_PORT_SDA(i2c)); // backup port configuration + uint32_t scl_crl = GPIO_CRL(GPIO_PORT_SCL(i2c)); // backup port configuration + uint32_t scl_crh = GPIO_CRH(GPIO_PORT_SCL(i2c)); // backup port configuration + uint32_t scl_bsrr = GPIO_BSRR(GPIO_PORT_SCL(i2c)); // backup port configuration + gpio_set_mode(GPIO_PORT_SDA(i2c), GPIO_MODE_INPUT, GPIO_CNF_INPUT_PULL_UPDOWN, GPIO_PIN_SDA(i2c)); // configure signal as pull down + gpio_set_mode(GPIO_PORT_SCL(i2c), GPIO_MODE_INPUT, GPIO_CNF_INPUT_PULL_UPDOWN, GPIO_PIN_SCL(i2c)); // configure signal as pull down + gpio_clear(GPIO_PORT_SDA(i2c), GPIO_PIN_SDA(i2c)); // pull down + gpio_clear(GPIO_PORT_SCL(i2c), GPIO_PIN_SCL(i2c)); // pull down + bool to_return = (0!=gpio_get(GPIO_PORT_SCL(i2c), GPIO_PIN_SCL(i2c)) && 0!=gpio_get(GPIO_PORT_SDA(i2c), GPIO_PIN_SDA(i2c))); // check if the signals are still pulled high by external stronger pull-up resistors + GPIO_CRL(GPIO_PORT_SDA(i2c)) = sda_crl; // restore port configuration + GPIO_CRH(GPIO_PORT_SDA(i2c)) = sda_crh; // restore port configuration + GPIO_BSRR(GPIO_PORT_SDA(i2c)) = sda_bsrr; // restore port configuration + GPIO_CRL(GPIO_PORT_SCL(i2c)) = scl_crl; // restore port configuration + GPIO_CRH(GPIO_PORT_SCL(i2c)) = scl_crh; // restore port configuration + GPIO_BSRR(GPIO_PORT_SCL(i2c)) = scl_bsrr; // restore port configuration + + return to_return; +} + +void i2c_master_reset(uint32_t i2c) +{ + // check I2C peripheral + if (I2C1!=i2c && I2C2!=i2c) { + while (true); + } + + // follow procedure described in STM32F10xxC/D/E Errata sheet, Section 2.14.7 + i2c_peripheral_disable(i2c); // disable i2c peripheral + gpio_set_mode(GPIO_PORT_SCL(i2c), GPIO_MODE_OUTPUT_10_MHZ, GPIO_CNF_OUTPUT_OPENDRAIN, GPIO_PIN_SCL(i2c)); // put I2C I/O pins to general output + gpio_set(GPIO_PORT_SCL(i2c), GPIO_PIN_SCL(i2c)); // set high + while (!gpio_get(GPIO_PORT_SCL(i2c), GPIO_PIN_SCL(i2c))); // ensure it is high + gpio_set_mode(GPIO_PORT_SDA(i2c), GPIO_MODE_OUTPUT_10_MHZ, GPIO_CNF_OUTPUT_OPENDRAIN, GPIO_PIN_SDA(i2c)); // put I2C I/O pins to general output + gpio_set(GPIO_PORT_SDA(i2c), GPIO_PIN_SDA(i2c)); // set high + while (!gpio_get(GPIO_PORT_SDA(i2c), GPIO_PIN_SDA(i2c))); // ensure it is high + gpio_clear(GPIO_PORT_SDA(i2c), GPIO_PIN_SDA(i2c)); // set low (try first transition) + while (gpio_get(GPIO_PORT_SDA(i2c), GPIO_PIN_SDA(i2c))); // ensure it is low + gpio_clear(GPIO_PORT_SCL(i2c), GPIO_PIN_SCL(i2c)); // set low (try first transition) + while (gpio_get(GPIO_PORT_SCL(i2c), GPIO_PIN_SCL(i2c))); // ensure it is low + gpio_set(GPIO_PORT_SCL(i2c), GPIO_PIN_SCL(i2c)); // set high (try second transition) + while (!gpio_get(GPIO_PORT_SCL(i2c), GPIO_PIN_SCL(i2c))); // ensure it is high + gpio_set(GPIO_PORT_SDA(i2c), GPIO_PIN_SDA(i2c)); // set high (try second transition) + while (!gpio_get(GPIO_PORT_SDA(i2c), GPIO_PIN_SDA(i2c))); // ensure it is high + gpio_set_mode(GPIO_PORT_SCL(i2c), GPIO_MODE_OUTPUT_10_MHZ, GPIO_CNF_OUTPUT_ALTFN_OPENDRAIN, GPIO_PIN_SCL(i2c)); // set I2C I/O pins back + gpio_set_mode(GPIO_PORT_SDA(i2c), GPIO_MODE_OUTPUT_10_MHZ, GPIO_CNF_OUTPUT_ALTFN_OPENDRAIN, GPIO_PIN_SDA(i2c)); // set I2C I/O pins back + I2C_CR1(i2c) |= I2C_CR1_SWRST; // reset device + I2C_CR1(i2c) &= ~I2C_CR1_SWRST; // reset device + i2c_peripheral_enable(i2c); // re-enable device +} + +enum i2c_master_rc i2c_master_start(uint32_t i2c) +{ + // check I2C peripheral + if (I2C1!=i2c && I2C2!=i2c) { + while (true); + } + // send (re-)start condition - i2c_send_start(I2C(I2C_MASTER_I2C)); // send start condition to start transaction - timer_set_counter(TIM(I2C_MASTER_TIMER), 0); // restart timer - timer_clear_flag(TIM(I2C_MASTER_TIMER), TIM_SR_UIF); // clear flag - timer_enable_counter(TIM(I2C_MASTER_TIMER)); // enable timer for timeouts - while (!(I2C_SR1(I2C(I2C_MASTER_I2C)) & I2C_SR1_SB) && !timer_get_flag(TIM(I2C_MASTER_TIMER), TIM_SR_UIF)); // wait until start condition is transmitted - timer_disable_counter(TIM(I2C_MASTER_TIMER)); // disable timer for timeouts - if (timer_get_flag(TIM(I2C_MASTER_TIMER), TIM_SR_UIF)) { // timeout occurred - timer_clear_flag(TIM(I2C_MASTER_TIMER), TIM_SR_UIF); // clear flag - return false; + if (I2C_CR1(i2c) & (I2C_CR1_START|I2C_CR1_STOP)) { // ensure start or stop operations are not in progress + return I2C_MASTER_RC_START_STOP_IN_PROGESS; } - if (!(I2C_SR2(I2C(I2C_MASTER_I2C)) & I2C_SR2_MSL)) { // verify if in master mode - return false; + i2c_send_start(i2c); // send start condition to start transaction + while ((I2C_CR1(i2c) & I2C_CR1_START) && !(I2C_SR1(i2c) & (I2C_SR1_BERR|I2C_SR1_ARLO))); // wait until start condition has been accepted and cleared + if (I2C_SR1(i2c) & (I2C_SR1_BERR|I2C_SR1_ARLO)) { + return I2C_MASTER_RC_BUS_ERROR; + } + while (!(I2C_SR1(i2c) & I2C_SR1_SB) && !(I2C_SR1(i2c) & (I2C_SR1_BERR|I2C_SR1_ARLO))); // wait until start condition is transmitted + if (I2C_SR1(i2c) & (I2C_SR1_BERR|I2C_SR1_ARLO)) { + return I2C_MASTER_RC_BUS_ERROR; + } + if (!(I2C_SR2(i2c) & I2C_SR2_MSL)) { // verify if in master mode + return I2C_MASTER_RC_NOT_MASTER; } - return true; + return I2C_MASTER_RC_NONE; } -bool i2c_master_select_slave(uint8_t slave, bool write) +enum i2c_master_rc i2c_master_select_slave(uint32_t i2c, uint16_t slave, bool address_10bit, bool write) { - if (!(I2C_SR2(I2C(I2C_MASTER_I2C)) & I2C_SR2_BUSY)) { // I2C device is not busy (start condition has not been sent) - if (!i2c_master_start()) { // send start condition - return false; // could not send start condition + // check I2C peripheral + if (I2C1!=i2c && I2C2!=i2c) { + while (true); + } + + enum i2c_master_rc rc = I2C_MASTER_RC_NONE; // to store I2C return codes + if (!(I2C_SR1(i2c) & I2C_SR1_SB)) { // start condition has not been sent + rc = i2c_master_start(i2c); // send start condition + if (I2C_MASTER_RC_NONE!=rc) { + return rc; } - } - if (!(I2C_SR2(I2C(I2C_MASTER_I2C)) & I2C_SR2_MSL)) { // I2C device is already not master mode - return false; + } + if (!(I2C_SR2(i2c) & I2C_SR2_MSL)) { // I2C device is not in master mode + return I2C_MASTER_RC_NOT_MASTER; } // select slave - i2c_send_7bit_address(I2C(I2C_MASTER_I2C), slave, write ? I2C_WRITE : I2C_READ); // select slave, with read/write flag - timer_set_counter(TIM(I2C_MASTER_TIMER), 0); // restart timer - timer_clear_flag(TIM(I2C_MASTER_TIMER), TIM_SR_UIF); // clear flag - timer_enable_counter(TIM(I2C_MASTER_TIMER)); // enable timer for timeouts - while (!(I2C_SR1(I2C(I2C_MASTER_I2C)) & I2C_SR1_ADDR) && !timer_get_flag(TIM(I2C_MASTER_TIMER), TIM_SR_UIF)); // wait until address is transmitted - timer_disable_counter(TIM(I2C_MASTER_TIMER)); // disable timer for timeouts - if (timer_get_flag(TIM(I2C_MASTER_TIMER), TIM_SR_UIF)) { // timeout occurred (no ACK received) - timer_clear_flag(TIM(I2C_MASTER_TIMER), TIM_SR_UIF); // clear flag - return false; + if (!address_10bit) { // 7-bit address + I2C_SR1(i2c) &= ~(I2C_SR1_AF); // clear acknowledgement failure + i2c_send_7bit_address(i2c, slave, write ? I2C_WRITE : I2C_READ); // select slave, with read/write flag + while (!(I2C_SR1(i2c) & (I2C_SR1_ADDR|I2C_SR1_AF)) && !(I2C_SR1(i2c) & (I2C_SR1_BERR|I2C_SR1_ARLO))); // wait until address is transmitted + if (I2C_SR1(i2c) & (I2C_SR1_BERR|I2C_SR1_ARLO)) { + return I2C_MASTER_RC_BUS_ERROR; + } + if (I2C_SR1(i2c) & I2C_SR1_AF) { // address has not been acknowledged + return I2C_MASTER_RC_NAK; + } + } else { // 10-bit address + // send first part of address + I2C_SR1(i2c) &= ~(I2C_SR1_AF); // clear acknowledgement failure + I2C_DR(i2c) = 11110000 | (((slave>>8)&0x3)<<1); // send first header (11110xx0, where xx are 2 MSb of slave address) + while (!(I2C_SR1(i2c) & (I2C_SR1_ADD10|I2C_SR1_AF)) && !(I2C_SR1(i2c) & (I2C_SR1_BERR|I2C_SR1_ARLO))); // wait until first part of address is transmitted + if (I2C_SR1(i2c) & I2C_SR1_AF) { // address has not been acknowledged + return I2C_MASTER_RC_NAK; + } + // send second part of address + I2C_SR1(i2c) &= ~(I2C_SR1_AF); // clear acknowledgement failure + I2C_DR(i2c) = (slave&0xff); // send remaining of address + while (!(I2C_SR1(i2c) & (I2C_SR1_ADDR|I2C_SR1_AF)) && !(I2C_SR1(i2c) & (I2C_SR1_BERR|I2C_SR1_ARLO))); // wait until remaining part of address is transmitted + if (I2C_SR1(i2c) & (I2C_SR1_BERR|I2C_SR1_ARLO)) { + return I2C_MASTER_RC_BUS_ERROR; + } + if (I2C_SR1(i2c) & I2C_SR1_AF) { // address has not been acknowledged + return I2C_MASTER_RC_NAK; + } + // go into receive mode if necessary + if (!write) { + rc = i2c_master_start(i2c); // send start condition + if (I2C_MASTER_RC_NONE!=rc) { + return rc; + } + // send first part of address with receive flag + I2C_SR1(i2c) &= ~(I2C_SR1_AF); // clear acknowledgement failure + I2C_DR(i2c) = 11110001 | (((slave>>8)&0x3)<<1); // send header (11110xx1, where xx are 2 MSb of slave address) + while (!(I2C_SR1(i2c) & (I2C_SR1_ADDR|I2C_SR1_AF)) && !(I2C_SR1(i2c) & (I2C_SR1_BERR|I2C_SR1_ARLO))); // wait until remaining part of address is transmitted + if (I2C_SR1(i2c) & (I2C_SR1_BERR|I2C_SR1_ARLO)) { + return I2C_MASTER_RC_BUS_ERROR; + } + if (I2C_SR1(i2c) & I2C_SR1_AF) { // address has not been acknowledged + return I2C_MASTER_RC_NAK; + } + } } if (write) { - if (!((I2C_SR2(I2C(I2C_MASTER_I2C)) & I2C_SR2_TRA))) { // verify we are in transmit mode (and read SR2 to clear ADDR) - return false; + if (!((I2C_SR2(i2c) & I2C_SR2_TRA))) { // verify we are in transmit mode (and read SR2 to clear ADDR) + return I2C_MASTER_RC_NOT_TRANSMIT; } } else { - if ((I2C_SR2(I2C(I2C_MASTER_I2C)) & I2C_SR2_TRA)) { // verify we are in read mode (and read SR2 to clear ADDR) - return false; + if ((I2C_SR2(i2c) & I2C_SR2_TRA)) { // verify we are in read mode (and read SR2 to clear ADDR) + return I2C_MASTER_RC_NOT_RECEIVE; } } - return true; + return I2C_MASTER_RC_NONE; } -bool i2c_master_read(uint8_t* data, size_t data_size) +enum i2c_master_rc i2c_master_read(uint32_t i2c, uint8_t* data, size_t data_size) { + // check I2C peripheral + if (I2C1!=i2c && I2C2!=i2c) { + while (true); + } + // sanity check if (data==NULL || data_size==0) { // no data to read - return true; + return I2C_MASTER_RC_NONE; } - if (!(I2C_SR2(I2C(I2C_MASTER_I2C)) & I2C_SR2_BUSY)) { // I2C device is not busy (start condition has not been sent) - return false; // address has probably also not been sent - } - if (!(I2C_SR2(I2C(I2C_MASTER_I2C)) & I2C_SR2_MSL)) { // I2C device not master mode - return false; + if (!(I2C_SR2(i2c) & I2C_SR2_MSL)) { // I2C device is not master + return I2C_MASTER_RC_NOT_MASTER; + } + if ((I2C_SR2(i2c) & I2C_SR2_TRA)) { // I2C device not in receiver mode + return I2C_MASTER_RC_NOT_RECEIVE; + } + if (I2C_SR1(i2c) & I2C_SR1_AF) { // check if the previous transaction went well + return I2C_MASTER_RC_NOT_READY; } // read data for (size_t i=0; i0) { - // read data - if (!i2c_master_read(data, data_size)) { + if (NULL!=data && data_size>0) { // only read data if needed + rc = i2c_master_read(i2c, data, data_size); + if (I2C_MASTER_RC_NONE!=rc) { goto error; } } - success = true; + rc = I2C_MASTER_RC_NONE; // all went well error: - i2c_master_stop(); // sent stop condition - return success; + i2c_master_stop(i2c); // sent stop condition + return rc; } -bool i2c_master_slave_write(uint8_t slave, const uint8_t* data, size_t data_size) +enum i2c_master_rc i2c_master_slave_write(uint32_t i2c, uint16_t slave, bool address_10bit, const uint8_t* data, size_t data_size) { - // sanity check - if (I2C_SR2(I2C(I2C_MASTER_I2C)) & I2C_SR2_BUSY) { // I2C device is busy - return false; - } - if (I2C_SR2(I2C(I2C_MASTER_I2C)) & I2C_SR2_MSL) { // I2C device is already in master mode - return false; + // check I2C peripheral + if (I2C1!=i2c && I2C2!=i2c) { + while (true); } - bool success = false; // return if read succeeded - - // send start condition - if (!i2c_master_start()) { + enum i2c_master_rc rc = I2C_MASTER_RC_NONE; // to store I2C return codes + rc = i2c_master_start(i2c); // send (re-)start condition + if (I2C_MASTER_RC_NONE!=rc) { + return rc; + } + rc = i2c_master_select_slave(i2c, slave, address_10bit, true); // select slave to write + if (I2C_MASTER_RC_NONE!=rc) { goto error; } - // select slave to write - if (!i2c_master_select_slave(slave, true)) { - goto error; - } - // write data - if (NULL!=data && data_size>0) { - if (!i2c_master_write(data, data_size)) { + if (NULL!=data && data_size>0) { // write data only is some is available + rc = i2c_master_write(i2c, data, data_size); // write data + if (I2C_MASTER_RC_NONE!=rc) { goto error; } } - success = true; + rc = I2C_MASTER_RC_NONE; // all went well error: - i2c_master_stop(); // sent stop condition - return success; + i2c_master_stop(i2c); // sent stop condition + return rc; } -bool i2c_master_address_read(uint8_t slave, const uint8_t* address, size_t address_size, uint8_t* data, size_t data_size) +enum i2c_master_rc i2c_master_address_read(uint32_t i2c, uint16_t slave, bool address_10bit, const uint8_t* address, size_t address_size, uint8_t* data, size_t data_size) { - // sanity check - if (I2C_SR2(I2C(I2C_MASTER_I2C)) & I2C_SR2_BUSY) { // I2C device is busy - return false; - } - if (I2C_SR2(I2C(I2C_MASTER_I2C)) & I2C_SR2_MSL) { // I2C device is already in master mode - return false; + // check I2C peripheral + if (I2C1!=i2c && I2C2!=i2c) { + while (true); } - bool success = false; // return if read succeeded + enum i2c_master_rc rc = I2C_MASTER_RC_NONE; // to store I2C return codes + rc = i2c_master_start(i2c); // send (re-)start condition + if (I2C_MASTER_RC_NONE!=rc) { + return rc; + } + rc = i2c_master_select_slave(i2c, slave, address_10bit, true); // select slave to write + if (I2C_MASTER_RC_NONE!=rc) { + goto error; + } // write address if (NULL!=address && address_size>0) { - // send start condition - if (!i2c_master_start()) { - goto error; - } - // select slave to write - if (!i2c_master_select_slave(slave, true)) { - goto error; - } - // send address - if (!i2c_master_write(address, address_size)) { + rc = i2c_master_write(i2c, address, address_size); // send memory address + if (I2C_MASTER_RC_NONE!=rc) { goto error; } } // read data if (NULL!=data && data_size>0) { - // send re-start condition - if (!i2c_master_start()) { + rc = i2c_master_start(i2c); // send re-start condition + if (I2C_MASTER_RC_NONE!=rc) { + return rc; + } + rc = i2c_master_select_slave(i2c, slave, address_10bit, false); // select slave to read + if (I2C_MASTER_RC_NONE!=rc) { goto error; } - // select slave to read - if (!i2c_master_select_slave(slave, false)) { - goto error; - } - // read data - if (!i2c_master_read(data, data_size)) { + rc = i2c_master_read(i2c, data, data_size); // read memory + if (I2C_MASTER_RC_NONE!=rc) { goto error; } } - success = true; + rc = I2C_MASTER_RC_NONE; // all went well error: - i2c_master_stop(); // sent stop condition - return success; + i2c_master_stop(i2c); // sent stop condition + return rc; } -bool i2c_master_address_write(uint8_t slave, const uint8_t* address, size_t address_size, const uint8_t* data, size_t data_size) +enum i2c_master_rc i2c_master_address_write(uint32_t i2c, uint16_t slave, bool address_10bit, const uint8_t* address, size_t address_size, const uint8_t* data, size_t data_size) { - // sanity check - if (I2C_SR2(I2C(I2C_MASTER_I2C)) & I2C_SR2_BUSY) { // I2C device is busy - return false; - } - if (I2C_SR2(I2C(I2C_MASTER_I2C)) & I2C_SR2_MSL) { // I2C device is already in master mode - return false; + // check I2C peripheral + if (I2C1!=i2c && I2C2!=i2c) { + while (true); } - bool success = false; // return if read succeeded + enum i2c_master_rc rc = I2C_MASTER_RC_NONE; // to store I2C return codes + rc = i2c_master_start(i2c); // send (re-)start condition + if (I2C_MASTER_RC_NONE!=rc) { + return rc; + } + rc = i2c_master_select_slave(i2c, slave, address_10bit, true); // select slave to write + if (I2C_MASTER_RC_NONE!=rc) { + goto error; + } - // send start condition - if (!i2c_master_start()) { - goto error; - } - // select slave to write - if (!i2c_master_select_slave(slave, true)) { - goto error; - } // write address if (NULL!=address && address_size>0) { - // send address - if (!i2c_master_write(address, address_size)) { + rc = i2c_master_write(i2c, address, address_size); // send memory address + if (I2C_MASTER_RC_NONE!=rc) { goto error; } } - // write data + // read data if (NULL!=data && data_size>0) { - if (!i2c_master_write(data, data_size)) { + rc = i2c_master_write(i2c, data, data_size); // write memory + if (I2C_MASTER_RC_NONE!=rc) { goto error; } } - success = true; + rc = I2C_MASTER_RC_NONE; // all went well error: - i2c_master_stop(); // sent stop condition - return success; + i2c_master_stop(i2c); // sent stop condition + return rc; } diff --git a/lib/i2c_master.h b/lib/i2c_master.h index a42cdd6..f4e4933 100644 --- a/lib/i2c_master.h +++ b/lib/i2c_master.h @@ -16,69 +16,117 @@ * @file i2c_master.h * @author King Kévin * @date 2017-2018 - * @note peripherals used: I2C @ref i2c_master_i2c, timer @ref i2c_master_timer - * @warning only 7-byte I2C slave addresses are supported + * @note peripherals used: I2C */ #pragma once +/** I2C return codes */ +enum i2c_master_rc { + I2C_MASTER_RC_NONE = 0, /**< no error */ + I2C_MASTER_RC_START_STOP_IN_PROGESS, /**< a start or stop condition is already in progress */ + I2C_MASTER_RC_NOT_MASTER, /**< not in master mode */ + I2C_MASTER_RC_NOT_TRANSMIT, /**< not in transmit mode */ + I2C_MASTER_RC_NOT_RECEIVE, /**< not in receive mode */ + I2C_MASTER_RC_NOT_READY, /**< slave is not read (previous operations has been nacked) */ + I2C_MASTER_RC_NAK, /**< not acknowledge received */ + I2C_MASTER_RC_BUS_ERROR, /**< an error on the I2C bus occurred */ +}; + /** setup I2C peripheral - * @param[in] fast use standard (100 kHz) or fast (400 kHz) mode + * @param[in] i2c I2C base address + * @param[in] frequency frequency to use in kHz (1-400) + * @note Standard mode (Sm) is used for frequencies up to 100 kHz, and Fast mode (Fm) is used for frequencies up to 400 kHz */ -void i2c_master_setup(bool fast); +void i2c_master_setup(uint32_t i2c, uint16_t frequency); +/** release I2C peripheral + * @param[in] i2c I2C base address + */ +void i2c_master_release(uint32_t i2c); +/** reset I2C peripheral, fixing any locked state + * @warning the I2C peripheral needs to be re-setup + * @note to be used after failed start or stop, and bus error + * @param[in] i2c I2C base address + */ +void i2c_master_reset(uint32_t i2c); +/** check if SDA and SCL signals are high + * @param[in] i2c I2C base address + * @return SDA and SCL signals are high + */ +bool i2c_master_check_signals(uint32_t i2c); /** send start condition - * @return if start condition was sent successfully (true) or error occurred (false) + * @param[in] i2c I2C base address + * @return I2C return code */ -bool i2c_master_start(void); -/** select slave device +enum i2c_master_rc i2c_master_start(uint32_t i2c); +/** select I2C slave device * @warning a start condition should be sent before this operation - * @param[in] slave 7-bit I2C address of slave device to select + * @param[in] i2c I2C base address + * @param[in] slave I2C address of slave device to select + * @param[in] address_10bit if the I2C slave address is 10 bits wide * @param[in] write this transaction will be followed by a read (false) or write (true) operation - * @return if slave was selected successfully (true) or error occurred (false) + * @return I2C return code */ -bool i2c_master_select_slave(uint8_t slave, bool write); -/** read data +enum i2c_master_rc i2c_master_select_slave(uint32_t i2c, uint16_t slave, bool address_10bit, bool write); +/** read data over I2C * @warning the slave device must be selected before this operation + * @param[in] i2c I2C base address * @param[out] data array to store bytes read * @param[in] data_size number of bytes to read + * @return I2C return code */ -bool i2c_master_read(uint8_t* data, size_t data_size); -/** write data +enum i2c_master_rc i2c_master_read(uint32_t i2c, uint8_t* data, size_t data_size); +/** write data over I2C * @warning the slave device must be selected before this operation + * @param[in] i2c I2C base address * @param[in] data array of byte to write to slave * @param[in] data_size number of bytes to write + * @return I2C return code */ -bool i2c_master_write(const uint8_t* data, size_t data_size); -/** sent stop condition */ -void i2c_master_stop(void); -/** read from date from an I2C slave - * @param[in] slave 7-bit I2C salve device address to read from +enum i2c_master_rc i2c_master_write(uint32_t i2c, const uint8_t* data, size_t data_size); +/** sent stop condition + * @param[in] i2c I2C base address + * @return I2C return code + */ +enum i2c_master_rc i2c_master_stop(uint32_t i2c); +/** read data from slave device + * @warning the slave device must be selected before this operation + * @param[in] i2c I2C base address + * @param[in] slave I2C address of slave device to select + * @param[in] address_10bit if the I2C slave address is 10 bits wide * @param[out] data array to store bytes read * @param[in] data_size number of bytes to read - * @return if read succeeded + * @return I2C return code */ -bool i2c_master_slave_read(uint8_t slave, uint8_t* data, size_t data_size); -/** write data to an I2C slave - * @param[in] slave 7-bit I2C salve device address to write to +enum i2c_master_rc i2c_master_slave_read(uint32_t i2c, uint16_t slave, bool address_10bit, uint8_t* data, size_t data_size); +/** write data to slave device + * @warning the slave device must be selected before this operation + * @param[in] i2c I2C base address + * @param[in] slave I2C address of slave device to select + * @param[in] address_10bit if the I2C slave address is 10 bits wide * @param[in] data array of byte to write to slave * @param[in] data_size number of bytes to write - * @return if write succeeded + * @return I2C return code */ -bool i2c_master_slave_write(uint8_t slave, const uint8_t* data, size_t data_size); +enum i2c_master_rc i2c_master_slave_write(uint32_t i2c, uint16_t slave, bool address_10bit, const uint8_t* data, size_t data_size); /** read data at specific address from an I2C memory slave - * @param[in] slave 7-bit I2C salve device address to read from + * @param[in] i2c I2C base address + * @param[in] slave I2C address of slave device to select + * @param[in] address_10bit if the I2C slave address is 10 bits wide * @param[in] address memory address of slave to read from * @param[in] address_size address size in bytes * @param[out] data array to store bytes read * @param[in] data_size number of bytes to read - * @return if read succeeded + * @return I2C return code */ -bool i2c_master_address_read(uint8_t slave, const uint8_t* address, size_t address_size, uint8_t* data, size_t data_size); +enum i2c_master_rc i2c_master_address_read(uint32_t i2c, uint16_t slave, bool address_10bit, const uint8_t* address, size_t address_size, uint8_t* data, size_t data_size); /** write data at specific address on an I2C memory slave - * @param[in] slave 7-bit I2C salve device address to write to + * @param[in] i2c I2C base address + * @param[in] slave I2C address of slave device to select + * @param[in] address_10bit if the I2C slave address is 10 bits wide * @param[in] address memory address of slave to write to * @param[in] address_size address size in bytes * @param[in] data array of byte to write to slave * @param[in] data_size number of bytes to write - * @return if write succeeded + * @return I2C return code */ -bool i2c_master_address_write(uint8_t slave, const uint8_t* address, size_t address_size, const uint8_t* data, size_t data_size); +enum i2c_master_rc i2c_master_address_write(uint32_t i2c, uint16_t slave, bool address_10bit, const uint8_t* address, size_t address_size, const uint8_t* data, size_t data_size); diff --git a/lib/menu.c b/lib/menu.c index 0665149..7eb089b 100644 --- a/lib/menu.c +++ b/lib/menu.c @@ -13,7 +13,7 @@ * */ /** definitions to build menus (code) - * @file menu.h + * @file menu.c * @author King Kévin * @date 2018 */ @@ -39,7 +39,7 @@ bool menu_handle_command(const char* line, const struct menu_command_t* command_ } // get command - char* dup = malloc(strlen(line)+1); // buffer to copy the line + char* dup = calloc(strlen(line)+1, sizeof(char)); // buffer to copy the line strncpy(dup, line, strlen(line)+1); // make a copy of the line since strtok can modify it const char* delimiter = " "; // words are separated by spaces char* word = strtok(dup, delimiter); // get first word @@ -57,6 +57,7 @@ bool menu_handle_command(const char* line, const struct menu_command_t* command_ if (MENU_ARGUMENT_NONE==command.argument) { // check if argument can be passed (*command.command_handler)(NULL); // call without argument } else { // argument can be passed + const char* original_argument = line+strlen(word)+1; // remember the start of the argument in the original line word = strtok(NULL, delimiter); // get next word if (!word) { // no argument provided (*command.command_handler)(NULL); // call without argument @@ -70,7 +71,10 @@ bool menu_handle_command(const char* line, const struct menu_command_t* command_ double argument = atof(word); // get floating point number (*command.command_handler)(&argument); // call with argument } else if (MENU_ARGUMENT_STRING==command.argument) { // next argument should be a string - (*command.command_handler)(word); // call with argument + if (delimiter[0]==original_argument[strlen(word)]) { // if there is more than one word + word[strlen(word)] = delimiter[0]; // remove the end of string + } + (*command.command_handler)(word); // call with argument (remaining of the string) } } } diff --git a/lib/menu.h b/lib/menu.h index 31b0190..e7e4774 100644 --- a/lib/menu.h +++ b/lib/menu.h @@ -40,13 +40,13 @@ struct menu_command_t { /** parse command from line and call corresponding command * @param[in] line use input to parse * @param[in] command_list list of available commands - * @prarm[in] command_list_length number of available commands + * @param[in] command_list_length number of available commands * @return if an command corresponding to the line has been found and called */ bool menu_handle_command(const char* line, const struct menu_command_t* command_list, size_t command_list_length); /** print the commands from the command list * @param[in] command_list list of available commands - * @prarm[in] command_list_length number of available commands + * @param[in] command_list_length number of available commands */ void menu_print_commands(const struct menu_command_t* command_list, size_t command_list_length); diff --git a/lib/print.c b/lib/print.c index 8e41253..e992a1f 100644 --- a/lib/print.c +++ b/lib/print.c @@ -136,6 +136,7 @@ static size_t print_signed(char** str, size_t* size, int64_t d, uint32_t padding * @param[in,out] size size of string * @param[in] f floating number to be printed * @param[in] padding number of 0's to pad + * @param[in] fractional numbers of digits after the decimal point * @param[in] sign if sign should be printed * @return number of characters printed **/ @@ -340,6 +341,7 @@ static size_t vsnprintf(char** str, size_t* size, const char *format, va_list va } // check padding if ('0'==*format) { // padding required + padding = 0; // reset padding format++; // go to padding number while (*format>='0' && *format<='9') { if (padding>UINT32_MAX/10) { // check for overflow @@ -361,6 +363,7 @@ static size_t vsnprintf(char** str, size_t* size, const char *format, va_list va } // check fractional if ('.'==*format) { // fractional required + fractional = 0; // reset fractional format++; // go to fractional number while (*format>='0' && *format<='9') { if (fractional>UINT32_MAX/10) { // check for overflow diff --git a/lib/terminal.h b/lib/terminal.h index 4bd108a..1b7fcb3 100644 --- a/lib/terminal.h +++ b/lib/terminal.h @@ -25,7 +25,9 @@ extern char* terminal_prefix; /** initialize terminal prompt */ void terminal_setup(void); -/** send character to terminal */ +/** send character to terminal + * @param[in] c character to send + */ void terminal_send(char c); /** called when a line is entered diff --git a/lib/uart.c b/lib/uart.c index 6baac9a..00f0b28 100644 --- a/lib/uart.c +++ b/lib/uart.c @@ -50,12 +50,12 @@ static volatile uint8_t tx_used = 0; /**< how much data needs to be transmitted void uart_setup(void) { /* enable UART I/O peripheral */ - rcc_periph_clock_enable(USART_PORT_RCC(UART_ID)); // enable clock for UART port peripheral - rcc_periph_clock_enable(USART_RCC(UART_ID)); // enable clock for UART peripheral + rcc_periph_clock_enable(RCC_USART_PORT(UART_ID)); // enable clock for UART port peripheral + rcc_periph_clock_enable(RCC_USART(UART_ID)); // enable clock for UART peripheral rcc_periph_clock_enable(RCC_AFIO); // enable pin alternate function (UART) - gpio_set_mode(USART_PORT(UART_ID), GPIO_MODE_OUTPUT_2_MHZ, GPIO_CNF_OUTPUT_ALTFN_PUSHPULL, USART_PIN_TX(UART_ID)); // setup GPIO pin UART transmit - gpio_set_mode(USART_PORT(UART_ID), GPIO_MODE_INPUT, GPIO_CNF_INPUT_PULL_UPDOWN, USART_PIN_RX(UART_ID)); // setup GPIO pin UART receive - gpio_set(USART_PORT(UART_ID), USART_PIN_RX(UART_ID)); // pull up to avoid noise when not connected + gpio_set_mode(USART_TX_PORT(UART_ID), GPIO_MODE_OUTPUT_2_MHZ, GPIO_CNF_OUTPUT_ALTFN_PUSHPULL, USART_TX_PIN(UART_ID)); // setup GPIO pin UART transmit + gpio_set_mode(USART_RX_PORT(UART_ID), GPIO_MODE_INPUT, GPIO_CNF_INPUT_PULL_UPDOWN, USART_RX_PIN(UART_ID)); // setup GPIO pin UART receive + gpio_set(USART_RX_PORT(UART_ID), USART_RX_PIN(UART_ID)); // pull up to avoid noise when not connected /* setup UART parameters */ usart_set_baudrate(USART(UART_ID), UART_BAUDRATE); diff --git a/lib/usb_cdcacm.c b/lib/usb_cdcacm.c index e98ccaa..dc1b967 100644 --- a/lib/usb_cdcacm.c +++ b/lib/usb_cdcacm.c @@ -15,30 +15,42 @@ /** library for USB CDC ACM communication (code) * @file usb_cdcacm.c * @author King Kévin - * @date 2016-2017 + * @date 2016-2018 */ /* standard libraries */ #include // standard integer types -#include // standard I/O facilities #include // general utilities /* STM32 (including CM3) libraries */ +#include // Cortex M3 utilities +#include // reset utilities +#include // interrupt handler #include // real-time control clock library #include // general purpose input output library -#include // interrupt handler -#include // reset utilities -#include // Cortex M3 utilities #include // USB library #include // USB CDC library -#include // synchronisation utilities #include // DFU definitions +/* own libraries */ #include "global.h" // global utilities #include "usb_cdcacm.h" // USB CDC ACM header and definitions +/** maximum packet size for USB data transfer */ +#define USB_DATA_TRANSFER_SIZE 64 // 64 is the maximum for full speed devices + +volatile bool usb_cdcacm_connecting = false; + static uint8_t usbd_control_buffer[128] = {0}; /**< buffer to be used for control requests */ static usbd_device *usb_device = NULL; /**< structure holding all the info related to the USB device */ +static volatile bool usb_tx_ongoing = false; /**< if USB transmission is already ongoing */ +static volatile bool first_connection = false; /**< used to detect when the first connection occurred */ + +/* output ring buffer, index, and available memory */ +static uint8_t tx_buffer[256] = {0}; /**< ring buffer for data to transmit */ +static volatile uint16_t tx_i = 0; /**< current position if transmitted data */ +static volatile uint16_t tx_used = 0; /**< how much data needs to be transmitted */ +static volatile bool tx_lock = false; /**< if the transmit buffer is currently being written */ /** USB CDC ACM device descriptor * @note as defined in USB CDC specification section 5 @@ -51,12 +63,12 @@ static const struct usb_device_descriptor usb_cdcacm_device_descriptor = { .bDeviceSubClass = 0, /**< unused */ .bDeviceProtocol = 0, /**< unused */ .bMaxPacketSize0 = 64, /**< packet size for endpoint zero in bytes */ - .idVendor = 0xc440, /**< Vendor ID (CuVo...) */ - .idProduct = 0x0d00, /**< product ID within the Vendor ID space (...odoo) */ - .bcdDevice = 0x0100, /**< version number for the device */ + .idVendor = 0x1209, /**< pid.codes vendor ID */ + .idProduct = 0x4256, /**< BusVoodo product ID within the Vendor ID space */ + .bcdDevice = 0x0000, /**< Device Release Number: board version number */ .iManufacturer = 1, /**< the index of the string in the string table that represents the name of the manufacturer of this device */ .iProduct = 2, /**< the index of the string in the string table that represents the name of the product */ - .iSerialNumber = 3, /**< the index of the string in the string table that represents the serial number of this item in string form */ + .iSerialNumber = 0, /**< the index of the string in the string table that represents the serial number of this item in string form */ .bNumConfigurations = 1, /**< the number of possible configurations this device has */ }; @@ -68,19 +80,19 @@ static const struct usb_endpoint_descriptor usb_cdcacm_data_endpoints[] = {{ .bDescriptorType = USB_DT_ENDPOINT, /**< a value of 5 indicates that this describes an endpoint */ .bEndpointAddress = 0x02, /**< OUT (from host) direction (0<<7), endpoint 2 */ .bmAttributes = USB_ENDPOINT_ATTR_BULK, /**< bulk mode */ - .wMaxPacketSize = 64, /**< maximum packet size */ + .wMaxPacketSize = USB_DATA_TRANSFER_SIZE, /**< maximum packet size */ .bInterval = 1, /**< the frequency, in number of frames, that we're going to be sending data */ },{ .bLength = USB_DT_ENDPOINT_SIZE, /**< the size of the endpoint descriptor in bytes */ .bDescriptorType = USB_DT_ENDPOINT, /**< a value of 5 indicates that this describes an endpoint */ .bEndpointAddress = 0x82, /**< IN (to host) direction (1<<7), endpoint 2 */ .bmAttributes = USB_ENDPOINT_ATTR_BULK, /**< bulk mode */ - .wMaxPacketSize = 64, /**< maximum packet size */ + .wMaxPacketSize = USB_DATA_TRANSFER_SIZE, /**< maximum packet size */ .bInterval = 1, /**< the frequency, in number of frames, that we're going to be sending data */ }}; /** USB CDC ACM communication endpoints - * @note This notification endpoint isn't implemented. According to CDC spec its optional, but its absence causes a NULL pointer dereference in Linux cdc_acm driver + * @note This notification endpoint isn't implemented. According to CDC spec its optional, but its absence causes a NULL pointer dereference in Linux cdc_acm driver */ static const struct usb_endpoint_descriptor usb_cdcacm_communication_endpoints[] = {{ .bLength = USB_DT_ENDPOINT_SIZE, /**< the size of the endpoint descriptor in bytes */ @@ -92,8 +104,8 @@ static const struct usb_endpoint_descriptor usb_cdcacm_communication_endpoints[] }}; /** USB CDC ACM functional descriptor - * @return * @note as defined in USB CDC specification section 5.2.3 + * @return packed structure */ static const struct { struct usb_cdc_header_descriptor header; /**< header */ @@ -153,17 +165,17 @@ static const struct usb_interface_descriptor usb_cdcacm_communication_interface * @note as defined in USB CDC specification section 5.1.3 */ static const struct usb_interface_descriptor usb_cdcacm_data_interface = { - .bLength = USB_DT_INTERFACE_SIZE, - .bDescriptorType = USB_DT_INTERFACE, - .bInterfaceNumber = 1, - .bAlternateSetting = 0, - .bNumEndpoints = 2, - .bInterfaceClass = USB_CLASS_DATA, - .bInterfaceSubClass = 0, - .bInterfaceProtocol = 0, - .iInterface = 0, + .bLength = USB_DT_INTERFACE_SIZE, /**< size of descriptor in byte */ + .bDescriptorType = USB_DT_INTERFACE, /**< interface descriptor type */ + .bInterfaceNumber = 1, /**< interface number in the list */ + .bAlternateSetting = 0, /**< no alternative settings */ + .bNumEndpoints = 2, /**< only the control pipe at endpoint 0 is used */ + .bInterfaceClass = USB_CLASS_DATA, /**< USB CDC interface class */ + .bInterfaceSubClass = 0, /**< USB CDC ACM interface subclass */ + .bInterfaceProtocol = 0, /**< USB CDC ACM none protocol */ + .iInterface = 0, /**< the index of the string in the string table that represents interface description */ - .endpoint = usb_cdcacm_data_endpoints, + .endpoint = usb_cdcacm_data_endpoints, /**< point to endpoint descriptor */ }; /** USB DFU functional descriptor @@ -190,7 +202,8 @@ static const struct usb_interface_descriptor usb_dfu_interface = { .bInterfaceClass = 0xFE, /**< DFU interface class (not defined in libopencm3 dfu lib) */ .bInterfaceSubClass = 1, /**< DFU interface subclass (not defined in libopencm3 dfu lib) */ .bInterfaceProtocol = 1, /**< runtime protocol (not defined in libopencm3 dfu lib) */ - .iInterface = 4, /**< the index of the string in the string table that represents interface description */ + .iInterface = 3, /**< the index of the string in the string table that represents interface description */ + .extra = &usb_dfu_functional, /**< point to functional descriptor */ .extralen = sizeof(usb_dfu_functional), /**< size of functional descriptor */ }; @@ -216,7 +229,7 @@ static const struct usb_config_descriptor usb_cdcacm_configuration_descriptor = .bConfigurationValue = 1, /**< the index of this configuration */ .iConfiguration = 0, /**< a string index describing this configuration (zero means not provided) */ .bmAttributes = 0x80, /**< bus powered (1<<7) */ - .bMaxPower = 0x32, /**< the maximum amount of current that this device will draw in 2mA units */ + .bMaxPower = 0xfa, /**< the maximum amount of current that this device will draw in 2mA units */ // end of header .interface = usb_cdcacm_interfaces, /**< pointer to an array of interfaces */ }; @@ -225,19 +238,11 @@ static const struct usb_config_descriptor usb_cdcacm_configuration_descriptor = * @note starting with index 1 */ static const char *usb_strings[] = { - "CuVoodoo", - "STM32F1", - "CDC-ACM", - "CuVoodoo DFU bootloader (runtime mode)", + "CuVoodoo", /**< manufacturer string */ + "BusVoodoo multi-protocol debugging adapter", /**< product string */ + "DFU bootloader (runtime mode)", /**< DFU interface string */ }; -/* output ring buffer, index, and available memory */ -static uint8_t tx_buffer[64] = {0}; /**< ring buffer for data to transmit */ -static volatile uint8_t tx_i = 0; /**< current position if transmitted data */ -static volatile uint8_t tx_used = 0; /**< how much data needs to be transmitted */ -mutex_t tx_lock = MUTEX_UNLOCKED; /**< lock to update tx_i or tx_used */ -static bool connected = false; /**< is the USB device is connected to a host */ - /** disconnect USB by pulling down D+ to for re-enumerate */ static void usb_disconnect(void) { @@ -246,17 +251,16 @@ static void usb_disconnect(void) rcc_periph_clock_enable(RCC_GPIOB); gpio_set_mode(GPIOB, GPIO_MODE_OUTPUT_2_MHZ, GPIO_CNF_OUTPUT_PUSHPULL, GPIO9); gpio_set(GPIOB, GPIO9); - for (uint32_t i = 0; i < 0x2000; i++) { - __asm__("nop"); + for (uint32_t i = 0; i < 0x2000; i++) { // wait for at least 10 ms + __asm__("nop"); } - gpio_clear(GPIOB, GPIO9); #else // pull USB D+ low for a short while rcc_periph_clock_enable(RCC_GPIOA); gpio_set_mode(GPIOA, GPIO_MODE_OUTPUT_2_MHZ, GPIO_CNF_OUTPUT_PUSHPULL, GPIO12); gpio_clear(GPIOA, GPIO12); - for (uint32_t i = 0; i < 0x2000; i++) { - __asm__("nop"); + for (uint32_t i = 0; i < 0x2000; i++) { // wait for at least 10 ms + __asm__("nop"); } #endif } @@ -269,6 +273,7 @@ static void usb_reset(usbd_device *usbd_dev, struct usb_setup_data *req) { (void)usbd_dev; // variable not used (void)req; // variable not used + usb_disconnect(); // USB detach (disconnect to force re-enumeration) scb_reset_system(); // reset device while (true); // wait for the reset to happen @@ -299,10 +304,6 @@ static void usb_dfu_detach(usbd_device *usbd_dev, struct usb_setup_data *req) */ static int usb_cdcacm_control_request(usbd_device *usbd_dev, struct usb_setup_data *req, uint8_t **buf, uint16_t *len, void (**complete)(usbd_device *usbd_dev, struct usb_setup_data *req)) { - (void)complete; - (void)buf; - (void)usbd_dev; - if (usb_dfu_interface.bInterfaceNumber==req->wIndex) { // check if request is for DFU switch (req->bRequest) { case DFU_DETACH: // USB detach requested @@ -320,13 +321,13 @@ static int usb_cdcacm_control_request(usbd_device *usbd_dev, struct usb_setup_da default: // other requests are not supported return 0; } - } else { + } else if (usb_cdcacm_communication_interface.bInterfaceNumber==req->wIndex) { // check if request is for CDC switch (req->bRequest) { case USB_CDC_REQ_SET_CONTROL_LINE_STATE: - connected = req->wValue ? true : false; // check if terminal is open + usb_cdcacm_connecting = (0!=req->wValue); // check if terminal is open (windows set the control line state before a terminal opens the port, but with value 0) //bool dtr = (req->wValue & (1 << 0)) ? true : false; //bool rts = (req->wValue & (1 << 1)) ? true : false; - /* this Linux cdc_acm driver requires this to be implemented + /* the Linux cdc_acm driver requires this to be implemented * even though it's optional in the CDC spec, and we don't * advertise it in the ACM functional descriptor. */ @@ -340,7 +341,7 @@ static int usb_cdcacm_control_request(usbd_device *usbd_dev, struct usb_setup_da notif->wLength = 2; reply[8] = req->wValue & 3; reply[9] = 0; - usbd_ep_write_packet(usbd_dev, 0x81, reply, LENGTH(reply)); + usbd_ep_write_packet(usbd_dev, 0x81, reply, LENGTH(reply)); // send the reply from communication endpoint (we can't use the complete callback because we are not using the current control endpoint) break; case USB_CDC_REQ_SET_LINE_CODING: // ignore if length is wrong @@ -363,45 +364,62 @@ static int usb_cdcacm_control_request(usbd_device *usbd_dev, struct usb_setup_da return 1; } +/** USB CDC ACM communication callback + * @note if transmission happens before the control setting is complete with a response form the communication endpoint, Linux echoes back the data + * @param[in] usbd_dev USB device descriptor + * @param[in] req control request information + */ +static void usb_cdcacm_communication_cb(usbd_device *usbd_dev, uint8_t ep) +{ + (void)ep; // not used + + first_connection |= usb_cdcacm_connecting; // check if port has been opened + if (usbd_dev && tx_used>0 && !usb_tx_ongoing && first_connection) { // if buffer is not empty + usbd_ep_write_packet(usbd_dev, 0x82, NULL, 0); // trigger tx callback + } +} + /** USB CDC ACM data received callback + * @note called when data has been received * @param[in] usbd_dev USB device descriptor * @param[in] ep endpoint where data came in */ static void usb_cdcacm_data_rx_cb(usbd_device *usbd_dev, uint8_t ep) { - (void)ep; + (void)ep; // not used - char usb_data[64] = {0}; // buffer to read data + char usb_data[USB_DATA_TRANSFER_SIZE] = {0}; // buffer to read data uint16_t usb_length = 0; // length of incoming data - /* receive data */ + // receive data usb_length = usbd_ep_read_packet(usbd_dev, 0x02, usb_data, sizeof(usb_data)); if (usb_length) { // copy received data - for (uint16_t i=0; i 64 ? 64 : tx_used); // length of data to be transmitted (respect max packet size) + if (!tx_lock) { + usb_tx_ongoing = true; // remember we started transmission + uint16_t usb_length = (tx_used > USB_DATA_TRANSFER_SIZE ? USB_DATA_TRANSFER_SIZE : tx_used); // length of data to be transmitted (respect max packet size) usb_length = (usb_length > (LENGTH(tx_buffer)-tx_i) ? LENGTH(tx_buffer)-tx_i : usb_length); // since here we use the source array not as ring buffer, only go up to the end while (usb_length != usbd_ep_write_packet(usb_device, 0x82, (void*)(&tx_buffer[tx_i]), usb_length)); // ensure data is written into transmit buffer tx_i = (tx_i+usb_length)%LENGTH(tx_buffer); // update location on buffer tx_used -= usb_length; // update used size - mutex_unlock(&tx_lock); // release lock } else { usbd_ep_write_packet(usb_device, 0x82, NULL, 0); // trigger empty tx for a later callback } @@ -414,19 +432,17 @@ static void usb_cdcacm_data_tx_cb(usbd_device *usbd_dev, uint8_t ep) */ static void usb_cdcacm_set_config(usbd_device *usbd_dev, uint16_t wValue) { - (void)wValue; + (void)wValue; // not used - usbd_ep_setup(usbd_dev, 0x81, USB_ENDPOINT_ATTR_INTERRUPT, 16, NULL); - usbd_ep_setup(usbd_dev, 0x02, USB_ENDPOINT_ATTR_BULK, 64, usb_cdcacm_data_rx_cb); - usbd_ep_setup(usbd_dev, 0x82, USB_ENDPOINT_ATTR_BULK, 64, usb_cdcacm_data_tx_cb); + usbd_ep_setup(usbd_dev, usb_cdcacm_communication_endpoints[0].bEndpointAddress, usb_cdcacm_communication_endpoints[0].bmAttributes, usb_cdcacm_communication_endpoints[0].wMaxPacketSize, usb_cdcacm_communication_cb); // set communication endpoint + usbd_ep_setup(usbd_dev, usb_cdcacm_data_endpoints[0].bEndpointAddress, usb_cdcacm_data_endpoints[0].bmAttributes, usb_cdcacm_data_endpoints[0].wMaxPacketSize, usb_cdcacm_data_rx_cb); // set outgoing (from host) data endpoint + usbd_ep_setup(usbd_dev, usb_cdcacm_data_endpoints[1].bEndpointAddress, usb_cdcacm_data_endpoints[1].bmAttributes, usb_cdcacm_data_endpoints[1].wMaxPacketSize, usb_cdcacm_data_tx_cb); // set incoming (to host) data endpoint - usbd_register_control_callback( usbd_dev, USB_REQ_TYPE_CLASS | USB_REQ_TYPE_INTERFACE, USB_REQ_TYPE_TYPE | USB_REQ_TYPE_RECIPIENT, usb_cdcacm_control_request); + usbd_register_control_callback(usbd_dev, USB_REQ_TYPE_CLASS | USB_REQ_TYPE_INTERFACE, USB_REQ_TYPE_TYPE | USB_REQ_TYPE_RECIPIENT, usb_cdcacm_control_request); } void usb_cdcacm_setup(void) { - connected = false; // start with USB not connected - // initialize USB rcc_periph_reset_pulse(RST_USB); // reset USB peripheral usb_disconnect(); // disconnect to force re-enumeration @@ -439,15 +455,18 @@ void usb_cdcacm_setup(void) // reset buffer states tx_i = 0; tx_used = 0; - mutex_unlock(&tx_lock); + tx_lock = false; // release lock + usb_cdcacm_connecting = false; // clear flag + usb_tx_ongoing = false; // clear transmission lock + first_connection = false; // reset first connection detection } void usb_cdcacm_putchar(char c) { - if (!usb_device || !connected) { + if (!usb_device) { return; } - mutex_lock(&tx_lock); // get lock to prevent race condition + tx_lock = true; // put lock on transmit buffer if (tx_used0 && usb_device && !usb_tx_ongoing) { // if buffer is not empty anymore usbd_ep_write_packet(usb_device, 0x82, NULL, 0); // trigger tx callback } } diff --git a/lib/usb_cdcacm.h b/lib/usb_cdcacm.h index d56f489..df1c534 100644 --- a/lib/usb_cdcacm.h +++ b/lib/usb_cdcacm.h @@ -19,6 +19,9 @@ */ #pragma once +/** flag set to true when user is connected to USB CDC ACM port (e.g. when a terminal is opened) */ +extern volatile bool usb_cdcacm_connecting; + /** setup USB CDC ACM peripheral */ void usb_cdcacm_setup(void); /** send character over USB (non-blocking) diff --git a/lib/usb_dfu.c b/lib/usb_dfu.c index bcfa5b9..fb0bc68 100644 --- a/lib/usb_dfu.c +++ b/lib/usb_dfu.c @@ -55,12 +55,12 @@ static const struct usb_device_descriptor usb_dfu_device = { .bDeviceSubClass = 0, /**< unused */ .bDeviceProtocol = 0, /**< unused */ .bMaxPacketSize0 = 64, /**< packet size for endpoint zero in bytes */ - .idVendor = 0xc440, /**< Vendor ID (CuVo...) */ - .idProduct = 0x0d00, /**< product ID within the Vendor ID space (...odoo) */ - .bcdDevice = 0x0100, /**< version number for the device */ + .idVendor = 0x1209, /**< pid.codes vendor ID */ + .idProduct = 0x4256, /**< BusVoodo product ID within the Vendor ID space */ + .bcdDevice = 0x0000, /**< Device Release Number: board version number */ .iManufacturer = 1, /**< the index of the string in the string table that represents the name of the manufacturer of this device */ .iProduct = 2, /**< the index of the string in the string table that represents the name of the product */ - .iSerialNumber = 3, /**< the index of the string in the string table that represents the serial number of this item in string form */ + .iSerialNumber = 0, /**< the index of the string in the string table that represents the serial number of this item in string form */ .bNumConfigurations = 1, /**< the number of possible configurations this device has */ }; @@ -88,7 +88,7 @@ static const struct usb_interface_descriptor usb_dfu_interface = { .bInterfaceClass = 0xFE, /**< DFU interface class (not defined in libopencm3 dfu lib) */ .bInterfaceSubClass = 1, /**< DFU interface subclass (not defined in libopencm3 dfu lib) */ .bInterfaceProtocol = 2, /**< DFU interface mode protocol (not defined in libopencm3 dfu lib) */ - .iInterface = 4, /**< the index of the string in the string table that represents interface description */ + .iInterface = 3, /**< the index of the string in the string table that represents interface description */ .extra = &usb_dfu_functional, /**< point to functional descriptor */ .extralen = sizeof(usb_dfu_functional), /**< size of functional descriptor */ }; @@ -119,10 +119,9 @@ static const struct usb_config_descriptor usb_dfu_configuration = { * @note starts with index 1 */ static const char *usb_dfu_strings[] = { - "CuVoodoo", - "STM32F1", - "DFU", - "CuVoodoo DFU bootloader (DFU mode)", + "CuVoodoo", /**< manufacturer string */ + "BusVoodoo multi-protocol debugging adapter ", /**< product string */ + "DFU bootloader (DFU mode)", /**< DFU interface string */ }; /** disconnect USB to force re-enumerate */