最近做的一個項目,其中需要對西門子PLC中定時器的間隔時間進行設定,資料格式為S5Time。
S5Time資料長度為兩個位元組,轉成16進位數後,第一位表示時間基準,第二至四位是用BCD碼錶示的時間值。時間基準的二進位代碼如下:
10ms 00
100ms 01
1s 10
10s 11
舉個例子,時間間隔值為5s時,轉成16進位的S5Time數就是0x0500,也可以是0x2005等,在PLC中CPU會自動選擇較小的時間基準來對數值進行表示,所以從PLC中讀到的以上數值應該是0x0500。通過OPC讀取到的為十進位表示的整數值,因此用C#讀取和設定的時候都必須先進行轉換。
知道原理,轉換就很容易了,代碼如下:
S5Time格式轉換
private int ConvertS5TimeToInt32(int init)
{
int qianwei, baiwei, shiwei, gewei;
int beishu = 0;
int result = 0;
qianwei = init / 4096;
init = init % 4096;
baiwei = init / 256;
init = init % 256;
shiwei = init / 16;
gewei = init % 16;
switch (qianwei)
{
case 0:
beishu = 10;
break;
case 1:
beishu = 100;
break;
case 2:
beishu = 1000;
break;
case 3:
beishu = 10000;
break;
}
result = (baiwei * 100 + shiwei * 10 + gewei) * beishu;
return result;
}
private int ConvertInt32ToS5Time(int init)
{
int qianwei, baiwei, shiwei, gewei;
int result = 0;
if (0 <= init && init <= 4095)
{
init = init / 10;
qianwei = 0;
baiwei = init / 100;
init = init % 100;
shiwei = init / 10;
gewei = init % 10;
result = qianwei * 4096 + baiwei * 256 + shiwei * 16 + gewei;
}
else if (0 <= init / 10 && init / 10 <= 4095)
{
init = init / 100;
qianwei = 1;
baiwei = init / 100;
init = init % 100;
shiwei = init / 10;
gewei = init % 10;
result = qianwei * 4096 + baiwei * 256 + shiwei * 16 + gewei;
}
else if (0 <= init / 100 && init / 100 <= 4095)
{
init = init / 1000;
qianwei = 2;
baiwei = init / 100;
init = init % 100;
shiwei = init / 10;
gewei = init % 10;
result = qianwei * 4096 + baiwei * 256 + shiwei * 16 + gewei;
}
else if (0 <= init / 1000 && init / 1000 <= 4095)
{
init = init / 10000;
qianwei = 3;
baiwei = init / 100;
init = init % 100;
shiwei = init / 10;
gewei = init % 10;
result = qianwei * 4096 + baiwei * 256 + shiwei * 16 + gewei;
}
return result;
}