【问题标题】:code docent work serial monitor and servos代码讲解工作串行监视器和伺服系统
【发布时间】:2020-06-30 20:31:16
【问题描述】:

我正在尝试用鼠标控制 2 个伺服系统。我有一个 python 程序寻找我的鼠标线并通过串行监视器将它们发送到 Arduino。我可以运行这两个程序而不会阻止我,但是当我运行它们来处理每个程序时,什么都没有发生,python 程序被用来打印我的电线,所以我知道它是否在工作,但我不知道它是否正在将电线发送到阿杜诺。这是我的代码,任何帮助都会被学徒。

Arduino 代码:

#include <Servo.h>

//1439
//899
Servo myservo;
Servo myservo1; 

//String cordXstr;
//String cordYstr;
String cord; 
int cordx = 0;
int cordy = 0;  

 
void setup() {
  myservo.attach(9);
  myservo1.attach(10);
  Serial.begin(9600);
}
 
void loop() {
cord = Serial.read();
if (cord[0] == 'x'){
      cord.remove(0,1);
    cordx = cord.toInt();

 }
 cord = Serial.read();
    if (cord[0] == 'y'){
    cord.remove(0,1);
    cordy = cord.toInt();

 }
  

    cordx = map(cordx, 0, 1439, 0, 180);     
    myservo.write(cordx);                  
    delay(15);       
    cordy = map(cordy , 0, 899, 0, 180);     
    myservo.write(cordy);                  
    delay(15);
  
}

python 代码

import serial
import pyautogui
ser = serial.Serial('/dev/tty.usbmodem14101', 9600)
while True:
    x, y = pyautogui.position()
    ser.write("x",x)
    ser.write("y",y)
    print(pyautogui.position())

【问题讨论】:

  • Serial.read() 读取单个字节而不是字符串。
  • “电线?”这个问题完全看不懂。
  • TomServo,cords 是坐标的缩写形式。
  • 像这个星球上的其他人一样使用坐标
  • ohhhhhhhhh 等待人们说坐标?我一直以为是绳子

标签: python arduino


【解决方案1】:

我可以同时运行这两个程序

怎么做?

您的 Arduino 草图无法编译,因为您从未声明 myservo

ser.write("x"x) 导致语法错误。你的意思是"x"+`x` (我不是 Python 专家)

您缺乏串行通信的基础知识。您尝试写 'x' 后跟一个整数。然后您尝试读取单个字节,如果等于“x”,则删除该字节的第一个字符(您只有 1 个!),然后将其转换为整数。 然后你读取第二个字节并尝试犯同样的错误,甚至没有检查你是否收到了一些东西。

请参阅 Arduino 手册,了解您实际使用的功能是什么以及如何正确使用它们。

https://www.arduino.cc/reference/en/language/functions/communication/serial/

做一些 Arduino / Python 系列教程也会有所帮助。

【讨论】:

  • k 谢谢,我对串行监视器和 Arduino 很陌生,我会去查看这些链接,感谢您的帮助
  • 我也不知道为什么我可以同时运行这两个程序都可以正常工作
猜你喜欢
  • 2017-06-11
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2010-11-03
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多