Skip to content

Instantly share code, notes, and snippets.

@dan-mckay
Created November 1, 2012 14:59
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save dan-mckay/3994137 to your computer and use it in GitHub Desktop.
Save dan-mckay/3994137 to your computer and use it in GitHub Desktop.
Takes a potentiometer reading and controls dimness of 3 LEDs
// These constants won't change. They're used to give names
// to the pins used:
const int analogInPin = A0; // Analog input pin that the potentiometer is attached to
const int greenOutPin = 9; // Analog output pin that the green LED is attached to
const int yellowOutPin = 10; // Analog output pin that the ylw LED is attached to
const int redOutPin = 11; // Analog output pin that the red LED is attached to
int sensorValue = 0; // value read from the pot
int outputValue = 0; // value output to the PWM (analog out)
void setup() {
// initialize serial communications at 9600 bps:
Serial.begin(9600);
}
void loop() {
// read the analog in value:
sensorValue = analogRead(analogInPin);
// map it to the range of the analog out:
outputValue = map(sensorValue, 0, 1023, 0, 767);
// light green LED:
if(outputValue <= 255) {
analogWrite(greenOutPin, outputValue);
analogWrite(yellowOutPin, 0);
analogWrite(redOutPin, 0);
}
// light green and yellow LEDs:
else if(outputValue <= 511) {
analogWrite(yellowOutPin, outputValue - 256);
analogWrite(greenOutPin, 255);
analogWrite(redOutPin, 0);
}
// light all LEDs:
else {
analogWrite(redOutPin, outputValue - 512);
analogWrite(yellowOutPin, 255);
analogWrite(greenOutPin, 255);
}
// print the results to the serial monitor:
Serial.print("sensor = " );
Serial.print(sensorValue);
Serial.print("\t output = ");
Serial.println(outputValue);
// wait 2 milliseconds before the next loop
// for the analog-to-digital converter to settle
// after the last reading:
delay(2);
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment