Lab 2

Posted by jlzych

jlzych's picture

Description

This lab and HW uses keyboard input to modify the PWM to create different colors with the RGB LEDs. My diffuser isn't a typical diffuser. I took pieces of a Subway straw (which is an opaque white) and put a piece on each LED (see attached picture, it's cooler in real life). This doesn't diffuse the light equally, but rather creates cylinders of colored light.

Components

Breadboard

Arduino Microcontroller

RGB LEDs

Resistors

Subway straw

Code

This is the code for HW Part 3, which takes RGB hex values from the user (formatted as '0F0' or '00ff00') and lights the LEDs accordingly.

 
int redPin   = 10;   // Red LED,   connected to digital pin 10
 int greenPin = 11;   // Green LED, connected to digital pin 11

int bluePin  = 9;    // Blue LED,  connected to digital pin 9

int* rgb[] = { &redPin, &greenPin, &bluePin };    // Pointers to each pin number, in rgb order


void setup() {

  Serial.flush();

  pinMode(redPin,   OUTPUT);   // sets the pins as output

  pinMode(greenPin, OUTPUT);   

  pinMode(bluePin,  OUTPUT);

  Serial.begin(9600);

  // set them all to mid brightness

  analogWrite(redPin, 127);

  analogWrite(greenPin, 127);

  analogWrite(bluePin,  127);

  Serial.println("Enter hex color (e.g. 00FF00 or 0F0): ");  

}


void loop() {

  char hex[7] = {0, 0, 0, 0, 0, 0, 0};

  int size = 0;           // Number of bytes read in

  int loopIncrement = 0;  // How much to increment the loop when converting input to hex (1 or 2)


  // Populate the array from Serial input

  while (Serial.available() && size < sizeof(hex)) {

    hex[size++] = Serial.read();

    int value = int(hex[size - 1]);

    // Check the value is 0-9, a-f, A-F

    if (value < 48 ||                 // Before '0'

      (value > 57 && value < 65) ||   // After '9', before 'A'

      (value > 70 && value < 97) ||   // After 'F', before 'a'

      value > 102) {                  // After 'f'

      size = 0;

      break;

    }

  }

  

  if (size == 3 || size == 6) {

    setLEDs(hex, size);

  }

  

  // If there were more than 7 bytes read flush the remaining contents

  Serial.flush();

  delay(100);  // wait a bit, for serial data

}


/* Given an array of chars representing a hex, such as 123 or ABCDEF,

 * light the LEDs according to those values

 */

void setLEDs(char* hex, int size) {

  int loopIncrement = 1;

  if (size == 6) loopIncrement = 2;

  

  Serial.print("Set to: ");

  for (int i = 0; i < size; i += loopIncrement) {

    // Put each individual color in an array and string scan it as a hex into an int 

    char color[] = { hex[i], hex[i + loopIncrement/2], 0 };

    int value;

    sscanf(color, "%x", &value);

    analogWrite(*(rgb[i / loopIncrement]), value);

    

    Serial.print(color[0]);

    (i + loopIncrement == size) ? Serial.println(color[1]) : Serial.print(color[1]);

  }

}
Lab
Diffuser
0
Your rating: None