Video
# Lab: Proximity Detection System
## **Objective**
Learn how to use the TK57 reflective optical sensor (TCRT5000) to detect hand proximity and objects. This lab covers the working principle of reflective sensors, analog reading, and proximity detection with threshold-based triggering.
## **Required Components**

1. **Lonely Binary UNO R3** - Main Arduino board
2. **TinkerBlock UNO R3 Shield** - Expansion shield that plugs onto the UNO R3
3. **TinkerBlock TK57** - Reflective Optical Sensor (TCRT5000)
## **Theory**
### **TCRT5000 Reflective Optical Sensor**
- **Infrared LED**: Emits infrared light (typically 950nm)
- **Phototransistor**: Detects reflected infrared light
- **Reflective Sensing**: Works by detecting light reflected from objects
- **Analog Output**: Provides continuous voltage based on reflection intensity
### **Working Principle**
1. **Infrared Emission**: IR LED emits invisible infrared light
2. **Object Detection**: Light reflects off nearby objects
3. **Light Detection**: Phototransistor detects reflected light
4. **Voltage Output**: Higher reflection = lower voltage output (phototransistor conducts more)
5. **Distance Sensing**: Closer objects reflect more light = lower sensor values
### **Detection Characteristics**
- **Detection Range**: Typically 2-15mm for reflective surfaces
- **Response Time**: Fast response (~1ms)
- **Ambient Light**: Resistant to ambient light interference
- **Surface Dependency**: Works best with reflective surfaces
### **Applications**
- **Proximity Detection**: Hand/object presence detection
- **Line Following**: Robot line following applications
- **Object Counting**: Production line object detection
- **Touchless Control**: Gesture-based interfaces
## **Wiring Instructions**
### **TK57 Reflective Optical Sensor Pinout**
- **GND** → Arduino GND
- **VCC** → Arduino 5V
- **NC** → No Connection
- **Signal** → Arduino Analog Pin A3
### **Connection Diagram**

