I am trying to create an optical encoder with an ir sensor. to do this i am using the Sharp IR sensor that will reflect off of a white board that has black segments painted onto it. The sensor is to take the time at the beginning of each black segment and calculate the time it took to go between each of those black segments. I have put together a code that seems to me would work but obviously is not and i cant figure out what is wrong. If anybody has any ideas please let me know. Attached is a diagram of the setup to visualize what i mean. The sensor will be connected to an analog pin and that is why the pinmode has been commented out because someone told me i need to initialize the pin but since it is analog and pinmode is a digital function i dont believe i need it.
The issue that i am having is that the serial monitor continuously prints values when it is in a white segment and none when it is in a black segment. also it prints both positive and negative values and there should be no reason to be printing a negative value.
//User Changeable Variables
int desiredRevs = 3;
int WheelResolution = 3;
//DO NOT CHANGE ANYTHING BEYOND THIS POINT
int SensorPin = A0;
int time1 = 0;
int time2 = 0;
int time3 = 0;
int Flag0 = 0;
int Flag1 = 0;
int Flag2 = 0;
int Flag3 = 0;
int desiredPulses = WheelResolution * desiredRevs;
int val = 0;
int couple = 0; //1 = beginning of first black, 2 = beginning of white
int status1 = 0;
int deltaT = 0;
int pulses = 0;
void setup()
{
//pinMode(SensorPin, INPUT);
Serial.begin(9600);
}
void loop()
{
if (pulses <= desiredPulses)
{
val = analogRead(SensorPin);
if (val >= 50)
{
Flag1 = 1;
status1 = 1;//black
}
else
{
Flag1 = 0;
status1 = 0;//white
}
if ( Flag1 == 1 && couple == 0 && status1 ==1)
{
couple = 1;
time1 = micros() ;
Serial.print(time1);
}
else if ( Flag1 == 0 && couple == 1 && status1 == 0)
{
couple = 2;
time2 = micros();
Serial.print(time2);
}
else if ( Flag1 == 1 && couple == 2 && status1 == 1)
{
time3 = micros();
Serial.print(time3);
//deltaT = time3 - time1;
Serial.println(deltaT);
couple = 1;
time1 = time3;
}
}
else
Serial.println("Done");
}