#include "sys.h" #include "delay.h" #include "usart.h" #include "string.h" #include "uart.h" #include "led.h" uint8_t recive_buff[256] = {0}; uint16_t recive_count = 0; uint8_t sendbuf[256] = {0}; #define AC_DC 1 #define AC3 2 uint16_t flag = 0; extern uint16_t recive_flag; unsigned short calculateModbusCRC16(uint8_t *data,uint16_t lenth) { uint16_t crc = 0xFFFF; // Initial value unsigned short swappedCRC = 0xFFFF; int i = 0; int j = 0; for (; i < lenth; i++) { crc = crc ^ data[i]; // XOR byte into the least significant byte of CRC j = 0; for (; j < 8; j++) { if (crc & 1) { crc >>= 1; crc ^= 0xA001; } else { crc >>= 1; } } } // Swap the bytes of the CRC to match Modbus convention swappedCRC = ((crc >> 8) & 0xFF) | ((crc & 0xFF) << 8); return crc; } int check_ac_dc() { int t = -1; uint16_t data = 0; recive_count = 0; memset(sendbuf,0,sizeof(sendbuf)); sendbuf[0] = 0x01; sendbuf[1] = 0x03; sendbuf[2] = 0x0f; sendbuf[3] = 0xA0; sendbuf[4] = 0x00; sendbuf[5] = 0x20; data = calculateModbusCRC16(sendbuf,6); sendbuf[6] = data; sendbuf[7] = data >> 8; recive_count = (sendbuf[5]) * 2 +3+2; uart3_send(&sendbuf[0],8); delay_ms(300); if(recive_flag) { flag = AC_DC; t = 0; }else flag = 0; return t; } int check_ac3() { int t = -1; #if 1 uint16_t data = 0; recive_count = 0; memset(sendbuf,0,sizeof(sendbuf)); sendbuf[0] = 0x01; sendbuf[1] = 0x03; sendbuf[2] = 0x17; sendbuf[3] = 0x70; sendbuf[4] = 0x00; sendbuf[5] = 0x20; data = calculateModbusCRC16(sendbuf,6); sendbuf[6] = data; sendbuf[7] = data >> 8; recive_count = (sendbuf[5]) * 2 + 2 + 4; uart3_send(&sendbuf[0],8); delay_ms(300); if(recive_flag) { flag = AC3; t = 0; }else flag = 0; #endif return t; } int main(void) { NVIC_PriorityGroupConfig(NVIC_PriorityGroup_2); delay_init(); uart_init(115200); led_init(); uart3_init(); while(1) { if(flag == 0) { if( -1 ==check_ac_dc()) check_ac3(); }else if(flag == 1) { check_ac_dc(); }else if(flag == 2) { check_ac3(); } if(flag) { led_flash(); led_status(); }else { led_clear(); } delay_ms(500); } }