Modbus Configuration for writing bit to PLC

Hello, I´m new zo use Homeassistant. I used openhab before. But now I want to make a new visualisation. I tried to cofigure read/write a single Bit to modbus/tcp. I tried a lot of different suggestions from chatgpt and google. With templates, scrips and so on. Does someone have a workung solution for me?

I could read a Register:

  • name: bit2_status
    slave: 1
    address: 12338
    input_type: holding
    data_type: int16
    last try creates an Switch, but without funktion:

Template:

template.yaml

  • sensor:
    • name: “bit2_status”
      state: “{{ (states(‘sensor.register_12338_raw’)|int(0) & 4) > 0 }}”

template.yaml

  • switch:
    • name: “bit2_schalter”
      state: “{{ is_state(‘sensor.bit2_status’, ‘True’) }}”
      turn_on:
      • service: script.bit2_set
        turn_off:
      • service: script.bit2_clear

Script:

scripts.yaml

bit2_set:
alias: “Set Bit2”
sequence:
- service: modbus.write_register
data:
hub: SPS_OG
unit: 1
address: 12338
value: 4 # direkt den Wert schreiben oder Bitwise-OR in PLC

bit2_clear:
alias: “Clear Bit2”
sequence:
- service: modbus.write_register
data:
hub: SPS_OG
unit: 1
address: 12338
value: 0 # Bit löschen

Could someone have a solution or a working config for me?
Steffen