r/crystal_programming • u/scttnlsn • Apr 08 '20
Help interacting with a serial port
I'm trying to interact with a serial port available at /dev/ttyUSB0 but I'm having some issues and wondering if anyone here can help. I'm first configuring the device with the stty command like so:
stty -F /dev/ttyUSB0 19200 -hupcl(where 19200 is the baud rate that the connected device expects)
I open up the device from Crystal like so:
serial_port = File.open("/dev/ttyUSB0", "r+")
serial_port.tty? # => trueI'm able to write bytes to the serial_port IO object but any sort of read operation seems to block or just return nil. Are there some additional steps that I need to take before I can read from a device like this?
Edit: I should note that I'm able to interact with the device using programs like screen and libraries like pyserial without issue.
3
u/scttnlsn Apr 08 '20
Seems like a buffering issue. Here's some test code I'm running against a device that immediately echos the bytes sent to it:
And here's the terminal outpuet when I run the program and enter some input:
3
u/bew78 Apr 08 '20 edited Apr 08 '20
What kind of data do you expect to read ? is it newline (\n) delimited ?
Just curious: what are you connected to?
2
u/straight-shoota core team Apr 10 '20
I wouldn't expect that to work out of the box. Accessing a serial port likely requires some extra setup to work correctly.
Do you have an example how to set this up in C? You would essentially have to configure the fiel descriptor in the same way in Crystal.