gpt4 book ai didi

python - 无法向Arduino串口写入1或0

转载 作者:太空宇宙 更新时间:2023-11-03 14:05:04 24 4
gpt4 key购买 nike

我是 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'

最佳答案

如果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中探索这个主题。 .

关于python - 无法向Arduino串口写入1或0,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48962827/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com