How to create AT Commands Parser in C to get the incoming string from USART1?

arissajonny picture arissajonny · Jul 23, 2014 · Viewed 14.1k times · Source

I want to get the string from USART1 of STM32VLDiscovery (STM32F100X4) and write an AT Command Parser from the string received from USART1.

Below are the concept that I have developed but I am not sure whether it's correct or not.

#include <stdio.h>
#include <stdlib.h>
#include <string.h>

#include "dosomethinga.h"

void dosomethingB();
void GET_AT_COMMAND(char*);
void takecommand(char *, char *);
int quit;


int main()
{   char buff[15];
    char command = '\0';
    quit = 0;

    while(!quit)
    {
        printf("Enter your command: ");
        scanf("%s", &buff);

        if (buff[0] == 'A' && buff[1] == 'T' && buff[2] == '+')
        {
            GET_AT_COMMAND(buff);
        }

    }
}

void dosomethingB()
{
    printf("dosomethingB called \n");
}

void GET_AT_COMMAND(char *text)
{
    int command;
    char temp[10] = "";

    /*if(text[3] == 'A')
          command = 1;

    else if(text[3] == 'B')
        command = 2;

    else if(text[3] == 'Z')
        command = 3;
    */

    takecommand(text,temp);

    if (strcmp(temp, "CALLA") == 0)
        command = 1;

    if (strcmp(temp, "CALLB") == 0)
        command = 2;

    if (strcmp(temp, "Z") == 0)
        command = 3;

    switch(command)
    {
        case 1:
            dosomethingA();
            break;

        case 2:
            printf("herehere.... \n");
            dosomethingB();
            break;

        case 3:
            printf("Exiting program.... \n");
            quit = 1;
            break;


        default:
            printf("Nothing to do here \n");
     }
}

void takecommand(char *mycmd, char *hold)
{
    int i;
    for(i = 0; i < 10 ; i++)
    {
         hold[i] = mycmd[i+3];
    }
}

Can anyone explain on the steps that I should do? Thanks.

Answer

SKi picture SKi · Jul 23, 2014

Basicly you should wait an attention "AT" from the input and ignore anything before it. For example inputs "XYZATZ\r" and "AaatZ\r" should be both handled as a "ATZ" command. There can also be short pause between 'A' and 'T' (and all other chars of commands too), because human may type those commands.

By the default all commands end to "\r" character.

See more about AT commands from ITU-T documentation. For example from V.250 standard.

There are probably many alternative ways to implement that. The best alternative depends on your needs. If you are going to implement all AT-commands of mobile-terminal, then you should spend more time for the parser. If you want make some test application for few commands, then your implementation could be simple as your provided one.