參考引用來源:電子天平透過RS232連線讀值
--
1.前言
以程式遠端讀取電子天平秤重數值,可將資料存檔紀錄歷史數據。
2.說明
本範例是針對Precisa Balances進行RS232遠端連線控制儀器,首先要做一條RJ45轉RS232的連接線(儀器端為RJ45接口,電腦端為RS232接口),RJ45端口接線配置與遠端控制的命令可參考原廠的操作說明書,這裡舉PRINT控制命令做說明。
PRT: Start printing(Press "Print" key)
加入命名空間
?
1
using System.IO.Ports;
加入serialPort,設定屬性
BaudRate:9600
DataBits:8
Parity:None
StopBits:One
Form_Load加入資料接收處理事件
private void Form1_Load(object sender, EventArgs e)
{
serialPort1.DataReceived += new SerialDataReceivedEventHandler(port_DataReceived);
}
private void port_DataReceived(object sender, SerialDataReceivedEventArgs e)
{
System.Threading.Thread.Sleep(100);
string message = serialPort1.ReadExisting();
SaveData(message);
}
儲存資料
private void SaveData(string message)
{
string _sign = "";
double _weight = 0;
string _unit = "";
string _datetime = DateTime.Now.ToString("yyyy/MM/dd HH:mm:ss");
_sign = message.Substring(3, 1);
if (_sign == "-") _weight = -double.Parse(message.Substring(4, 9));
if (_sign == "+") _weight = double.Parse(message.Substring(4, 9));
_unit = message.Substring(15, 3);
Console.WriteLine(_weight.ToString());
}
傳送命令
private void SendCommand(string command)
{
serialPort1.Write(command);
}
遠端下控制命令
string cmd = "PRT\r\n";
SendCommand(cmd);
沒有留言:
張貼留言