My goal is to run a vibrating motor for specific time intervals. I am using the millis()
function to successfully turn the motor on and off, but only if the intervalOn = intervalOff
. The problem comes when I try to change the intervals to turn the motor on for e.g. 120 ms, then turn off for 200 ms etc. My code seems to cause AVR restart and my motor sometimes stays running. First I thought this is caused by insufficient decouple capacitor (I have 100 uF one) but when running the millis()
code with one no-changing interval, it all works flawlessly...
Is there any other way to change the intervals?
The Vibrating()
function gets called from the loop()
whenever vibrEnabled = true
unsigned long interval = 0;
unsigned long previousMillis = 0;
int last = 120;
int pause = 200;
void Vibrating()
{
unsigned long currentMillis = millis();
static byte cyclesPassed = 0;
if((unsigned long)(currentMillis - previousMillis) >= interval)
{
PORTC ^= (1<<PC1);//toggle motor
if(interval != last) //this part causes the problem
interval = last; //
else //
interval = pause;//
cyclesPassed++;
if(cyclesPassed == 8)//motor is on 4x
{
cyclesPassed = 0;
vibrEnabled = false;
}
previousMillis = millis();
}
}
2 Answers 2
Maybe your vibrating motor is actually shaking something loose. A dodgy batter clip or something.
Maybe your vibrating motor is drawing too much current and power-cycling the board.
Maybe your vibrating motor is doing weird, bad things like generating back-EMF spikes that it's sending back into the arduino.
It's probably number 3. Generally speaking, you never power motors off an output pin. Run the output into a mosfet or something with a flyback diode across it. Google "circuit to power motor from digital out".
The problems were caused by the vibrating motor. It's shaking caused the rotating part touched the surface and the motor stopped for a while.
Thank you for you help.
while(vibrEnabled) Vibrating();
test and the code works, how I can see it being used. This is a hardware related problem, you should if possible post your hardware set up, schematic and such.