首页 \ 问答 \ 读取SerialPort vb.net中的字节值26(Reading byte value 26 in SerialPort vb.net)

读取SerialPort vb.net中的字节值26(Reading byte value 26 in SerialPort vb.net)

我有一个vb.net winforms应用程序,它可以读取/写入连接到USB-RS485设备的多个设备的串行数据。 该应用程序是用Visual Basic .NET 2008编写的,尽管我也尝试过.NET 2015。

几乎一切都运行良好,除非其中一个设备发送一个字节值为26的消息。然后我不确定究竟发生了什么但是在字节值26之后,读数似乎停止了。 之后的所有数据都会在下一个DataReceived事件中读取。

我做了一个简短的程序来测试serialport。 它显示完全相同。 此外,我只有一个设备连接测试。 设备发送的数据由10个字节组成。 值为251,20,(6个数据字节),校验和,校验和。

前两个和后两个字节永远不会达到26的值,它只是可以做到这一点的数据字节。

进口:

Imports System.IO.Ports
Imports System.Text

变量:

Dim WithEvents SP_TestCom As SerialPort
Public DataArray() As Byte

替补:

Public Sub OpenCom()
    If SP_TestCom.IsOpen Then
        Exit Sub
    End If
    SP_TestCom.Open()
End Sub

Public Sub CloseCom()
    If Not SP_TestCom.IsOpen Then
        Exit Sub
    End If
    SP_TestCom.Close()
End Sub

Public Sub SendData(ByVal Data() As Byte)
    Try
        If SP_TestCom.IsOpen Then
            SP_TestCom.Write(Data, 0, Data.Length)
        End If
    Catch ex As Exception

    End Try
End Sub


Private Sub SP_TestCom_DataReceived(ByVal sender As Object, ByVal e As System.IO.Ports.SerialDataReceivedEventArgs) Handles SP_TestCom.DataReceived
    Try
        If SP_TestCom.BytesToRead > 0 Then
            Dim DataArray_Temp(SP_TestCom.BytesToRead + 1) As Byte
            SP_TestCom.Read(DataArray_Temp, 0, SP_TestCom.BytesToRead)

            Array.Copy(DataArray_Temp, DataArray, DataArray_Temp.Length)
        End If
    Catch ex As Exception

    End Try
End Sub

我有一个带有两个按钮和一个计时器的主窗体。 按钮用于打开和关闭端口。 计时器读取数据阵列

我尝试了几种阅读方式。

  • 直接读入数组
  • 分别读取每个字节
  • 读入一个字符串,然后将其转换为字节数组

我也试过不同的编码。 虽然我不确定它是否会产生任何影响。

  • ASCII
  • UNICODE
  • UTF

All都给出了同样的错误。

我可以通过忽略包含字节值26的任何消息来绕过错误。这至少不会在我的应用程序的其余部分给出奇怪的结果,但它不是完美的解决方案。

有谁知道问题可能是什么?

编辑:

Public Sub InitSerial()
    SP_TestCom = New SerialPort
    SP_TestCom.PortName = "COM26"
    SP_TestCom.ReadTimeout = 20
    SP_TestCom.BaudRate = 19200
    SP_TestCom.DataBits = 8
    SP_TestCom.StopBits = StopBits.One
    SP_TestCom.Parity = Parity.None
    SP_TestCom.ReceivedBytesThreshold = 10
End Sub

I have an vb.net winforms application that reads/writes serial data to several devices connected to a USB-RS485 device. The application is written in visual basic .NET 2008, altough i tried .NET 2015 as well.

Almost everything is working well except when one of the devices sends a message with a byte value of 26. Then im not sure what exactly happens but after the byte value of 26 the reading seems to stop. And all data after that is read in the next DataReceived event.

I have made a short program to only test the serialport. And it shows exactly the same. Also i have only one device connected with the test. The data the device is sending consists of 10 bytes. The values are 251,20,(6 data bytes),checksum lo, checksum hi.

The first two and last two bytes can never reach a value of 26, it is just the data bytes that can do that.

Imports:

Imports System.IO.Ports
Imports System.Text

Variables:

Dim WithEvents SP_TestCom As SerialPort
Public DataArray() As Byte

subs:

Public Sub OpenCom()
    If SP_TestCom.IsOpen Then
        Exit Sub
    End If
    SP_TestCom.Open()
End Sub

Public Sub CloseCom()
    If Not SP_TestCom.IsOpen Then
        Exit Sub
    End If
    SP_TestCom.Close()
End Sub

Public Sub SendData(ByVal Data() As Byte)
    Try
        If SP_TestCom.IsOpen Then
            SP_TestCom.Write(Data, 0, Data.Length)
        End If
    Catch ex As Exception

    End Try
End Sub


