#include <reg51.h>

sbit VOLTAGE = P1^0; // 电压输入引脚 sbit CURRENT = P1^1; // 电流输入引脚 sbit LED = P2^0; // 输出引脚

unsigned char phase; // 相位

void delay(unsigned int x) // 延时函数 { unsigned int i, j; for (i = 0; i < x; i++) for (j = 0; j < 100; j++); }

void main() { TMOD = 0x01; // 设置定时器0为模式1 TH0 = 0; // 定时器0计数初值 TL0 = 0; TR0 = 1; // 启动定时器0 ET0 = 1; // 允许定时器0中断 EA = 1; // 允许中断

while (1)
{
    if (phase >= 120 && phase <= 240)   // 判断相位是否在120度到240度之间
        LED = 1;                        // 输出高电平
    else
        LED = 0;                        // 输出低电平
}

}

void timer0() interrupt 1 // 定时器0中断服务函数 { static unsigned char count; static unsigned char voltage_last, voltage_now, current_last, current_now;

voltage_last = voltage_now;
voltage_now = VOLTAGE;
current_last = current_now;
current_now = CURRENT;

count++;                // 计数器加1
if (count == 50)        // 每50次中断触发一次相位检测
{
    if (voltage_last == 0 && voltage_now == 1)   // 电压上升沿
    {
        if (current_last == 0 && current_now == 1)   // 电流上升沿
            phase = 0;                              // 相位为0度
        else if (current_last == 1 && current_now == 0)  // 电流下降沿
            phase = 180;                            // 相位为180度
    }
    else if (voltage_last == 1 && voltage_now == 0)  // 电压下降沿
    {
        if (current_last == 0 && current_now == 1)   // 电流上升沿
            phase = 360;                            // 相位为360度
        else if (current_last == 1 && current_now == 0)  // 电流下降沿
            phase = 540;                            // 相位为540度
    }
    count = 0;              // 计数器清零
}

}

程序思路:

程序中使用定时器0来检测电流电压的相位,每50次定时器中断触发一次相位检测。在检测过程中,通过检测电压和电流的上升和下降沿来确定相位。最后,根据相位判断输出引脚的电平。


原文地址: https://www.cveoy.top/t/topic/nnlX 著作权归作者所有。请勿转载和采集!

免费AI点我,无需注册和登录