multiple reed sensors

General discussions and questions abound development of code with MicroPython that is not hardware specific.
Target audience: MicroPython Users.
Post Reply
Posts: 2
Joined: Thu Jun 28, 2018 6:07 pm

multiple reed sensors

Post by jberg145 » Thu Jun 28, 2018 6:16 pm

Hey folks, i am new to micropython and was having trouble connecting multiple reed sensors. Not sure if i am on the right track or if this is even possible with the board i have.

I have an Wemos D1 mini lite (ESP8285) running micropython 1.9.3.

Here is what i have so far but does not seem to be consistent. It seems to work some of the time.
import machine
import time
import uasyncio as asyncio
switch1 = machine.Pin(12, machine.Pin.IN, machine.Pin.PULL_UP)
switch2 = machine.Pin(13, machine.Pin.IN, machine.Pin.PULL_UP)

async def check_contact(switch):
while True:
first = switch.value()
second = switch.value()
if first and not second:
print('Closed ', switch)
elif not first and second:
print('Open ', switch)
except OSError:
print("Can't read from Switch")

await asyncio.sleep(0)

loop = asyncio.get_event_loop()

User avatar
Posts: 938
Joined: Sat May 09, 2015 4:13 pm
Location: Rhineland, Europe

Re: multiple reed sensors

Post by Roberthh » Fri Jun 29, 2018 5:42 am

Could you detail on what you expect to get and what you really get?
From the program logic it seems that you want to tell the moment when a switch is opened or closed. The code you are using is hardly able to reliably work, because the two samples you take are 10ms distant, so the code has to be executed at least every 5 ms. Better keep the initial/last state of a switch in a variable, sample once (ignoring debouncing at the moment) in a call to the coroutine and compare against the last state. This would make not assumption on timing.

User avatar
Posts: 2708
Joined: Fri Jul 18, 2014 8:01 am
Location: UK

Re: multiple reed sensors

Post by pythoncoder » Fri Jun 29, 2018 6:19 am

Two points. It's bad practice to use time.sleep(t) in a coroutine because it stops any other coroutines running for that period. Use await asyncio.sleep_ms(10).

More importantly, as @Roberthh hinted, switches suffer from contact bounce . A Switch class exists for use with uasyncio. This handles debouncing transparently and provides for callbacks on closure and opening. I suggest you look at this resource for details.
Peter Hinch

Posts: 2
Joined: Thu Jun 28, 2018 6:07 pm

Re: multiple reed sensors

Post by jberg145 » Sat Jun 30, 2018 2:00 am

Thanks for the replays.

@Roberth, yes, I am trying to get a message when the switch is opened or closed.

@pythoncoder, thanks. I will take a look at the documentation.

Thanks again.

Post Reply