Skip to content

Instantly share code, notes, and snippets.

@sonnny
Created January 22, 2025 04:24
Show Gist options
  • Select an option

  • Save sonnny/ca2646d26236e56a848c2fcf00ef98af to your computer and use it in GitHub Desktop.

Select an option

Save sonnny/ca2646d26236e56a848c2fcf00ef98af to your computer and use it in GitHub Desktop.
pico cli demo
// https://github.com/kelu124/pic0rick/blob/main/software/rp2040_shell/main.c
// template console how to get command line from usb then process
// example: loco speed 15 4 -- set loco speed address 15 to 4
// k
#include <pico/stdio_usb.h>
#include <string.h>
#include <stdio.h>
typedef void (*command_func_t)(const char *args);
typedef struct
{
const char *command_name;
command_func_t func;
} command_t;
void loco_speed(const char *input){
char *address = strtok(input, " ");
char *speed = strtok(NULL, " ");
printf("address: %d speed: %d\n", atoi(address), atoi(speed));}
void loco_function(const char *input){}
void acc(const char *input){}
void hello(const char *input){
printf("hello world\n");}
command_t command_list[] = {
{"loco speed", loco_speed},
{"loco function", loco_function},
{"acc", acc},
{"hello", hello},
};
void process_command(char *input)
{
char *command = strtok(input, " ");
char *subcommand = strtok(NULL, " ");
char *args = strtok(NULL, "");
if (command != NULL && subcommand != NULL)
{
char full_command[50];
snprintf(full_command, sizeof(full_command), "%s %s", command, subcommand);
for (int i = 0; i < sizeof(command_list) / sizeof(command_t); i++)
{
if (strcmp(full_command, command_list[i].command_name) == 0)
{
if (args == NULL)
{
args = "0";
}
command_list[i].func(args);
return;
}
}
printf("Unknown command: %s %s\n", command, subcommand);
}
else if (command != NULL)
{
for (int i = 0; i < sizeof(command_list) / sizeof(command_t); i++)
{
if (strcmp(command, command_list[i].command_name) == 0)
{
command_list[i].func(args);
return;
}
}
printf("Unknown command: %s\n", command);
}
}
void read_input(char *buffer, int max_len)
{
int index = 0;
while (1)
{
char ch = getchar();
if (ch == '\r' || ch == '\n')
{
buffer[index] = '\0';
printf("\n");
return;
}
else if (ch == 127 || ch == '\b')
{
if (index > 0)
{
index--;
printf("\b \b");
}
}
else if (ch >= 32 && ch <= 126)
{
if (index < max_len - 1)
{
buffer[index++] = ch;
putchar(ch);
}
}
}
}
//---------------------------------------------------------------------------
// MAIN FUNCTION
//---------------------------------------------------------------------------
int main()
{
stdio_init_all();
while (!stdio_usb_connected())
{
tight_loop_contents();
}
char input[128];
while (true)
{
printf("run> ");
fflush(stdout);
read_input(input, sizeof(input));
process_command(input);
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment