QTR-1RC reflectance sensor simpler code


hey everybody!
working @ project implied huge amount of sensors on mini rover, stumped upon problem of insuficient memory code. 1 of sensors qtr-1rc reflectence sensor, used read speed of rover reading alternance of black , white  grid sticked on wheels:

initialy using qtrsensors libry pololu:https://github.com/pololu/qtr-sensors-arduino , using library sketch qtr had 5,278 bytes. after optimizing , geting rid of library, sketch 3,318bytes. know not big difference project every byte counted.
so, how did got rid of library? read how sensor works , code myself.
firstly, qtr-1rc? pololu qtr-1rc reflectance sensor carries single infrared led , phototransistor pair. phototransistor uses capacitor discharge circuit allows digital i/o line on microcontroller take analog reading of reflected ir measuring discharge time of capacitor. shorter capacitor discharge time indication of greater reflection.

the typical sequence reading sensor is:

set i/o line output , drive high
allow @ least 10 10 nf capacitor charge
make i/o line input (high impedance)
measure time capacitor discharge waiting i/o line go low

so it's simple, followed steps above , done.
here code used:
code: [select]
unsigned long time;
int color=1,last,last_color;
void setup()
{
serial.begin(9600);
}
void loop()
{
pinmode(9,output);
digitalwrite(9,high);
delaymicroseconds(12);
pinmode(9,input);
time=micros();
while(digitalread(9)) {}
// serial.println(micros()-time);
 
 if((micros()-time)>last && color==1) color=-1;
     else if((micros()-time)<last && color==-1) color=1;
 
   if(color!=last_color) serial.print(color),serial.println(" ");
   last=micros()-time;
   last_color=color;
}

this code returns 1 white , -1 black.
if not working black , white , want response time value use code has 2,948bytes:
code: [select]
unsigned long time;
void setup()
{
serial.begin(9600);
}
void loop()
{
pinmode(9,output);
digitalwrite(9,high);
delaymicroseconds(12);
pinmode(9,input);
time=micros();
while(digitalread(9)) {}
serial.println(micros()-time);

}

just remember lower value it's higer reflectence.
i hope useful you:d

thanks sharing,

some small remarks:
the code contains @ least 1 possible bug value last not explicitly specified first iteration.

if timing in low microseconds 1 might consider direct port manipulation faster digitalread()..
also 1 might use hardware timer instead more precise timing micros() goes in steps of 4 @ time..





Arduino Forum > Using Arduino > Sensors > QTR-1RC reflectance sensor simpler code


arduino

Comments

Popular posts from this blog

opencv3, tbb and rasp pi 2 - Raspberry Pi Forums

small ethernet problem - Raspberry Pi Forums

Multithumb configuration params not working? - Joomla! Forum - community, help and support