Unit 4: Taking Control

 

 

Code for Sketch One: 


const int POT_PIN = A0;           // Potentiometer analog input pin
const int RED_LED_PIN = 11;       // Red LED pin of RGB LED

void setup() {
  pinMode(RED_LED_PIN, OUTPUT);  // Set red LED pin as output
}

void loop() {
  // Read the value from the potentiometer (0 to 1023)
  int potValue = analogRead(POT_PIN);

  // Map the potentiometer value to the delay time (100 to 1000 milliseconds)
  int delayTime = map(potValue, 0, 1023, 100, 1000);

  // Turn on the red component of the RGB LED
  analogWrite(RED_LED_PIN, 255);   // Full brightness
  delay(delayTime);                // Delay for the specified time

  // Turn off the red component of the RGB LED
  analogWrite(RED_LED_PIN, 0);     // No brightness (off)
  delay(delayTime);                // Delay for the specified time
}

Code for Sketch Two:


const int POT_PIN = A0;              // Potentiometer analog input pin
const int RED_LED_PIN = 11;          // Red LED pin of RGB LED
const int GREEN_LED_PIN = 10;        // Green LED pin of RGB LED
const int BLUE_LED_PIN = 9;          // Blue LED pin of RGB LED

void setup() {
  pinMode(RED_LED_PIN, OUTPUT);     // Set red LED pin as output
  pinMode(GREEN_LED_PIN, OUTPUT);   // Set green LED pin as output
  pinMode(BLUE_LED_PIN, OUTPUT);    // Set blue LED pin as output
}

void loop() {
  // Read the value from the potentiometer (0 to 1023)
  int potValue = analogRead(POT_PIN);

  // Define threshold values for color transitions
  int amberThreshold = 512;         // Potentiometer reading for transition to amber
  int redThreshold = 256;           // Potentiometer reading for transition to red

  // Determine the current color based on the potentiometer value
  if (potValue >= amberThreshold) {
    // Green color
    setColor(0, 255, 0);            // Green
  } else if (potValue >= redThreshold) {
    // Amber color
    setColor(255, 191, 0);          // Amber
  } else {
    // Red color
    setColor(255, 0, 0);            // Red
  }
}

void setColor(int R, int G, int B) {
  analogWrite(RED_LED_PIN, R);
  analogWrite(GREEN_LED_PIN, G);
  analogWrite(BLUE_LED_PIN, B);
}


Notes: