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':
            // Just add any case commands if you want to..


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!

Posted in raspberrypi, discord, bot

In this post I will use a Discord to turn on/off a led that is attached to a Raspberry Pi Zero. This is going to show how easy is to control something from your house using the Discord. And will demonstrate that even if the Discord is designed for gaming communities it can be used for many more.


How do I do this?

To control the led using Discord we need to run a Bot on Rasbperry Pi Zero. To create a Discord Bot use the following steps that can be found here. After you create the application don't forget to mark it as a Bot (be aware, the action is irreversible). Save the token provided by the application and store it in a json file in order to be used.

In this mini project I named the file auth.json, don't forget to use the token of the Bot you created.


The package.json file for the this project. I may use some old dependencies of rpio (at the moment of writting this), but for this project is enough. Also the discord.js module to interact with Discord, make sure you have the node version 6 or higher. If you don't there are many tutorials on internet that help you achieve this.

   "name": "home-manager-led",
   "version": "0.0.1",
   "description": "A bot that helps me to automize my home.",
   "main": "bot.js",
   "author": "TheHumbleCode",
   "dependencies": {
      "rpio": "0.9.12",
      "discord.js": "^11.3.2"

The code below allows us to use the keywords !on, !off and !blink in the discord chat to control the led.

First, we import the auth token in order to login to Discord. In this project I have chose to use the PIN 18 from Raspberry Pi Zero. After the led is turned on or off a message is sent to the Discord chat in order to have a feedback when we are not close to the led.

var auth = require('./auth.json');
var Discord = require('discord.js');
var rpio = require('rpio');

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

const LED_PIN = 18;
 * Set the initial state to low. The state is set prior to the pin becoming
 * active, so is safe for devices which require a stable setup.
 */, rpio.OUTPUT, rpio.LOW);

turnOn = (channel) => {
    rpio.write(LED_PIN, rpio.HIGH);
    channel.send('The led is ON now!');

turnOff = (channel) => {
    rpio.write(LED_PIN, rpio.LOW);
    channel.send('The led is OFF now!');

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) {
            // !open
            case 'on':
            case 'off':
            case 'blink':
                setTimeout(() => {
                }, 3000);
            // Just add any case commands if you want to..


I put the above code in a file named bot.js and used the command node bot.js to start it.


You can add any custom commands or replace the led with something else, like a matrix of leds or a temperature sensor that will tell you how many oC (or fahrenheit) are in the room.  

Thank you for reading!