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}$
總結
以上是生活随笔為你收集整理的python和arduino串口通信_利用串行通信实现python与arduino的同步的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: python列表的表示形式_python
- 下一篇: websocket python爬虫_p