Skip to content

Instantly share code, notes, and snippets.

@ptweir
Last active October 9, 2015 05:18
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save ptweir/3444354 to your computer and use it in GitHub Desktop.
Save ptweir/3444354 to your computer and use it in GitHub Desktop.
Arduino code to control the intensity of an LED
// 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);
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment