Compare commits

...

9 Commits

Author SHA1 Message Date
Adolfo Reyna
eb0156bb9d improve logging 2025-12-10 13:41:39 -05:00
Adolfo Reyna
f197b9c1f4 fix wifi & flash + eink screen on core 1, by using queue 2025-12-10 13:38:04 -05:00
Adolfo Reyna
65650a7b57 wifi working tested on hardware 2025-12-10 08:09:38 -05:00
Adolfo Reyna
47956bf64c refactoring into multiple files, not tested on hardware 2025-12-09 18:41:03 -05:00
Adolfo Reyna
bc0e082b89 starting with commands 2025-12-09 18:30:42 -05:00
Adolfo Reyna
b200ba075b working by line 2025-12-09 11:18:44 -05:00
Adolfo Reyna
2738c4ac3d smooth refresh with aggregated changes 2025-11-29 23:33:02 -05:00
Adolfo Reyna
7ebfbcb0fb fix initial usb crash with a delay 2025-11-29 22:59:33 -05:00
Adolfo Reyna
2cb23b70d3 Add USB Keyboard support 2025-11-29 22:55:07 -05:00
15 changed files with 1134 additions and 423 deletions

View File

@@ -35,11 +35,15 @@ pico_sdk_init()
# Add executable. Default name is the project name, version 0.1
if (TARGET tinyusb_device)
if (TARGET tinyusb_host)
add_executable(hello_usb
hello_usb.cpp
display.cpp
commands/echo.cpp
keyboard_input.cpp
command_processor.cpp
epaper_manager.cpp
wifi_manager.cpp
)
add_subdirectory(pico-ssd1306 commands)
@@ -50,6 +54,7 @@ if (TARGET tinyusb_device)
# Add include directories for e-Paper
target_include_directories(hello_usb PRIVATE
${CMAKE_CURRENT_SOURCE_DIR}
${CMAKE_CURRENT_SOURCE_DIR}/Pico_ePaper_Code/c/lib/Config
${CMAKE_CURRENT_SOURCE_DIR}/Pico_ePaper_Code/c/lib/e-Paper
${CMAKE_CURRENT_SOURCE_DIR}/Pico_ePaper_Code/c/lib/Fonts
@@ -57,11 +62,11 @@ if (TARGET tinyusb_device)
)
# pull in common dependencies
target_link_libraries(hello_usb pico_stdlib pico_ssd1306 hardware_i2c Config ePaper GUI Fonts hardware_spi pico_multicore)
target_link_libraries(hello_usb pico_stdlib pico_ssd1306 hardware_i2c Config ePaper GUI Fonts hardware_spi pico_multicore pico_flash tinyusb_host tinyusb_board pico_cyw43_arch_lwip_threadsafe_background)
# enable usb output, disable uart output
pico_enable_stdio_usb(hello_usb 1)
pico_enable_stdio_uart(hello_usb 0)
pico_enable_stdio_usb(hello_usb 0)
pico_enable_stdio_uart(hello_usb 1)
# create map/bin/hex/uf2 file etc.
pico_add_extra_outputs(hello_usb)

84
DISPLAY_REFRESH.md Normal file
View File

@@ -0,0 +1,84 @@
# Display Refresh Mechanism
This document explains the dual-core architecture used to handle USB keyboard input and e-Paper display updates efficiently on the Raspberry Pi Pico.
## Architecture Overview
The system utilizes both cores of the RP2040 to ensure that the slow refresh rate of the e-Paper display does not block or lag the USB keyboard input.
### Core 0: Input Handling (Producer)
* **Role:** Handles USB Host tasks, processes keyboard reports, and manages the text buffer.
* **Behavior:**
1. Receives key presses via TinyUSB callbacks.
2. Updates the local text buffer (`g_entry_list`).
3. Triggers a display update via `send_display_update()`.
* **Non-Blocking Transmission:**
* When an update is needed, Core 0 allocates a `DisplayMessage` on the heap.
* It attempts to push the message pointer to the Multicore FIFO.
* **Critical Optimization:** It uses `multicore_fifo_wready()` to check if the FIFO has space.
* **If Ready:** Pushes the message.
* **If Full:** Immediately frees the message and skips the update. This ensures Core 0 never waits for Core 1, keeping typing responsive.
### Core 1: Display Driver (Consumer)
* **Role:** Manages the e-Paper hardware and performs the actual drawing operations.
* **Behavior:**
1. Initializes the e-Paper display.
2. Waits for messages in the Multicore FIFO.
* **Smart Refresh (Accumulation):**
* When Core 1 wakes up to process a message, it first checks if *more* messages have arrived while it was sleeping or busy.
* **FIFO Draining:** It loops through the FIFO, popping and freeing all intermediate messages, keeping only the **latest** one.
* This ensures that if the user types "Hello World" quickly, Core 1 might skip rendering "Hello " and jump straight to rendering "Hello World", preventing a queue of obsolete updates from slowing down the display.
## Data Flow Diagram
```mermaid
sequenceDiagram
participant User
participant Core0 as Core 0 (USB/Input)
participant FIFO as Multicore FIFO
participant Core1 as Core 1 (Display)
User->>Core0: Types 'A'
Core0->>FIFO: Push Msg('A')
User->>Core0: Types 'B'
Core0->>FIFO: Push Msg('AB')
Note over Core1: Busy refreshing...
User->>Core0: Types 'C'
alt FIFO is Full
Core0->>Core0: Drop Msg('ABC') (Free memory)
else FIFO has space
Core0->>FIFO: Push Msg('ABC')
end
Core1->>FIFO: Pop Msg('A')
Note over Core1: Checks FIFO for newer msgs
FIFO->>Core1: Msg('AB') exists
Core1->>Core1: Free Msg('A'), use Msg('AB')
FIFO->>Core1: Msg('ABC') exists
Core1->>Core1: Free Msg('AB'), use Msg('ABC')
Core1->>Display: Render('ABC')
```
## Key Functions
* **`send_display_update(const char *entry, bool finish_line)`**:
* Allocates memory.
* Checks FIFO status.
* Pushes or drops message.
* **`core1_display_init()`**:
* Main loop for Core 1.
* Drains FIFO to find the latest message.
* Calls e-Paper drawing functions.
## Memory Management
* Messages are `malloc`'d by Core 0.
* Messages are `free`'d by Core 1 (after processing or dropping).
* If Core 0 drops a message because the FIFO is full, it `free`s it immediately.

17
command_processor.cpp Normal file
View File

@@ -0,0 +1,17 @@
#include "command_processor.h"
#include <string.h>
#include <stdio.h>
CommandAction parse_command(const char* input) {
if (input[0] != '/') {
return CMD_NONE;
}
if (strcmp(input, "/refresh") == 0) return CMD_REFRESH;
if (strcmp(input, "/clear") == 0) return CMD_CLEAR;
if (strcmp(input, "/scan") == 0) return CMD_SCAN;
if (strncmp(input, "/connect ", 9) == 0 || strcmp(input, "/connect") == 0) return CMD_CONNECT;
if (strcmp(input, "/status") == 0) return CMD_STATUS;
return CMD_UNKNOWN;
}

20
command_processor.h Normal file
View File

@@ -0,0 +1,20 @@
#ifndef COMMAND_PROCESSOR_H
#define COMMAND_PROCESSOR_H
enum CommandAction {
CMD_NONE,
CMD_REFRESH,
CMD_CLEAR,
CMD_SCAN,
CMD_CONNECT,
CMD_STATUS,
CMD_UNKNOWN
};
/**
* Parses a string to check if it is a command.
* Returns the corresponding CommandAction.
*/
CommandAction parse_command(const char* input);
#endif // COMMAND_PROCESSOR_H

272
epaper_manager.cpp Normal file
View File

@@ -0,0 +1,272 @@
#include "epaper_manager.h"
#include "wifi_manager.h"
#include "pico/stdlib.h"
#include "pico/multicore.h"
#include "pico/flash.h"
#include "pico/util/queue.h"
#include <stdlib.h>
#include <string.h>
#include <stdio.h>
// e-Paper library includes
extern "C" {
#include "DEV_Config.h"
#include "EPD_7in5b_V2.h"
#include "GUI_Paint.h"
}
// e-Paper display buffers
static UBYTE *g_epd_image = NULL; // Black image buffer
static UBYTE *g_epd_red = NULL; // Red image buffer
// Entry list for display
#define MAX_ENTRIES 15
#define ENTRY_LENGTH 64
typedef struct {
char entries[MAX_ENTRIES][ENTRY_LENGTH];
int count;
} EntryList;
static EntryList g_entry_list = {{}, 0};
static bool g_force_full_refresh = false; // Flag to force full refresh when list is full
// Synchronization flag for multicore initialization
static volatile bool g_display_ready = false;
// Queue for display messages (replacing raw FIFO to avoid conflict with flash_safe_execute)
static queue_t g_display_queue;
#define QUEUE_LENGTH 8
// Display update message structure for inter-core communication
typedef struct {
EntryList entries;
bool use_partial; // Use partial refresh instead of full refresh
UWORD xstart; // Partial refresh region
UWORD ystart;
UWORD xend;
UWORD yend;
} DisplayMessage;
static void init_epaper_display() {
printf("[Core 1] Initializing 7.5\" e-Paper display (B V2)...\r\n");
// Initialize the hardware
if (DEV_Module_Init() != 0) {
printf("[Core 1] Failed to initialize e-Paper hardware!\r\n");
return;
}
// Initialize the display
printf("[Core 1] EPD_7IN5B_V2_Init()\r\n");
EPD_7IN5B_V2_Init_Fast();
printf("[Core 1] EPD_7IN5B_V2_Clear()\r\n");
// Create image buffers for black and red content
// 7.5" display: 800x480, 8 pixels per byte, so (800/8) * 480 = 48000 bytes each
UWORD imagesize = (EPD_7IN5B_V2_WIDTH / 8) * EPD_7IN5B_V2_HEIGHT;
g_epd_image = (UBYTE *)malloc(imagesize);
g_epd_red = (UBYTE *)malloc(imagesize);
if (g_epd_image == NULL || g_epd_red == NULL) {
printf("[Core 1] Failed to allocate memory for e-Paper image buffers!\r\n");
return;
}
// Initialize red buffer to all white (0xFF = no red pixels)
for (UWORD i = 0; i < imagesize; i++) {
g_epd_red[i] = 0xFF;
}
// Setup paint buffer for black content
printf("[Core 1] White background\r\n");
Paint_NewImage(g_epd_image, EPD_7IN5B_V2_WIDTH, EPD_7IN5B_V2_HEIGHT, 0, WHITE);
Paint_SelectImage(g_epd_image);
Paint_Clear(WHITE);
// Draw header
EPD_7IN5B_V2_Init_Part();
EPD_7IN5B_V2_Display_Partial(g_epd_image, 0, 0, EPD_7IN5B_V2_WIDTH, EPD_7IN5B_V2_HEIGHT);
EPD_7IN5B_V2_Display_Partial(g_epd_image, 0, 0, EPD_7IN5B_V2_WIDTH, EPD_7IN5B_V2_HEIGHT);
EPD_7IN5B_V2_Display_Partial(g_epd_image, 0, 0, EPD_7IN5B_V2_WIDTH, EPD_7IN5B_V2_HEIGHT);
printf("[Core 1] Trying to connect to wifi\r\n");
bool connected = wifi_try_auto_connect();
printf("[Core 1] Connected: %d\r\n", connected);
Paint_SelectImage(g_epd_red);
printf("[Core 1] Drawing header\r\n");
if (connected) {
Paint_DrawString_EN(10, 10, "What's new today: ...", &Font24, WHITE, RED);
} else {
Paint_DrawString_EN(10, 10, "What's new today:", &Font24, WHITE, RED);
}
// Display the image with both black and red buffers
EPD_7IN5B_V2_Display_Partial(g_epd_red, 0, 0, EPD_7IN5B_V2_WIDTH, EPD_7IN5B_V2_HEIGHT);
printf("[Core 1] e-Paper display ready!\r\n");
}
/**
* Core 1 function: Runs display initialization and update handling
*/
static void core1_display_init() {
// Initialize flash safe execute support for this core
flash_safe_execute_core_init();
// Initialize WiFi on Core 1 so IRQs are handled here
wifi_init();
init_epaper_display();
g_display_ready = true;
printf("[Core 1] Display ready, waiting for update messages...\n");
// Initialize for partial refresh on second call
EPD_7IN5B_V2_Init_Part();
// Core 1 main loop: handle display updates via Queue
while (true) {
DisplayMessage *msg;
// Check if there's a message in the queue
if (queue_try_remove(&g_display_queue, &msg)) {
// Drain Queue to get the latest message
DisplayMessage *next_msg;
while (queue_try_remove(&g_display_queue, &next_msg)) {
printf("[Core 1] Skipping intermediate update\n");
free(msg); // Free the stale message
msg = next_msg;
}
printf("[Core 1] Updating display with %d entries\n", msg->entries.count);
// Update the e-Paper display
if (g_epd_image != NULL && g_epd_red != NULL) {
// For partial refresh, only clear the text area
UWORD y_start = msg->ystart;
UWORD y_end = msg->yend;
Paint_SelectImage(g_epd_image);
Paint_Clear(WHITE);
// Calculate offset for partial refresh
UBYTE *image_ptr = g_epd_image + (msg->ystart * (EPD_7IN5B_V2_WIDTH / 8));
if(!msg->use_partial){
// for loop 5 times display white partial
int i = 0;
for(i = 0; i < 1; i++){
EPD_7IN5B_V2_Display_Partial(image_ptr, msg->xstart, msg->ystart, msg->xend, msg->yend);
}
}
// Draw all entries starting below header
UWORD y_pos = 0;
// paint only the last 10 entries
int start_index = msg->entries.count > 10 ? msg->entries.count - 10 : 0;
for (int i = start_index; i < msg->entries.count; i++) {
if (y_pos + 25 < 480) { //Don't draw beyond screen
Paint_DrawString_EN(20, 50 + i*25, msg->entries.entries[i], &Font16, WHITE, BLACK);
y_pos += 25; // Space between entries
} else {
printf("[Core 1] Skipping entry to avoid overflow\n");
}
}
// Use partial or full refresh
printf("[Core 1] Using partial refresh\n");
EPD_7IN5B_V2_Display_Partial(image_ptr, msg->xstart, msg->ystart, msg->xend, msg->yend);
}
// Free the message (it was allocated by core 0)
free(msg);
}
sleep_ms(10);
}
}
void epaper_start_background_thread() {
// Initialize the queue before starting the thread
queue_init(&g_display_queue, sizeof(DisplayMessage*), QUEUE_LENGTH);
printf("[Core 0] Launching e-Paper display init on core 1...\n");
multicore_launch_core1(core1_display_init);
}
void epaper_send_update(const char *entry, bool finish_line) {
if (!g_display_ready) return; // Don't send if display isn't ready
// printf("[Core 0] Preparing display update: '%s' (finish_line=%d)\n", entry, finish_line);
// Check if list is at capacity
if (g_entry_list.count >= MAX_ENTRIES) {
// List is full - clear all entries and start fresh
printf("[Core 0] List is FULL - clearing all entries and starting fresh\n");
g_entry_list.count = 0;
g_force_full_refresh = true;
}
// Update the current entry (at g_entry_list.count)
strncpy(g_entry_list.entries[g_entry_list.count], entry, ENTRY_LENGTH - 1);
g_entry_list.entries[g_entry_list.count][ENTRY_LENGTH - 1] = '\0';
// Allocate message structure
DisplayMessage *msg = (DisplayMessage *)malloc(sizeof(DisplayMessage));
if (msg == NULL) {
printf("[Core 0] Failed to allocate display message!\n");
return;
}
// Copy entry list to message
msg->entries = g_entry_list;
// We want to show the current line being edited, so we treat count as count + 1 for display purposes
msg->entries.count = g_entry_list.count + 1;
// Decide whether to use partial or full refresh
msg->use_partial = !g_force_full_refresh;
if (g_force_full_refresh) {
printf("[Core 0] Forcing full refresh this update\n");
g_force_full_refresh = false; // Reset flag after setting it in message
// Full text area refresh
msg->xstart = 0;
msg->ystart = 50; // Start below the header
msg->xend = 800; // Full width
msg->yend = 480; // Full height from header onwards
} else {
// Partial refresh of ONLY the current line
msg->xstart = 0;
msg->ystart = 50 + (g_entry_list.count * 25);
msg->xend = 800;
msg->yend = msg->ystart + 25;
}
// Send message pointer to core 1 via Queue
if (queue_try_add(&g_display_queue, &msg)) {
// printf("[Core 0] Display update sent to core 1\n");
} else {
printf("[Core 0] Queue full, skipping display update\n");
free(msg);
}
// If finishing the line, increment count for next time
if (finish_line) {
g_entry_list.count++;
}
}
void epaper_clear() {
g_entry_list.count = 0;
memset(g_entry_list.entries, 0, sizeof(g_entry_list.entries));
g_force_full_refresh = true;
epaper_send_update("", false);
}
void epaper_force_refresh() {
g_force_full_refresh = true;
epaper_send_update("", false);
}

