Hello, im trying to make a RC car controlled with gyroscope!
I can't get both motors to spin at the same time! and when trying to testing, it takes a few seconds then the serial freezes and one or two motors will spin constantly. this is the only time where both motors will spin at the same time.
please help me ! thx
#include <MPU6050_light.h>
#define enA 13
#define in1 12
#define in2 11
#define enB 10
#define in3 8
#define in4 9
int motorSpeedA = 0;
int motorSpeedB = 0;
MPU6050 mpu(Wire);
void setup() {
Serial.begin(9600);
pinMode(enA, OUTPUT);
pinMode(enB, OUTPUT);
pinMode(in1, OUTPUT);
pinMode(in2, OUTPUT);
pinMode(in3, OUTPUT);
pinMode(in4, OUTPUT);
byte status = mpu.begin();
Serial.println("Calculating offsets, do not move MPU6050");
delay(1000);
mpu.calcOffsets(true,true); //calibrating
Serial.println("Done!\n");
}
void loop() {
mpu.update();
if (mpu.getAngleX() > 30){
// Set Motor A forward
digitalWrite(in1, LOW);
digitalWrite(in2, HIGH);
//Set Motor B Forward
digitalWrite(in3, LOW);
digitalWrite(in4, HIGH);
motorSpeedA = map(mpu.getAngleX(), 0, 80, 0, 255);
motorSpeedB = map(mpu.getAngleX(), 0, 80, 0, 255);
Serial.print(map(mpu.getAngleX(), 0, 80, 0, 255));
}
else if (mpu.getAngleX() < -30){
// Set Motor A backward
digitalWrite(in1, HIGH);
digitalWrite(in2, LOW);
//Set Motor B backward
digitalWrite(in3, HIGH);
digitalWrite(in4, LOW);
motorSpeedA = map(mpu.getAngleX(), 0, -80, 0, 255);
motorSpeedB = map(mpu.getAngleX(), 0, 80, 0, 255);
Serial.print(map(mpu.getAngleX(), 0, 80, 0, 255));
}
// If joystick stays in middle the motors are not moving
else {
motorSpeedA = 0;
motorSpeedB = 0;
}
// X-axis used for left and right control
if (mpu.getAngleY() > 30) {
// Convert the declining X-axis readings from 470 to 0 into increasing 0 to 255 value
int xMapped = map(mpu.getAngleY(), 0, 80, 0, 255);
// Move to left - decrease left motor speed, increase right motor speed
motorSpeedA = motorSpeedA - xMapped;
motorSpeedB = motorSpeedB + xMapped;
// Confine the range from 0 to 255
if (motorSpeedA < 0) {
motorSpeedA = 0;
}
if (motorSpeedB > 255) {
motorSpeedB = 255;
}
}
if (mpu.getAngleY() < -30) {
// Convert the increasing X-axis readings from 550 to 1023 into 0 to 255 value
int xMapped = map(mpu.getAngleY(), 0, 80, 0, 255);
// Move right - decrease right motor speed, increase left motor speed
motorSpeedA = motorSpeedA + xMapped;
motorSpeedB = motorSpeedB - xMapped;
// Confine the range from 0 to 255
if (motorSpeedA > 255) {
motorSpeedA = 255;
}
if (motorSpeedB < 0) {
motorSpeedB = 0;
}
}
// Prevent buzzing at low speeds (Adjust according to your motors. My motors couldn't start moving if PWM value was below value of 70)
if (motorSpeedA < 70) {
motorSpeedA = 0;
}
if (motorSpeedB < 70) {
motorSpeedB = 0;
}
analogWrite(enA, motorSpeedA); // Send PWM signal to motor A
analogWrite(enB, motorSpeedB); // Send PWM signal to motor B
Serial.print("\tX:\t");Serial.print(mpu.getAngleX());
Serial.print("\tY:\t");Serial.print(mpu.getAngleY());
Serial.println();
}