當前位置:編程學習大全網 - 編程語言 - 如何編程讀取智能電表的數據?

如何編程讀取智能電表的數據?

方 法:

/// <summary>

/// 只能通過CreateInstance方法來創建類的實例。單例模式

/// </summary>

public static ElectricityMeter CreateInstance()

{

return _instance;

}

/// <summary>

/// 打開設備

/// </summary>

/// <param name="portName">串口號</param>

/// <param name="frm">調用這個類的窗體。</param>

public void Open( string portName, Form frm )

{

try

{

// 初始化窗體對象

_frm = frm;

_frm.FormClosing += new FormClosingEventHandler( _frm_FormClosing );

//初始化SerialPort對象

_serialPort.PortName = portName;

_serialPort.BaudRate = 2400; // 請將設備的波特率設置為此。

_serialPort.DataBits = 8;

_serialPort.StopBits = StopBits.One;

_serialPort.Parity = Parity.Even;

_serialPort.Open();

}

catch( Exception e )

{

MessageBox.Show( e.Message );

}

}

/// <summary>

/// 關閉設備。

/// </summary>

public void Close()

{

if( _serialPort.IsOpen == true )

{

_serialPort.Close();

_serialPort.Dispose();

}

}

/// <summary>

/// 獲取耗電量

/// </summary>

public Decimal GetPowerConsumption()

{

if( _serialPort.IsOpen == true )

{

// 十六進制的命令字符串

string strCmd = "68 AA AA AA AA AA AA 68 11 04 33 33 33 33 AD 16";

// 轉換為十六進制的字節數組

string[] strs = strCmd.Split( new char[] { ' ' } ); // 空格分組

byte[] cmdBytes = new byte[ strs.Length ];

// 轉換為十進制的字節數組

for( int i = 0; i < cmdBytes.Length; i++ ) {

cmdBytes[ i ] = Convert.ToByte( strs[ i ], 16 ); // 16進制轉換為10進制

}

_serialPort.Write( cmdBytes, 0, cmdBytes.Length );

System.Threading.Thread.Sleep( 500 ); // 500ms內應當有響應

byte[] resultBytes = new byte[ 21 ]; // 容量為21的字節數組

_serialPort.Read( resultBytes, 0, resultBytes.Length );

string n1 = Convert.ToString( resultBytes[ 18 ] - 51, 16 ); // 將十進制轉成16進制的字符串

string n2 = Convert.ToString( resultBytes[ 17 ] - 51, 16 ); // 將十進制轉成16進制的字符串

string n3 = Convert.ToString( resultBytes[ 16 ] - 51, 16 ); // 將十進制轉成16進制的字符串

string n4 = Convert.ToString( resultBytes[ 15 ] - 51, 16 ); // 將十進制轉成16進制的字符串

string resultString = n1 + n2 + n3 + "." + n4;

return Decimal.Parse( resultString );

}

else

{

throw new Exception( "串口沒有打開" );

}

}

/// <summary>

/// 在窗體關閉的時候關閉串口連接。

/// </summary>

/// <param name="sender"></param>

/// <param name="e"></param>

void _frm_FormClosing( object sender, FormClosingEventArgs e )

{

this.Close();

}

}

  • 上一篇:鐘擺的工作原理
  • 下一篇:C語言編寫程序
  • copyright 2024編程學習大全網