On the Pico, this works well:
Code:
// Menus - state machine using pointer to function// you can set up a callback function to handle user input asynchronously#include "pico/printf.h"#include "pico/stdio.h"#include "pico/time.h"// #include <stdio.h>volatile bool input_available = false; // Flag to indicate if input is availablevolatile char input_char = 0; // Variable to store the input character// Define function prototypes for state-handler functionsvoid mainMenu();void exitMenu();void state1();void state2();// Define function prototypes for character input callbackchar getInputChar();void inputCallback();// Pointer to the current state-handler functionvoid (*currentState)() = mainMenu;void inputCallback(void *param) { input_available = true; // Set the flag to indicate input is available input_char = getchar(); // Read the input character}char getInputChar() { input_available = false; // Reset the input flag return input_char; // Return the input character}// Main menu state-handler functionvoid mainMenu() { printf("\n\nExample Menu:\n"); printf("1. Choice One\n"); printf("2. Choice Two\n"); int choice; printf("Enter your choice (1 or 2): "); while (!input_available) { sleep_ms(10); // Wait for input to be available } choice = getInputChar() - '0'; // Convert char to int // switch calls state function switch (choice) { case 1: currentState = state1; break; case 2: currentState = state2; break; default: printf("Invalid choice"); sleep_ms(1000); break; }}// example, state 1 (do work)void state1() { printf("state 1, do stuff here"); sleep_ms(1000); currentState = mainMenu;}// example, state 2 (other work)void state2() { printf("state 2, do other stuff here"); sleep_ms(1000); currentState = mainMenu;}int main() { stdio_init_all(); // set up serial sleep_ms(2000); // give serial time to init? stdio_set_chars_available_callback(inputCallback, NULL); // Set the input callback // do the state-handler forever while (1) { currentState(); } return 0;}
Statistics: Posted by breaker — Sat Apr 06, 2024 1:49 am