SomeFreeRTOSExamples/examples/ex2_read_input/main.c

46 lines
1.4 KiB
C

#include <stdio.h>
#include "pico/stdlib.h"
#include "FreeRTOS.h"
#include "task.h"
void usbInputTask(void *params) {
char inputBuffer[100];
int bufferIndex = 0;
while (1) {
// Check if a character is available from USB
if (stdio_usb_connected()) { // Make sure USB is connected
int ch = getchar_timeout_us(0); // Non-blocking read
if (ch != PICO_ERROR_TIMEOUT) { // Data available
if (ch == '\n' || ch == '\r') {
if (ch == '\r') {
putchar('\n');
}
inputBuffer[bufferIndex] = '\0'; // Null-terminate the string
// Parse the buffer as needed
int value;
if (sscanf(inputBuffer, "%d", &value) == 1) {
printf("Received integer: %d\n", value);
}
bufferIndex = 0; // Reset buffer index for next input
} else if (bufferIndex < sizeof(inputBuffer) - 1) {
inputBuffer[bufferIndex++] = ch;
putchar(ch);
}
}
}
vTaskDelay(10 / portTICK_PERIOD_MS); // Small delay to prevent task hogging
}
}
int main() {
stdio_init_all(); // Initialize stdio over USB
xTaskCreate(usbInputTask, "USB Input", 1024, NULL, 1, NULL);
vTaskStartScheduler(); // Start FreeRTOS scheduler
for (;;);
}