Build a smart mailbox with a Sigfox and Pycom
Tags: python, opensource, iot, tutorial
Published: 2018-07-26 14:50:09

---
title: Build a smart mailbox with a Sigfox and Pycom
published: true
description: Learn how to create a Sigfox mail notifier using Wia and the Pycom SiPy.
tags: #python #opensource #iot #tutorial 
---
![alt text](https://s3-eu-west-1.amazonaws.com/wia-flarum-bucket/2018-07-13/1531496045-733399-smart-mailbox-sigfox-pycom.png)


Hi folks,

Today I’m going to show you how to create a Sigfox mail notifier using Wia and the Pycom SiPy.

This tutorial assumes that you have already connected Sigfox to Wia if you haven’t, please click [here](https://developers.wia.io/v1.0/docs/pycom-sipy) to find a tutorial for initial Sigfox setup and publishing data to Wia.
  
# Components

* [Pycom SiPy](https://pycom.io/hardware/sipy-specs/)
* [Pycom Expansion Board](https://pycom.io/product/expansion-board-3-0/)
* Sigfox compatible antenna
* Mobile device (iOS or Android)
* [HC-SR04 ultrasonic sensor](https://www.amazon.co.uk/ELEGOO-Ultrasonic-Raspberry-Datasheet-Available/dp/B01M0QL1F1/ref=sr_1_3?ie=UTF8&qid=1531485159&sr=8-3&keywords=hc-sr04)
  
# Setup your board

* Connect the SiPy to the Expansion board. (The Pycom logos should face the same way)
* Connect the Sigfox antenna to the SiPy. The connection is the small gold circle on the bottom left of the SiPy board. Simply snap the antenna in place.
[upl-image-preview url=https://s3-eu-west-1.amazonaws.com/wia-flarum-bucket/2018-07-13/1531486321-146149-sipy-antenna.png]

For the HC-SR04 ultrasonic sensor, you'll need to connect the following pins to the Pycom SiPy:

* HC-SR0 | Pycom
*  Vcc -> Vin
*  Trig -> G8
*  echo -> G7
*  Gnd -> GND
  
# Setup Your Project
In Atom:
 
* Create a new folder for your project. I'm going to call mine sigfox-mailbox
* In [Atom](https://atom.io/), go to `File > New Window` to open a new window

* Add your newly created folder by clicking `File > Add Project Folder` and navigating to it

* If the [Pymakr](https://atom.io/packages/pymakr) plugin is not open at the bottom of your Atom window, click on the arrow on the right hand side to open it

* Select `Settings > Project Settings`. In the address field replace the value with the device name from the step above e.g. `/dev/tty.usbmodemPy343431` (Mac OS X), `COM3` (Windows), `/dev/ttyACM0` (Linux) then save the file
  
# Publish a sigfox Event for our mail

 We'll need three files for our application:

 * `boot.py` which is run when the device is powered up
 * `main.py` which is where our main code is
 * `ultrasonic.py` is where is our functions for obtaining distance and calibration
  
In Atom: 

* Right click on your project and click New File. Enter `boot.py` as the filename

* Copy and paste the code below into the file

```
from machine import UART
import machine
import os

uart = UART(0, baudrate=115200)
os.dupterm(uart)

machine.main('main.py')
```

* Right click on your project and click New File. Enter `main.py` as the filename

* Copy and paste the code below into the file

```
import time
import pycom
import socket
from network import Sigfox
from machine import Pin, Timer
import ultrasonic


pycom.heartbeat(False)

echo = Pin(Pin.exp_board.G7, mode=Pin.IN)
trigger = Pin(Pin.exp_board.G8, mode=Pin.OUT)
trigger(0)

# Get the chronometer object
chrono = Timer.Chrono()

# init Sigfox for RCZ1 (Europe)
sigfox = Sigfox(mode=Sigfox.SIGFOX, rcz=Sigfox.RCZ1)
# create a Sigfox socket
s = socket.socket(socket.AF_SIGFOX, socket.SOCK_RAW)
# make the socket blocking
s.setblocking(True)
# configure it as uplink only
s.setsockopt(socket.SOL_SIGFOX, socket.SO_RX, False)


calibrated_distance = ultrasonic.calibration(chrono, trigger, echo, 1)
mailed_distance = 0
while True:
    time.sleep(30)
    distance = ultrasonic.getDistance(chrono, trigger, echo)
    print("distance: {}, calibration: {}".format(distance, calibrated_distance))
    if distance < calibrated_distance:
        if distance != mailed_distance:
            s.send('') # Send 1 bit
            print("you got mail")
            mailed_distance = ultrasonic.calibration(chrono, trigger, echo)

```

* Right click on your project and click New File. Enter `ultrasonic.py` as the filename

* Copy and paste the code below into the file

```
from machine import Pin, Timer
import pycom
import time
import socket

def calibration(chrono, trigger, echo, led = False):
    if led:
        pycom.rgbled(0x7f0000) # red
    prev_distance = 0
    distance = getDistance(chrono, trigger, echo)
    print("calibration distance is {}".format(distance))
    count = 0
    while True:
        prev_distance = distance
        distance = getDistance(chrono, trigger, echo)
        while prev_distance == distance:
            count+=1
            print("count: {}".format(count))
            if count > 5:
                if led:
                    pycom.rgbled(0x007f00) # green
                    time.sleep(1.5)
                    pycom.rgbled(0) # off
                return distance
            time.sleep(5)
            prev_distance = distance
            distance = getDistance(chrono, trigger, echo)
        else:
            count = 0

def getDistance(chrono, trigger, echo):
    chrono.reset()
    trigger(1)
    time.sleep_us(10)
    trigger(0)

    while echo() == 0:
        pass
    chrono.start()

    while echo() == 1:
        pass
    chrono.stop()

    distance = chrono.read_us() / 58.0
    if distance > 400:
        return -1
    else:
        return int(distance)

    time.sleep(1)
```

Your folder structure should now look like this:

* `ultrasonic.py`

* `boot.py`

* `main.py`


  
Click `Upload` in the Pymakr plugin at the bottom of your window in Atom and send the code to your Pycom board. Now go to the Wia dashboard and you should see data appearing in the debugger section of your dashboard.

In order for the sensor to operate correctly, it needs to calibrate the distance inside you mail box.
 
### Calibration
To calibrate the sensor, place the sensor in the mailbox where its suits best. Power the board; when the LED on the board is red, the sensor is calibrating; once the LED flashes green, the sensor has been calibrated. The sensor needs at-least 2cm of space in order for it to operate correctly. 

Now when mail is inserted into your mailbox, the distance will be reduced from the calibrated distance and the code will publish an Event via Sigfox to Wia.
  
# Send a Push Notification

Now for the next step, once we recieve the Sigfox event in Wia, we will send a notification to any connected phones that there is mail. For this we need to build a Flow.

Head over to your Wia dashboard and in the Space where your Sigfox device is held. From there click on the Flow icon in the left hand menu to go your Flows.

![alt text](https://s3-eu-west-1.amazonaws.com/wia-flarum-bucket/2018-05-14/1526284386-778692-flow.png)


Now to create your Flow, you can name it whatever you like. Once you have created a Flow, you should be taken to the Flow studio.

In the Flow studio:

* Drag the `trigger event node` from the left hand side onto the canvas

* Click on the node and enter `sigfoxDataUplink` as the event name

* Enable your Sigfox Device as the event source

Now we are going add a notification for the Sigfox Event so we get notified of our inbound mail. To do this, you will require the Wia mobile app. You can download it for iOS [here](https://itunes.apple.com/us/app/wia-talk-to-your-things/id1320616870?ls=1&mt=8) and Android [here](https://play.google.com/store/apps/details?id=io.wia.wia).

![alt text](https://s3-eu-west-1.amazonaws.com/wia-flarum-bucket/2018-07-13/1531485931-970630-mail-notifier.png)


In the Flow Studio editor:


* Drag over a notification node and enter the following text

```
You've got Mail!
```

Now you should receive Sigfox data to your mobile device.

![alt text](https://s3-eu-west-1.amazonaws.com/wia-flarum-bucket/2018-07-13/1531490491-960647-screenshot-20180713-150002-2.jpeg)