我試圖用C++/CLI應用程序向西門子PLC寫入內容。Snap7寫入S7-1200 PLC
閱讀是可以的(除了第一次讀取它給出奇數值)。
但寫作正在做一些完全不同於我想要的東西。
下面你可以找到代碼:
private: void WriteSiemensDB()
{
byte* buffer;
if (ConnectToSiemensPLC()) //Check if you are connected to PLC
{
String^ msg;
int DBNumber = 2;
bool NDR;
//Getting the values 1 time so buffer has a value
buffer = sPLC->ReadDB(DBNumber);
//give variables a value to write it to the PLC
NDR = true;
sPLC->SetBitAt(buffer, 0, 0, NDR); //Convert a bool to a bit
msg = sPLC->WriteDB(DBNumber, buffer); //write to the Datablock in Siemens
MessageBox::Show(msg); //Show if it worked or not
}
}
的sPLC-> SetBitAt方法:
void SiemensPLC::SetBitAt(byte buffer[], int Pos, int Bit, bool Value)
{
byte Mask[] = { 0x01, 0x02, 0x04, 0x08, 0x10, 0x20, 0x40, 0x80 };
if (Bit < 0) Bit = 0;
if (Bit > 7) Bit = 7;
if (Value)
{
buffer[Pos] = (byte)(buffer[Pos] | Mask[Bit]);
}
else
{
buffer[Pos] = (byte)(buffer[Pos] & ~Mask[Bit]);
}
}
WriteDB方法:
System::String^ SiemensPLC::WriteDB(int DBnumber, byte buffer[])
{
int Result;
String^ msg;
Result = MyClient->DBWrite(DBnumber, 0, 80, buffer);
if (Result == 0)
{
msg = "Gelukt!"; //success
}
else
{
msg = "Mislukt, error:" + Result; //failed
}
return msg;
}
其實我得到的消息 「Gelukt」 ,但它仍然寫入rwong值。所以填寫我的buffer
時出了點問題。我在緩衝區中做錯了什麼?
在C#我有同樣的應用程序,除了緩衝器是byte buffer[];
我的問題是:
- 請告訴我在C
byte* buffer;
++和C#中的byte buffer[];
之間的區別? - 當我在調試時將鼠標懸停在緩衝區上時,它說
buffer* = 0 ''
。這是否意味着它是空的?如果是這樣,爲什麼它仍然發送隨機數到我的PLC?
燁我發現我有我的緩衝更改爲陣,我已經做到這一點,它現在解決了。謝謝(你的)信息! :) – Bart