本例程可与昆仑通态触摸屏互通数据Modbus_KLTT
void main (){ int temp;
float temperature;
unsigned char displaytemp[16];//¶¨ÒåÏÔʾÇøÓòÁÙʱ´æ´¢Êý×é
LCD_Init(); // ³õʼ»¯Òº¾§
LCD_Clear();
EA = 1; // ¿ª×ÜÖжÏ
ConfigTimer0(1); // Åä Öà T0 ¶¨ ʱ
ConfigUART(9600); //ÅäÖò¨ÌØÂÊΪ9600
while(1)
{ temp=ReadTemperature();
temperature=(float)temp*0.0625;
sprintf(displaytemp,"Temp % 7.3f",temperature);//´òӡζÈÖµ
LCD_Write_String(0,1,displaytemp);//ÏÔʾµÚ¶þÐÐ
UartDriver();
}
}
void InterruptUART() interrupt 4 //UART ÖжϷþÎñº¯Êý
{
if (RI) // ½ÓÊÕµ½×Ö½Ú
{
RI = 0; // ÊÖ¶¯ÇåÁã½ÓÊÕÖжϱê־λ
if (cntRxd < sizeof(bufRxd)) // ½ÓÊÕ»º³åÇøÉÐδÓÃÍêʱ£¬
{
bufRxd[cntRxd ] = SBUF; // ±£´æ½ÓÊÕ×Ö½Ú£¬²¢µÝÔö¼ÆÊýÆ÷
}
}
if (TI) // ×Ö½Ú·¢ËÍÍê±Ï
{
TI = 0; // ÊÖ¶¯ÇåÁã·¢ËÍÖжϱê־λ
flagOnceTxd = 1; //ÉèÖõ¥´Î·¢ËÍÍê³É±êÖ¾
}
}
void UartDriver() // ´®¿ÚÇý¶¯º¯Êý£¬¼ì²â½ÓÊÕµ½µÄÃüÁî²¢Ö´ÐÐÏàÓ¦¶¯×÷
{
unsigned char i;
unsigned char cnt;
unsigned char len;
unsigned char buf[30];
unsigned int crc;
unsigned char crch, crcl;
if (cmdArrived) // ÓÐÃüÁîµ½´ïʱ£¬¶ÁÈ¡´¦Àí¸ÃÃüÁî
{
cmdArrived = 0;
len = UartRead(buf, sizeof(buf)); //½«½ÓÊÕµ½µÄÃüÁî¶ÁÈ¡µ½»º³åÇøÖÐ
if (buf[0] == 0x01) //ºË¶ÔµØÖ·ÒÔ¾ö¶¨ÊÇ·ñÏìÓ¦ÃüÁ±¾Àý±¾»úµØַΪ0x01
{
crc = GetCRC16(buf, len-2); //¼ÆËã CRCУÑéÖµ
crch = crc >> 8;
crcl = crc & 0xFF;
if ((buf[len-2] == crch) && (buf[len-1] == crcl)) // ÅÐ¶Ï CRCУÑéÊÇ·ñÕýÈ·
{
switch (buf[1]) // °´¹¦ÄÜÂëÖ´ÐвÙ×÷
{
case 0x03: // ¶ÁÈ¡Ò»¸ö»òÁ¬ÐøµÄ¼Ä´æÆ÷
if ((buf[2] == 0x00) && (buf[3] <= 0x05)) // ¼Ä´æÆ÷µØÖ·Ö§³Ö 0x0000 ¡«0x0005
{
if (buf[3] <= 0x04)
{
i = buf[3]; // ÌáÈ¡¼Ä´æÆ÷µØÖ·
cnt = buf[5]; //ÌáÈ¡´ý¶ÁÈ¡µÄ¼Ä´æÆ÷ÊýÁ¿
buf[2] = cnt*2; // ¶ÁÈ¡Êý¾ÝµÄ×Ö½ÚÊý£¬Îª¼Ä´æÆ÷Êý*2 £¬Òò Modbus¶¨ÒåµÄ¼Ä´æÆ÷Ϊ16 λ
len = 3;
while (cnt--)
{
buf[len ] = 0x00; // ¼Ä´æÆ÷¸ß×Ö½Ú²¹ 0
buf[len ] = regGroup[i ]; // µÍ×Ö½Ú
}
}
else
{
buf[2] = 2; // ¶ÁÈ¡Êý¾ÝµÄ×Ö½ÚÊý
buf[3] = 0x00;
buf[4] = 0x00;
len = 5;
}
break;
}
else // ¼Ä´æÆ÷µØÖ·²»±»Ö§³Öʱ£¬·µ»Ø´íÎóÂë
{
buf[1] = 0x83; // ¹¦ÄÜÂë×î¸ßλÖÃ1
buf[2] = 0x02; // ÉèÖÃÒì³£ÂëΪ02- ÎÞЧµØÖ·
len = 3;
break;
}
case 0x06: // дÈëµ¥¸ö¼Ä´æÆ÷
if ((buf[2] == 0x00) && (buf[3] <= 0x05))
{
if (buf[3] <= 0x04)
{
i = buf[3]; // ÌáÈ¡¼Ä´æÆ÷µØÖ·
regGroup[i] = buf[5]; // ±£´æ¼Ä´æÆ÷Êý¾Ý
}
else
{
}
len -= 2; // ³¤¶È -2 ÒÔÖØмÆËãCRC²¢·µ»ØÔÖ¡break;
}
else // ¼Ä´æÆ÷µØÖ·²»±»Ö§³Öʱ£¬·µ»Ø´íÎóÂë
{
buf[1] = 0x86; // ¹¦ÄÜÂë×î¸ßλÖà 1
buf[2] = 0x02; // ÉèÖÃÒì³£ÂëΪ 02- ÎÞЧµØÖ·
len = 3;
break;
}
default: // ÆäËü²»Ö§³ÖµÄ¹¦ÄÜÂë
buf[1] |= 0x80; // ¹¦ÄÜÂë×î¸ßλÖÃ1
buf[2] = 0x01; // ÉèÖÃÒì³£ÂëΪ 01- ÎÞЧ¹¦ÄÜ
len = 3;
break;
}
crc = GetCRC16(buf, len); //¼ÆËã CRCУÑéÖµ
buf[len ] = crc >> 8; //CRC ¸ß×Ö½Ú
buf[len ] = crc & 0xFF; //CRC µÍ× Ö½Ú
UartWrite(buf, len); // ·¢ËÍÏìÓ¦Ö¡
}
}
}
}
评论