[英]arduino turning on/off led using pySerial
I am trying to communicate between arduino and pySerial but the serial monitor is giving me back weird characters so the arduino is not turning on/off led like it should. 我正在尝试在arduino和pySerial之间进行通信,但是串行监视器给了我一些奇怪的字符,因此arduino并未像应有的那样打开/关闭。 Thanks in advance. 提前致谢。
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 code 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
after sending a 0 from python to arduino the following appears on the serial monitor F 1 < 从python向arduino发送0后,串行监视器F 1 <
after sending a 1 发送1后
the same thing appears 出现同样的事情
The piece of code: 这段代码:
state = Serial.read() -'0';
val = char(state);
Serial.println(val);
will print a (char) 0
instead of a '0'
and a (char) 1
instead of '1'
. 将打印(char) 0
而不是'0'
和(char) 1
而不是'1'
。 Also you compare val with character constants as if it was a character. 同样,您将val与字符常量进行比较,就好像它是一个字符一样。 However your code converts it to integer values that you store in a character. 但是,您的代码会将其转换为存储在字符中的整数值。
→ You should make up your mind about what types your variables are and what you store in them. →您应该确定变量的类型以及它们存储的内容。
In addition 此外
Serial.println('LED : Off');
and 和
Serial.println('LED : On');
should most probably use "
instad of '
quotation marks. 应该最有可能使用"
instad '
引号。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.