stm32f1/application.c

1653 lines
74 KiB
C

/** input/output pin identifier
* @file
* @author King Kévin <kingkevin@cuvoodoo.info>
* @copyright SPDX-License-Identifier: GPL-3.0-or-later
* @date 2016-2021
*/
/* standard libraries */
#include <stdint.h> // standard integer types
#include <stdlib.h> // standard utilities
#include <string.h> // string utilities
#include <time.h> // date/time utilities
#include <ctype.h> // utilities to check chars
#include <math.h> // rounding utilities
/* STM32 (including CM3) libraries */
#include <libopencmsis/core_cm3.h> // Cortex M3 utilities
#include <libopencm3/cm3/scb.h> // vector table definition
#include <libopencm3/cm3/nvic.h> // interrupt utilities
#include <libopencm3/stm32/gpio.h> // general purpose input output library
#include <libopencm3/stm32/rcc.h> // real-time control clock library
#include <libopencm3/stm32/exti.h> // external interrupt utilities
#include <libopencm3/stm32/rtc.h> // real time clock utilities
#include <libopencm3/stm32/iwdg.h> // independent watchdog utilities
#include <libopencm3/stm32/dbgmcu.h> // debug utilities
#include <libopencm3/stm32/desig.h> // design utilities
#include <libopencm3/stm32/flash.h> // flash utilities
#include <libopencm3/stm32/adc.h> // ADC utilities
#include <libopencm3/stm32/timer.h> // timer library
#include <libopencm3/stm32/usart.h> // universal synchronous asynchronous receiver transmitter library
/* own libraries */
#include "global.h" // board definitions
#include "print.h" // printing utilities
#include "uart.h" // USART utilities
#include "usb_cdcacm.h" // USB CDC ACM utilities
#include "terminal.h" // handle the terminal interface
#include "menu.h" // menu utilities
#include "usart_enhanced.h" // USART utilities got frame checking
/** watchdog period in ms */
#define WATCHDOG_PERIOD 10000
/** wakeup frequency (i.e. least number of times per second to perform the main loop) */
#define WAKEUP_FREQ 16
/** @defgroup main_flags flag set in interrupts to be processed in main task
* @{
*/
static volatile bool wakeup_flag = false; /**< flag set when wakeup timer triggered */
static volatile bool second_flag = false; /**< flag set when a second passed */
/** @} */
/** number of seconds since boot */
static uint32_t boot_time = 0;
#define TARGET_CHANNEL 6 /**< PA6/ADC1_IN6 used to measure target voltage */
#define SIGNAL_CHANNEL 1 /**< PA1/ADC1_IN1 used to measure signal voltage */
const uint8_t adc_channels[] = {ADC_CHANNEL17, ADC_CHANNEL(TARGET_CHANNEL), ADC_CHANNEL(SIGNAL_CHANNEL)}; /**< voltages to convert (channel 17 = internal voltage reference) */
#define TARGET_3V_PIN PC13 /**< pin to supply target voltage with 3.3V (controlling gate of pMOS) */
#define TARGET_RST_PIN PA0 /**< pin to reset target board */
#define SIGNAL_PD_PIN PA4 /**< pin to pull signal low for voltage measurement */
#define SIGNAL_PU_PIN PA5 /**< pin to pull signal to target voltage (controlling gate of pMOS) */
#define SHIFT_EN_PIN PC14 /**< pin to provide target voltage to LV side of voltage shifter (pulling them high through 10 kO) */
#define MUX_EN_PIN PC15 /**< pin to enable analog multiplexer (active low) */
#define MUX_S0_PIN PA7 /**< pin to set S0 bit of analog multiplexer */
#define MUX_S1_PIN PB0 /**< pin to set S1 bit of analog multiplexer */
#define MUX_S2_PIN PB1 /**< pin to set S2 bit of analog multiplexer */
#define MUX_S3_PIN PB2 /**< pin to set S3 bit of analog multiplexer */
#define CHANNEL_NUMBERS 16 /**< number of target signals */
static const uint32_t channel_ports[] = {GPIO_PORT(PB10), GPIO_PORT(PB9), GPIO_PORT(PB8), GPIO_PORT(PB7), GPIO_PORT(PB6), GPIO_PORT(PB5), GPIO_PORT(PB4), GPIO_PORT(PB3), GPIO_PORT(PA15), GPIO_PORT(PA10), GPIO_PORT(PA9), GPIO_PORT(PA8), GPIO_PORT(PB15), GPIO_PORT(PB14), GPIO_PORT(PB13), GPIO_PORT(PB12)}; /**< GPIO ports for signal pin */
static const uint32_t channel_pins[] = {GPIO_PIN(PB10), GPIO_PIN(PB9), GPIO_PIN(PB8), GPIO_PIN(PB7), GPIO_PIN(PB6), GPIO_PIN(PB5), GPIO_PIN(PB4), GPIO_PIN(PB3), GPIO_PIN(PA15), GPIO_PIN(PA10), GPIO_PIN(PA9), GPIO_PIN(PA8), GPIO_PIN(PB15), GPIO_PIN(PB14), GPIO_PIN(PB13), GPIO_PIN(PB12)}; /**< GPIO pins for signal pin */
static uint8_t channel_start = 0; /**< first signal of range to probe */
static uint8_t channel_stop = CHANNEL_NUMBERS - 1; /**< last signal of range to probe */
/** timer ID for timer to measure activity timing */
#define MONITOR_TIMER 3
/** timer to measure frequency and baud rate
* @note PA3/USART2_RX/TIM2_CH4 (PA2/USART2_TX/TIM2_CH3 could also be used)
* @{
*/
#define FREQUENCY_TIMER 2 /**< timer peripheral ID */
#define FREQUENCY_CHANNEL 4 /**< timer channel to capture edges */
#define FREQUENCY_AF GPIO_AF1 /**< alternate function for UART pin to use as timer channel */
/** @} */
/** UART peripheral for signal reading (TX and RX are connected together)
* @{
*/
#define UART_ID 2 /**< USART peripheral */
#define UART_TX PA2 /**< pin used for USART TX */
#define UART_RX PA3 /**< pin used for USART RX */
#define UART_AF GPIO_AF7 /**< alternate function for UART pins */
/** @} */
size_t putc(char c)
{
size_t length = 0; // number of characters printed
static char last_c = 0; // to remember on which character we last sent
if ('\n' == c) { // send carriage return (CR) + line feed (LF) newline for each LF
if ('\r' != last_c) { // CR has not already been sent
usb_cdcacm_putchar('\r'); // send CR over USB
length++; // remember we printed 1 character
}
}
usb_cdcacm_putchar(c); // send byte over USB
length++; // remember we printed 1 character
last_c = c; // remember last character
return length; // return number of characters printed
}
// only print when debug is enabled
#if DEBUG
#define puts_debug(x) puts(x)
#else
#define puts_debug(x) {}
#endif
/** print float with fixed precision
* @param[in] fpu float to print
* @param[in] precision number of digits after comma to print
* @note %f is used to force scientific notation
*/
static void print_fpu(double fpu, uint8_t precision)
{
uint32_t multiplier = 1;
for (uint8_t i = 0; i < precision; i++) {
multiplier *= 10;
}
double to_print = round(fpu * multiplier);
printf("%d.", (int32_t)to_print / multiplier);
char decimal[32];
snprintf(decimal, LENGTH(decimal), "%u", abs(to_print) % multiplier);
if (strlen(decimal) > precision) {
decimal[precision] = 0;
}
for (uint8_t i = strlen(decimal); i < precision; i++) {
putc('0');
}
puts(decimal);
}
/** get RCC from corresponding port
* @param[in] port port address
* @return RCC address corresponding to port
*/
static uint32_t port2rcc(uint32_t port)
{
uint32_t rcc = 0;
switch (port) {
case GPIOA:
rcc = RCC_GPIOA;
break;
case GPIOB:
rcc = RCC_GPIOB;
break;
case GPIOC:
rcc = RCC_GPIOC;
break;
case GPIOD:
rcc = RCC_GPIOD;
break;
case GPIOE:
rcc = RCC_GPIOE;
break;
case GPIOF:
rcc = RCC_GPIOF;
break;
case GPIOG:
rcc = RCC_GPIOG;
break;
default: // unknown port
while (true); // halt firmware
break;
}
return rcc;
}
/** measure target and signal voltages
* @return voltages of adc_channels
*/
static float* measure_voltages(void)
{
static float voltages[LENGTH(adc_channels)]; // to store and return the voltages
// read lid temperature using ADC
ADC_SR(ADC1) = 0; // reset flags
uint16_t adc_values[LENGTH(adc_channels)];
for (uint8_t i = 0; i < LENGTH(adc_channels); i++) {
adc_start_conversion_regular(ADC1); // start conversion (using trigger)
while (!adc_eoc(ADC1)); // wait until conversion finished
adc_values[i] = adc_read_regular(ADC1); // read voltage value (clears flag)
voltages[i] = adc_values[i] * 1.21 / adc_values[0]; // use 1.21 V internal voltage reference to get ADC voltage
}
voltages[1] *= 2.0; // the is a /2 voltage divider for target voltage
return voltages;
}
/** select channel of multiplexer
* @param[in] channel channel to select, or -1 to disable multiplexer
*/
static void mux_select(int8_t channel)
{
gpio_set(GPIO_PORT(MUX_EN_PIN), GPIO_PIN(MUX_EN_PIN)); // disable multiplexer while we are switching
if (channel < 0 || channel > 15 || (channel > CHANNEL_NUMBERS - 1)) {
return; // no channel to select
}
// select channel using bit pattern
if (channel & 0x1) {
gpio_set(GPIO_PORT(MUX_S0_PIN), GPIO_PIN(MUX_S0_PIN));
} else {
gpio_clear(GPIO_PORT(MUX_S0_PIN), GPIO_PIN(MUX_S0_PIN));
}
if (channel & 0x2) {
gpio_set(GPIO_PORT(MUX_S1_PIN), GPIO_PIN(MUX_S1_PIN));
} else {
gpio_clear(GPIO_PORT(MUX_S1_PIN), GPIO_PIN(MUX_S1_PIN));
}
if (channel & 0x4) {
gpio_set(GPIO_PORT(MUX_S2_PIN), GPIO_PIN(MUX_S2_PIN));
} else {
gpio_clear(GPIO_PORT(MUX_S2_PIN), GPIO_PIN(MUX_S2_PIN));
}
if (channel & 0x8) {
gpio_set(GPIO_PORT(MUX_S3_PIN), GPIO_PIN(MUX_S3_PIN));
} else {
gpio_clear(GPIO_PORT(MUX_S3_PIN), GPIO_PIN(MUX_S3_PIN));
}
gpio_clear(GPIO_PORT(MUX_EN_PIN), GPIO_PIN(MUX_EN_PIN)); // enable multiplexer
}
// menu commands
/** measure and print target voltage
* @param[in] argument 0 to no provide power, 3 to provide 3.3V
*/
static void command_target_voltage(void* argument)
{
(void)argument; // we won't use the argument
// set voltage
if (argument) { // if argument is provided
const uint8_t voltage = *(uint32_t*)argument; // get target voltage
switch (voltage) {
case 0:
gpio_set(GPIO_PORT(TARGET_3V_PIN), GPIO_PIN(TARGET_3V_PIN)); // disable 3V output
break;
case 3:
gpio_clear(GPIO_PORT(TARGET_3V_PIN), GPIO_PIN(TARGET_3V_PIN)); // enable 3V output
break;
default:
puts("unknown voltage to set\n");
break;
}
sleep_us(100); // wait a bit for voltage to settle
}
// show voltage output
if (!gpio_get(GPIO_PORT(TARGET_3V_PIN), GPIO_PIN(TARGET_3V_PIN))) {
puts("target voltage set to 3.3 V\n");
} else {
puts("target voltage externally provided\n");
}
float* voltages = measure_voltages(); // measure voltages
puts("target voltage: ");
print_fpu(voltages[1], 2);
puts(" V");
if (voltages[1] < 1.0) {
puts(" (warning: target voltage seems not connected)");
}
putc('\n');
}
/** configure or reset target
* @param[in] argument 1 to assert reset, 0 to release reset, ODL to set reset pin to open-drain active low, ODH to set reset pin to open-drain active high, PPL to set reset pin to push-pull active low, PPH to set reset pin to push-pull active high
*/
static void command_target_reset(void* argument)
{
(void)argument; // we won't use the argument
static bool active_low = true; // if the reset is active low or high
// set reset mode
if (argument) { // if argument is provided
if (0 == strcmp("0", argument)) { // release reset
if (active_low) {
gpio_set(GPIO_PORT(TARGET_RST_PIN), GPIO_PIN(TARGET_RST_PIN));
} else {
gpio_clear(GPIO_PORT(TARGET_RST_PIN), GPIO_PIN(TARGET_RST_PIN));
}
} else if (0 == strcmp("1", argument)) { // assert reset
if (active_low) {
gpio_clear(GPIO_PORT(TARGET_RST_PIN), GPIO_PIN(TARGET_RST_PIN));
} else {
gpio_set(GPIO_PORT(TARGET_RST_PIN), GPIO_PIN(TARGET_RST_PIN));
}
} else if (0 == strcmp("ODL", argument)) { // set reset to open-drain active low
active_low = true; // remember we are active low
gpio_set_output_options(GPIO_PORT(TARGET_RST_PIN), GPIO_OTYPE_OD, GPIO_OSPEED_2MHZ, GPIO_PIN(TARGET_RST_PIN)); // set output as open-drain
} else if (0 == strcmp("ODH", argument)) { // set reset to open-drain active high
active_low = false; // remember we are active high
gpio_set_output_options(GPIO_PORT(TARGET_RST_PIN), GPIO_OTYPE_OD, GPIO_OSPEED_2MHZ, GPIO_PIN(TARGET_RST_PIN)); // set output as open-drain
} else if (0 == strcmp("PPL", argument)) { // set reset to push-pull active low
active_low = true; // remember we are active low
gpio_set_output_options(GPIO_PORT(TARGET_RST_PIN), GPIO_OTYPE_PP, GPIO_OSPEED_2MHZ, GPIO_PIN(TARGET_RST_PIN)); // set output as push-pull
} else if (0 == strcmp("PPH", argument)) { // set reset to push-pull active high
active_low = false; // remember we are active high
gpio_set_output_options(GPIO_PORT(TARGET_RST_PIN), GPIO_OTYPE_PP, GPIO_OSPEED_2MHZ, GPIO_PIN(TARGET_RST_PIN)); // set output as push-pull
} else {
printf("unknown argument: %s\n", argument);
}
}
const bool open_drain = (GPIO_OTYPER(GPIO_PORT(TARGET_RST_PIN)) & GPIO_PIN(TARGET_RST_PIN)); // if the output is configured as open drain (else it's push-pull)
printf("reset pin set to %s active %s\n", open_drain ? "open-drain" : "push-pull (3.3V)", active_low ? "low" : "high");
if (gpio_get(GPIO_PORT(TARGET_RST_PIN), GPIO_PIN(TARGET_RST_PIN))) {
if (active_low) {
puts("reset released\n");
} else {
puts("reset asserted\n");
}
} else {
if (active_low) {
puts("reset asserted\n");
} else {
puts("reset released\n");
}
}
}
/** identify if signal is an input or output
* @param[in] argument no argument required
*/
static void command_types(void* argument)
{
(void)argument; // we won't use the argument
command_target_voltage(NULL); // print target voltage (also sets measurement conditions)
float* voltages = measure_voltages(); // measure voltages
if (voltages[1] < 0.5) { // check target voltage connection
puts("connect target voltage to test channel type\n");
return;
}
puts("measuring voltage on channels when pulled up and down using 2 kOhm resistor\n");
puts("channel no-pull pull-down pull-up type\n");
// just to be sure, reset measurement conditions
gpio_set(GPIO_PORT(SIGNAL_PD_PIN), GPIO_PIN(SIGNAL_PD_PIN)); // ensure pull-down is not active
gpio_set(GPIO_PORT(SIGNAL_PU_PIN), GPIO_PIN(SIGNAL_PU_PIN)); // ensure pull-up is not active
for (uint8_t i = channel_start; i <= channel_stop; i++) {
printf("CH%02u", i);
puts(" ");
mux_select(i); // select the channel
voltages = measure_voltages(); // measure raw voltages
print_fpu(voltages[2], 2);
const float raw = voltages[2]; // remember un-pulled voltage
puts(" ");
gpio_clear(GPIO_PORT(SIGNAL_PD_PIN), GPIO_PIN(SIGNAL_PD_PIN)); // pull down signal
sleep_us(10); // wait a tiny bit for voltage to settle
voltages = measure_voltages(); // measure pulled down voltages
gpio_set(GPIO_PORT(SIGNAL_PD_PIN), GPIO_PIN(SIGNAL_PD_PIN)); // remove pull-down
voltages[2] *= 2.0; // pulling creates a voltage divider (to ground)
const bool low = (voltages[2] < 0.5); // remember if we were able to pull it down
const float pullup = (2000.0 * (raw - voltages[2]) / voltages[2]) / 1000.0; // estimate external pull-up
print_fpu(voltages[2], 2);
puts(" ");
gpio_clear(GPIO_PORT(SIGNAL_PU_PIN), GPIO_PIN(SIGNAL_PU_PIN)); // pull up signal
sleep_us(10); // wait a tiny bit for voltage to settle
voltages = measure_voltages(); // measure pulled up voltages
gpio_set(GPIO_PORT(SIGNAL_PU_PIN), GPIO_PIN(SIGNAL_PU_PIN)); // remove pull-up
voltages[2] = voltages[2] * 2.0 - voltages[1]; // pulling creates a voltage divider (to target)
const bool high = (voltages[2] > 3.0 || voltages[2] > voltages[1] * 0.7); // remember if we were able to pull it up
const float pulldown = (2000.0 * voltages[2] / (voltages[1] - voltages[2])) / 1000.0; // estimate external pull-down
print_fpu(voltages[2], 2);
puts(" ");
if (pullup >= 0.9 && pullup < 100.0 && (pulldown <= 0.9 || pulldown > 100.0)) {
printf("pulled-up (%u kOhm)", (uint32_t)round(pullup));
} else if (pulldown >= 0.9 && pulldown < 100.0 && (pullup <= 0.9 || pullup > 100.0)) {
printf("pulled-down (%u kOhm)", (uint32_t)round(pulldown));
} else if (low && high) {
puts("floating");
} else if (low) {
puts("low");
} else if (high) {
puts("high");
} else {
puts("unknown");
}
putc('\n');
}
mux_select(-1); // disable multiplexer
}
/** monitor the channels for activity
* @param[in] argument 0 to pull low, 1 to pull high
*/
static void command_monitor(void* argument)
{
(void)argument; // we won't use the argument
// set input pull
if (NULL == argument) {
puts("channels are left floating\n");
for (uint8_t i = channel_start; i <= channel_stop; i++) {
gpio_mode_setup(channel_ports[i], GPIO_MODE_INPUT, GPIO_PUPD_NONE, channel_pins[i]); // set to floating
}
} else {
const uint32_t pull = *(uint32_t*)argument; // get pull argument
if (0 == pull) {
puts("channels are pulled low using internal 40 kOhm resistor\n");
for (uint8_t i = channel_start; i <= channel_stop; i++) {
gpio_mode_setup(channel_ports[i], GPIO_MODE_INPUT, GPIO_PUPD_PULLDOWN, channel_pins[i]); // set to pull down
}
} else if (3 == pull) {
puts("channels are pulled high to 3.3V using internal 40 kOhm resistor\n");
for (uint8_t i = channel_start; i <= channel_stop; i++) {
gpio_mode_setup(channel_ports[i], GPIO_MODE_INPUT, GPIO_PUPD_PULLUP, channel_pins[i]); // set to pull up
}
} else {
puts("unknown pull parameter. use 0 for low and 3 for 3.3V high\n");
return;
}
}
// collect pins we want to monitor
uint16_t gpioa_mask = 0; // which pins on GPIOA we want to monitor
uint16_t gpiob_mask = 0; // which pins on GPIOB we want to monitor
for (uint8_t i = channel_start; i <= channel_stop; i++) {
if (GPIOA == channel_ports[i]) {
gpioa_mask |= channel_pins[i];
} else if (GPIOB == channel_ports[i]) {
gpiob_mask |= channel_pins[i];
} else {
printf("unknown port for CH%02u\n", i);
}
}
// show help
puts("high = 2.3-5.5V, 'X' shows multiple changes\n");
puts("press any key to stop monitoring\n");
puts("time (s) ");
for (uint8_t i = channel_start; i <= channel_stop; i++) {
printf("%02u ", i);
}
puts("\n");
// setup timer to measure milliseconds
rcc_periph_clock_enable(RCC_TIM(MONITOR_TIMER)); // enable clock for timer peripheral
rcc_periph_reset_pulse(RST_TIM(MONITOR_TIMER)); // reset timer state
timer_disable_counter(TIM(MONITOR_TIMER)); // disable timer to configure it
timer_set_mode(TIM(MONITOR_TIMER), TIM_CR1_CKD_CK_INT, TIM_CR1_CMS_EDGE, TIM_CR1_DIR_UP); // set timer mode, use undivided timer clock, edge alignment (simple count), and count up
timer_set_prescaler(TIM(MONITOR_TIMER), (rcc_ahb_frequency / 2000) - 1); // generate half millisecond ticks (prescaler is not large enough for milliseconds)
timer_set_period(TIM(MONITOR_TIMER), 200 - 1); // set period to 0.1 seconds
timer_clear_flag(TIM(MONITOR_TIMER), TIM_SR_UIF); // clear update (overflow) flag
timer_update_on_overflow(TIM(MONITOR_TIMER)); // only use counter overflow as UEV source (use overflow as start time or timeout)
uint32_t seconds = 0; // count the 0.1 seconds using the overflow
timer_enable_counter(TIM(MONITOR_TIMER)); // enable timer
// start monitoring
uint16_t gpioa_old = UINT16_MAX; // the current level on the port where some channels are
uint16_t gpiob_old = UINT16_MAX; // since not all pins of the port care used for the channel, initializing to 0xffff will force an update to the actual data
bool channel_changed = false; // if a channel changed
uint8_t channels_changed[CHANNEL_NUMBERS] = {0}; // how many times a channel changed
bool channels_level[CHANNEL_NUMBERS]; // the level of the channels
for (uint8_t i = channel_start; i <= channel_stop; i++) { // initialize level of channels
const uint16_t port = (GPIOA == channel_ports[i] ? gpioa_old : gpiob_old); // get the port on which the channel is
channels_level[i] = (port & channel_pins[i]); // get the pin level on which the channel is
}
while (!user_input_available) { // run until user breaks it
// time to do periodic checks
if (wakeup_flag || second_flag) {
iwdg_reset(); // kick the dog
wakeup_flag = false; // clear flag
second_flag = false; // clear flag
}
if (timer_get_flag(TIM(MONITOR_TIMER), TIM_SR_UIF)) { // 0.1 second has passed
timer_clear_flag(TIM(MONITOR_TIMER), TIM_SR_UIF); // clear flag
seconds++; // count the 0.1 seconds
if (channel_changed) { // there was some activity
// we print the change every 0.1 s instead of synchronously to rate limit the print (and overfill the buffer)
printf("%04u.%01u ", seconds / 10, seconds % 10); // print current time stamp (change time stamp with 0.1s precision
for (uint8_t i = channel_start; i <= channel_stop; i++) { // print level of each change
putc(' '); // start new channel
if (channels_changed[i] > 1) { // channel changed more than once
putc('X'); // show multiple changes
} else {
putc(' '); // show no or single change
}
if (channels_level[i]) { // high level
putc('1');
} else {
putc('0');
}
channels_changed[i] = 0; // clear number of changes
}
puts("\n");
channel_changed = false; // clear flag
}
}
// check is there is a change on a channel
const uint16_t gpioa_new = gpio_get(GPIOA, gpioa_mask);
const uint16_t gpiob_new = gpio_get(GPIOB, gpioa_mask);
if (gpioa_new != gpioa_old || gpiob_new != gpiob_old) { // some GPIO changed (should be channel data)
for (uint8_t i = channel_start; i <= channel_stop; i++) { // check which channel changed
const uint16_t port = (GPIOA == channel_ports[i] ? gpioa_new : gpiob_new); // get the port on which the channel is
const bool pin = (port & channel_pins[i]); // get the pin level on which the channel is
if (pin != channels_level[i]) { // data on this channel changed
channel_changed = true; // remember one channel changed
channels_changed[i] = addu8_safe(channels_changed[i], 1); // remember how many times this channel changed
channels_level[i] = pin; // save new level
}
}
// save change
gpioa_old = gpioa_new;
gpiob_old = gpiob_new;
}
}
user_input_get(); // clean input
// clean up
for (uint8_t i = channel_start; i <= channel_stop; i++) { // set all back to input
gpio_mode_setup(channel_ports[i], GPIO_MODE_INPUT, GPIO_PUPD_NONE, channel_pins[i]); // ensure pin is floating input
}
timer_disable_counter(TIM(MONITOR_TIMER)); // disable timer
rcc_periph_reset_pulse(RST_TIM(MONITOR_TIMER)); // reset timer state
rcc_periph_clock_disable(RCC_TIM(MONITOR_TIMER)); // disable clock for timer peripheral
}
volatile bool pulse_flag = false; /**< set when a small pulse time is detected */
volatile uint32_t pulse_duration = UINT32_MAX; /**< smallest pulse duration measured */
/** timer ISR to measure edge timing */
void TIM_ISR(FREQUENCY_TIMER)(void)
{
static uint32_t pulse = UINT32_MAX; // measured pulse duration (MAX is an invalid value)
if (timer_get_flag(TIM(FREQUENCY_TIMER), TIM_SR_UIF)) { // overflow update event happened
timer_clear_flag(TIM(FREQUENCY_TIMER), TIM_SR_UIF); // clear flag
pulse = UINT32_MAX; // timer 2 is already a 32-bit timer, no need to count the overflow
}
if (timer_get_flag(TIM(FREQUENCY_TIMER), TIM_SR_CCOF(FREQUENCY_CHANNEL))) { // capture overflow occurred
timer_clear_flag(TIM(FREQUENCY_TIMER), TIM_SR_CCOF(FREQUENCY_CHANNEL)); // clear flag
pulse = UINT32_MAX; // invalidate measured pulse
}
if (timer_get_flag(TIM(FREQUENCY_TIMER), TIM_SR_CCIF(FREQUENCY_CHANNEL))) {
uint16_t edge = TIM_CCR(FREQUENCY_TIMER, FREQUENCY_CHANNEL); // retrieve captured value (clears flag)
if (UINT32_MAX != pulse) { // only calculate pulse if previous edge is valid
pulse = ((pulse & 0xffff0000) + edge) - (pulse & 0xffff); // calculate pulse duration
if (pulse < pulse_duration) { // save new pulse duration if smaller
pulse_duration = pulse; // save measurement for user
pulse_flag = true; // notify user we got a measurement
}
}
pulse = edge; // replace with current edge time
}
}
/** monitor single channel for activity and measure frequency
* @param[in] argument channel number
*/
static void command_monitor_single(void* argument)
{
// get input channel
if (NULL == argument) {
puts("provide channel to monitor\n");
return;
}
const uint32_t channel = *(uint32_t*)argument; // get channel argument
if (!(channel < CHANNEL_NUMBERS)) { // verify argument
printf("channel %u out of range (0-%u)\n", channel, CHANNEL_NUMBERS - 1);
return;
}
// verify target voltage is OK
const float* voltages = measure_voltages(); // get target voltage
if (voltages[1] < 1.5) {
puts("target voltage too low: ");
print_fpu(voltages[1], 2);
puts(" < 1.5V\n");
return;
} else {
puts("target voltage: ");
print_fpu(voltages[1], 2);
puts("V\n");
}
// select channel
rcc_periph_clock_enable(GPIO_RCC(UART_RX)); // enable clock for USART RX pin port peripheral
gpio_mode_setup(GPIO_PORT(UART_RX), GPIO_MODE_AF, GPIO_PUPD_NONE, GPIO_PIN(UART_RX)); // use as input for the timer (it is pulled up by level shifter)
gpio_set_af(GPIO_PORT(UART_RX), FREQUENCY_AF, GPIO_PIN(UART_RX)); // set alternate function to timer channel
mux_select(channel); // select channel
gpio_clear(GPIO_PORT(SHIFT_EN_PIN), GPIO_PIN(SHIFT_EN_PIN)); // connect target voltage to level shifters pull-up
// show help
printf("CH%02u is pulled to target voltage by 10 kOhm\n", channel);
puts("high = 1.5-5.5V, 'X' shows multiple changes\n");
puts("press any key to stop monitoring\n");
puts("time (s) CH freq. (Hz)\n");
// setup timer to measure frequency
rcc_periph_clock_enable(RCC_TIM(FREQUENCY_TIMER)); // enable clock for timer peripheral
rcc_periph_reset_pulse(RST_TIM(FREQUENCY_TIMER)); // reset timer state
timer_disable_counter(TIM(FREQUENCY_TIMER)); // disable timer to configure it
timer_set_mode(TIM(FREQUENCY_TIMER), TIM_CR1_CKD_CK_INT, TIM_CR1_CMS_EDGE, TIM_CR1_DIR_UP); // set timer mode, use undivided timer clock, edge alignment (simple count), and count up
timer_set_prescaler(TIM(FREQUENCY_TIMER), 0); // don't use prescale so to get the most precise measurement
timer_ic_set_input(TIM(FREQUENCY_TIMER), TIM_IC(FREQUENCY_CHANNEL), TIM_IC_IN_TI(FREQUENCY_CHANNEL)); // configure the input capture ICx to use the right channel TIn
timer_ic_set_filter(TIM(FREQUENCY_TIMER), TIM_IC(FREQUENCY_CHANNEL), TIM_IC_OFF); // use no filter input to keep precise timing
timer_ic_set_polarity(TIM(FREQUENCY_TIMER), TIM_IC(FREQUENCY_CHANNEL), TIM_IC_FALLING); // capture on falling edge
timer_ic_set_prescaler(TIM(FREQUENCY_TIMER), TIM_IC(FREQUENCY_CHANNEL), TIM_IC_PSC_OFF); // don't use any prescaler since we want to capture every pulse
timer_ic_enable(TIM(FREQUENCY_TIMER), TIM_IC(FREQUENCY_CHANNEL)); // enable capture interrupt
timer_clear_flag(TIM(FREQUENCY_TIMER), TIM_SR_CCIF(FREQUENCY_CHANNEL)); // clear input compare flag
timer_enable_irq(TIM(FREQUENCY_TIMER), TIM_DIER_CCIE(FREQUENCY_CHANNEL)); // enable capture interrupt
timer_update_on_overflow(TIM(FREQUENCY_TIMER)); // only use counter overflow as UEV source (use overflow to measure longer times)
timer_clear_flag(TIM(FREQUENCY_TIMER), TIM_SR_UIF); // clear overflow flag
timer_enable_irq(TIM(FREQUENCY_TIMER), TIM_DIER_UIE); // enable update interrupt for timer
nvic_enable_irq(NVIC_TIM_IRQ(FREQUENCY_TIMER)); // catch interrupts for this timer
pulse_duration = UINT32_MAX; // reset pulse duration
timer_enable_counter(TIM(FREQUENCY_TIMER)); // enable timer
// setup timer to measure 0.1 seconds
rcc_periph_clock_enable(RCC_TIM(MONITOR_TIMER)); // enable clock for timer peripheral
rcc_periph_reset_pulse(RST_TIM(MONITOR_TIMER)); // reset timer state
timer_disable_counter(TIM(MONITOR_TIMER)); // disable timer to configure it
timer_set_mode(TIM(MONITOR_TIMER), TIM_CR1_CKD_CK_INT, TIM_CR1_CMS_EDGE, TIM_CR1_DIR_UP); // set timer mode, use undivided timer clock, edge alignment (simple count), and count up
timer_set_prescaler(TIM(MONITOR_TIMER), (rcc_ahb_frequency / 2000) - 1); // generate half millisecond ticks (prescaler is not large enough for milliseconds)
timer_set_period(TIM(MONITOR_TIMER), 200 - 1); // set period to 0.1 seconds
timer_clear_flag(TIM(MONITOR_TIMER), TIM_SR_UIF); // clear update (overflow) flag
timer_update_on_overflow(TIM(MONITOR_TIMER)); // only use counter overflow as UEV source (use overflow as start time or timeout)
uint32_t seconds = 0; // count the 0.1 seconds using the overflow
timer_enable_counter(TIM(MONITOR_TIMER)); // enable timer
// start monitoring
bool channel_level = gpio_get(GPIO_PORT(UART_RX), GPIO_PIN(UART_RX)); // get initial level
uint8_t channel_changes = 1; // how many times the channel changed
while (!user_input_available) { // run until user breaks it
// time to do periodic checks
if (wakeup_flag || second_flag) {
iwdg_reset(); // kick the dog
wakeup_flag = false; // clear flag
second_flag = false; // clear flag
}
if (timer_get_flag(TIM(MONITOR_TIMER), TIM_SR_UIF)) { // 0.1 second has passed
timer_clear_flag(TIM(MONITOR_TIMER), TIM_SR_UIF); // clear flag
seconds++; // count the 0.1 seconds
if (channel_changes) { // there was some activity
// we print the change every 0.1 s instead of synchronously to rate limit the print (and overfill the buffer)
printf("%04u.%01u ", seconds / 10, seconds % 10); // print current time stamp (change time stamp with 0.1s precision
if (channel_changes > 1) { // channel changed more than once
putc('X'); // show multiple changes
} else {
putc(' '); // show no or single change
}
if (channel_level) { // high level
putc('1');
} else {
putc('0');
}
if (pulse_flag) { // frequency measurement worked
const uint32_t freq = rcc_ahb_frequency / pulse_duration;
printf(" %u", freq);
pulse_duration = UINT32_MAX; // clear measurement
pulse_flag = false; // clear flag
}
puts("\n");
channel_changes = 0; // clear changes
}
}
// check is there is a change on a channel
const bool level_new = gpio_get(GPIO_PORT(UART_RX), GPIO_PIN(UART_RX)); // get new level
if (level_new != channel_level) { // channel changed
channel_changes = addu8_safe(channel_changes, 1);
channel_level = level_new; // save new level
}
}
user_input_get(); // clean input
// clean up
gpio_set(GPIO_PORT(SHIFT_EN_PIN), GPIO_PIN(SHIFT_EN_PIN)); // remove power from level shifters pull-up
gpio_mode_setup(GPIO_PORT(UART_RX), GPIO_MODE_INPUT, GPIO_PUPD_NONE, GPIO_PIN(UART_RX)); // put pin back to safe floating mode
mux_select(-1); // disable multiplexer
timer_disable_counter(TIM(MONITOR_TIMER)); // disable timer
rcc_periph_reset_pulse(RST_TIM(MONITOR_TIMER)); // reset timer state
rcc_periph_clock_disable(RCC_TIM(MONITOR_TIMER)); // disable clock for timer peripheral
timer_disable_counter(TIM(FREQUENCY_TIMER)); // disable timer
nvic_disable_irq(NVIC_TIM_IRQ(FREQUENCY_TIMER)); // catch interrupts for this timer
timer_disable_irq(TIM(FREQUENCY_TIMER), TIM_DIER_UIE); // disable update interrupt for timer
timer_disable_irq(TIM(FREQUENCY_TIMER), TIM_DIER_CCIE(FREQUENCY_CHANNEL)); // disable capture interrupt
timer_ic_disable(TIM(FREQUENCY_TIMER), TIM_IC(FREQUENCY_CHANNEL)); // disable capture interrupt
rcc_periph_reset_pulse(RST_TIM(FREQUENCY_TIMER)); // reset timer state
rcc_periph_clock_disable(RCC_TIM(FREQUENCY_TIMER)); // disable clock for timer peripheral
}
/** the possible properties of a UART configuration (to be updated with every character) */
struct uart_configuration_t {
uint8_t databits; /**< data word size in bits */
bool databits_matching; /**< if the data is still matching the data bits */
bool parity_even; /**< if the date is still matching the additional even parity bit */
bool parity_odd; /**< if the date is still matching the additional odd parity bit */
bool parity_mark; /**< if the date is still matching the additional mark parity bit */
bool parity_space; /**< if the date is still matching the additional space parity bit */
uint8_t parity_possibilities; /**< the number to still matching parity possibilities (number of parity_* at true) */
};
/** reset all matching values of UART configuration
* @param[out] configuration UART configuration to reset
*/
static void uart_configuration_reset(struct uart_configuration_t* configuration)
{
configuration->databits_matching = true;
configuration->parity_even = true;
configuration->parity_odd = true;
configuration->parity_mark = true;
configuration->parity_space = true;
configuration->parity_possibilities = 4;
}
/** autodetect UART configuration on single channel
* @param[in] argument channel number
*/
static void command_uart_autodetect(void* argument)
{
// get input channel
if (NULL == argument) {
puts("provide channel to monitor for UART activity\n");
return;
}
const uint32_t channel = *(uint32_t*)argument; // get channel argument
if (!(channel < CHANNEL_NUMBERS)) { // verify argument
printf("channel %u out of range (0-%u)\n", channel, CHANNEL_NUMBERS - 1);
return;
}
// verify target voltage is OK
const float* voltages = measure_voltages(); // get target voltage
if (voltages[1] < 1.5) {
puts("target voltage too low: ");
print_fpu(voltages[1], 2);
puts(" < 1.5V\n");
return;
} else {
puts("target voltage: ");
print_fpu(voltages[1], 2);
puts("V\n");
}
// setup USART to receive character
uint8_t uart_databits = 8; // start with 8 bits since this is the most common case (i.e. no additional parity bit is used)
rcc_periph_clock_enable(RCC_USART(UART_ID)); // enable USART peripheral
rcc_periph_reset_pulse(RST_USART(FREQUENCY_TIMER)); // reset USART peripheral
usart_set_baudrate(USART(UART_ID), 1200); // configure UART to slowest baud rate
usart_set_databits(USART(UART_ID), uart_databits); // configure UART to pre-selected data-bits
usart_set_stopbits(USART(UART_ID), USART_STOPBITS_1); // 1 stop-bits also complies to 2 stop-bits
usart_set_parity(USART(UART_ID), USART_PARITY_NONE); // get the raw data since we will do the parity check ourselves
usart_set_mode(USART(UART_ID), USART_MODE_RX); // we will only receive data
USART_CR3(USART(UART_ID)) |= USART_CR3_HDSEL; // we will use the half-duplex mode to use the TX pin as RX
// USART will be enabled by the autodetection loop
// select channel
rcc_periph_clock_enable(GPIO_RCC(UART_RX)); // enable clock for USART RX pin port peripheral
gpio_mode_setup(GPIO_PORT(UART_RX), GPIO_MODE_AF, GPIO_PUPD_NONE, GPIO_PIN(UART_RX)); // use as input for the timer (it is pulled up by level shifter)
gpio_set_af(GPIO_PORT(UART_RX), FREQUENCY_AF, GPIO_PIN(UART_RX)); // set alternate function to timer channel
rcc_periph_clock_enable(GPIO_RCC(UART_TX)); // enable clock for USART TX pin port peripheral
gpio_mode_setup(GPIO_PORT(UART_TX), GPIO_MODE_AF, GPIO_PUPD_NONE, GPIO_PIN(UART_TX)); // use pin for UART data (normally output, but in half duplex it can become input)
gpio_set_af(GPIO_PORT(UART_TX), UART_AF, GPIO_PIN(UART_TX)); // set alternate function to UART
mux_select(channel); // select channel
gpio_clear(GPIO_PORT(SHIFT_EN_PIN), GPIO_PIN(SHIFT_EN_PIN)); // connect target voltage to level shifters pull-up
// show help
printf("CH%02u is pulled to target voltage by 10 kOhm\n", channel);
puts("high = 1.5-5.5V, data is shown as decoded\n");
puts("UART configuration autodetection improves with incoming data\n");
puts("press any key to stop autodetection\n");
// setup timer to measure frequency
rcc_periph_clock_enable(RCC_TIM(FREQUENCY_TIMER)); // enable clock for timer peripheral
rcc_periph_reset_pulse(RST_TIM(FREQUENCY_TIMER)); // reset timer state
timer_disable_counter(TIM(FREQUENCY_TIMER)); // disable timer to configure it
timer_set_mode(TIM(FREQUENCY_TIMER), TIM_CR1_CKD_CK_INT, TIM_CR1_CMS_EDGE, TIM_CR1_DIR_UP); // set timer mode, use undivided timer clock, edge alignment (simple count), and count up
timer_set_prescaler(TIM(FREQUENCY_TIMER), 0); // don't use prescale so to get the most precise measurement
timer_ic_set_input(TIM(FREQUENCY_TIMER), TIM_IC(FREQUENCY_CHANNEL), TIM_IC_IN_TI(FREQUENCY_CHANNEL)); // configure the input capture ICx to use the right channel TIn
timer_ic_set_filter(TIM(FREQUENCY_TIMER), TIM_IC(FREQUENCY_CHANNEL), TIM_IC_OFF); // use no filter input to keep precise timing
timer_ic_set_polarity(TIM(FREQUENCY_TIMER), TIM_IC(FREQUENCY_CHANNEL), TIM_IC_FALLING); // capture on falling edge
timer_ic_set_prescaler(TIM(FREQUENCY_TIMER), TIM_IC(FREQUENCY_CHANNEL), TIM_IC_PSC_OFF); // don't use any prescaler since we want to capture every pulse
timer_ic_enable(TIM(FREQUENCY_TIMER), TIM_IC(FREQUENCY_CHANNEL)); // enable capture interrupt
timer_clear_flag(TIM(FREQUENCY_TIMER), TIM_SR_CCIF(FREQUENCY_CHANNEL)); // clear input compare flag
timer_enable_irq(TIM(FREQUENCY_TIMER), TIM_DIER_CCIE(FREQUENCY_CHANNEL)); // enable capture interrupt
timer_update_on_overflow(TIM(FREQUENCY_TIMER)); // only use counter overflow as UEV source (use overflow to measure longer times)
timer_clear_flag(TIM(FREQUENCY_TIMER), TIM_SR_UIF); // clear overflow flag
timer_enable_irq(TIM(FREQUENCY_TIMER), TIM_DIER_UIE); // enable update interrupt for timer
nvic_enable_irq(NVIC_TIM_IRQ(FREQUENCY_TIMER)); // catch interrupts for this timer
pulse_duration = UINT32_MAX; // reset pulse duration
timer_enable_counter(TIM(FREQUENCY_TIMER)); // enable timer
// start autodetection
bool reset_state = true; // flag to know if we need to reset the states
uint8_t rx_errors; // number of UART receive errors received
bool wait_for_idle = false; // flag to wait for an IDLE frame
/** the possible UART configurations
* @note since the first valid configuration will be chosen, order in decreasing probability of being valid and decreasing probability or getting invalidated */
struct uart_configuration_t uart_configurations[] = {
{ .databits = 5 },
{ .databits = 6 },
{ .databits = 8 },
{ .databits = 7 },
};
uint8_t uart_configuration_valid = LENGTH(uart_configurations); // current best valid UART configuration index
char uart_configuration_parity = '?'; // current best valid UART parity
const uint32_t baudrates[] = { 1200, 1800, 2400, 4800, 9600, 19200, 38400, 57600, 115200, 230400, 460800, 576000, 921600, 1000000 }; // list of standard baud rates, to match with measured frequency
uint32_t uart_baudrate = 0; // fastest found baud rate
while (!user_input_available) { // run until user breaks it
// time to do periodic checks
if (wakeup_flag || second_flag) {
iwdg_reset(); // kick the dog
wakeup_flag = false; // clear flag
second_flag = false; // clear flag
}
if (reset_state) { // reset the configuration
rx_errors = 0;
for (uint8_t i = 0; i < LENGTH(uart_configurations); i++) {
uart_configuration_reset(&uart_configurations[i]);
}
usart_recv(USART(UART_ID)); // clear input buffer and allow flag to be set
usart_enable(USART(UART_ID)); // ensure UART is enabled
reset_state = false;
}
if (pulse_flag) { // new pulse duration has been measured
pulse_flag = false; // clear flag
uint32_t baudrate = rcc_ahb_frequency / (pulse_duration / 2); // calculate baud rate based on measured timing
if (baudrate > uart_baudrate + 100) { // new higher baud rate detected
uart_baudrate = baudrate; // save new baud rate
if (uart_baudrate >= 1200) { // ensure minimum hardware supported baud rate is respected
// search for closest standard baud rate
uint32_t standard_baudrate = 0;
for (uint8_t i = 0; i < LENGTH(baudrates); i++) {
if (uart_baudrate >= baudrates[i] * 0.9 && uart_baudrate <= baudrates[i] * 1.1) { // measured baud rate matches standard baud rate within factor
standard_baudrate = baudrates[i]; // remember matching baud rate
break; // stop searching for matching baud rate
}
}
if (standard_baudrate) { // matching standard baud rate found
uart_baudrate = standard_baudrate; // save matching baud rate
}
usart_disable(USART(UART_ID)); // disable UART before reconfiguring
usart_set_baudrate(USART(UART_ID), uart_baudrate); // set new baud rate
reset_state = true; // reset the states since we set a new baud rate
printf("\nnew baud rate: %u bps\n", uart_baudrate); // show measurement frequency
} else {
printf("\ndetected %u bps baud rate is lower than minimum supported 1200 bps\n", baudrate);
}
}
}
if (USART_SR(USART(UART_ID)) & (USART_SR_NE|USART_SR_FE)) { // error on UART received
usart_recv(USART(UART_ID)); // clear input buffer and flags
rx_errors++; // increment number of errors
if (rx_errors >= 5) { // the format seems wrong
// the threshold must be high enough so the UART peripheral has enough opportunities to synchronize to the start bit (just after an idle frame)
// too high frame error causes:
// - when set to 9 data-bits with high speed 8 data-bits traffic incoming: the next start bit comes right after the stop bit of and 8-bit frame, which is interpreted as faulty 9 data-bits frame stop bit
// - when set to 8 data-bits with 9 data-bits (8+1 parity) traffic incoming: the low parity bit is interpreted as faulty stop-bit
uart_databits = ((8 == uart_databits) ? 9 : 8); // switch between 8 and 9-bit packets
usart_disable(USART(UART_ID)); // disable UART before reconfiguring
usart_set_databits(USART(UART_ID), uart_databits); // set new data width
reset_state = true;
pulse_duration = UINT32_MAX; // also reset the baud rate
uart_baudrate = 0; // also reset the baud rate
rx_errors = 0; // reset error counter
printf("\nrestarting guessing because detected too many errors\n");
} else {
wait_for_idle = true; // wait form an IDLE frame so to better sync to the next start bit
}
}
if (wait_for_idle) {
/* we have to check the IDLE flag in the main loop instead of just looping over the flag because a hardware fault could prevent it from being set.
*/
if (USART(UART_ID) | USART_SR_IDLE) { // idle flag set
wait_for_idle = false; // no need to wait anymore
}
if (USART_SR(USART(UART_ID)) | USART_SR_RXNE) { // data is available
USART_DR(USART(UART_ID)); // empty receive buffer so the IDLE flag can retrigger
}
}
if (USART_SR(USART(UART_ID)) & USART_SR_RXNE) { // data received
const uint16_t usart_data = usart_recv(USART(UART_ID)); // save received data (also clears flag)
if (0 == uart_baudrate) { // we did not find any valid baud rate yet
continue;
}
const uint16_t usart_data_padded = ((8 == uart_databits) ? usart_data | 0xff00 : usart_data | 0xfe00); // pad with 1 (stop bit/idle state) for better word size detection
const uint16_t usart_data_relevant = usart_data & ~(0xffff << uart_configurations[uart_configuration_valid].databits); // get only the data bits
// verify parity and word size
for (uint8_t i = 0; i < LENGTH(uart_configurations); i++) {
// skip check if we already know the word size is wrong
if (!uart_configurations[i].databits_matching) {
continue;
}
// do parity checks
if (uart_configurations[i].parity_even) {
uart_configurations[i].parity_even &= usart_enhanced_even_parity_lut[usart_data_relevant];
}
if (uart_configurations[i].parity_odd) {
uart_configurations[i].parity_odd &= !usart_enhanced_even_parity_lut[usart_data_relevant];
}
if (uart_configurations[i].parity_mark) {
uart_configurations[i].parity_mark &= (usart_data_padded & (1 << uart_configurations[i].databits));
}
if (uart_configurations[i].parity_space) {
uart_configurations[i].parity_space &= !(usart_data_padded & (1 << uart_configurations[i].databits));
}
// update parity count
uart_configurations[i].parity_possibilities = 0;
if (uart_configurations[i].parity_even) {
uart_configurations[i].parity_possibilities++;
}
if (uart_configurations[i].parity_odd) {
uart_configurations[i].parity_possibilities++;
}
if (uart_configurations[i].parity_mark) {
uart_configurations[i].parity_possibilities++;
}
if (uart_configurations[i].parity_space) {
uart_configurations[i].parity_possibilities++;
}
// verify word size
const uint16_t databits_mask = (0xffff << (uart_configurations[i].databits + ((0 == uart_configurations[i].parity_possibilities) ? 0 : 1))); // mask for bits which should not be cleared
if (~usart_data_padded & databits_mask) { // see if bit outside the word size are cleared
uart_configurations[i].databits_matching = false;
}
}
bool no_valid_configuration = true;
uint8_t new_valid_configuration = LENGTH(uart_configurations);
char parity = '?';
for (uint8_t i = 0; i < LENGTH(uart_configurations); i++) {
// skip check the word size is wrong
if (!uart_configurations[i].databits_matching) {
continue;
}
no_valid_configuration = false;
if (uart_configurations[i].parity_possibilities > 1) { // parity is not yet clear
continue;
} else if (uart_configurations[i].parity_even) {
parity = 'E';
} else if (uart_configurations[i].parity_odd) {
parity = 'O';
} else if (uart_configurations[i].parity_mark) {
parity = 'M';
} else if (uart_configurations[i].parity_space) {
parity = 'S';
} else if (0==uart_configurations[i].parity_possibilities) {
parity = 'N';
}
new_valid_configuration = i;
break; // stop searching since we found a configuration
}
if (no_valid_configuration) {
reset_state = true; // reset the configurations
pulse_duration = UINT32_MAX; // also reset the baud rate
uart_baudrate = 0; // also reset the baud rate
} else if (new_valid_configuration < LENGTH(uart_configurations) && '?' != parity && (new_valid_configuration != uart_configuration_valid || parity != uart_configuration_parity)) { // we found a new valid configuration
uart_configuration_valid = new_valid_configuration;
uart_configuration_parity = parity;
printf("\nnew UART configuration found: %u %u%c1\n", uart_baudrate, uart_configurations[uart_configuration_valid].databits, uart_configuration_parity);
}
// print received data if a configuration has been found
if (uart_configuration_valid < LENGTH(uart_configurations)) { // valid configuration existing
if (uart_configurations[uart_configuration_valid].databits >= 7 && usart_data_relevant < 0x80) { // this is probably valid ASCII data
putc(usart_data_relevant);
} else {
printf("0x%02x ", usart_data_relevant);
}
} else {
printf("0b%09b\n", usart_data_relevant);
}
}
}
user_input_get(); // clean input
// clean up
gpio_set(GPIO_PORT(SHIFT_EN_PIN), GPIO_PIN(SHIFT_EN_PIN)); // remove power from level shifters pull-up
gpio_mode_setup(GPIO_PORT(UART_RX), GPIO_MODE_INPUT, GPIO_PUPD_NONE, GPIO_PIN(UART_RX)); // put pin back to safe floating mode
gpio_mode_setup(GPIO_PORT(UART_TX), GPIO_MODE_INPUT, GPIO_PUPD_NONE, GPIO_PIN(UART_TX)); // put pin back to safe floating mode
mux_select(-1); // disable multiplexer
timer_disable_counter(TIM(MONITOR_TIMER)); // disable timer
rcc_periph_reset_pulse(RST_TIM(MONITOR_TIMER)); // reset timer state
rcc_periph_clock_disable(RCC_TIM(MONITOR_TIMER)); // disable clock for timer peripheral
timer_disable_counter(TIM(FREQUENCY_TIMER)); // disable timer
nvic_disable_irq(NVIC_TIM_IRQ(FREQUENCY_TIMER)); // catch interrupts for this timer
timer_disable_irq(TIM(FREQUENCY_TIMER), TIM_DIER_UIE); // disable update interrupt for timer
timer_disable_irq(TIM(FREQUENCY_TIMER), TIM_DIER_CCIE(FREQUENCY_CHANNEL)); // disable capture interrupt
timer_ic_disable(TIM(FREQUENCY_TIMER), TIM_IC(FREQUENCY_CHANNEL)); // disable capture interrupt
rcc_periph_reset_pulse(RST_TIM(FREQUENCY_TIMER)); // reset timer state
rcc_periph_clock_disable(RCC_TIM(FREQUENCY_TIMER)); // disable clock for timer peripheral
rcc_periph_reset_pulse(RST_USART(UART_ID)); // reset USART peripheral
rcc_periph_clock_disable(RCC_USART(UART_ID)); // disable clock for USART peripheral
}
/** find the RX UART pin
* @param TX channel, baud rate, data bits parity and stop bits
*/
static void command_uart_probe(void* argument)
{
char* line = (char*)argument; // get line of arguments
if (NULL == argument || 0 == strlen(line)) { // ensure argument is provided
goto command_uart_probe_error;
return;
}
// get channel
const char* delimiter = " "; // words are separated by spaces
char* word = strtok(line, delimiter); // get first word
if (!word) {
goto command_uart_probe_error;
return;
}
const int32_t channel = strtol(word, NULL, 10); // get signed integer
if ((channel < 0) || (channel >= CHANNEL_NUMBERS)) { // verify argument
printf("channel %d out of range (0-%u)\n", channel, CHANNEL_NUMBERS - 1);
return;
}
// get baud rate
word = strtok(NULL, delimiter); // get second word
if (!word) {
goto command_uart_probe_error;
return;
}
const int32_t baudrate = strtol(word, NULL, 10); // get signed integer
if ((baudrate < 1200) || (baudrate >= 2000000)) { // verify argument
printf("baud rate %d out of range (1200-2000000 bps)\n", baudrate);
return;
}
// get frame format (data bits, parity, stop bits
word = strtok(NULL, delimiter); // get third word
if (!word || 3 != strlen(word)) {
printf("unknown frame format %s\n", word);
goto command_uart_probe_error;
return;
}
// data bits
if (word[0] < '5' || word[0] > '8') {
printf("unknown data bits %c\n", word[0]);
goto command_uart_probe_error;
return;
}
const uint8_t databits = word[0] - '0';
// parity
enum usart_enhanced_parity_t parity;
switch(word[1]) {
case 'N':
case 'n':
parity = USART_ENHANCED_PARITY_NONE;
break;
case 'E':
case 'e':
parity = USART_ENHANCED_PARITY_EVEN;
break;
case 'O':
case 'o':
parity = USART_ENHANCED_PARITY_ODD;
break;
case 'M':
case 'm':
parity = USART_ENHANCED_PARITY_MARK;
break;
case 'S':
case 's':
parity = USART_ENHANCED_PARITY_SPACE;
break;
default:
printf("unknown parity %c\n", word[1]);
goto command_uart_probe_error;
return;
}
// stop bits
if (word[2] < '1' || word[2] > '2') {
printf("unknown stop bits %c\n", word[2]);
goto command_uart_probe_error;
return;
}
const uint8_t stopbits = word[2] - '0';
// verify target voltage is OK
const float* voltages = measure_voltages(); // get target voltage
if (voltages[1] < 1.5) {
puts("target voltage too low: ");
print_fpu(voltages[1], 2);
puts(" < 1.5V\n");
return;
} else {
puts("target voltage: ");
print_fpu(voltages[1], 2);
puts("V\n");
}
// configure UART
rcc_periph_clock_enable(GPIO_RCC(UART_TX)); // enable clock for USART TX pin port peripheral
gpio_mode_setup(GPIO_PORT(UART_TX), GPIO_MODE_AF, GPIO_PUPD_NONE, GPIO_PIN(UART_TX)); // use pin for UART data (normally output, but in half duplex it can become input)
gpio_set_af(GPIO_PORT(UART_TX), UART_AF, GPIO_PIN(UART_TX)); // set alternate function to UART
gpio_clear(GPIO_PORT(SHIFT_EN_PIN), GPIO_PIN(SHIFT_EN_PIN)); // connect target voltage to level shifters pull-up
rcc_periph_clock_enable(RCC_USART(UART_ID)); // enable USART peripheral
rcc_periph_reset_pulse(RST_USART(FREQUENCY_TIMER)); // reset USART peripheral
usart_set_baudrate(USART(UART_ID), baudrate); // configure UART to slowest baud rate
if (2 == stopbits) {
usart_set_stopbits(USART(UART_ID), USART_STOPBITS_2); // ensure we have 2 stop bits
} else {
usart_set_stopbits(USART(UART_ID), USART_STOPBITS_1); // 1 stop-bits also complies to 2 stop-bits when receiving
}
usart_enhanced_config(USART(UART_ID), databits, parity); // set data bits and parity using enhanced library to support more modes
usart_set_mode(USART(UART_ID), USART_MODE_TX_RX); // we will send and receive data
USART_CR3(USART(UART_ID)) |= USART_CR3_HDSEL; // we will use the half-duplex mode to use the TX pin as RX
usart_enable(USART(UART_ID)); // ensure UART is enabled
// setup timer to measure 0.1 seconds
rcc_periph_clock_enable(RCC_TIM(MONITOR_TIMER)); // enable clock for timer peripheral
rcc_periph_reset_pulse(RST_TIM(MONITOR_TIMER)); // reset timer state
timer_disable_counter(TIM(MONITOR_TIMER)); // disable timer to configure it
timer_set_mode(TIM(MONITOR_TIMER), TIM_CR1_CKD_CK_INT, TIM_CR1_CMS_EDGE, TIM_CR1_DIR_UP); // set timer mode, use undivided timer clock, edge alignment (simple count), and count up
timer_set_prescaler(TIM(MONITOR_TIMER), (rcc_ahb_frequency / 2000) - 1); // generate half millisecond ticks (prescaler is not large enough for milliseconds)
timer_set_period(TIM(MONITOR_TIMER), 200 - 1); // set period to 0.1 seconds
timer_clear_flag(TIM(MONITOR_TIMER), TIM_SR_UIF); // clear update (overflow) flag
timer_update_on_overflow(TIM(MONITOR_TIMER)); // only use counter overflow as UEV source (use overflow as start time or timeout)
timer_one_shot_mode(TIM(MONITOR_TIMER)); // use timer one to count down once
timer_enable_counter(TIM(MONITOR_TIMER)); // start timer have the setting take effect (else the first oneshot is too short)
// probe each channel
const char cs[] = {' ', '0', 'X'}; // characters to send
bool found = false; // to remember if we found an RX channel
printf("probing for UART RX on CH%02u-CH%02u\n", channel_start, channel_stop);
while (!timer_get_flag(TIM(MONITOR_TIMER), TIM_SR_UIF)); // wait for oneshot to complete
timer_disable_counter(TIM(MONITOR_TIMER)); // ensure the timer if off (should be in one shot)
for (uint8_t ch = channel_start; ch <= channel_stop; ch++) { // go through each channel (it might also be the one we are sending from)
putc('.');
uint8_t success = 0; // count how often the characters has been echoed back
for (uint8_t i = 0; i < LENGTH(cs); i++) { // send each character
if (wakeup_flag || second_flag) {
iwdg_reset(); // kick the dog
wakeup_flag = false; // clear flag
second_flag = false; // clear flag
}
mux_select(ch); // select channel to transmit
USART_DR(USART(UART_ID)); // empty receive buffer
usart_get_flag(USART(UART_ID), USART_SR_TC); // read flag to clear it by writing to DR
usart_enhanced_send(USART(UART_ID), cs[i]); // send probing character (also clears TC flag)
while (!usart_get_flag(USART(UART_ID), USART_SR_TC)); // wait until transmission completed
mux_select(channel); // select channel to receive
while (!usart_get_flag(USART(UART_ID), USART_SR_RXNE)); // wait for own echo because we are in half duplex
USART_DR(USART(UART_ID)); // empty receive buffer
timer_clear_flag(TIM(MONITOR_TIMER), TIM_SR_UIF); // clear timer flag
timer_set_counter(TIM(MONITOR_TIMER), 0); // restart counter
timer_enable_counter(TIM(MONITOR_TIMER)); // start timer
while (!timer_get_flag(TIM(MONITOR_TIMER), TIM_SR_UIF)); // wait until 0.1 second has passed (it could be optimised by checking if data has been received)
timer_disable_counter(TIM(MONITOR_TIMER)); // ensure the timer if off (should be in one shot)
timer_clear_flag(TIM(MONITOR_TIMER), TIM_SR_UIF); // clear timer flag
if (usart_get_flag(USART(UART_ID), USART_SR_RXNE) && cs[i] == usart_enhanced_recv(USART(UART_ID))) { // data has been echoed back
success++; // remember data has been echoed back
}
}
if (success > 1) {
printf("\nUART RX found on CH%02u\n", ch); // show found channel to user
found = true; // remember we found a channel
}
}
if (!found) {
puts("\nUART RX not found");
}
putc('\n');
// clean up
gpio_set(GPIO_PORT(SHIFT_EN_PIN), GPIO_PIN(SHIFT_EN_PIN)); // remove power from level shifters pull-up
gpio_mode_setup(GPIO_PORT(UART_RX), GPIO_MODE_INPUT, GPIO_PUPD_NONE, GPIO_PIN(UART_RX)); // put pin back to safe floating mode
mux_select(-1); // disable multiplexer
timer_disable_counter(TIM(MONITOR_TIMER)); // disable timer
rcc_periph_reset_pulse(RST_TIM(MONITOR_TIMER)); // reset timer state
rcc_periph_clock_disable(RCC_TIM(MONITOR_TIMER)); // disable clock for timer peripheral
timer_disable_counter(TIM(FREQUENCY_TIMER)); // disable timer
nvic_disable_irq(NVIC_TIM_IRQ(FREQUENCY_TIMER)); // catch interrupts for this timer
timer_disable_irq(TIM(FREQUENCY_TIMER), TIM_DIER_UIE); // disable update interrupt for timer
timer_disable_irq(TIM(FREQUENCY_TIMER), TIM_DIER_CCIE(FREQUENCY_CHANNEL)); // disable capture interrupt
timer_ic_disable(TIM(FREQUENCY_TIMER), TIM_IC(FREQUENCY_CHANNEL)); // disable capture interrupt
rcc_periph_reset_pulse(RST_TIM(FREQUENCY_TIMER)); // reset timer state
rcc_periph_clock_disable(RCC_TIM(FREQUENCY_TIMER)); // disable clock for timer peripheral
return;
command_uart_probe_error:
puts("arguments: TX_channel baudrate DatabitsParityStopbits\n");
printf("TX_channel: 0-%u\n", CHANNEL_NUMBERS - 1);
puts("baudrate: 1200-2000000 (bps)\n");
puts("DatabitsParityStopbits: 5-8 databits, N=none/E=even/O=odd/M=mark/S=space, 1-2:stopbits\n");
puts("example: 01 115200 8N1\n");
}
/** set first channel of range to scan
* @param[in] argument optional pointer to first channel number
*/
static void command_channel_start(void* argument)
{
if (argument) {
const uint32_t channel = *(uint32_t*)argument;
if (channel < CHANNEL_NUMBERS && channel < channel_stop) {
channel_start = channel;
}
}
printf("channels to probe: %u-%u\n", channel_start, channel_stop);
}
/** set last channel of range to scan
* @param[in] argument optional pointer to last channel number
*/
static void command_channel_stop(void* argument)
{
if (argument) {
const uint32_t channel = *(uint32_t*)argument;
if (channel < CHANNEL_NUMBERS && channel > channel_start) {
channel_stop = channel;
}
}
printf("channels to probe: %u-%u\n", channel_start, channel_stop);
}
/** display available commands
* @param[in] argument no argument required
*/
static void command_help(void* argument);
/** show software and hardware version
* @param[in] argument no argument required
*/
static void command_version(void* argument)
{
(void)argument; // we won't use the argument
printf("firmware date: %04u-%02u-%02u\n", BUILD_YEAR, BUILD_MONTH, BUILD_DAY); // show firmware build date
printf("device serial: %08x%08x%08x\n", DESIG_UNIQUE_ID2, DESIG_UNIQUE_ID1, DESIG_UNIQUE_ID0); // show complete serial (different than the one used for USB)
}
/** convert RTC date/time to number of seconds
* @return number of seconds since 2000-01-01 00:00:00
* @warning for simplicity I consider every month to have 31 days
*/
static uint32_t rtc_to_seconds(void)
{
rtc_wait_for_synchro(); // wait until date/time is synchronised
const uint8_t year = ((RTC_DR >> RTC_DR_YT_SHIFT) & RTC_DR_YT_MASK) * 10 + ((RTC_DR >> RTC_DR_YU_SHIFT) & RTC_DR_YU_MASK); // get year
uint8_t month = ((RTC_DR >> RTC_DR_MT_SHIFT) & RTC_DR_MT_MASK) * 10 + ((RTC_DR >> RTC_DR_MU_SHIFT) & RTC_DR_MU_MASK); // get month
if (month > 0) { // month has been initialized, but starts with 1
month--; // fix for calculation
}
uint8_t day = ((RTC_DR >> RTC_DR_DT_SHIFT) & RTC_DR_DT_MASK) * 10 + ((RTC_DR >> RTC_DR_DU_SHIFT) & RTC_DR_DU_MASK); // get day
if (day > 0) { // day has been initialized, but starts with 1
day--; // fix for calculation
}
const uint8_t hour = ((RTC_TR >> RTC_TR_HT_SHIFT) & RTC_TR_HT_MASK) * 10 + ((RTC_TR >> RTC_TR_HU_SHIFT) & RTC_TR_HU_MASK); // get hours
const uint8_t minute = ((RTC_TR >> RTC_TR_MNT_SHIFT) & RTC_TR_MNT_MASK) * 10 + ((RTC_TR >> RTC_TR_MNU_SHIFT) & RTC_TR_MNU_MASK); // get minutes
const uint8_t second = ((RTC_TR >> RTC_TR_ST_SHIFT) & RTC_TR_ST_MASK) * 10 + ((RTC_TR >> RTC_TR_SU_SHIFT) & RTC_TR_SU_MASK); // get seconds
const uint32_t seconds = ((((((((year * 12) + month) * 31) + day) * 24) + hour) * 60) + minute) * 60 + second; // convert to number of seconds
return seconds;
}
/** show uptime
* @param[in] argument no argument required
*/
static void command_uptime(void* argument)
{
(void)argument; // we won't use the argument
const uint32_t uptime = rtc_to_seconds() - boot_time; // get time from internal RTC
printf("uptime: %u.%02u:%02u:%02u\n", uptime / (24 * 60 * 60), (uptime / (60 * 60)) % 24, (uptime / 60) % 60, uptime % 60);
}
/** reset board
* @param[in] argument no argument required
*/
static void command_reset(void* argument)
{
(void)argument; // we won't use the argument
scb_reset_system(); // reset device
while (true); // wait for the reset to happen
}
/** switch to system memory (e.g. embedded bootloader)
* @param[in] argument no argument required
*/
static void command_system(void* argument)
{
(void)argument; // we won't use the argument
system_memory(); // jump to system memory
}
/** switch to DFU bootloader
* @param[in] argument no argument required
*/
static void command_bootloader(void* argument)
{
(void)argument; // we won't use the argument
dfu_bootloader(); // start DFU bootloader
}
/** list of all supported commands */
static const struct menu_command_t menu_commands[] = {
{
.shortcut = 'h',
.name = "help",
.command_description = "display help",
.argument = MENU_ARGUMENT_NONE,
.argument_description = NULL,
.command_handler = &command_help,
},
{
.shortcut = 'V',
.name = "version",
.command_description = "show software and hardware version",
.argument = MENU_ARGUMENT_NONE,
.argument_description = NULL,
.command_handler = &command_version,
},
{
.shortcut = 'u',
.name = "uptime",
.command_description = "show uptime",
.argument = MENU_ARGUMENT_NONE,
.argument_description = NULL,
.command_handler = &command_uptime,
},
{
.shortcut = 'R',
.name = "reset_board",
.command_description = "reset board",
.argument = MENU_ARGUMENT_NONE,
.argument_description = NULL,
.command_handler = &command_reset,
},
{
.shortcut = 's',
.name = "system",
.command_description = "reboot into system memory",
.argument = MENU_ARGUMENT_NONE,
.argument_description = NULL,
.command_handler = &command_system,
},
{
.shortcut = 'b',
.name = "bootloader",
.command_description = "reboot into DFU bootloader",
.argument = MENU_ARGUMENT_NONE,
.argument_description = NULL,
.command_handler = &command_bootloader,
},
{
.shortcut = 'v',
.name = "voltage",
.command_description = "measure/set target voltage",
.argument = MENU_ARGUMENT_UNSIGNED,
.argument_description = "[0|3]",
.command_handler = &command_target_voltage,
},
{
.shortcut = 'r',
.name = "reset",
.command_description = "configure/reset target board",
.argument = MENU_ARGUMENT_STRING,
.argument_description = "[0|1|ODL|ODH|PPL|PPH]",
.command_handler = &command_target_reset,
},
{
.shortcut = 't',
.name = "type",
.command_description = "identify signal types",
.argument = MENU_ARGUMENT_NONE,
.argument_description = NULL,
.command_handler = &command_types,
},
{
.shortcut = 'm',
.name = "monitor",
.command_description = "monitor channel activity",
.argument = MENU_ARGUMENT_UNSIGNED,
.argument_description = "[0|3]",
.command_handler = &command_monitor,
},
{
.shortcut = 'M',
.name = "monitor_single",
.command_description = "monitor single channel activity",
.argument = MENU_ARGUMENT_UNSIGNED,
.argument_description = "CH",
.command_handler = &command_monitor_single,
},
{
.shortcut = 'a',
.name = "uart_tx",
.command_description = "autodetect UART configuration of TX pin",
.argument = MENU_ARGUMENT_UNSIGNED,
.argument_description = "CH",
.command_handler = &command_uart_autodetect,
},
{
.shortcut = 'u',
.name = "uart_rx",
.command_description = "find UART RX pin",
.argument = MENU_ARGUMENT_STRING,
.argument_description = "TX_CH baudrate DatabitsParityStopbits",
.command_handler = &command_uart_probe,
},
{
.shortcut = 'c',
.name = "start",
.command_description = "first channel of range to probe",
.argument = MENU_ARGUMENT_UNSIGNED,
.argument_description = "[ch]",
.command_handler = &command_channel_start,
},
{
.shortcut = 'C',
.name = "stop",
.command_description = "last channel of range to probe",
.argument = MENU_ARGUMENT_UNSIGNED,
.argument_description = "[ch]",
.command_handler = &command_channel_stop,
},
};
static void command_help(void* argument)
{
(void)argument; // we won't use the argument
printf("available commands:\n");
menu_print_commands(menu_commands, LENGTH(menu_commands)); // print global commands
}
/** process user command
* @param[in] str user command string (\0 ended)
*/
static void process_command(char* str)
{
// ensure actions are available
if (NULL == menu_commands || 0 == LENGTH(menu_commands)) {
return;
}
// don't handle empty lines
if (!str || 0 == strlen(str)) {
return;
}
bool command_handled = false;
if (!command_handled) {
command_handled = menu_handle_command(str, menu_commands, LENGTH(menu_commands)); // try if this is not a global command
}
if (!command_handled) {
printf("command not recognized. enter help to list commands\n");
}
}
/** program entry point
* this is the firmware function started by the micro-controller
*/
void main(void);
void main(void)
{
#if DEBUG
// enable functionalities for easier debug
DBGMCU_CR |= DBGMCU_CR_IWDG_STOP; // stop independent watchdog counter when code is halted
DBGMCU_CR |= DBGMCU_CR_WWDG_STOP; // stop window watchdog counter when code is halted
DBGMCU_CR |= DBGMCU_CR_STANDBY; // allow debug also in standby mode (keep digital part and clock powered)
DBGMCU_CR |= DBGMCU_CR_STOP; // allow debug also in stop mode (keep clock powered)
DBGMCU_CR |= DBGMCU_CR_SLEEP; // allow debug also in sleep mode (keep clock powered)
#else
// setup watchdog to reset in case we get stuck (i.e. when an error occurred)
iwdg_set_period_ms(WATCHDOG_PERIOD); // set independent watchdog period
iwdg_start(); // start independent watchdog
#endif
board_setup(); // setup board
usb_cdcacm_setup(); // setup USB CDC ACM (for printing)
puts("\nwelcome to the CuVoodoo I/O finder\n"); // print welcome message
#if DEBUG
// show reset cause
if (RCC_CSR & (RCC_CSR_LPWRRSTF | RCC_CSR_WWDGRSTF | RCC_CSR_IWDGRSTF | RCC_CSR_SFTRSTF | RCC_CSR_PORRSTF | RCC_CSR_PINRSTF)) {
puts("reset cause(s):");
if (RCC_CSR & RCC_CSR_LPWRRSTF) {
puts(" low-power");
}
if (RCC_CSR & RCC_CSR_WWDGRSTF) {
puts(" window-watchdog");
}
if (RCC_CSR & RCC_CSR_IWDGRSTF) {
puts(" independent-watchdog");
}
if (RCC_CSR & RCC_CSR_SFTRSTF) {
puts(" software");
}
if (RCC_CSR & RCC_CSR_PORRSTF) {
puts(" POR/PDR");
}
if (RCC_CSR & RCC_CSR_PINRSTF) {
puts(" pin");
}
putc('\n');
RCC_CSR |= RCC_CSR_RMVF; // clear reset flags
}
#endif
// setup RTC
puts_debug("setup RTC: ");
rcc_periph_clock_enable(RCC_RTC); // enable clock for RTC peripheral
rcc_osc_on(RCC_LSI); // enable LSI clock
while (!rcc_is_osc_ready(RCC_LSI)); // wait until clock is ready
if (!(RCC_BDCR && RCC_BDCR_RTCEN)) { // the RTC has not been configured yet
pwr_disable_backup_domain_write_protect(); // disable backup protection so we can set the RTC clock source
rtc_unlock(); // enable writing RTC registers
rtc_set_prescaler(250, 128); // set clock prescaler to 32000
RCC_BDCR = (RCC_BDCR & ~(RCC_BDCR_RTCSEL_MASK << RCC_BDCR_RTCSEL_SHIFT)) | (RCC_BDCR_RTCSEL_LSI << RCC_BDCR_RTCSEL_SHIFT); // select LSI as RTC clock source
RCC_BDCR |= RCC_BDCR_RTCEN; // enable RTC
rtc_lock(); // protect RTC register against writing
pwr_enable_backup_domain_write_protect(); // re-enable protection now that we configured the RTC clock
}
boot_time = rtc_to_seconds(); // remember the start time
puts_debug("OK\n");
// setup wakeup timer for periodic checks
puts_debug("setup wakeup: ");
// RTC needs to be configured beforehand
pwr_disable_backup_domain_write_protect(); // disable backup protection so we can write to the RTC registers
rtc_unlock(); // enable writing RTC registers
rtc_clear_wakeup_flag(); // clear flag for fresh start
rtc_set_wakeup_time((32000 / 2) / WAKEUP_FREQ - 1, RTC_CR_WUCLKSEL_RTC_DIV2); // set wakeup time based on LSI (keep highest precision, also enables the wakeup timer)
rtc_enable_wakeup_timer_interrupt(); // enable interrupt
rtc_lock(); // disable writing RTC registers
// important: do not re-enable backup_domain_write_protect, since this will prevent clearing flags (but RTC registers do not need to be unlocked)
puts_debug("OK\n");
puts_debug("setup voltage control: ");
rcc_periph_clock_enable(GPIO_RCC(SIGNAL_PD_PIN)); // enable clock for port domain
gpio_set(GPIO_PORT(SIGNAL_PD_PIN), GPIO_PIN(SIGNAL_PD_PIN)); // ensure we are not draining it
gpio_set_output_options(GPIO_PORT(SIGNAL_PD_PIN), GPIO_OTYPE_OD, GPIO_OSPEED_2MHZ, GPIO_PIN(SIGNAL_PD_PIN)); // set output as open-drain
gpio_mode_setup(GPIO_PORT(SIGNAL_PD_PIN), GPIO_MODE_OUTPUT, GPIO_PUPD_NONE, GPIO_PIN(SIGNAL_PD_PIN)); // configure pin as output
rcc_periph_clock_enable(GPIO_RCC(SIGNAL_PU_PIN)); // enable clock for port domain
gpio_set(GPIO_PORT(SIGNAL_PU_PIN), GPIO_PIN(SIGNAL_PU_PIN)); // ensure we are do enable pMOS to pull up the signal
gpio_set_output_options(GPIO_PORT(SIGNAL_PU_PIN), GPIO_OTYPE_OD, GPIO_OSPEED_2MHZ, GPIO_PIN(SIGNAL_PU_PIN)); // set output as open-drain
gpio_mode_setup(GPIO_PORT(SIGNAL_PU_PIN), GPIO_MODE_OUTPUT, GPIO_PUPD_NONE, GPIO_PIN(SIGNAL_PU_PIN)); // configure pin as output
rcc_periph_clock_enable(GPIO_RCC(SHIFT_EN_PIN)); // enable clock for port domain
gpio_set(GPIO_PORT(SHIFT_EN_PIN), GPIO_PIN(SHIFT_EN_PIN)); // ensure we do not enable pMOS to power level shifters
gpio_set_output_options(GPIO_PORT(SHIFT_EN_PIN), GPIO_OTYPE_OD, GPIO_OSPEED_2MHZ, GPIO_PIN(SHIFT_EN_PIN)); // set output as open-drain
gpio_mode_setup(GPIO_PORT(SHIFT_EN_PIN), GPIO_MODE_OUTPUT, GPIO_PUPD_NONE, GPIO_PIN(SHIFT_EN_PIN)); // configure pin as output
rcc_periph_clock_enable(GPIO_RCC(TARGET_3V_PIN)); // enable clock for port domain
gpio_set(GPIO_PORT(TARGET_3V_PIN), GPIO_PIN(TARGET_3V_PIN)); // ensure we do not enable pMOS to provide 3.3V on target voltage
gpio_set_output_options(GPIO_PORT(TARGET_3V_PIN), GPIO_OTYPE_OD, GPIO_OSPEED_2MHZ, GPIO_PIN(TARGET_3V_PIN)); // set output as open-drain
gpio_mode_setup(GPIO_PORT(TARGET_3V_PIN), GPIO_MODE_OUTPUT, GPIO_PUPD_NONE, GPIO_PIN(TARGET_3V_PIN)); // configure pin as output
rcc_periph_clock_enable(GPIO_RCC(TARGET_RST_PIN)); // enable clock for port domain
gpio_set(GPIO_PORT(TARGET_RST_PIN), GPIO_PIN(TARGET_RST_PIN)); // to not pull down (asserting reset)
gpio_set_output_options(GPIO_PORT(TARGET_RST_PIN), GPIO_OTYPE_OD, GPIO_OSPEED_2MHZ, GPIO_PIN(TARGET_RST_PIN)); // set output as open-drain
gpio_mode_setup(GPIO_PORT(TARGET_RST_PIN), GPIO_MODE_OUTPUT, GPIO_PUPD_NONE, GPIO_PIN(TARGET_RST_PIN)); // configure pin as output
puts_debug("OK\n");
puts_debug("setup analog multiplexer: ");
rcc_periph_clock_enable(GPIO_RCC(MUX_EN_PIN)); // enable clock for port domain
gpio_set(GPIO_PORT(MUX_EN_PIN), GPIO_PIN(MUX_EN_PIN)); // ensure multiplexer is disabled
gpio_set_output_options(GPIO_PORT(MUX_EN_PIN), GPIO_OTYPE_PP, GPIO_OSPEED_2MHZ, GPIO_PIN(MUX_EN_PIN)); // set output as push-pull to drive correctly
gpio_mode_setup(GPIO_PORT(MUX_EN_PIN), GPIO_MODE_OUTPUT, GPIO_PUPD_NONE, GPIO_PIN(MUX_EN_PIN)); // configure pin as output
rcc_periph_clock_enable(GPIO_RCC(MUX_S0_PIN)); // enable clock for port domain
gpio_clear(GPIO_PORT(MUX_S0_PIN), GPIO_PIN(MUX_S0_PIN)); // any channel selected is fine
gpio_set_output_options(GPIO_PORT(MUX_S0_PIN), GPIO_OTYPE_PP, GPIO_OSPEED_2MHZ, GPIO_PIN(MUX_S0_PIN)); // set output as push-pull to drive correctly
gpio_mode_setup(GPIO_PORT(MUX_S0_PIN), GPIO_MODE_OUTPUT, GPIO_PUPD_NONE, GPIO_PIN(MUX_S0_PIN)); // configure pin as output
rcc_periph_clock_enable(GPIO_RCC(MUX_S1_PIN)); // enable clock for port domain
gpio_clear(GPIO_PORT(MUX_S1_PIN), GPIO_PIN(MUX_S1_PIN)); // any channel selected is fine
gpio_set_output_options(GPIO_PORT(MUX_S1_PIN), GPIO_OTYPE_PP, GPIO_OSPEED_2MHZ, GPIO_PIN(MUX_S1_PIN)); // set output as push-pull to drive correctly
gpio_mode_setup(GPIO_PORT(MUX_S1_PIN), GPIO_MODE_OUTPUT, GPIO_PUPD_NONE, GPIO_PIN(MUX_S1_PIN)); // configure pin as output
rcc_periph_clock_enable(GPIO_RCC(MUX_S2_PIN)); // enable clock for port domain
gpio_clear(GPIO_PORT(MUX_S2_PIN), GPIO_PIN(MUX_S2_PIN)); // any channel selected is fine
gpio_set_output_options(GPIO_PORT(MUX_S2_PIN), GPIO_OTYPE_PP, GPIO_OSPEED_2MHZ, GPIO_PIN(MUX_S2_PIN)); // set output as push-pull to drive correctly
gpio_mode_setup(GPIO_PORT(MUX_S2_PIN), GPIO_MODE_OUTPUT, GPIO_PUPD_NONE, GPIO_PIN(MUX_S2_PIN)); // configure pin as output
rcc_periph_clock_enable(GPIO_RCC(MUX_S3_PIN)); // enable clock for port domain
gpio_clear(GPIO_PORT(MUX_S3_PIN), GPIO_PIN(MUX_S3_PIN)); // any channel selected is fine
gpio_set_output_options(GPIO_PORT(MUX_S3_PIN), GPIO_OTYPE_PP, GPIO_OSPEED_2MHZ, GPIO_PIN(MUX_S3_PIN)); // set output as push-pull to drive correctly
gpio_mode_setup(GPIO_PORT(MUX_S3_PIN), GPIO_MODE_OUTPUT, GPIO_PUPD_NONE, GPIO_PIN(MUX_S3_PIN)); // configure pin as output
mux_select(-1); // ensure it is disabled
puts_debug("OK\n");
puts_debug("setup signal pins: ");
for (uint8_t i = 0; i < CHANNEL_NUMBERS; i++) {
rcc_periph_clock_enable(port2rcc(channel_ports[i])); // enable clock for port domain
gpio_mode_setup(channel_ports[i], GPIO_MODE_INPUT, GPIO_PUPD_NONE, channel_pins[i]); // ensure pin is floating input
}
puts_debug("OK\n");
puts_debug("setup ADC to measure voltages: ");
rcc_periph_clock_enable(RCC_ADC1); // enable clock for ADC domain
adc_power_off(ADC1); // switch off ADC while configuring it
adc_set_right_aligned(ADC1); // ensure it is right aligned to get the actual value in the 16-bit register
adc_enable_scan_mode(ADC1); // use scan mode do be able to go to next discontinuous subgroup of the regular sequence
adc_enable_discontinuous_mode_regular(ADC1, 1); // use discontinuous mode (to go through all channels of the group, one after another)
adc_set_single_conversion_mode(ADC1); // ensure continuous mode is not used (that's not the same as discontinuous)
adc_eoc_after_each(ADC1); // set EOC after each conversion instead of each group
adc_set_sample_time_on_all_channels(ADC1, ADC_SMPR_SMP_28CYC); // use at least 15 cycles to be able to sample at 12-bit resolution
adc_set_regular_sequence(ADC1, LENGTH(adc_channels), (uint8_t*)adc_channels); // set channel to convert
adc_enable_temperature_sensor(); // enable internal voltage reference
adc_power_on(ADC1); // switch on ADC
sleep_us(3); // wait t_stab for the ADC to stabilize
rcc_periph_clock_enable(RCC_ADC1_IN(TARGET_CHANNEL)); // enable clock for GPIO domain for target voltage channel
gpio_mode_setup(ADC1_IN_PORT(TARGET_CHANNEL), GPIO_MODE_ANALOG, GPIO_PUPD_NONE, ADC1_IN_PIN(TARGET_CHANNEL)); // set target voltage channel as analog input for the ADC
rcc_periph_clock_enable(RCC_ADC1_IN(SIGNAL_CHANNEL)); // enable clock for GPIO domain for signal channel
gpio_mode_setup(ADC1_IN_PORT(SIGNAL_CHANNEL), GPIO_MODE_ANALOG, GPIO_PUPD_NONE, ADC1_IN_PIN(SIGNAL_CHANNEL)); // set signal channel as analog input for the ADC
measure_voltages(); // try to measure voltages
puts_debug("OK\n");
// setup terminal
terminal_prefix = ""; // set default prefix
terminal_process = &process_command; // set central function to process commands
terminal_setup(); // start terminal
// start main loop
bool action = false; // if an action has been performed don't go to sleep
button_flag = false; // reset button flag
while (true) { // infinite loop
iwdg_reset(); // kick the dog
if (user_input_available) { // user input is available
action = true; // action has been performed
char c = user_input_get(); // store receive character
terminal_send(c); // send received character to terminal
}
if (wakeup_flag) { // time to do periodic checks
wakeup_flag = false; // clear flag
}
if (second_flag) { // one second passed
second_flag = false; // clear flag
}
if (action) { // go to sleep if nothing had to be done, else recheck for activity
action = false;
} else {
__WFI(); // go to sleep
}
} // main loop
}
/** interrupt service routine when the wakeup timer triggered */
void rtc_wkup_isr(void)
{
static uint16_t tick = WAKEUP_FREQ; // how many wakeup have occurred
exti_reset_request(EXTI22); // clear EXTI flag used by wakeup
rtc_clear_wakeup_flag(); // clear flag
wakeup_flag = true; // notify main loop
tick--; // count the number of ticks down (do it in the ISR to no miss any tick)
if (0 == tick) { // count down completed
second_flag = true; // notify main loop a second has passed
tick = WAKEUP_FREQ; // restart count down
}
}