我想使用Arduino将消息发送到手机。
我正在使用Twilio的API,Python和Arduino IDE。因此,我使用两个按钮,如果我按下button1,则消息为“ TURN ON LAMP”,如果我按下button2,则消息为“ TURN OFF LAMP”。
但是python中有问题:
TypeError: '>' not supported between instances of 'str' and 'int'
我在下面的代码中隐藏了我的帐户SID,令牌和编号。
Arduino代码
const int buttonPin1 = 6; // the number of the pushbutton pin
const int buttonPin2 = 7;
int buttonstate1 = 0;
int buttonstate2 = 0;
void setup() {
Serial.begin(9600);
pinMode(buttonPin1, INPUT);
pinMode(buttonPin2, INPUT);
pinMode(LED_BUILTIN, OUTPUT);
}
void loop() {
buttonstate1 = digitalRead(buttonPin1);
buttonstate2 = digitalRead(buttonPin2);
if (buttonstate1 == HIGH) {
Serial.println("a");
digitalWrite(LED_BUILTIN, HIGH);
delay(1000);
} else {
// turn LED off:
digitalWrite(LED_BUILTIN, LOW);
}
if (buttonstate2 == HIGH) {
Serial.println("b");
digitalWrite(LED_BUILTIN, HIGH);
delay(1000);
}
else {
digitalWrite(LED_BUILTIN, LOW);
}
Python代码
import time
import serial
from twilio.rest import Client
arduinoserial = serial.Serial('COM3', 9600)
time.sleep(2)
account_sid = "xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx"
auth_token = "xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx"
client = Client(account_sid, auth_token)
while True:
if arduinoserial.read('a'):
print(arduinoserial.readline().str())
messageTosend="TURN ON LAMP"
message = client.messages.create(
body=messageTosend,
from_='+14xxxxxxx',
to='+14xxxxxxxx'
)
if arduinoserial.read(int('b')):
print(arduinoserial.readline().str())
messageTosend = "TURN OFF LAMP"
message = client.messages.create(
body=messageTosend,
from_='+14xxxxxxxxxxxx',
to='+14xxxxxxxxxxxxxxx'
)
time.sleep(1)
print(message.sid)
arduinoserial.close()
答案 0 :(得分:0)
您的两个if语句是问题。
以下是serial.read()的工作原理:
arduinoserial.read() #reads one byte from buffer
arduinoserial.read(10) #reads ten bytes from buffer
arduinoserial.read('a') #makes no sense
因此,这是您需要调整代码的方式:(如果只想执行一次,就可以摆脱while循环)
while true:
arduino_input = arduinoserial.readline() #reads a full line of text (also waits till the arduino sent a line of text)
if arduino_input == 'a': #compares text to 'a'
[do your stuff here]
if arduino_input == 'b': #compares text to 'b'
[do your stuff here]
此行代码从缓冲区读取一行,将其转换为字符串,然后将其与另一个字符(“ a”或“ b”)进行比较。如果字符串和字符等价,则执行if语句的正文。
希望这会有所帮助。 :]