typedef unsigned char uint8_t;
void cmd_reset()
{
int i;
i++;
}
void cmd_ymodem()
{
int i;
i++;
}
uint8_t CmdListener(char c)
{
#define CMD_SIZE 5
static uint8_t cmdQueue[CMD_SIZE] = { 0,0,0,0,0 };
static uint8_t cmdReset[] = { '!', 'b', 'o', 'o', 't' };
static uint8_t cmdYModem[] = { 0x01, 0x00, 0xff };
static uint8_t cmdIdx = 0;
int i;
if (c == '!')
{
cmdIdx = 0;
}
if (cmdIdx >= CMD_SIZE) cmdIdx = 0;
cmdQueue[cmdIdx++] = c;
if (cmdIdx == sizeof(cmdReset))
{
i = cmdIdx;
while (i-- > 0)
{
if (cmdReset[i] != cmdQueue[i]) break;
if (i == 0)
{
cmd_reset();
}
}
}
if (cmdIdx == sizeof(cmdYModem))
{
i = cmdIdx;
while (i-- > 0)
{
if (cmdYModem[i] != cmdQueue[i]) break;
if (i == 0)
{
cmd_ymodem();
}
}
}
return c;
}
我或者从来没有快过,或者现在快速衰退。
上面的这段代码,思路还行,对吧?但是它调试耗费了3个小时。几乎。单片机无法调试,我刚刚把它放在VS里面跑了一下,才意识到几个低级错误。它的最终形式是这样的:
typedef unsigned char uint8_t;
void cmd_reset()
{
int i;
i++;
}
void cmd_ymodem()
{
int i;
i++;
}
typedef void (*Cmd_Fun)();
bool CheckAndInvokeCmd(uint8_t *input_buf, int len_input, uint8_t *cmd_code_to_check, int len_cmd, Cmd_Fun fn)
{
if (len_input != len_cmd) return false;
int i = len_cmd;
while (i-- > 0)
{
if (cmd_code_to_check[i] != input_buf[i]) break;
if (i == 0)
{
fn();
return true;
}
}
return false;
}
uint8_t CmdListener(char c)
{
#define CMD_SIZE 5
static uint8_t cmdQueue[] = { '0', '0', '0', '0', '0' };
static uint8_t cmdReset[] = { '!', 'b', 'o', 'o', 't' };
static uint8_t cmdYModem[] = { 0x01, 0x00, 0xff };
static uint8_t cmdIdx = 0;
int i;
if (c == '!')
{
cmdIdx = 0;
}
if (cmdIdx >= CMD_SIZE) cmdIdx = 0;
cmdQueue[cmdIdx++] = c;
do
{
if (CheckAndInvokeCmd(cmdQueue, cmdIdx, cmdReset, sizeof(cmdReset), cmd_reset)) break;
if (CheckAndInvokeCmd(cmdQueue, cmdIdx, cmdYModem, sizeof(cmdYModem), cmd_ymodem)) break;
} while (0);
return c;
}
上面这段代码,我在改写调试过程中,又至少犯了6~7个错误,才改就。
我是端不起这碗饭吗?这些迟滞让我异常郁闷。