Hardwarenahe Programmierung

PWM Speaker

Der folgende Code gibt ein Beispiel für die Verwendung des Lautsprechers (Speaker) des mbed-Application-Board:

mbedESP32S_Speaker-PWM.ino

const int speaker = 12;  // 12 corresponds to GPIO26

// setting PWM properties
const int freq = 5000;
const int spkrChannel = 0;
const int resolution = 8;
 
void setup(){
  // configure spkr PWM functionalitites
  ledcSetup(spkrChannel, freq, resolution);
  
  // attach the channel to the GPIO to be controlspkr
  ledcAttachPin(speaker, spkrChannel);
}
 
void loop(){
  // increase the spkr frequency
  for(int dutyCycle = 0; dutyCycle <= 255; dutyCycle++){   
    // changing the spkr brightness with PWM
    ledcWrite(spkrChannel, dutyCycle);
    delay(15);
  }

  // decrease the spkr frequency
  for(int dutyCycle = 255; dutyCycle >= 0; dutyCycle--){
    // changing the spkr brightness with PWM
    ledcWrite(spkrChannel, dutyCycle);   
    delay(15);
  }
}

All wikipages