Description:
Microcontrollers have special pins for Pulse width modulation which enables us to simulate LED brightness. In this assignment we change the LED brightness based on the user input from the serial port.
Components Used:
Arduino - 1
220 ohm resistor - 3
LED - 3
Breadboard - 1
Code:
Attached.
char serInString[100];
char colorCode;
int redColorVal=125;
int greenColorVal=125;
int blueColorVal=125;
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
void setup()
{
pinMode(redPin, OUTPUT); // sets the pins as output
pinMode(greenPin, OUTPUT);
pinMode(bluePin, OUTPUT);
Serial.begin(9600);
analogWrite(redPin, redColorVal); // set them all to mid brightness
analogWrite(greenPin, greenColorVal); // set them all to mid brightness
analogWrite(bluePin, blueColorVal); // set them all to mid brightness
Serial.println("enter color command (e.g. 'r') :");
}
void loop()
{
memset(serInString,0,100);
readSerialString(serInString);
colorCode = serInString[0];
if(colorCode == 'r')
{
if (redColorVal==250)
{
redColorVal = 0;
}else
{
redColorVal = redColorVal+25;
}
Serial.print("Red to");
Serial.print(redColorVal);
Serial.println();
}
if(colorCode == 'g')
{
if (greenColorVal==250)
{
greenColorVal = 0;
}else
{
greenColorVal = greenColorVal+25;
}
Serial.print("Green to");
Serial.print(greenColorVal);
Serial.println();
}
if(colorCode == 'b')
{
if (blueColorVal==250)
{
blueColorVal = 0;
}else
{
blueColorVal = blueColorVal+25;
}
Serial.print("Blue to");
Serial.print(blueColorVal);
Serial.println();
}
analogWrite(redPin, redColorVal);
analogWrite(greenPin, greenColorVal);
analogWrite(bluePin, blueColorVal);
delay(100);
}
void readSerialString (char *strArray) {
int i = 0;
if(!Serial.available())
{
return;
}
while (Serial.available())
{
strArray[i] = Serial.read();
i++;
}
}
- Login to post comments