前言
Ubuntu18.04使用Python实现串口通信方案和之前那篇文章 基本相同,毕竟Jeston nano安装的系统便是arm版本的Ubuntu18.04.
基本信息
库:Python的serial
硬件:电脑Ubuntu18.04系统、USB转ttl、Jeston nano(做信息接受发送)
配置过程
串口调试软件
和Windos一样,ubuntu下也有很多串口调试软件,这里我使用的是 CuteCom ;
您可以通过以下命令安装它:
sudo apt-get install cutecom
CuteCom 界面:
安装serial库
1
你可以直接在终端下通过pip安装下载
pip install pyserial
或者conda命令 conda install pyserial
:
Note:如果您使用了anaconda,这里要注意终端下的环境是哪一个,记得在您计划使用的Python环境下使用pip命令;
2
你也可以直接在Pycharm编辑器下下载,pyserial即是。
3
测试是否安装成功:import serial
不报错就可。
通信调试过程
硬件连接:
测试结果:
电脑端:
Jeston nano端:
测试成功。
电脑Ubuntu18.04端代码:
import time
import serial
print("UART Demonstration Program")
print("NVIDIA Jetson Nano Developer Kit")
serial_port = serial.Serial(
port='/dev/ttyUSB0',
baudrate=115200,
bytesize=serial.EIGHTBITS,
parity=serial.PARITY_NONE,
stopbits=serial.STOPBITS_ONE,
)
# Wait a second to let the port initialize
time.sleep(1)
try:
# Send a simple header
serial_port.write("UART Demonstration Program\r\n".encode())
serial_port.write("NVIDIA Jetson Nano Developer Kit\r\n".encode())
while True:
if serial_port.inWaiting() > 0:
data = serial_port.read()
print(data)
serial_port.write(data)
# if we get a carriage return, add a line feed too
# \r is a carriage return; \n is a line feed
# This is to help the tty program on the other end
# Windows is \r\n for carriage return, line feed
# Macintosh and Linux use \n
if data == "\r".encode():
# For Windows boxen on the other end
serial_port.write("\n".encode())
except KeyboardInterrupt:
print("Exiting Program")
except Exception as exception_error:
print("Error occurred. Exiting Program")
print("Error: " + str(exception_error))
finally:
serial_port.close()
pass
其他问题
这里有一个小问题
问题描述:
插上usb转ttl,电脑不识别,但是有 /dev/ttyUSB0 这个文件
解决方法:
添加权限:sudo chmod 666 /dev/ttyUSB0
Note:这里 ttyUSB0 这个文件不是一直都在的,您插上USB转ttl它就有,拔下它就无了;所有你添加的权限伴随着它拔下就消失了,重新插回需要再添加权限。
另外如果插上USB转ttl 不显示 /dev/ttyUSB0,请参考这篇文章装驱动:
https://blog.csdn.net/u010750137/article/details/57103002.
其他笔记
lsusb能查看到所有通过USB接入的外设,如下图,第一个为使用ch340芯片的USB转ttl、第二个为我使用的联想鼠标、第三个为雷蛇键盘;
lsmod | grep usbserial
lsmod(英文全拼:list modules)命令用于显示已载入系统的模块;grep 命令用于查找文件里符合条件的字符串;lsmod | grep 查询当前系统是否加载了某些模块。
ubuntu下切换原先python3.6版本和anaconda的python版本安装库:默认base是anaconda基础的Python环境;
你可以使用以下命令激活anaconda环境:
conda activate
以下命令退出:
conda deactivate
查看虚拟环境
conda-env list
激活虚拟环境
conda activate pythonProject
其中 pythonProject 为虚拟环境名。
参考资料
1、CSDN博文: Windows下使用Python实现串口通信.
2、CSDN博文: 英伟达Jeston nano<3>使用Python实现三种方式串口通信.