我有一台通过RS-232进行通信的Keyence相机。它被配置为在触发时输出三个整数值。我在读取整数值时遇到问题。我尝试使用char数组缓冲区,但它只读取输出中的第一个+符号。我用putty测试它,输出就像这样
+ 346.0,+ 261.0,098
我想知道是否有什么需要用来读取像这样的整数值?
static void Main(string[] args)
{
char[] buffer1 = new char[200] ;
SerialPort port = new SerialPort("COM4", 9600, Parity.None, 8, StopBits.One);
port.Open();
if (port.IsOpen) { Console.WriteLine("port is now open"); } else { Console.WriteLine("port not opened correctly"); }
port.Write("T"); //triggers the camera
port.Read(buffer1, 0, 200);
for (int i = 0; i < 200; i++)
{
Console.WriteLine(buffer1[i]);
}
Console.ReadLine();
}
答案 0 :(得分:0)
我之前遇到过从串口读取而没有阅读所有预期内容的问题。
原来我正在读取设备的响应,但尚未写完。我认为串口对象会继续尝试填充缓冲区,直到达到读取超时,这不是发生的事情。
在我的场景中,我知道我将从串口读取多少个字符。因此,如果您知道可以在读取时实现重复,直到字符缓冲区已满。如果您从SerialPort.BaseStream中读取,我不知道是否同样适用。
SerialPort serialPort;
char[] buffer = new char[expectedLength];
int totalBytesRead = 0;
//continue to read until all of the expected characters have been read
while (totalBytesRead < expectedLength)
{
totalBytesRead += serialPort.Read(buffer, totalBytesRead, expectedLength - totalBytesRead);
}
答案 1 :(得分:0)
这是我使用的代码(简化):
public class Scanner : SerialPort
{
private string _word;
private int _globalCounter;
private readonly char[] _rxArray = new char[2047];
public Scanner()
{
DataReceived += MyDataReceivedEventHandler;
}
public event EventHandler<CodeScannedEventArgs> CodeScanned;
private void MyDataReceivedEventHandler(object sender, SerialDataReceivedEventArgs e)
{
do
{
var rxByte = (byte)ReadByte();
// end of word
if (rxByte == 10)
{
// first byte (02) and last two bytes (13 and 10) are ignored
_word = new string(_rxArray, 1, _globalCounter - 2);
DisplayData(_word);
_globalCounter = 0;
}
else
{
_rxArray[_globalCounter] = (char)rxByte;
_globalCounter++;
}
} while (BytesToRead > 0);
}
private void DisplayData(string receivedText)
{
OnCodeScanned(new CodeScannedEventArgs(receivedText));
}
protected void OnCodeScanned(CodeScannedEventArgs e)
{
EventHandler<CodeScannedEventArgs> handler = CodeScanned;
if (handler != null)
{
handler(this, e);
}
}
}
我使用的扫描程序将字节02添加为前缀,将字节13和10作为后缀添加到它扫描的所有内容中,因此我很容易将其分解为单词。您显然需要稍微更改实现,以便它适合您。
编辑 - CodeScannedEventArgs类:
public class CodeScannedEventArgs : EventArgs
{
public CodeScannedEventArgs(string scannedCode)
{
ScannedCode = scannedCode;
}
public string ScannedCode { get; set; }
}
答案 2 :(得分:0)
我使用了port.ReadTo(“\ r \ n”)并且它有效,因为输出以回车结束。
但我想知道使用数据接收事件有什么好处?