Notifications
Clear all

Pico - buzzing a piezo

1 Posts
1 Users
0 Likes
97 Views
THRandell
(@thrandell)
Estimable Member
Joined: 2 years ago
Posts: 154
Topic starter  

I was testing a new main board today and I thought that I’d share the bit of code I was using to make sure my soldering hadn’t fried the piezo buzzer.

 Tom

 

/*
 * Trying to play some musical frequencies out of a piezo buzzer
 *   I tried multiple duty cycles at the various frequencies
 *   and the volume is too low.  Plastic gear motor noise drowns it out.
 *
 *  wrap = frequency and channel level = duty_cycle
 *
*/
#include <stdio.h>
#include "pico/stdlib.h"
#include "hardware/pwm.h"

#define BUZZER_PWM  5   // GPIO pin number for piezo buzzer connection

// these tones are piercing.... ouch.  Even with a smaller set the B7, C#8 and D8 are loud and piercing.
uint32_t toneFreq[15] = {1175,1318,1480,1568,1760,1975,2217,2349,2637,2960,3136,3520,3951,4435,4699}; //,5274,5588,5920};
// D6 ,E6, F#6, G6, A6, B6, C#7, D7, E7, F#7, G7, A7, B7, C#8, D8

uint32_t pwm_set_freq_duty(uint slice_num, uint chan, uint32_t f, int d)
{ 
  uint32_t clock = 125000000;
  uint32_t divider16 = clock / f / 4096 + (clock % (f * 4096) != 0);
  if (divider16 / 16 == 0)
    divider16 = 16;
  uint32_t wrap = clock * 16 / divider16 / f - 1;
  pwm_set_clkdiv_int_frac(slice_num, divider16 / 16, divider16 & 0xF);
  pwm_set_wrap(slice_num, wrap);
  pwm_set_chan_level(slice_num, chan, wrap * d / 100);
  return wrap;
}

uint32_t pwm_get_wrap(uint slice_num)
{
  valid_params_if(PWM, slice_num >= 0 && slice_num < NUM_PWM_SLICES);
  return pwm_hw->slice[slice_num].top;
}


void main() {
  stdio_init_all();
  gpio_set_function(BUZZER_PWM, GPIO_FUNC_PWM);
  uint slice_num = pwm_gpio_to_slice_num(BUZZER_PWM);
  uint channel = pwm_gpio_to_channel(BUZZER_PWM);

  pwm_set_freq_duty(slice_num, channel, toneFreq[0], 50);
  pwm_set_enabled(slice_num, true);

  while (true) {
    for (int x = 0; x <= 14; x++) {
      pwm_set_freq_duty(slice_num, channel, toneFreq[x], 50);
      uint32_t top = pwm_get_wrap(slice_num);
      printf("value for top is: %d\n", top);
      sleep_ms(500);
    }
    sleep_ms(1000);
  }
}

 

 

Pico/RP2040 ≠ Arduino
Pico = hot rod kit car, Arduino = hot rod kit car wrapped in cotton wool with buoyancy aids & parachute


   
Quote
Topic Tags