Skip to content

Instantly share code, notes, and snippets.

@cowdinosaur
Created September 19, 2014 10:25
Show Gist options
  • Save cowdinosaur/51f9a71dad9c6695a6d6 to your computer and use it in GitHub Desktop.
Save cowdinosaur/51f9a71dad9c6695a6d6 to your computer and use it in GitHub Desktop.
Tinkerbot 3.6.1: Controlling brightness of LED with proximity sensor
#include <NewPing.h>
const int ULTRASONIC_TRIGGER = 6;
const int ULTRASONIC_ECHO = 7;
const int LED_PIN = 11;
#define MAX_DISTANCE 100
NewPing sonar(ULTRASONIC_TRIGGER, ULTRASONIC_ECHO, MAX_DISTANCE);
void setup() {
pinMode(ULTRASONIC_TRIGGER, OUTPUT);
pinMode(ULTRASONIC_ECHO, INPUT);
pinMode(LED_PIN, OUTPUT);
Serial.begin(9600);
}
void loop() {
int distance = sonar.ping_cm();
// If distance value is 0, it means that the object is very far away
if (distance == 0) {
distance = MAX_DISTANCE;
}
// We are only interested in the 10cm to 20cm range, so we constrain
// it to that range, and then map it to the brightness value (inverse map)
distance = constrain(distance, 10, 20);
int brightness = map(distance, 10, 20, 128, 0);
// brightness should be a value between 0 and 255
analogWrite(LED_PIN, brightness);
Serial.print(distance);
Serial.print(", ");
Serial.println(brightness);
delay(5);
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment