之前使用树莓派2的串口/dev/ttyAMA0一直没有什么问题,但发现树莓派3使用相同的方法不灵了。
查了网上很多资料,都是旧的用法如:http://blog.csdn.net/xukai871105/article/details/22713925
终于用google找到了:http://spellfoundry.com/2016/05/29/configuring-gpio-serial-port-raspbian-jessie-including-pi-3/ 上面还有很多有趣的树莓派应用。
总结在安装了Raspbian Jessie的树莓派3上正确使用J8第8脚(TXD, GPIO14)和第10脚(RXD, GPIO15)上的串口需要做:
- Raspbian Jessie基于Debian Jessie, 相对之前的版本Wheezy, 新版本系统Jessie使用了systemd, 所以找不到/etc/inittab文件了。找不到就不要找了,因为不需要了。
- 因为树莓派3加入了蓝牙功能,于是把/dev/ttyAMA0串口分配给蓝牙了。之前使用J8.8, J8.10这个串口是对应/dev/ttyAMA0的,但是现在重新分配给/dev/ttyS0了,所以之前的程序对修改过来。
- 那如何使用之个/dev/ttyS0呢?因为系统开机的信息和登录程序getty都使了这个串口,那么我们要禁用它,和之前一样可以运行:
1sudo raspi-config
选择Advanced Options:选择Serial:
Would you like a login shell to be accessible over serial?选择<No>
然后后面的选<ok>, <Finish>, 重启后, 串口就不再输出启动信息, 也不能在串口登录, 这时相信当于没有/dev/ttyS0了:
1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768pi@raspberrypi:~ $ ls /dev |grep ttyttytty0tty1tty10tty11tty12tty13tty14tty15tty16tty17tty18tty19tty2tty20tty21tty22tty23tty24tty25tty26tty27tty28tty29tty3tty30tty31tty32tty33tty34tty35tty36tty37tty38tty39tty4tty40tty41tty42tty43tty44tty45tty46tty47tty48tty49tty5tty50tty51tty52tty53tty54tty55tty56tty57tty58tty59tty6tty60tty61tty62tty63tty7tty8tty9ttyAMA0ttyprintk
可以看到没有ttyS0了, 但是ttyAMA0还在, 因为是给蓝牙用的,就别再打它的主意了。这时要启用ttyS0:
1sudo vi /boot/config.txt在最后一行找到:enable_uart=0, 把它改成enable_uart=1, 保存,退出, 重启。
串口就可以被自已的程序使用,用来连接打印机,arduino或其它单片机之类的了。
- 这时还可以看看/boot/cmdline.txt文件内容:
1dwc_otg.lpm_enable=0 console=tty1 root=/dev/mmcblk0p2 rootfstype=ext4 elevator=deadline fsck.repair=yes rootwait
对比之前串口可以登录getty的内容:
1dwc_otg.lpm_enable=0 console=tty1 console=serial0,115200 root=/dev/mmcblk0p2 rootfstype=ext4 elevator=deadline fsck.repair=yes rootwait最后一个console=的设备serial0就是启动信息的输出。它是一个符号链接到ttySo.
1234pi@raspberrypi:~ $ ls /dev -la |grep serialdrwxr-xr-x 4 root root 80 Oct 26 10:41 seriallrwxrwxrwx 1 root root 5 Oct 26 10:41 serial0 -> ttyS0lrwxrwxrwx 1 root root 7 Oct 26 10:41 serial1 -> ttyAMA0这里就很清楚了,serial0 指向ttyS0, serial1指向ttyAMA0, 所以以后写程序可以用serial0, serial1代替tty这种写法,做到兼容。
- 最后用python写两个程序,外接一个USB转串口的线做个loopback测试:
serial_write.py:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 |
#!/usr/bin/env python import time import serial ser = serial.Serial( port = '/dev/serial0', baudrate = 115200, 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:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 |
#!/usr/bin/env python import time import serial ser = serial.Serial( port='/dev/ttyUSB0', baudrate = 115200, parity = serial.PARITY_NONE, stopbits = serial.STOPBITS_ONE, bytesize = serial.EIGHTBITS, timeout = 1 ) counter = 0 while 1: x=ser.readline() print x |