// ------------
// ECE 210 - Lab 5
// ------------
/*-------------
Author: Giri Venkataramanan
This code is used in ECE 210 in Practicum 5.
The code demonstrates reading analog signals and operating a blinking LED with different
parameters leading to PWM
Pin A0 is used to read potentiometer signal input (10 bits)
Pin D2 (red LED) and Pin D11 (green LED) are used to write signal outputs
Pin D2 indicates switch position
Pin D11 is operated to vary the blink-on time to reflect PotValue is used as period
Duty is used to vary the on-time/period of the green LED
-------------*/
// constants won't change. They're used here to set pin numbers:
const int VL = 4; // the number of the swich pin, VL stands for logic voltage
const int PR = 2; // the number of the LED pin, PR stands for red probe
const int PG = 11; // the number of the LED pin, PG stand for green probe
const int VP = A0; // select the input pin for the potentiometer
const int Duty = 50; // duty ratio of on-state in percentage
// variables will change:
int SwitchState = 0; // give a name for the switch state variable
int Period = 0; // Duty ratio variable to store the value coming from the sensor
int OnTime = 0; // variable to store the value of on-time
int OffTime = 0; // variable to store the value of off-time
//declares the inputs and outputs of the circuit
void setup() {
pinMode(A0, INPUT);
pinMode(VL, INPUT);
pinMode(PR, OUTPUT);
pinMode(PG, OUTPUT);
}
// your code written here keeps running until eternity
void loop() {
//reads from the switch to determine which LED should be on
SwitchState = digitalRead(VL);
//reads from the pot pin, adds 20 and assign it to the Period in ms
Period = 20 + analogRead(VP);
//calculate on-time and off-time in ms
OnTime = Duty*Period/100;
OffTime = (100-Duty)*Period/100;
//Reflects SwitchState on Red LED
digitalWrite(PR, SwitchState);
//turns off the green LED if Switch state is high
if (SwitchState == 1) {
digitalWrite(PG, 1);
}
//blinks the green LED if Switch state is low
if (SwitchState == 0) {
digitalWrite(PG,0); // Green on
delay(OnTime); // wait for end of on-time
digitalWrite(PG,1); // Green off
delay(OffTime); // wait for end of off-time
}
if (SwitchState == 1) {
digitalWrite(PR,1); // Red on
delay(OnTime); // wait for end of on-time
digitalWrite(PR,0); // Red off
delay(OffTime); // wait for end of off-time
}
}