stm32f1/application.c

787 lines
29 KiB
C

/** clock generator, using AD9850
* @file
* @author King Kévin <kingkevin@cuvoodoo.info>
* @copyright SPDX-License-Identifier: GPL-3.0-or-later
* @date 2016-2022
*/
/* 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> // float 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/exti.h> // external interrupt defines
/* 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 "lcd_hd44780.h" // LCD display
/** 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;
/** connection to AD9850 */
#define AD9850_DATA PA7
#define AD9850_FQUD PA6
#define AD9850_WCLK PA5
//#define AD9850_D0 PA0
//#define AD9850_D1 PA1
//#define AD9850_D2 PA2
/** AD9850 frequency to set (in mHz) */
static uint64_t ad9850_freq = 0;
/** maximum frequency (in mHz) */
#define AD9850_MAX_FREQ 125000000000ULL
/** connections to rotary encoder (common is ground) */
#define ROTARY_A PA1
#define ROTARY_B PA2
static volatile int8_t rotary_flag = 0; /** flag set when rotary encoder is turned (1 = CW, -1 = CCW) */
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
uart_putchar_nonblocking('\r'); // send CR over USART
usb_cdcacm_putchar('\r'); // send CR over USB
length++; // remember we printed 1 character
}
}
uart_putchar_nonblocking(c); // send byte over USART
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
/** 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);
}
/** show date and time
* @param[in] argument date and time to set
*/
static void command_datetime(void* argument)
{
char* datetime = (char*)argument; // argument is optional date time
const char* days[] = { "??", "Mo", "Tu", "We", "Th", "Fr", "Sa", "Su"}; // the days of the week
// set date
if (datetime) { // date has been provided
// parse date
const char* malformed = "date and time malformed, expecting YYYY-MM-DD WD HH:MM:SS\n";
if (strlen(datetime) != (4 + 1 + 2 + 1 + 2) + 1 + 2 + 1 + (2 + 1 + 2 + 1 + 2)) { // verify date/time is long enough
printf(malformed);
return;
}
if (!(isdigit((int8_t)datetime[0]) && isdigit((int8_t)datetime[1]) && isdigit((int8_t)datetime[2]) && isdigit((int8_t)datetime[3]) && \
'-' == datetime[4] && \
isdigit((int8_t)datetime[5]) && isdigit((int8_t)datetime[6]) && \
'-' == datetime[7] && \
isdigit((int8_t)datetime[8]) && isdigit((int8_t)datetime[9]) && \
' ' == datetime[10] && \
isalpha((int8_t)datetime[11]) && isalpha((int8_t)datetime[12]) && \
' ' == datetime[13] && \
isdigit((int8_t)datetime[14]) && isdigit((int8_t)datetime[15]) && \
':' == datetime[16] && \
isdigit((int8_t)datetime[17]) && isdigit((int8_t)datetime[18]) && \
':' == datetime[19] && \
isdigit((int8_t)datetime[20]) && isdigit((int8_t)datetime[21]))) { // verify format (good enough to not fail parsing)
printf(malformed);
return;
}
const uint16_t year = strtol(&datetime[0], NULL, 10); // parse year
if (year <= 2000 || year > 2099) {
puts("year out of range\n");
return;
}
const uint8_t month = strtol(&datetime[5], NULL, 10); // parse month
if (month < 1 || month > 12) {
puts("month out of range\n");
return;
}
const uint8_t day = strtol(&datetime[8], NULL, 10); // parse day
if (day < 1 || day > 31) {
puts("day out of range\n");
return;
}
const uint8_t hour = strtol(&datetime[14], NULL, 10); // parse hour
if (hour > 24) {
puts("hour out of range\n");
return;
}
const uint8_t minute = strtol(&datetime[17], NULL, 10); // parse minutes
if (minute > 59) {
puts("minute out of range\n");
return;
}
const uint8_t second = strtol(&datetime[30], NULL, 10); // parse seconds
if (second > 59) {
puts("second out of range\n");
return;
}
uint8_t week_day = 0;
for (uint8_t i = 1; i < LENGTH(days) && 0 == week_day; i++) {
if (days[i][0] == toupper(datetime[11]) && days[i][1] == tolower(datetime[12])) {
week_day = i;
break;
}
}
if (0 == week_day) {
puts("unknown week day\n");
return;
}
uint32_t date = 0; // to build the date
date |= (((year - 2000) / 10) & RTC_DR_YT_MASK) << RTC_DR_YT_SHIFT; // set year tenth
date |= (((year - 2000) % 10) & RTC_DR_YU_MASK) << RTC_DR_YU_SHIFT; // set year unit
date |= ((month / 10) & RTC_DR_MT_MASK) << RTC_DR_MT_SHIFT; // set month tenth
date |= ((month % 10) & RTC_DR_MU_MASK) << RTC_DR_MU_SHIFT; // set month unit
date |= ((day / 10) & RTC_DR_DT_MASK) << RTC_DR_DT_SHIFT; // set day tenth
date |= ((day % 10) & RTC_DR_DU_MASK) << RTC_DR_DU_SHIFT; // set day unit
date |= (week_day & RTC_DR_WDU_MASK) << RTC_DR_WDU_SHIFT; // time day of the week
uint32_t time = 0; // to build the time
time = 0; // reset time
time |= ((hour / 10) & RTC_TR_HT_MASK) << RTC_TR_HT_SHIFT; // set hour tenth
time |= ((hour % 10) & RTC_TR_HU_MASK) << RTC_TR_HU_SHIFT; // set hour unit
time |= ((minute / 10) & RTC_TR_MNT_MASK) << RTC_TR_MNT_SHIFT; // set minute tenth
time |= ((minute % 10) & RTC_TR_MNU_MASK) << RTC_TR_MNU_SHIFT; // set minute unit
time |= ((second / 10) & RTC_TR_ST_MASK) << RTC_TR_ST_SHIFT; // set second tenth
time |= ((second % 10) & RTC_TR_SU_MASK) << RTC_TR_SU_SHIFT; // set second unit
// write date
pwr_disable_backup_domain_write_protect(); // disable backup protection so we can set the RTC clock source
rtc_unlock(); // enable writing RTC registers
RTC_ISR |= RTC_ISR_INIT; // enter initialisation mode
while (!(RTC_ISR & RTC_ISR_INITF)); // wait to enter initialisation mode
RTC_DR = date; // set date
RTC_TR = time; // set time
RTC_ISR &= ~RTC_ISR_INIT; // exit initialisation mode
rtc_lock(); // protect RTC register against writing
pwr_enable_backup_domain_write_protect(); // re-enable protection now that we configured the RTC clock
}
// show date
if (!(RTC_ISR & RTC_ISR_INITS)) { // date has not been set yet
puts("date/time not initialized\n");
} else {
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
const 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
const 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
const uint8_t week_day = ((RTC_DR >> RTC_DR_WDU_SHIFT) & RTC_DR_WDU_MASK); // get week day
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
printf("date: 20%02d-%02d-%02d %s %02d:%02d:%02d\n", year, month, day, days[week_day], hour, minute, second);
}
}
/** 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
}
/** set AD9850 output frequency
* @param[in] frequency frequency to set (in Hz)
* @return actual frequency set (in Hz)
* @note a frequency of 0 disables the output
*/
static double ad9850_set_freq(double frequency)
{
if (frequency > AD9850_MAX_FREQ / 1000) {
frequency = AD9850_MAX_FREQ / 1000;
} else if (frequency < 0) {
frequency = 0;
}
// start with default state
gpio_clear(GPIO_PORT(AD9850_WCLK), GPIO_PIN(AD9850_WCLK));
gpio_clear(GPIO_PORT(AD9850_FQUD), GPIO_PIN(AD9850_FQUD));
// enable serial mode (W0 must we xxxxx011, D0=1, D1=1, D2=0)
gpio_set(GPIO_PORT(AD9850_WCLK), GPIO_PIN(AD9850_WCLK));
sleep_us(1); // tWH = 3.5 ns
gpio_clear(GPIO_PORT(AD9850_WCLK), GPIO_PIN(AD9850_WCLK));
gpio_set(GPIO_PORT(AD9850_FQUD), GPIO_PIN(AD9850_FQUD));
sleep_us(1); // tFH = 7 ns
gpio_clear(GPIO_PORT(AD9850_FQUD), GPIO_PIN(AD9850_FQUD));
// shift out data
const uint32_t freq = round(frequency * 0xffffffff / 125E6); // output 100 kHz
const uint8_t control = 0; // must be 0 for serial data
uint8_t power_down = 0; // power up
if (0 == frequency) {
power_down = 1;
}
const uint8_t phase = 0;
uint64_t shift_out = ((uint64_t)freq << 0) | ((uint64_t)control << 32) | ((uint64_t)power_down << 34) | ((uint64_t)phase << 35); // data to be shifted out
for (uint8_t b = 0; b < 40; b++) { // shift out data, LSb first
if (shift_out & 0x01) {
gpio_set(GPIO_PORT(AD9850_DATA), GPIO_PIN(AD9850_DATA));
} else {
gpio_clear(GPIO_PORT(AD9850_DATA), GPIO_PIN(AD9850_DATA));
}
sleep_us(1); // tDS = 3.5 ns
gpio_set(GPIO_PORT(AD9850_WCLK), GPIO_PIN(AD9850_WCLK));
sleep_us(1); // tWH = 3.5 ns
gpio_clear(GPIO_PORT(AD9850_WCLK), GPIO_PIN(AD9850_WCLK));
sleep_us(1); // tWL = 3.5 ns
// tDH = 3.5ns
shift_out >>= 1; // prepare next bit
}
// latch data
// tFD = 7.0 ns
gpio_set(GPIO_PORT(AD9850_FQUD), GPIO_PIN(AD9850_FQUD));
sleep_us(1); // tFH = 7.0 ns
gpio_clear(GPIO_PORT(AD9850_FQUD), GPIO_PIN(AD9850_FQUD));
sleep_us(1); // tFL = 7.0 ns
return freq * (125E6 / 0xffffffff);
}
/** set AD9850 output frequency */
static void command_freq(void* argument)
{
if (argument) {
ad9850_freq = *(double*)argument * 1000.0; // get user provided frequency
}
const double freq = ad9850_set_freq(ad9850_freq / 1000.0); // set frequency and get the one set
printf("frequency set to %0.3f Hz\n", freq);
}
/** 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 = 'd',
.name = "date",
.command_description = "show/set date and time",
.argument = MENU_ARGUMENT_STRING,
.argument_description = "[YYYY-MM-DD HH:MM:SS]",
.command_handler = &command_datetime,
},
{
.shortcut = 'r',
.name = "reset",
.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 = 'f',
.name = "frequency",
.command_description = "set output frequency",
.argument = MENU_ARGUMENT_FLOAT,
.argument_description = "[Hz]",
.command_handler = &command_freq,
},
};
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");
}
}
/** create 16 char representation of number
* @number number to represent
* @return 16 char representation
*/
static char* freq2s(uint64_t freq)
{
static char line[16 + 1];
for (uint8_t i = 0; i < LENGTH(line) - 1; i++) {
line[i] = ' '; // clear line
}
line[LENGTH(line) - 1] = '\0'; // terminate string
bool zero_padding = false;
uint64_t divider = 100000000000UL;
uint8_t pos = 1; // position in the line
for (uint8_t d = 0; d < 12; d++) {
if (3 == d || 6 == d) {
if (zero_padding) {
line[pos] = ','; // add separator
}
pos++;
} else if (9 == d) {
if (zero_padding) {
line[pos] = '.'; // add separator
}
pos++;
}
if (8 == d) {
zero_padding = true; // enforce hertz unit display
}
const uint8_t digit = (freq / divider) % 10;
if (digit > 0) {
line[pos] = '0' + digit; // set digit
zero_padding = true; // remember to pad with zeros now
} else if (zero_padding) {
line[pos] = '0';
} else {
line[pos] = ' ';
}
divider /= 10; // go to next digit
pos++; // go to next position
}
return line;
}
static void update_display(uint64_t freq, uint8_t position, bool selected)
{
const uint8_t position2cursor_lut[] = {0x47, 0x46, 0x45, 0x43, 0x42, 0x41, 0x07, 0x06, 0x05, 0x03, 0x02, 0x01};
if (position >= LENGTH(position2cursor_lut)) {
position = LENGTH(position2cursor_lut) - 1;
}
const char* line = freq2s(freq); // get frequency representation
lcd_hd44780_write_line(0, &line[0], 8); // display set frequency
lcd_hd44780_write_line(1, &line[8], 8); // display set frequency
lcd_hd44780_set_ddram_address(position2cursor_lut[position]); // set cursor position
lcd_hd44780_display_control(true, true, selected);
}
/** load settings from SRAM */
static void load_settings(uint8_t* position, uint64_t* frequency)
{
if (position) {
*position = RTC_BKPXR(0);
if (*position >= 12) {
*position = 11;
}
}
if (frequency) {
*frequency = (RTC_BKPXR(1) << 0) + ((uint64_t)RTC_BKPXR(2) << 32);
if (*frequency > AD9850_MAX_FREQ) {
*frequency = AD9850_MAX_FREQ;
}
}
}
/** save settings to SRAM */
static void save_settings(uint8_t position, uint64_t frequency)
{
if (position >= 12) {
position = 11;
}
RTC_BKPXR(0) = position;
if (frequency > AD9850_MAX_FREQ) {
frequency = AD9850_MAX_FREQ;
}
RTC_BKPXR(1) = frequency >> 0;
RTC_BKPXR(2) = frequency >> 32;
}
/** 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
uart_setup(); // setup USART (for printing)
usb_cdcacm_setup(); // setup USB CDC ACM (for printing)
puts("\nwelcome to the CuVoodoo clock generator\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_debug("reset cause(s):");
if (RCC_CSR & RCC_CSR_LPWRRSTF) {
puts_debug(" low-power");
}
if (RCC_CSR & RCC_CSR_WWDGRSTF) {
puts_debug(" window-watchdog");
}
if (RCC_CSR & RCC_CSR_IWDGRSTF) {
puts_debug(" independent-watchdog");
}
if (RCC_CSR & RCC_CSR_SFTRSTF) {
puts_debug(" software");
}
if (RCC_CSR & RCC_CSR_PORRSTF) {
puts_debug(" POR/PDR");
}
if (RCC_CSR & RCC_CSR_PINRSTF) {
puts_debug(" pin");
}
puts_debug("\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
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
#if defined(MINIF401)
rcc_osc_on(RCC_LSE); // enable LSE clock
while (!rcc_is_osc_ready(RCC_LSE)); // wait until clock is ready
rtc_set_prescaler(256, 128); // set clock prescaler to 32768
RCC_BDCR = (RCC_BDCR & ~(RCC_BDCR_RTCSEL_MASK << RCC_BDCR_RTCSEL_SHIFT)) | (RCC_BDCR_RTCSEL_LSE << RCC_BDCR_RTCSEL_SHIFT); // select LSE as RTC clock source
#else
rcc_osc_on(RCC_LSI); // enable LSI clock
while (!rcc_is_osc_ready(RCC_LSI)); // wait until clock is ready
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
#endif
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
#if defined(MINIF401)
rtc_set_wakeup_time((32768 / 2) / WAKEUP_FREQ - 1, RTC_CR_WUCLKSEL_RTC_DIV2); // set wakeup time based on LSE (keep highest precision, also enables the wakeup timer)
#else
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)
#endif
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 rotary encoder: ");
rcc_periph_clock_enable(GPIO_RCC(ROTARY_B)); // enable clock for button
gpio_mode_setup(GPIO_PORT(ROTARY_B), GPIO_MODE_INPUT, GPIO_PUPD_PULLUP, GPIO_PIN(ROTARY_B)); // set GPIO to input and pull up
rcc_periph_clock_enable(GPIO_RCC(ROTARY_A)); // enable clock for button
gpio_mode_setup(GPIO_PORT(ROTARY_A), GPIO_MODE_INPUT, GPIO_PUPD_PULLUP, GPIO_PIN(ROTARY_A)); // set GPIO to input and pull up
exti_select_source(GPIO_EXTI(ROTARY_A), GPIO_PORT(ROTARY_A)); // mask external interrupt of this pin only for this port
exti_set_trigger(GPIO_EXTI(ROTARY_A), EXTI_TRIGGER_FALLING); // trigger when button is pressed
exti_enable_request(GPIO_EXTI(ROTARY_A)); // enable external interrupt
nvic_enable_irq(GPIO_NVIC_EXTI_IRQ(ROTARY_A)); // enable interrupt
uint8_t digit_position = 0; // which digit is selected
load_settings(&digit_position, NULL); // load saved position
bool digit_selected = false; // if a digit is selected
puts_debug("OK\n");
puts_debug("setup AD9850: ");
rcc_periph_clock_enable(GPIO_RCC(AD9850_DATA)); // enable clock for GPIO
gpio_clear(GPIO_PORT(AD9850_DATA), GPIO_PIN(AD9850_DATA)); // don't care about data
gpio_mode_setup(GPIO_PORT(AD9850_DATA), GPIO_MODE_OUTPUT, GPIO_PUPD_NONE, GPIO_PIN(AD9850_DATA)); // set pin as output
gpio_set_output_options(GPIO_PORT(AD9850_DATA), GPIO_OTYPE_PP, GPIO_OSPEED_2MHZ, GPIO_PIN(AD9850_DATA)); // set output as push-pull
rcc_periph_clock_enable(GPIO_RCC(AD9850_WCLK)); // enable clock for GPIO
gpio_clear(GPIO_PORT(AD9850_WCLK), GPIO_PIN(AD9850_WCLK)); // idle low
gpio_mode_setup(GPIO_PORT(AD9850_WCLK), GPIO_MODE_OUTPUT, GPIO_PUPD_NONE, GPIO_PIN(AD9850_WCLK)); // set pin as output
gpio_set_output_options(GPIO_PORT(AD9850_WCLK), GPIO_OTYPE_PP, GPIO_OSPEED_2MHZ, GPIO_PIN(AD9850_WCLK)); // set output as push-pull
rcc_periph_clock_enable(GPIO_RCC(AD9850_FQUD)); // enable clock for GPIO
gpio_clear(GPIO_PORT(AD9850_FQUD), GPIO_PIN(AD9850_FQUD)); // idle low
gpio_mode_setup(GPIO_PORT(AD9850_FQUD), GPIO_MODE_OUTPUT, GPIO_PUPD_NONE, GPIO_PIN(AD9850_FQUD)); // set pin as output
gpio_set_output_options(GPIO_PORT(AD9850_FQUD), GPIO_OTYPE_PP, GPIO_OSPEED_2MHZ, GPIO_PIN(AD9850_FQUD)); // set output as push-pull
load_settings(NULL, &ad9850_freq); // load saved frequency
ad9850_set_freq(ad9850_freq);
puts_debug("OK\n");
puts_debug("setup HD44780 LCD: ");
lcd_hd44780_setup(true, false); // I don't know why the initialisation does not always works the first time (but replugging the power in solveds it)
update_display(ad9850_freq, digit_position, digit_selected);
puts_debug("OK\n");
load_settings(&digit_position, &ad9850_freq);
// 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
led_on(); // switch LED to indicate booting completed
while (true) { // infinite loop
iwdg_reset(); // kick the dog
if (user_input_available) { // user input is available
action = true; // action has been performed
led_toggle(); // toggle LED
char c = user_input_get(); // store receive character
terminal_send(c); // send received character to terminal
}
if (button_flag) { // user pressed button
action = true; // action has been performed
sleep_ms(10); // debounce
if (!gpio_get(GPIO_PORT(BUTTON_PIN), GPIO_PIN(BUTTON_PIN))) { // only allow press (not release)
digit_selected = !digit_selected;
update_display(ad9850_freq, digit_position, digit_selected);
}
sleep_ms(100); // wait a bit to remove noise and double trigger
button_flag = false; // reset flag
}
if (rotary_flag) { // user turned rotary encoder
action = true; // action has been performed
if (rotary_flag > 0) {
if (digit_selected) {
uint64_t unit = 1;
for (uint8_t i = 0; i < digit_position; i++) {
unit *= 10;
}
ad9850_freq += unit;
if (ad9850_freq > AD9850_MAX_FREQ) {
ad9850_freq = AD9850_MAX_FREQ;
}
} else {
if (digit_position > 0) {
digit_position--;
}
}
} else {
if (digit_selected) {
uint64_t unit = 1;
for (uint8_t i = 0; i < digit_position; i++) {
unit *= 10;
}
if (unit > ad9850_freq) {
ad9850_freq = 0;
} else {
ad9850_freq -= unit;
}
} else {
if (digit_position < 11) {
digit_position++;
}
}
}
save_settings(digit_position, ad9850_freq); // save setting to SRAM
ad9850_set_freq(ad9850_freq / 1000.0); // reset frequency (in case the target has been reset)
update_display(ad9850_freq, digit_position, digit_selected);
sleep_ms(100); // wait a bit to remove noise and double trigger
rotary_flag = 0; // reset flag
}
if (wakeup_flag) { // time to do periodic checks
wakeup_flag = false; // clear flag
}
if (second_flag) { // one second passed
second_flag = false; // clear flag
action = true; // action has been performed
ad9850_set_freq(ad9850_freq / 1000.0); // reset frequency (in case the target has been reset)
update_display(ad9850_freq, digit_position, digit_selected);
led_toggle(); // toggle LED to indicate if main function is stuck
}
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
}
}
/** interrupt service routine called when rotary encoder is turned */
void GPIO_EXTI_ISR(ROTARY_A)(void)
{
exti_reset_request(GPIO_EXTI(ROTARY_A)); // reset interrupt
if (rotary_flag) { // flag not cleared yet
return;
} else if (gpio_get(GPIO_PORT(ROTARY_B), GPIO_PIN(ROTARY_B))) {
rotary_flag = 1;
} else {
rotary_flag = -1;
}
}