Hey I am trying to make a self balancing car (two wheels on either sides ). I have got it to balance itself but it still struggles and adjusts a lot to balance. Here is the code I used
#include <Wire.h>
const int MPU_addr=0x68;
int16_t AcX,AcY,AcZ,Tmp,GyX,GyY,GyZ;
int minVal=265; int maxVal=402;
double x; //A4 (SDA), A5 (SCL)
double y;
double z;
int lmt1=6;
int lmt2=5;
int rmt1=10;
int rmt2=9;
int value;
void setup(){
pinMode(lmt1,OUTPUT);
pinMode(lmt2,OUTPUT);
pinMode(rmt1,OUTPUT);
pinMode(rmt2,OUTPUT);
Wire.begin();
Wire.beginTransmission(MPU_addr);
Wire.write(0x6B); Wire.write(0);
Wire.endTransmission(true);
Serial.begin(9600); }
void loop(){
Wire.beginTransmission(MPU_addr);
Wire.write(0x3B);
Wire.endTransmission(false);
Wire.requestFrom(MPU_addr,14,true);
AcX=Wire.read()<<8|Wire.read();
AcY=Wire.read()<<8|Wire.read();
AcZ=Wire.read()<<8|Wire.read();
int xAng = map(AcX,minVal,maxVal,-90,90);
int yAng = map(AcY,minVal,maxVal,-90,90);
int zAng = map(AcZ,minVal,maxVal,-90,90);
x= RAD_TO_DEG * (atan2(-yAng, -zAng)+PI);
y= RAD_TO_DEG * (atan2(-xAng, -zAng)+PI);
z= RAD_TO_DEG * (atan2(-yAng, -xAng)+PI);
y=y-78;
if(y<(-1) || y>1){
if(y<0){//backward tilt
y=y*(-1);
value=map(y,0,20,0,255);
analogWrite(lmt1,0);
analogWrite(lmt2,value);
analogWrite(rmt1,0);
analogWrite(rmt2,value);
}
else if(y>0){// forward tilt
value=map(y,0,20,0,255);
analogWrite(lmt1,value);
analogWrite(lmt2,0);
analogWrite(rmt1,value);
analogWrite(rmt2,0);
}}
}
The code is actually is done using very basic algorithms. Is there any way to like make this code little better (I tried using code from online, youtube etc. None of them are like suitable with the hardwares I use or too complicated to modify). I also want to make this remote controlled but I don't know how to tackle the problem where I have to maintain balance at the same time move the robot.
Thanks for helping.