Hi everybody,
I recently started using arduino and I wanted to make an obstacle avoiding robot as a first robot project..
I know how to drive the motors and how to measure distance, and both of them workt great..
But when I combine the codes, the distance measuring starts to 'lag' and returns 0cm distance randomly between other distances..
I use this code..
int URPWM=3; // PWM Output 0-25000us,every 50us represent 1cm
int URTRIG=5; // PWM trigger pin
unsigned long time; // create a time variable
unsigned long urmTimer = 0; // timer for managing the sensor reading flash rate
unsigned int Distance=0;
uint8_t EnPwmCmd[4]={0x44,0x22,0xbb,0x01}; // distance measure command
int E1 = 5;
int M1 = 4;
int E2 = 6;
int M2 = 7;
void setup(){ // Serial initialization
Serial.begin(9600); // Sets the baud rate to 9600
pinMode(M1, OUTPUT);
pinMode(M2, OUTPUT);
PWM_Mode_Setup();
}
void loop(){
if(millis()-time>=20){ // interval 0.02 seconds
time=millis(); // get the current time of program
}
if(millis()-urmTimer>50){
urmTimer=millis();
PWM_Mode();
}
}
void PWM_Mode_Setup(){
pinMode(URTRIG,OUTPUT); // A low pull on pin COMP/TRIG
digitalWrite(URTRIG,HIGH); // Set to HIGH
pinMode(URPWM, INPUT); // Sending Enable PWM mode command
for(int i=0;i<4;i++){
Serial.write(EnPwmCmd[i]);
}
}
void PWM_Mode(){ // a low pull on pin COMP/TRIG triggering a sensor reading
digitalWrite(URTRIG, LOW);
digitalWrite(URTRIG, HIGH); // reading Pin PWM will output pulses
unsigned long DistanceMeasured=pulseIn(URPWM,LOW);
if(DistanceMeasured==50000){ // the reading is invalid.
Serial.print("Invalid");
}
else{
Distance=DistanceMeasured/50; // every 50us low level stands for 1cm
if(Distance > 15){
digitalWrite(M1, HIGH);
digitalWrite(M2, HIGH);
analogWrite(E1, 150);
analogWrite(E2, 150);
} else {
digitalWrite(M1, LOW);
digitalWrite(M2, LOW);
analogWrite(E1, 150);
analogWrite(E2, 150);
}
}
Serial.print("Distance=");
Serial.print(Distance);
Serial.println("cm");
}
and it it always prints this:
Distance = right distance
Distance = 0
Distance = right distance
Distance = 0
Distance = right distance
Distance = 0
etc..
But if I remove the if(distance > 15){ //code } else {//code }, then it just works fine..
Does anybody know what's wrong?
ps. The motor drive isn't wrong.. It just drives forward or backward.. I already tested that in a seperate sketch..
pps. The measuring code comes from dfrobot wiki