This is my first C program. hello world! I’m sure this is no problem for high school programmers these days, but they didn’t have programming when I was in high school. 🙂
I want to write to a serial port until the string I write is echoed back to me. Then do other stuff. My code below runs for a few seconds and then claims to see the string and ends, even when it could not have actually seen the string. It behaves the same no matter what so, I obviously have something very wrong.
Yes, the serial device /dev/kittens is real and, from a terminal, bash echoed strings to /dev/kittens are received(echoed) on the serial port when the port is looped.
I would be most appreciative to anyone who could correct my mistakes.
#include <stdio.h>
#include <string.h>
#include <unistd.h>
#include <fcntl.h>
#include <errno.h>
#include <termios.h>
int fd;
char *buff;
int open_port(void)
{
fd = open("/dev/kitens", O_RDWR | O_NOCTTY | O_NDELAY);
if (fd == -1)
{
perror("open_port: Unable to open /dev/kittens ");
}
else
fcntl(fd, F_SETFL, 0);
return (fd);
}
int main()
{
int wr,rd;
open_port();
char msg[]="There are mice in the wire.\r";
do
{
/* Read from the port */
fcntl(fd, F_SETFL, FNDELAY);
rd=read(fd,buff,sizeof(msg));
/* Write to the port */
wr = write(fd, msg, sizeof(msg));
printf("debugging - Wrote to port\n");
usleep(10000);
if (wr < 0) {
fputs("write() to port /dev/kittens failed!\n", stderr);
break;
}
} while (buff != msg);
if (buff=msg)
printf(buff, "String Found! Now do the work.");
/*
system("dostuff.sh);
*/
/* Close the port on exit. */
close(fd);
return 0;
}
First,
is assignment, not comparison 🙂 The latter is
==.Second,
is actually pointer comparison, not string comparison. For string comparison, see
strcmp()from C standard library.Third,
buffis left uninitialized – there’s no memory allocated for it, so you’re happy enough it doesn’t crash at all.Well, there is more to check, but listed above is already enough to prevent the program from functioning correctly.
As an advice: try to put a debugging
printfbelow thereadline to see what is actually read from the port. And remember, the data read from the port is not guaranteed to be zero-terminated (seezero-terminated stringsfor reference), so you have to watch for this also (either add a zero after the actual data, or somehow limit string operations on the buffer, like usingstrncmp()instead ofstrcmp()).