take changes from busvoodoo branch

This commit is contained in:
King Kévin 2018-04-03 16:59:02 +02:00
parent 922661ffb3
commit 593b0e0e25
14 changed files with 801 additions and 405 deletions

View File

@ -14,7 +14,7 @@ APPLICATION = "application"
FIRMWARES = [BOOTLOADER, APPLICATION] FIRMWARES = [BOOTLOADER, APPLICATION]
# which development board is used # 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" BOARD = ENV["BOARD"] || "CORE_BOARD"
# libopencm3 definitions # libopencm3 definitions
@ -72,7 +72,7 @@ ldflags << "-nostartfiles"
# only keep used sections # only keep used sections
ldflags << "--gc-sections" ldflags << "--gc-sections"
# add standard libraries (for libc, libm, libnosys, libgcc) because we don't use arm-none-eabi-gcc to locate them # 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 # add libopencm3
library_paths += [LIBOPENCM3_LIB] library_paths += [LIBOPENCM3_LIB]
# include libraries in flags # include libraries in flags
@ -144,7 +144,7 @@ task :doc => ["Doxyfile", "README.md"] do |t|
end end
desc "compile source into object" 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]}" sh "#{CC} #{cflags} #{archflags} -o #{t.name} -c #{t.prerequisites[0]}"
end end
@ -154,7 +154,7 @@ rule '.d' => ['.c', "#{LIBOPENCM3_LIB}/lib#{STM32F1_LIB}.a"] do |t|
end end
desc "link binary" 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 "#{LD} #{ldflags} --script #{t.name.ext('ld')} #{t.prerequisites[0..-3].join(' ')} #{ldlibs} -o #{t.name}"
sh "size #{t.name}" sh "size #{t.name}"
end end
@ -198,7 +198,7 @@ BMP_PORT = ENV["BMP_PORT"] || "/dev/ttyACM0"
desc "flash application using USB DFU" desc "flash application using USB DFU"
task :flash => APPLICATION+".bin" do |t| 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 end
desc "flash bootloader using SWD" desc "flash bootloader using SWD"
@ -227,7 +227,7 @@ task :debug => APPLICATION+".elf" do |t|
case SWD_ADAPTER case SWD_ADAPTER
when "STLINKV2" when "STLINKV2"
# for GDB to work with openOCD the firmware needs to be reloaded # 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" 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}") 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 end

View File

@ -39,16 +39,13 @@ void main(void)
// check if a soft boot has been used // 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 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; dfu_force = true;
} else { // check if } else { // check if the force DFU mode input is set
// disable SWJ pin to use as GPIO // disable SWJ pin to use as GPIO
#if (GPIO(B)==GPIO(DFU_FORCE_PORT)) && (GPIO(4)==GPIO(DFU_FORCE_PIN)) #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); 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))) #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); 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))) #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); gpio_primary_remap(AFIO_MAPR_SWJ_CFG_JTAG_OFF_SW_OFF, 0);
#endif #endif
rcc_periph_clock_enable(RCC_GPIO(DFU_FORCE_PORT)); // enable clock for GPIO domain 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 rcc_clock_setup_in_hse_8mhz_out_72mhz(); // start main clock
board_setup(); // setup board to control LED 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 led_on(); // indicate bootloader started
#endif
usb_dfu_setup(); // setup USB DFU for firmware upload usb_dfu_setup(); // setup USB DFU for firmware upload
usb_dfu_start(); // run DFU mode usb_dfu_start(); // run DFU mode
} }

View File

