【发布时间】:2018-11-06 14:09:31
【问题描述】:
我想使用 Python 在我的 Raspberry Pi 和 Arduino 之间进行通信。 至此,Arduino 成功向 Raspberry Pi 发送了一条串行消息,并使用 Python 中的 ser.readline() 函数读取了该消息。 但是当我想用 IF 语句闪烁连接到我的 Raspberry Pi 的 LED 时,它不起作用
blink() 函数和其他所有功能都有效,但代码不会进入使用 检查 ser.readline() 值的 IF 语句>字符串变量
这是我的 Arduino 的代码:
String data="hello";
void setup() {
// put your setup code here, to run once:
Serial.begin(9600);
}
void loop() {
// put your main code here, to run repeatedly:
Serial.println(data);//data that is being Sent
delay(5000);
}
这是在我的 Raspberry Pi 上运行的 Python 代码:
import serial
import RPi.GPIO as GPIO
import time
LedPin = 11 # pin11
ser=serial.Serial("/dev/ttyUSB0",9600) #change ACM number as found from ls /dev/tty/ACM*
ser.baudrate=9600
def setup():
GPIO.setmode(GPIO.BOARD) # Set the board mode to numbers pins by physical location
GPIO.setup(LedPin, GPIO.OUT) # Set pin mode as output
GPIO.output(LedPin, GPIO.HIGH) # Set pin to high(+3.3V) to off the led
def blink():
print 'led on'
GPIO.output(LedPin, GPIO.LOW) # led on
time.sleep(1.0) # wait 1 sec
print 'led off'
GPIO.output(LedPin, GPIO.HIGH) # led off
time.sleep(1.0) # wait 1 sec
setup()
while True:
serialmessage = ser.readline()
print("serial message is " + serialmessage)
if serialmessage == "hello":
print("message recieved")
blink()
这是我在终端中看到的: terminal_image
我一直在寻找几个小时试图找到解决方案,但没有运气。 我也刚开始用 Python 编程。 感谢您的宝贵时间。
【问题讨论】:
-
在 Pi 上使用标准串行终端应用程序进行测试以检查链接是否正常工作可能是个好主意
-
假设此处显示的缩进准确地反映了您的来源,您的
if语句和对blink()的调用不在while循环内。它们需要缩进。
标签: python arduino raspberry-pi serial-port