我正在尝试使用连接到Arduino的HC12实现无线土壤湿度传感器,以发送信号(值:0-100%),然后激活连接到树莓派3的继电器,具体取决于百分比(例如:打开20%,关闭90%)。我弄清楚了如何发送值,并且能够在pi上看到它们,但是我无法激活继电器。请帮忙。
这是我正在使用的代码:
import RPi.GPIO as GPIO
import smtplib
import time
from time import sleep
import serial
GPIO.setmode(GPIO.BCM) # Set our GPIO numbering to BCM
relay_pin = 16
GPIO.setup(relay_pin, GPIO.OUT)
GPIO.output(relay_pin, 1)
ser = serial.Serial ("/dev/ttyS0",9600) #Open port with baud rate
try:
while True:
received_data = ser.read() #read serial port
data_left = ser.inWaiting()
received_data += ser.read(data_left)
print (received_data) #print received data
ser.write(received_data) #transmit data serially
if received_data <= '20':
GPIO.output(relay_pin, 0)
elif received_data >= '90':
GPIO.output(relay_pin, 1)
except KeyboardInterrupt:
pass
GPIO.cleanup()
答案 0 :(得分:0)
我认为,问题出在语句if
中。
if received_data <= '20':
GPIO.output(relay_pin, 0)
elif received_data >= '90':
GPIO.output(relay_pin, 1)
'20'
是不是数字的字符串。
尝试删除引号,如下所示:
if received_data <= 20:
GPIO.output(relay_pin, 0)
elif received_data >= 90:
GPIO.output(relay_pin, 1)
答案 1 :(得分:0)
我仍然在使用代码方面遇到麻烦,并且将代码更改为:如果int(received_data)<= 20,则会出现错误消息。这是修改后的代码:
import RPi.GPIO as GPIO
import smtplib
import time
from time import sleep
import serial
GPIO.setmode(GPIO.BCM) # Set our GPIO numbering to BCM
relay_pin = 16
GPIO.setup(relay_pin, GPIO.OUT)
GPIO.output(relay_pin, GPIO.HIGH)
ser = serial.Serial ("/dev/ttyS0",9600)
try:
while True:
received_data = ser.read() #read serial port
data_left = ser.inWaiting()
received_data += ser.read(data_left)
print (received_data) #print received data
ser.write(received_data) #transmit data serially
if int(received_data) <= 20:
GPIO.output(relay_pin, GPIO.HIGH)
elif int(received_data) >= 90:
GPIO.output(relay_pin, GPIO.LOW)
else:
GPIO.output(relay_pin, GPIO.LOW)
except KeyboardInterrupt:
pass
GPIO.cleanup()
但是,当我删除“ if int(received_data)<= 20”并将代码保留为:
import RPi.GPIO as GPIO
import smtplib
import time
from time import sleep
import serial
GPIO.setmode(GPIO.BCM) # Set our GPIO numbering to BCM
relay_pin = 16
GPIO.setup(relay_pin, GPIO.OUT)
GPIO.output(relay_pin, GPIO.HIGH)
ser = serial.Serial ("/dev/ttyS0",9600)
try:
while True:
received_data = ser.read() #read serial port
data_left = ser.inWaiting()
received_data += ser.read(data_left)
print (received_data) #print received data
ser.write(received_data) #transmit data serially
if received_data <= 20:
GPIO.output(relay_pin, GPIO.HIGH)
elif received_data >= 90:
GPIO.output(relay_pin, GPIO.LOW)
else:
GPIO.output(relay_pin, GPIO.LOW)
except KeyboardInterrupt:
pass
GPIO.cleanup()
继电器打开,但不响应从Arduino和土壤湿度传感器接收到的串行数据。我在想也许可以定义来自Arduino的串行数据,比如说:在湿度为20%时打开继电器,在土壤湿度为90%时关闭继电器,因此将20%的值定义为“ 1”或GPIO.HIGH打开继电器,反之亦然,但是我不知道该如何实现。有什么建议吗?