我是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'
答案 0 :(得分: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。
中探讨此主题