树莓派串口通信python函数_(12)树莓派串口通信

1串口

树莓派代码(python):

需要先安装python串口读取的库文件:pip install pyserial

(如果已经安装过了则忽略)

找到Arduino的串口地址:/dev/ttyACM0

Arduino代码:

运行时如果报/x86或者ASCII码无法解析错误。可以将代码中的中文全部换成英文,就不会错了,可能是因为无法识别中文

#include

#define DHTPIN 3

#define DHTTYPE DHT11

DHT dht(DHTPIN, DHTTYPE);

void setup() {

// put your setup code here, to run once:

Serial.begin(9600);

dht.begin();

Serial.println("Hi Vcancy. Arduino is running...");

}

/**

Arduino loop

@param none

@return none

*/

char target[] = "GET TH";

void loop() {

// 每次等待2秒后再输出(这里必须等大于1秒,不然不准确)

delay(2000);

// 从串口读数据并判断

if (Serial.available() > 0) {

if ( Serial.find(target)) {

// 获取温度或者湿度需要250毫秒!

// 传感器获取到的温度和湿度可能是2秒内的

float h = dht.readHumidity();// 读取当前的湿度

float t = dht.readTemperature(); // 读取当前的温度,单位C

float f = dht.readTemperature(true);//读取当前的温度,单位F

// 如果读取失败则退出,再读取一次

if (isnan(h) || isnan(t) || isnan(f)) {

Serial.println("Failed to read from DHT sensor!");

return;

}

// 读取体感温度,单位F

float hif = dht.computeHeatIndex(f, h);

// 读取体感温度,单位C

float hic = dht.computeHeatIndex(t, h, false);

Serial.print("湿度: ");

Serial.print(h);

Serial.print(" %\t");

Serial.print("温度: ");

Serial.print(t);

Serial.print(" *C ");

Serial.print(f);

Serial.print(" *F\t");

Serial.print("体感温度: ");

Serial.print(hic);

Serial.print(" *C ");

Serial.print(hif);

Serial.println(" *F");

}

}

}

2 树莓派接受

# -*- coding: utf-8 -*

import serial

import time

ser = serial.Serial('/dev/ttyUSB0', 115200)

if ser.isOpen == False:

ser.open() # 打开串口

ser.write(b"Raspberry pi is ready")

try:

while True:

response = ser.readline()

print(response)

time.sleep(0.1) # 软件延时

except KeyboardInterrupt:

ser.close()

你可能感兴趣的:(树莓派串口通信python函数)