#include "main.h" //*------------------------------------------------------------- //*功能说明: 定时器3,可用于系统定时器,System1MsCnt毫秒计时器 //*全局参数: System1MsCnt--毫秒计数器 //*------------------------------------------------------------- unsigned long System1MsCnt=0; void Timer3Init(void) { T3CTL |= 0x08 ; //开溢出中断 T3IE = 1; //开总中断和T3中断 T3CTL &= ~0x03; //自动重装00->0xff T3CTL |= 0x10; //启动 EA = 1; //开总中断 } #pragma vector = T3_VECTOR __interrupt void T3_ISR(void) { static unsigned char cnt=0; IRCON = 0x00; //清中断标志, 也可由硬件自动完成 if(cnt++ > 51) //1ms 示波器观察1.02ms { //经过示波器测量确保精确 cnt = 0; //计数清零 System1MsCnt++; } } void clock_setup(void) { CLKCONCMD &= ~0x40; //设置系统时钟源为32MHZ晶振 while(CLKCONSTA & 0x40); //等待晶振稳定 CLKCONCMD &= ~0x47; //设置系统主时钟频率为32MHZ Delay_ms(500); //让设备稳定 Timer3Init(); //可选项,系统1ms计数器 } void InitBuzzer(void) { P1DIR |= 0x08; //P1_3 定义为输出 BUZZER = 0; //BUZZER 初始化关闭 } void init_sensor_io(void) { //1.设置IO为普通IO P0SEL |= 0xC0; P1SEL |= 0x07; //2.设置编码口为输入 P0DIR &= ~0xC0; P1DIR &= ~0x07; } uchar get_sensor_id(void) { volatile uchar temp = P0_6<<4|P0_7<<3|P1_0<<2|P1_1<<1|P1_2; return temp; } void InitKey(void) { P2DIR &= ~0x01; //P20定义为输入 KEY = 1; } uchar CheckKey(void) { if(KEY == 0) { Delay_ms(10); if(KEY == 0) { KEY = 1; return 1; } } return 0; } void init_rs485(void) { APCFG &= 0xFE; P0SEL &= 0xFE; P0DIR |= 0x01; } void main(void) { ModbusRecv MBRecv; ModbusSend MBSend; Digital Dig; ulong curtime; uchar temp8; uchar buf[16]; clock_setup(); //系统时钟设置,精确延时必须要设置 port_init(); initial_lcd(); InitBuzzer(); init_rs485(); InitUart(9600); clear_screen(); //清屏 disp_string_8x16_16x16(1,1,"武汉唯众智创科技"); //显示字符串,括号里的参数分别为(PAGE,列,字符串指针) disp_string_8x16_16x16(3,1,"----实验3.4-----"); Delay_ms(1000); while(1) { Delay_ms(10); temp8 = get_sensor_id(); if(temp8!=14 && temp8!=11){ disp_string_8x16_16x16(1,1,"请插RS485模块"); disp_string_8x16_16x16(3,1,"----实验3.4-----"); Delay_ms(1000); continue; } if(System1MsCnt-curtime>1000){ curtime = System1MsCnt; fg_FillBuf(MBSend.Buf,6,0x01,0x03,0x00,0x02,0x00,0x06); RS485_SEND = 1; UartSendBytes(MBSend.Buf,8); Delay_ms(10); RS485_SEND = 0; temp8 = UartRecvBytes(MBRecv.Buf,0,50); if(temp8==MBRecv.P.len+5){ uint8_t *temp = fg_MakeCrc16(0xFFFF,MBRecv.P.len+3,MBRecv.Buf); if(temp[0]!=MBRecv.P.crc0 || temp[1]!=MBRecv.P.crc1){ break; } memcpy(Dig.A.c,MBRecv.P.data+0,4); //电流 fg_ReverseBuf(Dig.A.c,4); memcpy(Dig.V.c,MBRecv.P.data+4,4); //电压 fg_ReverseBuf(Dig.V.c,4); memcpy(Dig.W.c,MBRecv.P.data+8,4); //功率 fg_ReverseBuf(Dig.W.c,4); clear_screen(); sprintf(buf,"W:%.2f",Dig.W.f); //显示电压,保留2位小数 disp_string_8x16_16x16(1,1,buf); sprintf(buf,"A:%.2f V:%.2f",Dig.A.f,Dig.V.f); //显示电流和电压,保留2位小数 disp_string_8x16_16x16(3,1,buf); } } } } |