#Below is the feedback that I keep getting back, may someone please help, I am using Thonny, Raspberry Pi Pico w, everything is up to date
Connecting to My Phone Connected to @@@@@@@@@ mac = @@@@@@@@@@@@ Current time is 19/03/2023 03:32:01 Count = 0 Task exception wasn't retrieved future: <Task> coro= <generator object 'debounce' at 20013e30> Traceback (most recent call last): File "uasyncio/core.py", line 1, in run_until_complete File "<stdin>", line 176, in debounce TypeError: function missing 1 required positional arguments
import machine, _thread, time, socket, rp2, network, ubinascii, utime, struct, ntptime
from machine import Pin, reset
import urequests as requests
from secrets import saved_networks, secret_ifttt
import sys
import uasyncio as asyncio
# Initialise values
value1 = '?value1=' # Webhooks requires a '?value1='
timeout = 10
wlan = network.WLAN(network.STA_IF)
count = 0
last_count = 0
#Define the pins to use
led = Pin('LED', Pin.OUT)
#Wifi Configuration
# Set country to avoid possible errors
def scan_networks():
wlan.active(True)
networks = wlan.scan()
return networks
# Loop through the list of saved networks and connect to the strongest available network
while True:
networks = scan_networks()
for net in saved_networks:
for available_net in networks:
if available_net[0].decode() == net["ssid"]:
signal_strength = available_net[2]
if signal_strength > net["signal_strength"]:
print("Connecting to", net["ssid"])
wlan.connect(net["ssid"], net["password"])
net["signal_strength"] = signal_strength
break
else:
continue
break
else:
time.sleep(5)
continue
break
# Wait for the connection to be established
while not wlan.isconnected():
time.sleep(5)
print("Connected to", wlan.ifconfig()[0])
# See the MAC address in the wireless chip OTP
mac = ubinascii.hexlify(network.WLAN().config('mac'),':').decode()
print('mac = ' + mac)
# Define blinking function for onboard LED to indicate error codes
def blink_onboard_led(num_blinks):
global led
for i in range(num_blinks):
led.on()
time.sleep(.2)
led.off()
time.sleep(.2)
# Handle connection error
# Error meanings
# 0 Link Down
# 1 Link Join
# 2 Link NoIp
# 3 Link Up
# -1 Link Fail
# -2 Link NoNet
# -3 Link BadAuth
wlan_status = wlan.status()
blink_onboard_led(wlan_status)
if wlan_status != 3:
print("Rebooting in 5 seconds, failed to connect to WiFi")
time.sleep(5)
machine.reset()
raise RuntimeError('Wi-Fi connection failed')
else:
status = wlan.ifconfig()
# Define get_time
def get_time():
NTP_QUERY = bytearray(48)
NTP_QUERY[0] = 0x1B
addr = socket.getaddrinfo(host, 123)[0][-1]
s = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
try:
s.settimeout(timeout)
res = s.sendto(NTP_QUERY, addr)
msg = s.recv(48)
finally:
s.close()
val = struct.unpack("!I", msg[40:44])[0]
EPOCH_YEAR = utime.gmtime(0)[0]
if EPOCH_YEAR == 2000:
NTP_DELTA = 3155673600 # (date(2000, 1, 1) - date(1900, 1, 1)).days * 24*60*60
elif EPOCH_YEAR == 1970:
NTP_DELTA = 2208988800 # (date(1970, 1, 1) - date(1900, 1, 1)).days * 24*60*60
else:
raise Exception("Unsupported epoch: {}".format(EPOCH_YEAR))
return val - NTP_DELTA
#Get the current time
ct = utime.localtime()
formatted_time = "{:02d}/{:02d}/{} {:02d}:{:02d}:{:02d}".format(ct[2], ct[1], ct[0], ct[3], ct[4], ct[5]) #Format the current time as "dd/mm/yyyy HH:MM:SS"
print ("Current time is" ,formatted_time.format(ct[2], ct[1], ct[0], ct[3], ct[4], ct[5]))
print("Count =",count)
async def pulse_led():
'''
Coroutine that pulses the onboard LED
'''
for i in range(count):
led.toggle()
print("LED on")
await asyncio.sleep(0.2)
led.toggle()
print("LED off")
await asyncio.sleep(0.5)
async def adjust_count():
''''
Coroutine that sends a 'IFTTT' request
'''
global count, last_count
while True:
await asyncio.sleep(0.1)
if count != last_count:
last_count = count
print("AC-Count =" ,count)
ifttt_url = 'https://maker.ifttt.com/trigger/pico_w_request/with/key/'+ secret_ifttt['ifttt_key']+ value1+ str(count) # Address for webhooks to increase item count
print("AC-Awaiting 'pico_w_request' feedback")
request = requests.get(ifttt_url)
request.close()
print("As of", formatted_time.format(ct[2], ct[1], ct[0], ct[3], ct[4], ct[5]), "there is" ,count, "items in the letterbox") # Provide feedback to amount of items in the letterbox
async def monitor_pins():
"""
Coroutine that monitors pins 14 and 15.
"""
pin14 = Pin(14, Pin.IN, Pin.PULL_DOWN)
pin15 = Pin(15, Pin.IN, Pin.PULL_DOWN)
last_pin14_value = 0
last_pin15_value = 0
global count
while True:
pin14_value = await debounce(pin14)
pin15_value = await debounce(pin15)
if pin14_value == 1 and last_pin14_value == 0:
count = 0
print("Pin 14 pressed")
print("Count = ", count)
last_pin14_value = 1
elif pin14_value == 0 and last_pin14_value == 1:
last_pin14_value = 0
if pin15_value == 1 and last_pin15_value == 0:
print("Pin 15 pressed")
count += 1
print("Count = ", count)
last_pin15_value = 1
elif pin15_value == 0 and last_pin15_value == 1:
last_pin15_value = 0
async def debounce(pin):
"""
Coroutine that debounces an input pin.
"""
pin_state = pin.value()
stable_count = 0
while True:
await asyncio.sleep(0.01)
pin_value = pin.value()
if pin_value != pin_state:
stable_count = 0
else:
stable_count += 1
if stable_count >= 25:
return pin_value
pin_state = pin_value
# Create an event loop
loop = asyncio.get_event_loop()
# Schedule all coroutine
loop.create_task(pulse_led())
loop.create_task(adjust_count())
loop.create_task(monitor_pins())
loop.create_task(debounce(Pin))
# Run the event loop forever
loop.run_forever()
Code needs to do the following: Connect to wifi, ssid: @@@@@@@@, password: @@@@@@@@ Once wifi is connected print the status of the connection Get current time from NTP server and use this for timestamping all print statements, format should be dd/mm/yyyy hh/mm/ss Print the time. When pin 15 is triggered, increment a variable called "count" by 1 When pin 14 is triggered, reset the "count" variable. Pin 14 and 15 should be able to trigger at any time without having to wait for the pulse_led to finish.
Input monitoring should not be affected by running the 'pulse-led' function.
The script should define pins 14 and 15 as input pins with pull-down resistors, and the onboard LED as led = machine.Pin('LED', machine.Pin.OUT) The script should define a debounce function that waits for 25ms before checking the pin value for the rising edge. The script should define a pin monitoring function that waits for either pin 14 or pin 15 to be triggered. When one of the pins is triggered, the function shall check which pin was triggered and update the "count" variable accordingly. The function shall also print the current time and the new value of "count".
The script should define a pulse_led function that checks whether the "count" variable is greater than 0. If it is, the function shall blink the onboard LED at a rate of 0.2 seconds on, 0.5 seconds off "count" times, and use a print statement informing of the led status, then waits 2 seconds before repeating. If the "count" variable is 0, the function waits for 0.1 seconds before checking again.
Hope all this helps!? Thanks in advance for any assistance.
debounce(Pin)is trying to call the debounce function on thePinconstructor, which doesn't make sense. As you said in your answer, that whole line isn't needed.