Combining two sketches - please help!

Hi guys,

I am having some trouble with an arduino project and I was hoping you could give me a little help.
I am trying to make an LED fade and a motor vibrate at the same time. I got them working separately, but when I try to combine them, the script dosn't work. They are supposed to work independent of each other.

Here is my script for the LED:

int led = 1; 
int brightness = 0;
int fadeAmount= 5;
 
void setup() {
  pinMode(led, OUTPUT);
 
}
 
void loop()  { 
  analogWrite(led, brightness);    
  brightness = brightness + fadeAmount;
  if (brightness == 0 || brightness == 255) {
    fadeAmount = -fadeAmount ; 
  }     
  delay(50); 
}

And my motor has this script:

const int motorPin = 2;
void setup()
{
pinMode(motorPin, OUTPUT);
}
void loop()
{
digitalWrite(motorPin, HIGH);
delay(100);
digitalWrite(motorPin, LOW);
delay(780);
}

When I tried to combine them, I used the code below. The motor works well, but the LED is going crazy and I can't figure out why:

const int motorPin = 2;
int led = 1; 
int brightness = 0;
int fadeAmount= 5;
void setup()
{
pinMode(motorPin, OUTPUT);
pinMode(led, OUTPUT);
}
void loop()
{
digitalWrite(motorPin, HIGH);
delay(100);
digitalWrite(motorPin, LOW);
delay(780);
analogWrite(led, brightness);    
  brightness = brightness + fadeAmount;
  if (brightness == 0 || brightness == 255) {
    fadeAmount = -fadeAmount ; 
  }     
  delay(50);

}

:smiley:
Thank you in advance!

Take a look at the blink without delay example, and lose all the delay()s.

In a simple sketch like this the use of delay() doesn't cause a problem whereas it should be avoided in any complex sketch.

I think the problem here is your use of pin1 for the LED. In general don't use Pin0 or Pin1 as they are used by the USART for serial communication over the USB cable.

I tried your sketch with the led on Pin3 and it seems to work fine. I just had another Led in place of the motor.

I presume you know not to power the motor from the Arduino as it can't supply enough current.

...R