我有一个需要:使用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}$