我正在尝试通过相同的串行2伺服器和距离传感器进行连接。在Arduino中,我有这段代码。如果我将Arduino的串行监控器值写入120,120之类的伺服器中,它将起作用。我用python编写了一个程序来根据传感器的结果更改值,但是该程序发送值,但是什么也没有发生。你能帮我做错什么吗?
#include <NewPing.h>
#include <Servo.h>
#define TRIGGER_PIN 12 // Arduino pin tied to trigger pin on the ultrasonic sensor.
#define ECHO_PIN 11 // Arduino pin tied to echo pin on the ultrasonic sensor.
#define MAX_DISTANCE 200 // Maximum distance we want to ping for (in centimeters). Maximum sensor distance is rated at 400-500cm.
NewPing sonar(TRIGGER_PIN, ECHO_PIN, MAX_DISTANCE); // NewPing setup of pins and maximum distance.
Servo servo1;
Servo servo2;
int num1,num2;
void setup()
{
servo1.attach(9);
servo2.attach(10);
Serial.begin(115200); // Open serial at 115200 baud to see ping results.
}
void loop()
{
Serial.println(sonar.ping_cm(),DEC);
num1= Serial.parseInt();
num2= Serial.parseInt();
servo1.write(num1);
servo2.write(num2);
}
使用python编程
if mean10 > 8:
ser.write( "130,130".encode())
else:
ser.write( "30,30".encode())
答案 0 :(得分:0)
这是我尝试过的,但已解决了。希望它也对您有用。
Arduino代码:
Serial.println(sonar.ping_cm(),DEC);
num = Serial.parseInt();
num1= num / 1000;
num2= num % 1000;
servo1.write(num1);
servo2.write(num2);
Python代码:
if mean10 > 8:
data = "130" + "130"
ser.write(data.encode())
else:
data = "030" + "030"
ser.write(data.encode())
或者:
Arduino Side:
Serial.println(sonar.ping_cm(),DEC);
num = Serial.parseInt();
if(num == 1){
num1 = 30;
num2 = 30;
}
else if(num == 2){
num1 = 130;
num2 = 130;
}
servo1.write(num1);
servo2.write(num2);
Python代码:
if mean10 > 8:
data = 1
ser.write(data)
else:
data = 2
ser.write(data)