Hello, I am having trouble with the IR sensor.
I am trying to make a robot that runs 2 dc motors and 2 IR sensor with arduino. I am using a breadboard, arduino uno, 2dc motor, 2 sharp infrared sensor (says 2Y0A21 for model?) and an h bridge chip. The way I want to have it set up is the pin connected to the IR sensor will tell the motors to start or stop based on distance from the IR sensor. A chart i read online says the IR sensor is supposed to return a voltage to the pin based on the distance it reads. (around 3v max at 15cm )
http://3.bp.blogspot.com/-jd2TQQlOo1Q/TzKvUP5uE-I/AAAAAAAAAZ8/o_TNffud7_g/s1600/Slika04.jpg When i first upload my code and have the sensor pointed in a direction, the motors will run based on how far the sensor is from something. Right now it will only run when something is from 10cm -40cm (2V). However they only work correctly RIGHT AFTER i upload my code to the arduino. After that the motors will stay spinning or stay stopped. Shouldn't the void loop just keep looping and get new values though? Or do I need to write another loop to constantly acquire new voltage values for the pin for when the distance changes? Any ideas?
Here is the code.
const int switchPin = 2; // switch input
const int motor1Pin = 3; // H-bridge leg 1 (pin 2, 1A)
const int motor2Pin = 4; // H-bridge leg 2 (pin 7, 2A)
const int MOTOR1PIN = 5;
const int MOTOR2PIN = 6;
const int enablePin = 9; // H-bridge enable pin
const int ENABLEPIN = 10;
int sensorpin = 0;
double value;
void setup()
{
// set all the other pins you're using as outputs:
pinMode(MOTOR1PIN, OUTPUT);
pinMode(MOTOR2PIN, OUTPUT);
pinMode(motor1Pin, OUTPUT);
pinMode(motor2Pin, OUTPUT);
pinMode(enablePin, OUTPUT);
pinMode(ENABLEPIN, OUTPUT);
// set enablePin high so that motor can turn on:
digitalWrite(enablePin, HIGH);
digitalWrite(ENABLEPIN, HIGH);
}
void loop()
{
value = analogRead(sensorpin);
// if the sensor pin is greater than 2Volts
if (value >2) {
digitalWrite(motor1Pin, LOW); // set leg 1 of the H-bridge low
digitalWrite(motor2Pin, HIGH); // set leg 2 of the H-bridge high
digitalWrite(MOTOR1PIN, LOW);
digitalWrite(MOTOR2PIN, HIGH);
}
else
{
digitalWrite(enablePin, LOW);
digitalWrite(ENABLEPIN, LOW
}
}