views:

234

answers:

1

All the code below works. My device responds, C,7 is a reset. When I run this the second time it doesn't respond. If I manually turn my device off and on, then run this script again it works. But not if I press the button to run the script the second time.

RS232: 57600,8,N,1

Any ideas?? Is there any more information needed to solve this?

*Also when I get this working I'm going to have to use the read() function to get the devices responses. Does anyone know the correct format I need to use, based on the below code? Sorry I'm new to C++...I'm more of a PHP guy.

*I also don't know if 1024 is right, but it seems to work so eh...

Thanks so much!

#include <termios.h>

int fd;
struct termios options;
fd=open("/dev/tty.KeySerial1", O_RDWR | O_NOCTTY | O_NDELAY);
fcntl(fd, F_SETFL, 0);
tcgetattr(fd,&options);
options.c_ispeed=57600;
options.c_ospeed=57600;
options.c_cflag |= (CLOCAL | CREAD);
options.c_lflag &= ~(ICANON | ECHO | ECHOE | ISIG);
options.c_cflag &= ~CSTOPB;
options.c_lflag &= ~ECHO;
options.c_oflag &= ~ECHO;
options.c_oflag &= ~OPOST;
options.c_cflag |= CS8;
options.c_cflag |= CRTSCTS;
options.c_cc[VMIN] = 0;
options.c_cc[VTIME] =10;
tcflush(fd, TCIFLUSH);
tcsetattr(fd,TCSANOW,&options);

write(fd, "C,7\r\n", 1024);

close(fd);
+3  A: 

The 1024 may in fact be your problem. The third paramter to the write() function indicates the number of bytes to be written:

ssize_t write(int fildes, const void *buf, size_t nbyte);

See the man page for write() for details.

In your case, the number should be 5, since you are sending 5 characters ('C' ',' '7' '\r' and '\n').

By providing a value of 1024, you are actually sending another 1019 garbage characters over the serial channel.

update:

The read() function has almost the same arguments:

ssize_t read(int fildes, void *buf, size_t nbyte);

Note that you must provide a writable buffer as the second parameter. For example, to read 12 bytes you would use:

char someData[12];
read(fd, someData, 12);

I'm not quite sure how to determine the number of characters you need to read, but the ssize_t number returned by the function will tell you how many were actually read.

e.James
Brilliant!!!! That worked! That little change would have taken me all day(or more) to figure out.Thank you very much!Any idea on my read() function format? :)
Pfeffer