LinuxQuestions.org

LinuxQuestions.org (/questions/)
-   Programming (https://www.linuxquestions.org/questions/programming-9/)
-   -   Serial programming - binary data using open() and read() (https://www.linuxquestions.org/questions/programming-9/serial-programming-binary-data-using-open-and-read-633494/)

neutron001 04-06-2008 02:44 PM

Serial programming - binary data using open() and read()
 
Hello everyone!
I am using the old "open" function to access the serial port to try and read some incoming data. The problem is when I receive beyond the standard ascii characters, 0x80 and above, when I do a read I get 0xffff(msb)(lsb). I'm assuming that these f's are getting tacked on because I'm doing a read - and it's expecting ascii chars. How do I get around this? It goes something like this...

Code:

int fd;

fd = open("/dev/ttyS0", O_RDWR | O_NOCTTY | O_NDELAY);

...setup async handler and serial settings..

Now.. in my signal handler
Code:

int raw_rx_data;
char in_bufer[128];

//read two bytes
read(fd, in_buffer, 2);

//convert to 16 bit integer
raw_rx_data = (in_buffer[0] << 8) | in_buffer[1];

1. Now do you think the issue is the way I'm converting the string to integer? (Note: I don't want to just mask the bits for other reasons).
2. Is there a way to use the open function with a binary flag (searched and couldn't find one)?
3. Is there a way to use the fopen function with the serial port? I don't think fopen supports the noctty / ndelay flags.

Thanks!

Tischbein 04-06-2008 03:56 PM

Yes, it's sign extension. int8 0xff == int32 0xffffff == -1 ; uint8 0xff == (u)int32 0x000000ff == 127.

Ha det. Beeneken.

neutron001 04-06-2008 04:28 PM

Hmmm... I don't quite understand.
If my shifting operation works for ascii values, why does it not work for non-ascii values?
Could you please explain the correct way to perform this operation? Sorry, I'm still new to this bit stuff.
Is simple bit shifting not enough?

ta0kira 04-07-2008 07:01 AM

Why not raw_rx_data = *(uint16_t*) in_buffer;? Bit operators automatically promote to int when using C. Also, you might have your bytes backwards: maybe byte 1 should have been shifted? I guess it depends on the system and how you wrote the data in the first place.
ta0kira

ntubski 04-07-2008 08:02 AM

Non-ascii values have the high bit set, so they are negative numbers. I think declaring in_buffer as unsigned char would work.

theNbomr 04-07-2008 03:04 PM

Note, also, that the serial driver may trap certain character sequences (eg XON/XOFF), depending upon how you have configured the serial port. The Serial Programming Guide forPOSIX Operating Systems, and the Serial Programming Howto both provide a good bit of information on the subject.
--- rod.


All times are GMT -5. The time now is 03:57 PM.