4

When put return in while loop the loop will stop How to fix it?

ser = serial.Serial(
    port='COM5',
    baudrate = 9600,
    timeout=1)
while 1:
    x=str(ser.readline())
    x = re.findall("\d+\.\d+", x)
    x = float(x[0])
    return(x) #loop stopped
    print(x)

Could you please help me?

Fabri Pautasso
  • 485
  • 6
  • 17
Juizy J.
  • 43
  • 1
  • 1
  • 4

3 Answers3

1

Simply take your

x=str(ser.readline())
x = re.findall("\d+\.\d+", x)
x = float(x[0])
return(x) #loop stopped

put it into a function like

def foo(ser):
    x=str(ser.readline())
    x = re.findall("\d+\.\d+", x)
    x = float(x[0])
    return(x)

and change your while loop to simply be

while 1:
    print(foo(ser))

However @developius had a better solution which would look something like

while 1:
    x=str(ser.readline())
    x = re.findall("\d+\.\d+", x)
    x = float(x[0])
    print(x)
Dillanm
  • 876
  • 12
  • 28
  • 1
    Thanks for advice Dillanm i will try i am a beginner of coding – Juizy J. Jan 13 '17 at 11:29
  • @JuizyJ. we all have to start somewhere! The Python docs are pretty good on their own, I also found [Codecademy](https://www.codecademy.com/learn/python) and [TutorialsPoint](https://www.tutorialspoint.com/python/) to be pretty good when I was learning Python, particularly Codecademy since it's interactive and gives immediate feedback! (and they're both free too!) – Dillanm Jan 13 '17 at 11:35
1

If you want to pass the values continuously to a separate piece of code, you can use yield.

You can modify your code as followed:

def func():
    while 1:
        x=str(ser.readline())
        x = re.findall("\d+\.\d+", x)
        x = float(x[0])
        yield x

And then call the function. Note that f will be a generator so you will have to loop over it as below.

f = func()
for i in f:
    print(i) # or use i for any purpose

Reference: here

asif
  • 171
  • 6
-2

u can try this one

while 1:
    x=str(ser.readline())
    x = re.findall("\d+\.\d+", x)
    x = float(x[0])
return x
Stefani Johnsson
  • 381
  • 1
  • 5
  • 18