Demonstrates analog input through a potentiometer and a photoreceptor paired to dimming LED lights.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
/* | |
Analog input, analog output, serial output | |
Reads an analog input pin, maps the result to a range from 0 to 255 and uses | |
the result to set the pulse width modulation (PWM) of an output pin. | |
Also prints the results to the Serial Monitor. | |
The circuit: | |
- potentiometer connected to analog pin 0. | |
Center pin of the potentiometer goes to the analog pin. | |
side pins of the potentiometer go to +5V and ground | |
- LED connected from digital pin 9 to ground | |
*/ | |
// These constants won't change. They're used to give names to the pins used: | |
int analogInPin1 = A0; // Analog input pin that the potentiometer is attached to | |
int analogInPin2 = A1; // Analog input pin that the photoreceptor is attached to | |
int ledPin1 = 9; // Digital output pin that uses PWM | |
int ledPin2 = 10; // Analog output pin that uses PWM | |
int sensorValue1 = 0; // value read from the potentometer | |
int sensorValue2 = 0; // calue read from the photoreceptor | |
int outputValue1 = 0; // value output to ledPin1 | |
int outputValue2 = 0; // calue output to ledPin2 | |
void setup() { | |
// initialize serial communications at 9600 bps: | |
Serial.begin(9600); | |
pinMode(9, OUTPUT); | |
pinMode(10, OUTPUT); | |
} | |
void loop() { | |
// read the analog in value: | |
sensorValue1 = analogRead(analogInPin1); | |
// map it to the range of the analog out: | |
outputValue1 = map(sensorValue1, 0, 1023, 0, 255); | |
// change the analog out value: | |
analogWrite(ledPin1, outputValue1); | |
// read the analog in value: | |
sensorValue2 = analogRead(analogInPin2); | |
// map it to the range of the analog out: | |
outputValue2 = map(sensorValue2, 300, 900, 0, 255); | |
// change the analog out value: | |
// Turns off ledPin2 if the light level drops below 500 | |
if (outputValue2 < 0){ | |
outputValue2 = 0; | |
} | |
analogWrite(ledPin2, outputValue2); | |
// print the potentiometer results to the Serial Monitor: | |
Serial.print("potentiometer = "); | |
Serial.print(sensorValue1); | |
Serial.print("\t output = "); | |
Serial.println(outputValue1); | |
Serial.print("\n"); | |
// print the photoreceptor results to the Serial Monitor: | |
Serial.print("photoreceptor = "); | |
Serial.print(sensorValue2); | |
Serial.print("\t output = "); | |
Serial.println(outputValue2); | |
// wait 2 milliseconds before the next loop for the analog-to-digital | |
// converter to settle after the last reading: | |
delay(5); | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment