ESP32学习2--error: 'analogWrite' was not declared in this scope

今天尝试使用PWM控制led和电机,按照教程写下如下程序:

int ledPin = 2; // 设定控制 LED 的数字 IO 脚

int val; //定义一个变量

void setup()

{

  pinMode(ledPin, OUTPUT); // 设定数字 IO 口的模式, OUTPUT 为输出

}

void loop()

{

  for(val=0;val<255;val++) //变量循环+1

  {

    analogWrite(ledPin, val); //PWM 输出

    delay(50); //设定延时时间

  }

  for(val=255;val>0;val--) //变量循环-1

  {

    analogWrite(ledPin, val);

    delay(50);

  }

}

编译的时候提示error: 'analogWrite' was not declared in this scope

经多方查找以后发现esp32中并未实现analogWrite方法,详见analogWrite() not implemented #4

官方说法是这个函数正在搞,暂时可以用下面三个方法实现PWM:

16 channels LEDC which is PWM

8 channels SigmaDelta which uses SigmaDelta modulation

2 channels DAC which gives real analog output

下面是2个例子,分别使用SigmaDelta 和 LEDC

1、使用PWM:SigmaDelta实现呼吸灯效果,PIN2

int ledPin=2;

int val;

void setup() {

  //设置 channel 0 频率为 312500 Hz

    sigmaDeltaSetup(0, 312500);

    //IO口 pin 18 附加到 channel 0

    sigmaDeltaAttachPin(ledPin,0);

    //channel 0 初始状态为关闭

    sigmaDeltaWrite(0, 0);

}

void loop() {

  for(val=0;val<255;val++)

  {

    sigmaDeltaWrite(0,val);

    delay(50);

  }

  for(val=255;val>0;val--)

  {

    sigmaDeltaWrite(0,val);

    delay(50);

  }

}

2、使用LEDC控制led和电机

// use first channel of 16 channels (started from zero)

#define LEDC_CHANNEL_0    0

// use 13 bit precission for LEDC timer

#define LEDC_TIMER_13_BIT  13

// use 5000 Hz as a LEDC base frequency

#define LEDC_BASE_FREQ    20000

// fade LED PIN (replace with LED_BUILTIN constant for built-in LED)

#define LED_PIN            2

int brightness = 0;    // how bright the LED is

int fadeAmount = 5;    // how many points to fade the LED by

// Arduino like analogWrite

// value has to be between 0 and valueMax

void ledcAnalogWrite(uint8_t channel, uint32_t value, uint32_t valueMax = 255) {

  // calculate duty, 8191 from 2 ^ 13 - 1

  uint32_t duty = (8191 / valueMax) * min(value, valueMax);

  // write duty to LEDC

  ledcWrite(channel, duty);

}

void setup() {

  // Setup timer and attach timer to a led pin

  ledcSetup(LEDC_CHANNEL_0, LEDC_BASE_FREQ, LEDC_TIMER_13_BIT);

  ledcAttachPin(LED_PIN, LEDC_CHANNEL_0);

}

void loop() {

  // set the brightness on LEDC channel 0

  ledcAnalogWrite(LEDC_CHANNEL_0, brightness);

  // change the brightness for next time through the loop:

  brightness = brightness + fadeAmount;

  // reverse the direction of the fading at the ends of the fade:

  if (brightness <= 0 || brightness >= 255) {

    fadeAmount = -fadeAmount;

  }

  // wait for 30 milliseconds to see the dimming effect

  delay(30);

}

用上这段代码,nidec的无刷直流电机终于转动了

推荐阅读更多精彩内容

  • /************单片机:HT66018​​********/ /************ 日期:1603...
    _小豆豆阅读 160评论 0 0
  • 今天又像打鸡血似的,忙碌了一天。昨晚作业下来总结,发现教练是真心的对我们好。作业量虽然很大,但是只要自己把学的知识...
    护眼天使萍萍阅读 37评论 0 0
  • 体育课啊,排球考试,之前卖力地打都可以过,一到考试就他妈得事事不顺。宿舍人都过了,只有我差一个球,真的心痛,失落。...
    可我是璇璇啊阅读 91评论 0 0
  • 上篇内容请戳:关于『简诗 花非花 野草』专题 :投稿拒稿须知 此文只做几点补充 ,请按规范投稿: 我们即将严格审稿...
    买米的人阅读 672评论 7 24