A black plastic card, a black printed patch and black electrical tape can look similar to your eyes while returning different infrared signals. Before building a line-following robot, test that ambiguity on a stationary bench. This lesson measures material, distance and ambient-light effects, and lets the program answer unknown when the evidence does not fit either reference.
Use one Pololu QTR-1A analog reflectance board from the active two-pack, item2458, with an original Arduino UNO Rev3 using the ATmega328P and Arduino AVR Boards1.8.6. The older single-unit item958 is discontinued; QTR-1RC and generic comparator modules are different interfaces. IR means infrared, light beyond the red part of human vision. This experiment senses returned IR from its own light-emitting diode (LED); it is not a visible-colour camera.
What the three-wire sensor actually does
The QTR-1A contains an infrared LED and a phototransistor. The LED illuminates the nearby surface. A phototransistor changes its conduction with received light; together with the fitted pullup resistor it produces an analog output. For this exact module, more returned IR generally pulls the output voltage lower. Visible black is therefore not a sufficient specification of that voltage.
The manufacturer specifies5V operation, approximately17mA supply current, analog output from0V up to the supplied voltage, approximately3mm optimal distance and6mm maximum recommended distance. The board should be parallel to the surface. These are setup boundaries, not a promise to classify arbitrary materials at6mm. The measurement also depends on surface finish, angle, surrounding illumination and the geometry of the emitter/receiver pair.
An ADC, analog-to-digital converter, translates the output voltage into a number. The UNO’s ten-bit conversion returns0–1023 using its supply-based default reference. Sharing the sensor and ADC supply makes the reading partly ratiometric, meaning that a supply-proportional output is compared with a related reference. It does not cancel lamp changes, detector nonlinearity, optical distance or every supply effect in the emitter circuit.
Keep the electrical connection deliberately simple
- Original Arduino UNO Rev3/ATmega328P and a data-capable Universal Serial Bus (USB) cable; Arduino AVR Boards1.8.6 software baseline.
- One Pololu QTR-1A from item2458; three short jumper wires or soldered leads. Use the documented power, ground and output nets, not an assumed left-to-right header order.
- Optional100nF ceramic bypass capacitor, at least10V rating, from module supply to ground close to its pads if using jumper leads.
- A non-reflective spacer/mount for3.0,4.5 and6.0mm separation; ruler or calipers; a stable room lamp and several coupons larger than the sensor’s optical footprint.
- Two reproducibly positioned reference coupons, for example a matte white card labelledA and matte black tape labelledB. Also collect glossy black plastic, a black marker patch and another visibly similar material.

| UNO label | QTR-1A net | Purpose |
|---|---|---|
| 5V | Positive supply, VIN/VCC | Powers the sensor from the board rail; approximately17mA belongs in its supply budget. |
| GND | Ground | Common0V reference for power and analog output. |
| A0 | OUT | Analog input reading the sensor output. No output-driving mode or pullup is enabled. |
GPIO means general-purpose input/output, the controller’s programmable pins. Although an older manufacturer note discusses powering some sensors from a suitable GPIO, this build uses the5V rail. No digital pin supplies the LED, and there is no separate emitter-enable wire in our three-pad circuit. We do not invent an emitter-off sample for ambient subtraction.
A0 can encounter nearly5V here. Do not transfer this wiring directly to a3.3V-only ESP32 or Pico input. With power disconnected, identify the exact analog board, inspect solder joints and confirm all three nets. Power only through the UNO’s normal USB connection for this fixture; do not add a second5V source. No motor driver, relay or moving mechanism is connected.
Make a material-and-distance matrix
Mount the sensor face parallel to the coupon and measure separation from its optical face, rather than from a random mounting screw. Keep the same coupon position and orientation for every comparison. A thick replacement coupon can change the gap even when it rests on the same table; measure that change. Keep hands, cable shade and shiny nearby objects out of the optical path during capture.

