Files

105 lines
2.6 KiB
C
Raw Permalink Blame History

This file contains ambiguous Unicode characters
This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.
#include <reg52.h>
// --- 引脚定义 ---
sbit MOS1 = P1^2;
sbit MOS2 = P1^3;
sbit MOS3 = P1^4;
sbit MOS4 = P1^5;
sbit KEY_START = P3^6; // 启动/停止
sbit KEY_ADJ = P3^7; // 参数调节/复位
// --- 全局变量 ---
unsigned int pulse_width = 100; // 脉宽计数值 (单位: 100us)
unsigned int period = 1000; // 周期计数值 (单位: 100us)
unsigned char run_flag = 0; // 运行标志
unsigned char tick_1ms = 0; // 1ms 标志
// --- 定时器0初始化 (1ms @ 12MHz) ---
void Timer0_Init() {
TMOD &= 0xF0;
TMOD |= 0x01; // 模式1,16位定时器
TH0 = 0xFC; // 1ms 初值 (12MHz)
TL0 = 0x18;
ET0 = 1;
EA = 1;
TR0 = 1;
}
// --- 毫秒级延时 (用于消抖) ---
void DelayMs(unsigned int ms) {
unsigned int i, j;
for(i = ms; i > 0; i--)
for(j = 110; j > 0; j--);
}
// --- 定时器0中断服务 ---
void Timer0_ISR() interrupt 1 {
TH0 = 0xFC;
TL0 = 0x18;
tick_1ms = 1;
}
// --- 按键扫描 (带消抖) ---
void Key_Scan() {
static unsigned char key_lock = 0;
if (!key_lock && (KEY_START == 0)) {
DelayMs(10);
if (KEY_START == 0) {
run_flag = !run_flag;
key_lock = 1;
// 停止时立即关闭所有 MOS
if (!run_flag) { P1 &= 0xC3; } // 清零 P1.2~P1.5
}
} else if (KEY_START == 1) {
key_lock = 0;
}
// 简易参数调节:切换预设脉宽/频率 (可扩展)
if (!key_lock && (KEY_ADJ == 0)) {
DelayMs(10);
if (KEY_ADJ == 0) {
// 示例:切换脉宽
pulse_width = (pulse_width == 100) ? 500 : 100;
while(KEY_ADJ == 0); // 等待释放
}
}
}
// --- 产生脉冲 (阻塞式,适用于低频/中频) ---
void Generate_Pulse() {
unsigned int cnt;
// 1. 输出高电平 (开启 MOS)
P1 |= 0x3C; // 置位 P1.2~P1.5 (0x3C = 0011 1100)
// 2. 维持脉宽
for(cnt = 0; cnt < pulse_width; cnt++) {
DelayMs(1); // 简单延时,实际可改用定时器精确控制
}
// 3. 输出低电平 (关闭 MOS)
P1 &= 0xC3; // 清零 P1.2~P1.5
// 4. 维持周期剩余时间
for(cnt = pulse_width; cnt < period; cnt++) {
DelayMs(1);
}
}
// --- 主函数 ---
void main() {
P1 = 0xC3; // 初始化 P1.2~P1.5 为低电平 (确保上电 MOS 关断)
Timer0_Init();
while(1) {
Key_Scan();
if (run_flag) {
Generate_Pulse();
} else {
P1 &= 0xC3; // 确保停止时输出低电平
}
}
}