Search code examples
c++cmicrocontrolleravrgsm

gets in AVR microcontroller just reads two characters


I am doing a proyect that involves communication between a GSM module and a ATMEGA328P. I try to emulate through a terminal the GSM module before actually trying with the AVR to check if my program works correctly, however whenever I input a string that is read by a "gets" function, the string is not properly captured. I checked by trying to display it with a "printf" after reading it and it only displays the first two characters. Any idea why is this happening? I try to empty the buffer after typing the string with this: "while ((ch = getchar()) != '\n'); to avoid problems since I have to read multiple values and whenever I type I append CR+LF as the GSM module does to answer.

Here is the part of the code:

writeSerial("AT+CMGF=1");
clear();
readSerial(status);
writeSerial(status);

The functions listed above are declared as the following:

void clear(void){
    char ch;    
    while ((ch = getchar()) != '\n');
}

void readSerial(char *arr){
    gets(arr,sizeof(arr));
}

void writeSerial(char *arr){
    printf("%s\r\n", arr); //CR+LF
}    

Solution

  • sizeof(arr) == 2 because arr is a char* not an array.

    Arrays in C are not first class data types and cannot be passed to a function; instead a pointer is passed and the array size information is lost. You need to pass the length separately.

    void readSerial(char *arr, size_t len )
    {
        gets( arr, len ) ;
    }
    

    Note that the standard library gets() does not take a size parameter in any case. I am assuming this is a non-standard implementation.

    As an aside, your clear() function can be simplified:

    void clear(void)
    {
        while( getchar() != '\n' ) ;
    }
    

    Though note that if the buffer is already empty, it will wait indefinitely for a new-line, so is probably not what you want in any case.