Killertechno
Posts: 194
Joined: Wed Jan 02, 2013 8:28 am

[C] Reading from serial port, how?

Mon Aug 29, 2016 12:29 pm

Hi guys, I feel so stupid asking for this but.... how can I read from serial port in C? (I already did this using hi-level code as Gambas or Python, but I MUST do this in C).
I'm using Arduino board sending me from 400 up to 2014 bytes at once.
I use RTS/CTS signals as GPIO for handshaking.
I've read/tested several pieces of C code found online about reading from serial port without timeout:

Code: Select all

unsigned char SerialBuffer[4096];


while(1)
{

...
...
   if (getCTS(fd))   // detected Arduino "ready to send data"
      setRTS(fd,1);   // set "ready to receive data"

   while  (getCTS(fd))
   {
      // detected Arduino line "sending data"
       n = read(fd, SerialBuffer, sizeof(SerialBuffer));
      if (n<0)
      {
         ...
         ...
      }
      else
      {
         printf("received %d bytes\r\n", n);
      }
     ...
   }
   ...

}

Result is:
received 20 bytes
received 83 bytes
received 12 bytes

Which is correct code to get "received 2048 bytes" or is this a limit of C code?
Thanks.

User avatar
topguy
Posts: 6157
Joined: Tue Oct 09, 2012 11:46 am
Location: Trondheim, Norway

Re: [C] Reading from serial port, how?

Mon Aug 29, 2016 1:16 pm

Assuming all other things are correct ( like baudrate ) I would try to remove the "while (getCTS(fd))" and see if there is another way to detect the end of received data. For example until read() returns zero bytes.
The while clause will make you stop reading from the uart-buffer if CTS drops too soon. The fact that you get the data in batches makes me thing that the arduino is not sending the data "continously".

Have you looked at the data and see if its "real" data and not just garbage ?

User avatar
DavidS
Posts: 4334
Joined: Thu Dec 15, 2011 6:39 am
Location: USA
Contact: Website

Re: [C] Reading from serial port, how?

Mon Aug 29, 2016 3:08 pm

Yes use a valid terminating sequence to the send instead of relying on HW handshaking.
RPi = The best ARM based RISC OS computer around
More than 95% of posts made from RISC OS on RPi 1B/1B+ computers. Most of the rest from RISC OS on RPi 2B/3B/3B+ computers

Killertechno
Posts: 194
Joined: Wed Jan 02, 2013 8:28 am

Re: [C] Reading from serial port, how?

Tue Aug 30, 2016 8:34 am

arduino is not sending the data "continously".
Checking code and using oscilloscope, Arduino pulls CTS low to say "data ready", than waits for RTS low (ready to receive), then data is sent.
ALL data sent continously, then there is a timer for 100ms delay to keep led on after last sent byte, then CTS signal returns in idle state.
Now Arduino waits until RTS is high again, in this case transmission is completed, new data is processed, then restarts sequence.
I'll try to chenge C code, but this sequence was correctly working when using Gambas instead C.

Return to “C/C++”