Begin at3mm under one fixed ambient condition. Build fresh references at that distance, then test each material. Repeat the full reference procedure at4.5mm and6mm; do not carry one convenient threshold across all distances. After completing that matrix, change only ambient illumination and repeat. For example, use the same lamp with a fixed shade arrangement, then remove the shade without moving the sensor or coupons.
A glossy coupon can return a narrow specular reflection, like a mirror, while a matte coupon scatters light more broadly. Rotating a glossy coupon can therefore change the result while its visible colour stays the same. Record finish and orientation. The purpose is to expose this dependence before asking a robot to make a steering decision from it.
Use whole sample windows, not one attractive average
Every capture takes32 conversions with5ms delays between them, then records minimum, maximum and mean. The capture lasts roughly0.16seconds including conversion time; the delay is not a precision200Hz sample clock. A window containing a code0–2 or1021–1023 is rejected by our conservative near-rail policy. Such a result might be genuine optical clipping, a wiring problem or another limitation; software does not diagnose which.
Each reference window is expanded by12 ADC counts on both sides, limited to the legal code range. We require reference means at least80counts apart and the expanded bands to remain entirely separated. These are declared experimental quality rules, not Pololu error specifications or a trained classifier’s accuracy claim. If noisy reference windows overlap despite different means, calibration is rejected.
A new material is A_LIKE only if its entire useful window lies inside A’s expanded band; the same rule applies to B_LIKE. Everything between, outside, or spanning both bands becomes UNKNOWN_RANGE. A mean near A can hide a mixture of very different samples. Requiring the full observed window to fit makes that ambiguity visible; it still does not guarantee that future samples will remain inside it.
The reported relative coordinate is u=(mean−Amean)/(Bmean−Amean), computed only from accepted references and useful data. It is0 atA and1 atB even if their electrical order is reversed. It is not clamped: negative or greater-than-one results preserve evidence of a new condition beyond the references. It is not physical reflectance percentage, distance in millimetres or a visible-colour score.
For a synthetic example, Amean=110 and Bmean=765 with a target mean437.5 givesu=0.5. A window spanning100–775 can have a similar mean but must not be called halfway between two materials: it may contain movement, a border, flicker or a changing surface. The program keeps its range and returns unknown. A visually black test coupon can be A-like in IR without either the sensor or your eyes being “wrong.”
Bracket every material capture with referenceA
The program keeps calibration in RAM, random-access memory, so restarting removes it. Send a while referenceA is in place, then b with referenceB. Storing a newA deliberately discards the previousB. A valid pair permits a trial, but does not prove that lighting will stay unchanged afterwards.
For each material, perform v,m,v: verifyA before, capture the material, then restoreA and verify again. The firstv arms one material capture. The m result remains pending with no final classification. Only a successful secondv permits that pending result to be classified. If either reference check falls outside A’s band, REFERENCE_DRIFT discards the pending result and both references; repeat a,b under the new condition.
This bracketing can catch some movement or illumination changes, not every brief disturbance during the middle sample. The sensor’s own emitter remains powered throughout, and ambient IR is not subtracted. Likewise a disconnected analog wire can occasionally produce a plausible value; reference checks are evidence controls, not comprehensive wiring diagnostics. Every distance, ambient or mounting change requires a fresh reference pair.
Complete Arduino program
C++ is the programming language; the Arduino application programming interface (API) supplies calls such as analogRead, delay and Serial.print. This complete source needs no external sensor library. Create a sketch folder named reflectance_lab with an empty reflectance_lab.ino, and keep the complete downloaded .cpp file beside it. Select UNO and the pinned Arduino AVR Boards1.8.6 core, then compile the folder before any real trial. That future target build is not claimed by our host tests.
Open the serial monitor at115200 baud, the serial signaling rate. Send one command after physically placing the coupon; do not queue an entire command string while the surface stays unchanged. Capture output includes the board’s elapsed-time counter and capture duration, not a wall-clock timestamp. The serial console travels through the board’s USB connection.
Download full C++/Arduino source (ZIP; file: batch-005/code/uno-reflectance-calibration.cpp) · Blank coupon worksheet (ZIP; file: batch-005/code/uno-reflectance-calibration-observations-blank.csv)
/* Original UNO Rev3/ATmega328P; Arduino AVR Boards1.8.6; Pololu QTR-1A PID2458.
Keep this .cpp beside an empty reflectance_lab.ino in a reflectance_lab folder.
Host tests compile the same helpers/state machine; no AVR target build claimed. */
#include <stdint.h>
const uint8_t SAMPLE_COUNT=32;
const int MARGIN=12;
const double MIN_SPAN=80.0;
struct Window {
uint16_t lo,hi;uint32_t sum;uint8_t n;bool useful;
double mean() const {return n ? double(sum)/n : 0.0;}
};
Window collect_window(int (*read_sample)(),void (*wait_ms)(unsigned long)) {
Window w={1023,0,0,0,true};
for(uint8_t i=0;i<SAMPLE_COUNT;i++) {
int raw=read_sample();
if(raw<0 || raw>1023) w.useful=false;
else {
if(raw<w.lo)w.lo=raw;
if(raw>w.hi)w.hi=raw;
w.sum+=raw;w.n++;
if(raw<=2 || raw>=1021)w.useful=false; // Conservative rail policy.
}
if(i+1<SAMPLE_COUNT)wait_ms(5);
}
w.useful=w.useful && w.n==SAMPLE_COUNT;
return w;
}
struct Band {int lo,hi;};
Band band(const Window &w) {
Band b={int(w.lo)-MARGIN,int(w.hi)+MARGIN};
if(b.lo<0)b.lo=0;if(b.hi>1023)b.hi=1023;
return b;
}
bool inside(const Window &w,Band b) {
return w.useful && w.n==SAMPLE_COUNT && w.lo>=b.lo && w.hi<=b.hi;
}
enum CalState { CAL_MISSING,CAL_INVALID,CAL_SMALL_SPAN,CAL_OVERLAP,CAL_READY };
struct Calibration {
Window a,b;bool have_a,have_b;
CalState state() const {
if(!have_a || !have_b)return CAL_MISSING;
if(!a.useful || !b.useful || a.n!=SAMPLE_COUNT || b.n!=SAMPLE_COUNT)return CAL_INVALID;
double span=b.mean()-a.mean();
if(span>-MIN_SPAN && span<MIN_SPAN)return CAL_SMALL_SPAN;
Band aa=band(a),bb=band(b);
if(!(aa.hi<bb.lo || bb.hi<aa.lo))return CAL_OVERLAP;
return CAL_READY;
}
};
enum Kind { SAMPLE_INVALID,REFERENCE_INVALID,A_LIKE,B_LIKE,UNKNOWN_RANGE };
struct Analysis {Kind kind;double relative_coordinate;bool has_coordinate;};
Analysis analyze(const Calibration &c,const Window &w) {
Analysis out={REFERENCE_INVALID,0.0,false};
if(c.state()!=CAL_READY)return out;
out.kind=SAMPLE_INVALID;
if(!w.useful || w.n!=SAMPLE_COUNT)return out;
out.has_coordinate=true;
out.relative_coordinate=(w.mean()-c.a.mean())/(c.b.mean()-c.a.mean());
bool is_a=inside(w,band(c.a)),is_b=inside(w,band(c.b));
out.kind=is_a ? A_LIKE : is_b ? B_LIKE : UNKNOWN_RANGE;
return out; // Coordinate is not clamped and is not physical reflectance%.
}
enum Event { REFERENCE_A_STORED,REFERENCE_B_STORED,CALIBRATION_REJECTED,
NEED_CALIBRATION,BEFORE_ACCEPTED,WAIT_AFTER_REFERENCE,
TRIAL_COMPLETE,SEQUENCE_REJECTED,REFERENCE_DRIFT };
class Trial {
public:
Calibration cal;bool armed,pending;Window target;Analysis last;
Trial(){reset();}
void reset(){cal.have_a=cal.have_b=false;armed=pending=false;last={REFERENCE_INVALID,0.0,false};}
Event set_a(const Window &w){reset();cal.a=w;cal.have_a=true;return w.useful ? REFERENCE_A_STORED : CALIBRATION_REJECTED;}
Event set_b(const Window &w){armed=pending=false;if(!cal.have_a)return NEED_CALIBRATION;cal.b=w;cal.have_b=true;return cal.state()==CAL_READY ? REFERENCE_B_STORED : CALIBRATION_REJECTED;}
Event verify_a(const Window &w){
if(cal.state()!=CAL_READY)return NEED_CALIBRATION;
if(!inside(w,band(cal.a))){reset();return REFERENCE_DRIFT;}
if(pending){last=analyze(cal,target);pending=false;armed=false;return TRIAL_COMPLETE;}
armed=true;return BEFORE_ACCEPTED;
}
Event measure(const Window &w){
if(!armed || pending)return SEQUENCE_REJECTED;
target=w;armed=false;pending=true;return WAIT_AFTER_REFERENCE;
}
};
#ifndef HOST_TEST
#include <Arduino.h>
Trial experiment;
int sensor_read(){return analogRead(A0);}
void wait_ms(unsigned long ms){delay(ms);}
Window capture(){
unsigned long start=millis();
Window w=collect_window(sensor_read,wait_ms);
Serial.print(F("WINDOW,start_ms="));Serial.print(start);
Serial.print(F(",duration_ms="));Serial.print(millis()-start);
Serial.print(F(",n="));Serial.print(w.n);
Serial.print(F(",min="));Serial.print(w.lo);
Serial.print(F(",max="));Serial.print(w.hi);
Serial.print(F(",mean="));Serial.print(w.mean(),3);
Serial.print(F(",useful="));Serial.println(w.useful ? F("yes") : F("no"));
return w;
}
void event_report(Event e){
switch(e){
case REFERENCE_A_STORED:Serial.println(F("A_STORED: place referenceB; send b"));break;
case REFERENCE_B_STORED:Serial.println(F("CAL_READY: restore referenceA; send v"));break;
case CALIBRATION_REJECTED:Serial.println(F("CAL_REJECTED: check rails/span/overlap; restart a then b"));break;
case NEED_CALIBRATION:Serial.println(F("NEED_CALIBRATION: a then b"));break;
case BEFORE_ACCEPTED:Serial.println(F("BEFORE_OK: place test material; send m"));break;
case WAIT_AFTER_REFERENCE:Serial.println(F("PENDING: restore referenceA; send v; no final class yet"));break;
case SEQUENCE_REJECTED:Serial.println(F("SEQUENCE_REJECTED: follow v,m,v after calibration"));break;
case REFERENCE_DRIFT:Serial.println(F("REFERENCE_DRIFT: pending result discarded; repeat a,b"));break;
case TRIAL_COMPLETE:
Serial.print(F("TRIAL_COMPLETE,kind="));
switch(experiment.last.kind){
case A_LIKE:Serial.print(F("A_LIKE"));break;
case B_LIKE:Serial.print(F("B_LIKE"));break;
case UNKNOWN_RANGE:Serial.print(F("UNKNOWN_RANGE"));break;
default:Serial.print(F("SAMPLE_INVALID"));break;
}
Serial.print(F(",relative_coordinate="));
if(experiment.last.has_coordinate)Serial.println(experiment.last.relative_coordinate,4);
else Serial.println(F("unknown"));
break;
}
}
void setup(){
Serial.begin(115200);analogReference(DEFAULT);pinMode(A0,INPUT);
(void)analogRead(A0); // Allow reference/channel selection before trial.
Serial.println(F("QTR-1A PID2458 on UNO5V. a=Aref,b=Bref,v=verifyA,m=material,x=reset"));
Serial.println(F("32samples5ms; margin12counts,minspan80counts are experiment policy."));
}
void loop(){
if(!Serial.available())return;
char command=Serial.read();
switch(command){
case 'a':event_report(experiment.set_a(capture()));break;
case 'b':event_report(experiment.set_b(capture()));break;
case 'v':event_report(experiment.verify_a(capture()));break;
case 'm':event_report(experiment.measure(capture()));break;
case 'x':experiment.reset();Serial.println(F("RESET: calibration removed"));break;
case '\r':case '\n':case ' ':break;
default:Serial.println(F("Commands:a,b,v,m,x. Send one after placing the coupon."));break;
}
}
#endif
A practical trial order
- Inspect the exact board and power-off wiring. Fix3mm separation and the ambient setup. Reset the program withx; record board/core/source identity in the sheet.
- PlaceA, senda and wait for its window report. PlaceB, sendb and inspect whether calibration is ready. Small span, rail-level or overlapping references are a meaningful failed experiment; do not lower every rule merely to obtain a label.
- RestoreA and sendv. Place a test material without changing its optical-face gap and sendm. RestoreA and sendv again. Record the final state, raw window and unbounded coordinate, including unknown results.
- Repeat each coupon several times, changing which coupon is tested first. Compare within-material spread with between-material differences. Never delete inconvenient windows just because the mean spoils a tidy picture.
- Change separation to4.5mm, then6mm, recalibrating for each. Repeat the matrix under a second documented ambient condition. Keep the sensor parallel and the source position fixed within each matrix.
- For a controlled drift trial, change ambient illumination afterm but before the finalv. The program may reject the reference if its band is exceeded. If it passes, record that limitation rather than claiming the rule detects every lighting change.
For software fault trials, use the provided host suite rather than forcing5V onto an incompatible board. The real experiment has no actuators. Before reusing the sensor in a line-following application, test the actual line tape, floor, gap, ambient and mounting orientation. A bench result for one black coupon does not establish a safe steering threshold for a different track.
What the checks establish
The actual supplied collector, calibration, normalizer and state machine are compiled with host C++11. Tests cover all32 sample positions through the real collector, out-of-range and near-rail readings, short/invalid references, small spans, overlapping bands, reversed electrical order, mixed windows and unclamped extrapolation. State tests verify that m cannot bypass the before-reference, replace a pending sample or complete without the after-reference, and that drift/reset discards stale context. They do not run the Arduino API branch, characterize the phototransistor or establish classification accuracy.
Challenge: two black coupons have different means but overlapping sample ranges. Which one should a robot call black?
This experiment has not established a reliable distinction between them. Keep the result unknown, improve the mechanical/optical conditions or choose a sensing method suited to the actual task. If visible colour is the real requirement, infrared reflectance alone is the wrong quantity to treat as a colour measurement.
Primary documents and next learning
- Pololu QTR-1A two-pack item2458: exact analog module, supply/current, response direction and recommended geometry.
- Pololu QTR reflectance application note: material, distance and analog-interface considerations. Current product/note review found no separate applicable errata; this does not guarantee no future notice.
- Arduino UNO Rev3 documentation and official AVR core1.8.6 analog implementation: reference selection and conversion calls.
Build the divider and analog-input foundations in the interactive lessons. This stationary experiment adds material ambiguity, observed distributions and reference bracketing; it does not duplicate a robot’s chassis, motor or steering instructions.



