樹莓派 .net core3.1 讀取S7 200 Smart 資料測試

2020-11-13 12:00:16

目標

    使用.net core3.1 通過樹莓派閘道器(armv7且具備乙太網通訊,zero不行,處理器是armv6的)讀取西門子PLC的資料。

測試工具

  1. 樹莓派,具備乙太網口;
  2. 西門子PLC,我用的是S7 200 Smart;
  3. 4口交換機,一個給plc,一個給樹莓派,一個給上位機;
  4. .net core 3.1,PC上安裝的是vs2019帶的,樹莓派上安裝需要先下載 32位元 sdk和runtime
  5. Sharp7 程式碼,檔案在doc/sharp7-refman.pdf,裡面描述了各類西門子plc的連線引數;
  6. Putty用於遠端登陸樹莓派;
  7. FillZilla用於向樹莓派傳檔案。

安裝.net core

mkdir dotnet
tar zxf aspnetcore-runtime-3.1.9-linux-arm.tar.gz -C $HOME/dotnet
tar zxf dotnet-sdk-3.1.403-linux-arm.tar.gz -C $HOME/dotnet
修改環境變數
nano ~/.bashrc 
export DOTNET_ROOT=$HOME/dotnet
export PATH=$PATH:$HOME/dotnet
ctrl+o儲存,回車,ctrl+x
source ~/.bashrc
驗證安裝有效
dotnet --info

設定網路

    設定樹莓派、plc、pc有線網路在一個網段。

其中,plc ip設定:

樹莓派ip設定:

ifconfig

sudo nano /etc/network/interfaces

auto lo
iface lo inet loopback
auto eth0
iface eth0 inet static
address 192.168.2.101
netmask 255.255.255.0
gateway 192.168.2.254

pc ip設定:

設定完成後在樹莓派上測試ping plc ip看是否通過。

PC上編寫程式

    在vs2019中,建立一個.net core3.1 console application,將 Sharp7庫中的Sharp7.cs 檔案複製進來,然後在program.cs中加入測試程式碼。

static void Main(string[] args)
{
	Sharp7.S7Client client = new Sharp7.S7Client();
	client.SetConnectionType(3);//用basic模式連線,2 OP應該也可以,詳細請參考sharp7-refman.pdf
	var error = client.ConnectTo("192.168.2.1", 0, 0);//
	if(error == 0)
		Console.WriteLine("連線成功");
	else
		Console.WriteLine("連線失敗: "+ error);
	byte[] buffer = new byte[1024];
	int start = 500;
	int byteread = 0;
	error = client.ReadArea(Sharp7.S7Area.DB, 1, start, 15, Sharp7.S7WordLength.DWord, buffer, ref byteread);//S7 200 Smart 的 V 地址空間對應於 DB 1,參見Sharp7-refman.pdf Page 9
	if (error == 0)
	{
		for(int i = 0; i < 16; i++)
		{
			var f = Sharp7.S7Helper.GetRealAt(buffer, 4 * i);
			Console.WriteLine(f.ToString());
			//Console.Write(buffer[i].ToString("X2"));
			//if ((i+1) % 4 == 0) { Console.WriteLine(); }
		}
	}
	else
		Console.WriteLine("連線失敗: " + error);
	error = client.Disconnect();
	if (error == 0)
		Console.WriteLine("連線已斷開");
	else
		Console.WriteLine("斷開連線失敗: " + error);
}

在樹莓派上執行程式

    用FillZilla將console application 工程 debug/netcoreapp3.1 資料夾 中的 ***.dll 檔案 和 ***.runtimeconfig.json 複製到樹莓派上。

    Putty到樹莓派上,cd 到 ***.dll檔案所在目錄,執行:dotnet ***.dll,然後就大功告成了!