index2018-09-25

Week 3 ~ Digital + Analog + Inputs + Outputs

This week I used some new tools: a potentiometer, the analog input pin and the digital output pins on the arduino.

I created a circuit that has three digital outputs. Each is connected to an LED through a 220ohm resistor.

The analog input pin is connected to the middle leg of the potentiometer, the other two legs are connected to ground and power.

In my arduino code I am listening to the value of the voltage that the pontetiometer is giving me using analogRead. Through doing this I found out that the higest number is around 1023 and the lowest number is 0. Using that knowledge I wrote an if else statement in which the conditions are checking if the value is above or below a certain number. Using those conditions I used digitalWrite to ensure that a different LED gets power at different points in the pontentiometer’s rotation.

Here is a video of the circuit in action:

Here is the code:

void setup() {
  Serial.begin(9600);
  // pin 2 is connected to a 220ohm rsstr -> LED -> grnd
  pinMode(2, OUTPUT);
  // pin A0 is connected to potentiometer middle pin, outer pins are connected to pwr + grnd
  pinMode(A0, INPUT);
  // add more pins for more LEDS!!!
  pinMode(3, OUTPUT);
  pinMode(4, OUTPUT);
}
 
void loop() {
 int readValue = analogRead(A0);
 int red = digitalRead(2);
 int yellow = digitalRead(3);
 int green = digitalRead(4);
 
 Serial.println(readValue);
 
 if (readValue > 900) {
  // light up green LED
  digitalWrite(3, LOW);
  digitalWrite(4, LOW);
  digitalWrite(2, HIGH);
 } else if (readValue < 900 && readValue > 400 ) {
  // light up yellow LED
  digitalWrite(2, LOW);
  digitalWrite(4, LOW);
  digitalWrite(3, HIGH);
 } else {
  // light up red LED
  digitalWrite(3, LOW);
  digitalWrite(2, LOW);
  digitalWrite(4, HIGH);
 }
}