Вот мой код Arduino:
Код: Выделить всё
void setup() {
Serial.begin(9600);
delay(1000);
}
void loop() {
if (Serial.available() > 0) { // check if there's data from python
String command = Serial.readStringUntil('\n'); // read python command
Serial.println(command); // show command in Arduino monitor
Serial.write("command\n");
if (command == "test") { // if command is "test"
Serial.write(1);} // Envoie 1 en tant que byte
else {
Serial.write(0);} // Envoie 0 en tant que byte
Serial.flush();
}
}
Код: Выделить всё
import serial
import time
capt = serial.Serial('COM5',9600,timeout=5)
def testcomm(test):
out = 0
com = (test + '\n').encode() # Send test command with end ligne indicator \n
print(f"Commande envoyée : {com}")
capt.write(com) # send command to Arduino
time.sleep(4)
# Check if there's data
if capt.in_waiting > 0 :
testout = capt.readline() # read
print(f'testout val (raw): {testout}') # show raw
if testout:
out = testout.strip() # clean answer
print(f'testout val (cleaned): {out}')
else:
print("Doesn't work")
return out
test1 = testcomm('test')
capt.close()
Код: Выделить всё
Commande envoyée : b'test\n'
Doesn't work
Я проверил, работает ли командная строка сама по себе внутри монитора Arduino, она работает, и он возвращает 1, но на самом деле я не могу прочитать это в Python.
Я также попробовал read(), readline() и readlines() на всякий случай.
Я пробовал много разных вещей , но я не уследил, извините, и тоже учился pyserial параллельно, поэтому многие мои попытки были просто странными.
Спасибо
Подробнее здесь: https://stackoverflow.com/questions/793 ... ork-help-m