Read and Write From Serial Port With Raspberry Pi

416,532

262

35

Intro: Read and Write From Serial Port With Raspberry Pi

In this tutorial we will see how to use the serial port on Raspberry Pi. We will use the serial port available on Raspberry with a RS232/TTL 3-5,5V adapter and a USB-serial adapter. By default the Raspberry Pi’s serial port is configured to be used for console input/output. This can help to fix problems during boot, or to log in to the Pi if the video and network are not available.

To be able to use the serial port to connect and talk to other devices (e.g. a modem a printer.. ), the serial port console login needs to be disabled.

Here we use Raspberry Pi 2, and we connect a RS232/TTL 3-5,5V adapter to pins 4 (5V), 6 (GND) ,8 (TX),10 (RX) of Raspberry, obviously connect tx with rx and vice versa.

Emmeshop tutorial Raspberry serial connection

To search for available serial ports we use the command

dmesg | grep tty

The output is something like this

pi@raspberrypi ~ $ dmesg | grep tty
  [    0.000000] Kernel command line: dma.dmachans=0x7f35 bcm2708_fb.fbwidth=656 bcm2708_fb.fbheight=416 bcm2709.boardrev=0xa01041 bcm2709.serial=0x93f9c7f9 smsc95xx.macaddr=B8:27:EB:F9:C7:F9 bcm2708_fb.fbswap=1 bcm2709.disk_led_gpio=47 bcm2709.disk_led_active_low=0 sdhci-bcm2708.emmc_clock_freq=250000000 vc_mem.mem_base=0x3dc00000 vc_mem.mem_size=0x3f000000  dwc_otg.lpm_enable=0 console=tty1 console=ttyAMA0,115200 root=/dev/mmcblk0p2 rootfstype=ext4 elevator=deadline rootwait
  [    0.001774] console [tty1] enabled
  [    0.749509] dev:f1: ttyAMA0 at MMIO 0x3f201000 (irq = 83, base_baud = 0) is a PL011 rev3
  [    1.268971] console [ttyAMA0] enabled
  pi@raspberrypi ~ $

Last line indicates that the console is enabled on the serial port ttyAMA0, so we disable it

Run the configuration command and follow the instructions below

sudo raspi-config

Emmeshop tutorial Raspberry serial

Emmeshop tutorial Raspberry serial

Emmeshop tutorial Raspberry serial

Emmeshop tutorial Raspberry serial

Emmeshop tutorial Raspberry serial

Reboot and try with

dmesg | grep tty

output now is

pi@raspberrypi ~ $ dmesg | grep tty
  [    0.000000] Kernel command line: dma.dmachans=0x7f35 bcm2708_fb.fbwidth=656 bcm2708_fb.fbheight=416 bcm2709.boardrev=0xa01041 bcm2709.serial=0x93f9c7f9 smsc95xx.macaddr=B8:27:EB:F9:C7:F9 bcm2708_fb.fbswap=1 bcm2709.disk_led_gpio=47 bcm2709.disk_led_active_low=0 sdhci-bcm2708.emmc_clock_freq=250000000 vc_mem.mem_base=0x3dc00000 vc_mem.mem_size=0x3f000000  dwc_otg.lpm_enable=0 console=tty1 root=/dev/mmcblk0p2 rootfstype=ext4 elevator=deadline rootwait
  [    0.001769] console [tty1] enabled
  [    0.749438] dev:f1: ttyAMA0 at MMIO 0x3f201000 (irq = 83, base_baud = 0) is a PL011 rev3
  pi@raspberrypi ~ $

Now we can use the serial ttyAMA0. We connect an adapter usb / serial, then we will try to establish a communication between the two serial ports; obviously in a practical application to every serial we could connect a device, for example a modem, a printer a RFID reader etc.

Emmeshop tutorial Raspberry two serial port communication

After connecting the second serial port we launch the command to find the name that Raspberry gives him

dmesg | grep tty

The output is something like this

pi@raspberrypi ~ $ dmesg | grep tty
  [    0.000000] Kernel command line: dma.dmachans=0x7f35 bcm2708_fb.fbwidth=656 bcm2708_fb.fbheight=416 bcm2709.boardrev=0xa01041 bcm2709.serial=0x93f9c7f9 smsc95xx.macaddr=B8:27:EB:F9:C7:F9 bcm2708_fb.fbswap=1 bcm2709.disk_led_gpio=47 bcm2709.disk_led_active_low=0 sdhci-bcm2708.emmc_clock_freq=250000000 vc_mem.mem_base=0x3dc00000 vc_mem.mem_size=0x3f000000  dwc_otg.lpm_enable=0 console=tty1 root=/dev/mmcblk0p2 rootfstype=ext4 elevator=deadline rootwait
  [    0.001769] console [tty1] enabled
  [    0.749438] dev:f1: ttyAMA0 at MMIO 0x3f201000 (irq = 83, base_baud = 0) is a PL011 rev3
  [  971.919417] usb 1-1.2: pl2303 converter now attached to ttyUSB0
  pi@raspberrypi ~ $

Ok, now we create two files, one who writes something on the ttyAMA0 port and the other that reads on the ttyUSB0 port.

