please provide an example of controlling two motors in pwm to run straight by yaw mesagges in c
时间: 2024-06-03 22:09:35 浏览: 8
Sure, here's an example code snippet for controlling two motors in PWM to run straight by yaw messages in C:
#include <Servo.h>
int motorPin1 = 9; // motor 1 PWM pin
int motorPin2 = 10; // motor 2 PWM pin
int yawPin = A0; // yaw sensor pin
Servo motor1; // motor 1 object
Servo motor2; // motor 2 object
int yawThresh = 512; // yaw threshold for straight running
int motorSpeed = 50; // motor speed
void setup() {
motor1.attach(motorPin1); // attaches the motor 1 object to the PWM pin
motor2.attach(motorPin2); // attaches the motor 2 object to the PWM pin
}
void loop() {
int yawVal = analogRead(yawPin); // reads the yaw sensor value
if (yawVal < yawThresh) { // turn left
motor1.write(0); // set motor 1 to full speed
motor2.write(motorSpeed); // set motor 2 to half speed
} else if (yawVal > yawThresh) { // turn right
motor1.write(motorSpeed); // set motor 1 to half speed
motor2.write(0); // set motor 2 to full speed
} else { // go straight
motor1.write(motorSpeed); // set motor 1 to half speed
motor2.write(motorSpeed); // set motor 2 to half speed
}
}
I hope this helps! Let me know if you have any other questions.