【问题标题】:arduino turning on/off led using pySerialarduino 使用 pySerial 打开/关闭 LED
【发布时间】:2015-01-12 03:29:36
【问题描述】:

我正在尝试在 arduino 和 pySerial 之间进行通信,但是串行监视器给我返回了奇怪的字符,因此 arduino 没有像应有的那样打开/关闭 LED。提前致谢。

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 向 arduino 发送 0 后,串行监视器上出现以下内容 F 1

发送 1 后

同样的东西出现

【问题讨论】:

    标签: python arduino pyserial


    【解决方案1】:

    这段代码:

    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');
    

    应该很可能使用" instad of ' 引号。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2019-04-29
      相关资源
      最近更新 更多