1. 程式人生 > 其它 >Unity連線ModbusTcp傳送讀取暫存器

Unity連線ModbusTcp傳送讀取暫存器

unity連線modbus需要有NModbus4.dll檔案

檔案地址: (暫時還沒上傳完畢,上傳完畢之後連結上,)

1.配置一個modbus主站,

2.unity用來連線

下面直接上程式碼

using Modbus.Device;
using System;
using System.Collections;
using System.Collections.Generic;
using System.Net;
using System.Net.Sockets;
using System.Text;
using System.Threading;
using UnityEngine;


public class Concent_ : MonoBehaviour { public ModbusMaster modbusIpMaster; public TcpClient tcpClient; IPAddress address = new IPAddress(new byte[] { 127,0,0,1 }); public int port = 502; public bool conen = false; public bool Reda_White = false; private ushort[] udata = new
ushort[]{0x03}; private ushort star=1; Thread mythread; //Thread youthread; public bool isconect = false; // Start is called before the first frame update void Start() { if (Connect (address.ToString (), port)) { Debug.Log("連線成功"); }
else { Debug.Log("連線失敗"); } } public bool Connect(string ip, int port) { try { tcpClient = new TcpClient(ip, port); tcpClient.SendTimeout = 1; modbusIpMaster = ModbusIpMaster.CreateIp(tcpClient); //開啟另一個執行緒(可用可不用) mythread = new Thread(WriteMessageFromClient); //執行緒開啟 mythread.Start(); conen = true; return true; } catch (Exception ex) { tcpClient.Close(); Debug.LogError(ex.Message); return false; } } public void WriteMessageFromClient() { while (conen) { try { if (Reda_White) { Write_jiChunQi(star, udata); Debug.Log("傳送成功"); } if (kuse) { ushort [] msg= modbusIpMaster.ReadHoldingRegisters(0x01,1, 0x01); } } catch { break; } } tcpClient.Close(); } public void Write_jiChunQi(ushort star,ushort[]data) { modbusIpMaster.WriteMultipleRegisters(1,star, data); } /// 10進位制轉16進位制 private byte GetHex(string msg) { byte hex = Convert.ToByte(msg); return hex; } ///16進位制轉10進位制 public int GetDex(string msg) { int res = Convert.ToInt32(msg,16); return res; } //退出的時候關閉連線 private void OnApplicationQuit() { tcpClient.Close(); } public bool kuse = false; private void Update() { if (Input.GetMouseButtonDown(0)) { //WriteMultipleRegisters(裝置地址,暫存器起始地址, 要寫入的值) modbusIpMaster.WriteMultipleRegisters(0x01,star,udata); Debug.Log("傳送成功"); } if (Input.GetKeyDown (KeyCode.Space)) { //ReadHoldingRegisters(裝置地址, 暫存器起始地址, 讀取數量); 讀取多個暫存器 ushort[] msg = modbusIpMaster.ReadHoldingRegisters(0x01, 1, 0x06); foreach (var item in msg) { Debug.Log(item); } } } }
Modbus連線