www.pudn.com > VC.zip > MBMaster.cpp, change:2013-05-22,size:2035b


// MBMaster.cpp: implementation of the CMBMaster class. 
// 
////////////////////////////////////////////////////////////////////// 
 
#include "stdafx.h" 
#include "MBMaster.h" 
#include "MbCommon.h" 
 
////////////////////////////////////////////////////////////////////// 
// Construction/Destruction 
////////////////////////////////////////////////////////////////////// 
 
CMBMaster::CMBMaster() 
{ 
 
} 
 
CMBMaster::~CMBMaster() 
{ 
 
} 
 
s16 CMBMaster::MBMasterSnd(u8 protocolsMode,u8 Addr,u8 RegCode,u16 RegStart,u16 RegNum,void *src,s16 srclen,u8 *dst) 
{ 
	u8  *srcu8 = (u8 *)src; 
	u16 *srcu16 = (u16 *)src; 
	u8 tempu8; 
	u16 tempu16; 
	 
	int len;  
 
	u8 tmp[300]; 
	s16 tmpindex=0;		 
	//地址 
    tmp[tmpindex++] = Addr; 
    //指令码 
    tmp[tmpindex++] = RegCode; 
	switch ( RegCode ) 
    { 
	case 1: //1:读线圈寄存器 
		//寄存器起始地址 
		tmpindex += methord::u16tou8(tmp + tmpindex, RegStart); 
		//寄存器起始地址 
		tmpindex += methord::u16tou8(tmp + tmpindex, RegNum); 
		break; 
	case 2: //2:读光耦状态 
		//寄存器起始地址 
		tmpindex += methord::u16tou8(tmp + tmpindex, RegStart); 
		//寄存器起始地址 
		tmpindex += methord::u16tou8(tmp + tmpindex, RegNum); 
		break; 
	case 5: //写单个线圈 
		//寄存器起始地址 
		tmpindex += methord::u16tou8(tmp + tmpindex, RegStart); 
		//读取线圈状态 
		tempu8 = srcu8[0]; 
		if( tempu8 & 0x01 ) tempu16 = 0xff00; 
		else tempu16 = 0x0000; 
		tmpindex += methord::u16tou8(tmp + tmpindex, tempu16); 
		break;	 
	case 15: //写多个线圈寄存器 
		//寄存器起始地址 
		tmpindex += methord::u16tou8(tmp + tmpindex, RegStart); 
		//寄存器起始地址 
		tmpindex += methord::u16tou8(tmp + tmpindex, RegNum);	 
		 
		len = (RegNum % 8) ? (RegNum / 8 + 1) : (RegNum / 8); 
		tmp[tmpindex++] = len; 
		if(len<=srclen) 
		{ 
			for(int i=0;i<len;i++) 
				tmp[tmpindex++] = srcu8[i]; 
		} 
		else 
			return -2; 
		break;			 
	default: 
		break; 
    } 
 
    if( tmpindex < 3 ) 
    { 
        return ( -2 ); 
    } 
	return CMbCommon::eMBinfoSnd(tmp,tmpindex,dst,protocolsMode); 
}