建立数组并写入数据_Visual Studio 2010--C#跟西门子1200通讯(Sharp7)⑥--数据写入
Visual Studio 2010--C#跟西門子1200通訊(Sharp7)⑥--數據寫入
上期回顧(上2期主要編寫了從PLC讀取數據到緩沖區,再從緩沖區拿取需要的數據,并轉換成C#格式):
本期開始寫寫入數據的過程,寫入的過程跟讀取正好相反,先把要寫入的數據都集中到數組,然后在整體寫入到PLC
1.0 先新建一個12個字節的數組用來存放,需要寫入的值
//寫入
var writeBuffer = new byte[12];
2.0 開始寫入S7.SetBitAt(ref writeBuffer,0,0,true);往第一個字節的0位寫1,S7.SetIntAt(writeBuffer,2,20);這一句的意思是往第三個字節2里面寫入20,其他以此類推,注意要與你寫入的PLC數據塊的地址相匹配
//寫入BOOL
S7.SetBitAt(ref writeBuffer,0,0,true);
S7.SetBitAt(ref writeBuffer,0,1,true);
//寫入word
S7.SetIntAt(writeBuffer,2,20);
//寫入real
S7.SetRealAt(writeBuffer, 4, (float)25.33);
//寫入Dint
S7.SetDIntAt(writeBuffer,8,123456);
3.0 寫入需要的數據到數組封裝后,就要開始把封裝后的數組,傳送給PLC的數據庫DB1的從地址0開始的數據,并判斷是否傳送成功
//寫入數據塊DB1,從地址0開始的12個字節,從writeBuffer寫入
int writeReswlt = client.DBWrite(1, 0, writeBuffer.Length, writeBuffer);
if (writeReswlt == 0)//如果寫入完成就OK,否則為error
{
Console.WriteLine("DB1 write ok");
}
else
{
Console.WriteLine("DB1 write error");
return;
}
4.0 保存,仍舊在斷開連接那邊打上斷點,按F5調試,如果代碼沒有錯誤,PLC監控狀態下,你就會看到如下圖的數據
完整程序如下:
static void Main(string[] args)
{
var client = new S7Client();//創建S7客戶端對象
int comectionResult = client.ConnectTo("192.168.0.1",0,1);//接受來次通訊的結果
if (comectionResult == 0)//如果為0就說明通信OK,如果不為0就說明不通
{
Console.WriteLine("comection ok");
}
else
{
Console.WriteLine("conection error");
return;
}
//創建38個字節的數組,用來讀取PLC數據
var buffer = new byte[38];
//讀取DB1的從地址0開始的38個字節的數據,讀到buffer
int readResult = client.DBRead(1,0,buffer.Length,buffer);
if (readResult == 0)//如果等于0說明等于讀取完成,否則讀取不成功
{
Console.WriteLine("DB1 Read ok");
}
else
{
Console.WriteLine("DB1 Read error");
return;
}
//讀取
//第一列是數據類型
bool db1dbx00 = S7.GetBitAt(buffer,0,0);
bool db1dbx01 = S7.GetBitAt(buffer, 0, 1);
//讀取word
int db1dbw2 = S7.GetIntAt(buffer,2);
//讀取real
double db1dbd4 = S7.GetRealAt(buffer, 4);
//讀取Dint
int db1dbd8 = S7.GetDIntAt(buffer, 8);
//讀取16進制數
uint db1dbd12 = S7.GetDWordAt(buffer,12);
ushort db1dbd14 = S7.GetWordAt(buffer,16);
//強制轉換字符串類型,相當于PLC的16進制數,tostring()中要加“x”,不然仍舊是10進制數
string hexdb1dbd12 = db1dbd12.ToString("x");
string hexdb1dbd14 = db1dbd14.ToString("x");
//寫入
var writeBuffer = new byte[12];
//寫入BOOL
S7.SetBitAt(ref writeBuffer,0,0,true);
S7.SetBitAt(ref writeBuffer,0,1,true);
//寫入word
S7.SetIntAt(writeBuffer,2,20);
//寫入real
S7.SetRealAt(writeBuffer, 4, (float)25.33);
//寫入Dint
S7.SetDIntAt(writeBuffer,8,123456);
//寫入數據塊DB1,從地址0開始的12個字節,從writeBuffer寫入
int writeReswlt = client.DBWrite(1, 0, writeBuffer.Length, writeBuffer);
if (writeReswlt == 0)//如果寫入完成就OK,否則為error
{
Console.WriteLine("DB1 write ok");
}
else
{
Console.WriteLine("DB1 write error");
return;
}
client.Disconnect();//斷開
}
總結
以上是生活随笔為你收集整理的建立数组并写入数据_Visual Studio 2010--C#跟西门子1200通讯(Sharp7)⑥--数据写入的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: WPS文字制作公文的文头技巧
- 下一篇: 监听js变量的变化_Node.js从零开