Skip to content

Instantly share code, notes, and snippets.

@peow2373
Created February 26, 2020 03:40
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 peow2373/ae91b7685cf67e156ce4bda784c267ff to your computer and use it in GitHub Desktop.
Save peow2373/ae91b7685cf67e156ce4bda784c267ff to your computer and use it in GitHub Desktop.
Demonstrates analog input through a potentiometer and a photoreceptor paired to dimming LED lights.
/*
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