Thursday, August 23, 2012

Arduino control of LED

Here is code to control the intensity of an LED using Arduino.

// control intensity of LED using serial communication
int incomingByte = 0; // for incoming serial data
int outVal = 0; // for signal out
int pwmPin = 6; // white wire (pin 5 and 6 have pwm frequency ~1000 Hz, faster than pin 9)
int statusLED = 13;
int delaymsec = 100;
void setup() {
Serial.begin(9600); // opens serial port, sets data rate to 9600 bps
// initialize pwm and dir pins as outputs.
pinMode(pwmPin, OUTPUT);
pinMode(statusLED, OUTPUT); // status LED
}
void loop() {
// check for incoming serial data:
if (Serial.available() > 0) {
// read the incoming byte:
incomingByte = int(Serial.read()) - 48;
}
if ((incomingByte >= 0) && (incomingByte <= 5)){
if (incomingByte > 0) {digitalWrite(statusLED,HIGH);}
else {digitalWrite(statusLED,LOW);}
outVal = map(incomingByte, 0, 5, 0, 255);
analogWrite(pwmPin, outVal);
delay(delaymsec);
}
}

No comments: