I am programming a Raspberry Pi Pico in C. I have this MWE:
#include "pico/stdlib.h"
#include "pico/cyw43_arch.h"
#include "hardware/uart.h"
#define UART_ID uart0
#define BAUD_RATE 2000000
#define UART_TX_PIN 0
#define UART_RX_PIN 1
uint8_t blink_LED;
void handle_uart_commands() {
// Function to be called when data is received in the UART.
while (uart_is_readable(UART_ID)) {
uint8_t ch = uart_getc(UART_ID);
switch (ch) {
case 'b':
printf("%d", blink_LED); // This sends "0", ok!
blink_LED = 7;
printf("%d", blink_LED); // This sends "7", ok!
break;
}
}
}
void init_uart(void) {
uart_init(UART_ID, BAUD_RATE);
gpio_set_function(UART_TX_PIN, UART_FUNCSEL_NUM(UART_ID, UART_TX_PIN));
gpio_set_function(UART_RX_PIN, UART_FUNCSEL_NUM(UART_ID, UART_RX_PIN));
// Set up a RX interrupt:
int UART_IRQ = UART_ID == uart0 ? UART0_IRQ : UART1_IRQ; // Select correct interrupt for the UART we are using.
irq_set_exclusive_handler(UART_IRQ, handle_uart_commands);
irq_set_enabled(UART_IRQ, true);
uart_set_irq_enables(UART_ID, true, false);
}
void init_stuff(void) {
stdio_init_all();
init_uart();
hard_assert(cyw43_arch_init() == PICO_OK);
blink_LED = 3;
}
int main() {
init_stuff();
while (true) {
if (blink_LED) {
cyw43_arch_gpio_put(CYW43_WL_GPIO_LED_PIN, 1);
sleep_ms(333);
cyw43_arch_gpio_put(CYW43_WL_GPIO_LED_PIN, 0);
sleep_ms(333);
blink_LED -= 1;
printf("b"); // Indicate that the LED blinked once.
}
}
}
What it is supposed to do:
- Blink the LED 3 times upon power on.
- Upon receiving
b
through the UART serial communication, it should blink the LED 7 times.
What it does:
- Blinks the LED 3 times upon power on. Ok!
- Upon receiving
b
, the LED does not blink a single time. Not ok.
I added the two printf
lines just to see the value of blink_LED
, and it sends the right values, meaning it is receiving and correctly processing b
. However, the LED does not blink. Moreover, the printf("b")
line is only executed 3 times after power on, meaning it never goes back into the if (blink_LED)
. I don’t understand why. Is the value of blink_LED=7
somehow only valid within handle_uart_commands
and after that it returns to the previous value?
3