我正在尝试在arduino和pySerial之间进行通信,但串行监视器正在给我回复奇怪的字符,所以arduino没有像它应该那样开启/关闭。提前谢谢。
Arduino code
int ledpin = 13;
int state; // 0 = led off, 1 = led on
int flag = 0; // used so msg is only printed once
char val;
void setup(){
pinMode(ledpin, OUTPUT);
digitalWrite(ledpin, LOW);
Serial.begin(9600);
}
void loop(){
//if data sent, read and save
if(Serial.available() > 0){
state = Serial.read() -'0';
val = char(state);
Serial.println(val);
flag = 0;
}
//if state = 0
if (val == '0'){
digitalWrite(ledpin, LOW);
if(flag = 0){
Serial.println('LED : Off');
flag = 1;
}
}
//if state = 1
if (val = '1'){
digitalWrite(ledpin,HIGH);
if(flag = 0){
Serial.println('LED : On');
flag = 1;
}
}
}
Python代码
import serial
from tkinter import *
port = '/dev/ttyACM0'
speed = 9600
def send_command(val):
connection = serial.Serial(port,speed)
connection.write(b"val")
connection.close()
#Create the window
win = Tk()
#Modify the root window
win.title("Arduino system") # gives title to window
win.geometry("320x100") # sets the size of the window
#Creating components
f = Frame(win) # creates window
#label with text
l = Label(win , text = "Flash LED")
b1 = Button(f, text ="Send 0")
b2 = Button(f, text ="Send 1")
#Defining methods
def but1(): send_command('0') # command run if button 1 pressed
def but2(): send_command('1') # command run if button 1 pressed
b1.configure(command = but1) # assiging methods to buttons
b2.configure(command = but2) # assiging methods to buttons
#Adding Components
l.pack() #packs in the label
b1.pack(side = LEFT) #packs the buttons in one after the other
b2.pack(side = LEFT) #packs the buttons in one after the other
f.pack()
win.mainloop() # start Gui
从python发送0到arduino后,串行监视器上会出现以下内容 F 1 <
发送1
后出现同样的事情
答案 0 :(得分:0)
这段代码:
state = Serial.read() -'0';
val = char(state);
Serial.println(val);
将打印(char) 0
而不是'0'
和(char) 1
而不是'1'
。您还要将val与字符常量进行比较,就像它是一个字符一样。但是,您的代码会将其转换为存储在字符中的整数值。
→您应该决定变量的类型以及存储在其中的内容。
另外
Serial.println('LED : Off');
和
Serial.println('LED : On');
应该最有可能使用"
个'
引号。