ar223yc
  • NEW!
    NEW!  Connect Ideas Across Notes
    Save time and share insights. With Paragraph Citation, you can quote others’ work with source info built in. If someone cites your note, you’ll see a card showing where it’s used—bringing notes closer together.
    Got it
      • Create new note
      • Create a note from template
        • Sharing URL Link copied
        • /edit
        • View mode
          • Edit mode
          • View mode
          • Book mode
          • Slide mode
          Edit mode View mode Book mode Slide mode
        • Customize slides
        • Note Permission
        • Read
          • Only me
          • Signed-in users
          • Everyone
          Only me Signed-in users Everyone
        • Write
          • Only me
          • Signed-in users
          • Everyone
          Only me Signed-in users Everyone
        • Engagement control Commenting, Suggest edit, Emoji Reply
      • Invite by email
        Invitee

        This note has no invitees

      • Publish Note

        Share your work with the world Congratulations! 🎉 Your note is out in the world Publish Note No publishing access yet

        Your note will be visible on your profile and discoverable by anyone.
        Your note is now live.
        This note is visible on your profile and discoverable online.
        Everyone on the web can find and read all notes of this public team.

        Your account was recently created. Publishing will be available soon, allowing you to share notes on your public page and in search results.

        Your team account was recently created. Publishing will be available soon, allowing you to share notes on your public page and in search results.

        Explore these features while you wait
        Complete general settings
        Bookmark and like published notes
        Write a few more notes
        Complete general settings
        Write a few more notes
        See published notes
        Unpublish note
        Please check the box to agree to the Community Guidelines.
        View profile
      • Commenting
        Permission
        Disabled Forbidden Owners Signed-in users Everyone
      • Enable
      • Permission
        • Forbidden
        • Owners
        • Signed-in users
        • Everyone
      • Suggest edit
        Permission
        Disabled Forbidden Owners Signed-in users Everyone
      • Enable
      • Permission
        • Forbidden
        • Owners
        • Signed-in users
      • Emoji Reply
      • Enable
      • Versions and GitHub Sync
      • Note settings
      • Note Insights New
      • Engagement control
      • Make a copy
      • Transfer ownership
      • Delete this note
      • Save as template
      • Insert from template
      • Import from
        • Dropbox
        • Google Drive
        • Gist
        • Clipboard
      • Export to
        • Dropbox
        • Google Drive
        • Gist
      • Download
        • Markdown
        • HTML
        • Raw HTML
    Menu Note settings Note Insights Versions and GitHub Sync Sharing URL Create Help
    Create Create new note Create a note from template
    Menu
    Options
    Engagement control Make a copy Transfer ownership Delete this note
    Import from
    Dropbox Google Drive Gist Clipboard
    Export to
    Dropbox Google Drive Gist
    Download
    Markdown HTML Raw HTML
    Back
    Sharing URL Link copied
    /edit
    View mode
    • Edit mode
    • View mode
    • Book mode
    • Slide mode
    Edit mode View mode Book mode Slide mode
    Customize slides
    Note Permission
    Read
    Only me
    • Only me
    • Signed-in users
    • Everyone
    Only me Signed-in users Everyone
    Write
    Only me
    • Only me
    • Signed-in users
    • Everyone
    Only me Signed-in users Everyone
    Engagement control Commenting, Suggest edit, Emoji Reply
  • Invite by email
    Invitee

    This note has no invitees

  • Publish Note

    Share your work with the world Congratulations! 🎉 Your note is out in the world Publish Note No publishing access yet

    Your note will be visible on your profile and discoverable by anyone.
    Your note is now live.
    This note is visible on your profile and discoverable online.
    Everyone on the web can find and read all notes of this public team.

    Your account was recently created. Publishing will be available soon, allowing you to share notes on your public page and in search results.

    Your team account was recently created. Publishing will be available soon, allowing you to share notes on your public page and in search results.

    Explore these features while you wait
    Complete general settings
    Bookmark and like published notes
    Write a few more notes
    Complete general settings
    Write a few more notes
    See published notes
    Unpublish note
    Please check the box to agree to the Community Guidelines.
    View profile
    Engagement control
    Commenting
    Permission
    Disabled Forbidden Owners Signed-in users Everyone
    Enable
    Permission
    • Forbidden
    • Owners
    • Signed-in users
    • Everyone
    Suggest edit
    Permission
    Disabled Forbidden Owners Signed-in users Everyone
    Enable
    Permission
    • Forbidden
    • Owners
    • Signed-in users
    Emoji Reply
    Enable
    Import from Dropbox Google Drive Gist Clipboard
       Owned this note    Owned this note      
    Published Linked with GitHub
    • Any changes
      Be notified of any changes
    • Mention me
      Be notified of mention me
    • Unsubscribe
    # Light and temperature monitor for drawing the curtains on warm days By Abu (ar223yc) ## Overview This project monitors the temperature and light condition of a south facing room so that the curtains can be drawn when the room is too warm due to sun shining into it. As part of this project, one gets to explore and play around with * using a temperature sensor and a photoresistor * coding in micropython and program a Lopy4 pycom board * using Helium Lorawan network * visualising and monitoring the sensor data using Ubidots. It can take about **5** hours to finish this project following this tutorial. ## Objective ### Purpose The main purpose of the project is to explore and get a hands-on experience of the different components of an Internet of Things (IoT). At the same time, this project also serves monitoring the warm indoor environment during the warm summer days in Sweden. ### **Problem**: During warm summer days (of 2021) in Sweden, the south facing rooms in my apartment gets extremely warm when the sun shines into the room. The trapped heat has no way to escape in the well isolated building and makes the indoor environment less pleasant. Therefore, it is important to draw the curtains on the south facing windows early during the day on sunny days to keep the heat away. ### Approach: As part of the project, a combination of temperature and light intensity sensors were used to monitor the room. The goal is two folds 1. to first understand the correlation between light intensity and temperature numerically. With this insight, 2. one can then set thresholds on these two variables to notify to draw the curtains before the room starts warming up. ## Material used All the components used in the project can be purchased from [electrokit](https://www.electrokit.com). As part of the [IoT course](https://lnu.se/en/course/introduction-to-applied-internet-of-things/distance-international-part-time-summer/), a [bundle](https://www.electrokit.com/produkt/lnu-1dt305-tillampad-iot-lopy4-and-sensors-bundle/) costing 949 SEK has been set up in electrokit that includes Lopy4 board, expansion board, Lora antenna, sensors, breadboard, jumper wires and resistors, among other things. In addition to the bundle, a rechargeable LiPo batteri was bought to be able to power the device. | Component | Price (in SEK) | Purpose | | -------- | -------- | -------- | | Lopy4 + Expansion board 3.0 | Bundle | Microcontroller + development board used for collecting data from the sensor and communicating the data over the network | |LoraWAN antenna|Bundle|To communicate over the Helium LoraWAN network| |Breadboard + jumper wires + resistors|Bundle|For connecting the sensors to the microcontroller and expansion board| |Temperature sensor MCP9700|Bundle| To monitor temperature of the sensor| |Photoresistor|Bundle| To monitor the lighting condition of the room| |[Batteri](https://www.electrokit.com/produkt/batteri-lipo-3-7v-4400mah/) LiPo 3.7V 4400mAh|249| To power the setup away from computer| ## Computer setup The device is programmed using micropython. For someone with experience in python programming, micropython is more or less straighforward to use. The operating system used for the project was linux (ubuntu). Below the procedure for setting up the environment is provided. Note the steps below can be done with development board + expansion board connected to the computer using a USB cable, without having to setup the rest of the circuit with sensors. **Things to setup** * Update the firmware of the Lopy4 using the procedure [here](https://docs.pycom.io/updatefirmware/device/). If one does not succeed with the update, one can choose the "**legacy**" for "**Type**". If one would like to send the data over wifi to Pybytes, register the device at [pybytes](https://pybytes.pycom.io) during this update step. * Install [node.js](https://nodejs.org/en/download/) using **sudo apt install nodejs**, a prerequisite for pymakr. * IDE used for this project is [Visual Studio Code](https://code.visualstudio.com/download) (VS code). * In VS code, install both [python](https://marketplace.visualstudio.com/items?itemName=ms-python.python) and [pymakr](https://marketplace.visualstudio.com/items?itemName=pycom.Pymakr) plugins following the instructions [here](https://code.visualstudio.com/docs/editor/extension-marketplace). * Code was flashed into the device through [REPL](https://code.visualstudio.com/docs/python/editing#_run-selectionline-in-terminal-repl). Once the pymakr plugin is installed and the device is connected using USB to the computer, the VS code program on the computer shows the REPL window by default and connects to the USB port. Then to flash the code, one can simply click on **Upload**. * To flash the code into the board when the device is in sleep mode, one can use **CTRL+F** to get the control back in REPL and follow the procedure as in the above command. ## Putting everything together In the below figure, the entire set up is shown. The colored lines in red, green, black, yellow and blue denote the jumper wires. Note that there are no jumper wires between the sensor (temperature and photo resistor) pins to the bread board. Instead, the sensors pins can be directly attached to the bread board. In the circuitry, the same color of the jumper wire indicates that they are all the same point, speaking in ciruits language. That is, all blue wires eventually lead to the **GND** pin on Lopy4 board, and all red wires lead to the **3V3** pin and so on. When using a photoresistor, **10k** ohm pulldown resistor is needed to ensure that there is enough current flowing through the photoresistor for the development board to register. A good explanation of how a pull down resistor works can be found [here](https://electronics.stackexchange.com/a/70012). This setup has many messy jumper wires making the setup not stable when moved around and hence not suitable for production. It is possible to do some soldering to make the setup stabler. ![Setup](https://i.imgur.com/5ZjMy3P.png) ## Platform The platform used for data visualisation is cloud based [Ubidots STEM](https://ubidots.com/stem/) which can be used for free for educational purposes. With ubidots, there is a possibility to visualise data from different sources - pycom using wifi and helium using Lora in this project. More on this will be discussed in the subsequent sections. The platform has limited options for visualising the data, compared to what one can do with a few lines of python code using [matplotlib](https://matplotlib.org) library. When trying to visualise two variables in the same plot, only possibility available is **scatter** with no possibility to label or scale the axes. With the ubidots account, when setting up the trigger events, one can only set the event based on one variable. Once the correlatin between the light and temperature is understood, it might be possible to combine the temperature and light intensity into one variable during decoding and just set an event trigger based on this new variable. Note that in ubidots, when changing the payload decoding with desired variable names, it can take a few minutes before the variables become available in the dashboard. ## The code Once the computer is setup with all the installations and the circuit board is put together, the next step is to code. The code snippets used for the project are provided below. The snippets are discussed in different categories. Whenever good tutorials are available for the specific steps, the links are attached. ### Setting up the networks * For connecting the pycom decide over wifi (to ubidots specifically in this project), one can follow the procedure [here](https://help.ubidots.com/en/articles/961994-connect-any-pycom-board-to-ubidots-using-wi-fi-over-http). ```{python} from network import WLAN import urequests as requests import machine import time TOKEN = "Assign_your_Ubidots_token_here" #Put here your TOKEN DELAY = 1 # Delay in seconds wlan = WLAN(mode=WLAN.STA) wlan.antenna(WLAN.INT_ANT) # Assign your Wi-Fi credentials wlan.connect("wifi-SSID-here", auth=(WLAN.WPA2, "wifi-password-here"), timeout=5000) ``` * For connecting to the LoraWAN network, one can use code snippets from [here](https://docs.pycom.io/tutorials/networks/lora/lorawan-otaa/). In this case, **app_eui** and **app_key** are [obtained](https://docs.pycom.io/gettingstarted/registration/lora/helium/) from the LoraWAN network one chooses to use - Helium for this project. ```{python} from network import LoRa import socket lora = LoRa(mode=LoRa.LORAWAN, region=LoRa.EU868) app_eui = ubinascii.unhexlify('68645756JHJKHJKJKH') app_key = ubinascii.unhexlify('B7887BN78H7676786786H786') lora.join(activation=LoRa.OTAA, auth=(app_eui, app_key), timeout=0) # create a LoRa socket s = socket.socket(socket.AF_LORA, socket.SOCK_RAW) # set the LoRaWAN data rate s.setsockopt(socket.SOL_LORA, socket.SO_DR, 5) ``` ### Reading the data from sensors ```{python} from machine import ADC # pins used on the board for these sensors temp_pin = 'P17' ldr_pin = 'P16' ######################################################## # For reading from temperature sensor adc1 = ADC() temp_adc = adc1.channel(pin=temp_pin) # pin where the sensor is connected def temp_measure(): millivolts = temp_adc.voltage() celsius = (millivolts - 500.0) / 10.0 return celsius celsius = temp_measure() ######################################################## # For reading from photoresistor ldr_nbits = 12 # no of bits to represent the light intensity. Here the value ranges from 0 to 4095 adc2 = ADC(bits=ldr_nbits) ldr_adc = adc2.channel(attn=ADC.ATTN_11DB, pin=ldr_pin) def light_measure(): max_light = (2**ldr_nbits) value = max_light - ldr_adc() # flip the values such that high value = bright light and vice versa value = value * 100 // max_light # convert to % return value light = light_measure() ``` ### Sending the data over the networks * To send data over wifi to ubidots, one can follow the tutorial [here](https://help.ubidots.com/en/articles/961994-connect-any-pycom-board-to-ubidots-using-wi-fi-over-http). Using the function **post_var**, the code snippet simply becomes ```{python} post_var("pycom", light, celsius) time.sleep(DELAY) ``` * To send over LORA, one needs to pack the data into bytes. In this case, 3 bytes of data are used as described in the comments below: ```{python} # > = big-endian # h = Temperature (2 bytes, 16 bits, signed) Range: −32,768 to 32,767 # B = Light (1 byte, 8 bits, unsigned) Range: 0 to 256 # Note celsius multiplied by 100 before making into an integer so that two decimal places can be retained. payload = struct.pack('>hB', int(celsius * 100), int(light)) s.send(payload) ``` ### Putting the device to sleep In this project, sensor data is sent over wifi and/or loraWAN. As there are [limitations](https://lora.readthedocs.io/en/latest/#in-europe) on the airtime when it comes to using loraWAN network, data is sent over loraWAN only once every 15 minutes. Over wifi, the data is sent every minute. Therefore, the readings from the sensors are obtained and the device is put to sleep every minute. Here the code blocks described in the previous sections are skipped to avoid repetition. ```{python} n_sleep_seconds = 60 n_mins = 0 # counter to count number of mins since last lora transmission while True: # add code for reading sensor data # send over wifi if wlan.isconnected(): # can be moved outside while # add code for sending over wifi # send lora msg only every 15 mins if n_mins == 14: if lora.has_joined(): # can be moved outside while # add code for sending over lora n_mins = 0 # reset the number of mins time.sleep(n_sleep_seconds) # send every min over wifi, if available n_mins += 1 ``` In the above snippet, one can move the lines of code which check if wifi and/or lora are connected to outside the **while** loop if one prefers to start the whole setup only when both the connections are available. A word of warning when it comes to power consumption is that sending data over wifi drains the battery, hence it is recommended to use when the setup is connected to the computer through USB. Instead, one can also increase the time for sleep by changing the variable **n_sleep_seconds**. Naturally, in that case, the number of minutes between successive Lora transmissions scales accordingly. ## Transmitting the data / connectivity As mentioned in the previous section, the data is transmitted to the cloud using both wifi and Lora. In case of Lora, the data is packed into 3 bytes (2 for temperature in celsius with 2 decimal places and 1 for light%). Over wifi, the data is sent every min and over Lora, data is sent every 15 minutes. For more details on the coding of this part, refer to the above section. With wifi-pycom-ubidots setup, [http](https://help.ubidots.com/en/articles/961994-connect-any-pycom-board-to-ubidots-using-wi-fi-over-http) protocol is used. With Lorawan-helium-ubidots setup, [webhooks](https://docs.helium.com/use-the-network/console/integrations/ubidots/) protocol is used. Following these two links, one basically gets both the options under **Ubidots->Devices**. ## Presenting the data ![Ubidots dashboard](https://i.imgur.com/liG562h.png) The dashboard is built following the procedure in [this page](https://help.ubidots.com/en/articles/2400308-create-dashboards-and-widgets). To see the Helium variables for this project, one needs to click on the Helium plugin in Ubidots and add the below snippet to the **decoded_payload** such that the **temperature** and **light** variables can be unpacked based on the packing during transmission. ```{python} decoded_payload['temperature'] = (bytes[0] << 24 >> 16 | bytes[1]) / 100 # division by 100 to get the 2 decimal places decoded_payload['light'] = bytes[2] ``` The dashboard shows, from left to right * the current temperature and light condition sent over Lora * the trends of temperature and light conditions sent both over lora (orange) and wifi (red line) * and a scatter plot to see the relation between temperature (on x-axis) and light (on y-axis). In the plot in 2nd row 2nd column, one can see the repeating pattern showing the variations of light over several 24 hour cycles. In the first few days of the project when the data was not yet uploaded to the cloud (and hence not in the plots), the light intensity was at 100% on the sunny days. Note that the wifi was used only for a short period for this project and hence, the limited number of data points. Ubidots does not seem to have limit on how long the data can be preserved. However, it has a [limit](https://help.ubidots.com/en/articles/636666-how-many-dots-can-i-send-with-ubidots-stem) of 5000 on how many dots (data points) one can send in a day. One of the goals of the project is to understand the relation between the light intensity due to sun shining into the room and the temperature of the room. The data obtained so far is presented in the below image (temperature in Celsius on x-axis and light in % on y-axis). ![Temperature vs light](https://i.imgur.com/gtF7K1A.png) Unfortunately, the days got colder and cloudier between the days when the setup was ready and this tutorial was written. Hence, there are fewer dots in the top right corner of the plot. Ideally, once enough data points are available, one can set a threshold on the light and temperature and trigger a notification based on that. For now, an event is setup within ubidots following procedure [here](https://help.ubidots.com/en/articles/1445537-events-creating-conditional-events-and-alerts) such that an email is received whenever the temperature exceeds certain value (chosen to be 25 C for the sake of this tutorial). Ideally, the event should depend on both temperature and light condition. But due to Ubidots STEM limitation mentioned before, the event can only depend on one variable. ## Finalizing the design There are two key results from the project. First is the scatter plot shown above that is useful for understanding the correlation between the sun shining and the heat in the room. Second is the event notification based on this data, which right now is an email notification as shown below based on temperature. ![Email notification](https://i.imgur.com/KAbSIDG.png) Even though the project is not 100% complete when it comes to setting the trigger, it is still on a good path to understanding the indoor climate. The immediate next step from here is to collect more data and set up the right thresholds for the email notification. An advanced step is to also add the actuation step to the set up to automate drawing the curtains using stepper motors similar to the idea in the project in [this link](https://www.youtube.com/watch?v=nrUu21NXrx0).

    Import from clipboard

    Paste your markdown or webpage here...

    Advanced permission required

    Your current role can only read. Ask the system administrator to acquire write and comment permission.

    This team is disabled

    Sorry, this team is disabled. You can't edit this note.

    This note is locked

    Sorry, only owner can edit this note.

    Reach the limit

    Sorry, you've reached the max length this note can be.
    Please reduce the content or divide it to more notes, thank you!

    Import from Gist

    Import from Snippet

    or

    Export to Snippet

    Are you sure?

    Do you really want to delete this note?
    All users will lose their connection.

    Create a note from template

    Create a note from template

    Oops...
    This template has been removed or transferred.
    Upgrade
    All
    • All
    • Team
    No template.

    Create a template

    Upgrade

    Delete template

    Do you really want to delete this template?
    Turn this template into a regular note and keep its content, versions, and comments.

    This page need refresh

    You have an incompatible client version.
    Refresh to update.
    New version available!
    See releases notes here
    Refresh to enjoy new features.
    Your user state has changed.
    Refresh to load new user state.

    Sign in

    Forgot password
    or
    Sign in via Google Sign in via Facebook Sign in via X(Twitter) Sign in via GitHub Sign in via Dropbox Sign in with Wallet
    Wallet ( )
    Connect another wallet

    New to HackMD? Sign up

    By signing in, you agree to our terms of service.

    Help

    • English
    • 中文
    • Français
    • Deutsch
    • 日本語
    • Español
    • Català
    • Ελληνικά
    • Português
    • italiano
    • Türkçe
    • Русский
    • Nederlands
    • hrvatski jezik
    • język polski
    • Українська
    • हिन्दी
    • svenska
    • Esperanto
    • dansk

    Documents

    Help & Tutorial

    How to use Book mode

    Slide Example

    API Docs

    Edit in VSCode

    Install browser extension

    Contacts

    Feedback

    Discord

    Send us email

    Resources

    Releases

    Pricing

    Blog

    Policy

    Terms

    Privacy

    Cheatsheet

    Syntax Example Reference
    # Header Header 基本排版
    - Unordered List
    • Unordered List
    1. Ordered List
    1. Ordered List
    - [ ] Todo List
    • Todo List
    > Blockquote
    Blockquote
    **Bold font** Bold font
    *Italics font* Italics font
    ~~Strikethrough~~ Strikethrough
    19^th^ 19th
    H~2~O H2O
    ++Inserted text++ Inserted text
    ==Marked text== Marked text
    [link text](https:// "title") Link
    ![image alt](https:// "title") Image
    `Code` Code 在筆記中貼入程式碼
    ```javascript
    var i = 0;
    ```
    var i = 0;
    :smile: :smile: Emoji list
    {%youtube youtube_id %} Externals
    $L^aT_eX$ LaTeX
    :::info
    This is a alert area.
    :::

    This is a alert area.

    Versions and GitHub Sync
    Get Full History Access

    • Edit version name
    • Delete

    revision author avatar     named on  

    More Less

    Note content is identical to the latest version.
    Compare
      Choose a version
      No search result
      Version not found
    Sign in to link this note to GitHub
    Learn more
    This note is not linked with GitHub
     

    Feedback

    Submission failed, please try again

    Thanks for your support.

    On a scale of 0-10, how likely is it that you would recommend HackMD to your friends, family or business associates?

    Please give us some advice and help us improve HackMD.

     

    Thanks for your feedback

    Remove version name

    Do you want to remove this version name and description?

    Transfer ownership

    Transfer to
      Warning: is a public team. If you transfer note to this team, everyone on the web can find and read this note.

        Link with GitHub

        Please authorize HackMD on GitHub
        • Please sign in to GitHub and install the HackMD app on your GitHub repo.
        • HackMD links with GitHub through a GitHub App. You can choose which repo to install our App.
        Learn more  Sign in to GitHub

        Push the note to GitHub Push to GitHub Pull a file from GitHub

          Authorize again
         

        Choose which file to push to

        Select repo
        Refresh Authorize more repos
        Select branch
        Select file
        Select branch
        Choose version(s) to push
        • Save a new version and push
        • Choose from existing versions
        Include title and tags
        Available push count

        Pull from GitHub

         
        File from GitHub
        File from HackMD

        GitHub Link Settings

        File linked

        Linked by
        File path
        Last synced branch
        Available push count

        Danger Zone

        Unlink
        You will no longer receive notification when GitHub file changes after unlink.

        Syncing

        Push failed

        Push successfully