如何在Arduino中产生少量脉冲后停止pwm?

时间:2016-04-22 15:36:47

标签: arduino

我试图从Arduino产生脉冲到驱动电机步进器5相。  驱动器只需要脉冲即可使电机步进工作。我的问题是当我使用这样的代码时

for(int i=0; i <= 125; i++)
{
    //analogWrite(13,125);
    digitalWrite(13, HIGH);
    delayMicroseconds(300);
    digitalWrite(13, LOW);
    delayMicroseconds(300);
}
digitalWrite(13,LOW);
delay(3000);

步进电机可以完美地工作,但经过10多次旋转, 电机的角度没有回到原来的位置。我们可以像这样在Arduino中使用pwm吗?所以在使用pwm产生5000个脉冲后,我们停止了pwm?

1 个答案:

答案 0 :(得分:0)

试试这段代码:

#include <TimerOne.h>
const byte CLOCKOUT = 11;
volatile byte counter=0;

void setup() {
    Timer1.initialize(15);         //Every 15 microseconds change the state of the pin in the wave function giving a period of 30 microseconds 
    Timer1.attachInterrupt(Onda);  
    pinMode (CLOCKOUT, OUTPUT);
    digitalWrite(CLOCKOUT,HIGH);
}
void loop() {
    if (counter>=6000){               //With 6000 changes you should achieve the amount of pulses you need
        Timer1.stop();               //Here I create the dead time, which must be in HIGH
        PORTB = B00001000;
        counter=0;
        delayMicroseconds(50);
        Timer1.resume();
    }
}
void Onda(){
    PORTB ^= B00001000;   //Change pin status
    counter+=1;
}

我不能消除抖动。如果您找到解决方案,请告诉我