根据文档中提供的信息,完成文档中的要求,将所有.c和.h文件以及所有包含的需要的代码都写出来,尽可能简洁明了,但不要框架。矩阵按键按下后,矩阵扫描扫描到电平变化,蜂鸣器工作发出声音,电平变化结束蜂鸣器停止工作
时间: 2024-09-15 20:09:40 浏览: 40
C语言中.h和.c文件的解析.doc
为了实现您所描述的功能——即当矩阵按键被按下后,蜂鸣器会发出声音,并且数码管上会显示出相应的编号,我们需要对现有的代码进行扩展。以下是整合后的`main.c`及`main.h`文件的内容:
### main.h
```c
#ifndef __MAIN_H__
#define __MAIN_H__
#include <STC32G.H>
#define MAIN_Fosc 12000000UL
typedef unsigned char u8;
typedef unsigned int u16;
typedef unsigned long int u32;
sbit DS = P2^0;
sbit ST = P2^1;
sbit SH = P2^2;
sbit COM1 = P0^0;
sbit COM2 = P0^1;
sbit COM3 = P0^2;
sbit BUZZER = P1^7; // 蜂鸣器控制端口定义
u8 SEG_Code[13] = {0x3f, 0x06, 0x5b, 0x4f, 0x66, 0x6d, 0x7d, 0x07, 0x7f, 0x6f, 0x00, 0x40, 0xFF};
void delayms(u16 ms);
void Write595(u8 dat);
void displayNumber(u8 number);
#endif
```
### main.c
```c
#include "main.h"
void main(void) {
u8 number = 0;
u8 key;
u8 beep = 0;
EAXFR = 1; // Enable XFR access
CKCON = 0x00; // Set external data bus speed to fastest
WTST = 0x00; // Set program read wait time to zero clocks, CPU executes program at maximum speed
P0M1 = 0x00; P0M0 = 0x00; // Configure P0 port as quasi-bidirectional mode
P1M1 = 0x00; P1M0 = 0x00; // Configure P1 port as quasi-bidirectional mode
P2M1 = 0x00; P2M0 = 0xFF; // Configure P2 port as push-pull output
while (1) {
P2 = 0x7E;
u8 temp = P2;
temp &= 0x70;
if(temp != 0x70) {
delayms(10);
if(temp != 0x70) {
temp = P2;
switch(temp) {
case 0x6E: key = 1; beep = 1; break;
case 0x5E: key = 5; beep = 1; break;
case 0x3E: key = 8; beep = 1; break;
}
delayms(100);
beep = 0;
while(temp != 0x70) {
temp = P2;
temp &= 0x70;
}
}
}
if(beep == 1)
BUZZER = 1;
else
BUZZER = 0;
if(key > 0 && key <= 10) {
displayNumber(key);
key = 0; // Reset after displaying the value
}
delayms(1);
}
}
void delayms(u16 ms) {
u16 i;
do {
i = MAIN_Fosc / 6000;
while(--i);
} while(--ms);
}
void Write595(u8 dat) {
u16 i;
u8 datcode = SEG_Code[dat];
for(i = 0; i < 8; ++i) {
SH = 0;
DS = datcode & 0x80;
SH = 1;
datcode <<= 1;
}
ST = 0;
ST = 1;
}
void displayNumber(u8 number) {
Write595((u8)(number / 100));
COM1 = 0;
COM2 = 1;
COM3 = 1;
delayms(1);
Write595((u8)(number / 10 % 10));
COM1 = 1;
COM2 = 0;
COM3 = 1;
delayms(1);
Write595((u8)(number % 10));
COM1 = 1;
COM2 = 1;
COM3 = 0;
delayms(1);
}
```
上述代码实现了当检测到有效的按键按下时,通过蜂鸣器发出声音提示,并在数码管上显示对应的按键值。注意这里简化处理了部分逻辑以保持代码的清晰度。
阅读全文