python和arduino串口通信_利用串行通信实现python与arduino的同步

我有一个需要:使用arduino将伺服电机移动到某个位置并在该位置停止

让一个由python控制的相机在那个位置获取图像

当图像被采集到时,伺服机构应该移动到一个对称的位置

这个序列重复N次

所以我尝试使用串行通信同步arduino和python代码。在arduino端,当伺服到达某个位置时,它使用串行通信向python代码发送一个字符串。根据到达的位置,字符串可以是“Cross”或“Co”。arduino应该等待python代码通过串行通信发送一个字符串“Ok”(在图像采集之后)。接收到该串后,arduino应启动伺服,使其移动到另一个位置。在

在python代码方面,我读取串行数据,根据接收到的字符串(Cross或Co):定义了字符串名称

使用照相机获取图像

图像将被保存或附加到列表中

字符串“Ok”被发送到arduino。在

代码附在下面。在

问题是我不能正确同步伺服位置和图像采集。串行读写器似乎并没有从两个位置来回读伺服。它永远不会停在某个位置上。然而,arduino代码确实向python代码发送“Cross”和“Co”,python代码确实能够读取它们并获取和保存图像,但通常使用错误的名称。让arduino代码在每个位置等待足够长的时间不是解决方案,因为我需要一个合适的图像采集频率。

所以我想知道什么是最好的方式来同步两个代码,并确保,我的图像的正确名称将对应于正确的位置伺服?在

提前感谢任何链接或想法。在

格雷格

arduino代码

`在#include

//servo

Servo myservo; // create servo object to control a servo

// twelve servo objects can be created on most boards

int pos = 0; // variable to store the servo position

//camera

const int CameraPin = 53; // the number of the camera trigg

int CameraState = LOW; // ledState used to set the LED

const int ledPin = 13; // the number of the LED pin

String Str = "c";

void setup() {

myservo.attach(9); // attaches the servo on pin 9 to the servo object

// set the digital LED pin as output:

pinMode(CameraPin, OUTPUT);

// set the digital camera pin as output:

pinMode(ledPin, OUTPUT);

//serial communication

Serial.begin(9600);

Serial.println("Ready");

}

void loop() {

Serial.flush();

// go to Co position and wait

ServoCo(15); // go to Co position

Serial.println("Co"); //send signal Co to python

while(!Serial.available()) {} // wait for python to send data acquired

while ((Serial.available()<2)) // Test on the length of the serial string

{

delay(1);

String Str = Serial.readStringUntil('\n');

Serial.println(Str);

}

// go to cross position and wait

ServoCross(15); // go to Cross position

Serial.println("Cross");

while(!Serial.available()) {}

while ((Serial.available()<2))

{

delay(1);

String Str = Serial.readStringUntil('\n');

Serial.println(Str);

}

}

delay(100);

}

void ServoCross(int ServoDelay)

{

for (pos = 105; pos >= 75; pos -= 1) { // goes from 0 degrees to 180 degrees

// in steps of 1 degree

myservo.write(pos); // tell servo to go to position in variable 'pos'

delay(ServoDelay);

}

}

void ServoCo(int ServoDelay)

{

for (pos = 75; pos <= 105; pos += 1)

{ // goes from 0 degrees to 180 degrees

// in steps of 1 degree

myservo.write(pos); // tell servo to go to position in variable 'pos'

delay(ServoDelay);

}`

Python代码:

^{pr2}$

  • 0
    点赞
  • 5
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值