繁体   English   中英

Python不会写入Arduino串行

[英]Python doesn't write to Arduino serial

我是Arduino的新手,我只想左右旋转伺服电机。 我的arduino代码如下所示:

#include <Servo.h>

int servoPin = 9;

Servo myServo;
int pos1 = 0;

void setup() {

  Serial.begin(9600);
  myServo.attach(servoPin);

}

void loop() {
  myServo.write(180);
  delay(1000);
  myServo.write(0);
  delay(1000);
}

而且效果很好。 现在,我想使用python实现相同的功能,因此我的python代码如下所示:

import serial
import time

ser = serial.Serial('/dev/ttyACM0', 9600)
while True:
    print("Writing")
    ser.write("180;".encode())
    time.sleep(1)
    ser.write("0;".encode())
    time.sleep(1)

ser.close()

这段代码在日志中显示“ Writing”,但绝对不会执行任何操作。

您正在正确地向Arduino编写命令,而Arduino只是不在监听。 如果希望看到伺服运动,则需要读取Arduino端的串行端口。 这是从https://www.arduino.cc/en/Serial/Read上的Arduino文档中读取串行端口的示例

int incomingByte = 0;   // for incoming serial data

void setup() {
        Serial.begin(9600);     // opens serial port, sets data rate to 9600 bps
}

void loop() {

        // send data only when you receive data:
        if (Serial.available() > 0) {
                // read the incoming byte:
                incomingByte = Serial.read();

                // say what you got:
                Serial.print("I received: ");
                Serial.println(incomingByte, DEC);
        }
}

使用某些if-else逻辑或字符串到整数的转换来修改它,以发送所需的伺服命令。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM