創作內容

12 GP

C# Modbus ASCII LRC 計算器

作者:貓貓風 ฅ●ω●ฅ│2019-01-15 10:25:40│巴幣:24│人氣:3297
.

















在ASCII(AmericanStandard Code for Information Interchange)傳輸模式下,封包以英文冒號(:,ASCII3A Hex)開始,以回車和換行(CRLF,ASCII 0D and 0A Hex)符號結束,允許的傳輸的字元集為十六進位的0~9和A~F;網路中的從設備監視傳輸通路上是否有英文冒號(:),如果有的話,就對封包進行解碼,查看封包中的ID是否與自己的ID相同,如果相同的話,就接收其中的資料;如果不同的話,則不予理會。
 
在ASCII模式下,每個8位元的位元組被拆分成兩個ASCII字元進行發送,例如十六進位數0xCA ,會被分解成ASCII字元C和A進行發送,發送的字元量比RTU增加一倍。ASCII模式的好處是允許兩個字元之間間隔的時間長達1s而不引發通信故障,該模式採用縱向冗餘校驗(LongitudinalRedundancy Check ,LRC) 的方法來檢驗錯誤

如果使用的是 ModBUS RTU
CRC的計算可以參考這篇  C# Modbus RTU CRC 計算器

Modbus ASCII 傳輸格式
Header
  
ID
  
function
  
Data
  
LRC
  
Delimiter
  
1byte
  
2bytes
  
2bytes
  
2N  bytes
  
2bytes
  
2bytes
  

本篇主要說明  Modbus ASCII  中 LRC的計算方式

LRC 錯誤檢查碼生成步驟如下

1. 將所有資料(不包含Header 和 Delimiter )轉成 16進位格式(Hex Code)
2.   將步驟一所產生的資料全部相加
3.   相加結果進行2補數運算 (將位元全部相反後 + 1)
4.   存入長度8 bit的變數中
5.   將16進位格式轉成 ASCII   CODE (2bytes)  即為 LRC

