Im making an object avoiding robot and I was going to use an IR distance sensor, but when I got it, it gave extremely fluctuating results that it would not even perform at all. to convert the non linear readings to linear i used the formula range = (6787/(logicvalue-3))-4 even with this conversion, my IR sensor would set off my motor reactions at completely random instances. Basically I have no control whatsoever over the IR sensor and I am looking for a solution. Would an ultrasonic sensor do this as well? I will attach my code and would appreciate any advice!! thank you. Im using an arduino uno with motor shield.
int sensorPin = A0;
int sensorValue = A0;
void setup(){
Serial.begin(9600);
pinMode(13,OUTPUT); //direction of ch. B
pinMode(12,OUTPUT); //direction of ch. A
pinMode(11,OUTPUT); //PWM ch. B
pinMode(3,OUTPUT); //PWM ch. A
pinMode(8,OUTPUT); //Brake B
pinMode(9,OUTPUT); //Brake A
}
void loop(){
int range = A0;
digitalWrite(8,LOW); //Brake B disengage
digitalWrite(9,LOW); //Brake A disengage
digitalWrite(12,0); //A forward
analogWrite(3,250); //A full speed/PWM
digitalWrite(13,255); //B forward
analogWrite(11,250); //B full speed/PWM
range = readDistance();
if (range < 16) {
digitalWrite(12,LOW); // may just want to engage brakes
digitalWrite(13,LOW);
delay(500);
//stop motors
digitalWrite(12,255); //A reverse
analogWrite(3, 123); //A half speed
digitalWrite(13,0); //B reverse
analogWrite(11, 123); //B half speed
delay(1500);
//reverse motors
digitalWrite(12,LOW);
digitalWrite(13,LOW);
delay(200);
//stops motors
digitalWrite(12,0); //A forward
analogWrite(3,250); //A speed
digitalWrite(13,0); //B reverse
analogWrite(11,250); //B speed
delay(2000);
//zero degree turn
}
}
int readDistance(){
sensorValue=analogRead(sensorPin);
if (sensorValue > 3){
int range = (6787 / (sensorValue-3)) - 4;
return(range);
}
}
I'm confused then, whats this bit about in the arduino reference.
The analogRead command will not work correctly if a pin has been previously set to an output, so if this is the case, set it back to an input before using analogRead.
int sensorPin = A0; // Good
int sensorValue = A0; // Not good set to ZERO, not A0
int range = A0; // Not good set to ZERO, not A0
Where did you get that quote?
The analogRead command will not work correctly if a pin has been previously set to an output, so if this is the case, set it back to an input before using analogRead
AnalogREAD is looking for an INPUT, but can't, if it is set as an OUTPUT.
Fair enough, I guess I wasn't sure if there was a default and if that default was input. I'm also not sure about how setting pinmode in one sketch effects subsequent steps, i.e. do pinModes carry over if you don't set them again.