ZBLOG

#define E1A 2 #define E1B 3 #define LeftMotor1 4 #define LeftMotor2 5 int valA=0, ValB=0; float m, o; int flag=0, flag1=0; int speedc=70, speedgord=750; //speed_a:自定速度初始值 speed_b:目标速度 int speedb...

根据你提供的代码,我帮你进行了一些修正:

#define E1A 2
#define E1B 3
#define LeftMotor1 4
#define LeftMotor2 5

volatile int valA = 0, ValB = 0;
volatile float m, o;
volatile int flag = 0;

int speedc = 70, speedgord = 750; //speed_a:自定速度初始值 speed_b:目标速度

void timer()
{
    valA++;
    if (valA >= speedgord) {
        detachInterrupt(0); //关中断
        flag = 1;
        valA = 0;
    }
}

void setup()
{
    pinMode(E1A, INPUT);
    pinMode(LeftMotor1, OUTPUT);
  
    Serial.begin(9600);
  
    attachInterrupt(digitalPinToInterrupt(E1A), timer, RISING); //上升沿开中断
  
    Serial.println(millis());
}

void loop()
{
    analogWrite(LeftMotor1, speedc);

    if (flag == 1)
    {
        m = ValB * 100; //放大一百倍串口绘图
        Serial.println(m, 3);
    
        if (m > speedgord) //如果编码器测得的实际速度大于我们设定的目标速度就减速
        {
            speedc--; //speed为60/100 r/s
        }
        else //如果编码器测得的实际速度小于我们设定的目标速度就加速
        {
            speedc++;
        }
      
         delay(0);
         attachInterrupt(digitalPinToInterrupt(E1A), timer, RISING);
         flag = 0;
    }
}

修正的内容包括:

  • 将中断引脚的参数 0 修改为 digitalPinToInterrupt(E1A),这样可以根据引脚号自动匹配对应的中断号。

  • timer() 函数和全局变量声明中,添加了 volatile 关键字来确保编译器正确处理中断相关的变量。

  • setup() 函数中,将 pinMode(speedgord, OUTPUT); 移除,因为在代码中并没有使用到该引脚。

请注意检查修改后的代码,并根据你的实际硬件连接进行测试。


内容由零声教学AI助手提供,问题来源于学员提问

本站部分文章来源于网络,版权归原作者所有,如有侵权请联系站长删除。
转载请注明出处:https://golang.0voice.com/?id=17154

分享:
扫描分享到社交APP
上一篇
下一篇
发表列表
游客 游客
此处应有掌声~
评论列表

还没有评论,快来说点什么吧~

联系我们

在线咨询: 点击这里给我发消息

微信号:3007537140

上班时间: 10:30-22:30

关注我们
x

注册

已经有帐号?