最後附上實作程式碼


  1. using System;  
  2. using System.Collections.Generic;  
  3. using System.ComponentModel;  
  4. using System.Data;  
  5. using System.Drawing;  
  6. using System.Linq;  
  7. using System.Text;  
  8. using System.Windows.Forms;  
  9.   
  10. namespace Modbus_ASCII_LRF_calculator  
  11. {  
  12.     public partial class Form1 : Form  
  13.     {  
  14.         byte[] send_command;  
  15.         int command_lenth; // 不包含 header delimiter  
  16.   
  17.         public Form1()  
  18.         {  
  19.             InitializeComponent();  
  20.         }  
  21.   
  22.         private byte HexToByte(string hex)  
  23.         {  
  24.             if (hex.Length > 2 || hex.Length <= 0)  
  25.                 throw new ArgumentException("hex must be 1 or 2 characters in length");  
  26.             byte newByte = byte.Parse(hex,
  27.            System.Globalization.NumberStyles.HexNumber);  
  28.             return newByte;  
  29.         }  
  30.   
  31.         // byte array to ASCII & combine Hex string  
  32.         //EX  0x32 0x46 -> 2F  
  33.         public static string ConvertHex(String hexString)  
  34.         {  
  35.             try  
  36.             {  
  37.                 string ascii = string.Empty;  
  38.   
  39.                 for (int i = 0; i < hexString.Length; i += 2)  
  40.                 {  
  41.                     String hs = string.Empty;  
  42.                     hs = hexString.Substring(i, 2);  
  43.                     uint decval = System.Convert.ToUInt32(hs, 16);  
  44.                     char character = System.Convert.ToChar(decval);  
  45.                     ascii += character;  
  46.                 }  
  47.   
  48.                 return ascii;  
  49.             }  
  50.             catch (Exception ex) { MessageBox.Show(ex.Message); }  
  51.   
  52.             return string.Empty;  
  53.         }  
  54.   
  55.         private void aquaButton1_Click(object sender, EventArgs e)  
  56.         {  
  57.             String[] sp_str = textBox1.Text.Split(new char[] { ',' });  
  58.             command_lenth = sp_str.Length;  
  59.             send_command = new byte[command_lenth];  
  60.   
  61.             for (int i = 0; i < send_command.Length; i++)  
  62.             {  
  63.                 //textBox1.Text += "0x" +send_command[i].ToString("X")+ " ";  
  64.                 send_command[i] = HexToByte(sp_str[i]);  
  65.             }  
  66.   
  67.             //convert all data to Hex         
  68.             string hex = BitConverter.ToString(send_command).Replace("-",
  69.             string.Empty);   
  70.             String result = ConvertHex(hex);  
  71.             int sum = 0;  
  72.             int index = 0;  
  73.             string temp_str = string.Empty;  
  74.   
  75.             for (int i = 0; i < command_lenth / 2; i++)  
  76.             {  
  77.                 temp_str += result[index];  
  78.                 temp_str += result[++index];  
  79.                 int value = Convert.ToInt32(temp_str, 16); // 16進位加法  
  80.                 sum += value;  
  81.                 ++index;  
  82.                 temp_str = string.Empty;  
  83.             }  
  84.   
  85.             // 2's complement  
  86.             sum = ~sum;   
  87.             sum = sum + 1;  
  88.             // convert to uint8   將轉換結果存入8bit變數中  
  89.             sbyte LRC_origin = (sbyte)sum;
  90.             string hexValue = LRC_origin.ToString("X");  
  91.   
  92.             byte[] LRCArray = null;  
  93.             String LRC = string.Empty;  
  94.             System.Text.StringBuilder hexNumbers = new System.Text.StringBuilder();  
  95.             //Convert to ASCII   LRF store in byteArray              
  96.             LRCArray = System.Text.ASCIIEncoding.ASCII.GetBytes(hexValue);
  97.             for (int i = 0; i <= LRCArray.Length - 1; i++)  
  98.             {  
  99.                 LRC += "0x" + LRCArray[i].ToString("x") + " ";  
  100.             }  
  101.   
  102.             for (int i = 0; i < LRCArray.Length; i++)  
  103.             {  
  104.                 if (i < LRCArray.Length - 1)  
  105.                 {  
  106.                     textBox2.Text = LRCArray[i].ToString("X");  
  107.                 }  
  108.                 else  
  109.                 {  
  110.                     textBox3.Text = LRCArray[i].ToString("X");  
  111.                 }  
  112.             }  
  113.         }         
  114.     }  
  115. }  

執行結果







輸入其他長度資料測試




引用網址:https://home.gamer.com.tw/TrackBack.php?sn=4261522
All rights reserved. 版權所有,保留一切權利

相關創作

同標籤作品搜尋:涼涼風|C#

留言共 1 篇留言

小刀
讚歐!

01-15 16:42

貓貓風 ฅ●ω●ฅ
謝謝刀姊owo01-15 17:02
我要留言提醒:您尚未登入,請先登入再留言

12喜歡★s1234567 可決定是否刪除您的留言,請勿發表違反站規文字。

前一篇:C# 正規表達式(Reg... 後一篇:C# 自定義Button...

追蹤私訊切換新版閱覽

作品資料夾

Lobster0627全體巴友
大家可以多多來我的YT頻道看看哦(*´∀`)~♥https://www.youtube.com/@lobstersandwich看更多我要大聲說昨天10:27


face基於日前微軟官方表示 Internet Explorer 不再支援新的網路標準,可能無法使用新的應用程式來呈現網站內容,在瀏覽器支援度及網站安全性的雙重考量下,為了讓巴友們有更好的使用體驗,巴哈姆特即將於 2019年9月2日 停止支援 Internet Explorer 瀏覽器的頁面呈現和功能。
屆時建議您使用下述瀏覽器來瀏覽巴哈姆特:
。Google Chrome(推薦)
。Mozilla Firefox
。Microsoft Edge(Windows10以上的作業系統版本才可使用)

face我們了解您不想看到廣告的心情⋯ 若您願意支持巴哈姆特永續經營,請將 gamer.com.tw 加入廣告阻擋工具的白名單中,謝謝 !【教學】