16,721
社区成员
发帖
与我相关
我的任务
分享

有个C#的
public void PortReciveDataStart()
{
_SerPort.DiscardInBuffer();
_SerPort.DiscardOutBuffer();
_SerPort.DataReceived += SerialPort_DataReceived;
IsRecive = true;
iReciveCount = 0;
}
private void SerialPort_DataReceived(System.Object sender, System.IO.Ports.SerialDataReceivedEventArgs e)
{
if (_SerPort.IsOpen == false)
{
return;
}
try
{
string message = _SerPort.ReadExisting();
SaveData(message);
}
catch (TimeoutException) { }
}
private void SaveData(string data)
{
if (((data == null) == false) && (!string.IsNullOrEmpty(data)))
{
switch (typeTool)
{
case enmType.MT10:
StrRecData strctData = default(StrRecData);
strctData.strName = data.Substring(8, 8);
strctData.strData = data.Substring(16, 8);
strctData.strUnit = data.Substring(24, 8);
MeasedData = Convert.ToSingle(strctData.strData.Replace(" ", "")) ;
iReciveCount += 1;
break;
case enmType.LoadCell:
string tmpStr = data;
Int32 idx = tmpStr.IndexOf("WT");
if ((idx != -1))
{
Int32 idxEnd = tmpStr.IndexOf("\r", idx);
if ((idxEnd != -1))
{
tmpStr = tmpStr.Substring(idx + 3, idxEnd - (idx + 3));
Single tmpDbl = Convert.ToSingle(tmpStr);
MeasedData = tmpDbl;
}
else
{
//RcvTextBox.Text = ("Error")
}
}
else
{
//RcvTextBox.Text = ("Error")
}
break;
}
}
}
Public Function SendCMDtoDriver(ByVal strCMDSend As String)
If frmMain.SerialPortforLampDriver.IsOpen Then
frmMain.SerialPortforLampDriver.Close()
End If
frmMain.SerialPortforLampDriver.Open()
Dim bytHex() As Byte
Dim indata As String
Dim bytesRead As Int16 = 0
ReDim bytHex((Len(strCMDSend) \ 2) - 1)
Dim i As Integer
indata = ""
For i = 1 To Len(strCMDSend) Step 2
bytHex((i - 1) / 2) = Val("&H" & Mid(strCMDSend, i, 2))
Next
'MessageBox.Show(frmMain.SerialPortforLampDriver.IsOpen)
frmMain.SerialPortforLampDriver.Write(bytHex, 0, bytHex.Length)
'frmMain.SerialPortforLampDriver.DiscardOutBuffer()
Sleep(50)
Dim byteToRead As Int16 = frmMain.SerialPortforLampDriver.BytesToRead
Dim ch(byteToRead) As Byte
bytesRead = frmMain.SerialPortforLampDriver.Read(ch, 0, byteToRead)
If bytesRead > 0 Then
For ii As Int16 = 0 To bytesRead - 1
indata = indata & DecToHex(ch(ii))
Next
Return indata
Else
End If
frmMain.SerialPortforLampDriver.Close()
End Function
发送SCPI指令的。。。
Public Function SendCMDtoChroma62012P(ByVal strCMDSend As String) As String
If frmMain.SerialPortforChroma62012P.IsOpen Then
frmMain.SerialPortforChroma62012P.Close()
End If
frmMain.SerialPortforChroma62012P.Open()
Try
frmMain.SerialPortforChroma62012P.DiscardOutBuffer()
frmMain.SerialPortforChroma62012P.Write(strCMDSend & Chr(13) & Chr(10))
Sleep(300)
Return frmMain.SerialPortforChroma62012P.ReadExisting()
frmMain.SerialPortforChroma62012P.Close()
Catch ex As Exception
MessageBox.Show(ex.Message & RS232Error, ErrorOccurs, MessageBoxButtons.OK, MessageBoxIcon.Error)
frmMain.SerialPortforChroma62012P.Close()
Return 0
End Try
frmMain.SerialPortforChroma62012P.Close()
End Function
为毛不用SerialPort