cwiringpi

Segmentation violation wiringpi


I have a problem with the following code. I think it's a pointer issue but I don't know how to solve it.

I want to call the SIM7070_Start function from main. This function calls SIM7070_SendCommand and then the error appears. It is related to the 'serial' variable of WiringPi?

please help


#include <stdio.h>
#include <string.h>
#include <errno.h>
#include <wiringPi.h>
#include <wiringSerial.h>

const int pwr = 4;
const int dtr = 25;

int SIM7070_PowerOn()
{
   printf("SIM7070_PowerOn\n");
   pinMode(pwr, OUTPUT);
   digitalWrite(pwr, HIGH);
   delay(2000);
   digitalWrite(pwr, LOW);
   delay(2000);

   pinMode(dtr, OUTPUT);
   digitalWrite(dtr, LOW);
   delay(1000);

}

int SIM7070_powerDown(void)
{
   printf("SIM7070_PowerDown\n");
   digitalWrite(pwr, HIGH);
   delay(1000);
   digitalWrite(pwr, LOW);
   delay(2000);

}

int SIM7070_SendCommand(int serial, char * command, char * expectedResponse)
{
   char data;
   data = (char *) malloc(sizeof(char));

   printf("\nSEND COMMAND IS: %s\n", command);

   serialPrintf(serial, command);
   delay(200);

   while (serialDataAvail(serial)) {
       data = serialGetchar(serial);
       printf("%s", data);
   }

   if (strlen(expectedResponse) != 0) {
       if (strcmp(data, expectedResponse) <= 0) {
           printf("\nSIM7070_SendCommand - The expected response has been found\n");
           return 1;
       } else {
           printf("\nSIM7070_SendCommand - The expected response hasn't been found\n");
           return 0;
       }
   }
}

void SIM7070_Start(int serial)
{
   SIM7070_SendCommand(serial, "AT\r\n", "OK");
}

int main()
{
   int serial;
   char data;

   if (wiringPiSetup() < 0)
       return 1;
   if ((serial = serialOpen("/dev/ttyS0", 57600)) < 0)
       return 1;

   printf("Serial start ...\n");

   SIM7070_PowerOn();
   delay(2000);

   SIM7070_Start(serial);

   delay(5000);
   serialClose(serial);
   SIM7070_powerDown();

   return 0;
}

if main is:

int main()
{
   int serial;
   char data;

   if (wiringPiSetup() < 0)
       return 1;
   if ((serial = serialOpen("/dev/ttyS0", 57600)) < 0)
       return 1;

   printf("Serial start ...\n");

   SIM7070_PowerOn();
   delay(2000);

   SIM7070_SendCommand(serial, "AT\r\n", "OK");

   delay(5000);
   serialClose(serial);
   SIM7070_powerDown();

   return 0;
}

it works.


Solution

  • See also my comments. You may want a loop like:

    char data[256], *pData= data;
    while(serialDataAvail(serial)){ 
       *pData++ = serialGetchar(serial);     
    }
    *pData= '\0';
    printf ("%s", data);
    

    This uses an array of chars to place the data received into. Pointer variable pData then points to this buffer and increments with each character received. At the end it terminates the (string) buffer with a terminating null character.