将一个电阻和一个电容串联起来接地。最左边为电阻,电阻的最左端接单片机的PC1口,并设为输出。电阻和电容中间引出一根线,接到PC0口,设为输入。
最初PC1输出低电平,电容上没有电荷,PC0为低电平。
此时立即将PC1设为高电平,电容开始充电,PC0仍为低电平,过了一段时间后才变为高电平。也就是说PC0比PC1变化慢。将PC1设置回低电平后,也要过一段时间PC0才能变回低电平。
【计时用的程序】
#include <stm32f10x.h>
#define MODE 0
// MODE: 0->六位小数, 1->4位小数
#if MODE
#define TPSC 7199 // 精度: 100us
#define N 4
#else
#define TPSC 71 // 精度: 1us
#define N 6
#endif
uint8_t seg8[] = {0xc0, 0xf9, 0xa4, 0xb0, 0x99, 0x92, 0x82, 0xf8, 0x80, 0x90};
uint16_t num = 0;
void delay(void)
{
uint16_t i;
for (i = 0; i < 20000; i++);
}
void ser_in(uint8_t data)
{
uint8_t i;
for (i = 0; i < 8; i++)
{
GPIOB->BRR = GPIO_BRR_BR9; // SCLK=PB9
if (data & 0x80)
GPIOB->BSRR = GPIO_BSRR_BS7; // DIO=PB7
else
GPIOB->BRR = GPIO_BRR_BR7;
data <<= 1;
GPIOB->BSRR = GPIO_BSRR_BS9;
}
}
void par_out(void)
{
GPIOB->BRR = GPIO_BRR_BR8; // RCLK=PB8
GPIOB->BSRR = GPIO_BSRR_BS8;
}
void seg_scan(void)
{
uint8_t i;
uint16_t numbuf = num;
for (i = 0; i <= N; i++)
{
if (i == N)
ser_in(seg8[numbuf % 10] & 0x7f);
else
ser_in(seg8[numbuf % 10]);
ser_in(1 << i);
par_out();
delay();
numbuf /= 10;
}
}
int main(void)
{
RCC->APB1ENR = RCC_APB1ENR_TIM6EN;
RCC->APB2ENR = RCC_APB2ENR_IOPBEN | RCC_APB2ENR_IOPCEN;
GPIOB->CRH = 0x00300033;
GPIOB->CRL = 0x30000033;
GPIOC->CRL = 0x34;
TIM6->ARR = TIM_ARR_ARR;
TIM6->PSC = TPSC;
TIM6->CR1 = TIM_CR1_URS | TIM_CR1_OPM;
TIM6->EGR = TIM_EGR_UG;
TIM6->CR1 |= TIM_CR1_CEN; // 开始计时
GPIOC->BSRR = GPIO_BSRR_BS1; // 充电
while ((GPIOC->IDR & GPIO_IDR_IDR0) == 0); // 等待输出端的电平变为1
num = TIM6->CNT; // 记录时间
GPIOC->BRR = GPIO_BRR_BR1; // 放电
while (1)
seg_scan();
}