Serial Port – How to Configure Serial Port on Linux Easily

serial port

In Windows command prompt to configure a serial port, I can simple use:

mode com1: 9600,n,8,1

or to read the configuration:

mode com1:

Are there similar commands in Linux? What would be the easiest way to find and configure the serial port in Linux?

Best Answer

You can use the stty command to set such parameters.

This will show all settings on the first serial port (replace ttyS0 with ttyUSB0 if using an USB serial port):

stty -F /dev/ttyS0 -a

This will set the baud rate to 9600, 8 bits, 1 stop bit, no parity:

stty -F /dev/ttyS0 9600 cs8 -cstopb -parenb

One thing that generally confuses people is that most serial drivers will reset the settings to the defaults once the device is closed (i.e. no process has the device open anymore). So the above stty command will set the settings, then when it's done the driver resets them again. If you first have your POS software open the device and then perform the stty settings, they should stick around until your POS software closes the device again (e.g. upon exiting).

I'd have thought that the POS software should have some way of configuring these settings on its own. If you're writing your own software to drive the printer, make sure you first open the device, and then perform the stty command.

You may also need to play around with other settings, e.g. opost means that output postprocessing will be performed. If opost and onlcr are both set, the onlcr will cause an extra carriage return (0xd) to be added when a newline (0xa) byte is output, typically to prevent staircase printing such as

This is a line
              This is the next line

This may or may not be what you want. If you want a raw one-to-one output to the printer turn opost off (add -opost to the stty parameters).

Handshaking (flow control) is also controlled with stty, without knowing more about the printer I can't tell whether you need to set anything.

Check the stty manpage for lots more info.

Related Question