baue mir gerade eine kleine shell über die UART. Ich hab schon oft sowas
gemacht aber sonst immer die commandliste von hand gebaut mit switch und
so, geht, find ich aber irgendwie hässlich! Das ganze kann man ja auch
universeller machen. ich sehe das oft mal da wird dann eine liste
gebaut wie:
(pseudocode)
cmdlist = { "setup", setup_func, .... } usw.
wenn ich jetzt durch diese liste durchloopen würde, dann immer den
commandkey ("setup") mit der eingabe vergleiche wie würde ich dann
klarmachen, dass setup_func eine funktion ist die dann aufgerufen
werden soll? Hat jemand ne idee? danke :)
  Du definierst das Element als Funktionszeiger. Vielleicht hilft folgendes:
1  | struct cmd  | 
2  | {
 | 
3  | const char* name,  | 
4  | void (*func)(void);  | 
5  | };
 | 
6  | |
7  | struct cmd cmdlist[] =  | 
8  | {
 | 
9  | { "setup", setup_func},  | 
10  | { 0, 0}  | 
11  | };
 | 
12  | |
13  | ...
 | 
14  | |
15  | int execute(const char* command)  | 
16  | {
 | 
17  | for (cmd* c = cmdlist; cmd->name != 0; ++cmd)  | 
18  |     {
 | 
19  | if (strcmp(cmd->name, command))  | 
20  |         {
 | 
21  | cmd->func();  | 
22  | return 1;  | 
23  |         }
 | 
24  |     }
 | 
25  | printf("Unknown command\n");  | 
26  | return 0;  | 
27  | }
 | 
Wenn du noch Parameter übergeben willst, mußt du dir halt überlegen, wie du das einbaust.
Dann ist ja gut. Das Finden der (wie ich gerade sehe) zahlreichen Fehler bleibt als Übung ;-)
so hab glaub ich alle gefunden :p
struct cmd
{
  const char* name;
  void (*func)(void);
};
void poll()
{
  float val = ((float)ADC/1024.0f)*5.0f;
  char string[10];
  dtostrf(val,5,1,string);
  printf("Polling.....\nADC: %sV\n",string);
}
struct cmd cmdlist[] =
{
  { "poll", poll },
  { 0, 0 }
};
int execute(const char* command)
{
  struct cmd *c = 0;
  for (c = cmdlist; c->name != 0; ++c) {
    if (!strcmp(c->name, command)) {
      c->func();
      return 1;
    }
  }
  printf("Unknown command\n");
  return 0;
}
  Bitte melde dich an um einen Beitrag zu schreiben. Anmeldung ist kostenlos und dauert nur eine Minute.
  
  Bestehender Account
  
  
  
  Schon ein Account bei Google/GoogleMail? Keine Anmeldung erforderlich!
Mit Google-Account einloggen
Mit Google-Account einloggen
  Noch kein Account? Hier anmelden.