#include<reg52.h>
/***********************************/
#define bp 8
unsigned char bpq[bp]; //變頻器數據緩沖區定義
unsigned char flag1,temp1;
/****************串行口初始化函數****************/
void InitUART(void)
{
TMOD = 0x20; //定時器1工作在方式2 8位自動重裝
SCON = 0xda;
TH1 = 0xfd; //定時器1初值
TL1 = TH1;
TR1 = 1; //定時器1開始計數
EA =1; //開總中斷
ES =1; //開串口1中斷
}
/****************串行口發送****************/
void UART_1SendOneByte(unsigned char c)
{
ACC=c;
if(P)
{
TB8=1;
}
else
{
TB8=0;
}
SBUF = ACC;
while(TI==0);
TI=0;
}
//向串口1發送一個字符串,strlen為該字符串長度
void send_string_com(unsigned char *str,unsigned int strlen)
{
unsigned int k=0;
do
{
UART_1SendOneByte(*(str + k));
k++;
} while(k < strlen);
}
/**********************************CRC算法****************************/
unsigned int crc_check(unsigned char *dat,unsigned char length)
{
int j;
unsigned int reg_crc=0xffff;
while(length--)
{
reg_crc^=*dat++;
for(j=0;j<8;j++)
{
if(reg_crc&0x01)
{
reg_crc=(reg_crc>>1)^0xa001;
}
else
{
reg_crc=reg_crc>>1;
}
}
}
return reg_crc;
}
/************************************************寫變頻器函數**************************************/
void write_uart_buffer(unsigned char add,unsigned char cmd,unsigned int dat_add,unsigned int dat_data)
//add表示從機地址,cmd表示命令,dat_add表示數據地址,dat_data表示數據內容
{
bpq[0]=add;
bpq[1]=cmd;
bpq[2]=(unsigned char)(dat_add>>8);
bpq[3]=(unsigned char)dat_add;
bpq[4]=(unsigned char)(dat_data>>8);
bpq[5]=(unsigned char)dat_data;
// 插入CRC算法的兩個字節
bpq[6]= (unsigned char)(crc_check(bpq,6));
bpq[7]= (unsigned char)(crc_check(bpq,6)>>8);
send_string_com(bpq,bp);
}
/**************變頻器啟動函數****************/
void bpq_start()
{
write_uart_buffer(0x01,0x06,0x2000,0x0012);
}
/**************變頻器停止函數**********/
void bpq_stop()
{
write_uart_buffer(0x01,0x06,0x2000,0x0011);
}
/*******************變頻器換向函數****************/
void bpq_rev()
{
write_uart_buffer(0x01,0x06,2000,0x0032);
}
/*****************主函數******************/
void main(void)
{
temp1=0x00;
InitUART(); //串行口初始化
while(1)
{
if(flag1==1)
{
unsigned char m;
m=temp1;
flag1=0;
temp1=0x00;
switch(m)
{
case 0x01: bpq_start();break;
case 0x02: bpq_stop();break;
case 0x03: bpq_rev();break;
default:break;
}
}
}
}
/************串行口1中斷處理函數*************/
void UART_1Interrupt(void) interrupt 4
{
if(RI==1)
{
RI=0;
flag1=1;
temp1=SBUF;
}
}