我是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报告错误,则可以尝试以下方法:
说明:
Python字符串可以以下列方式转换为字节:
更改:
编码的字符串被转换为字节,不再被视为字符串。你知道吗
您可以在documentation中探索这个主题。你知道吗
相关问题 更多 >
编程相关推荐