无法将1或0写入Arduino serial p

2024-04-25 20:35:32 发布

您现在位置:Python中文网/ 问答频道 /正文

我是Python 3和Arduino Uno的初学者。我正在尝试从Python命令行控制板上的LED。你知道吗

Arduino代码:

const int led=13;
int value=0;

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


void loop() 
{
  while (Serial.available())
  {
    value = Serial.read();
  }

  if (value == '1')
    digitalWrite (led, HIGH);
  else if (value == '0')
    digitalWrite (led, LOW);
}

Python代码:

import serial                                 # add Serial library for Serial communication

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('1')             #send 1 to arduino
        print ("LED ON")


    if (input_data == '0'):                   #if the entered data is 0
        Arduino_Serial.write('0')             #send 0 to arduino 
        print ("LED OFF")

我得到以下错误:

TypeError: unicode strings are not supported, please encode to bytes: '1'

Tags: theto代码inputdataledifvalue
1条回答
网友
1楼 · 发布于 2024-04-25 20:35:32

如果Python报告错误,则可以尝试以下方法:

import serial                                 # Add Serial library for Serial communication

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 
        one_encoded = str.encode('1')
        Arduino_Serial.write(one_encoded)             #send byte encoded 1 to arduino
        print ("LED ON")


    if (input_data == '0'):                   #if the entered data is 0
        zero_encoded = str.encode('0')
        Arduino_Serial.write(zero_encoded)             #send byte encoded 0 to arduino 
        print ("LED OFF")

说明:

Python字符串可以以下列方式转换为字节:

old_string = 'hello world'
old_string_to_bytes = str.encode(old_string)

更改:

old_string = 'hello world'
old_string_to_bytes = old_string.encode()

编码的字符串被转换为字节,不再被视为字符串。你知道吗

>>> type(old_string_to_bytes)
<class 'bytes'>

您可以在documentation中探索这个主题。你知道吗

相关问题 更多 >