Published on

Level 4 Solutions

Table of Contents

Assignment 1

Make a circuit that has 1 RGB LED, 3 LDR sensors (or Potentiometers), and a button. When a push button is pressed, the LED should cycle between red, blue, and green colors. There should be one LDR/Potentiometer for each color to control its brightness when it is active.

int x;

void setup()
{
  Serial.begin(9600);
  pinMode(2,INPUT_PULLUP); //Initialize input pullup
  pinMode(3,OUTPUT);
  pinMode(5,OUTPUT);
  pinMode(6,OUTPUT);

  //Initialize Analog Input
  pinMode(A0,INPUT);
  pinMode(A1,INPUT);
  pinMode(A2,INPUT);
}

void loop()
{
  if(digitalRead(2)==0)
  {
    x+=1;  //Adding 1 to x each time switch is pressed
    delay(50);
  }
  if((x%3)==0)
  {

    analogWrite(3,map(analogRead(A0), 0, 1023, 0, 255)); //Map function to map values from 0-1023 to 0-255
    analogWrite(5,0);
    analogWrite(6,0);
    Serial.println(analogRead(A0)*0.25); //Print %duty cycle
  }
  if((x%3)==1)
  {
    analogWrite(3,0);
    analogWrite(5,map(analogRead(A1), 0, 1023, 0, 255));
    analogWrite(6,0);
    Serial.println(analogRead(A1)*0.25);
  }
  if((x%3)==2)
  {
    analogWrite(3,0);
    analogWrite(5,0);
    analogWrite(6,map(analogRead(A2), 0, 1023, 0, 255));
    Serial.println(analogRead(A2)*0.25);
  }
  Serial.println(x);
}

  Test the RGB LED and have fun!

Assignment 2

Generate a PWM wave of any desired % Duty Cycle from a Non-PWM supporting pin (Pins other than 3,5,6,9,10,11) and demonstrate the square wave on an oscilloscope. Pick a convenient Frequency for your square wave.

int bright;

void setup()
{
  pinMode(4, OUTPUT);
  Serial.begin(9600);
}

void loop()
{
  //Enter the % duty cycle needed at 1kHz frequency.
  if (Serial.available() > 0)
  {
    bright=Serial.parseInt();
    Serial.println(bright);
  }
  digitalWrite(4, HIGH);
  delayMicroseconds(map(bright,0,100,0,1000)); // LED on for x% of 1000 microseconds
  digitalWrite(4, LOW);
  delayMicroseconds(1000-map(bright,0,100,0,1000)); //LED of for (100-x)% of 1000 microseconds
}

Check the PWM pulse on oscilloscope.

-->