I've had my arduino packed a way for a while and tonight decided to get it out and learn. I modified the fade example sketch to accept commands from a serial connection - so an LED is connected with a resistor to pin 9 on the arduino, sending a '1' over the serial connection turns it on, sending a '0' turns it off.
I have been reading over the forums and am really impressed by the knowledge that most people have here, so I would really appreciate it if I could get your thoughts on my sketch. I just want to see if I am doing things correctly so far or if there are easier ways of doing things. Thanks very much in advance.
int command = '2';
int oneLed = 9;
int ledState = 0;
int fadeOutFunction(int pin){
for (int fadeValue = 255 ; fadeValue >= 0; fadeValue -=5){
analogWrite(oneLed, fadeValue);
delay(30);
}
ledState = 0;
}
int fadeInFunction(int pin){
for (int fadeValue = 0 ; fadeValue <= 255; fadeValue +=5){
analogWrite (oneLed, fadeValue);
delay(30);
}
ledState = 1;
}
void setup()
{
Serial.begin(9600);
digitalWrite (oneLed, LOW);
}
void loop()
{
while (Serial.available() > 0) {
command = Serial.read();
if (command=='1')
{
if (ledState == 1)
{
Serial.println("LED was already on, doing nothing");
} else {
Serial.println("Switching LED on");
fadeInFunction(oneLed);
}
}
else if (command=='0')
{
if (ledState == 0)
{
Serial.println("LED was already off, doing nothing");
} else {
Serial.println("Switching LED off");
fadeOutFunction(oneLed);
}}
else
{if (ledState == 0){
Serial.println("Unknown command - leaving LED off");
} else {
Serial.println("Unknown command - turning off LED");
fadeOutFunction(oneLed);
}}
}
}