Linux串口通信Arduino#1

mac2025-09-26  29

Linux串口通信Arduino#1

参考文章:神奇的python(六)之python的串口操作(pyserial 参考文章:【python】bytearray和string之间转换,用在需要处理二进制文件和数据流上

前言

本文学习Linux利用pyserial与Arduino进行串口通信,通过Linux与Arduino串口通讯从而实现树莓派与Arduino的通讯。

目录

安装python3 serial库函数查找Arduino端口编写arduino程序编写serial_linux.py程序

安装pyserial

本文python使用的是python3,我们可以利用两种方式来安装pyserial。

方式一
sudo pip3 install serial
方式二
sudo apt-get install python3-serial

安装过程不多赘述

查找Arduino端口

用usb线将Arduino开发板连接到电脑上,打开终端,执行指令:

ls /dev/tty*

一般Arduino的端口为/dev/ttyACM0,端口是会改变的,所以使用串口通讯时,要先找对端口,不然程序会报错。

编写Arduino程序

在Arduino IDE上,编写程序

void setup() { Serial.begin(9600);//设置波特率 } void loop() { char a; a = Serial.read();//读取串口内容 if (Serial.available()) { if (a=='1') { Serial.print("hello,i got!"); } } }

给Arduino烧录程序

编写serial_arduino.py

import serial #导入serial模块 port = "/dev/ttyACM0" #Arduino端口 ser = serial.Serial(port,9600,timeout=1) #设置端口,每秒回复一个信息 ser.flushInput() #清空缓冲器 try: while True: ser.write(b'1') #将'1'字符转换为字节发送 response = ser.read() print(var(response)) except: print("连接失败!") ser.close() #关闭端口

#这里,如果不对接受到的数据进行处理,就无法在终端正常看到Arduino在串口回应的"hello,i got",这里.decode(‘utf-8’)将读取到的数据转换成str格式,并在终端下显示。

import serial #导入serial模块 port = "/dev/ttyACM0" #Arduino端口 ser = serial.Serial(port,9600,timeout=1) #设置端口,每秒回复一个信息 ser.flushInput() #清空缓冲器 try: while True: ser.write(b'1') #将'1'字符转换为字节发送 response = ser.read().decode('utf-8') #.decode('utf-8')将数据转换成str格式 print(response) except: print("连接失败!") ser.close() #关闭端口
最新回复(0)