31
epaper_manager.h Normal file
View File

@@ -0,0 +1,31 @@
#ifndef EPAPER_MANAGER_H
#define EPAPER_MANAGER_H
#include <stdbool.h>
/**
* Launches the e-Paper display handling loop on Core 1.
* This function returns immediately after launching the core.
*/
void epaper_start_background_thread();
/**
* Sends an update to the e-Paper display.
* @param entry The text content of the current line.
* @param finish_line If true, the line is committed (moved to the list of static lines).
* If false, it updates the current line being typed.
*/
void epaper_send_update(const char *entry, bool finish_line);
/**
* Clears all text entries and refreshes the display to white.
*/
void epaper_clear();
/**
* Forces a full refresh of the display on the next update.
* Useful for clearing ghosting.
*/
void epaper_force_refresh();
#endif // EPAPER_MANAGER_H

View File

@@ -1,135 +0,0 @@
/**
* Simple USB Serial Echo Program with Timeout, Reconnect, and Backspace Logic.
* This program now correctly handles the backspace character by deleting it
* from the buffer and sending the necessary control codes to the terminal
* for visual deletion.
*/
#include "pico/stdlib.h"
#include "pico/time.h" // Needed for time_us_64()
#include <stdio.h>
#include <ctype.h>
// Define the maximum size for the input string buffer
#define MAX_INPUT_LEN 64
// Define the timeout period: 1 second in microseconds
#define TIMEOUT_US 5000000
// ASCII code for Backspace (often sent as 0x08)
#define ASCII_BACKSPACE 8
// Helper function to handle the echoing and resetting of the buffer
void echo_and_reset(char* buffer, int* index_ptr) {
if (*index_ptr > 0) {
// Null-terminate the string
buffer[*index_ptr] = '\0';
// Echo the string back, converting to uppercase
printf("\nEchoed (ALL CAPS): ");
for (int i = 0; buffer[i] != '\0'; i++) {
printf("%c", toupper(buffer[i]));
}
printf("\n");
}
// Reset buffer for next line and print a new prompt
*index_ptr = 0;
printf("> ");
}
// Function to handle the initial waiting and reconnect waiting
void wait_for_usb_connection() {
printf("Waiting for USB host to connect...\n");
// Wait until the USB host (e.g., terminal program) opens the serial port
while (!stdio_usb_connected()) {
sleep_ms(100);
}
// Connection established!
printf("\nConnection Established! Starting Echo Session...\n");
}
void run_echo_session() {
char input_buffer[MAX_INPUT_LEN];
int buffer_index = 0;
// Track the time (in microseconds) when the last character was received
uint64_t last_char_time = time_us_64();
printf("--- Pico USB String Echo Program Started ---\n");
printf("Type a sentence (up to %d chars). It will echo on Enter/Timeout.\n", MAX_INPUT_LEN - 2);
printf("--------------------------------------------\n");
printf("> "); // Prompt for input
// Inner loop runs ONLY while the USB connection is active
while (stdio_usb_connected()) {
// Check for incoming character without blocking
int c = getchar_timeout_us(0);
if (c != PICO_ERROR_TIMEOUT) {
// Character received, update the timer
last_char_time = time_us_64();
char input_char = (char)c;
// 1. --- BACKSPACE HANDLING ---
if (input_char == ASCII_BACKSPACE || input_char == 127) { // 127 is sometimes sent by terminals (DEL key)
if (buffer_index > 0) {
// Decrease buffer index (remove the character)
buffer_index--;
// Send backspace, space, and backspace to erase the character on the terminal:
// \b: move cursor back
// ' ': overwrite with a space
// \b: move cursor back again, ready for the next character
printf("\b \b");
}
// 2. --- End of Input (Newline/CR) ---
} else if (input_char == '\r' || input_char == '\n') {
echo_and_reset(input_buffer, &buffer_index);
// 3. --- Collect regular characters ---
} else if (buffer_index < (MAX_INPUT_LEN - 1) && isprint(input_char)) {
// Echo character locally so the user sees what they type
printf("%c", input_char);
// Store character in the buffer
input_buffer[buffer_index] = input_char;
buffer_index++;
}
// Ignore non-printable characters and overflowed buffer input
}
// 4. Timeout Check
if (buffer_index > 0 && (time_us_64() - last_char_time) > TIMEOUT_US) {
printf("\n--- Timeout Reached (5.0s silence) ---\n");
echo_and_reset(input_buffer, &buffer_index);
last_char_time = time_us_64(); // Reset time to prevent immediate re-trigger
}
// Add a small delay to prevent the loop from consuming too much CPU time
sleep_us(100);
}
// Connection lost or closed by host
printf("\nHost disconnected. Ending Echo Session.\n");
}
int main() {
// Initialize Standard I/O (stdio) to use the USB backend
stdio_init_all();
// Outer loop: Allows the program to run continuously and restart the
// session after a disconnection.
while (true) {
// 1. Wait for a connection
wait_for_usb_connection();
// 2. Run the program logic while connected
run_echo_session();
// Loop repeats, going back to wait_for_usb_connection()
}
// Note: main should not return
}

View File