Private Sub SP_TestCom_DataReceived(ByVal sender As Object, ByVal e As System.IO.Ports.SerialDataReceivedEventArgs) Handles SP_TestCom.DataReceived
    Try
        If SP_TestCom.BytesToRead > 0 Then
            Dim DataArray_Temp(SP_TestCom.BytesToRead + 1) As Byte
            SP_TestCom.Read(DataArray_Temp, 0, SP_TestCom.BytesToRead)

            Array.Copy(DataArray_Temp, DataArray, DataArray_Temp.Length)
        End If
    Catch ex As Exception

    End Try
End Sub

I have a main form with two buttons and a timer. The buttons are for opening and closing the port. The timer reads the dataarray

I have tried several ways of reading.

  • Reading directly into an array
  • Reading each byte seperatly
  • Reading into a string and then converting it into a byte array

I also tried different encodings. Although i am not sure if it would have any effect.

  • ASCII
  • UNICODE
  • UTF

All gives the same error.

I could bypass the error by ignoring any message containing a byte value of 26. This at least does not give me strange results in the rest of my application but it is not the perfect solution.

Does anyone have an idea of what the issue might be?

Edit:

Public Sub InitSerial()
    SP_TestCom = New SerialPort
    SP_TestCom.PortName = "COM26"
    SP_TestCom.ReadTimeout = 20
    SP_TestCom.BaudRate = 19200
    SP_TestCom.DataBits = 8
    SP_TestCom.StopBits = StopBits.One
    SP_TestCom.Parity = Parity.None
    SP_TestCom.ReceivedBytesThreshold = 10
End Sub

原文:https://stackoverflow.com/questions/36423786
更新时间:2023-09-01 09:09

最满意答案

如果您要连接的API使用“request_time - 1个月”,那么您的脚本认为时间是不相关的,只是API背后的脚本认为它的时间。 (一个愚蠢的比喻:如果一家商店在下午5点关门,提早设置您的手表不会让您在5点半进入;您需要潜入并更换墙上的时钟,以便员工不会锁定向上。)

所以,除非你能找到一种方法来欺骗远程API,使其认为你在不同的时间发送了请求,否则你就无能为力。

如果您控制API,那么只需编辑API以使参数超出“now”的定义,也许只能在特殊调试模式下使用。


If the API you are connecting to is using "request_time - 1 month", then what your script thinks the time is isn't relevant, only what time the script behind the API thinks it is. (As a silly analogy: if a shop closes at 5PM, setting your watch early won't let you in at 5:30; you'd need to sneak in and change the clock on the wall so that the staff don't lock up.)

So unless you can find a way to fool the remote API into thinking you sent the request at a different time, there is nothing you can do.

If you control the API, then just edit the API to have a parameter which over-rides the definition of "now", perhaps only allowed in a special debug mode.

相关问答

