使用.net core3.1 通過樹莓派閘道器(armv7且具備乙太網通訊,zero不行,處理器是armv6的)讀取西門子PLC的資料。
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看是否通過。
在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,然後就大功告成了!