如何通过c#中的串口发送整数值 [英] how to send integer value through serial port in c#

查看:155
本文介绍了如何通过c#中的串口发送整数值的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我使用此代码,但我可以在另一端获得不同的值,请帮我如何通过串口发送整数值?

i using this code ,but i can get different values at other end,please help me how to send integer value through serial port?

serialPort1.Open();
serialPort1.Write(new byte[] { 0x0D }, 0, 1);
serialPort1.Close();

推荐答案

请看我对这个问题的评论。



首先,您可以以字节数组的形式发送任何数据: http://msdn.microsoft.com/en-us/library/ms143551%28v=vs.110%29.aspx [ ^ ]。



任何数据都可以序列化为字节数组。对于整数类型,可以使用类 System.BitConverter 来完成:

http://msdn.microsoft.com/en-us/library/system.bitconverter%28v=vs.110%29。 aspx [ ^ ]。



查看所有 System.BitConverter.GetBytes 方法。



对于阅读,两种类型都有对称的反向方法。



实际上,你是什么真正需要发送取决于某些设备在RS-232电缆另一端实现的某种应用级协议。在许多情况下,这是表示一种或另一种形式的数字的文本数据。相同的文档还说明了如何使用字符串。



-SA
Please see my comment to the question.

First of all, you can send any data in the form of array of bytes: http://msdn.microsoft.com/en-us/library/ms143551%28v=vs.110%29.aspx[^].

Any data can be serialized into array of bytes. For integer types, it can be done using the class System.BitConverter:
http://msdn.microsoft.com/en-us/library/system.bitconverter%28v=vs.110%29.aspx[^].

Look at all of the System.BitConverter.GetBytes methods.

For reading, there are symmetrical reverse methods, in both classes.

Actually, what you really need to send depends on some kind of application-level protocol implemented by some device on the other end of your RS-232 cable. In many cases, this is text data representing numbers in one or another form. The same documentation also shows how to work with strings.

—SA


这篇关于如何通过c#中的串口发送整数值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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