如何从C#中的serialport获取数字数据 [英] how to get numeric data from serialport in C#

查看:175
本文介绍了如何从C#中的serialport获取数字数据的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

大家好,
我在从C#中收到的串行端口获取variabel(浮动,整数或双精度)数值数据时遇到问题.
都可以帮我解决这个问题吗?

hello all,
i have problem to get numeric data in variabel (float, int or double) from serialport received in C#.
can all help me for that ???

推荐答案

请参见 ^ ]中有关C#中串行端口处理的示例.

串行端口上未定义任何数据协议-这是具有一些基本同步和错误检测(开始/停止位,奇偶校验)的纯比特流.您没有在C#中接触到它.您得到的是字节流.

您需要指定发送方/接收方如何编码数据,例如如何解释整数:
-int的大小(1、2、4字节)?
-字节序(小/大字节序)?
-签名/未签名?
-...

除此之外,您可能还拥有除int之外的其他一些数据.

我假设您有一些协议"规范,可以告诉您什么消息是通过串行线路传输的.

一旦有了该规范,就可以编写消息解析器.请提供该规范(或部分规范),以便我们提供更具体的建议.

干杯
Andi
See MSDN: SerialPort Class[^] for an example on serial port handling in C#.

There is no data protocol defined on serial port - this is pure bit stream with some rudimentary synchronization and error detection (start/stop bits, parity). You are not exposed to that in C#. What you get is a byte stream.

You need to specify how the sender/receiver encode data, e.g. how an integer is to be interpreted:
- size of the int (1,2,4 bytes)?
- endian-ness (little/big endian)?
- signed/unsigned?
- ...

In addition to that, you may also have some other data than int only.

I assume you have some "protocol" specification that tells what messages are transfered over the serial line.

Once you have that specification, you write a message parser. Please provide that specification (or part of it) so that we can give more specific advise.

Cheers
Andi


如果您不知道什么,那么没有例子可以帮助您.
使用 SerialPort.Read [ BitConverter [
No example will help you, if you don''t know what you try to read.
Use SerialPort.Read [^] method to read as many bytes as you need for your datatype. Than, use BitConverter[^] class to convert the bytes read to the data type you need. But this is only the general approach. A serial protocol might be more complicated than that.

Update:

If you have a text protocol as you exposed finally, you need something like this:
string[] values = data.Split(' ');
int temperature = int.Parse(values[0]);
int humidity = int.Parse(values[1]); 
int count = int.Parse(values[2]);


或者,您可以使用以下方法:
.net的scanf替换 [ ^ ]


Or you can use this one: scanf replacement for .net[^]


这篇关于如何从C#中的serialport获取数字数据的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