This is a function running inside a loop. Basically the app receives a message from Arduino and sends the message to this function:
void parseMessage(char *message){
char *sensor_num="";
char *value="";
char *percentage="";
char *delimiter = "|";
sensor_num = strtok(message , delimiter);
value = strtok(NULL, delimiter);
percentage = strtok(NULL, delimiter);
// Do stuff with values
}
It keeps running for a time, but sometimes I get a segfault on the value = strtok(NULL, delimiter);
part.
The message arriving is like:
1|123|50|
And the main function that is calling parseMessage
int main() {
SYS_LOG_INFO("Opening device... ");
int BLUETOOTH = open("/dev/tty.HC-05-DevB", O_RDONLY | O_NOCTTY | O_NONBLOCK);
SYS_LOG_INFO("Opened!");
struct termios tty;
struct termios tty_old;
memset (&tty, 0, sizeof tty);
/* Error Handling */
if (tcgetattr(BLUETOOTH, &tty) != 0) {
SYS_LOG_ERROR("Error on read Bluetooth.");
return 1;
}
/* Save old tty parameters */
tty_old = tty;
/* Set Baud Rate */
cfsetospeed (&tty, (speed_t)B9600);
cfsetispeed (&tty, (speed_t)B9600);
/* Setting other Port Stuff */
tty.c_cflag &= ~PARENB; // Make 8n1
tty.c_cflag &= ~CSTOPB;
tty.c_cflag &= ~CSIZE;
tty.c_cflag |= CS8;
tty.c_cflag &= ~CRTSCTS; // no flow control
tty.c_cc[VMIN] = 1;
tty.c_cc[VTIME] = 5;
tty.c_cflag |= CREAD | CLOCAL; // turn on READ & ignore ctrl lines
/* Make raw */
cfmakeraw(&tty);
/* Flush Port, then applies attributes */
tcflush(BLUETOOTH, TCIFLUSH);
if ( tcsetattr ( BLUETOOTH, TCSANOW, &tty ) != 0) {
SYS_LOG_ERROR("Error on flush port.");
return 1;
}
int n = 0;
char buf[255];
SYS_LOG_INFO("Starting to read data...");
do {
n = read(BLUETOOTH, &buf, sizeof buf);
if (n > 0) {
printf("buf = %s\n", buf);
parseMessage(buf);
memset(&buf, '\0', sizeof buf);
}
usleep(500000); /* sleep for 100 milliSeconds */
} while(1);
return 0;
}