单片机比如51系列都有定时器,因此可以利用它来控制扬声器按一定频率发声,以下就是一个例程,用按键的按下和抬起来模拟电子琴的控制程序。
T0H EQU 30H
T0L EQU 31H
ORG 0000H
LJMP MAIN
ORG 000BH
LJMP T0ISR
ORG 0030H
MAIN:
MOV SP,#5FH
MOV TMOD,#01H
SETB ET0
SETB EA
LOOP:
MOV DPTR,#FREQ
MOV A,P2 ;控制高中低音区
MOV R1,#0
ANL A,#03H
JB ACC.0,LOOP01
MOV R1,#14
SJMP LOOP0
LOOP01:
JB ACC.1,LOOP0
MOV R1,#28
LOOP0:
JB P0.0,LOOP1 ;控制音频1234567
MOV A,R1
MOVC A,@A+DPTR
MOV T0H,A
INC DPTR
MOV A,R1
MOVC A,@A+DPTR
MOV T0L,A
LJMP LOOP
LOOP1:
JB P0.1,LOOP2
MOV A,R1
ADD A,#2
MOVC A,@A+DPTR
MOV T0H,A
INC DPTR
MOV A,R1
ADD A,#2
MOVC A,@A+DPTR
MOV T0L,A
LJMP LOOP
LOOP2:
JB P0.2,LOOP3
MOV A,R1
ADD A,#4
MOVC A,@A+DPTR
MOV T0H,A
INC DPTR
MOV A,R1
ADD A,#4
MOVC A,@A+DPTR
MOV T0L,A
LJMP LOOP
LOOP3:
JB P0.3,LOOP4
MOV A,R1
ADD A,#6
MOVC A,@A+DPTR
MOV T0H,A
INC DPTR
MOV A,R1
ADD A,#6
MOVC A,@A+DPTR
MOV T0L,A
LJMP LOOP
LOOP4:
JB P0.4,LOOP5
MOV A,R1
ADD A,#8
MOVC A,@A+DPTR
MOV T0H,A
INC DPTR
MOV A,R1
ADD A,#8
MOVC A,@A+DPTR
MOV T0L,A
LJMP LOOP
LOOP5:
JB P0.5,LOOP6
MOV A,R1
ADD A,#10
MOVC A,@A+DPTR
MOV T0H,A
INC DPTR
MOV A,R1
ADD A,#10
MOVC A,@A+DPTR
MOV T0L,A
LJMP LOOP
LOOP6:
JB P0.6,LOOP7
MOV A,R1
ADD A,#12
MOVC A,@A+DPTR
MOV T0H,A
INC DPTR
MOV A,R1
ADD A,#12
MOVC A,@A+DPTR
MOV T0L,A
LJMP LOOP
LOOP7:
CLR TR0
LJMP LOOP
;-----------------------------
T0ISR:
CLR TR0
MOV TH0,T0H
MOV TL0,T0L
SETB TR0
CPL P3.0
RETI
;-----------------------------
FREQ:
DB 0F2H,03DH ;低音1
DB 0F3H,0BDH ;低音2
DB 0F5H,014H ;低音3
DB 0F5H,0B1H ;低音4
DB 0F6H,0D0H ;低音5
DB 0F7H,0D1H ;低音6
DB 0F8H,0B5H ;低音7
DB 0F9H,01EH ;中音1
DB 0F9H,0DEH ;中音2
DB 0FAH,08AH ;中音3
DB 0FAH,0D8H ;中音4
DB 0FBH,068H ;中音5
DB 0FBH,0E8H ;中音6
DB 0FCH,05AH ;中音7
DB 0FCH,08FH ;高音1
DB 0FCH,0EFH ;高音2
DB 0FDH,045H ;高音3
DB 0FDH,06CH ;高音4
DB 0FDH,0B4H ;高音5
DB 0FDH,0F4H ;高音6
DB 0FEH,029H ;高音7
;-----------------------------
END