用一个光码盘计算电机转速,用示波器检测到输出的是40Hz的矩形波。
可是用外部中断计数然后串口输出(1s左右输出一次)的计数有400、700多的,各种离谱(正常1s接近一圈20个孔计数应该20~40)
中断相关的代码:
attachInterrupt(0, interruptR, RISING); //在setup里
void interruptR() //right wheel interrupt function
{ countR += 1; }
脉冲输出接到数字口2口(中断0),有共地。
一些实验:
1、用了Uno和Mega 2560 都测过,均不能准确计数,Mega的6个中断口都测过,每个口的计数不一样,有在400、500、100、700、1000等波动的,但都是不稳定却远远超出理论值。
2、用自带的pwm输出口给中断口计数,把128的pwm波输出,是能稳定计数的,每次计数显示490或491,十分稳定。两块板子都没问题。
3、光电码盘模块的输入电压是3.3V~5.0V,我用板上的3.3V和5.0V电压供电也是无法正常工作的(会改变矩形波的最大电压,记得分别是3.7和5.4V)。怕板子供电电流驱动能力不够,也用外部稳定5V电压供电过(共地),也是没用。
4、也试过防抖,没什么效果。。。
5、在51单片机上是能稳定准确计数的。
实在没辙了,求救!!!
完整代码:- #define IN1 4 //IN1,2 control left motor
- #define IN2 5
- #define IN3 6 //IN3,4 control right motor
- #define IN4 7
- #define ENA 9 //pin with #
- #define ENB 10 //pin with #
- int pwmENA = 128, pwmENB = 128;
- volatile unsigned long countR = 0; //count for keepline. right with ENB
- volatile unsigned long countL = 0;
- volatile unsigned long time1, time2,;
- void setup()
- {
- Serial.begin(115200);
- //motor
- pinMode(IN1, OUTPUT);
- pinMode(IN2, OUTPUT);
- pinMode(IN3, OUTPUT);
- pinMode(IN4, OUTPUT);
- pinMode(ENA, OUTPUT);
- pinMode(ENB, OUTPUT);
- time1 = millis();
- time2 = millis();
-
- //interrupt
- attachInterrupt(0, interruptR, RISING);
- attachInterrupt(1, interruptL, RISING);
- }
- void loop()
- {
- if((millis() - time1) > 1000)
- {
- speedFeedback();
- time1 = millis();
- }
- forward();
- }
- void forward()
- {
- analogWrite(ENA, pwmENA);
- analogWrite(ENB, pwmENB);
- digitalWrite(IN1, HIGH); // left motor forward
- digitalWrite(IN2, LOW);
- digitalWrite(IN3, HIGH); //right motor forward
- digitalWrite(IN4, LOW);
- }
- void interruptR() //right wheel interrupt function
- {
- countR += 1;
- }
- void interruptL()
- {
- // if((millis() - time2) > 3) //之前加的防抖
- // {
- countL += 1;
- // time2 = millis();
- // }
- }
- void speedFeedback()
- {
- Serial.print("right ");
- Serial.print("-----");
- Serial.println(countR);
- Serial.print("left ");
- Serial.print(pwmENA);
- Serial.print("-----");
- Serial.println(countL);
- countL = 0;
- countR = 0;
- }
复制代码 |