|
|
PWM调速与MsTimer2冲突 导致电驱板两个控制输出端 只有一个可用
调速程序是
- int INA = 8; //电机A正反转控制端
- int PWMA = 9; //电机A调速端
- int INB = 10; //电机B正反转控制端
- int PWMB = 11;
- char getstr;
- void advance(int v)
- {
- digitalWrite(INA,LOW); //HIGH为前进,LOW为后退
- digitalWrite(INB,HIGH);
- analogWrite(PWMA,v); //PWM调速
- analogWrite(PWMB,v);
- }
- void bluetooth() {
- getstr=Serial.read(); //读取串口数据
- switch(getstr) {
- case 'a':
- Serial.println("go forward!");
- advance(250);break;
- default:break;
- }
- }
- void setup() {
- pinMode(INA,OUTPUT);
- pinMode(INB,OUTPUT);
- pinMode(PWMB,OUTPUT);
- pinMode(PWMA,OUTPUT);
-
- Serial.begin(9600);
- }
- void loop() {
- bluetooth();
- }
复制代码 可以正常运行
后来加入MsTimer2就出现有一个驱动输出口不能控制,后来排查,在setup 中加入MsTimer2::start();就会出现问题- #include <MsTimer2.h>
- #define Value 1.0995574
- int INA=10;
- int PWMA=11;
- int INB=8;
- int PWMB=9; //电机控制端口
- int EchoPin = 4;
- int TrigPin = 5; //超声波端口
- float distance;
- char getstr;
- int out1=2; //光码盘端口
- long c1=0; //光码盘初始计数
- float r_velocity=0;//速度;
- void advance(int spe)
- {digitalWrite(INB,LOW);
- digitalWrite(INA,HIGH);
- analogWrite(PWMA,spe);
- analogWrite(PWMB,spe);
- }
- void stopp()
- {
- digitalWrite(INB,HIGH);
- analogWrite(PWMB,0);
- digitalWrite(INA,HIGH);
- analogWrite(PWMA,0);
- }
- void read_csb() //超声波数据读取
- {
- digitalWrite(TrigPin, LOW);
- delayMicroseconds(2);
- digitalWrite(TrigPin, HIGH);
- delayMicroseconds(10);
- digitalWrite(TrigPin, LOW);
- distance = pulseIn(EchoPin, HIGH)/58; //单位换算为厘米
- Serial.print("UTdistance is ");
- Serial.println(distance); //窗口输出测距值
- }
- void bluetooth()
- {
- getstr = Serial.read(); //读取串口数据
- switch(getstr) {
- case 'a':
- Serial.println("go forward!");
- advance(250);
- break;
- }
- }
- float velocity(int n)
- {
- float vel =Value*n;
- return vel;
- }
- void flash()
- {
- int r;
- r=c1;
- r_velocity = velocity(r);
- Serial.print("Motorspeed is ");
- Serial.print(r_velocity);
- Serial.println("cm/s");
- c1 = 0;
- }
- void COUNT()
- {
- c1++; //光码盘累加计数
- }
- void loop()
- {
- read_csb();
- delay(1000); //控制显示数据间隔,可以注释掉
- if (distance<15 and distance>0) //前方距离小于15cm
- {
- stopp(); //停止
- }
- else
- {
- bluetooth();
- }
- }
- void setup()
- {
- pinMode(INA,OUTPUT);
- pinMode(INB,OUTPUT);
- pinMode(PWMB,OUTPUT);
- pinMode(PWMA,OUTPUT);
-
- pinMode(EchoPin, INPUT);
- pinMode(TrigPin, OUTPUT);
-
- attachInterrupt(0,COUNT,FALLING);
-
- Serial.begin(9600);
- MsTimer2::set(1000, flash); // 中断设置函数,每 1s 进入一次中断
- MsTimer2::start();
-
- }
复制代码 |
|