这是一个针对学校俱乐部的项目。我有一个非常基本的Arduino程序,根据收到的输入,该程序以两种不同的速率使LED闪烁。我对python真的很陌生,所以我真的不知道自己在做什么。到目前为止,我为此编写了一小段代码,仅在python中工作。我只接受用户输入并将其写入Arduino。效果很好。
但是我的意思是要有一个基于烧瓶的GUI来控制Arduino。我设置了两个按钮来执行此操作。当我修改代码以与flask应用程序一起运行时,Arduino LED只会闪烁一次,并且不会运行该程序。我不知道怎么了。这是我的代码:
Arduino:
int led =13, data;
void setup() {
// put your setup code here, to run once:
Serial.begin(9600); // Set the baud rate
pinMode(13, OUTPUT); // Set the onboard LED to output
digitalWrite(13, LOW);
Serial.println("Ready");
}
void loop()
{
while (Serial.available())
{
data = Serial.read();
}
if (data =='1')
{
digitalWrite(led, HIGH); //turn LED on
delay(500); //wait for a second
digitalWrite(led, LOW);//turn LED off
delay(500); //wait for a second
}
if (data =='0')
{
digitalWrite(led, HIGH);//turn LED on
delay(2000); //wait for a second
digitalWrite(led, LOW);//turn LED off
delay(2000); //wait for a second
}
}
HTML表单提交按钮:
<form action ="/gui" method= "POST">
<input type="submit" name="submit" value="Blink Fast">
<input type="submit" name="submit" value="Blink Slow">
</form>
Python Flask
import serial
from flask import render_template, request
from flask import Flask
app = Flask(__name__)
@app.route('/')
@app.route('/gui', methods=(['GET', 'POST']))
def hello_world():
if request.method =='POST':
request.form['submit']
arduino_serial = serial.Serial('COM3', 9600) # Create Serial port object called arduinoSerialData
if request.form['submit']== 'Blink Fast': # if the entered data is blink fast
print(b'1')
arduino_serial.write(b'1') # send 1 to arduino
elif request.form['submit']=='Blink Slow':
arduino_serial.write(b'0') # send 0 to arduino
print(b'1')
return render_template('gui.html')
if __name__ == '__main__':
app.run()
最后这是有效的代码:
import serial
Arduino_Serial = serial.Serial('COM3', 9600) # Create Serial port object called arduinoSerialData
print
Arduino_Serial.readline() # read the serial data and print it as line
print("Enter 1 to ON LED and 0 to OFF LED")
while 1: # infinite loop
input_data = input() # waits until user enters data
print
"you entered", input_data # prints the data for confirmation
if (input_data == '1'): # if the entered data is 1
Arduino_Serial.write(b'1') # send 1 to arduino
print("LED ON")
if (input_data == '0'): # if the entered data is 0
Arduino_Serial.write(b'0') # send 0 to arduino
print("LED OFF")