Catch serial commands

Hi, i have a problem.
I’m using Ubuntu linux and arduino duemilanove.
I have code for console program, which catch every serial input (from arduino).

#include <fcntl.h>
#include <stdio.h>
#include <termios.h>
#include <stdlib.h>
#include <strings.h>
#define SPEED B9600
#define PORT "/dev/ttyUSB0"

int main( ){
int fd = open( PORT, O_RDONLY | O_NOCTTY );
if (fd <0) {perror(PORT); exit(-1); }
struct termios options;

bzero(&options, sizeof(options));
options.c_cflag = SPEED | CS8 | CLOCAL | CREAD | IGNPAR;
tcflush(fd, TCIFLUSH);
tcsetattr(fd, TCSANOW, &options);

int r;
char buf[255];
while( 1 ){
r = read( fd, buf, 255 );
buf[r]=0;
printf( "%s", buf );
}
}

And when i press some button on my arduino, it sends Serial.println("1"); code “1” to serial port.

So, i need to add some code to upper part to catch this (code “1”) and launch some application, for example.
I tried

int r;
char buf[255];
while( 1 ){
r = read( fd, buf, 255 );
if (strcmp(buf, "1")==0) {
printf("gotcha");
}
buf[r]=0;
printf( "%s", buf );
}
}

or just

if (buf=="1") {
printf("gotcha");
}

it’s not working for me :frowning:

Anybody can help me catch and compare this ?

r = read( fd, buf, 255 );
if (strcmp(buf, "1")==0) {
printf("gotcha");
}
buf[r]=0;
printf( "%s", buf );
}

The strcmp() function expects the input array to be NULL terminated. You should be adding the NULL terminator first, then calling strcmp().

PaulS: The strcmp() function expects the input array to be NULL terminated. You should be adding the NULL terminator first, then calling strcmp().

i had a same problem) thanks!

2all: just needed to add

if (strcmp(buf, "1\0")==0) {
printf("gotcha");
}
if (strcmp(buf, "1\0")==0) {

The \0 is redundant.

But there is one big problem:

when this program is running, cpu have 100% load. how can it be helped?

when this program is running, cpu have 100% load. how can it be helped?

It can't. The Arduino runs flat out, as fast as it can, all the time. Even when it is accomplishing nothing.

What is the real problem you are trying to solve. Reducing CPU load on a single core processor isn't the solution to that problem.

PaulS

BUT, when you listening serial port with Arduino IDE, it takes about 5-7% CPU :relaxed:

when you listening serial port with Arduino IDE, it takes about 5-7% CPU

How have you measured this? How is it related to whatever problem you are trying to solve?

Serial data is collected in an interrupt handler. The Serial.available() function is used to determine if the interrupt handler has been fired to collect some data. So, the Arduino isn't really ACTIVELY listening for serial data, any more than you actively listen for a phone to ring.

I can only assume that the CPU utilization in that post refers to the PC rather than the Arduino

so, here some screens. idle:

Arduino IDE:

this program:

I don't know what it actually mean, but i will try to fix cpu usage problem. When i'll get solution, i post it :P