Author Topic: ON/OFF Button for bit in a register Modbus TCP  (Read 2739 times)

Nikola Tesla

  • Newbie
  • *
  • Posts: 10
    • View Profile
ON/OFF Button for bit in a register Modbus TCP
« on: February 05, 2024, 01:18:02 PM »
Hi, I'm new with VB and I was looking for some forum posts to create a couple of buttons for an application. The first button is to set to 1 independent bits of a modbus tcp register and for that I have used Godra's code in another post:

Private Sub BasicButton1_Click(sender As Object, e As EventArgs) Handles BasicButton1.Click
    Try
        Dim b_Num As Integer = 1 'or if dynamically changing then call it from a TextBox, like: Dim b_Num As Integer = TextBox1.Text
        Dim Value = Me.ModbusTCPCom1.Read("40001")
        Me.ModbusTCPCom1.Write("40001", Value Or 2 ^ (b_Num - 1))
    Catch ex As Exception
        System.Windows.Forms.MessageBox.Show("Failed to write value. " & ex.Message)
    End Try

 The second button I created to disable the bit of the word I enabled earlier and for this I used the same Godra code and changed the following command:

Me.ModbusTCPCom1.Write("40001", Value - 2 ^ (b_Num - 1)).

The off button is only connected and appears on screen if the bit it disables is set to 1, but if you quickly hit the button before the associated bit is disabled, it is able to subtract more than once the same bit, how could I avoid it to subtract more than once and not modify the register in a wrong way? Can you think of another way to create an off/on button for independent bits of a register?


Archie

  • Administrator
  • Hero Member
  • *****
  • Posts: 5322
    • View Profile
    • AdvancedHMI
Re: ON/OFF Button for bit in a register Modbus TCP
« Reply #1 on: February 05, 2024, 01:24:07 PM »
in conjunction with the subtract you want to use a logical AND.

ModbusTCPCom1.Write("40001", Value AND (65535 - 2 ^ (b_Num - 1)))

I can't test that right now, but the 65535 assumes it is an unsigned 16 bit integer, it may need to be a 32767

Nikola Tesla

  • Newbie
  • *
  • Posts: 10
    • View Profile
Re: ON/OFF Button for bit in a register Modbus TCP
« Reply #2 on: February 05, 2024, 01:51:08 PM »
in conjunction with the subtract you want to use a logical AND.

ModbusTCPCom1.Write("40001", Value AND (65535 - 2 ^ (b_Num - 1)))

I can't test that right now, but the 65535 assumes it is an unsigned 16 bit integer, it may need to be a 32767

Thanks Archie!

I have just teste with a ModbusPal Tcp Servidor Simulator and run with 65535 y 32767, this week I'll test with a plc.