从其他函数调用serial.read

时间:2019-05-26 20:49:01

标签: python arduino

我正在尝试使用串行连接python与Arduino代码,但无法在serial.read()函数中调用led_on_off()

这是Arduino代码:

int led=13;
int val=0;
char functionname='K';
#include <string.h>
void setup() 
   { 
      Serial.begin(9600); 
      pinMode(led, OUTPUT);
      digitalWrite (led, LOW);
      Serial.println("Connection established...");
   }

void loop()
{

    functionname = Serial.read();
 if (functionname= 'L')
  {
    led_on_off();
    }

 }//void loop
void led_on_off()
{
  val=Serial.read()
  if (val= 1)
  digitalWrite(led,HIGH) 
  else if (val == 0)
  digitalWrite(led,LOW)
}

这是python代码:

import serial    


Arduino_Serial = serial.Serial('com18',9600)  # Create Serial port object called arduinoSerialData
print(Arduino_Serial.readline())             # read the serial data and print it as line
print("Enter L to ON LED and M dc motor") 



input_data = input()                  
Arduino_Serial.write(input_data.encode())
print(Arduino_Serial.readline())
input_value=input("enter 1 or 0")      
Arduino_Serial.write(input_value.encode())            

我的期望是从Python代码获取输入(1 or 0),并使用serial.read()函数在Arduino代码的led_on_off函数中对其进行处理,然后打开或关闭引脚13的led。

1 个答案:

答案 0 :(得分:0)

如@KIIV所述,您的Arduino代码有一些语法错误。除此之外,您还从Python脚本(input函数)发送了一个字符串,因此您需要在Arduino上将其作为字符串读取。像这样的事情就可以完成工作:

Python脚本:

import serial


# Create Serial port object called arduinoSerialData
Arduino_Serial = serial.Serial('com18', 9600)
# read the serial data and print it as line
print(Arduino_Serial.readline())

input_data = input("Enter L to ON LED and M dc motor: ")
Arduino_Serial.write(input_data.encode())
print("Received Command:", Arduino_Serial.readline())
while True:
    input_value = input("enter 1 or 0")
    Arduino_Serial.write(input_value.encode())

Arduino代码:

int led = 13;

void setup()
{
    Serial.begin(9600);
    pinMode(led, OUTPUT);
    digitalWrite(led, LOW);
}

void loop()
{
    //void loop
    if (Serial.available())
    {
        String functionname = Serial.readString();
        if (functionname == "L")
        {
            Serial.println("Command received from Arduino!");
            while (1)
            {
                led_on_off();
            }
        }
    }
}
void led_on_off()
{
    if (Serial.available())
    {
        String val = Serial.readString();
        if (val == "1")
            digitalWrite(led, HIGH);
        else if (val == "0")
            digitalWrite(led, LOW);
    }
}