#coding=utf-8 import json # 常量定义 MCU_CLK = 1000000 # 12MHz,内部时钟12分频 MCU_T = 1000000/MCU_CLK # 单位时间为1us # 音符映射 note_mapping = { 1: 'C4', 2: 'D4', 3: 'E4', 4: 'F4', 5: 'G4', 6: 'A4', 7: 'B4' } # 根据频率计算计数器初值 def freq_to_num(freq): T = 10**6/freq # 单位时间为1us time0 = int(2**16 - (T/2) / MCU_T) time0H = hex(time0>>8) time0L = hex(time0&0xff) print("freq = %0.2fHz, T = %dus, time0 = %d, time0H = %s, time0L = %s" % (freq, T, time0, time0H, time0L)) return time0H, time0L # 根据音符名称获取频率 def note_to_freq(note_name): try: # 读取 JSON 文件 with open('note_data.json', 'r') as file: notes = json.load(file) # 获取特定音符的频率 frequency = notes[note_name]['frequency'] return frequency except KeyError: return None except Exception as e: print(f"An error occurred: {e}") return None # 根据音符名称获取计数器初值 def note_to_num(note_name): frequency = note_to_freq(note_name.upper()) if frequency is not None: print(f"{note_name}的频率为{frequency}Hz。") freq_to_num(frequency) else: print(f"{note_name} 不是有效的音符。") # 转换函数 def map_tones_to_notes(tone_array): notes = [] for tone in tone_array: # 将音调映射到相应的音符 note = note_mapping.get((tone - 1) % 7 + 1 if tone <= 7 else (tone - 1) % 7 + 8) notes.append(note) return notes # 原始数据:小星星歌曲 soundtones = [ 1,1,5,5,6,6,5,4,4,3,3,2,2,1, 5,5,4,4,3,3,2,5,5,4,4,3,3,2, 1,1,5,5,6,6,5,4,4,3,3,2,2,1 ] if __name__ == '__main__': mapped_notes = map_tones_to_notes(soundtones) for note in mapped_notes: note_to_num(note)