*Jonathan Eriksson, je224fn Mechanical Engineering student* --- # Overview When developing an air-compressor, testing will ultimately have to take place in order to evalute the capability of the compressor. Several mechanical quantaties are of interest such as pressure, angular speed and torque. These quanteties can be used to calculate the compressor efficency, maximum pressure etc. This project consists of building a testing rig equipped with sensors, capable of gathering the data of interest. The data is then used for further calculations and the results sent to a cloud service and visualized in graphs. Do you want to know how good your 3D-printed aircompressor is? Do you want to send the data to the internet for visualization? This tutorial is for you! Estimated time: Several days but not a whole week --- # Objective This project was choosen to further understanding of IoT and to integrate mechanical solutions into an IoT system. Also, mechanical engineering and IoT is fun. Primarly, this project gives an introduction to IoT, sensors and programming in python. Secondarly, skills in CAD and mechanical anlysis are needed but can be learnt by the engineer a long the way. The purpose is primarly to learn and have fun, but hopefully also to test an air-compressor and send the data to the internet. This project might give insight into the difficullty of integrating mechanical systems and IoT. A lot of 3D-printing will be done wich will give the engineer higher profficency in 3D-printing. Most importantly the engineer will get a better understanding of how sensors, communication protocols and IoT works. --- # Material **List of Materials** | Part | Purpose | Where to find - Price | | -------- | -------- | -------- | | 1x Rasperry Pi Pico W | Controll sensors and send data | [Link](https://www.electrokit.com/produkt/raspberry-pi-pico-wh/) - 109 SEK | |1x Breadboard|Connecting Pico to sensors|[Link](https://www.electrokit.com/produkt/kopplingsdack-840-anslutningar/) - 69 SEK| |20x male-male wires (breadboard compatible) | Connecting electonics|[Link](https://www.electrokit.com/produkt/labbsladd-20-pin-15cm-hane-hane/) - 29 SEK| |15x male-female wires (breadboard compatible) | Connecting electonics|[Link](https://www.electrokit.com/produkt/labbsladd-20-pin-15cm-hona-hane/) - 29 SEK| |1x 10kΩ resistor|For setting up the force sensor (FSR)|[Link](https://www.electrokit.com/produkt/motstand-1w-5-10kohm-10k/) - 3 SEK| |1x Micro B USB-cable|Connecting Pico to computer|[Link](https://www.electrokit.com/produkt/usb-kabel-a-hane-micro-b-5p-hane-1-8m/) - 19 SEK| |1x Sparkfun Qwiic MicroPressureSensor|Sensor for reading pressure data|[Link](https://www.electrokit.com/produkt/trycksensor-mini-0-06-2-5bar/) - 269 SEK| |1x Optical Sensor (Fork)|Sensor for reading angular speed|[Link](https://www.electrokit.com/produkt/modul-med-optisk-lasgaffel/) - 39 SEK| |1x Force sensitive resistor (FSR)|Sensor for reading force|[Link](https://www.electrokit.com/produkt/tryckkansligt-motstand-0-3/) - 99 SEK| |1x 24V DC-motor|Motor for turning the compressor|Bought on FB marketplace - 50 SEK. Amazon: [Link](https://www.amazon.se/Borstad-Conversion-Elektrisk-Skoter-Motorcykel/dp/B0BHTP542H/ref=sr_1_9?keywords=dc+motor+24v+dc+100w&s=sporting-goods&sr=1-9)| |2x Battery 12v 5Ah |Powering the motor|[Link](https://www.biltema.se/bil---mc/fordonsbatterier/mc-batterier/smf-batterier/mc-batteri-smf-12-v-5-ah-113-x-70-x-105-mm-2000029838) - 2x 239 SEK| |1x MD13S 13Amp DC Motor Driver|Controlling the motor|[Link](https://www.electrokit.com/produkt/motordrivare-1-kanal-6-30v-13a/) - 290 SEK| |4x 8x22x7mm Bearings|Holding the axels between compressor, planetgear and motor|[Link](https://www.biltema.se/bil---mc/bilreservdelar/kullager/kullager-608zz-8x22x7-mm-2000050564) - 4x 54.90 SEK| |15x M5 Hex screw with nut|Mounting all the mechanical components to plywood|Local hardware store - A few SEK |1x 400x400x7mm plywood |Mounting all the components to|Local hardware store - A few SEK| |Capability to 3D-print|Manifacture mechanical components|Buy: [Link](https://www.inet.se/produkt/3506894/creality-ender-3-v2-neo) or 3D-printing service: [Link](https://printmaker3d.com/)| The Rasperry Pi Pico WH (Fig 1) is a microcontroller well suited for many IoT applications. As we will use both digital and analog sensors we need a microcontroller with pins that have the right capabillity. ![](https://hackmd.io/_uploads/ByeLSK2_h.jpg) *Raspberry Pico WH - Fig 1* **Pin requirement** Sparkfun Qwiic MicroPressureSensor uses I2C protocol. FSR will output an analog signal wich will need to be converted to digital via an analog to digital converter(ADC). Optical sensor outputs digital signals. * I2C-pins ![](https://hackmd.io/_uploads/rJj5rFn_n.jpg) *Sparkfun Qwiic MicroPressureSensor - Fig 2* * ADC-pins ![](https://hackmd.io/_uploads/SJJeIK3un.jpg) *Force sensitive resistor (FSR) - Fig 3* * General output input-pins ![](https://hackmd.io/_uploads/SyAc8Y2u3.jpg) Optical sensor - Fig 4 **The pico have all of these pins!** **Sensor purpose** *Sparkfun Qwiic MicroPressureSensor* in Fig 2 is a digital pressure sensor that connects to a 2.5mm rubber tube. We will use this to measure the pressure in the airtank where we have compressed air. *Force sensitive resistor (FSR)* in Fig 3 is a resistor that changes resistance when the applied force is changed. This will be used to measure the torque required to turn the compressor. The planetary gearbox have three axels. One input shaft, one output shaft and the gear ring. The gear ring needs to be fixed in order for the gearbox to work. Fixing the outer ring will cause a reaction torque when a torque is applied to the input and output shafts. We will use this to our advantage. Fixing the outerring in a way that it pushes on the FSR will enable us to calculate the torque on the outer ring, multiplying force by lever (distance from sensor to the central axis of the gearbox). We now know the torque on the outer ring and using two formulas we will be able to calculate the torque on the input shaft and the output shaft. *Optical sensor* in Fig 4 is a digital sensor that outputs a 1 if and object is between the reading fork and a 0 otherwise. We will put a rod orthogonal to one of shafts from the gearbox that can pass through the fork. The first time the rod passes it will start a timer. The second time it passes it will stop the timer. In this way we can calculate the angular speed of the shaft. Now we will be able to know the pressure that the compressor achives but also the power that is put in the compressor by multiplying angular speed and torque. **What is a motorcontroller?** A motor controller is (obviously?) a way of controlling one or more motors. The motor i have choosen has a maximum power output of 100 watts at 24 volts. The output current will be power devided by voltage wich is over 4 amps at maximum power (*Electrical calculations?). The pico in it self is not able to provide this to the motor. Therefore we need the right power supply (batteries) while at the same time being able to regulate the power to the motor. This is what a motorcontroller is for. The motorcontroller needs to be choosen so it can handle the voltage and amps of the motor. **The motor** For turning the compressor we will need a motor and corresponding batteries. You can choose any motor as long as it has enough power to turn the compressor that is being tested. Also worthy of note is the planetary gear that will be put between the compressor and the motor. This will enable you to have a lower torque motor. In this project the planetary gear has a gear ratio of 4. This means that the torque from the motor can be 1/4th of the torque required to turn the compressor. Often you won't know the torque required for turning the compressor so it is strongly recommended that you use a motor with plenty of power. I choose a 100 Watt motor wich is about the same power as a low-power electric scooter. *Also make sure that the Motor Controller can handle the voltage and amps of your choosen motor (look in the datasheet).* --- # Computer Setup **Thonny** For this project we will use Thonny as the integrated development environment (IDE). Meaning this is the program where we write and save code to the pico. Thonny has been developed for beginners and is easy to understand and use. One drawback is lower functionallity. **Step 1 - Installing Thonny on computer** Dowload and install the latest version of Thonny [here](https://thonny.org/). (Note that the latest installer for thonny also installs Python automatically, wich is needed.) **Step 2 - Connect pico in BOOTSELL-mode** Connect your raspberry pico to your computer in "BOOTSEL-mode". This is done by holding down the BOOTSEL button for a few seconds while you connect the pico to the computer via the USB cable. The computer will now register the Pico as a storage device (flash drive). Open up the storage folder for the pico. **Step 3 - Flashing firmware** Download the latest UF2-file [here](https://micropython.org/download/rp2-pico/) and copy the file to the pico storage folder. This file will install micropython on the pico. **Step 4 - See if Thonny works** Open up Thonny on your computer and make sure the pico is connected. In the command prompt there should be no error messages (if there is try clicking the red button in the upper left corner to establish a connection). Click File -> New to open a empty document. To save the file click File -> Save and choose to save it to the pico. In the document write `print("Hello world")` and save. Click the green button in the upper left corner to run the script. In the command prompt it should say `Hello world` Click the red button in the upper left corner to stop the script, this should be done after each time you have run a script for testing. You have now run your first script on the pico. **Step 5 - Saving libraries** In order to control sensors, libraries are convinient. A library is a file that you can save on a device (pico) and import into a script in order to use the functions that the library contains. I have writen a simple library for the Sparkfun Qwiic MicroPressureSensor that you can download [here](https://github.com/jontehero1/SparcFun_MicroPressure_sensor_MicroPython_Library) called "pressure_sensor.py". In Thonny click File -> New and copy the code from the link provided. Click File -> Save and choose to save on the pico. Now you have the library on the pico. When writing a script you can import the library with `import pressure_sensor` (If you saved the file by the original name). --- # Putting everything together The curcuit diagram below shows how everything should be connected. The breadboard is very convinient to use when connecting everything. ![](https://hackmd.io/_uploads/rk7ZVB0On.png) All the ground (GND) connections can be connected to any ground on the pico, wichever is most convinient. The FSR is setup in a voltage devider configuration with a 10 000 Ohm resistor. The pico reads voltage and therefore we need a voltage devider in order to get a reading of the corresponding resistance in the FSR. Other resistors can be used to change the sensitivity range of the FSR. Also other curcuits can be built to change the functionality of the FSR (look in the datasheet). The choosen motorcontroller has a connector attached wich won't fit with the cables or breadboard. Either cut of one end of the cable and solder the connecting wires to each wire on the cable or buy an adapter. **When connecting the battery to the motorcontroller there might be sparks. Make sure to use batteries that aren't spark sensitive (doesn't produce explosive gases).** This is a development setup. For production a few things might be changed. For example there needs to be a switch for turning of the power between the batteries and the motorcontroller. Also a button for restarting a test cycle and a display with the live data would be nice. Ability to change the maximum allowed pressure and the maximum output of the motor via a button pad would increase functionality. In this setup the pico is powered by a connected computer. A DC-DC converted could be installed between the batteries and the pico instead making the test rig completely wireless. Charging the batteries in development setup can be done using a standard 12V car battery charger (charge batteries individually). For production a AC-DC converter can be installed in order to charge the test rig directly from a wall outlet. Below is a sketch of how the test rig can be setup. CAD-files for planetary gearbox can be found [here](https://grabcad.com/library/planetary-gearbox-ratio-4-1-1). ![](https://hackmd.io/_uploads/SySiE3-F2.jpg) **Estimated power consumption and battery life** {%pdf https://aqua-betteanne-20.tiiny.site%} --- # Platform The platform i have choosen is Adafruit IO. This is a beginner friendly, free, cloud-based platform that is easy to set up and use. Dashboards can be created in order to visualize data and interact with the device with switches, dials etc. Data that has been sent to the platform can be downloaded by the user. There is a limit on how much data can be sent in a certain amount of time (data rate limit) of 30 datapoints per minute. Data is visulized as data vs time. The dashboard is also limited in its scoope and the combined datarate across all feeds are 60 datapoints per minute. The data is only stored on the platform for 30 days. Going forward one might set up a self hosted server for reciving the data from the test rig. This server could be on a regular computer or a single-board computer like the Raspberry Pi 4. This could store the data and increase the the ways the data can be visualized and used. As an example we could automatically plot power vs pressure in order to visualize how the input power to the compressor varies with the airtank pressure. The data could be stored indefinetly and there would be no data rate limit wich is more appropriate for the test rig. The reason for choosing the Adafruit IO platform is strictly because of limited time. Setting up a self-hosted server is not overly complicated and anyone willing could learn how to do it. To set up a MQTT-broker(self-hosted server) use [this tutorial](https://hackmd.io/@lnu-iot/rJr_nGyq5). Use ChatGPT to help with converting the commands into the right syntax for your system. --- # The code **Pressure sensor library** Download [here](https://github.com/jontehero1/SparcFun_MicroPressure_sensor_MicroPython_Library) This library was made from a arduino library by PaulZC for the same sensor. It was converted using ChatGPT and debugged. [Arduino library](https://github.com/sparkfun/SparkFun_MicroPressure_Arduino_Library) ```python= import machine import time from machine import Pin ``` `machine` is used to access the pins on the pico and to use I2C. I2C is a digital way of communicating. It consists of a master (pico) and slaves (pressure sensor). ```python=25 def read_pressure(self): # Read pressure data #First we go to the adress 0xAA in the sensors memory #and set this register to 0. #This will pull the sensor out of standby mode in 5 milliseconds. self._i2c.writeto(self._address, bytes([0xAA, 0x00, 0x00])) time.sleep_ms(5) #We send a 1 as a byte to the sensor in order to tell #the sensor we want to read from it. self._i2c.writeto(self._address, bytes([1])) #4 bytes of data is read with the first one being a #status byte telling the status of the sensor. data = self._i2c.readfrom(self._address, 4) #We take out the 3 last bytes of data wich is the #pressure data pressure_data = data[1:] #Converting the data to integer from bytes. pressure = int.from_bytes(pressure_data, "big", False) # Scale pressure to the desired unit using the function #given in the datasheet Pa = (((pressure - OUTPUT_MIN) * (self._max_Pa - self._min_Pa)) / (OUTPUT_MAX - OUTPUT_MIN)) + self._min_Pa return Pa ``` Function above will be used in our main program to read the pressure sensor value. **Force sensor library** Download [here](https://github.com/jontehero1/LNU_IoT_Compressore_Testing_rig/tree/main) ```python= import machine #Initialize the pin that is being read from pin = machine.ADC(28) lever = 0.0584 #This should be changed to the distance (in meters) #from central axis of the planetary gear to the FSR R = 3 def read_moment(): #Read value from pin value = pin.read_u16() #Conversion from value to force not yet coded, #can be done with experiment + linear regression #These formulas come from moment-equations for planetary #gearboxes #Calculate torque on outer ring M2 = force * lever #Calculate torque on motor shaft M1 = -M2/R #Calculate torque on compressor chaft Mc = -(M2*(-1 + R))/R return M1, Mc, M2 ``` This library is used for calculating the moment on the shafts. Variable R is dependent on planetary gear design and is number of teeth on outer ring divided by number of teeth on solar gear (connected to motor shaft in this case). If the choice of planetary gear isn't changed no changes need to be made in the librar. Your will however need to calibrate the FSR. This could be done using a torque wrench on one of the gear shafts, calculating the moment on the outer ring, converting to force by moment divided by lever. Then taking this value together with resistance of the sensor att that torque and having it as a datapoint. Several of these datapoints needs to be collected and the a interpolation function can be created. One could use the simple "linear regression" on a scientific calculator in order to get the function needed. This works, even though the resistance/force-function is logarhitmic it approximates a linear function. The function then is used to convert the resistance value from the FSR into the forcevalue. **Optical sensor library** Download [here](https://github.com/jontehero1/LNU_IoT_Compressore_Testing_rig/tree/main) This library has a function for reading angular speed. The first time the optical sensor is triggered a timer starts. The second time the timer stops. The angular speed can then be calculated. --- # Transmitting the data / connectivity One datapoint is sent each second wich is at the data rate limit for Adafruit IO. The wireless protocol is Wi-Fi. **Step 1 - Setup Wi-Fi** Down below is the simple function for connecting to Wi-Fi. ```python= import machine import network #secrets contains the Wi-Fi credentials. Storing them #in a seperate file increases security. import secrets from time import sleep def connect(): #Initilize wlan wlan = network.WLAN(network.STA_IF) #Activate wlan wlan.active(True) #Connect to wlan wlan.connect(secrets.SSID, secrets.PASSWORD) #Check if wlan is connected, if not, wait 1 sec #for connection and check again. while wlan.isconnected() == False: print('Waiting for connection...') sleep(1) #Print the adresses of the connection print(wlan.ifconfig()) ``` **Step 2 - Adafruit IO** Create an account on adafruit [here](https://io.adafruit.com/). Navigate to IO -> FEEDS and create a new feed where the data will be sent to. You will need one feed for each category of data. Create one for pressure, angular speed, outer ring torque, motor torque and compressor torque. Navigate to dashboard and create a new dashboard. Create 3 different line chart blocks. **Step 3 - MQTT** The transport protocol is MQTT. MQTT is a very simple messaging protocol that uses low bandwidth. It is simple to set up and use. The library needed for MQTT can be downloaded [here](https://github.com/iot-lnu/applied-iot/blob/master/Pycom%20Micropython%20(esp32)/network-examples/mqtt_ubidots/mqtt.py). To set up the MQTT client in your main program see the code below. Note that in the code below i will only set up for sending to one feed. More feeds should be added. Setup up the credentials. Initilize the client. Read the sensor value. Publish the value to a feed. ```python= from mqtt import MQTTClient import pressure_sensor AIO_SERVER = "io.adafruit.com" AIO_PORT = 1883 #Put in your adafruit username AIO_USER = "your_username" #Find the key by clicking on the yellow key in adafruit #Insert the key below AIO_KEY = "xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx" #Choose any name AIO_CLIENT_ID = "Any_name_will_do" #Navigate to the feed and look for the "MQTT by key" #in the feed info. Insert the key below. AIO_PRESSURE_FEED = "your_username/feeds/pressure-feed-id" #Initilize MQTT client client = MQTTClient(AIO_CLIENT_ID, AIO_SERVER, port=AIO_PORT, user=AIO_USER, password=AIO_KEY) #Connect to server client.connect() #Initilize pressure sensor psensor = pressure_sensor.SparkFunMicroPressure() while True: #Read value from pressure sensor pressure_value = psensor.read_pressure() #Publish the value to your feed client.publish(topic=AIO_PRESSURE_FEED, msg=str(pressure_value)) #Dont forget to sleep to not exceed data rate limit sleep(2) ``` **Why Wi-Fi?** One drawback with Wi-Fi is the high power consumption. But we have choosen batteries that will be able to handle this in a production setup (using a DC-DC converter). The major benefit would be higher data rate capabillities. This benefit is only available if the data is sent to a self hosted server or a cloud-based service with high data rate limits. Setting up a self hosted server is therefore highly recommended. The device range can be lower with Wi-Fi. If the device wanted to be used in an area with no WiFi, one could integrate a USB-port for a wireless modem. The modem would need to have sufficient reception and a fee would need to be paid to a telephone company, but the range of the device would be huge. **Why MQTT?** MQTT is a very lightweight communications protocol that is easy to set up and use. Very popular when using unstable networks. Even when using Wi-Fi the stability of the connection can be a bit unstable when using devices like the pico. It also has the added benefit of an ability to incorporate sefety measures. Which this project could need in the future. --- # Presenting the data Below is how my dashboard looks. ![](https://hackmd.io/_uploads/SJ4BBDgK2.png) The data is saved in the database as soon as it is recived and stored for 30 days. Using adafruit as your database is not recommended for a wireless compressor test rig. This choice was made because of limited time and ease of use for beginners. It would be really cool to build a GUI for controlling the test rig remotely. In our case with adafruit we could add for example a switch to our dashboard and make the appropriate changes to the code for the abillity to start the test rig in adafruit. The compressor rig will be used "hands on" and this type of automation might be a bit redundant. # Finalizing the design **Integration** Integrating a solution into the physical world is always harder than it seems. Because of this many engineers and makers around the world come to appriciate even the simplest elegant products and designs. One should therefore be proud of even the most comical actualization of a solution to a problem. Remember most people doesn't even begin on a theoretical solution. So hats of to all of you who reached something tangible. **This is what i achived** ![](https://hackmd.io/_uploads/SJYqK-Mt2.jpg) As you can see there is no compressor...(yet) The tube to the pressure sensor is easily disconnected because of wrong size... (but it can still hold some pressure) ![](https://hackmd.io/_uploads/rJGRF-zF2.jpg) The FSR (little blue strip underneath planetary gear) isn't glued in place or calibrated... (yet) I was also rushing to get a selfhosted server on a Raspberry Pi 3B+ using mosquitto and Node-red. Everything went well, node-red connected to mosquitto and i was almost done but for some reason i couldn't send or recive any data when using pico. I tried: * Enabling the port in the firewall settings * Making sure the `mosquitto.conf` file was correct * Quadruple-checking username and password * Restarting the MQTT broker * Double checking the ip-adress * Sending data through MQTTExplorer (No success) * Sending data throug the Linux-terminal with `mosquitto_pub` (No sucess) * Add the port as a rule in "Port Forwarding" in my Wi-Fi hub * Using ChatGPT along the way to compensate for my incompetence * Asking more knowledgeable people for help **If anyone has any more ideas please contact me, the future of my 3D-printed compressors depend on it! ;)** In the pictures above i have mentioned a few improvements that should be made. And throughout the report i have mentioned other improvements and now tried the whole "if i make a self-hosted server i will probably get an A" idea. Even though the self-hosted server never worked and i never had time to build the compressor, i'm actually very happy with this project. It was very challenging to do in such a short time period and i have something to look forward to and continue with in the future. [Video presentation](https://youtu.be/mQU15d_oF0Y) # Update I managed to build a simple prototype and test it with the pressure sensor and a power drill. I was laughing about how bear bones it was but here is the results: ![](https://hackmd.io/_uploads/B1SPznNF3.jpg) The axle broke during the test XD ![](https://hackmd.io/_uploads/rJL3z34K2.jpg) This is the data that i gathered. 0.15 bars! One small step for man, a giant leap for humanity!