Beginning Arduino/Circuits - Middle School Age Appropriate

View the sketch here:

https://create.arduino.cc/editor/ado88/c09ae657-4be8-4687-8d1f-726801bcb99e/preview

Here's the code:

/*
  Authors: ado88 and JohnRob
  Email: arduino.ado88@gmail.com
  Date: Sept 18, 2021
  Revision: Version 0.1.2 Beta
  License: CC0 1.0 Universal License

  Project: Arduino Uno no3

  The Arduino Uno analog to digital converter compares an analog input (i.e. A0) to the voltage at the wiper of the potentiometer 
  (maximum 5 volts, because it is using the 5v pin). A potentiometer is a device that creates a variable voltage.
  
  It divides the 5V into 1024 levels called "counts" (0 to 1023).  It compares the A0 voltage to the different levels and
  returns the count of the level that most closely equals the input voltage on A0
  Each level is 5V/1024 = 0.00488 volts. 


  The PWM (Pulse Width Modulated) outputs a 490 Hz (aka 490 times a second) waveform.  The on time can be controlled in 255 steps
  0 = not on any time
  128 = on 50% of the time
  255 = on 100% of the time

  In the code below, the processor will "measure" the voltage (by converting it to counts, see above)

  At very low counts, the RED light will be dominant and the GREEN off.  As the voltage on the pot wiper increases,
  the RED will start to dim and the GREEN will increase in brightness.
  When the pot is in the center, both LED will be on the same brightness, creating an orange color.

*/

#define RED 9 // Set red output - may need to switch LED or numbering within program
#define GREEN 10 // Set green output - #define does not use up memory resources on the Uno
#define V_POT 0 // Set voltage input pin (A0)

void setup() {

  pinMode(RED, OUTPUT); //Set as outputs for LED
  pinMode(GREEN, OUTPUT);
  analogWrite(RED, 0); // Initializes red/green LED to off (LOW) (0)
  analogWrite(GREEN, 0);
}

void loop() {

  int inputVoltage = analogRead(V_POT); // Read voltage at pin A0 and store it in a variable called inputVoltage
  
  int pwmOut = 0.25 * inputVoltage; // Change voltage counts into Pulse Width Modulation steps and store in a variable called pwmOut.
    // int is a whole number variable type so it will automatically round to a whole number

  analogWrite(RED, (255 - pwmOut)); // When pwmOut is at max, RED is at 0
  analogWrite(GREEN, pwmOut); // When pwmOut is at max, GREEN is at full brightness (255)

  delay(100); // delay in milliSeconds. Makes the program more stable when responding to changes in POT voltage.
    // To get seconds, divide by 1000 or move the decimal left 3 places.  100.0 ms = 0.1 seconds

}