本帖最后由 elecfans跑堂 于 2015-9-1 09:39 编辑
今天我们要学习FireBLE的ADC和PWM,GPIO结合起来使用板子上的Buzzer来演奏音乐。因为板子上只有一个五向按键,所以我们也只能演奏出:倒 软 咪 法 扫 五个音符。
实验目的:
ADC和PWM,GPIO结合起来使用板子上的Buzzer来演奏音乐
实验电路:
实验代码:
- #include "system.h"
- #include "adc.h"
- #include "timer.h"
- #include "pwm.h"
- #include "analog.h"
- #include "uart.h"
- #include "stdio.h"
- //pwm周期
- int period = 1500;
- volatile uint32_t adc_done = 0;
- int16_t buf[10];
- static void adc_test_cb(void)
- {
- adc_done = 1;
- }
- void gpio_callback(enum gpio_pin pin)
- {
- // Read configuration
- adc_read_configuration read_cfg;
- read_cfg.trig_src = ADC_TRIG_SOFT;
- // modify here
- read_cfg.mode = BURST_MOD;
- read_cfg.start_ch = AIN0;
- read_cfg.end_ch = AIN0;
- adc_read(&read_cfg, buf, 10, adc_test_cb);
- }
- void adc_io_config(void)
- {
- // pin mux
- syscon_SetPMCR0(QN_SYSCON, P00_UART0_TXD_PIN_CTRL
- | P05_ADCT_PIN_CTRL
- | P06_SW_DAT_PIN_CTRL
- | P07_SW_CLK_PIN_CTRL
- | P17_UART0_RXD_PIN_CTRL
- );
- syscon_SetPMCR1(QN_SYSCON, P26_PWM1_PIN_CTRL
- | P30_AIN0_PIN_CTRL
- );
- }
- int main (void)
- {
- //系统初始化
- SystemInit();
-
- //配置ADC
- adc_io_config();
- analog_pin_enable(AIN0, MASK_ENABLE);
- // ADC initialization
- adc_init(ADC_SINGLE_WITHOUT_BUF_DRV, ADC_CLK_1000000, ADC_INT_REF, ADC_12BIT);
- //配置UART
- uart_init(QN_UART0, __USART_CLK, UART_115200);
- uart_tx_enable(QN_UART0, MASK_ENABLE);
-
- //初始化PWM_CH1
- pwm_init(PWM_CH1);
- //设置PWM的周期和占空比
- pwm_config(PWM_CH1,119,PWM_COUNT_US(period,119),PWM_COUNT_US(1000,119));
- //启用PWM_CH1
- pwm_enable(PWM_CH1,MASK_ENABLE);
- //启用PWM时钟
- pwm_clock_on();
- adc_done = 0;
-
- //GPIo设置
- gpio_init(gpio_callback);
- //设置下降沿触发
- gpio_set_interrupt(GPIO_P12,GPIO_INT_FALLING_EDGE);
- //开中断
- gpio_enable_interrupt(GPIO_P12);
- gpio_clock_on();
-
-
- while (1) /* Loop forever */
- {
- if(adc_done == 1)
- {
- int sum = 0;
- for (int i = 0; i < 10; i++)
- {
- sum += buf[i];
- }
- int avg = sum / 10;
- //根据不同按键设置PWM周期
- switch(avg)
- {
- case 470:
- case 471:
- case 472:
- case 473:
- case 474:
- period = 956;
- break;
- case 1278:
- case 1279:
- case 1280:
- case 1281:
- case 1282:
- period = 851;
- break;
- case 1788:
- case 1789:
- case 1790:
- case 1791:
- case 1792:
- period = 758;
- break;
- case 866:
- case 867:
- case 868:
- case 869:
- case 870:
- period = 715;
- break;
- case 2045:
- case 2046:
- case 2047:
- case 2048:
- case 2049:
- period = 637;
- break;
- }
- pwm_config(PWM_CH1,119,PWM_COUNT_US(period,119),PWM_COUNT_US(period*0.8,119));
- printf("ADC Value:%dt Voltage:%d(mV)rnrn", avg, ADC_RESULT_mV(avg));
- adc_done = 0;
- }
- }
- }
复制代码
以上代码编译完下载到 开发板,重启,然后依次按五向按键 的上下左右中,就能听到 dao ruan mi fa suo的音乐了。
0
|
|
|
|