Arduino Input and Output

Having prior experience in Arduinos, I took this opportunity to play around with analog input and output mechanisms with the potentiometer, servo motor and LEDs provided in the starter kit.

Taking reference from a Knob Circuit, documented in the Arduino examples collection, I decided to create a version of it including LED’s. The objective is to rotate the servo arm following the manual adjustment of the potentiometer. The rotation is limited from 0 to 180 degrees. A red LED will light up when the servo arm swings below 90 degrees and the green LED will light up when the arm crosses 90 degrees. 

While I completed the implementation in class, for documentation, I built and simulated the circuit in TinkerCAD.

#include <Servo.h> // adding the servo library

Servo servo1; //creating servo object

int potpin = 0;  // analog pin 0 is used to connect to the potentiometer
int a_read;    // variable to read and store the value from the analog pin

int red_led = 12;
int green_led = 11;

void setup() {

  servo1.attach(13);  // telling the servo object that servo is attached to pin 13 on Uno
  pinMode(red_led,OUTPUT);
  pinMode(green_led,OUTPUT);
}

void loop() {
   
   a_read = analogRead(potpin); // reads the value of the potentiometer (value between 0 and 1023)
   a_read = map(a_read, 0, 1023, 0, 180); // scale it to use it with the servo (value between 0 and 180)
   servo1.write(a_read);                  // sets the servo position according to the scaled value
   delay(15);                           // waits for the servo to get there

   if(a_read < 90){
     digitalWrite(red_led,HIGH);
     digitalWrite(green_led,LOW);
   }else if(a_read > 90){
     digitalWrite(green_led,HIGH);
     digitalWrite(red_led,LOW);
   }else{
     digitalWrite(red_led,LOW);
     digitalWrite(green_led,LOW);
   }

}