@ -34,13 +34,14 @@
#include "global.h" // common methods #include "global.h" // common methods
volatile bool button_flag = false; volatile bool button_flag = false;
volatile uint32_t sleep_duration = 0; /**< sleep duration count down (in SysTick interrupts) */
volatile bool user_input_available = false; 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_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_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 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) char* b2s(uint64_t binary, uint8_t rjust)
{ {
static char string[64+1] = {0}; // the string representation to return 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 */ /** switch on board LED */
void led_on(void) 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 #if defined(LED_ON) && LED_ON
gpio_set(GPIO(LED_PORT), GPIO(LED_PIN)); gpio_set(GPIO(LED_PORT), GPIO(LED_PIN));
#else #else
@ -76,28 +81,77 @@ void led_on(void)
/** switch off board LED */ /** switch off board LED */
void led_off(void) 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 #if defined(LED_ON) && LED_ON
gpio_clear(GPIO(LED_PORT), GPIO(LED_PIN)); gpio_clear(GPIO(LED_PORT), GPIO(LED_PIN));
#else #else
gpio_set(GPIO(LED_PORT), GPIO(LED_PIN)); gpio_set(GPIO(LED_PORT), GPIO(LED_PIN));
#endif #endif
#endif
} }
/** toggle board LED */ /** toggle board LED */
void led_toggle(void) 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)); 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) void sleep_us(uint32_t duration)
{ {
systick_counter_disable(); // disable SysTick to reconfigure it 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_clear(); // reset SysTick
systick_set_frequency(1000000,rcc_ahb_frequency); // set SysTick frequency to microseconds
systick_interrupt_enable(); // enable interrupt to count duration systick_interrupt_enable(); // enable interrupt to count duration
sleep_duration = duration; // save sleep duration for count down sleep_duration = duration; // save sleep duration for count down
systick_counter_enable(); // start counting 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 __WFI(); // go to sleep
} }
} }
@ -105,25 +159,28 @@ void sleep_us(uint32_t duration)
void sleep_ms(uint32_t duration) void sleep_ms(uint32_t duration)
{ {
systick_counter_disable(); // disable SysTick to reconfigure it 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_clear(); // reset SysTick
systick_set_frequency(1000,rcc_ahb_frequency); // set SysTick frequency to milliseconds
systick_interrupt_enable(); // enable interrupt to count duration systick_interrupt_enable(); // enable interrupt to count duration
sleep_duration = duration; // save sleep duration for count down sleep_duration = duration; // save sleep duration for count down
systick_counter_enable(); // start counting 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 // __WFI(); // go to sleep
} }
} }
/** SysTick interrupt handler */ /** SysTick interrupt handler */
void sys_tick_handler(void) void sys_tick_handler(void)
{ {
if (sleep_duration) { if (sleep_duration>0) {
sleep_duration--; // decrement duration sleep_duration--; // decrement duration
} }
if (0==sleep_duration) { // sleep complete if (0==sleep_duration) { // sleep complete
systick_counter_disable(); // stop systick systick_counter_disable(); // stop systick
systick_interrupt_disable(); // stop interrupting systick_interrupt_disable(); // stop interrupting
sleep_duration = 0; // ensure it still is at 0
} }
} }
@ -155,7 +212,18 @@ void board_setup(void)
{ {
// setup LED // setup LED
rcc_periph_clock_enable(RCC_GPIO(LED_PORT)); // enable clock for 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' 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 led_off(); // switch off LED per default
// setup button // setup button

View File

@ -20,7 +20,7 @@
#pragma once #pragma once
/** enable debugging functionalities */ /** enable debugging functionalities */
#define DEBUG true #define DEBUG false
/** get the length of an array */ /** get the length of an array */
#define LENGTH(x) (sizeof(x) / sizeof((x)[0])) #define LENGTH(x) (sizeof(x) / sizeof((x)[0]))
@ -181,25 +181,32 @@
/** get USART based on USART identifier */ /** get USART based on USART identifier */
#define USART(x) CAT2(USART,x) #define USART(x) CAT2(USART,x)
/** get RCC for USART based on USART identifier */ /** 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 */ /** get NVIC IRQ for USART based on USART identifier */
#define USART_IRQ(x) CAT3(NVIC_USART,x,_IRQ) #define USART_IRQ(x) CAT3(NVIC_USART,x,_IRQ)
/** get interrupt service routine for USART based on USART identifier */ /** get interrupt service routine for USART based on USART identifier */
#define USART_ISR(x) CAT3(usart,x,_isr) #define USART_ISR(x) CAT3(usart,x,_isr)
/** get port for USART based on USART identifier */ /** get port for USART transmit pin based on USART identifier */
#define USART_PORT(x) CAT2(USART_PORT,x) #define USART_TX_PORT(x) CAT3(GPIO_BANK_USART,x,_TX)
#define USART_PORT1 GPIOA /**< USART 1 is on port A */ /** get port for USART receive pin based on USART identifier */
#define USART_PORT2 GPIOA /**< USART 2 is on port A */ #define USART_RX_PORT(x) CAT3(GPIO_BANK_USART,x,_RX)
#define USART_PORT3 GPIOB /**< USART 3 is on port B */ /** 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 */ /** 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_PORT1 RCC_GPIOA /**< USART 1 is on port A */
#define RCC_USART_PORT2 RCC_GPIOA /**< USART 2 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 */ #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 */ /** get port based on ADC12_IN identifier */
#define ADC12_IN_PORT(x) CAT3(ADC12_IN,x,_PORT) #define ADC12_IN_PORT(x) CAT3(ADC12_IN,x,_PORT)
#define ADC12_IN0_PORT GPIOA /**< ADC12_IN0 is on PA0 */ #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 */ #define RCC_ADC12_IN15 RCC_GPIOC /**< ADC12_IN15 is on PC5 */
/** get channel based on ADC12_IN identifier */ /** get channel based on ADC12_IN identifier */
#define ADC_CHANNEL(x) CAT2(ADC_CHANNEL,x) #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 */ /** get SPI based on SPI identifier */
#define SPI(x) CAT2(SPI,x) #define SPI(x) CAT2(SPI,x)
/** get RCC for SPI based on SPI identifier */ /** 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_PORT B /**< GPIO port (port B on maple mini) */
#define LED_PIN 1 /**< GPIO pin (pin PB1 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 */ #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 #endif
/** @} */ /** @} */
@ -414,6 +406,11 @@
#define DFU_FORCE_PORT BUTTON_PORT /**< button port */ #define DFU_FORCE_PORT BUTTON_PORT /**< button port */
#define DFU_FORCE_PIN BUTTON_PIN /**< button pin */ #define DFU_FORCE_PIN BUTTON_PIN /**< button pin */
#define DFU_FORCE_VALUE 0 /**< button floating unpressed, connected to ground pressed to force DFU mode */ #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 #else
/* use the JNTRST pin as GPIO (this will disable the SWJ function, but we are not using it) */ /* 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) */ #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); void led_off(void);
/** toggle board LED */ /** toggle board LED */
void led_toggle(void); 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 /** go to sleep for some microseconds
* @param[in] duration sleep duration in us * @param[in] duration sleep duration in us
*/ */

View File

@ -16,376 +16,618 @@
* @file i2c_master.c * @file i2c_master.c
* @author King Kévin <kingkevin@cuvoodoo.info> * @author King Kévin <kingkevin@cuvoodoo.info>
* @date 2017-2018 * @date 2017-2018
* @note peripherals used: I2C @ref i2c_master_i2c, timer @ref i2c_master_timer * @note peripherals used: I2C
*/ */
/* standard libraries */ /* standard libraries */
#include <stdint.h> // standard integer types #include <stdint.h> // standard integer types
//#include <stdio.h> // standard I/O facilities
#include <stdlib.h> // general utilities #include <stdlib.h> // general utilities
/* STM32 (including CM3) libraries */ /* STM32 (including CM3) libraries */
#include <libopencm3/stm32/rcc.h> // real-time control clock library #include <libopencm3/stm32/rcc.h> // real-time control clock library
#include <libopencm3/stm32/gpio.h> // general purpose input output library #include <libopencm3/stm32/gpio.h> // general purpose input output library
#include <libopencm3/stm32/i2c.h> // I2C library #include <libopencm3/stm32/i2c.h> // I2C library
#include <libopencm3/stm32/timer.h> // timer utilities
/* own libraries */ /* own libraries */
#include "global.h" // global utilities #include "global.h" // global utilities
#include "i2c_master.h" // I2C header and definitions #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 */ static uint32_t RCC_I2C(uint32_t i2c)
/** @} */
/** @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)
{ {
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 // configure I2C peripheral
rcc_periph_clock_enable(RCC_I2C_SCL_PORT(I2C_MASTER_I2C)); // enable clock for I2C I/O peripheral rcc_periph_clock_enable(RCC_GPIO_PORT_SCL(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(GPIO_PORT_SCL(i2c), GPIO_PIN_SCL(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 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_I2C_SCL_PORT(I2C_MASTER_I2C)); // enable clock for I2C I/O peripheral rcc_periph_clock_enable(RCC_GPIO_PORT_SDA(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(GPIO_PORT_SDA(i2c), GPIO_PIN_SDA(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 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_AFIO); // enable clock for alternate function
rcc_periph_clock_enable(RCC_I2C(I2C_MASTER_I2C)); // enable clock for I2C peripheral rcc_periph_clock_enable(RCC_I2C(i2c)); // enable clock for I2C peripheral
i2c_reset(I2C(I2C_MASTER_I2C)); // reset configuration i2c_reset(i2c); // reset peripheral domain
i2c_peripheral_disable(I2C(I2C_MASTER_I2C)); // I2C needs to be disable to be configured i2c_peripheral_disable(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) I2C_CR1(i2c) |= I2C_CR1_SWRST; // reset peripheral
if (fast) { I2C_CR1(i2c) &= ~I2C_CR1_SWRST; // clear peripheral reset
i2c_set_fast_mode(I2C(I2C_MASTER_I2C)); if (0==frequency) { // don't allow null frequency
i2c_set_ccr(I2C(I2C_MASTER_I2C), rcc_apb1_frequency/(400000*2)); // set Thigh/Tlow to generate frequency of 400 kHz frequency = 1;
i2c_set_trise(I2C(I2C_MASTER_I2C), (300/(1000/(rcc_apb1_frequency/1000000)))+1); // max rise time for 300 kHz is 300 ns } else if (frequency>400) { // limit frequency to 400 kHz
} else { frequency = 400;
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)
} }
i2c_peripheral_enable(I2C(I2C_MASTER_I2C)); // enable I2C after configuration completed 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
// configure time for timeouts i2c_set_fast_mode(i2c); // set fast mode (Fm)
rcc_periph_clock_enable(RCC_TIM(I2C_MASTER_TIMER)); // enable clock for timer block i2c_set_ccr(i2c, rcc_apb1_frequency/(frequency*1000*2)); // set Thigh/Tlow to generate frequency (fast duty not used)
timer_reset(TIM(I2C_MASTER_TIMER)); // reset timer state i2c_set_trise(i2c, (300/(1000/(rcc_apb1_frequency/1000000)))+1); // max rise time for Fm mode (< 400) kHz is 300 ns
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 } else { // use fast mode for frequencies below 100 kHz
timer_one_shot_mode(TIM(I2C_MASTER_TIMER)); // stop counter after update event (we only need to one timeout and reset before next operation) i2c_set_standard_mode(i2c); // set standard mode (Sm)
if (fast) { i2c_set_ccr(i2c, rcc_apb1_frequency/(frequency*1000*2)); // set Thigh/Tlow to generate frequency of 100 kHz
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) i2c_set_trise(i2c, (1000/(1000/(rcc_apb1_frequency/1000000)))+1); // max rise time for Sm mode (< 100 kHz) is 1000 ns (~1 MHz)
} 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)
} }
timer_set_period(TIM(I2C_MASTER_TIMER), I2C_MASTER_TIMEOUT*9); // use factor to wait for all 9 bits to be transmitted i2c_peripheral_enable(i2c); // enable I2C after configuration completed
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
} }
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 // send (re-)start condition
i2c_send_start(I2C(I2C_MASTER_I2C)); // send start condition to start transaction if (I2C_CR1(i2c) & (I2C_CR1_START|I2C_CR1_STOP)) { // ensure start or stop operations are not in progress
timer_set_counter(TIM(I2C_MASTER_TIMER), 0); // restart timer return I2C_MASTER_RC_START_STOP_IN_PROGESS;
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_SR2(I2C(I2C_MASTER_I2C)) & I2C_SR2_MSL)) { // verify if in master mode i2c_send_start(i2c); // send start condition to start transaction
return false; 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) // check I2C peripheral
if (!i2c_master_start()) { // send start condition if (I2C1!=i2c && I2C2!=i2c) {
return false; // could not send start condition 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 if (!(I2C_SR2(i2c) & I2C_SR2_MSL)) { // I2C device is not in master mode
return false; return I2C_MASTER_RC_NOT_MASTER;
} }
// select slave // select slave
i2c_send_7bit_address(I2C(I2C_MASTER_I2C), slave, write ? I2C_WRITE : I2C_READ); // select slave, with read/write flag if (!address_10bit) { // 7-bit address
timer_set_counter(TIM(I2C_MASTER_TIMER), 0); // restart timer I2C_SR1(i2c) &= ~(I2C_SR1_AF); // clear acknowledgement failure
timer_clear_flag(TIM(I2C_MASTER_TIMER), TIM_SR_UIF); // clear flag i2c_send_7bit_address(i2c, slave, write ? I2C_WRITE : I2C_READ); // select slave, with read/write flag
timer_enable_counter(TIM(I2C_MASTER_TIMER)); // enable timer for timeouts while (!(I2C_SR1(i2c) & (I2C_SR1_ADDR|I2C_SR1_AF)) && !(I2C_SR1(i2c) & (I2C_SR1_BERR|I2C_SR1_ARLO))); // wait until address is transmitted
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 if (I2C_SR1(i2c) & (I2C_SR1_BERR|I2C_SR1_ARLO)) {
timer_disable_counter(TIM(I2C_MASTER_TIMER)); // disable timer for timeouts return I2C_MASTER_RC_BUS_ERROR;
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 if (I2C_SR1(i2c) & I2C_SR1_AF) { // address has not been acknowledged
return false; 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 (write) {
if (!((I2C_SR2(I2C(I2C_MASTER_I2C)) & I2C_SR2_TRA))) { // verify we are in transmit mode (and read SR2 to clear ADDR) if (!((I2C_SR2(i2c) & I2C_SR2_TRA))) { // verify we are in transmit mode (and read SR2 to clear ADDR)
return false; return I2C_MASTER_RC_NOT_TRANSMIT;
} }
} else { } else {
if ((I2C_SR2(I2C(I2C_MASTER_I2C)) & I2C_SR2_TRA)) { // verify we are in read mode (and read SR2 to clear ADDR) if ((I2C_SR2(i2c) & I2C_SR2_TRA)) { // verify we are in read mode (and read SR2 to clear ADDR)
return false; 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 // sanity check
if (data==NULL || data_size==0) { // no data to read 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) if (!(I2C_SR2(i2c) & I2C_SR2_MSL)) { // I2C device is not master
return false; // address has probably also not been sent return I2C_MASTER_RC_NOT_MASTER;
} }
if (!(I2C_SR2(I2C(I2C_MASTER_I2C)) & I2C_SR2_MSL)) { // I2C device not master mode if ((I2C_SR2(i2c) & I2C_SR2_TRA)) { // I2C device not in receiver mode
return false; 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 // read data
for (size_t i=0; i<data_size; i++) { // read bytes for (size_t i=0; i<data_size; i++) { // read bytes
if (i==data_size-1) { // prepare to sent NACK for last byte if (i==data_size-1) { // prepare to sent NACK for last byte
i2c_disable_ack(I2C(I2C_MASTER_I2C)); // NACK received to stop slave transmission i2c_disable_ack(i2c); // NACK received to stop slave transmission
i2c_send_stop(I2C(I2C_MASTER_I2C)); // send STOP after receiving byte
} else { } else {
i2c_enable_ack(I2C(I2C_MASTER_I2C)); // ACK received byte to continue slave transmission i2c_enable_ack(i2c); // ACK received byte to continue slave transmission
} }
timer_set_counter(TIM(I2C_MASTER_TIMER), 0); // restart timer while (!(I2C_SR1(i2c) & I2C_SR1_RxNE) && !(I2C_SR1(i2c) & (I2C_SR1_BERR|I2C_SR1_ARLO))); // wait until byte has been received
timer_clear_flag(TIM(I2C_MASTER_TIMER), TIM_SR_UIF); // clear flag if (I2C_SR1(i2c) & (I2C_SR1_BERR|I2C_SR1_ARLO)) {
timer_enable_counter(TIM(I2C_MASTER_TIMER)); // enable timer for timeouts return I2C_MASTER_RC_BUS_ERROR;
while (!(I2C_SR1(I2C(I2C_MASTER_I2C)) & I2C_SR1_RxNE) && !timer_get_flag(TIM(I2C_MASTER_TIMER), TIM_SR_UIF)); // wait until byte has been received
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;
} }
data[i] = i2c_get_data(I2C(I2C_MASTER_I2C)); // read received byte data[i] = i2c_get_data(i2c); // read received byte
} }
return true; return I2C_MASTER_RC_NONE;
} }
bool i2c_master_write(const uint8_t* data, size_t data_size) enum i2c_master_rc i2c_master_write(uint32_t i2c, const uint8_t* data, size_t data_size)
{ {
// check I2C peripheral
if (I2C1!=i2c && I2C2!=i2c) {
while (true);
}
// sanity check // sanity check
if (data==NULL || data_size==0) { // no data to write if (data==NULL || data_size==0) { // no data to write
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) if (!(I2C_SR2(i2c) & I2C_SR2_MSL)) { // I2C device is not master
return false; // address has probably also not been sent return I2C_MASTER_RC_NOT_MASTER;
} }
if (!(I2C_SR2(I2C(I2C_MASTER_I2C)) & I2C_SR2_MSL)) { // I2C device is not master mode if (!(I2C_SR2(i2c) & I2C_SR2_TRA)) { // I2C device not in transmitter mode
return false; return I2C_MASTER_RC_NOT_TRANSMIT;
}
if (I2C_SR1(i2c) & I2C_SR1_AF) { // check if the previous transaction went well
return I2C_MASTER_RC_NOT_READY;
} }
// write data // write data
for (size_t i=0; i<data_size; i++) { // write bytes for (size_t i=0; i<data_size; i++) { // write bytes
i2c_send_data(I2C(I2C_MASTER_I2C), data[i]); // send byte to be written in memory I2C_SR1(i2c) &= ~(I2C_SR1_AF); // clear acknowledgement failure
timer_set_counter(TIM(I2C_MASTER_TIMER),0); // restart timer i2c_send_data(i2c, data[i]); // send byte to be written in memory
timer_clear_flag(TIM(I2C_MASTER_TIMER), TIM_SR_UIF); // clear flag while (!(I2C_SR1(i2c) & (I2C_SR1_TxE|I2C_SR1_AF)) && !(I2C_SR1(i2c) & (I2C_SR1_BERR|I2C_SR1_ARLO))); // wait until byte has been transmitted
timer_enable_counter(TIM(I2C_MASTER_TIMER)); // enable timer for timeouts if (I2C_SR1(i2c) & (I2C_SR1_BERR|I2C_SR1_ARLO)) {
while (!(I2C_SR1(I2C(I2C_MASTER_I2C)) & I2C_SR1_TxE) && !timer_get_flag(TIM(I2C_MASTER_TIMER), TIM_SR_UIF)); // wait until byte has been transmitted return I2C_MASTER_RC_BUS_ERROR;
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) if (I2C_SR1(i2c) & I2C_SR1_AF) { // data has not been acknowledged
timer_clear_flag(TIM(I2C_MASTER_TIMER), TIM_SR_UIF); // clear flag return I2C_MASTER_RC_NAK;
return false;
} }
} }
return true; return I2C_MASTER_RC_NONE;
} }
void i2c_master_stop(void) enum i2c_master_rc i2c_master_stop(uint32_t i2c)
{ {
// sanity check // check I2C peripheral
if (!(I2C_SR2(I2C(I2C_MASTER_I2C)) & I2C_SR2_BUSY)) { // release is not busy if (I2C1!=i2c && I2C2!=i2c) {
return; // bus has probably already been released while (true);
} }
// sanity check
if (!(I2C_SR2(i2c) & I2C_SR2_BUSY)) { // release is not busy
return I2C_MASTER_RC_NONE; // bus has probably already been released
}
// send stop condition // send stop condition
i2c_send_stop(I2C(I2C_MASTER_I2C)); // send stop to release bus if (I2C_CR1(i2c) & (I2C_CR1_START|I2C_CR1_STOP)) { // ensure start or stop operations are not in progress
timer_set_counter(TIM(I2C_MASTER_TIMER), 0); // restart timer return I2C_MASTER_RC_START_STOP_IN_PROGESS;
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_SR2(I2C(I2C_MASTER_I2C)) & I2C_SR2_MSL) && !timer_get_flag(TIM(I2C_MASTER_TIMER), TIM_SR_UIF)); // wait until bus released (non master mode)
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
} }
i2c_send_stop(i2c); // send stop to release bus
while ((I2C_CR1(i2c) & I2C_CR1_STOP) && !(I2C_SR1(i2c) & (I2C_SR1_BERR|I2C_SR1_ARLO))); // wait until stop condition is accepted and cleared
if (I2C_SR1(i2c) & (I2C_SR1_BERR|I2C_SR1_ARLO)) {
return I2C_MASTER_RC_BUS_ERROR;
}
while ((I2C_SR2(i2c) & I2C_SR2_MSL) && !(I2C_SR1(i2c) & (I2C_SR1_BERR|I2C_SR1_ARLO))); // wait until bus released (non master mode)
if (I2C_SR1(i2c) & (I2C_SR1_BERR|I2C_SR1_ARLO)) {
return I2C_MASTER_RC_BUS_ERROR;
}
return I2C_MASTER_RC_NONE;
} }
bool i2c_master_slave_read(uint8_t slave, uint8_t* data, size_t data_size) enum i2c_master_rc i2c_master_slave_read(uint32_t i2c, uint16_t slave, bool address_10bit, uint8_t* data, size_t data_size)
{ {
// sanity check // check I2C peripheral
if (I2C_SR2(I2C(I2C_MASTER_I2C)) & I2C_SR2_BUSY) { // I2C device is busy if (I2C1!=i2c && I2C2!=i2c) {
return false; while (true);
}
if (I2C_SR2(I2C(I2C_MASTER_I2C)) & I2C_SR2_MSL) { // I2C device is already in master mode
return false;
} }
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
// send start condition if (I2C_MASTER_RC_NONE!=rc) {
if (!i2c_master_start()) { return rc;
}
rc = i2c_master_select_slave(i2c, slave, address_10bit, false); // select slave to read
if (I2C_MASTER_RC_NONE!=rc) {
goto error; goto error;
} }
// select slave to write if (NULL!=data && data_size>0) { // only read data if needed
if (!i2c_master_select_slave(slave, true)) { rc = i2c_master_read(i2c, data, data_size);
goto error; if (I2C_MASTER_RC_NONE!=rc) {
}
// read data
if (NULL!=data && data_size>0) {
// read data
if (!i2c_master_read(data, data_size)) {
goto error; goto error;
} }
} }
success = true; rc = I2C_MASTER_RC_NONE; // all went well
error: error:
i2c_master_stop(); // sent stop condition i2c_master_stop(i2c); // sent stop condition
return success; 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 // check I2C peripheral
if (I2C_SR2(I2C(I2C_MASTER_I2C)) & I2C_SR2_BUSY) { // I2C device is busy if (I2C1!=i2c && I2C2!=i2c) {
return false; while (true);
}
if (I2C_SR2(I2C(I2C_MASTER_I2C)) & I2C_SR2_MSL) { // I2C device is already in master mode
return false;
} }
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
// send start condition if (I2C_MASTER_RC_NONE!=rc) {
if (!i2c_master_start()) { return rc;
}
rc = i2c_master_select_slave(i2c, slave, address_10bit, true); // select slave to write
if (I2C_MASTER_RC_NONE!=rc) {
goto error; goto error;
} }
// select slave to write if (NULL!=data && data_size>0) { // write data only is some is available
if (!i2c_master_select_slave(slave, true)) { rc = i2c_master_write(i2c, data, data_size); // write data
goto error; if (I2C_MASTER_RC_NONE!=rc) {
}
// write data
if (NULL!=data && data_size>0) {
if (!i2c_master_write(data, data_size)) {
goto error; goto error;
} }
} }
success = true; rc = I2C_MASTER_RC_NONE; // all went well
error: error:
i2c_master_stop(); // sent stop condition i2c_master_stop(i2c); // sent stop condition
return success; 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 // check I2C peripheral
if (I2C_SR2(I2C(I2C_MASTER_I2C)) & I2C_SR2_BUSY) { // I2C device is busy if (I2C1!=i2c && I2C2!=i2c) {
return false; while (true);
}
if (I2C_SR2(I2C(I2C_MASTER_I2C)) & I2C_SR2_MSL) { // I2C device is already in master mode
return false;
} }
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 // write address
if (NULL!=address && address_size>0) { if (NULL!=address && address_size>0) {
// send start condition rc = i2c_master_write(i2c, address, address_size); // send memory address
if (!i2c_master_start()) { if (I2C_MASTER_RC_NONE!=rc) {
goto error;
}
// select slave to write
if (!i2c_master_select_slave(slave, true)) {
goto error;
}
// send address
if (!i2c_master_write(address, address_size)) {
goto error; goto error;
} }
} }
// read data // read data
if (NULL!=data && data_size>0) { if (NULL!=data && data_size>0) {
// send re-start condition rc = i2c_master_start(i2c); // send re-start condition
if (!i2c_master_start()) { 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; goto error;
} }
// select slave to read rc = i2c_master_read(i2c, data, data_size); // read memory
if (!i2c_master_select_slave(slave, false)) { if (I2C_MASTER_RC_NONE!=rc) {
goto error;
}
// read data
if (!i2c_master_read(data, data_size)) {
goto error; goto error;
} }
} }
success = true; rc = I2C_MASTER_RC_NONE; // all went well
error: error:
i2c_master_stop(); // sent stop condition i2c_master_stop(i2c); // sent stop condition
return success; 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 // check I2C peripheral
if (I2C_SR2(I2C(I2C_MASTER_I2C)) & I2C_SR2_BUSY) { // I2C device is busy if (I2C1!=i2c && I2C2!=i2c) {
return false; while (true);
}
if (I2C_SR2(I2C(I2C_MASTER_I2C)) & I2C_SR2_MSL) { // I2C device is already in master mode
return false;
} }
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 // write address
if (NULL!=address && address_size>0) { if (NULL!=address && address_size>0) {
// send address rc = i2c_master_write(i2c, address, address_size); // send memory address
if (!i2c_master_write(address, address_size)) { if (I2C_MASTER_RC_NONE!=rc) {
goto error; goto error;
} }
} }
// write data // read data
if (NULL!=data && data_size>0) { 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; goto error;
} }
} }
success = true; rc = I2C_MASTER_RC_NONE; // all went well
error: error:
i2c_master_stop(); // sent stop condition i2c_master_stop(i2c); // sent stop condition
return success; return rc;
} }

View File

@ -16,69 +16,117 @@
* @file i2c_master.h * @file i2c_master.h
* @author King Kévin <kingkevin@cuvoodoo.info> * @author King Kévin <kingkevin@cuvoodoo.info>
* @date 2017-2018 * @date 2017-2018
* @note peripherals used: I2C @ref i2c_master_i2c, timer @ref i2c_master_timer * @note peripherals used: I2C
* @warning only 7-byte I2C slave addresses are supported
*/ */
#pragma once #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 /** 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 /** 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); enum i2c_master_rc i2c_master_start(uint32_t i2c);
/** select slave device /** select I2C slave device
* @warning a start condition should be sent before this operation * @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 * @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); enum i2c_master_rc i2c_master_select_slave(uint32_t i2c, uint16_t slave, bool address_10bit, bool write);
/** read data /** read data over I2C
* @warning the slave device must be selected before this operation * @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[out] data array to store bytes read
* @param[in] data_size number of bytes to 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); enum i2c_master_rc i2c_master_read(uint32_t i2c, uint8_t* data, size_t data_size);
/** write data /** write data over I2C
* @warning the slave device must be selected before this operation * @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 array of byte to write to slave
* @param[in] data_size number of bytes to write * @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); enum i2c_master_rc i2c_master_write(uint32_t i2c, const uint8_t* data, size_t data_size);
/** sent stop condition */ /** sent stop condition
void i2c_master_stop(void); * @param[in] i2c I2C base address
/** read from date from an I2C slave * @return I2C return code
* @param[in] slave 7-bit I2C salve device address to read from */
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[out] data array to store bytes read
* @param[in] data_size number of bytes to 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); 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 an I2C slave /** write data to slave device
* @param[in] slave 7-bit I2C salve device address to write to * @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 array of byte to write to slave
* @param[in] data_size number of bytes to write * @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 /** 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 memory address of slave to read from
* @param[in] address_size address size in bytes * @param[in] address_size address size in bytes
* @param[out] data array to store bytes read * @param[out] data array to store bytes read
* @param[in] data_size number of bytes to 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 /** 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 memory address of slave to write to
* @param[in] address_size address size in bytes * @param[in] address_size address size in bytes
* @param[in] data array of byte to write to slave * @param[in] data array of byte to write to slave
* @param[in] data_size number of bytes to write * @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);

View File

@ -13,7 +13,7 @@
* *
*/ */
/** definitions to build menus (code) /** definitions to build menus (code)
* @file menu.h * @file menu.c
* @author King Kévin <kingkevin@cuvoodoo.info> * @author King Kévin <kingkevin@cuvoodoo.info>
* @date 2018 * @date 2018
*/ */
@ -39,7 +39,7 @@ bool menu_handle_command(const char* line, const struct menu_command_t* command_
} }
// get 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 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 const char* delimiter = " "; // words are separated by spaces
char* word = strtok(dup, delimiter); // get first word 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 if (MENU_ARGUMENT_NONE==command.argument) { // check if argument can be passed
(*command.command_handler)(NULL); // call without argument (*command.command_handler)(NULL); // call without argument
} else { // argument can be passed } 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 word = strtok(NULL, delimiter); // get next word
if (!word) { // no argument provided if (!word) { // no argument provided
(*command.command_handler)(NULL); // call without argument (*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 double argument = atof(word); // get floating point number
(*command.command_handler)(&argument); // call with argument (*command.command_handler)(&argument); // call with argument
} else if (MENU_ARGUMENT_STRING==command.argument) { // next argument should be a string } 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)
} }
} }
} }

