如何使用C/Rust将蜂鸣器连接到Raspberry pi皮科?

bvn4nwqk  于 2022-11-12  发布在  其他
关注(0)|答案(1)|浏览(158)

我有一个Raspberry pi皮科和一个蜂鸣器,我将其连接到GPIO 15。我可以使用MicroPython和Thony让它发出嗡嗡声并播放几个音符,如下所示:

from machine import Pin, PWM
from utime import sleep
buzzer = PWM(Pin(15))

tones = {
"C5": 523,
"CS5": 554,
"D5": 587,
"DS5": 622,
"E5": 659,
"F5": 698,
"FS5": 740,
"G5": 784,
"GS5": 831,
"A5": 880,
"AS5": 932,
"B5": 988,
}

song = ["E5","G5","A5","P","E5","G5","B5","A5","P","E5","G5","A5","P","G5","E5"]
led = Pin(25, Pin.OUT)

def playtone(frequency):
    buzzer.duty_u16(1000)
    buzzer.freq(frequency)
    led.toggle()

def bequiet():
    buzzer.duty_u16(0)

def playsong(mysong):
    for i in range(len(mysong)):
        if (mysong[i] == "P"):
            bequiet()
        else:
            playtone(tones[mysong[i]])
        sleep(0.3)
    bequiet()
playsong(song)

它的工作原理就像一个魔咒。然而,我不是一个python的人,我想用C/Rust做同样的事情。我已经做了几天的研究,现在认为我应该用PWM来做,但我非常不知所措。请帮助。

j13ufse2

j13ufse21#

WiringPi是一个相当成熟的C语言中的RPi GPIO访问库。
它还附带了像PWMtones这样的东西,应该会很有帮助。
下面是一个如何使用它的示例:


# include <wiringPi.h>

# include <softTone.h>

# include <stdio.h>

# define BuzzPin 0

# define CL1 131

# define CL2 147

# define CL3 165

# define CL4 175

# define CL5 196

# define CL6 221

# define CL7 248

# define CM1 262

# define CM2 294

# define CM3 330

# define CM4 350

# define CM5 393

# define CM6 441

# define CM7 495

# define CH1 525

# define CH2 589

# define CH3 661

# define CH4 700

# define CH5 786

# define CH6 882

# define CH7 990

int song_1[] = {CM3,CM5,CM6,CM3,CM2,CM3,CM5,CM6,CH1,CM6,CM5,CM1,CM3,CM2,
CM2,CM3,CM5,CM2,CM3,CM3,CL6,CL6,CL6,CM1,CM2,CM3,CM2,CL7,
CL6,CM1,CL5};

int beat_1[] = {1,1,3,1,1,3,1,1,1,1,1,1,1,1,3,1,1,3,1,1,1,1,1,1,1,2,1,1,
1,1,1,1,1,1,3};

int song_2[] = {CM1,CM1,CM1,CL5,CM3,CM3,CM3,CM1,CM1,CM3,CM5,CM5,CM4,CM3,CM2,
CM2,CM3,CM4,CM4,CM3,CM2,CM3,CM1,CM1,CM3,CM2,CL5,CL7,CM2,CM1
};

int beat_2[] = {1,1,1,3,1,1,1,3,1,1,1,1,1,1,3,1,1,1,2,1,1,1,3,1,1,1,3,3,2,3};

int main(void) {
  int i, j;

  if (wiringPiSetup() == -1) {
    When wiringpi initialization failed printf "WiringPi Failed"
    printf("14CORE | WiringPi initialization failed !");
    return 1;
  }

  if (softToneCreate(BuzzPin) == -1) {
    printf("14CORE| Soft Tone Failed !");
    return 1;
  }

  while (1) {
    printf("14CORE| Sound is generated...\n");

    for (i = 0; i < sizeof(song_1) / 4; i++) {
      softToneWrite(BuzzPin, song_1[i]);
      delay(beat_1[i] * 500);
    }

    for (i = 0; i < sizeof(song_2) / 4; i++) {
      softToneWrite(BuzzPin, song_2[i]);
      delay(beat_2[i] * 500);
    }
  }

  return 0;
}

相关问题