Posted in raspberrypi, aws

How to send notifications from Raspberry Pi using AWS SNS for FREE

Have you felt the need to be notified by your Rasp when something is happening in your home (and not only)?

Well, I certainly did. I always forgot a lot of things that can be friendly reminded. Like watering the plants, closing the door, leaving the light open, although I don't have a cat or dog, I would definitely have needed to know if they are low on food or water. (and many other situations)

If you want to be notified on your phone, this can get very expensive and complicated. Why spending money on a GSM modem and a prepaid phone card when you can get the same benefits for free using AWS SNS? Luckily, there is another way.

Use the comment section and tell me your thoughts about this. 

AWS prerequisite

If you never had any contact with AWS (Amazon Web Services), you can create an account for free at

But, what is AWS SNS? AWS Simple Notification Service (SNS) makes easier to send notifications to your phone or email address. It allows you to send 100 SMS and 100.000 emails to be sent each month for free (at the moment of writing this). I proved that it’s easy to work with AWS on how to publish temperature and humidity to CloudWatch. You can compare this service with the Observer design pattern.

The first thing that we need it's a way to give permissions to our Rasp to publish SNS topics. In the post mentioned above, I showed how to give permission to the CloudWatch service. The process is very similar, but we need to give access to AWS SNS instead. Please give the following permission policy to your IAM user, AmazonSNSFullAccess. Don't forget to save the AWS access key id and secret access key in a safe place.

After we have the access keys we need to go to AWS SNS Console and follow this tutorial created by AWS to create a topic. After you successfully created the topic, save the topic ARN, we will need it later.

I said that we will send the notifications to our phones and emails, we need to add them as subscribers to the topic that we just created. Use the guidance provided by the AWS to register them. For email addresses don't forget that you have to confirm your registrations, strangely, for a phone, you don't have to confirm that you want to receive notifications.

What do I need to get started?

It's very easy to integrate the AWS SNS functionality in your project. In order to prove this, I will use a project that detects if the door is open or closed. I will modify this project to send notifications with the door status (open/close).

To give you a little context about the project, it uses an ultrasonic sensor to read the distance from the nearest object. When the door is opened/closed the distance increase/decrease as well. To determine if the door status it uses an if/else code block using a fixed distance to compare against. At a first glance this doesn't seem a problem, but if the door is opened, the program will output:

Door Open # 1 notification
Door Open # 2 notifications Door Open # 3 notifications
Door Open # n notifications

Every time this will run, it will send a notification. Because the number of notifications from the free tier is limited we need to make some changes in order to send only 1 message. Even if the money wasn't a problem, it would be very annoying and not cost effective to send so many alerts in a short span of time.

How can I send the messages only once?

After searching a little, the solution that I stumbled upon is to observe the percentage change between 2 consecutive distances (also known as Delta).

\text{Percentage change} = \frac{\Delta V}{V_1} = \frac{V_2 - V_1}{V_1} \times100 .

We put the sensor at 4cm from the door, with the door closed the output is ~4cm. When the door opens, the distance will significantly increase. The reverse applies equally when the door closes, the distance significantly decrease. In this case, significantly means that the distance increase/decrease by more than 100% (you can increase or decrease this value as you like).

Let's suppose for simplicity that we read 4cm and for the next point we read 20cm. You can notice even if from 4cm to 20cm it's not much it will give a huge output (20cm - 4cm)/4cm * 100 = 400%. Because 400 breaches our threshold of 100 we can say that the door is Open or Close.

Note: If the door opens (or closes) very slowly this algorithm won't catch the status change, before implementing this make sure that you don't have any ninja or cats in the house in order to be effective.

Take me to the code

In the below snipped I focused mainly on the AWS part of the code, the part that is focusing on the ultrasonic sensor can be found here

For Python 2 (if you use Python 3 please search for the equivalent commands), in order to be able to run the code, you will need to install the AWS SDK in Python, who is called boto3.

pip install boto3

If you don't have pip you can install it using the following command

sudo apt-get install python-pip

Let's do the most important things first so that we don't forget, replace INSER_AWS_ACCESS_KEY,  INSER_AWS_SECRET_ACCESS, and INSER_TOPIC_ARN with your own.

