The problem is that your toggle_forever is running, well, forever.
The only way to tell if data is available on sys.stdin is to use poll or select. It looks like you're running on an ESP. I have a pyboard so I modified your example a bit to run on my pyboard.
I created forever.py:
Code: Select all
import time
import pyb
import sys
import select
led = pyb.LED(4)
poll = select.poll()
poll.register(sys.stdin, select.POLLIN)
def toggle_forever():
poll_delay = 1
t = 0
while True:
led.toggle()
print('changed state', t)
t += 1
events = poll.poll(poll_delay * 100)
for file in events:
if file[0] == sys.stdin:
ch = sys.stdin.read(1)
print('Got', ch)
if ch >= '0' and ch <= '9':
poll_delay = ord(ch) - ord('0')
print('Changing delay to', poll_delay, 'seconds')
and then I created run_forever.py:
Code: Select all
#!/usr/bin/env python
import pyboard
import time
# Initialize PyBoard and connect in REPL mode
pyb = pyboard.Pyboard('/dev/ttyACM1')
pyb.enter_raw_repl()
# Execute the file that reports the pulse and time ticks
print('execfile poll_stdin.py')
pyb.execfile('forever.py')
print('About to call toggle_forever')
pyb.exec_raw_no_follow("toggle_forever()")
# Wait for 3 seconds and then set the delay to 2
print('Sleeping for 3 seconds')
time.sleep(3)
print('Sending a 2')
pyb.serial.write(b'2')
# Wait for 6 seconds and then set the delay to 1
print('Sleeping for 3 seconds')
time.sleep(3)
print('Sending a 2')
pyb.serial.write(b'1')
# Exit REPL and close the connection
pyb.exit_raw_repl()
pyb.close()
Now if I execute run_forever.py then I see this on my PC:
Code: Select all
About to call toggle_forever
Sleeping for 3 seconds
Sending a 2
Sleeping for 3 seconds
Sending a 1
And when it sends the 2 you should see the blinking slow down, and then when it sends the 1 you should see it speed up again.
So you could do something like this:
Code: Select all
import time
import pyb
import sys
import select
led = pyb.LED(4)
poll = select.poll()
poll.register(sys.stdin, select.POLLIN)
def toggle_forever():
poll_delay = 1
t = 0
while True:
led.toggle()
print('changed state', t)
t += 1
events = poll.poll(poll_delay * 1000)
for file in events:
if file[0] == sys.stdin:
ch = sys.stdin.read(1)
print('Got', ch)
if ch >= '0' and ch <= '9':
poll_delay = ord(ch) - ord('0')
print('Changing delay to', poll_delay, 'seconds')
and then