I am working with the mqtt examples for uPython, i adapted the example given to do something different. My code is suppose to publish a simple message when light levels drops below a given threshold. but i get this error:
download ok
exec(open('main.py').read(),globals())
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
File "<string>", line 43
SyntaxError: invalid syntax
below is my main.py
from machine import Pin, ADC from time import sleep ldr = ADC(0) def sub_cb(topic, msg): print((topic, msg)) if topic == b'notification' and msg == b'received': print('ESP received hello message') def connect_and_subscribe(): global client_id, mqtt_server, topic_sub client = MQTTClient(client_id, mqtt_server) client.set_callback(sub_cb) client.connect() client.subscribe(topic_sub) print('Connected to %s MQTT broker, subscribed to %s topic' % (mqtt_server, topic_sub)) return client def restart_and_reconnect(): print('Failed to connect to MQTT broker. Reconnecting...') time.sleep(10) machine.reset() try: client = connect_and_subscribe() except OSError as e: restart_and_reconnect() while True: ldrValue = ldr.read() print(ldrValue) sleep(0.1) if ldrValue >= 350 msg = b'laser0' client.publish(topic_pub, msg) last_message = time.time() counter += 1 except OSError as e: restart_and_reconnect()
Hello Joseph, what’s your line 43 in that script? Can you tell me the line and double-check the indentation. According to that error, it’s usually missing some spaces.
Did you double-check the spacing?
Unfortunately the forum doesn’t support MicroPython spacing, you should use pastebin.com to share properly formatted MicroPython scripts
Yes. I double checked that spacing. I made sure they’re all tabbed in two spaces. Nutbfor clarity purpose here’s the code on paste bin. https://pastebin.com/kcuRfR2A
The spacing does look right. However, line 43 is:
last_message = time.time()
What’s that line doing? I think you can delete it
Deleted that line. Didn’t fix the problem, and oh, the error is now line 41 which is
msg = b'laser
‘
Hello Joseph,
This is your problem at line 40, there’s a : missing after the if statement. it needs to be something like this:
You also had your indentation wrong (specially in the while true). It should now be fixed the indentation, but I’m not sure if it will work as expected, because I couldn’t try it.
I apologize for taking so long to get back to you, but I’ve been with an eye problem and I had to limit my access to screens (computer/smartphones).
Thanks for the reply Rui. I’ll test it and give feed back. btw, there’s s protective eye glass you can buy (if you do no already own one) that blocks the harmful uv light from your eyes.