In order to publish the message to our listeners, we need to use the publish method from the SNS client API. This method has the following parameters that we will use:

  • TopicArn - this is the topic identification (ARN) 
  • Message - the message that will be sent in the email/SMS, be careful with the text size because an SMS allows only 153 characters
  • Subject - (optional) this is used only in the emails (an SMS doesn't have a subject)

For a comprehensive documentation about SNS you can check the following page, you can find details to build more sophisticated systems using this service.

import RPi.GPIO as GPIO
import time
import boto3

TOPIC_ARN = 'INSERT_TOPIC_ARN' # should similar with this arn:aws:sns:us-east-1:1234567890:door-status

# ....
# missing functions/constants can be found here 
# ....

def publish(snsClient, message):
# replace the TOPIC_ARN with your own
response = snsClient.publish( TopicArn=TOPIC_ARN,
Message=message, Subject='Door status' ) print ("Published with id %s " % response) def percentChange(current, previous, difference): increase = current - previous increasePercentage = increase / previous * 100 if increasePercentage > difference: return True return False if __name__ == '__main__': try: snsClient = boto3.client( 'sns', aws_access_key_id=AWS_ACCESS_KEY, aws_secret_access_key=AWS_SECRET_ACCESS, region_name='us-east-1' ) currentDistance=distance() previousDistance=currentDistance while 1: currentDistance = distance() print ("Distance = %.1f cm" % currentDistance) if percentChange(currentDistance, previousDistance, 100): message = "Door opened. Distance greatly increased from %.1f cm to %.1f" % (previousDistance, currentDistance) print (message) publish(snsClient, message) elif percentChange(previousDistance, currentDistance, 100): message = "Door closed. Distance greatly decreased from %.1f cm to %.1f" % (previousDistance, currentDistance) print (message)
publish(snsClient, message) previousDistance = currentDistance time.sleep(1) # close execution by pressing CTRL + C except KeyboardInterrupt: print("Intrerrupted by user") pass finally: print("Program stopped") GPIO.cleanup()

Run the code using the following command on the terminal and press CTRL + C to cancel anytime.



Final thoughts

I hope that you find this useful, AWS SNS is a tool that can come in handy in some situations and has a lot of potential for future projects. 

If you encounter any trouble or have any curiosity, feel free to use the comment section to share your feelings about this.

But most importantly, don't stop learning!

Posted in rasberrypi, hc-sr04

How to detect your door activity using Raspberry Pi and HC-SR04

I plan to hang my Raspberry Pi on top of the door and detect if it was opened or closed. No one will ever pass that door without you knowing (not even the night monsters). To achieve this I will be using a Raspberry Pi Zero along with HC-SR04 distance sensor.

Remember that you are free to leave any comment below for requests/improvements/bugs or anything you would like to discuss.

Hardware used in this project

In this project, I plan to use HC-SR04 ultrasonic sensor to measure distance and it will be connected to the Raspberry Pi Zero. The HC-SR04 can measure a minimum distance of 2cm and a maximum distance of 400cm.

Because the Echo pin is at 5V and the GPIO pins from Rasp are at 3.3V. In order to convert the input voltage to a lower one, we need a Voltage Divider. The schema for it is defined below:

hc-sr04 coonected to raspberry pi with a voltage divider

In order to obtain the desired 3.3V, I have chosen the resistors to be as following R1=1k and an R2=2k (I didn't have a resistor with 2.4k value so I used 2x1k resistors in series). If you don't have 1k resistors don't despair, remember that you need resistors in order to build the 2/3 fraction, another possible combination is R1=2.4k and R2=4.7K. I have detailed how I came to this fraction:

voltage divider formula

If it's hard to follow how the cables are connected in the above image, use this table instead. But don't forget to add the voltage divider.

 HC-SR04Raspberry Pi Zero
2TrigGPIO18 with PWM 1 (PIN12)
3Echo 5VGPIO17 3.3V (PIN11)

The logic behind 

In order to achieve our goal of observing when the door is open or closed, we need to know the distance and a way to know the status of the door. 

How I measure the distance? Before putting the hands of the formula, let's explain a little bit what is happening behind the scene. I'm focusing here mostly on the distance() function defined in the code below. 

The first thing that needs to be done is to notify (setting Trig to True) the sensor of your intention of measuring: "Hey, how far is the nearest obstacle?". Immediately after this, the sensor tries to find the answer for you and will send 8 sonic bursts at 40kHz. After this 'research' of the upfront area, will come with an answer: "Hey, the distance is about HIGH ...wait... STOP."  (Echo pin set to True).

Maybe you wonder how the distance can be measured from this. Even though the only information that the ultrasonic sensor gives is emitting the '1 value' (actually 5V) on Echo pin for a specific duration. Using the duration of the HIGH level multiplied by the sonic speed of 343m/s and everything divided by 2 we will give us the distance in cm.

The first idea that came to my mind was to use the percentage change function to identify if the status of the door, open or close, for simplicity I went with an if statement. For open, I chose the distance greater than 10cm and for close otherwise. A better idea will be to use 

Below you can find all the code associated with this project. I tried to comment everything in order to make it more easily understandable.

#   The Humble Code
import RPi.GPIO as GPIO
import time

# use channel numbers on the Broadcom SOC
# configure your preffered GPIO pins
def distance():
    # send a pulse to the utlrasonic sensor
    GPIO.output(GPIO_TRIGGER, True)
    # The pulse must be of 0.01ms=10uS TTL pulse 
    time.sleep(0.00001) # seconds
    GPIO.output(GPIO_TRIGGER, False)
    # the sensor computes the distance
    # using the time when the emmited wave was sent
    # and the time when it 'bounced' back 
    startTime = time.time()
    stopTime = startTime
    # wait to send sonic burst at 40 kHz
    while GPIO.input(GPIO_ECHO) == 0:
        startTime = time.time()
    # sonic burst finished, waiting for echo
    while GPIO.input(GPIO_ECHO) == 1:
        stopTime = time.time()
    # time difference between start and arrival
    timeElapsed = stopTime - startTime
    # multiply with the sonic speed (34300 cm/s)
    # and divide by 2, the emmited wave and reflected wave
    distance = (timeElapsed * 34300) / 2
    return distance

if __name__ == '__main__':
        while 1:
            currentDistance = distance()
            print ("Distance = %.1f cm" % currentDistance)

            # If the distance is greater than 10cm
            if currentDistance > 10:
                print ("Door open.")
                print ("Door closed.")

        # close execution by pressing CTRL + C
    except KeyboardInterrupt:
        print("Intrerrupted by user")
        print("Program stopped")

Run the code using the following command on the terminal and press CTRL + C to cancel anytime.


Door status on terminal


This can be an interesting way to learn how to use the distance sensor, and if you are not bothered by the sensor hanging in front of the door it's perfect. But this can be solved by hiding it in a place where it can go unnoticed, not necessarily close to the door, it has a range of 400cm that can be used. 

As a next step, you can add notifications via SMS or email with the door status. This way you will know for sure what happened without being close to the monitor. Or you can publish metrics to see how much the door is used for a period of time.

Don't stop learning!

Posted in raspberrypi, aws, cloudwatch

header image

Did you ever wonder how to bring your mini computer to the cloud?

I always was under the impression that the cloud services are very expensive and it would be impossible for people like me to use them. But I was wrong, cloud giants offer several services for free. Even though there are more limited, they can provide value on a personal/home and even startup project. There are many cloud services providers out there: Azure, Amazon Web Services (AWS), Google Cloud, etc. Because of the competition, most of them offer something for free or for a limited period (12 months).

What’s the best service to learn? It should be fun, interesting and easy to use. From so many out there to chose, the only that matched the description was AWS CloudWatch. This product allows us to publish a value at a point in time. If we publish enough points we will end up with a time-series. We can have up to 10 time-series.

For any thought/question/problem, use the comment section and tell me your thoughts on this. 

What's the hardware prerequisite?

raspberry pi dht11 sensor with aws inside

I always start with the hardware, because the only thing that remains is to focus on the code.

For this how-to you are free to choose/imagine any sensor you would like. I have chosen the DHT11 sensor (it’s the only sensor that I have, not much of a choice) that will collect the humidity and temperature. If you are going this way, you will also need 3 wires and a resistor of 6KΩ - 10KΩ (ohm). I know that are components out there which already contain the resistor, if you own one of them, you don't need a resistor.

I the image below shows how the components are connected between them. The good part of this sensor is that it can be connected at 3.3V or 5V (red wire), your choice! The blue wire is the data wire, used to read the values of interest. The resistor needs to be connected between this two pins (red and blue). The black wire is connected to GND. 

Use this table for writing representation of the cable connection that I made. 

DHT11SignalRaspberry Pi Zero
13.3V ~ 5.5V 4 (VCC)
2Data 7 (BCM 4)
3not used 
4Ground 6 (GND)

How do I setup my AWS account?

Although this part looks a little bit scary if you never had any contact with AWS. You don’t have to worry about this, you are in good hands.

The first thing that you have to do is creating your account for free at .

After you log in to the console, you might feel intimidated by the number of services, luckily, we need to use just one, CloudWatch. Maybe I lied, we need to use 2 of them (IAM – Identity and Access Management). Before going on, you can go on an adventure on your own by exploring the console.

For what is IAM used for? Simply put, we need a way to authenticate and publish the metrics. In this service, we will create a user that will have the rights to publish metrics in CloudWatch.

Go to IAM service in the AWS console and click on the Add user button, give it a name and make sure that you select the Programmatic access

aws iam add user


In the next step, we will grant permissions to the user in order to be able to publish metrics in CloudWatch. To keep things simple, we will choose an existing policy, CloudWatchFullAccess. Make sure that you check the checkbox in order to give the rights. 

aws iam attach policy for cloudwatch full access

One last step and we are done. Hit next until you stumble on to the Access key ID and Secret access keyDon’t close the window, the Secret access key will be shown only in this place. Save them in a safe place, we need them in the next phase.

aws iam save credentials step

I am all set; how do I publish metrics in CloudWatch?

Remember what I said at the beginning? We need to publish one point at a time. 

The first thing that should be done is creating the CloudWatch client. Replace the INSERT_YOUR_ACCESS_KEY_ID_HERE and INSERT_YOUR_SECRET_ACCESS_KEY_HERE with the values saved above. Make sure that you are in the right region. In the region that you configure, you will be able to see the metrics.

In order to publish metrics to cloudwatch, we need to use the putMetricData method from the API. This method requires some parameters to be set and are explained below:

  • MetricName - the name of the metric, in this case, Temperature and Humidity
  • Dimensions - it's used to identify the metric, as a best practice I recommend to include the source of the metric (SensorType: DHT11)
  • TimeStamp - the moment in time when I read the metric. Using new Date() will assure that I will log the metrics at the current time.
  • Unit - unfortunately CloudWatch doesn't have the "Custom" option, here should have been the °C for temperature. Humidity uses percent and it already exists.
  • Value - the value that is read from the sensor. 
  • Namespace - this can be anything you like

The most important fields from the above are TimeStamp and Value. This is what is really building or time-series. For full details, you can check the official documentation for CloudWatch.

We use setInterval to read the values from DHT11 every five seconds and insert them in the cloud.

Don't forget that you have to make some preparation before using the node-dht-sensor library. If you are stumbling in any problem, I described in a previous project how to make the setup.

const sensor = require('node-dht-sensor');
const AWS = require('aws-sdk');

var cloudWatch = new AWS.CloudWatch({
    region: "us-east-1" 
}); const DHT = 11; const SENSOR_PIN = 4; publishMetric = (metricName, value) => { var params = { MetricData: [ /* required */ { MetricName: metricName, /* required */ Dimensions: [ { Name: 'SensorType', /* required */ Value: 'DHT11' /* required */ } /* more dimensions */ ], Timestamp: new Date(), Unit: "None", Value: value } /* more items */ ], Namespace: 'TheHumbleCode' /* required */ }; cloudWatch.putMetricData(params, function(err, data) { if (err) console.log(err, err.stack); // an error occurred else console.log(data); // successful response }); } setInterval(() => { const sensorResult =, SENSOR_PIN); console.log(`The current temperature is ${sensorResult.temperature.toFixed(2)} °C and humidity ${sensorResult.humidity.toFixed(2)} %`); // publish sensor values in Cloud Watch publishMetric("Temperature", sensorResult.temperature) publishMetric("Humidity", sensorResult.humidity) }, 5000)

In case you need it, I'm using the following package.json file.

  "name": "cloudwatch-sensor",
  "version": "0.0.1",
  "description": "A tool that publishes metrics to cloudwatch (e.g. temperature and humidity).",
  "main": "publisher.js",
  "author": "TheHumbleCode",
  "dependencies": {
    "aws-sdk": "^2.228.1",
    "node-dht-sensor": "^0.0.34"

First thing, install all the dependencies for this project and run it by executing the following commands:

npm install
node publisher

The metrics should start publishing and in ~15 minutes can be seen in AWS CloudWatch console.

If you connect to your Raspberry Pi by SSH and plan to leave the terminal open for several days, you need to use the screen command, otherwise, it will close after a while. If you don't have the command, you can install it using the following command:

sudo apt-get install screen
screen #open a new screen and start the publisher

After you start the program on the screen, you can detach from it by pressing Ctrl+a d. If you wish to reattach to the screen to make sure that everything works fine, run this command:

screen -r #reattach to the screen

if you stumble on any problem/curiosity/question use the comment section to address them, I'm more then glad to help/answer you. 

Final thoughts

Showing temperature and humidity metrics in CloudWatch

In the above results, I monitored my room for more than 1 day. From the time-series, ti can be seen a drop in temperature and humidity. That happened because I opened the window very early in the morning all the values dropped but recovered after during the day.

CloudWatch allows setting alarms on the metrics that you publish. If you left your AC ON while you are out, you can receive an email that the temperature dropped/increased to a certain level. And other handy situations that can be built with different sensors. 

But most importantly, stay curious!

Posted in discord, nodejs, raspberrypi


The main aim of this project is to teach absolute beginners how to create a discord bot and having fun doing it. By absolute beginners, I mean people that had no contact with discordapp before or very little. All of this, without throwing away all the work involved in the work (hopefully).

The project that I have in mind is to create a Discord Bot that will randomly post a joke when it will be commanded to do so. The code will be written in JavaScript if you are stumbling in any issue feel free to ask for help in the comment section.

I chose to write this because when I created a discord bot for the first time, it took me more time then I expected. The main points of this will include, creating the discord bot, creating the server, writing the code for the bot and running the bot. You can skip any of these steps if you don’t need it.

How do I create the Discord Bot?

In order to create a Discord Bot click on the following link and follow the instructions that I had written below:

  1. Chose a name for your Discord Bot, for the project in case I chose the name make jokes, but you are free to choose any name you want. After you name your bot, click on Create app button.

  2. Scroll to the bottom of the page and push the Create a Bot User button. Be aware that this action is irrevocable.

    The below popup will appear and by accepting it, you have a Discord Bot.
    What happens when you convert your applications to a Discord Bot.

  3. After the creation, you will be able to see the username and the token. We will need the token later, make sure that you save it or remember the way find when needing it. 
    Discord bot token position on website

Who do I add the Discord Bot to my DiscordApp Server?

After I learned to create my first Discord Bot, I was completely lost. I think I wasted around 1 hour trying to figure out how to add it to my server/channel. Remember that you need to have the right privleges on the server in order to add the bot.

If you don’t have a discordapp server, create one at (pushing the big + button from the top left)  

There are two ways to add a Discord Bot to your channels:

Information to get your Client Id and Generate OAuth2 URL in order to add the bot the a discord server or channel.

  1. The first one and the easiest one is to replace the Client Id in the URL presented below and just click it. It will redirect you to chose the server where to use the bot.{REPLACE_ME_WITH_CLIENT_ID}&scope=bot&permissions=0
  2. The second one is to click on Generate OAuth2 URL, select the correct permissions and an URL will be generated very similarly to the one from the above.

What is the code for a Discord Bot?

As I mentioned at the beginning of the post the code for this Discord Bot will be written in JavaScript executed with nodejs. The library that I love using when I write bots is discord.js, if you choose another tool, please let me know why in the comments section.

In the beginning, I said that the project will generate random jokes. But, where do they come from? For this a public API will be used, I chose one that generates jokes with Chuck Norris. If you don’t like it you can google another one or ever make your own repository of jokes.

The endpoint used to generate jokes is this one:

In order to call the API, we need a library to help us. Fortunately natively, nodejs comes with a simple library http.get that is more than enough for this project.

// references
const auth = require('./auth.json');
const http = require("http");
var Discord = require('discord.js');

// Initialize Discord Bot
var bot = new Discord.Client();
bot.on('ready', (evt) => {

const url =  "";

randomizeJoke = (channel) => {
    // most of the code is taken from documentation
    http.get(url, res => {

        let body = "";
        res.on("data", chunk => {
            body += chunk;

        res.on("end", () => {
            body = JSON.parse(body);
            console.log(`Result: ${body.value.joke}`); // for debug purposes
            channel.send(body.value.joke); // send to Discord Channel
} bot.on('message', message => { // Our bot needs to know if it will execute a command // It will listen for messages that will start with `!` var text = message.content; var channel =; if (text.substring(0, 1) == '!') { var args = text.substring(1).split(' '); var cmd = args[0]; args = args.splice(1); switch(cmd) { // !joke case 'joke': randomizeJoke(channel); break; // Just add any case commands if you want to.. } } }); bot.login(auth.token);

The above code might look scary if you have little experience with JavaScript, but don't let it scare you. Is fairly easy, I will explain the most important parts of the code.

At the beginning of the code, we have the require statements that basically says I want to use these libraries/files (http, discord.js, auth.json) in the following code. 

Below the bot is created var bot = new Discord.Client();, but not logged in to discordapp. Before the bot is login some events are attached, one of the most important is the one that listens for the messages that are posted on the channels.  

bot.on('message',  message => { /* execute commands */ }

In this event, we can read the message (!joke) and respond to it (with the joke).

In the randomizeJoke function, the joke is being read from the API that provides jokes with Chuck Norris. The API is easy to use and we need to use HTTP GET verb, and fortunately, nodejs offers this functionality under this form http.get

If you copy paste this URL in your browser you will be able to see the structure of the JSON that will be answered, it looks like the following:

  type: "success",
  value: {
    id: 419,
    joke: "Count from one to ten. That's how long it would take Chuck Norris to kill you...Forty seven times.",
    categories: [ ]

This is the reason why I sent to discord channel on the following line of code channel.send(body.value.joke);.

And, at the end of the file the bot is logging in discord bot.login(auth.token);

Maybe you already noticed, we need 2 additional files on this project before we are ready to move to the next step. The first one that is marked as require('./auth.json') in the above code.

Create the file auth.json and don't forget to use the token that I mentioned to save after the bot was created.


One of the most important files is package.json file that is very simple for this project. The only dependency that you need is on discord.js. And that's it, you are good to go on the next section.

  "name": "discord-bot-jokes",
  "version": "0.0.2",
  "description": "A bot that will make my day.",
  "main": "bot.js",
  "author": "TheHumbleCode",
  "dependencies": {
    "discord.js": "^11.3.2"

How do I run my Discord Bot in Raspberry Pi?

The shortest answer is, everywhere nodejs is supported. The nice part of this project is that it doesn’t have any hard dependency so it is very flexible where you can run it. The most common places will be on your PC, someone else’s PC, a Raspberry Pi or any development board meeting this condition.

I chose to run this bot on a Raspberry Pi, and it’s not the first time I’m doing this.

The first requirement is to install a operating system on Rasp (if you don't already have it) and the second one is to be able to SSH and/or SCP on to it. If you are not able to SCP, don’t worry too much, instead, you can write or copy paste the code through SSH. 

The first step is to install nodejs, if you do not have it already installed it's time to do so. This tutorial explains what you have to do. I will add the commands needed to install nodejs in order to be handy:

tar -xzf node-v7.7.2-linux-armv6l.tar.gz
sudo cp -R node-v7.7.2-linux-armv6l/* /usr/local/
export PATH=$PATH:/usr/local/bin

node -v
npm -v

Now make sure that you use SCP to copy the files on to your Raspberry or just use SSH to create the files (touch command) in a folder (mkdir).

After you have all the code I mentioned above (bot.js, auth.json, package.json) in your Raspberry Pi, you need to execute the following command and you are ready to go.

npm install
node bot.js

The results can be seen in the below gif. Now you are ready to make bigger steps and create other projects that make use of discordapp.

Thank you for reading!

Posted in raspberrypi, discord, dht11, nodejs

In my first blog post, I created a Discord Bot that runs on Raspberry Pi Zero and turned a LED on and off. Today I want to continue using this combo but instead of a LED, I will use a DHT11 sensor that reads the humidity and temperature. This information will be posted in a channel from Discord and will be read from a room from my house (1 to 1 relationship here). 

The coolest thing about using Discord is that you can use any device or invite anyone to use the functionality that is made without making complicated setups.


Hardware specification and setup for DHT11

The temperature and humidity sensor is not very fast, the data must be read once at ~5s. It needs a resistor with a value between 5.1K-10K that will be placed between VCC (Pin 1) and Pin 2.


The table below shows the connections that I made between Raspberry Pi and DHT11. 

DHT pinSignalRaspberry Pi physical pin
13.3V ~ 5.5V 4 (VCC)
2Data 7 (BCM 4) and 4 (VCC) with resistor
3not used 
4Ground 6 (GND)

Below I created the schema that I will use to read the values from DHT11 sensor using fritzing. The resistor that I have used has 10K (ohm). I chose to connect the resistor directly between pin 7 and 4.


Reading the sensor and publishing to discord 

To read the DHT11 sensor from nodejs I will use the node-dht-sensor library. 

The file package.json for this project is pretty simple, contains the library mentioned above and discord.js library in order to publish the values read from the sensor to a channel.

  "name": "home-manager-sensor",
  "version": "0.0.2",
  "description": "A bot that helps me to automize my home.",
  "main": "bot.js",
  "author": "TheHumbleCode",
  "dependencies": {
    "discord.js": "^11.3.2",
    "node-dht-sensor": "^0.0.34"

Mentioning the Discord Bot, don't forget to create the auth.json file and add the token for the bot.


To read the sensor every 5 seconds for this example, in a real case every hour will make more sense in order to avoid spamming. In Discord, I created a channel named living-room and use it to send the updates periodically. 

The code is very tight, but it can very easily be implemented commands to stop or to continue publishing the temperature and humidity.

The below code is written to a file named, bot.js

const auth = require('./auth.json');
const Discord = require('discord.js');
const sensor = require('node-dht-sensor');

const DHT = 11;
const SENSOR_PIN = 4;

notifyChannel = function(channel) {
    const sensorResult =, SENSOR_PIN);
    const message = `The current temperature is ${sensorResult.temperature.toFixed(2)} °C and humidity ${sensorResult.humidity.toFixed(2)} %`;

// Initialize Discord Bot
const bot = new Discord.Client();
bot.on('ready', (evt) => {

    let livingRoomChannel = bot.channels.find('name', 'living-room');
    setInterval(() => {
    }, 5000)


In order for node-dht-sensor library to work on the project, it needs the following prerequisites. I described the steps I used below.

1. Install Broadcom bcm2835 following the steps below (if the version will get obsolete, search for the latest on their website).

tar zxvf bcm2835-1.55.tar.gz
cd bcm2835-1.55
./configure make sudo make check sudo make install

2. Install node-gyp to compile native nodejs modules (nodejs addons).

sudo npm install node-gyp -g

3. At the top of the project folder install the dependencies needed (discord.js and node-dht-sensor).

npm install

Now we are ready to start the Discord Bot

node bot.js


Although for this type of data (timestamp, value) makes more sense to be published in a service where it can be seen as a line chart.

The way I like to look at this is like having an audit. Now I need to remote control the AC from far.. far away in order to set up the perfect room temperature.


Thank you for reading!