【发布时间】:2017-10-30 01:30:53
【问题描述】:
我制作了一个播放歌曲的程序(使用蜂鸣器)保存在数组中:
(...)
//function which plays a single note
void playNote(int8 wavelength, int duration) {
if (wavelength != 1) {
OCR0A = wavelength; /* set pitch */
SPEAKER_DDR |= (1 << SPEAKER); /* enable output on speaker */
}
while (duration) { /* Variable delay */
_delay_ms(1);
duration--;
}
SPEAKER_DDR &= ~(1 << SPEAKER); /* turn speaker off */
//function which plays song from array
void playSong( int8 *song,int tempo){
int length_16_note = tempo;
for( int8 i = 0;song[i]) ; i += 2){
playNote(song[i],song[i+1]*length_16_note);
_delay_ms(15);
}
}
int main(void){
//array of macros and lenghts of notes
int8 song1[] = {
C,4, E1,4, F1,3, E1,3, F1,2,
F1,2, F1, 2, B1,2, A1,2, G1,1, F1,2, G1,5,
G1,4, B1,4, C1,3, F1,3, E1,2,
B1,2, B1,2, G1,2, B1,2,
B1,3, C1,13, 0};
//initialize a timer
initTimer();
//play song
playSong(song1, 150)
}
我省略了其中的某些部分,但这段代码运行良好。现在我想将我的歌曲保存到程序内存中,所以我进行了更改:
#include <avr/pgmspace.h>
(...)
int8 song1[] PROGMEM = {...}
void playSong( int8 *song, int tempo){
int length_16_note = tempo;
for( int8 i = 0; pgm_read_byte(&(song[i])) ; i += 2){
playNote(pgm_read_byte(&(song[i])), pgm_read_byte(&(song[i+1]))*length_16_note);
_delay_ms(15);
}
}
当我在 Arduino 上运行该代码时,我会收到随机的 哔声,持续时间随机(比预期的要长得多)。看起来pgm_read_byte(&(song[i])) 返回随机值。
我试图从函数playSong 到main 中提取代码,以便不将数组作为参数传递给函数并且没有任何改变。那么这段代码有什么问题呢?
【问题讨论】: