____ _ ____ | _ \ ___ | |__ ___/ ___| _ _ _ __ ___ ___ | |_) / _ \| '_ \ / _ \___ \| | | | '_ ` _ \ / _ \ | _ < (_) | |_) | (_) |__) | |_| | | | | | | (_) | |_| \_\___/|_.__/ \___/____/ \__,_|_| |_| |_|\___/ ____ _ _ _ / ___|___ ___ | | _| |__ ___ ___ | | __ | | / _ \ / _ \| |/ / '_ \ / _ \ / _ \| |/ / | |__| (_) | (_) | <| |_) | (_) | (_) | < \____\___/ \___/|_|\_\_.__/ \___/ \___/|_|\_\
Version 1: Switch an LED on and off
//
// TCRT5000 example program
//
// This switches an LED on or off depending on whether the sensor
// voltage is greater than 2.5 V or not.
//
// Written by Ted Burke on 8-Feb-2023
//
void setup()
{
// Configure pin D2 as a digital output
pinMode(2, OUTPUT);
}
void loop()
{
// Declare an integer variable to store a number (the sensor reading)
int colour;
// Read analog voltage from pin A0 as a number between 0 and 1023
colour = analogRead(0);
// Decide whether to switch the LED on or off based on the sensor voltage
if (colour > 512)
{
digitalWrite(2, HIGH); // LED on
}
else
{
digitalWrite(2, LOW); // LED off
}
}
Version 2: Control an LED and print readings via serial connection
//
// TCRT5000 example program
//
// This version controls an LED and prints sensor readings via
// the serial connection to the PC, so that they can be displayed
// using the Serial Monitor or Serial Plotter in the Arduino IDE.
//
// Written by Ted Burke on 8-Feb-2023
//
void setup()
{
// Open a serial connection to the PC at 9600 bits per second
Serial.begin(9600);
// Configure pin D2 as a digital output
pinMode(2, OUTPUT);
}
void loop()
{
// Declare an integer variable to store a number (the sensor reading)
int colour;
// Read analog voltage from pin A0 as a number between 0 and 1023
colour = analogRead(0);
// Print the sensor reading to the PC via the serial connection
Serial.println(colour);
// Decide whether to switch the LED on or off based on the sensor voltage
if (colour > 512)
{
digitalWrite(2, HIGH); // LED on
}
else
{
digitalWrite(2, LOW); // LED off
}
}