View File

@ -40,13 +40,13 @@ struct menu_command_t {
/** parse command from line and call corresponding command /** parse command from line and call corresponding command
* @param[in] line use input to parse * @param[in] line use input to parse
* @param[in] command_list list of available commands * @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 * @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); 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 /** print the commands from the command list
* @param[in] command_list list of available commands * @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); void menu_print_commands(const struct menu_command_t* command_list, size_t command_list_length);

View File

@ -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,out] size size of string
* @param[in] f floating number to be printed * @param[in] f floating number to be printed
* @param[in] padding number of 0's to pad * @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 * @param[in] sign if sign should be printed
* @return number of characters 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 // check padding
if ('0'==*format) { // padding required if ('0'==*format) { // padding required
padding = 0; // reset padding
format++; // go to padding number format++; // go to padding number
while (*format>='0' && *format<='9') { while (*format>='0' && *format<='9') {
if (padding>UINT32_MAX/10) { // check for overflow 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 // check fractional
if ('.'==*format) { // fractional required if ('.'==*format) { // fractional required
fractional = 0; // reset fractional
format++; // go to fractional number format++; // go to fractional number
while (*format>='0' && *format<='9') { while (*format>='0' && *format<='9') {
if (fractional>UINT32_MAX/10) { // check for overflow if (fractional>UINT32_MAX/10) { // check for overflow

View File

@ -25,7 +25,9 @@ extern char* terminal_prefix;
/** initialize terminal prompt */ /** initialize terminal prompt */
void terminal_setup(void); void terminal_setup(void);
/** send character to terminal */ /** send character to terminal
* @param[in] c character to send
*/
void terminal_send(char c); void terminal_send(char c);
/** called when a line is entered /** called when a line is entered

View File

@ -50,12 +50,12 @@ static volatile uint8_t tx_used = 0; /**< how much data needs to be transmitted
void uart_setup(void) void uart_setup(void)
{ {
/* enable UART I/O peripheral */ /* enable UART I/O peripheral */
rcc_periph_clock_enable(USART_PORT_RCC(UART_ID)); // enable clock for UART port peripheral rcc_periph_clock_enable(RCC_USART_PORT(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(UART_ID)); // enable clock for UART peripheral
rcc_periph_clock_enable(RCC_AFIO); // enable pin alternate function (UART) 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_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_PORT(UART_ID), GPIO_MODE_INPUT, GPIO_CNF_INPUT_PULL_UPDOWN, USART_PIN_RX(UART_ID)); // setup GPIO pin UART receive 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_PORT(UART_ID), USART_PIN_RX(UART_ID)); // pull up to avoid noise when not connected gpio_set(USART_RX_PORT(UART_ID), USART_RX_PIN(UART_ID)); // pull up to avoid noise when not connected
/* setup UART parameters */ /* setup UART parameters */
usart_set_baudrate(USART(UART_ID), UART_BAUDRATE); usart_set_baudrate(USART(UART_ID), UART_BAUDRATE);

View File

@ -15,30 +15,42 @@
/** library for USB CDC ACM communication (code) /** library for USB CDC ACM communication (code)
* @file usb_cdcacm.c * @file usb_cdcacm.c
* @author King Kévin <kingkevin@cuvoodoo.info> * @author King Kévin <kingkevin@cuvoodoo.info>
* @date 2016-2017 * @date 2016-2018
*/ */
/* standard libraries */ /* standard libraries */
#include <stdint.h> // standard integer types #include <stdint.h> // standard integer types
#include <stdio.h> // standard I/O facilities
#include <stdlib.h> // general utilities #include <stdlib.h> // general utilities
/* STM32 (including CM3) libraries */ /* STM32 (including CM3) libraries */
#include <libopencmsis/core_cm3.h> // Cortex M3 utilities
#include <libopencm3/cm3/scb.h> // reset utilities
#include <libopencm3/cm3/nvic.h> // interrupt handler
#include <libopencm3/stm32/rcc.h> // real-time control clock library #include <libopencm3/stm32/rcc.h> // real-time control clock library
#include <libopencm3/stm32/gpio.h> // general purpose input output library #include <libopencm3/stm32/gpio.h> // general purpose input output library
#include <libopencm3/cm3/nvic.h> // interrupt handler
#include <libopencm3/cm3/scb.h> // reset utilities
#include <libopencmsis/core_cm3.h> // Cortex M3 utilities
#include <libopencm3/usb/usbd.h> // USB library #include <libopencm3/usb/usbd.h> // USB library
#include <libopencm3/usb/cdc.h> // USB CDC library #include <libopencm3/usb/cdc.h> // USB CDC library
#include <libopencm3/cm3/sync.h> // synchronisation utilities
#include <libopencm3/usb/dfu.h> // DFU definitions #include <libopencm3/usb/dfu.h> // DFU definitions
/* own libraries */
#include "global.h" // global utilities #include "global.h" // global utilities
#include "usb_cdcacm.h" // USB CDC ACM header and definitions #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 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 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 /** USB CDC ACM device descriptor
* @note as defined in USB CDC specification section 5 * @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 */ .bDeviceSubClass = 0, /**< unused */
.bDeviceProtocol = 0, /**< unused */ .bDeviceProtocol = 0, /**< unused */
.bMaxPacketSize0 = 64, /**< packet size for endpoint zero in bytes */ .bMaxPacketSize0 = 64, /**< packet size for endpoint zero in bytes */
.idVendor = 0xc440, /**< Vendor ID (CuVo...) */ .idVendor = 0x1209, /**< pid.codes vendor ID */
.idProduct = 0x0d00, /**< product ID within the Vendor ID space (...odoo) */ .idProduct = 0x4256, /**< BusVoodo product ID within the Vendor ID space */
.bcdDevice = 0x0100, /**< version number for the device */ .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 */ .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 */ .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 */ .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 */ .bDescriptorType = USB_DT_ENDPOINT, /**< a value of 5 indicates that this describes an endpoint */
.bEndpointAddress = 0x02, /**< OUT (from host) direction (0<<7), endpoint 2 */ .bEndpointAddress = 0x02, /**< OUT (from host) direction (0<<7), endpoint 2 */
.bmAttributes = USB_ENDPOINT_ATTR_BULK, /**< bulk mode */ .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 */ .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 */ .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 */ .bDescriptorType = USB_DT_ENDPOINT, /**< a value of 5 indicates that this describes an endpoint */
.bEndpointAddress = 0x82, /**< IN (to host) direction (1<<7), endpoint 2 */ .bEndpointAddress = 0x82, /**< IN (to host) direction (1<<7), endpoint 2 */
.bmAttributes = USB_ENDPOINT_ATTR_BULK, /**< bulk mode */ .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 */ .bInterval = 1, /**< the frequency, in number of frames, that we're going to be sending data */
}}; }};
/** USB CDC ACM communication endpoints /** 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[] = {{ static const struct usb_endpoint_descriptor usb_cdcacm_communication_endpoints[] = {{
.bLength = USB_DT_ENDPOINT_SIZE, /**< the size of the endpoint descriptor in bytes */ .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 /** USB CDC ACM functional descriptor
* @return
* @note as defined in USB CDC specification section 5.2.3 * @note as defined in USB CDC specification section 5.2.3
* @return packed structure
*/ */
static const struct { static const struct {
struct usb_cdc_header_descriptor header; /**< header */ 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 * @note as defined in USB CDC specification section 5.1.3
*/ */
static const struct usb_interface_descriptor usb_cdcacm_data_interface = { static const struct usb_interface_descriptor usb_cdcacm_data_interface = {
.bLength = USB_DT_INTERFACE_SIZE, .bLength = USB_DT_INTERFACE_SIZE, /**< size of descriptor in byte */
.bDescriptorType = USB_DT_INTERFACE, .bDescriptorType = USB_DT_INTERFACE, /**< interface descriptor type */
.bInterfaceNumber = 1, .bInterfaceNumber = 1, /**< interface number in the list */
.bAlternateSetting = 0, .bAlternateSetting = 0, /**< no alternative settings */
.bNumEndpoints = 2, .bNumEndpoints = 2, /**< only the control pipe at endpoint 0 is used */
.bInterfaceClass = USB_CLASS_DATA, .bInterfaceClass = USB_CLASS_DATA, /**< USB CDC interface class */
.bInterfaceSubClass = 0, .bInterfaceSubClass = 0, /**< USB CDC ACM interface subclass */
.bInterfaceProtocol = 0, .bInterfaceProtocol = 0, /**< USB CDC ACM none protocol */
.iInterface = 0, .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 /** 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) */ .bInterfaceClass = 0xFE, /**< DFU interface class (not defined in libopencm3 dfu lib) */
.bInterfaceSubClass = 1, /**< DFU interface subclass (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) */ .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 */ .extra = &usb_dfu_functional, /**< point to functional descriptor */
.extralen = sizeof(usb_dfu_functional), /**< size of 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 */ .bConfigurationValue = 1, /**< the index of this configuration */
.iConfiguration = 0, /**< a string index describing this configuration (zero means not provided) */ .iConfiguration = 0, /**< a string index describing this configuration (zero means not provided) */
.bmAttributes = 0x80, /**< bus powered (1<<7) */ .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 // end of header
.interface = usb_cdcacm_interfaces, /**< pointer to an array of interfaces */ .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 * @note starting with index 1
*/ */
static const char *usb_strings[] = { static const char *usb_strings[] = {
"CuVoodoo", "CuVoodoo", /**< manufacturer string */
"STM32F1", "BusVoodoo multi-protocol debugging adapter", /**< product string */
"CDC-ACM", "DFU bootloader (runtime mode)", /**< DFU interface string */
"CuVoodoo DFU bootloader (runtime mode)",
}; };
/* 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 */ /** disconnect USB by pulling down D+ to for re-enumerate */
static void usb_disconnect(void) static void usb_disconnect(void)
{ {
@ -246,17 +251,16 @@ static void usb_disconnect(void)
rcc_periph_clock_enable(RCC_GPIOB); rcc_periph_clock_enable(RCC_GPIOB);
gpio_set_mode(GPIOB, GPIO_MODE_OUTPUT_2_MHZ, GPIO_CNF_OUTPUT_PUSHPULL, GPIO9); gpio_set_mode(GPIOB, GPIO_MODE_OUTPUT_2_MHZ, GPIO_CNF_OUTPUT_PUSHPULL, GPIO9);
gpio_set(GPIOB, GPIO9); gpio_set(GPIOB, GPIO9);
for (uint32_t i = 0; i < 0x2000; i++) { for (uint32_t i = 0; i < 0x2000; i++) { // wait for at least 10 ms
__asm__("nop"); __asm__("nop");
} }
gpio_clear(GPIOB, GPIO9);
#else #else
// pull USB D+ low for a short while // pull USB D+ low for a short while
rcc_periph_clock_enable(RCC_GPIOA); rcc_periph_clock_enable(RCC_GPIOA);
gpio_set_mode(GPIOA, GPIO_MODE_OUTPUT_2_MHZ, GPIO_CNF_OUTPUT_PUSHPULL, GPIO12); gpio_set_mode(GPIOA, GPIO_MODE_OUTPUT_2_MHZ, GPIO_CNF_OUTPUT_PUSHPULL, GPIO12);
gpio_clear(GPIOA, GPIO12); gpio_clear(GPIOA, GPIO12);
for (uint32_t i = 0; i < 0x2000; i++) { for (uint32_t i = 0; i < 0x2000; i++) { // wait for at least 10 ms
__asm__("nop"); __asm__("nop");
} }
#endif #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)usbd_dev; // variable not used
(void)req; // variable not used (void)req; // variable not used
usb_disconnect(); // USB detach (disconnect to force re-enumeration) usb_disconnect(); // USB detach (disconnect to force re-enumeration)
scb_reset_system(); // reset device scb_reset_system(); // reset device
while (true); // wait for the reset to happen 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)) 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 if (usb_dfu_interface.bInterfaceNumber==req->wIndex) { // check if request is for DFU
switch (req->bRequest) { switch (req->bRequest) {
case DFU_DETACH: // USB detach requested 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 default: // other requests are not supported
return 0; return 0;
} }
} else { } else if (usb_cdcacm_communication_interface.bInterfaceNumber==req->wIndex) { // check if request is for CDC
switch (req->bRequest) { switch (req->bRequest) {
case USB_CDC_REQ_SET_CONTROL_LINE_STATE: 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 dtr = (req->wValue & (1 << 0)) ? true : false;
//bool rts = (req->wValue & (1 << 1)) ? 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 * even though it's optional in the CDC spec, and we don't
* advertise it in the ACM functional descriptor. * 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; notif->wLength = 2;
reply[8] = req->wValue & 3; reply[8] = req->wValue & 3;
reply[9] = 0; 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; break;
case USB_CDC_REQ_SET_LINE_CODING: case USB_CDC_REQ_SET_LINE_CODING:
// ignore if length is wrong // 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; 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 /** USB CDC ACM data received callback
* @note called when data has been received
* @param[in] usbd_dev USB device descriptor * @param[in] usbd_dev USB device descriptor
* @param[in] ep endpoint where data came in * @param[in] ep endpoint where data came in
*/ */
static void usb_cdcacm_data_rx_cb(usbd_device *usbd_dev, uint8_t ep) 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 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)); usb_length = usbd_ep_read_packet(usbd_dev, 0x02, usb_data, sizeof(usb_data));
if (usb_length) { // copy received data if (usb_length) { // copy received data
for (uint16_t i=0; i<usb_length; i++) { // only until buffer is full for (uint16_t i=0; i<usb_length && i<LENGTH(usb_data); i++) { // only until buffer is full
user_input_store(usb_data[i]); // store user data user_input_store(usb_data[i]); // store user data
} }
} }
} }
/** USB CDC ACM data transmitted callback /** USB CDC ACM data transmitted callback
* @note called once transmission is completed
* @param[in] usbd_dev USB device descriptor * @param[in] usbd_dev USB device descriptor
* @param[in] ep endpoint where data came in * @param[in] ep endpoint where data came in
*/ */
static void usb_cdcacm_data_tx_cb(usbd_device *usbd_dev, uint8_t ep) static void usb_cdcacm_data_tx_cb(usbd_device *usbd_dev, uint8_t ep)
{ {
(void)ep; (void)ep; // not used
(void)usbd_dev;
if (!usbd_dev || !connected || !tx_used) { // verify if we can send and there is something to send if (!usbd_dev || 0==tx_used || !first_connection) { // verify if we can send and there is something to send
usb_tx_ongoing = false; // transmission ended
return; return;
} }
if (mutex_trylock(&tx_lock)) { // try to get lock if (!tx_lock) {
uint8_t usb_length = (tx_used > 64 ? 64 : tx_used); // length of data to be transmitted (respect max packet size) 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 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 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_i = (tx_i+usb_length)%LENGTH(tx_buffer); // update location on buffer
tx_used -= usb_length; // update used size tx_used -= usb_length; // update used size
mutex_unlock(&tx_lock); // release lock
} else { } else {
usbd_ep_write_packet(usb_device, 0x82, NULL, 0); // trigger empty tx for a later callback 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) 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, 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, 0x02, USB_ENDPOINT_ATTR_BULK, 64, usb_cdcacm_data_rx_cb); 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, 0x82, USB_ENDPOINT_ATTR_BULK, 64, usb_cdcacm_data_tx_cb); 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) void usb_cdcacm_setup(void)
{ {
connected = false; // start with USB not connected
// initialize USB // initialize USB
rcc_periph_reset_pulse(RST_USB); // reset USB peripheral rcc_periph_reset_pulse(RST_USB); // reset USB peripheral
usb_disconnect(); // disconnect to force re-enumeration usb_disconnect(); // disconnect to force re-enumeration
@ -439,15 +455,18 @@ void usb_cdcacm_setup(void)
// reset buffer states // reset buffer states
tx_i = 0; tx_i = 0;
tx_used = 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) void usb_cdcacm_putchar(char c)
{ {
if (!usb_device || !connected) { if (!usb_device) {
return; return;
} }
mutex_lock(&tx_lock); // get lock to prevent race condition tx_lock = true; // put lock on transmit buffer
if (tx_used<LENGTH(tx_buffer)) { // buffer not full if (tx_used<LENGTH(tx_buffer)) { // buffer not full
tx_buffer[(tx_i+tx_used)%LENGTH(tx_buffer)] = c; // put character in buffer tx_buffer[(tx_i+tx_used)%LENGTH(tx_buffer)] = c; // put character in buffer
tx_used++; // update used buffer tx_used++; // update used buffer
@ -455,8 +474,8 @@ void usb_cdcacm_putchar(char c)
tx_i = (tx_i+1)%LENGTH(tx_buffer); // shift start tx_i = (tx_i+1)%LENGTH(tx_buffer); // shift start
tx_buffer[(tx_i+tx_used)%LENGTH(tx_buffer)] = c; // overwrite old data tx_buffer[(tx_i+tx_used)%LENGTH(tx_buffer)] = c; // overwrite old data
} }
mutex_unlock(&tx_lock); // release lock tx_lock = false; // release lock on transmit buffer
if (tx_used==1) { // to buffer is not empty anymore if (tx_used>0 && usb_device && !usb_tx_ongoing) { // if buffer is not empty anymore
usbd_ep_write_packet(usb_device, 0x82, NULL, 0); // trigger tx callback usbd_ep_write_packet(usb_device, 0x82, NULL, 0); // trigger tx callback
} }
} }

View File

@ -19,6 +19,9 @@
*/ */
#pragma once #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 */ /** setup USB CDC ACM peripheral */
void usb_cdcacm_setup(void); void usb_cdcacm_setup(void);
/** send character over USB (non-blocking) /** send character over USB (non-blocking)

View File

@ -55,12 +55,12 @@ static const struct usb_device_descriptor usb_dfu_device = {
.bDeviceSubClass = 0, /**< unused */ .bDeviceSubClass = 0, /**< unused */
.bDeviceProtocol = 0, /**< unused */ .bDeviceProtocol = 0, /**< unused */
.bMaxPacketSize0 = 64, /**< packet size for endpoint zero in bytes */ .bMaxPacketSize0 = 64, /**< packet size for endpoint zero in bytes */
.idVendor = 0xc440, /**< Vendor ID (CuVo...) */ .idVendor = 0x1209, /**< pid.codes vendor ID */
.idProduct = 0x0d00, /**< product ID within the Vendor ID space (...odoo) */ .idProduct = 0x4256, /**< BusVoodo product ID within the Vendor ID space */
.bcdDevice = 0x0100, /**< version number for the device */ .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 */ .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 */ .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 */ .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) */ .bInterfaceClass = 0xFE, /**< DFU interface class (not defined in libopencm3 dfu lib) */
.bInterfaceSubClass = 1, /**< DFU interface subclass (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) */ .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 */ .extra = &usb_dfu_functional, /**< point to functional descriptor */
.extralen = sizeof(usb_dfu_functional), /**< size of 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 * @note starts with index 1
*/ */
static const char *usb_dfu_strings[] = { static const char *usb_dfu_strings[] = {
"CuVoodoo", "CuVoodoo", /**< manufacturer string */
"STM32F1", "BusVoodoo multi-protocol debugging adapter ", /**< product string */
"DFU", "DFU bootloader (DFU mode)", /**< DFU interface string */
"CuVoodoo DFU bootloader (DFU mode)",
}; };
/** disconnect USB to force re-enumerate */ /** disconnect USB to force re-enumerate */