Ithamar_code/documentation/source/pico.rst
2024-10-08 22:34:17 +02:00

203 lines
12 KiB
ReStructuredText

Arduino pico
=============
This is where the pico ledstrip projects are store, for a bit of context: for year 1 period 2 i am tasked with working with the arduino pico and a ledstrip (w2812B).
This project mostly revolves around making the ledstrip light up certain leds and patterns, the fundamental lesson that the school is trying to teach us is
learning to work with loops and statements. Through these projects we will be required to rely less on simple inputs and imports and more on thinking out of the box.
The files refferenced can be found in https://git.herreweb.nl/IthamarHerrewijnen/Ithamar_code/src/branch/main/documentation/source or the git repository.
Apart from micropython no other packages have to be installed.
.. code-block:: python
from discolight_sl import *
# DiscoLed()
police()
# shutoff()
# Riveting stuff i know
What i did for this period code-wise is simply write a new function or script everytime i needed something, from there i'd just call said function in an adequetly named "main"
file to test the function live. To this extent i only made a few files/functions to accomodate this class subject listed below:
- Main.py: As the name suggests this file's only purpose (as shown above) is to call upon a function from another file.
- Colorwave: This file is used to define color to send to a ledstrip. This file is also equipped to test a led strip if the file is run as main.
.. code-block:: python
from neopixel import Neopixel
numpix = 30
strip = Neopixel(numpix, 0, 28, "GRB")
# strip = Neopixel(numpsix, 0, 0, "GRBW")
red = (255, 0, 0)
orange = (255, 50, 0)
yellow = (255, 100, 0)
green = (0, 255, 0)
blue = (0, 0, 255)
indigo = (100, 0, 90)
violet = (200, 0, 100)
colors_rgb = [red, orange, yellow, green, blue, indigo, violet]
while True:
strip.rotate_right(1)
time.sleep(0.15)
strip.show()
Trivia
Colorwave: This is one of the files required to work with the ledstrip. It defines colors for easier use and can be used as a test file to see if a strip works or not. This code
contains a lot of callable intergers to be used as a reference sheet to avoid clutter in the main code, it also gives the function to the ledstrip to move from left to right.
NeoPixel: this file actually programs directly into the ledstrip rather than give it some intergers. This file is required to operate the ledstrip to begin with.
therefore it is a rather large file (text wise) with a full documentation on `github <https://github.com/adafruit/Adafruit_NeoPixel>`.
This code contains all the technical functions of the ledstrip script. The interesting part for the user are functions such as **brightness**, **show** and **rotate**. Whereas
colorwave gave the user the colors for the ledstrip, Neopixel gives the user all the *fun* functions to create your own custom lighting.
discolight_sl: This is the main file i'm currently using to stash all my functions in. For the moment this only includes some code i got from some `guy <https://git.herreweb.nl/EljakimHerrewijnen>`_
called disco. My own code which is called police and a shutoff function. Because i'm too lazy to scroll for the functions i call them in a different file.
This code has very few interesting notes on how it functions: In the function: "discolight" we use a randomizer to set every pixel to some random rgb value. In the function:
**police** we use a simpole calculation to get the even numbers for one set of leds and the very same formula to get the uneven leds. After that we simply make the leds take
turns in who gets to light up first, creating a policelight effect.
The Exams
I'll tell you straight up i failed the exams almost thrice due to a mixture of circumstance, lack of cricital knowledge, tunnel vision and as it's called in my own generation's
words; *an issue of the skill* or *skill issue*. Since i generally find the fault with myself i tend to agree with the latter reason even if one exam was actually scuffed.
The exams revolved around being able to fetch data from a website, filter this data out to only show the data you want such as the latest uploaded temperature and wind direction.
This data would be printed and the leds would be programmed to respond to the data with different collors (cold = 1-15 blue, hot 1-15 red stuff like that). The time given for this
was about 3 days to figure out and turn into an essay with some proof. Now i knew my leds better than i knew everything else which was exactly the problem the first time,
I could not figure out how to filter data and this caused me to crash with the grace of a piece of satelite space debris.
The second time i did an exam i was with one other guy. This time i actually had a decent idea of what i was supposed to do but there was a minor ever so slight inconvenience:
The data you were supposed to collect was set up with a mqtt connection through a ssl connection. Now for context when i figured out this problem at the end of the 2nd day (roughly
16-24 hours of work in). The ssl certificate system (in hindsight was a simple fix) was never mentioned or provided in the readers which caused me great annoyance. If it looks
bad right now don't worry it gets worse. I mailed my teacher about it who neither knew nor cared about the issue at the time so i tried to just make things work by generating
data myself and working out every solution i could.
Whilst doing all of this i learned a lot more about python and found out i'm very easily electrically charged. Yeah AD study's are something sometimes, just not a good something.
So i mentioned it would get worse and a random guy, now i made an essay with proof and an unhealthy dosis of "office passive aggression" to which I was asked and i quote: "How do
you put so much malevolence and hatred in an essay?". Well i showed up hoping my extensive work would at least get me a pass on the subject, I was wrong: My teacher said that due
asking the AI to generate data to test my code he couldn't trust my work even though i could not collect the data myself, to add insult to injury he blatanly ignored his connection
mishap pulling the bureacratic move called "pleading oopsie daisy" and "It's a hbo study you should figure it out yourself bozo". To top it off the other guy had sent nothing
in stating "if it didn't work he couldn't send it" and gave up early on. So to sum it up i spent 3 days debugging something unsolvable at the time and got another shot for my trouble,
the other guy also got another shot for doing absolutely nothing. So the teacher would send another exam (3rd) later that week where he'd solve the connection part to ensure there was
no faulty information or code on our side. Now i knew the other guy was notorious for using AI from which i restrain so my frustration was immense and understandable at this point. Since
i got told to my face that my effort didn't matter in the slightest I opted to bureacraticly engage my teacher to a breaking point from that point on to ensure he would not pull any shenanigans
like this again. (I continue this practice to this day.)
The third exam i did pass a week later and it felt hollow as a dead piece of bark. The code i wrote changed quite a lot since i copied from github and AI alike if i didn't understand something
since at this point i didn't really give a hoot whether my code was or looked authentic since i got memed on by my teachers so I decided to return similar effort. This marks the beginning of
the time where i stopped caring about how i got my code provided it worked first.
Much like how I started my code i divided everything up in functions but did throw at intergers into a singular file since at this point i did not care anymore. To quickly summarize everything;
The code is given all functions to connect to the local wifi and to the mqtt broker afterwards. The last exam did not care for the ledstrip and just wanted to see a led output so it
has a place alongside the print lines to show if the water was rising or falling. One of the tasks was to write the data of every hour or so to a csv file, for this I used the time of the
watermeter against itself since it only updated every 10-15 minutes and made the pico write the data down every 5th time. I will say that the tricks employed in this code are interesting
since it has a heavy focus on just being lazy but efficient which is a programmer's quota.
.. code-block:: python
import time
import network
from machine import Pin
from simple import MQTTClient
# import csv #i can't figure out why yet but csv disables the whole script
wlan = network.WLAN(network.STA_IF)
wlan.active(True)
wlan.connect("ssid","ssidpwd")
ledup = Pin(16, Pin.OUT)
leddown = Pin(17, Pin.OUT)
time.sleep(5)
print(wlan.isconnected())
# Use the correct MQTT server address and topic
mqtt_server = '825c912987534f048c3fbc28bb6ad943.s2.eu.hivemq.cloud'
topic_sub = b'waterstand'
def sub_cb(topic, msg):
global preval, counter #create all variables used to avoid undefined errors
topic_str = topic.decode("utf-8") # remove unwanted characters using the strip() method https://www.w3schools.com/python/ref_string_strip.asp
# remove unwanted characters using the strip() method
msg_str = msg.decode("utf-8").strip()
print("New message on topic {}".format(topic_str))
# value = msg_str[-4:].replace(';', '') # this is the first method i used to ensure if the leds function worked, this however had problems with slicing giving me characters back which crashed the program
print(f"Received Data: Topic = {topic_str}, Msg = {msg_str}")
# get the last item of the resulting list sorted by ;
value = msg_str.split(";")[-1]
print("Value: ", value)
newval = int(value)
if newval != preval: # compare new value with previous value
if newval > preval:
ledup.on()
leddown.off()
print("value going up")
elif newval < preval:
leddown.on()
ledup.off()
print("value going down")
preval = newval # update previous value
counter += 1
if counter == 4:
csvfile2 = open("data.csv", "a") #turns out write overwrites the entire file and i'm just a moron
# to ensure this works i'm using the stripped string version so no b or /n but ; stays
csvfile2.write(str(msg_str).replace(';', ',') + ",")
print('Data written to CSV file')
# Reset counter
counter = 0
# data = [] #initially i thought i needed a list and to call or clear the last function every time
# # # hoe kom je van de b" en de \n af? zoek dat op.
def connectMQTT():
client = MQTTClient(client_id=b'1061348',
server=mqtt_server,
port=8883,
user=b"racdata",
password=b"herkansingpython2",
keepalive=7200,
ssl=True,
ssl_params={'server_hostname': mqtt_server}
)
client.set_callback(sub_cb)
client.connect()
print('Connected to %s MQTT Broker' % (mqtt_server))
return client
# If failed to connect to the MQTT broker, reset the machine
def reconnect():
print('Failed to connect to MQTT Broker. Reconnecting...')
time.sleep(5)
machine.reset()
# Try to connect to the MQTT broker, if failed, reconnect
try:
client = connectMQTT()
except OSError as e:
reconnect()
preval = 0 # old first value
counter = 0 # Initialize the counter
while True:
# ledup.on()
time.sleep(5)
# ledup.off()
client.subscribe(topic_sub) # subscribe to the topic
time.sleep(1)
What you can take away from all this is that much like the modern workplace hard work does not actually pay, efficient, lazy, idiotproof and preresearched work pays. It's not
about how hard you try or how committed you are it's about if it works and how good it works. The strongest sword wains when the wielder is weak so be smart and disciplined.