用到的gomodbus包是壇友slzm40編寫和共享的,感謝他的無(wú)私分享,本帖只是拋磚引玉,將我自己學(xué)習(xí)的一些經(jīng)歷分享給大家;有關(guān)modbus包可以直接向slzm40請(qǐng)教或一起討論;
我們提供的服務(wù)有:成都做網(wǎng)站、成都網(wǎng)站設(shè)計(jì)、成都外貿(mào)網(wǎng)站建設(shè)、微信公眾號(hào)開(kāi)發(fā)、網(wǎng)站優(yōu)化、網(wǎng)站認(rèn)證、晉寧ssl等。為1000+企事業(yè)單位解決了網(wǎng)站和推廣的問(wèn)題。提供周到的售前咨詢和貼心的售后服務(wù),是有科學(xué)管理、有技術(shù)的晉寧網(wǎng)站制作公司
包地址"github.com/thinkgos/gomodbus";
添加一對(duì)虛擬串口
打開(kāi)modbus-slave從機(jī)軟件,用來(lái)測(cè)試從機(jī);
需要注意設(shè)置通信地址和讀取寄存器的地址和數(shù)量;
查看可用串口,因?yàn)樘摂M串口選擇com1和com2,虛擬中我選擇使用/dev/ttyS1
編譯運(yùn)行,會(huì)提示串口打開(kāi)失敗,這是因?yàn)閘inux對(duì)設(shè)備的權(quán)限做了限制
獲取串口讀寫、運(yùn)行等權(quán)限
我們已經(jīng)能正確讀取03寄存器的值;其他功能可以自行測(cè)試;
package main
import (
"fmt"
modbus "github.com/thinkgos/gomodbus"
"github.com/thinkgos/gomodbus/mb"
"time"
)
func main(){
//調(diào)用RTUClientProvider的構(gòu)造函數(shù),返回結(jié)構(gòu)體指針
p := modbus.NewRTUClientProvider()
p.Address = "/dev/ttyS1"
p.BaudRate = 115200
p.DataBits = 8
p.Parity = "N"
p.StopBits = 1
p.Timeout = 100 * time.Millisecond
client := mb.NewClient(p)
client.LogMode(true)
err := client.Start()
if err != nil {
fmt.Println("start err,", err)
return
}
for {
value, err := client.ReadHoldingRegisters(1, 1, 3)
if err != nil {
fmt.Println("readHoldErr,", err)
} else {
fmt.Printf("%#v\n", value)
}
time.Sleep(time.Second * 3)
}
}
//創(chuàng)建一個(gè)串口通訊 SerialPort CurrentPort = null; CurrentPort = new SerialPort(); CurrentPortReadBufferSize = 128; CurrentPortPortName = comName; //端口號(hào) CurrentPortBaudRate = bandRate; //比特率 CurrentPortParity =parity;/go語(yǔ)言做串口通信,我應(yīng)該從什么地方入手,IO是什
//創(chuàng)建一個(gè)串口通訊
SerialPort CurrentPort = null;
CurrentPort = new SerialPort();
CurrentPort.ReadBufferSize = 128;
CurrentPort.PortName = comName; //端口號(hào)
CurrentPort.BaudRate = bandRate; //比特率
CurrentPort.Parity =parity;//奇偶校驗(yàn)
CurrentPort.StopBits = stop;//停止位
CurrentPort.DataBits = databit;//數(shù)據(jù)位
CurrentPort.ReadTimeout = 1000; //讀超時(shí),即在1000內(nèi)未讀到數(shù)據(jù)就引起超時(shí)異常
//綁定數(shù)據(jù)接收事件,因?yàn)榘l(fā)送是被動(dòng)的,所以你無(wú)法主動(dòng)去獲取別人發(fā)送的代碼,只能通過(guò)這個(gè)事件來(lái)處理
CurrentPort.DataReceived += Sp_DataReceived;
CurrentPort.Open();
定義一個(gè)變量 byte[] receiveStr;
//綁定的事件處理函數(shù)
private static void Sp_DataReceived(object sender, System.IO.Ports.SerialDataReceivedEventArgs e)
{
SerialPort sp = sender as SerialPort;
if (sp == null)
return;
byte[] readBuffer = new byte[sp.ReadBufferSize];
sp.Read(readBuffer, 0, readBuffer.Length);
//賦值
receiveStr=readBuffer;//當(dāng)然你可以通過(guò)轉(zhuǎn)換將byte[]轉(zhuǎn)換為字符串。
}
//你要求的按鈕事件可以這么寫
private void button1_Click(object sender, EventArgs e)
{
if(receiveStr!=null)
{
變量 xxx=receiveStr;
}
}