@@ -1,329 +1,251 @@
/*
* Simple USB Serial Echo Program with Timeout, Reconnect, and Backspace Logic.
* Converted to C++ so the project can use the `pico-ssd1306` C++ library.
* Integrated with e-ink display support via Pico_ePaper library.
* USB Host Keyboard Example with Display Support
*/
#include "pico/stdlib.h"
#include "pico/time.h" // Needed for time_us_64()
#include "pico/time.h"
#include "pico/multicore.h"
#include "tusb.h"
#include <stdio.h>
#include <ctype.h>
#include <cstring>
#include <stdlib.h>
#include <malloc.h>
#include "display.h"
#include "commands/echo.h"
// e-Paper library includes
extern "C" {
#include "DEV_Config.h"
#include "EPD_7in5b_V2.h"
#include "GUI_Paint.h"
}
#include "keyboard_input.h"
#include "command_processor.h"
#include "epaper_manager.h"
#include "wifi_manager.h"
// Holds last echoed line for display
static char g_last_echo[128] = "";
// e-Paper display buffers
static UBYTE *g_epd_image = NULL; // Black image buffer
static UBYTE *g_epd_red = NULL; // Red image buffer
// Global DisplayManager pointer
static DisplayManager* g_display_manager = nullptr;
// Entry list for display
#define MAX_ENTRIES 15
#define ENTRY_LENGTH 64
typedef struct {
char entries[MAX_ENTRIES][ENTRY_LENGTH];
int count;
} EntryList;
static EntryList g_entry_list = {{}, 0};
static bool g_force_full_refresh = false; // Flag to force full refresh when list is full
// Synchronization flag for multicore initialization
static volatile bool g_display_ready = false;
// Display update message structure for inter-core communication
typedef struct {
EntryList entries;
bool use_partial; // Use partial refresh instead of full refresh
UWORD xstart; // Partial refresh region
UWORD ystart;
UWORD xend;
UWORD yend;
} DisplayMessage;
void init_epaper_display() {
printf("Initializing 7.5\" e-Paper display (B V2)...\r\n");
// Initialize the hardware
if (DEV_Module_Init() != 0) {
printf("Failed to initialize e-Paper hardware!\r\n");
return;
}
// Initialize the display
printf("EPD_7IN5B_V2_Init()\r\n");
EPD_7IN5B_V2_Init_Fast();
printf("EPD_7IN5B_V2_Clear()\r\n");
EPD_7IN5B_V2_Clear();
DEV_Delay_ms(500);
// Create image buffers for black and red content
// 7.5" display: 800x480, 8 pixels per byte, so (800/8) * 480 = 48000 bytes each
UWORD imagesize = (EPD_7IN5B_V2_WIDTH / 8) * EPD_7IN5B_V2_HEIGHT;
g_epd_image = (UBYTE *)malloc(imagesize);
g_epd_red = (UBYTE *)malloc(imagesize);
if (g_epd_image == NULL || g_epd_red == NULL) {
printf("Failed to allocate memory for e-Paper image buffers!\r\n");
return;
}
// Initialize red buffer to all white (0xFF = no red pixels)
for (UWORD i = 0; i < imagesize; i++) {
g_epd_red[i] = 0xFF;
}
// Setup paint buffer for black content
printf("White background\r\n");
Paint_NewImage(g_epd_image, EPD_7IN5B_V2_WIDTH, EPD_7IN5B_V2_HEIGHT, 0, WHITE);
Paint_SelectImage(g_epd_image);
Paint_Clear(WHITE);
// Draw header
EPD_7IN5B_V2_Init_Part();
Paint_SelectImage(g_epd_red);
printf("Drawing header\r\n");
Paint_DrawString_EN(10, 10, "What's new today:", &Font24, WHITE, RED);
// Display the image with both black and red buffers
// printf("display text\r\n");
EPD_7IN5B_V2_Display_Partial(g_epd_red, 0, 0, EPD_7IN5B_V2_WIDTH, EPD_7IN5B_V2_HEIGHT);
// printf("delay\r\n");
// DEV_Delay_ms(1000);
printf("e-Paper display ready!\r\n");
// EPD_7IN5B_V2_Sleep();
}
// Define the maximum size for the input string buffer
// Keyboard buffer
#define MAX_INPUT_LEN 64
// Define the timeout period: 5 seconds in microseconds
#define TIMEOUT_US 5000000
// ASCII code for Backspace (often sent as 0x08)
#define ASCII_BACKSPACE 8
static char g_input_buffer[MAX_INPUT_LEN];
static int g_buffer_index = 0;
/**
* Add an entry to the display list and send update to core 1
*/
void send_display_update(const char *entry) {
if (!g_display_ready) return; // Don't send if display isn't ready
// Check if list is at capacity
if (g_entry_list.count >= MAX_ENTRIES) {
// List is full - clear all entries and start fresh
printf("[Core 0] List is FULL - clearing all entries and starting fresh\n");
g_entry_list.count = 0;
g_force_full_refresh = true;
}
// Add entry to global list
strncpy(g_entry_list.entries[g_entry_list.count], entry, ENTRY_LENGTH - 1);
g_entry_list.entries[g_entry_list.count][ENTRY_LENGTH - 1] = '\0';
g_entry_list.count++;
// Allocate message structure
DisplayMessage *msg = (DisplayMessage *)malloc(sizeof(DisplayMessage));
if (msg == NULL) {
printf("Failed to allocate display message!\n");
return;
}
// Copy entry list to message
msg->entries = g_entry_list;
// Decide whether to use partial or full refresh
msg->use_partial = !g_force_full_refresh;
if (g_force_full_refresh) {
printf("[Core 0] Forcing full refresh this update\n");
g_force_full_refresh = false; // Reset flag after setting it in message
}
// Setup partial refresh region (text area at top of display)
msg->xstart = 0;
msg->ystart = 50; // Start below the header
msg->xend = 800; // Full width
msg->yend = 480; // Full height from header onwards
// Send message pointer to core 1
multicore_fifo_push_blocking((uint32_t)msg);
// Wait for core 1 to complete the update
multicore_fifo_pop_blocking();
}
/**
* Core 1 function: Runs display initialization and update handling
*/
void core1_display_init() {
init_epaper_display();
g_display_ready = true;
printf("[Core 1] Display ready, waiting for update messages...\n");
// Initialize for partial refresh on second call
EPD_7IN5B_V2_Init_Part();
// Core 1 main loop: handle display updates via FIFO
while (true) {
// Check if there's a message from core 0
if (multicore_fifo_rvalid()) {
// Read the message pointer
uint32_t msg_addr = multicore_fifo_pop_blocking();
DisplayMessage *msg = (DisplayMessage *)msg_addr;
static bool execute_command(CommandAction action, const char* input) {
switch (action) {
case CMD_REFRESH:
printf("Command: /refresh\n");
epaper_force_refresh();
return true;
case CMD_CLEAR:
printf("Command: /clear\n");
epaper_clear();
return true;
case CMD_SCAN:
printf("Command: /scan\n");
if (g_display_manager) g_display_manager->refresh("Scanning WiFi...", nullptr);
epaper_send_update("Scanning WiFi...", true);
wifi_scan();
return true;
case CMD_CONNECT: {
printf("Command: /connect\n");
char ssid[33] = {0};
char password[64] = {0};
// Skip "/connect " (9 chars)
const char* args = input + 9;
printf("[Core 1] Updating display with %d entries\n", msg->entries.count);
// Update the e-Paper display
if (g_epd_image != NULL && g_epd_red != NULL) {
UWORD imagesize = (EPD_7IN5B_V2_WIDTH / 8) * EPD_7IN5B_V2_HEIGHT;
// For partial refresh, only clear the text area
UWORD width = (EPD_7IN5B_V2_WIDTH / 8);
UWORD y_start = msg->ystart;
UWORD y_end = msg->yend;
Paint_SelectImage(g_epd_image);
Paint_Clear(WHITE);
if(!msg->use_partial){
// for loop 5 times display white partial
int i = 0;
for(i = 0; i < 1; i++){
EPD_7IN5B_V2_Display_Partial(g_epd_image, msg->xstart, msg->ystart, msg->xend, msg->yend);
}
}
// Draw all entries starting below header
UWORD y_pos = 0;
/*for (int i = 0; i < msg->entries.count; i++) {
if (y_pos + 20 < 480) { // Don't draw beyond screen
Paint_DrawString_EN(20, y_pos, msg->entries.entries[i], &Font16, WHITE, BLACK);
y_pos += 25; // Space between entries
}
}*/
// paint only the last 3 entries
int start_index = msg->entries.count > 2 ? msg->entries.count - 2 : 0;
for (int i = start_index; i < msg->entries.count; i++) {
if (y_pos + 25 < 480) { //Don't draw beyond screen
Paint_DrawString_EN(20, i*25, msg->entries.entries[i], &Font16, WHITE, BLACK);
y_pos += 25; // Space between entries
} else {
printf("Skipping entry to avoid overflow\n");
}
}
// Use partial or full refresh
//if (msg->use_partial) {
printf("[Core 1] Using partial refresh\n");
EPD_7IN5B_V2_Display_Partial(g_epd_image, msg->xstart, msg->ystart, msg->xend, msg->yend);
/*} else {
printf("[Core 1] Using full refresh\n");
// EPD_7IN5B_V2_Init();
// EPD_7IN5B_V2_Clear();
// DEV_Delay_ms(500);
// Re-initialize partial refresh mode after full refresh
printf("[Core 1] Reinitializing partial refresh mode\n");
EPD_7IN5B_V2_Init_Part();
Paint_SelectImage(g_epd_image);
EPD_7IN5B_V2_Display_Partial(g_epd_image, msg->xstart, msg->ystart, msg->xend, msg->yend);
}*/
// Simple parsing: first word is ssid, rest is password
int parsed = sscanf(args, "%32s %63s", ssid, password);
if (parsed < 2) {
printf("Usage: /connect <ssid> <password>\n");
if (g_display_manager) g_display_manager->refresh("Usage: /connect <ssid> <pass>", nullptr);
epaper_send_update("Usage: /connect <ssid> <pass>", true);
return true;
}
// Free the message (it was allocated by core 0)
free(msg);
if (g_display_manager) g_display_manager->refresh("Connecting...", ssid);
// epaper_send_update("Connecting...", true);
// Signal back to core 0 that update is complete
multicore_fifo_push_blocking(1);
if (wifi_connect(ssid, password)) {
if (g_display_manager) g_display_manager->refresh("Connected!", ssid);
int rc = wifi_save_credentials(ssid, password);
if (rc != 0) {
char err_msg[32];
snprintf(err_msg, sizeof(err_msg), "Flash Error: %d", rc);
if (g_display_manager) g_display_manager->refresh(err_msg, nullptr);
epaper_send_update(err_msg, true);
} else {
epaper_send_update("Connected!", true);
}
} else {
if (g_display_manager) g_display_manager->refresh("Connection Failed", nullptr);
epaper_send_update("Connection Failed", true);
}
return true;
}
sleep_ms(10);
case CMD_STATUS: {
printf("Command: /status\n");
struct mallinfo m = mallinfo();
char status_msg[64];
// fordblks is the free chunk size in the arena.
// Note: This might not account for the total available system RAM if the heap hasn't grown to fill it yet.
// But it gives an idea of fragmentation and available malloc-able memory within the current arena.
snprintf(status_msg, sizeof(status_msg), "Heap: %d B, IP: %s", m.fordblks, wifi_get_ip());
printf("%s\n", status_msg);
if (g_display_manager) g_display_manager->refresh(status_msg, nullptr);
epaper_send_update(status_msg, true);
return true;
}
default:
return false;
}
}
void wait_for_usb_connection(DisplayManager &display) {
printf("Waiting for USB host to connect...\n");
while (!stdio_usb_connected()) {
sleep_ms(100);
}
printf("\nConnection Established! Starting Echo Session...\n");
display.refresh(">", nullptr);
}
void run_echo_session(DisplayManager &display) {
char input_buffer[MAX_INPUT_LEN];
int buffer_index = 0;
printf("--- Welcome User! ---\n");
printf("Type a command (or write help):\n");
printf("--------------------------------------------\n");
printf("> ");
while (stdio_usb_connected()) {
int c = getchar_timeout_us(0);
if (c != PICO_ERROR_TIMEOUT) {
char input_char = (char)c;
if (input_char == ASCII_BACKSPACE || input_char == 127) {
if (buffer_index > 0) {
buffer_index--;
printf("\b \b");
// update displays to reflect removed char
input_buffer[buffer_index] = '\0';
display.refresh(input_buffer, g_last_echo);
// send_display_update(input_buffer, g_last_echo);
static void process_kbd_report(hid_keyboard_report_t const *report) {
KeyEvent event;
if (parse_keyboard_report(report, &event)) {
if (event.is_backspace) {
if (g_buffer_index > 0) {
printf("\b \b");
g_buffer_index--;
g_input_buffer[g_buffer_index] = '\0';
// Update OLED
if (g_display_manager) g_display_manager->refresh(g_input_buffer, g_last_echo);
// Update e-Paper (in-place)
epaper_send_update(g_input_buffer, false);
}
} else if (event.is_enter) {
printf("\n");
// Always commit the input line to e-Paper so commands are visible
if (g_buffer_index > 0) {
epaper_send_update(g_input_buffer, true);
}
CommandAction action = parse_command(g_input_buffer);
if (execute_command(action, g_input_buffer)) {
// Command handled
if (g_display_manager) {
g_display_manager->set_last_echo("Command Executed");
g_display_manager->refresh("", "Command Executed");
}
} else if (input_char == '\r' || input_char == '\n') {
echo_and_reset(input_buffer, &buffer_index);
// Save last echoed (all caps) for display
size_t i = 0;
for (; input_buffer[i] != '\0' && i < sizeof(g_last_echo) - 1; ++i) {
g_last_echo[i] = input_buffer[i];
} else {
// Not a command, just text (already committed to e-Paper above)
// Save to last echo
strncpy(g_last_echo, g_input_buffer, sizeof(g_last_echo) - 1);
g_last_echo[sizeof(g_last_echo) - 1] = '\0';
// Update OLED
if (g_display_manager) {
g_display_manager->set_last_echo(g_last_echo);
g_display_manager->refresh("", g_last_echo);
}
g_last_echo[i] = '\0';
// Update both displays to show cleared input and last echo
display.set_last_echo(g_last_echo);
display.refresh("", g_last_echo);
send_display_update(g_last_echo);
} else if (buffer_index < (MAX_INPUT_LEN - 1) && isprint(input_char)) {
printf("%c", input_char);
input_buffer[buffer_index] = input_char;
buffer_index++;
// update both displays with current input
input_buffer[buffer_index] = '\0';
display.refresh(input_buffer, g_last_echo);
// send_display_update(input_buffer, g_last_echo);
}
// Clear buffer
g_buffer_index = 0;
g_input_buffer[0] = '\0';
} else if (event.is_printable) {
printf("%c", event.ascii);
if (g_buffer_index < MAX_INPUT_LEN - 1) {
g_input_buffer[g_buffer_index++] = event.ascii;
g_input_buffer[g_buffer_index] = '\0';
// Update OLED
if (g_display_manager) g_display_manager->refresh(g_input_buffer, g_last_echo);
// Update e-Paper on every keystroke
epaper_send_update(g_input_buffer, false);
}
}
sleep_us(100);
}
}
//--------------------------------------------------------------------+
// TinyUSB Callbacks
//--------------------------------------------------------------------+
static bool g_keyboard_mounted = false;
// Invoked when device is suspended
void tuh_device_suspend_cb(uint8_t dev_addr) {
printf("Device address = %d suspended\r\n", dev_addr);
}
// Invoked when device is resumed
void tuh_device_resume_cb(uint8_t dev_addr) {
printf("Device address = %d resumed\r\n", dev_addr);
}
void tuh_hid_mount_cb(uint8_t dev_addr, uint8_t instance, uint8_t const* desc_report, uint16_t desc_len) {
printf("HID device address = %d, instance = %d is mounted\r\n", dev_addr, instance);
uint8_t const itf_protocol = tuh_hid_interface_protocol(dev_addr, instance);
if (itf_protocol == HID_ITF_PROTOCOL_KEYBOARD) {
printf("Keyboard mounted\r\n");
g_keyboard_mounted = true;
if (g_display_manager) {
g_display_manager->refresh("Keyboard Connected", nullptr);
}
if (!tuh_hid_receive_report(dev_addr, instance)) {
printf("Error: cannot request to receive report\r\n");
}
}
}
void tuh_hid_umount_cb(uint8_t dev_addr, uint8_t instance) {
printf("HID device address = %d, instance = %d is unmounted\r\n", dev_addr, instance);
g_keyboard_mounted = false;
printf("\nHost disconnected. Ending Echo Session.\n");
// Reset input buffer
g_buffer_index = 0;
g_input_buffer[0] = '\0';
if (g_display_manager) {
g_display_manager->refresh("Waiting for Keyboard", nullptr);
}
}
void tuh_hid_report_received_cb(uint8_t dev_addr, uint8_t instance, uint8_t const* report, uint16_t len) {
uint8_t const itf_protocol = tuh_hid_interface_protocol(dev_addr, instance);
if (itf_protocol == HID_ITF_PROTOCOL_KEYBOARD) {
process_kbd_report((hid_keyboard_report_t const*) report);
}
// continue to request to receive report
if (!tuh_hid_receive_report(dev_addr, instance)) {
printf("Error: cannot request to receive report\r\n");
}
}
int main() {
stdio_init_all();
// Launch display initialization on core 1
printf("Launching e-Paper display init on core 1...\n");
multicore_launch_core1(core1_display_init);
sleep_ms(3000); // Give time for power to settle and serial to connect
printf("System Booting...\n");
// Launch display initialization on core 1, WIFI and Flash safe execute
epaper_start_background_thread();
DisplayManager display;
display.init();
display.refresh("Waiting for USB/Serial", nullptr);
g_display_manager = &display;
printf("Initializing TinyUSB Host...\n");
tuh_init(BOARD_TUH_RHPORT);
printf("TinyUSB Host Initialized.\n");
uint32_t last_print = 0;
while (true) {
wait_for_usb_connection(display);
run_echo_session(display);
tuh_task();
uint32_t now = to_ms_since_boot(get_absolute_time());
if (now - last_print > 5000) {
printf("Heartbeat: %u, Mounted: %d\n", now, g_keyboard_mounted);
last_print = now;
}
}
return 0;

142
keyboard_input.cpp Normal file
View File

@@ -0,0 +1,142 @@
#include "keyboard_input.h"
#include <stdio.h>
static const uint8_t keycode2ascii[128][2] = {
{0, 0}, /* 0x00 */
{0, 0}, /* 0x01 */
{0, 0}, /* 0x02 */
{0, 0}, /* 0x03 */
{'a', 'A'}, /* 0x04 */
{'b', 'B'}, /* 0x05 */
{'c', 'C'}, /* 0x06 */
{'d', 'D'}, /* 0x07 */
{'e', 'E'}, /* 0x08 */
{'f', 'F'}, /* 0x09 */
{'g', 'G'}, /* 0x0a */
{'h', 'H'}, /* 0x0b */
{'i', 'I'}, /* 0x0c */
{'j', 'J'}, /* 0x0d */
{'k', 'K'}, /* 0x0e */
{'l', 'L'}, /* 0x0f */
{'m', 'M'}, /* 0x10 */
{'n', 'N'}, /* 0x11 */
{'o', 'O'}, /* 0x12 */
{'p', 'P'}, /* 0x13 */
{'q', 'Q'}, /* 0x14 */
{'r', 'R'}, /* 0x15 */
{'s', 'S'}, /* 0x16 */
{'t', 'T'}, /* 0x17 */
{'u', 'U'}, /* 0x18 */
{'v', 'V'}, /* 0x19 */
{'w', 'W'}, /* 0x1a */
{'x', 'X'}, /* 0x1b */
{'y', 'Y'}, /* 0x1c */
{'z', 'Z'}, /* 0x1d */
{'1', '!'}, /* 0x1e */
{'2', '@'}, /* 0x1f */
{'3', '#'}, /* 0x20 */
{'4', '$'}, /* 0x21 */
{'5', '%'}, /* 0x22 */
{'6', '^'}, /* 0x23 */
{'7', '&'}, /* 0x24 */
{'8', '*'}, /* 0x25 */
{'9', '('}, /* 0x26 */
{'0', ')'}, /* 0x27 */
{'\r', '\r'}, /* 0x28 ENTER */
{'\x1b', '\x1b'}, /* 0x29 ESCAPE */
{'\b', '\b'}, /* 0x2a BACKSPACE */
{'\t', '\t'}, /* 0x2b TAB */
{' ', ' '}, /* 0x2c SPACE */
{'-', '_'}, /* 0x2d MINUS */
{'=', '+'}, /* 0x2e EQUAL */
{'[', '{'}, /* 0x2f BRACKET_LEFT */
{']', '}'}, /* 0x30 BRACKET_RIGHT */
{'\\', '|'}, /* 0x31 BACKSLASH */
{'#', '~'}, /* 0x32 EUROPE_1 */
{';', ':'}, /* 0x33 SEMICOLON */
{'\'', '\"'}, /* 0x34 APOSTROPHE */
{'`', '~'}, /* 0x35 GRAVE */
{',', '<'}, /* 0x36 COMMA */
{'.', '>'}, /* 0x37 PERIOD */
{'/', '?'}, /* 0x38 SLASH */
{0, 0}, /* 0x39 CAPS_LOCK */
{0, 0}, /* 0x3a F1 */
{0, 0}, /* 0x3b F2 */
{0, 0}, /* 0x3c F3 */
{0, 0}, /* 0x3d F4 */
{0, 0}, /* 0x3e F5 */
{0, 0}, /* 0x3f F6 */
{0, 0}, /* 0x40 F7 */
{0, 0}, /* 0x41 F8 */
{0, 0}, /* 0x42 F9 */
{0, 0}, /* 0x43 F10 */
{0, 0}, /* 0x44 F11 */
{0, 0}, /* 0x45 F12 */
{0, 0}, /* 0x46 PRINT_SCREEN */
{0, 0}, /* 0x47 SCROLL_LOCK */
{0, 0}, /* 0x48 PAUSE */
{0, 0}, /* 0x49 INSERT */
{0, 0}, /* 0x4a HOME */
{0, 0}, /* 0x4b PAGE_UP */
{0, 0}, /* 0x4c DELETE */
{0, 0}, /* 0x4d END */
{0, 0}, /* 0x4e PAGE_DOWN */
{0, 0}, /* 0x4f RIGHT_ARROW */
{0, 0}, /* 0x50 LEFT_ARROW */
{0, 0}, /* 0x51 DOWN_ARROW */
{0, 0}, /* 0x52 UP_ARROW */
{0, 0}, /* 0x53 NUM_LOCK */
{'/', '/'}, /* 0x54 KP_DIVIDE */
{'*', '*'}, /* 0x55 KP_MULTIPLY */
{'-', '-'}, /* 0x56 KP_MINUS */
{'+', '+'}, /* 0x57 KP_PLUS */
{'\r', '\r'}, /* 0x58 KP_ENTER */
{'1', '1'}, /* 0x59 KP_1 */
{'2', '2'}, /* 0x5a KP_2 */
{'3', '3'}, /* 0x5b KP_3 */
{'4', '4'}, /* 0x5c KP_4 */
{'5', '5'}, /* 0x5d KP_5 */
{'6', '6'}, /* 0x5e KP_6 */
{'7', '7'}, /* 0x5f KP_7 */
{'8', '8'}, /* 0x60 KP_8 */
{'9', '9'}, /* 0x61 KP_9 */
{'0', '0'}, /* 0x62 KP_0 */
{'.', '.'}, /* 0x63 KP_DECIMAL */
};
static inline bool find_key_in_report(hid_keyboard_report_t const *report, uint8_t keycode) {
for(uint8_t i=0; i<6; i++) {
if (report->keycode[i] == keycode) return true;
}
return false;
}
bool parse_keyboard_report(hid_keyboard_report_t const *report, KeyEvent* result) {
static hid_keyboard_report_t prev_report = { 0, 0, {0} };
bool event_found = false;
for(uint8_t i=0; i<6; i++) {
if (report->keycode[i]) {
if (find_key_in_report(&prev_report, report->keycode[i])) {
// exist in previous report means the current key is holding
} else {
// not existed in previous report means the current key is pressed
bool const is_shift = report->modifier & (KEYBOARD_MODIFIER_LEFTSHIFT | KEYBOARD_MODIFIER_RIGHTSHIFT);
uint8_t ch = keycode2ascii[report->keycode[i]][is_shift ? 1 : 0];
if (ch) {
result->ascii = ch;
result->is_enter = (ch == '\r' || ch == '\n');
result->is_backspace = (ch == '\b' || ch == 127);
result->is_printable = !result->is_enter && !result->is_backspace;
event_found = true;
// We only process one key event per report for simplicity in this refactor
// Ideally we might want to queue them if multiple keys are pressed at once
break;
}
}
}
}
prev_report = *report;
return event_found;
}

19
keyboard_input.h Normal file
View File

@@ -0,0 +1,19 @@
#ifndef KEYBOARD_INPUT_H
#define KEYBOARD_INPUT_H
#include "tusb.h"
struct KeyEvent {
char ascii;
bool is_enter;
bool is_backspace;
bool is_printable;
};
/**
* Parses a raw HID keyboard report and returns true if a new key press was detected.
* The result is stored in the provided KeyEvent pointer.
*/
bool parse_keyboard_report(hid_keyboard_report_t const *report, KeyEvent* result);
#endif // KEYBOARD_INPUT_H

53
lwipopts.h Normal file
View File

@@ -0,0 +1,53 @@
#ifndef _LWIPOPTS_H
#define _LWIPOPTS_H
// Common settings used in most of the pico_w examples
#define NO_SYS 1
#define LWIP_SOCKET 0
#define MEM_LIBC_MALLOC 0
#define MEM_ALIGNMENT 4
#define MEM_SIZE 4000
#define MEMP_NUM_TCP_SEG 32
#define MEMP_NUM_ARP_QUEUE 10
#define PBUF_POOL_SIZE 24
#define LWIP_ARP 1
#define LWIP_ETHERNET 1
#define LWIP_ICMP 1
#define LWIP_RAW 1
#define TCP_WND (8 * TCP_MSS)
#define TCP_MSS 1460
#define TCP_SND_BUF (8 * TCP_MSS)
#define TCP_SND_QUEUELEN ((4 * (TCP_SND_BUF) + (TCP_MSS - 1)) / (TCP_MSS))
#define LWIP_NETIF_STATUS_CALLBACK 1
#define LWIP_NETIF_LINK_CALLBACK 1
#define LWIP_NETIF_HOSTNAME 1
#define LWIP_NETCONN 0
#define MEM_STATS 0
#define SYS_STATS 0
#define MEMP_STATS 0
#define LINK_STATS 0
#define LWIP_CHKSUM_ALGORITHM 3
#define LWIP_DHCP 1
#define LWIP_IPV4 1
#define LWIP_TCP 1
#define LWIP_UDP 1
#define LWIP_DNS 1
#define LWIP_TCP_KEEPALIVE 1
#define LWIP_NETIF_TX_SINGLE_PBUF 1
#define DHCP_DOES_ARP_CHECK 0
#define LWIP_DHCP_DOES_ACD_CHECK 0
// Enable debugging
#ifndef NDEBUG
#define LWIP_DEBUG 1
#define LWIP_STATS 1
#define LWIP_PLATFORM_DIAG(x) do {printf x;} while(0)
#else
#define LWIP_DEBUG 0
#define LWIP_STATS 0
#define LWIP_PLATFORM_DIAG(x) do {} while(0)
#endif
#endif /* _LWIPOPTS_H */

42
suspend_fix_notes.md Normal file
View File

@@ -0,0 +1,42 @@
# TinyUSB Host Keyboard Suspend/Freeze Issues on RP2040
## Common Issues
1. **Device Auto-Suspend:** Some keyboards automatically enter a low-power suspend mode if they don't detect activity or if the host stops sending Start-Of-Frame (SOF) packets.
2. **Host Controller Freeze:** The RP2040 USB host controller can sometimes get into a state where it stops processing events, especially if there are signal integrity issues or if the `tuh_task()` is blocked for too long.
3. **Missing Keep-Alive:** If the host doesn't send SOFs, the device will suspend. The RP2040 host should send SOFs automatically when configured as host.
## `tuh_task` Usage
- **Requirement:** `tuh_task()` must be called continuously and frequently in the main loop.
- **Blocking:** It should not be blocked by long delays (like `sleep_ms` or blocking display updates) in the same thread.
- **Current Code:** Your `hello_usb.cpp` calls `tuh_task()` in a tight loop, which is correct. The display updates are offloaded to Core 1, and the FIFO push is non-blocking (checked with `multicore_fifo_wready`), so Core 0 should remain responsive.
## Potential Fixes & Debugging
### 1. Handle Suspend/Resume Callbacks
TinyUSB provides callbacks to notify the application when a device suspends or resumes. Implementing these can help determine if the device is actually suspending.
Add these to your `hello_usb.cpp`:
```cpp
// Invoked when device is suspended
void tuh_device_suspend_cb(uint8_t dev_addr) {
printf("Device address = %d suspended\r\n", dev_addr);
}
// Invoked when device is resumed
void tuh_device_resume_cb(uint8_t dev_addr) {
printf("Device address = %d resumed\r\n", dev_addr);
}
```
### 2. Force Resume
If the device suspends and doesn't wake up, you might need to force a resume from the host side, although usually the device initiates resume (remote wakeup) or the host keeps it awake.
### 3. Check Power
Ensure the keyboard is receiving sufficient power. Some mechanical keyboards with LEDs draw significant current, potentially causing voltage drops that reset the USB connection or cause a freeze.
### 4. Disable Suspend (Device Side)
Some devices have internal settings to disable sleep, but this is device-specific.
### 5. SDK/TinyUSB Version
Ensure you are using a recent version of the Pico SDK and TinyUSB, as there have been fixes for RP2040 host mode stability.

46
tusb_config.h Normal file
View File

@@ -0,0 +1,46 @@
#ifndef _TUSB_CONFIG_H_
#define _TUSB_CONFIG_H_
#ifdef __cplusplus
extern "C" {
#endif
//--------------------------------------------------------------------+
// COMMON CONFIGURATION
//--------------------------------------------------------------------+
#define CFG_TUSB_MCU OPT_MCU_RP2040
// Host Mode
#define CFG_TUH_ENABLED 1
// RHPort number used for Host can be defined by board.mk, default to port 0
#ifndef BOARD_TUH_RHPORT
#define BOARD_TUH_RHPORT 0
#endif
// RHPort max operational speed can defined by board.mk
#ifndef BOARD_TUH_MAX_SPEED
#define BOARD_TUH_MAX_SPEED OPT_MODE_DEFAULT_SPEED
#endif
//--------------------------------------------------------------------+
// HOST CONFIGURATION
//--------------------------------------------------------------------+
// Size of buffer to hold descriptors and other data used for enumeration
#define CFG_TUH_ENUMERATION_BUFSIZE 256
#define CFG_TUH_HUB 1
#define CFG_TUH_CDC 0
#define CFG_TUH_HID 4 // typical number of HID devices
#define CFG_TUH_MSC 0
#define CFG_TUH_VENDOR 0
// max device support (excluding hub device)
#define CFG_TUH_DEVICE_MAX (CFG_TUH_HUB ? 4 : 1) // hub typically has 4 ports
#ifdef __cplusplus
}
#endif
#endif /* _TUSB_CONFIG_H_ */

148
wifi_manager.cpp Normal file
View File

@@ -0,0 +1,148 @@
#include "wifi_manager.h"
#include "pico/cyw43_arch.h"
#include "pico/multicore.h"
#include "pico/flash.h"
#include "hardware/flash.h"
#include "hardware/sync.h"
#include <stdio.h>
#include <string.h>
// Use the last sector of the 2MB flash
#define FLASH_TARGET_OFFSET (2 * 1024 * 1024 - FLASH_SECTOR_SIZE)
#define WIFI_CREDS_MAGIC 0x42574946 // 'BWIF'
struct WifiCreds {
uint32_t magic;
char ssid[33];
char password[64];
};
static volatile bool g_wifi_initialized = false;
static bool g_wifi_connected = false;
bool wifi_init() {
if (g_wifi_initialized) return true;
if (cyw43_arch_init()) {
printf("WiFi init failed!\n");
return false;
}
cyw43_arch_enable_sta_mode();
g_wifi_initialized = true;
printf("WiFi initialized on Core %u\n", get_core_num());
return true;
}
static int scan_result(void *env, const cyw43_ev_scan_result_t *result) {
if (result) {
printf("SSID: %-32s RSSI: %4d Auth: %u\n", result->ssid, result->rssi, result->auth_mode);
}
return 0;
}
void wifi_scan() {
// Wait for initialization
int timeout = 500; // 5 seconds
while (!g_wifi_initialized && timeout > 0) {
sleep_ms(10);
timeout--;
}
if (!g_wifi_initialized) {
printf("WiFi not initialized!\n");
return;
}
printf("Starting WiFi scan...\n");
cyw43_wifi_scan_options_t scan_options = {0};
int err = cyw43_wifi_scan(&cyw43_state, &scan_options, NULL, scan_result);
if (err != 0) {
printf("Failed to start scan: %d\n", err);
}
}
// Helper struct for flash operations
struct FlashWriteParams {
const uint8_t* data;
size_t size;
};
// Actual flash operation to be executed safely
static void do_flash_write(void *param) {
FlashWriteParams *p = (FlashWriteParams*)param;
flash_range_erase(FLASH_TARGET_OFFSET, FLASH_SECTOR_SIZE);
flash_range_program(FLASH_TARGET_OFFSET, p->data, p->size);
}
int wifi_save_credentials(const char* ssid, const char* password) {
WifiCreds creds;
creds.magic = WIFI_CREDS_MAGIC;
strncpy(creds.ssid, ssid, sizeof(creds.ssid) - 1);
creds.ssid[sizeof(creds.ssid) - 1] = '\0';
strncpy(creds.password, password, sizeof(creds.password) - 1);
creds.password[sizeof(creds.password) - 1] = '\0';
FlashWriteParams params = { (const uint8_t*)&creds, sizeof(creds) };
int rc = flash_safe_execute(do_flash_write, &params, 1000);
if (rc == PICO_OK) {
printf("WiFi credentials saved to flash.\n");
} else {
printf("Failed to save WiFi credentials: %d\n", rc);
}
return rc;
}
bool wifi_try_auto_connect() {
// On RP2040/RP2350, flash is memory-mapped at XIP_BASE (0x10000000).
// We can read from it directly like a normal pointer without special API calls.
// The hardware XIP controller handles fetching data from the flash chip.
const WifiCreds* creds = (const WifiCreds*)(XIP_BASE + FLASH_TARGET_OFFSET);
// Check for the magic number to verify valid data exists.
// Erased flash reads as 0xFFFFFFFF, so this check fails if no data was saved.
if (creds->magic != WIFI_CREDS_MAGIC) {
printf("No saved WiFi credentials found.\n");
return false;
}
printf("Found saved credentials for SSID: %s\n", creds->ssid);
return wifi_connect(creds->ssid, creds->password);
}
bool wifi_connect(const char* ssid, const char* password) {
// Wait for initialization
int timeout = 500; // 5 seconds
while (!g_wifi_initialized && timeout > 0) {
sleep_ms(10);
timeout--;
}
if (!g_wifi_initialized) {
printf("WiFi not initialized!\n");
return false;
}
printf("Connecting to WiFi: %s...\n", ssid);
// Connect in blocking mode for simplicity
if (cyw43_arch_wifi_connect_timeout_ms(ssid, password, CYW43_AUTH_WPA2_AES_PSK, 30000)) {
printf("WiFi connection failed!\n");
g_wifi_connected = false;
return false;
}
printf("WiFi connected!\n");
g_wifi_connected = true;
return true;
}
bool wifi_is_connected() {
return g_wifi_connected;
}
const char* wifi_get_ip() {
if (!g_wifi_connected) return "Disconnected";
return ip4addr_ntoa(netif_ip4_addr(&cyw43_state.netif[0]));
}

45
wifi_manager.h Normal file
View File

@@ -0,0 +1,45 @@
#ifndef WIFI_MANAGER_H
#define WIFI_MANAGER_H
#include <stdbool.h>
/**
* Initializes the WiFi hardware.
* Returns true on success.
*/
bool wifi_init();
/**
* Scans for available WiFi networks and prints them to stdout.
*/
void wifi_scan();
/**
* Connects to the specified WiFi network.
* Returns true if connected successfully.
*/
bool wifi_connect(const char* ssid, const char* password);
/**
* Saves the WiFi credentials to flash memory for auto-connect.
* Returns 0 (PICO_OK) on success, or an error code on failure.
*/
int wifi_save_credentials(const char* ssid, const char* password);
/**
* Attempts to connect using saved credentials.
* Returns true if connected.
*/
bool wifi_try_auto_connect();
/**
* Returns true if currently connected to WiFi.
*/
bool wifi_is_connected();
/**
* Returns the current IP address as a string, or "Disconnected".
*/
const char* wifi_get_ip();
#endif // WIFI_MANAGER_H