cwiringpi

serialPutchar with char* variable


I need to send char* (command) with serial WiringPi. How do I do it if serialPutchar (int fd, unsigned char c) needs an unsigned char?

int SendCommand(int serial, char *command, char *expectedResponse, char response []) {
   serialFlush(serial);
   serialPutchar(serial, command);
   return 1;
}

I still have something wrong with my code that I don't know what it is.

I use SendCommand function to send data to a server. However, I send an empty NULL packet when I try to send 'a'.

I don't understand :(

int SendCommand(int serial, char *command,  char *expectedResponse, char response []) {
   int max_Retries = 0;
   int i;
   char data[256], *pData = data;

   serialFlush(serial);

   for(i = 0; i <= strlen(command); i++) {
       serialPutchar(serial, command[i]);
   }
   delay(100);

   while(serialDataAvail(serial)){ 
      *pData++ = serialGetchar(serial);
   }        

      while(strstr(data, expectedResponse) == (const char*) NULL){ 
         if(max_Retries >= 150) {          
            printf("\nSIM7070_SendCommand - The expected response hasn't been found\n");
            return 0;
         }
                 
        else{
           *pData++ = serialGetchar(serial);
            max_Retries++;
            delay(100);
        }

      }            
      if(strstr(data, expectedResponse) != (const char*) NULL){  
         *pData= '\0';
         printf ("%s", data);                  
         printf("\nSIM7070_SendCommand - The expected response has been found\n");
         
         if(response != NULL){
            strcpy(response, data);
         }   
         return 1;                   
               
      }
      return 0; 
}
   SendCommand(serial, "AT+CASEND=1,1\r\n", ">", NULL);
   serialFlush(serial);
   serialPutchar(serial,'a');
   serialFlush(serial);

Solution

  • A char* is a pointer to a char type. It might be both an array of char or a single char. Your command is probably a ponter to an array, so you will need to loop over it or use a better serial sender which accepts strings and not single chars.

    Loop over string

    There are several ways to loop a C string. This one uses a i variable which increases from 0 until the string length (got using strlen(command)):

    int SendCommand(int serial, char *command, char *expectedResponse, char response []) {
       int i;
       serialFlush(serial);
       // Use <= to send also the `0` string terminating char
       for(i = 0; i <= strlen(command); i++) {
           serialPutchar(serial, command[i]);
       }
       return 1;
    }
    

    You could also:

    Use a better serial sender

    Here, I use serialPuts to send the full string at once:

    int SendCommand(int serial, char *command, char *expectedResponse, char response []) {
       serialFlush(serial);
       serialPuts(serial, command);
       return 1;
    }