## **Basic Code**
```cpp
// TK57 Reflective Optical Sensor (TCRT5000) Basic Test
// Pin definitions
#define SENSOR_PIN A3 // Analog pin connected to TK57 Signal
// Threshold values (adjust based on your setup)
#define PROXIMITY_THRESHOLD 400 // Threshold for hand detection (lower values = closer)
#define OBJECT_THRESHOLD 800 // Threshold for object detection (lower values = closer)
// Variables
int sensorValue = 0; // Raw sensor reading
int proximityLevel = 0; // Proximity level (0-3)
void setup() {
// Initialize serial communication
Serial.begin(9600);
Serial.println("TK57 Reflective Optical Sensor Test");
Serial.println("===================================");
// Wait for sensor to stabilize
delay(1000);
Serial.println("Sensor initialized. Place hand near sensor to test.");
Serial.println();
}
void loop() {
// Read sensor value
sensorValue = analogRead(SENSOR_PIN);
// Determine proximity level
proximityLevel = getProximityLevel(sensorValue);
// Display results
displaySensorInfo();
// Small delay for stable readings
delay(100);
}
// Function to determine proximity level
int getProximityLevel(int value) {
if (value < PROXIMITY_THRESHOLD) {
return 3; // Very close (hand very near)
} else if (value < OBJECT_THRESHOLD) {
return 2; // Close (object detected)
} else if (value < 500) {
return 1; // Medium (some reflection)
} else {
return 0; // Far (no reflection)
}
}
// Function to display sensor information
void displaySensorInfo() {
// Clear line and display current values
Serial.print("Raw: ");
Serial.print(sensorValue);
Serial.print(" | Proximity: ");
// Display proximity status
switch (proximityLevel) {
case 0:
Serial.print("Far ");
break;
case 1:
Serial.print("Medium ");
break;
case 2:
Serial.print("Close ");
break;
case 3:
Serial.print("VERY CLOSE!");
break;
}
// Display hand detection status
if (sensorValue < PROXIMITY_THRESHOLD) {
Serial.print(" | HAND DETECTED!");
} else if (sensorValue < OBJECT_THRESHOLD) {
Serial.print(" | Object detected");
} else {
Serial.print(" | No object");
}
Serial.println();
}
```
## **Advanced Code with Calibration**
```cpp
// TK57 Reflective Optical Sensor with Calibration
// Pin definitions
#define SENSOR_PIN A3
// Calibration variables
int sensorMin = 1023; // Minimum sensor value
int sensorMax = 0; // Maximum sensor value
bool isCalibrated = false; // Calibration status
// Threshold values (will be calculated during calibration)
int proximityThreshold = 0;
int objectThreshold = 0;
// Variables
int sensorValue = 0;
int mappedValue = 0; // Value mapped to 0-100 range
void setup() {
Serial.begin(9600);
Serial.println("TK57 Reflective Optical Sensor - Advanced Test");
Serial.println("==============================================");
Serial.println();
// Perform calibration
calibrateSensor();
Serial.println("Calibration complete! Start testing.");
Serial.println();
}
void loop() {
// Read sensor value
sensorValue = analogRead(SENSOR_PIN);
// Map value to 0-100 range
mappedValue = map(sensorValue, sensorMin, sensorMax, 0, 100);
mappedValue = constrain(mappedValue, 0, 100);
// Display comprehensive information
displayAdvancedInfo();
delay(100);
}
// Function to calibrate sensor
void calibrateSensor() {
Serial.println("Starting sensor calibration...");
Serial.println("1. Keep sensor away from any objects (far position)");
Serial.println("2. Press any key when ready to start");
while (!Serial.available()) {
delay(100);
}
Serial.read(); // Clear the input
Serial.println("Calibrating far position...");
delay(2000);
// Read far position (maximum reflection = high values)
for (int i = 0; i < 50; i++) {
int value = analogRead(SENSOR_PIN);
if (value > sensorMax) {
sensorMax = value;
}
delay(50);
}
Serial.println("3. Place hand very close to sensor (close position)");
Serial.println("4. Press any key when ready");
while (!Serial.available()) {
delay(100);
}
Serial.read(); // Clear the input
Serial.println("Calibrating close position...");
delay(2000);
// Read close position (minimum reflection = low values)
for (int i = 0; i < 50; i++) {
int value = analogRead(SENSOR_PIN);
if (value < sensorMin) {
sensorMin = value;
}
delay(50);
}
// Calculate thresholds
proximityThreshold = sensorMin + ((sensorMax - sensorMin) * 0.2);
objectThreshold = sensorMin + ((sensorMax - sensorMin) * 0.4);
// Display calibration results
Serial.println("Calibration Results:");
Serial.print(" Far position (max): ");
Serial.println(sensorMax);
Serial.print(" Close position (min): ");
Serial.println(sensorMin);
Serial.print(" Object threshold: ");
Serial.println(objectThreshold);
Serial.print(" Proximity threshold: ");
Serial.println(proximityThreshold);
Serial.println();
isCalibrated = true;
}
// Function to display advanced sensor information
void displayAdvancedInfo() {
Serial.print("Raw: ");
Serial.print(sensorValue);
Serial.print(" | Mapped: ");
Serial.print(mappedValue);
Serial.print("%");
// Display proximity status with mapped values
if (mappedValue > 80) {
Serial.print(" | VERY CLOSE!");
} else if (mappedValue > 60) {
Serial.print(" | Close");
} else if (mappedValue > 30) {
Serial.print(" | Medium");
} else {
Serial.print(" | Far");
}
// Display detection status
if (sensorValue < proximityThreshold) {
Serial.print(" | HAND DETECTED!");
} else if (sensorValue < objectThreshold) {
Serial.print(" | Object detected");
} else {
Serial.print(" | No object");
}
Serial.println();
}
```
## **Interactive Code with Serial Commands**
```cpp
// TK57 Reflective Optical Sensor with Interactive Control
// Pin definitions
#define SENSOR_PIN A3
// Configuration
int threshold = 500; // Detection threshold (lower values = closer)
bool continuousMode = true; // Continuous output mode
// Variables
int sensorValue = 0;
unsigned long lastDetection = 0;
bool objectDetected = false;
void setup() {
Serial.begin(9600);
Serial.println("TK57 Reflective Optical Sensor - Interactive Mode");
Serial.println("================================================");
Serial.println("Commands:");
Serial.println("t: Toggle continuous mode");
Serial.println("+: Increase threshold");
Serial.println("-: Decrease threshold");
Serial.println("c: Calibrate threshold");
Serial.println("r: Reset to defaults");
Serial.println("s: Show current settings");
Serial.println();
displaySettings();
}
void loop() {
// Check for serial commands
if (Serial.available()) {
handleCommand(Serial.read());
}
// Read sensor
sensorValue = analogRead(SENSOR_PIN);
// Check for object detection
bool currentDetection = (sensorValue < threshold);
// Handle detection changes
if (currentDetection != objectDetected) {
objectDetected = currentDetection;
if (objectDetected) {
lastDetection = millis();
Serial.println("*** OBJECT DETECTED! ***");
} else {
Serial.println("*** OBJECT REMOVED ***");
}
}
// Continuous output mode
if (continuousMode) {
Serial.print("Raw: ");
Serial.print(sensorValue);
Serial.print(" | Threshold: ");
Serial.print(threshold);
Serial.print(" | Status: ");
Serial.println(objectDetected ? "DETECTED" : "Clear");
}
delay(200);
}
// Function to handle serial commands
void handleCommand(char command) {
switch (command) {
case 't':
continuousMode = !continuousMode;
Serial.print("Continuous mode: ");
Serial.println(continuousMode ? "ON" : "OFF");
break;
case '+':
threshold += 10;
Serial.print("Threshold increased to: ");
Serial.println(threshold);
break;
case '-':
threshold -= 10;
if (threshold < 0) threshold = 0;
Serial.print("Threshold decreased to: ");
Serial.println(threshold);
break;
case 'c':
calibrateThreshold();
break;
case 'r':
resetToDefaults();
break;
case 's':
displaySettings();
break;
}
}
// Function to calibrate threshold
void calibrateThreshold() {
Serial.println("Calibration mode:");
Serial.println("1. Keep sensor clear of objects");
Serial.println("2. Press any key when ready");
while (!Serial.available()) {
delay(100);
}
Serial.read();
// Read baseline (no object)
int baseline = 0;
for (int i = 0; i < 20; i++) {
baseline += analogRead(SENSOR_PIN);
delay(50);
}
baseline /= 20;
Serial.println("3. Place object near sensor");
Serial.println("4. Press any key when ready");
while (!Serial.available()) {
delay(100);
}
Serial.read();
// Read with object
int objectLevel = 0;
for (int i = 0; i < 20; i++) {
objectLevel += analogRead(SENSOR_PIN);
delay(50);
}
objectLevel /= 20;
// Calculate threshold
threshold = baseline - ((baseline - objectLevel) * 0.7);
Serial.print("Baseline (no object): ");
Serial.println(baseline);
Serial.print("Object level: ");
Serial.println(objectLevel);
Serial.print("New threshold: ");
Serial.println(threshold);
Serial.println("Calibration complete!");
}
// Function to reset to defaults
void resetToDefaults() {
threshold = 500;
continuousMode = true;
Serial.println("Reset to defaults");
displaySettings();
}
// Function to display current settings
void displaySettings() {
Serial.println("Current Settings:");
Serial.print(" Threshold: ");
Serial.println(threshold);
Serial.print(" Continuous mode: ");
Serial.println(continuousMode ? "ON" : "OFF");
Serial.println();
}
```
## **Code Explanation**
### **Basic Functions**
- **`analogRead(SENSOR_PIN)`**: Read raw sensor value (0-1023)
- **Threshold Detection**: Compare smoothed value to threshold
- **Serial Output**: Display sensor readings and detection status
### **Calibration Process**
1. **Baseline Reading**: Measure sensor with no objects
2. **Object Reading**: Measure sensor with object present
3. **Threshold Calculation**: Set threshold between baseline and object level
4. **Dynamic Adjustment**: Adapt to different environments
### **Detection Logic**
- **Raw Value**: Direct ADC reading (0-1023)
- **Smoothed Value**: Noise-reduced reading
- **Mapped Value**: Percentage (0-100%) for easier understanding
- **Proximity Levels**: Multiple detection zones
## **Troubleshooting**
### **Sensor not responding:**
- Check wiring connections (GND, VCC, Signal)
- Verify analog pin A3 is correct
- Ensure sensor is not damaged
- Check power supply (5V required)
### **False detections:**
- Adjust threshold values
- Check for ambient light interference
- Calibrate sensor for your environment
### **Inconsistent readings:**
- Check for loose connections
- Ensure stable power supply
- Clean sensor surface
### **Detection range too short:**
- Check sensor orientation
- Verify reflective surface quality
- Adjust threshold to lower value
- Check for obstructions
## **Customization Ideas**
### **Add More Sensors:**
- **Multiple TK57**: Create proximity array
- **Different Types**: Combine with other sensors
- **Spatial Detection**: 3D proximity mapping
### **Add Actuators:**
- **Servo Motor**: Move based on proximity
- **Relay**: Control external devices
- **Buzzer**: Audio feedback
- **Display**: Show proximity values
### **Advanced Features:**
- **Gesture Recognition**: Multiple proximity levels
- **Object Tracking**: Follow moving objects
- **Distance Estimation**: Approximate distance calculation
- **Pattern Recognition**: Identify different objects
## **Next Steps**
- Experiment with different threshold values
- Test with various reflective surfaces
- Combine with other sensors for complex detection
- Create interactive applications
## **Resources**
- **TCRT5000 Datasheet**: Available online for detailed specifications
- **Reflective Sensor Theory**: Understanding IR reflection principles
- **Proximity Detection Applications**: Real-world use cases