OpenWrt Forum Archive

Topic: Using serial port in C

The content of this topic has been archived on 5 Apr 2018. There are no obvious gaps in this topic, but there may still be some posts missing at the end.

I am using a Fonera-device for some experiments. I have an Atmel microcontroller attached to it's serial port and I want to communicate with it at 250kbps (I know it's an unusual baudrate but I can't change it).

Here is what I did and which worked great:

root@OpenWrt:~# setserial /dev/ttyS0 spd_cust baud_base 250000 divisor 1
root@OpenWrt:~# echo -n -e '\xFF' > /dev/ttyS0

I tried the same (I suppose) in C. I don't have much experience in C on linux, so I tried some code I found on the net. Here are my 2 attempts, I'm posting only the relevant parts of the code. I don't use tcsetattr() anymore because it always messed with the serial port and my shell-code didn't work anymore.

system("/usr/sbin/setserial /dev/ttyS0 spd_cust baud_base 250000 divisor 1");

port=fopen("/dev/ttyS0", "w");

i=fputc(0xFF,port);
printf("%i", i);
system("/usr/sbin/setserial /dev/ttyS0 spd_cust baud_base 250000 divisor 1");

port=open("/dev/ttyS0", O_RDWR);

i=write(port,(char *)0xFF,1);
printf("%i", i);

fputc in the first one returns 0xFF, but actually doesn't send anything. write in the second program returns -1.


I don't really understand what I am doing wrong here. Can someone point me into the right direction?

1) stdio functions perform some buffering - you need to flush the buffer to make sure the data has really been written out.

2) write() needs a pointer to the buffer with data, e.g.

static const char buf[1] = { 0xff };

i = write(port, buf, 1);

The discussion might have continued from here.