更多
  • 尝试为PDO::PARAM_NULL绑定null 。 $type = PDO::PARAM_INT; if($_POST['code'] == "") { $_POST['code'] = null; $type = PDO::PARAM_NULL; } $stmt = $dbh->prepare("UPDATE Product SET code=? WHERE id=?"); $stmt->bindValue(1, $_POST['code'], $type); $stmt->bindV ...
  • 只需确保您的脚本生成适当的Content-Type标头。 您可以使用header()执行此操作 。 Just make sure your script generates the appropriate Content-Type header. You can do so with header().
  • localtime()函数返回服务器本地时间的所有数据。 它有很多选项,所以你可以在不同类型的数组中获得它(关联或数字索引)。 您也可以使用使用服务器本地时区的date() 。 您可以使用date_default_timezone_set()函数更改服务器的时区。 了解有关localtime()函数及其参数的更多信息: http : //php.net/manual/en/function.localtime.php或http://www.w3schools.com/php/func_date_localt ...
  • 我不太确定你需要做什么,我通常会改变操作系统时间,无论如何,简单来说: // DEMO mock date js browser // comment uncoment to play arround, if you need to automate with or without mock date plain an simple: mockDateTime('2018/02/02'); // with mock // mockDateTime() // no mock $('#d ...
  • 使用依赖注入框架来处理依赖项。 在单元测试中,您可以将实际实现与存根实现交换。 例如,在StructureMap中,您将在代码中说明。 “好吧,现在给我一个IDataRepository的活动实例”,对于你的普通代码,这将指向真实数据库的实现。 在您的unittest中,您可以通过放置ObjectFactory.Inject(new FakeDataRepository())来覆盖它。 然后,所有代码都会使用虚假仓库,这使得测试单个工作单元变得非常容易 Use a Dependency injection ...
  • 用户可以简单地在他们的本地机器上创建一个文件:
    您不能在类中使用函数调用或函数外部的变量。 默认值必须是静态的。 以下作业是有效的: public $data = "hello"; public $data = array(1,2,3,4); public $data = SOME_CONSTANT; 以下不是: public $data = somefunction(); public $data = $test; 但是,您可以使用构造函数: public function __construct() { $this->bdate = da ...
  • PHP对于大数字来说有点不好,但是sprintf可以提供帮助。 尝试: echo sprintf( '%018.0f', $nanoseconds ); -> 130868575890000000 或者,您可以更改描述precision的“精度”设置: 精度整数 The number of significant digits displayed in floating point numbers. ini_set("precision",20); echo $nanoseconds; -> 13086 ...
  • 如果您要连接的API使用“request_time - 1个月”,那么您的脚本认为时间是不相关的,只是API背后的脚本认为它的时间。 (一个愚蠢的比喻:如果一家商店在下午5点关门,提早设置您的手表不会让您在5点半进入;您需要潜入并更换墙上的时钟,以便员工不会锁定向上。) 所以,除非你能找到一种方法来欺骗远程API,使其认为你在不同的时间发送了请求,否则你就无能为力。 如果您控制API,那么只需编辑API以使参数超出“now”的定义,也许只能在特殊调试模式下使用。 If the API you are con ...
  • 摆脱“$ hour”。 在回声中。 代码应该是, echo ' the date and time now is ' . date('d/m/y H:i'); 请注意,在“is”之后你还有一个额外的空间可能不是故意的。 Get rid of the "$hour ." in the echo. The code should be, echo ' the date and time now is ' . date('d/m/y H:i'); Note you also had an extra spac ...

相关文章

更多

最新问答

更多
  • 散列包括方法和/或嵌套属性(Hash include methods and/or nested attributes)
  • TensorFlow:基于索引列表创建新张量(TensorFlow: Create a new tensor based on list of indices)
  • 企业安全培训的各项内容
  • 错误:RPC失败;(error: RPC failed; curl transfer closed with outstanding read data remaining)
  • NumPy:将int64值存储在np.array中并使用dtype float64并将其转换回整数是否安全?(NumPy: Is it safe to store an int64 value in an np.array with dtype float64 and later convert it back to integer?)
  • 注销后如何隐藏导航portlet?(How to hide navigation portlet after logout?)
  • 将多个行和可变行移动到列(moving multiple and variable rows to columns)
  • 对setOnInfoWindowClickListener的意图(Intent on setOnInfoWindowClickListener)
  • Angular $资源不会改变方法(Angular $resource doesn't change method)
  • 如何配置Composite C1以将.m和桌面作为同一站点提供服务(How to configure Composite C1 to serve .m and desktop as the same site)
  • 不适用:悬停在悬停时:在元素之前[复制](Don't apply :hover when hovering on :before element [duplicate])
  • Mysql DB单个字段匹配多个其他字段(Mysql DB single field matching to multiple other fields)
  • 产品页面上的Magento Up出售对齐问题(Magento Up sell alignment issue on the products page)
  • 是否可以嵌套hazelcast IMaps?(Is it possible to nest hazelcast IMaps? And whick side effects can I expect? Is it a good Idea anyway?)
  • UIViewAnimationOptionRepeat在两个动画之间暂停(UIViewAnimationOptionRepeat pausing in between two animations)
  • 在x-kendo-template中使用Razor查询(Using Razor query within x-kendo-template)
  • 在BeautifulSoup中替换文本而不转义(Replace text without escaping in BeautifulSoup)
  • 如何在存根或模拟不存在的方法时配置Rspec以引发错误?(How can I configure Rspec to raise error when stubbing or mocking non-existing methods?)
  • asp用javascript(asp with javascript)
  • “%()s”在sql查询中的含义是什么?(What does “%()s” means in sql query?)
  • 如何为其编辑的内容提供自定义UITableViewCell上下文?(How to give a custom UITableViewCell context of what it is editing?)
  • c ++十进制到二进制,然后使用操作,然后回到十进制(c++ Decimal to binary, then use operation, then back to decimal)
  • 以编程方式创建视频?(Create videos programmatically?)
  • 无法在BeautifulSoup中正确解析数据(Unable to parse data correctly in BeautifulSoup)
  • webform和mvc的区别 知乎
  • 如何使用wadl2java生成REST服务模板,其中POST / PUT方法具有参数?(How do you generate REST service template with wadl2java where POST/PUT methods have parameters?)
  • 我无法理解我的travis构建有什么问题(I am having trouble understanding what is wrong with my travis build)
  • iOS9 Scope Bar出现在Search Bar后面或旁边(iOS9 Scope Bar appears either behind or beside Search Bar)
  • 为什么开机慢上面还显示;Inetrnet,Explorer
  • 有关调用远程WCF服务的超时问题(Timeout Question about Invoking a Remote WCF Service)