serial_write.py

    #!/usr/bin/env python
          
      
           import time
           import serial
          
      
           ser = serial.Serial(
              
               port='/dev/ttyAMA0',
               baudrate = 9600,
               parity=serial.PARITY_NONE,
               stopbits=serial.STOPBITS_ONE,
               bytesize=serial.EIGHTBITS,
               timeout=1
           )
           counter=0
          
      
           while 1:
               ser.write('Write counter: %d \n'%(counter))
               time.sleep(1)
               counter += 1

serial_read.py

    #!/usr/bin/env python
          
      
           import time
           import serial
          
      
           ser = serial.Serial(
              
               port='/dev/ttyUSB0',
               baudrate = 9600,
               parity=serial.PARITY_NONE,
               stopbits=serial.STOPBITS_ONE,
               bytesize=serial.EIGHTBITS,
               timeout=1
           )
           counter=0
          
      
           while 1:
               x=ser.readline()
               print x

If we run both files, serial_read.py will read what serial_write.py writes

Emmeshop tutorial Raspberry serial write and read

This is just a small example but it can serve as a starting point to send a print to an old printer or read data from a router or a gps.

Follow us on social to stay informed.
http://www.emmeshop.eu

Emmeshop tutorial Raspberry serial connection

4 People Made This Project!

Recommendations

  • Audio Contest 2018

    Audio Contest 2018
  • Optics Contest

    Optics Contest
  • Electronics Tips & Tricks Challenge

    Electronics Tips & Tricks Challenge

35 Discussions

0
None
GunjalA1

2 months ago

Hi , I am trying to interface fingerprint sensor R307 with raspberry pi. but I got error in serial communication as follow:

Exception : Unknown error 0x21

I don't understand why this come? please help me.

0
None
SilvanoN

Tip 3 months ago

There is an error, you can't "write" a data if you don't add .encode()

ser.write(str(10).encode())

0
None
parovelb

1 year ago

Set it up communicating but the output is garbled. The language of the rpi2 is english, character enconde utf8, baud rate 9600, stop bits one, eight bits data. Any hints?

2 replies
0
None
philaciousparovelb

Reply 6 months ago

Just figured it out. It's because I didn't connect a the ground on the pins.

0
None
philaciousparovelb

Reply 6 months ago

Did you find a solution to this? I am having the same problem.

0
None
MirkoT8

Question 6 months ago on Introduction

So I run both programs at once, but serial_read.py does not give me the Write counter like it should. Any thoughts on why that is? Help would be appreciated. Also if its really simple, I'm a noob XD

1 more answer
0
None
MirkoT8MirkoT8

Answer 6 months ago

Never mind I was being stupid I got it

0
None
AmitP103

Question 7 months ago

Hello. Firstly let me thank you for this great tutorial. I have followed the exact same procedure as given above. I have used an FTDI chip to connect between raspberry pi. On the sender side the port name id /dev/ttyAMA0 and on the receiving side it is ttyUSB0. However when i run the code of serial_write the code gets stuck at ser.write() line and on the receiving side only space and newline are getting printed. What does this mean? Why am I getting such error? Help plzzzz. Thanks in advance

0
None
barotroma

Question 8 months ago

hello guys i m trying to connect arduino and raspberry pi3 via HC-05 bluetooth communication .
i had done the pairing with pi. but when i am executing serial code to send data to pi its print ? on pi terminal. please help me out .
thanks

0
None
mtorquato

8 months ago

Thank you for your help.
I used serial communication for a industrial thermal printer.

0
None
JurgenN1

9 months ago

I am a noob sorry,

Where to make the files on raspberry pi 3 ?
Ok, now we create two files, one who writes something on the ttyAMA0 port and the other that reads on the ttyUSB0 port

0
None
hcgrant

10 months ago

Many thanks for this ... Ive upgraded my Raspberry Pi and it must have set /dev/ttyAMA0 for console use .. Now its all working again! ;-)))

0
None
LucasT70

1 year ago

i work directly on a raspberry pi zero, and when i try to run the program and test the serial communication the time library is missing ans the program wont execute. Do you have any idea how to solve that?

thanks

0
None
MandavaC

1 year ago

I'm using HC-05 Bluetooth module with RPi3 through UART to receive data from other bluetooth module.

What I have to replace ttyUSB0 in port='/dev/ttyUSB0' in order to read serial data.

0
None
AlbertJ

1 year ago

I'm working on this to try and get it to work, but ttyAMA0 disappeared after disabling serial.

Capture.PNG
2 replies
0
None
LeifM3AlbertJ

Reply 1 year ago

I'm not sure if it's a problem with raspi-config GUI or not, I ended up undoing that and doing the following, though I'm not entirely sure if step 2 is necessary:

1. Changed code to use /dev/tty1

2. (from stack exchange)

" step 5 -

a)to disable the Serial Console edit the file using

sudo nano /boot/cmdline.txt

remove the word phase "console=serial0,115200" or "console=ttyAMA0,115200"

Exit and save your changes "

Then 'Sudo Reboot'

0
None
LeifM3AlbertJ

Reply 1 year ago

I'm having the same problem, I disabled and now ttyAMA0 is gone. Did you figure out what was wrong?