Instantly share code, notes, and snippets.

@noah95 /usbcdc.c
Last active Jun 4, 2017

Embed
What would you like to do?
ChibiOS C shell variables
/**
* File: usbcdc.h
*/
typedef struct
{
const char* name;
float* loc;
} usbcdcParameterStruct_t;
void usbcdcSetShellVars(const usbcdcParameterStruct_t** vars);
/**
* File: usbcdc.c
*/
static const usbcdcParameterStruct_t** mShellVars;
void usbcdcSetShellVars(const usbcdcParameterStruct_t** vars)
{
mShellVars = vars;
}
static void cmd_get(BaseSequentialStream *chp, int argc, char *argv[])
{
(void)argc;
(void)argv;
uint8_t ctr;
for(ctr = 0; mShellVars[ctr] != NULL; ctr++)
{
chprintf(chp, "%s = %.3f\r\n", mShellVars[ctr]->name, *mShellVars[ctr]->loc);
}
}
static void cmd_set(BaseSequentialStream *chp, int argc, char *argv[])
{
uint8_t ctr;
if(argc != 2)
{
chprintf(chp, "Too few arguments\r\n");
return;
}
for(ctr = 0; mShellVars[ctr] != NULL; ctr++)
{
if(strcmp(mShellVars[ctr]->name, argv[0]) == 0)
{
(*mShellVars[ctr]->loc) = stof(argv[1]);
chprintf(chp, "%s = %.3f\r\n", mShellVars[ctr]->name, *mShellVars[ctr]->loc);
return;
}
}
chprintf(chp, "%s not found\r\n", argv[0]);
}
static const ShellCommand commands[] = {
{"mem", cmd_mem},
{"threads", cmd_threads},
{"get", cmd_get},
{"set", cmd_set},
{NULL, NULL}
};
static float stof(const char* s)
{
float rez = 0, fact = 1;
if (*s == '-')
{
s++;
fact = -1;
}
for (int point_seen = 0; *s; s++)
{
if (*s == '.')
{
point_seen = 1;
continue;
}
int d = *s - '0';
if (d >= 0 && d <= 9)
{
if (point_seen) fact /= 10.0f;
rez = rez * 10.0f + (float)d;
}
}
return rez * fact;
};
/**
* File: main.c
*/
static float mFoo, mBar;
static const usbcdcParameterStruct_t mShellParmFoo = {"foo", &mFoo};
static const usbcdcParameterStruct_t mShellParmBar = {"bar", &mBar};
static const usbcdcParameterStruct_t* mShellVars[] =
{
&mShellParmFoo,
&mShellParmBar,
NULL
};
int main(void)
{
usbcdcSetShellVars(mShellVars);
while(1);
return 0;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment