ezieragabriel / arduino

Automatically exported from code.google.com/p/arduino
Other
0 stars 0 forks source link

analogWrite in loop() seems to interfere with digitalWrite in serialEvent() #1091

Open GoogleCodeExporter opened 9 years ago

GoogleCodeExporter commented 9 years ago
/* serial_pin_control_with_breathing - take commands from serial and light or 
extinguish leds based on it

Demonstration of taking serial commands while doing something else.

*/

int max_led=7;
int min_led=2;
int state=0;
int position=0;

// the setup routine runs once when you press reset:
void setup() {                
  // initialize the digital pin as an output.
  for (int pin=min_led;pin<=max_led;pin++) 
  {
    pinMode(pin, OUTPUT);     
    digitalWrite(pin,LOW);
  }
  Serial.begin(115200);
  pinMode(11, OUTPUT);
}

void loop(){
  // breathing effect from http://sean.voisen.org/blog/2011/10/breathing-led-with-arduino/ to test using serialEvent to 
  // "multitask".
  float val = (exp(sin(millis()/2000.0*PI)) - 0.36787944)*108.0;
  analogWrite(11, val);
  delay(1); // needed so that the digitalWrites in serialEvent() go through.  I do not know why this is needed!
}

void serialEvent() {

 Serial.println(state);
 switch(state) {
   case 0: {
     char inChar = (char)Serial.read();
     if (inChar!='\n') { // ignore newlines
       position=atoi(&inChar);
       state++;
     }
     break;
   }
   case 1: {
     char inChar = (char)Serial.read();

     if (inChar=='+') {
       digitalWrite(min_led+position,HIGH);
     } else if (inChar=='-') {
       digitalWrite(min_led+position,LOW);
     }
   state=0;
   Serial.println("command done");
   break;
   }

  }

}

If I remove delay(1) from the loop, the serial routine works, but the LEDs do 
not go on or off.  If I remove both delay(1) and analogWrite(11, val) then the 
LEDs work.  The LEDs also work if loop() is blank.

Original issue reported on code.google.com by bmi...@gmail.com on 1 Nov 2012 at 2:46