写一个c51单片机测量脉冲频率的c语言程序,通过测量周期时间内的脉冲数量得到脉冲频率
时间: 2023-06-02 13:05:39 浏览: 118
以下是C语言程序的代码,用于测量脉冲频率:
```C
#include <reg51.h>
#include <stdio.h>
#define CLK 22118400UL
#define BAUD 115200
#define TIMER_PRESCALER 12
sbit TEST_PIN = P1^0;
unsigned char receiveBuffer[16];
unsigned char receiveCounter = 0;
float frequency;
void initSerial()
{
SCON = 0x50;
TMOD &= 0x0F;
TMOD |= 0x20;
TH1 = 256 - CLK/(32*TIMER_PRESCALER*BAUD);
TR1 = 1;
}
void receiveInterrupt() interrupt 4
{
RI = 0;
receiveBuffer[receiveCounter] = SBUF;
receiveCounter++;
if (receiveBuffer[receiveCounter-1] == '\n') {
receiveBuffer[receiveCounter-1] = '\0';
receiveCounter = 0;
sscanf(receiveBuffer, "%f\r", &frequency);
}
}
void main()
{
unsigned long pulseCount = 0;
unsigned long pulsePeriod = 0;
unsigned long start = 0;
initSerial();
TMOD &= 0xF0;
TMOD |= 0x01;
TEST_PIN = 0;
while(1) {
TEST_PIN = 1;
while(!TEST_PIN);
TR0 = 1;
while(TEST_PIN);
TR0 = 0;
pulseCount++;
pulsePeriod += TH0 * 256 + TL0;
if (pulseCount == 100) {
frequency = 1.0/pulsePeriod*100*TIMER_PRESCALER*CLK;
printf("%.2f Hz\n", frequency);
pulseCount = 0;
pulsePeriod = 0;
}
start = TH0 * 256 + TL0;
while ((TH0 * 256 + TL0) - start < (CLK/(TIMER_PRESCALER*100)))
;
}
}
```
这个程序实现了通过测量一定时间内的脉冲数量来计算脉冲频率。程序中使用了定时器和外部触发脉冲来实现精确测量。具体来说,程序中使用了定时器 T0 来计算脉冲周期的时间,每测量到 100 个脉冲,就通过计算平均周期时间来计算脉冲频率。在本例中,使用的是 22118400Hz 的晶振。
阅读全文