I noticed something weird yet reproducible.
I first check my serial port settings:
bash-3.1# stty -F /dev/ttyS0
speed 0 baud; line = 0;
intr = <undef>; quit = <undef>; erase = <undef>; kill = <undef>; eof = <undef>; start = <undef>;
stop = <undef>; susp = <undef>; rprnt = <undef>; werase = <undef>; lnext = <undef>; flush = <undef>;
min = 1; time = 0;
-cread
-brkint -icrnl -imaxbel
-opost -onlcr
-isig -icanon -iexten -echo -echoe -echok -echoctl -echoke
Then change speed to 1200bps:
bash-3.1# stty -F /dev/ttyS0 1200
I then execute this fragment of my program in a function to change the baud:
fd=open(dev,O_NOCTTY | O_NONBLOCK | O_RDWR);
struct termios ser[1];
tcflush(fd,TCIFLUSH);
tcflush(fd,TCOFLUSH);
cfmakeraw(ser);
// I call tcsetattr after each terminal setting to make sure its applied.
if (tcsetattr(fd,TCSANOW,ser) < 0){
return -1;
}
cfsetspeed(ser,B9600);
if (tcsetattr(fd,TCSANOW,ser) < 0){
return -2; //returns this after manually setting port via STTY
}
The problem is the baud rate does NOT get changed properly. In fact, I get -2 returned from the function and strerror(errno) returns "input/output error".
After program execution, I check system port settings:
bash-3.1# stty -F /dev/ttyS0
speed 0 baud; line = 0;
intr = <undef>; quit = <undef>; erase = <undef>; kill = <undef>; eof = <undef>; start = <undef>;
stop = <undef>; susp = <undef>; rprnt = <undef>; werase = <undef>; lnext = <undef>; flush = <undef>;
min = 1; time = 0;
-cread
-brkint -icrnl -imaxbel
-opost -onlcr
-isig -icanon -iexten -echo -echoe -echok -echoctl -echoke
And it resets to zero bps even though I specifically asked for 9600bps.
Why does it do that? and how do I force the speed to go to 9600bps programmatically?
O_NOCTTY
andO_NONBLOCK
in the call to open?O_NOCTTY
is not needed as you are starting the program from a session shell and the process is not a process group leader. AndO_NONBLOCK
makes no sense with a local tty device (you can set it later on, but don't do it on open call) Have you checked the result ofopen(2)
for errors. You can get that errno if the open failed. – Luis Colorado