hp222mg
    • 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

      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.
      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

    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.
    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
    ## How to use MQTT to publish temperature data as well as displaying it on discord using webhook. By: Henrik Paldán, hp222mg # Introduction This tutorial has as its final goal to display temperature data on a discord server but is a good way to being introduced to using the MQTT protocol as well as webhooks along the way. The MQTT protocol is a fairly simple way of having devices communicate with each other via a publish/subscribe system. Being able to send and receive data between devices is a first step of actually using data to not only measure the surroundings but actually use these measurements as inputs to other devices to perform various tasks, this could as an example be to signal a watering system to water when the moisture sensor signals that its dry or activating your AC when the room temperature is above a certain level. So this tutorial is a first step in starting to actually use measurement data as inputs to other devices. Webhook is also another way of sending data which can be useful for example if the goal is to publish it to several people in an easy way or having it more easily available on your phone. Completing this whole tutorial will take approximately 3 hours assuming that all hardware and software works exactly as planned (which it rarely does). # Objective This project is useful for anyone that is interested in collecting their room temperature data and want the possibility to allow other devices to subscribe to that data in order to control them in someway, one way to use the temperature data is to have a servo connected to a Pycom device that closes the curtains if the temperature reaches above a certain point. The intended end goal for the project was to connect a smart wifi plug to a fan and having the smart wifi plug subscribe to temperature sensor data, then during the night while everyone is asleep the fan would switch off once the room temperature goes below a certain point saving energy as well as reducing fan noise giving a better nights sleep, however it proved harder than expected to get access to the chosen wifi plug. While it was difficult to subscribe from a wifi plug it proved easier to subscribe via a pycom device, which is also showed in the tutorial so it is a useful guide for anyone that wants to transmit data between devices wirelessly via a MQTT protocol. As a final touch the webhook connected from discord to Adafruit is another rather easy way to treat your data. # Material * Pycom LoPy4 device The Pycom device was used to gather data from the temperature sensor and connect to internet via wifi in order to send the data. It is a good general purpose device for gathering in sensor data and transmit it via different channels like wifi, bluetooth, LoRa and SigFox. * Breadboard The Breadboard was used to more easily connect the sensor to the Pycom device. * MCP9700 TO-92 Temperature sensor The sensor was used to measure the room temperature and transmit the data to the Pycom device. * wires The wires were used to connect all components. All of the material was purchased on electrokit.se as a part of a bundle that cost in total 949 sek but the temperature sensors are incredibly cheap and can be purchased separately for around 15 sek, the rest can probably be purchased for a few hundred as well. # Computer setup * IDE: The chosen IDE was VS Code since it is easy to get acquinted with and have a plugin called Pymakr that is used to upload code directly to the Pycom device which is incredibly useful. How to get started: First of all download VS code from the internet (https://code.visualstudio.com/Download) and install it. Then install pymakr as an extension. Then you also need to install Python since the Pycom device runs on micropython, Python can be downloaded here (https://www.python.org/downloads/). You also need Node.js in which is a package for running javascripts, it can be found here (https://nodejs.org/en/). Once everything is up and running you should update the firmware on your Pycom device, instructions on how to do that. # Putting everything together The only hardware connections that are needed to make is to connect the Pycom device to the temperature measurement board and connect the Pycom to a power source, during the tutorial the easiest is to connect it to a computer where the code is uploaded from since it also works as a powersource but once the code has been uploaded to the device any usb connection works. Here is a simple picture of how the connections are made: ![](https://i.imgur.com/C6xWT7i.png) # Platform The platform used is called Adafruit, the main reason for this is that it was used in a example found on a webpage about MQTT for Pycom devices (https://docs.pycom.io/tutorials/networkprotocols/mqtt/). It is very user friendly with different choices for graphical representation. Still though any platform that works as a broker for the MQTT protocol works and there are several others out there, none of which I have tried. Other bonuses with Adafruit is that it is also free and has a simple way of connecting to the data feed via webhooks. A downside is that there is a limitation on the frequency of which you can send data to it. If you wish to scale up with multiple clients that publish and subscribe to data it is possible to upgrade to Adafruit+ but then it will no longer be free. # The code The most important code part is the library for MQTT protocol for the Pycom device. This can be found on the Github library for Pycom devices here (https://docs.pycom.io/tutorials/networkprotocols/mqtt/), there is also a code example from where a lot my code was taken since I felt that the documentation was a bit lacking, the code example can be found here: (https://docs.pycom.io/tutorials/networkprotocols/mqtt/). Something that was a bit bothersome about the code and the library is that when subscribing to a topic there is a function in the library used to get access to the message, this one: ```python def check_msg(self): self.sock.setblocking(False) return self.wait_msg() ``` However it turns out that to use the library you need to create a function that is used in the library in order to treat the message, in the example it looks like this: ```python def sub_cb(topic, msg): print(msg) # and then further below this line of code: client.set_callback(sub_cb) ``` The problem with this one is that it only prints the message and doesn't give you access to it, and since the function you define is being used in another function you can't simply get access to it with a return statement. My solution was like this: ```python= Q = b'0' def sub_cb(topic, msg): global Q Q = msg # And then further below where it receives the data: client.check_msg() Q = float(Q) ``` Here it creates a float variable from a byte object but the byte object can really be converted to anything depending on what you datatype you are sending. This is the only strange thing using the given library for MQTT on the Pycom. Also worth noting that the main goal of this tutorial isn't to subscribe which I just showed how to do but to publish it. When publishing data the only thing worth noting is that the format needs to be a string so any other datatype needs to be converted to a string before being sent. Another good thing to know is that a formula was used in order to convert the temperature from the temperature sensor to celsius degrees, this code looks like this: ```python= celsius = (milliVal - 500.0) / 10.0 + 62 ``` Please note that because of the cheapness of the temperature sensor the correct temperature can sometimes be a bit off and is not guaranteed to show the correct room temperature. # Transmitting the data / connectivity Transmitting the data is the most interesting part of this project, as previouslyt mentioned it was done using the MQTT protocol. The MQTT protocol is a very simple lightweight protocol that is very commonly used to send data, in this project it is done through wifi but it would probably be just as easy to send it through some other channel. There are a few terms that is good to know with the MQTT protocol: * Subscribe/publish Subscribe means that you want to get data from a topic and publish is that you want to put data to a topic. * Client A client is an entity (usually a computer of some sort) that can either publish data to a topic or subscribe for data from a topic. * Topic A topic is a channel where data is being transferred, so a client can either publish to a topic or subscribe to a topic. * Broker A broker is a program that handles all of these topics and clients and makes sure that everything that is suppose to be published is published and everything that is supposed to be subscrbed to is being subscribed to. So what is being done here is that the pycom device (client) is using a library to publish data on Adafruit (broker) through a feed called "roomTemperature" (topic). Then theoretically any device like a fan (another client) can subscribe to this topic and get access to the data. Then a webhook is being used to further transmit the data from Adafruit to discord. In this tutorial the temperature is being sent every hour or so. Due to MQTT being very lightweight the energy consumtion for this project shouldn't be that much. # Presenting the data The data is displayed both on Adafruit and on discord. On discord for being able to monitor the temperature remotely in an easy way and on Adafruit because it has better ways of presenting it in a graphically appealing way. Here is the temperature on discord: ![](https://i.imgur.com/DETnDRh.png) This picture is taken from when trials still are being made and thats why it sends every 10 minutes. Here is a picture of the more graphical presentation from Adafruit:![](https://i.imgur.com/d50UeUA.png) This picture is also taken in a time where everything wasn't quite in place hence the wild data values. The data is stored on Adafruit for 24 hours before being discarded. In Adafruit it is also easy to condition the webhook messages as for an example it could give an alarm if the data reaches above some threshold. # Finalizing the design The whole code can be found on Github on this link: https://github.com/hpaldan/IOT_SummerCourseProject_2021 This is the end product hardware: ![](https://i.imgur.com/dlFGXeA.jpg)

    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

    By clicking below, you agree to our terms of service.

    Sign in via Facebook Sign in via Twitter Sign in via GitHub Sign in via Dropbox Sign in with Wallet
    Wallet ( )
    Connect another wallet

    New to HackMD? Sign up

    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