我正在尝试编写一个代码,允许我使用 Python 代码将输出发送到我的微控制器(Sparkfun Redboard)。
我想传递不同的变量(CMJ 或 SJ),如果传递 CMJ,我希望内置 LED 打开(并保持打开状态);如果传递 SJ,则关闭(并保持关闭状态)。如果通过了其他任何内容,我还想打印(“无效”)。
这是我的Python代码:
import serial
import time
# Setup serial communication
serialcomm = serial.Serial("COM4", 500000)
serialcomm.timeout = 1
# Define your variable
activity = "CMJ" # Change this to "CMJ" or anything else to test different scenarios
while True:
if activity == "done":
print("finished")
break
elif activity == "CMJ":
command = "on"
elif activity == "SJ":
command = "off"
else:
command = "invalid"
# Send the command to the Arduino
serialcomm.write(('command'+'\n').encode()) # Send command with newline character
# Wait for a moment to ensure the command is processed
time.sleep(0.5)
# Read and print the response from the Arduino
response = serialcomm.readline().decode('ascii').strip()
print(response)
# Close the serial communication when done
serialcomm.close()
和我的 Arduino 代码:
String InBytes;
void setup() {
Serial.begin(500000); // Ensure this matches the Python code
pinMode(LED_BUILTIN, OUTPUT); // Set the LED pin as an output
digitalWrite(LED_BUILTIN, LOW); // Ensure the LED is off initially
}
void loop() {
if (Serial.available() > 0) {
InBytes = Serial.readStringUntil('\n'); // Read the incoming string until newline
InBytes.trim(); // Remove any leading or trailing whitespace/newline characters
// Debugging output
Serial.print("Received command: ");
Serial.println(InBytes);
if (InBytes == "on") {
digitalWrite(LED_BUILTIN, HIGH); // Turn the LED on
Serial.write("Led on"); // Send a response back
} else if (InBytes == "off") {
digitalWrite(LED_BUILTIN, LOW); // Turn the LED off
Serial.write("Led off"); // Send a response back
} else {
Serial.write("Invalid"); // Handle invalid commands
}
}
}
结果是,无论我传递什么变量(CMJ、SJ或其他任何变量),LED都会闪烁一秒钟。代码一定有问题,但无法弄清楚。
仔细查看您的代码,错误在于您正在使用
('command'+'\n').encode()
。在这种情况下,arduino 将获取字符串 "command\n"
。
要修复它,请在 python 端使用它:
# Setup serial communication
serialcomm = serial.Serial("COM4", 500000)
serialcomm.timeout = 1
# Define your variable
activity = "CMJ" # Change this to "CMJ" or anything else to test different scenarios
while True:
try:
if activity == "done":
print("finished")
break
elif activity == "CMJ":
command = "on"
elif activity == "SJ":
command = "off"
else:
command = "invalid"
command += "\n"
serialcomm.write(command.encode()) # Send command with newline character
time.sleep(0.5)
response = serialcomm.readline().decode('ascii').strip()
print(response)
except KeyboardInterrupt:
print("Goodbye!")
serialcomm.close()
break
请注意,我添加了一个
try:except
语句,像这样,循环将继续,直到有人使用cntrl+c
,此时脚本将结束,serialcomm
将被关闭。
希望这有帮助。
还有我这边的“证据”:
注意:确保除了 python 脚本之外,无法从其他任何地方访问 arduino。否则,串口是“打开”的,尝试在 python 中访问它会抛出权限错误。