Assignment: Digital I/O with Arduino Boards + Diffuser
Collaborators:
The user enters a temperature (range 1-100), and the system translates the temperature to a color and a blink rate. It glows the color temperature indicated and blinks more times faster for a high temperature and fewer times slower for a low temperature. The program also allows customization for an LED that appears weaker than the others.
/*
* How Hot Are You?
* ---------------
* Serial commands control the brightness of R,G,B LEDs
* LED color temperature and blink rate correspond to input
* Enter a temperature in celsius, in the range 1-100
*
* Created September 13, 2008
* by Annette Greiner
*/
int temp = -1; //variable to hold the temperature as entered by the user
int redVal, greenVal, blueVal; //values for the various LED brightnesses
int redPin = 9; // Red LED, connected to digital pin 9
int greenPin = 10; // Green LED, connected to digital pin 10
int bluePin = 11; // Blue LED, connected to digital pin 11
//customize the maximum brightnesses to balance a weak LED
//e.g., if your red is weak, set greenMax and blueMax to something less than 255.
int redMax = 255;
int greenMax = 127;
int blueMax = 127;
void setup() {
pinMode(redPin, OUTPUT); // sets the pins as output
pinMode(greenPin, OUTPUT);
pinMode(bluePin, OUTPUT);
Serial.begin(9600);
analogWrite(redPin, 0); // set them all to zero degrees
analogWrite(greenPin, 0); // set them all to zero degrees
analogWrite(bluePin, blueMax); // set them all to zero degrees
Serial.println("How hot do you feel? Enter a celsius temperature between 1 and 100:");
}
void loop () {
//read the serial port and set temp to the integer value of what you find
temp = readSerialInt();
if(temp > 0 && temp <= 100){
Serial.print("setting temperature to ");
Serial.print(temp);
Serial.println();
redVal = (int)(temp * redMax / 100); //red is at max when temp is 100 and min when 1
blueVal = (int)((100 - temp) * blueMax / 100); //blue is at max when temp is 1 and min when 100
if (temp <= 50) greenVal = temp * 2 * greenMax / 100; // green is at max when temp = 50
else greenVal = (int)((100-temp) * 2 * greenMax / 100); //and min when temp = 1 or 100
for(int i=temp; i>=0; i--){
analogWrite(redPin, 0);
analogWrite(greenPin, 0);
analogWrite(bluePin, 0);
delay(2000/temp);
analogWrite(redPin, redVal);
analogWrite(greenPin, greenVal);
analogWrite(bluePin, blueVal);
delay(5000/temp);
}
temp = 0; // indicates we've used this string
}
delay(100); // wait a bit, for serial data
}
//read an integer from the serial and return it
int readSerialInt(){
if(!Serial.available()){
return 0;
}
char strArray[100]; //array to hold the input
for(int j=0; j<100; j++) strArray[j] = NULL;
int i = 0;
while (Serial.available()){
strArray[i] = Serial.read();
i++;
}
int numInput = atoi(strArray);
return numInput;
}