0

So I run this code which is supposed to cycle between these setpoints for ten seconds each. It all works as expected, but the problem is that sometimes the instrument does not respond. I would like to add an if statement that resends the message if there is no response. The problem is that Minimalmodbus exits out the script when there is no response. Is there any way I can bypass that error so that I can add the if statement?

The error occurs at line b = board.custommsg(). If the error didn't end the script, I could add an if statement to resend if b is empty.

import time
import readboard
import struct
import crc16
import os
import threading

def timer():
    current = time.time()
    while (time.time() - current) < 10:
        print('\r', round((time.time() - current), 2), end='')
    pass


board = readboard.comport('COM5')

setpoint = [50, 125, 250, 375, 500]

a = 0
while a < 10:
    for x in setpoint:
        msg = bytearray(b'\x7F\x06\x00\x05')
        max = 550
        integer = int((x/max)*65535)
        i = struct.pack('<H', integer)
        msg.append(i[1])
        msg.append(i[0])
        crc = crc16.getfilecrc(msg)
        msg = crc16.addcrc(msg, crc)
        final = bytes(msg)
        b = board.custommsg(final, 8)   #<---- this is where it errors out
        t1 = threading.Thread(target=timer, args=())
        print('         Setpoint: ', round((struct.unpack('>H', bytearray(b)[4:6])[0])*(550/65535), 2), end='\r')
        t1.start()
        time.sleep(10)
        t1.join()
  • 3
    Without the error text this is a bit of a guess, but I suspect you just need a [try/except as per the docs](https://minimalmodbus.readthedocs.io/en/stable/usage.html#handling-communication-errors). – Brits Oct 10 '22 at 22:44
  • I'll give that a try tomorrow and report back. I will also add the error text here. – Isaac Zaiek Oct 10 '22 at 23:06
  • It's fine to [answer your own question](https://stackoverflow.com/help/self-answer) it might help others finding this question in the future. – import random Oct 29 '22 at 11:40

0 Answers0