目錄
前言
一、串口、CAN總線
二、使用步驟
1.RS232串口通訊(指令下發與接收)
2.CAN總線通訊
總結
前言
學習及工作中我們經常會遇到上位機與下位機通訊等工作,結合場景使用不同的通訊方式實時通訊,以下為工作中遇到的上位機與下位機進行實時通訊,采用RS232串口和CAN總線形式進行網絡通訊。
一、串口、CAN總線
串行接口簡稱串口,也稱串行通訊接口或串行通訊接口(通常指設備的COM接口),是采用串行通信方式的擴展接口。串行接口 (Serial Interface)是指數據一位一位地順序傳送。其特點是通訊簡單,只要一對傳輸線,通過設備設置傳輸線端口等參數就可以實現雙向通信,從而大大降低了成本,特別適用於遠距離通信,但傳送速度較慢。
CAN是控制器局域網絡(Controller Area Network, CAN)的簡稱,是由以研發和生產汽車電子產品著稱的德國BOSCH公司開發的,並最終成為國際標准(ISO 11898),是國際上應用最廣泛的現場總線之一。 在北美和西歐,CAN總線協議已經成為汽車計算機控制系統和嵌入式工業控制局域網的標准總線,並且擁有以CAN為底層協議專為大型貨車和重工機械車輛設計的J1939協議。上位機與與下位機制定好通用協議通過CAN模塊將數據進行16進制轉換實時通訊。
二、使用步驟
1.RS232串口通訊(指令下發與接收)
代碼如下(示例):
//命名空間引入
using System.IO.Ports;
public SerialPort serialPort;//定義串口對象類public
//定義連接方法
public void Connect()
{
serialPort = new SerialPort();
serialPort.BaudRate = 1200;//波特率
serialPort.PortName = "COM1";
serialPort.Parity = Parity.None;//校驗法:無
serialPort.DataBits = 8;//數據位:8
serialPort.StopBits = StopBits.One;//停止位:1
try
{
serialPort.Open();//打開串口
serialPort.DtrEnable = true;//設置DTR為高電平
serialPort.RtsEnable = true;//設置RTS位高電平
serialPort.DataReceived += new SerialDataReceivedEventHandler(serialPort_DataReceived);//DataReceived事件委托
byte[] WriteBuffer = Encoding.ASCII.GetBytes("下發指令");
//下發
serialPort.Write(WriteBuffer, 0, WriteBuffer.Length);
}
catch (Exception ex)
{
//打開串口出錯,顯示錯誤信息
Console.WriteLine("串口打開失敗");
}
}
2.CAN總線通訊
代碼如下(示例):
//首先與CAN模塊進行連接
public TcpClient mTcp = new TcpClient();
private const int READ_BUFFER_SIZE = 1000;
private byte[] readBuffer = new byte[READ_BUFFER_SIZE + 1];
public delegate void DoReadEventHandle(object sender, string e);
public event DoReadEventHandle ReadedEvent;
public event DoReadEventHandle LogEvent;
public string recStr { get; set; }
public string HandString { get; set; }
public bool Connect()
{
//Can模塊ip
string mIPAddress = "192.168.1.1";
IPAddress hostIPAddress = IPAddress.Parse(mIPAddress);
//端口
int mPort = 8080;
IPEndPoint endIP = new IPEndPoint(hostIPAddress, mPort);
try
{
mTcp = new TcpClient(mIPAddress, mPort);
DateTime Savetime = DateTime.Now;
TimeSpan n = new TimeSpan();
while (true)
{
n = DateTime.Now - Savetime;
if (n.TotalMilliseconds > 1000 || mTcp.Client.Connected) break;
}
if (!mTcp.Client.Connected) return false;
mTcp.GetStream().BeginRead(readBuffer, 0, READ_BUFFER_SIZE, DoRead, null);
}
catch (Exception)
{
return false;
}
return true;
}
private void DoRead(IAsyncResult ar)
{
try
{
int BytesRead = mTcp.GetStream().EndRead(ar);
if (BytesRead > 0)
{
string s = "";
for (int i = 0; i <= BytesRead - 1; i++)
{
s = s + string.Format("{0:x2}", readBuffer[i]) + " ";
}
Console.WriteLine(s);
var t = s.Split(new string[] { "aa 00 ff 00 00 00 00 00 00 00 00 00 55" }, StringSplitOptions.RemoveEmptyEntries).FirstOrDefault(ex => ex != " ");
if (!string.IsNullOrEmpty(t))
{
recStr += t + "\r\n";
if (HandString == recStr && LogEvent != null)
{
HandString = null;
LogEvent(this, "握手成功!");
}
} mTcp.GetStream().BeginRead(readBuffer, 0, READ_BUFFER_SIZE, DoRead, null);
}
}
catch (Exception e)
{
mTcp.Client.Close();
}
}
//數據發送
public void sendCan(string temperature, bool check)
{
HandString = "0xC0 0x02 0x02 0x00 0x00";
string[] tmp = temperature.Split(' ');
var buf = new byte[22];
for (int i = 0; i < buf.Length; i++)
{
buf[i] = 0;
}
for (int i = 0; i < tmp.Length; i++)
{
try
{
buf[i] = Convert.ToByte(tmp[i], 16);
}
catch (Exception e)
{
buf[i] = 0;
}
}
SendData(buf, 0, 13, check);
}
public bool SendData(byte[] sendBytes, int mStart, int mLen, bool check = true)
{
if (!check) return false;
try
{
lock (mTcp.GetStream())
{
mTcp.GetStream().Write(sendBytes, mStart, mLen);
}
return true;
}
catch (Exception x)
{
return false;
}
}
總結
1、RS232串口通訊
接口的信號電平值較高,易損壞接口電路的芯片,傳輸速率較低,傳輸距離有限。
2、CAN模塊通訊
具有實時性強、傳輸距離較遠、抗電磁干擾能力強、成本低等優點;可根據報文的內容決定接收或屏蔽該報文;通訊過程信道容易阻塞。
————————————————
版權聲明:本文為CSDN博主「奔波灞」的原創文章,遵循CC 4.0 BY-SA版權協議,轉載請附上原文出處鏈接及本聲明。
原文鏈接:https://blog.csdn.net/weixin_43292039/article/details/108215111
