Home > OS >  Making this if statement loop until a certain string value is reached
Making this if statement loop until a certain string value is reached

Time:10-03

I'm trying to loop the if statement below but under the condition of it continuing only when the response from the serial port = "OK".

The problem I'm having is that before I can get the response "OK" it loops the statement by sending the next command. Also the response from the serial port comes out chopped up and I don't know why (did not include the commands in COMMAND_LIST due to security reasons, but I checked and the values are being input correctly)

import serial
import time

## use the time module to give an interval to the commands ##

print('serial' serial.__version__)

PORT = 'COM8'
Baudrate = 115200

ARD=serial.Serial(PORT,Baudrate, timeout = 1)

## COMMAND_LIST is a list that contains the AT Commands 
that are to be input through the code below (in order) ##  

for cmd in COMMAND_LIST:
    Trans=cmd.encode('utf-8')
    ARD.write(Trans)
    ARD.write(b'\x0d')
    time.sleep(2)
    print("SENT")
## Make it loop until value "OK" comes out (below is the if statement i'm trying to make) ##
    if ARD.readable():
        msg=ARD.read(76).decode('utf-8')
        print(msg)

ARD.close()

CodePudding user response:

Does the "break" statement suits your case?

data = ["OK", "OK", "OK", "OK", 2, "foo", "bar"]

status = "OK"

for item in data:
    if not status == "OK":
        break
    print(item)
    status = item

CodePudding user response:

    if ARD.readable():
        if msg != "OK":
            msg=ARD.read(76).decode('utf-8')
            print(msg)

ARD.close()

    enter code here

  • Related