empowering creative people

How to Build Internet-Connected Electronics Projects

What do we mean when we talk about the "Internet of Things"? Mostly we're talking about tiny computers that have access to the internet and do some useful work. Unlike the computers we're used to holding in our hands, they don't have a touchscreen and they're not intended to be touched by people. They are hidden away in light bulbs, garage door openers, automatic garden watering systems and the like. These simple computers become very powerful because they're online. Instead of watering your garden for an hour every day, maybe being able to sense if it rained, new Internet of Things (IoT) devices can look at the forecast for the local weather before deciding if watering is necessary. It could even download a radar image of rainfall to decide if rain is imminent.

The variety of devices that can be put to work in IoT projects has exploded. There's probably an ideal device for every maker project. So that we can get our heads around it, we need to choose a device that's simple; a good place to start for beginners. Pycom makes a range of devices that are a great starting place for IoT projects even for people who are new to electronics and programming. For this workshop I've chosen the Pycom WiPy. It's small, powerful, and easy to use. How small? You can put six of them side-by-side on a credit card! By using another Pycom device, an Expansion Board, we can easily plug the WiPy into a computer and get to work building something wonderful.

The Project

Completed project for IoT Workshop 1

What shall we build? To show off the power of IoT I think it's essential we build something without wires. The finished project needs to communicate between our device and something on the Internet without needing to be plugged in. We'll add a battery to power our device and use a phone to interact with a web page that communicates with our device.

With only few wires and two electronics components we can build a circuit that measures the brightness of light in the room. Once measured, our device needs to send that measured light level to a website, so it can be graphed. Adafruit IO is a web site that's free to use for this kind of purpose. Adafruit are makers like us and they provide this service for imaginative minds like ours. No catch; no cost. You can sign up at Adafruit IO then go straight to designing your web page. But more on that later.

We'll also be able to control the coloured light (LED) on the WiPy. An Adafruit IO colour picker will let us select any colour and send that to the WiPy which will then match that colour with its LED. Let's add a switch on Adafruit IO too so we can turn the light off and on!

Hardware

Things you'll need to get:

  • Pycom WiPy
  • Pycom Expansion Shield
  • A LiPo battery
  • Breadboard
  • 3 x male-to-male jumper wires
  • A 10kΩ resistor
  • A photocell

Things you'll probably already have:

  • A Windows computer
  • A modem or router with Wi-Fi and internet service
  • A smartphone
  • A USB to micro USB cable

When you unpack your WiPy and Expansion Board, you'll need to snap the two together. First, make sure they're the right way around. The pycom logo on both devices should be the same way up. Also make sure you're getting all the pins under the WiPy into the holes in the expansion board. Don't let any overhang at either end. Then push down and the pins will disappear into the socket.

Orientation of WiPy on Expansion BoardPressing WiPy onto Expansion Board

You can now plug both ends of the USB cable in. Be kind to the USB socket on the device! When first plugged in, the WiPy should give you a green flash from the LED (white square) and then it should give a blue flash about every four seconds. That's the "heartbeat" telling you it's ok.

Windows 10 - Setting up a device

Windows 10 - Device is ready

While you're plugging it in, Windows should detect and install the new device without you needing to do anything. To check it's ready, you can go to Settings, search for and open Device Manager, then look under Ports (COM & LPT).

A Programming App

The way to get our device to do what we want is to give it a program. We'll write code in the Python language to program it. Don’t freak out! Python is a very good place to start with computer programming. Yes, it will be strange if you've never done computer programming before, but all the code needed for this project is provided. We'll go step by step with what to do and how to know if it's working or something went wrong.

We need an app on our Windows computer that we can use to type up our programming code and communicate with the device. Atom is just perfect for this.

The Atom IDE

IDE means Integrated Development Environment – a program for creating programs. Let's get it installed:

  1. In your favourite web browser, go to the web site atom.io
  2. Scroll down the page a little to find the Download button and click it.
  3. When the download completes, go to your Downloads folder and open the file AtomSetup-x64.exe (or AtomSetup.exe)
  4. Atom won't ask any questions but will install itself.
    Atom IDE installing
  5. When it's done, you'll see this:
    Atom IDE on first launch
  6. Several tabs will open, the only one of which we need is Welcome Guide. Click on Install a Package.
    Atom IDE install a package
  7. In the search box, type pymakr and hit the enter key.
    Atom IDE searching for pymakr
  8. When pymakr is found, click Install
    Atom IDE found pymakr
  9. When pymakr is installed a black box will open at the bottom of Atom. We can close all the tabs across the top except for untitled. We're ready to get to work!
    Atom IDE pymakr running

Code Files

The computer programming code for this project has been pre-cooked. We need to get the files and open them up using Atom.

  1. Download the IoT Workshop file
  2. Unzip the zip file you downloaded.
  3. Windows Explorer will open a new window to show the files that were unzipped. We need to move this out of Downloads. Drag the folder to Documents.

Now, back to Atom:

  1. From the File menu, select Open Folder
  2. Find your Documents folder and open the iot-workshop-master folder.
  3. Once there, click the Select Folder button at the bottom
  4. Atom should show the list of files in the folder down the left side, like this:

Now we have all the code files we'll use in this project. The only step of preparation left to do is to get Atom talking to the device.

Connecting Atom to the Device

Between the halves of Atom is a horizontal menu. By clicking More we can find the Get serial ports feature. This will list communications devices attached to the computer, one of which will be our device. I get the following:

Found 1 serialport

COM13 (Microsoft) (copied to clipboard)

So my device is COM13. It's nice and easy if only one device is found. If there are more than one, unplug your Pycom device and do Get serial ports again. The device that disappeared from the list is your Pycom device. Plug it back in, do Get serial ports again, and it should reappear on the list.

Again in the horizontal menu, click Settings then Project settings. Make sure the value on the "address" line is the COM name for your device. It might currently say "192.168.4.1", that needs to be changed to "COMx" where x is the number for your device. Mine is COM13.

{

    "address": "COM13",

    "username": "micro",

    "password": "python",

    "sync_folder": "",

    "open_on_start": true,

    "safe_boot_on_upload": false,

    "sync_file_types": "py,txt,log,json,xml",

    "ctrl_c_on_connect": false

}

The tab we're working on has the name pymakr.conf. When we close that tab, Atom will ask if we want to save the file. Click Save. With that done, click Connect (again on the horizontal menu). If the connect operation works properly, you'll see what I call the "triple chevron" in the black box at the bottom. A few things might go wrong at this point.

If clicking Connect hasn't brought up the triple chevron, you'll notice that same button is now labelled Disconnect. You can Disconnect and try to Connect again, as I did in the image above. Don't worry if the connection hasn't worked. Try these steps to resolve the problem:

  1. Use More, Get serial ports to check your Pycom device is connected to the computer. If it's not listed, it's not connected.
  2. Check Settings, Project settings and ensure you haven't made a mistake with adding your COM port. A stray space or a missing comma is enough to cause this file to no longer make sense to Atom. You must be exact.
  3. Click Disconnect and Connect to try again.
  4. On the Pycom WiPy device, next to the blue flashing light is a tiny black button. This is the reset button. Push it. Now try again to Connect.
  5. Unplug your device from the USB cable. Wait about 10 seconds and plug it back in. Try connecting again.
  6. Close the Atom app and start it up again.
  7. Restart the computer.
  8. Check Device Manager (mentioned above) to ensure your device can be "seen" by Windows.

Hopefully that list of tips will get you through any problems you might have connecting to your device from Atom.

Read, Evaluate, Print, Loop (REPL)

One of the great features of Python is that we can type in that black box at the bottom of Atom and our device will do what we say instantly. Assuming you have the triple chevron displayed, you can click in that box, type the following and press the enter key at the end of the line:

print('Hello world!')

The black box should show what you typed (with >>> in front of it) and what the device did (line without the >>> in front).

>>> print('Hello World!')

Hello World!

>>> 

We've just run our first program! OK it was only one line, but this is what REPL is all about. Our device reads what we type, evaluates it: meaning it assumes you're writing in the Python language and does what it should according to the rules of Python. It then prints out anything we've asked it to print out and then "loops": goes back to waiting for more Python code.

Did yours fail? If I misspell print this happens:

>>> pint('Hello World!')

Traceback (most recent call last):

  File "<stdin>", line 1, in <module>

NameError: name 'pint' is not defined

If I leave out one of the apostrophes, this happens:

>>> print('Hello World!)

...

What's happening? What we've done is made a simple error, one that we'll make thousands of times as computer programmers. Our device knows the rules of Python code. It expects everything we type to be valid Python, and it's merciless in its perfectionism. Every character we write has to be in the right place, keywords (like 'print') have to be Python programming words: 'pint' isn't a keyword.

In my second example above, I left out an apostrophe. In response the device gave an ellipsis (…) which says "I don't think you're finished". We need to enter another apostrophe of the first line doesn't make sense. Unfortunately we would also then have to add another closing bracket – ah, it's a mess! We can just type ctrl+C (hold down the ctrl key and press the C key) to cancel that line.

Now we'll build up our program for the device in stages. By clicking a file in the Project list and clicking the Run button in Atom we can see what that program does.

01 Hello World

On the left side of Atom you should have the list of files for our iot-workshop-master project. Click on 01 Hello World.py to open it. Here's our first Python code file. It only has one line in it that makes sense to the device. The other lines all have a hash character (#) at the start. A line beginning with a hash is a comment. They're notes made by the programmer to help them understand or remember what the code does. When we run this code on our device the comments are ignored.

Now we can use the Run button to get our device to run this program. If it responds with No file open to run then just click anywhere inside the 01 Hello World.py file and click Run again. It prints

Hello World!

Let's do something slightly more advanced.

02 Make It Red

Clicking on the 02 Make It Red.py file shows different code. Again there are lots of comments so you can read the file from top to bottom and gain some understanding of what it does.

No doubt you will have questions that I haven't thought to answer in this workshop. Regardless of your level of experience let me encourage you to push through. If you fall down a rabbit hole and just can't get back Google is your friend. For example if I get an error like this:

ImportError: no module named 'umqtt'.

… I would search Google for: Pycom WiPy ImportError "no module named"

Back to Make It Red. This program controls the blinking blue light and sets it to a colour of our choosing. Read the comments in the code file to understand what each line does. When I click the Run button the light turns red! Now we're getting somewhere. We needed our device to change only one thing about itself, but it took six lines of code to make it work. If we removed any except the last line we would not get a red light.

Use Google to design your own colour codes and put them into the program on line 23. You'll need to leave the "0x" at the start of the code. I made a code for orange and changed the program line to this:

pycom.rgbled(0xfc7500)

03 I See The Light

Now we need our baby electronics circuit. Rather than draw a diagram I've chosen to show in photographs what to do. A few things before you begin:

  • The expansion board has two rows of sockets for you to push jumper wires into. Each socket directly corresponds to the adjacent pin on the WiPy device. We know what each pin does by looking at the Pinout Diagram. [Link: https://docs.pycom.io/chapter/datasheets/downloads/wipy3-pinout.pdf]
  • The "breadboard" shown in the pictures also has holes to put wires and components into. Each row of five holes (eg. 1A to 1E) are connected inside the breadboard.
  • The photocell changes its resistance based on how much light falls on it. When in bright light its resistance drops (to maybe 500Ω) and the darker it gets the higher it goes (as far as 5,000,000Ω).

When in the circuit, pin P13 will see voltages ranging from about 0V to 3.3V depending on the light. We can tell the WiPy that we want to read (input) the voltage at that pin and it will convert the voltage to a number between 0 and 4095. This process is called Analogue to Digital Conversion (ADC). Once we have a number it's an easy thing to send that value to our web site (Adafruit IO) for it to be displayed on a graph.

[Breadboard Circuit Pictures]

  1. In Atom, click Disconnect
  2. Unplug the USB cable connecting your device to the computer.
  3. Build the circuit shown in the photographs
  4. Double check it!
  5. Plug your device back in to the PC

If the device heartbeat (blue flash) doesn't come back on, unplug it. You've got something wrong. If your circuit works as intended you can run the 03 I See The Light.py file and a line will print in the REPL box:

>>> 

Light level: 520

Hooray! Now you can play with covering the photocell with your hand or shining a bright light onto it to see what happens to the light level each time you run the program.

You should find something unexpected happens: the more light, the lower the number. Wouldn't it be intuitive if zero meant no light and higher numbers meant brighter light? We could change our electronic components around on the breadboard but it's faster and easier to change the code. Let's just change line 36 of the program from:

print("Light level: {}".format(apin()))

… to …

print("Light level: {}".format(4095 - apin()))

Now let's see what happens! Can you get the number right down to zero? Does it go all the way up to 4095? Wouldn't it be easier if we didn't have to keep clicking the Run button?

04 Keep Seeing the Light

In this program we've used the Python keyword while to make the part of the program indented under that word repeat itself forever. Now we can play with the photocell and just watch the changes in the number in real time.

Just to add a little fun, we've now told the LED on the WiPy to change its brightness in response to the measured light level. By playing with the photocell can you get the LED to turn off completely?

05 Connect to WiFi

Is it impossibly difficult to get this tiny computer connected to the Internet? Well, no. It's more code and it looks strange but if we change two magic lines it will work.

WIFI_NETWORK_NAME = "IoT"

WIFI_PASSWORD = "45GreenCarpet"

If your wireless network where you are is called "MyWiFi" then just replace "IoT" in the program with yours. Whatever the Wi-Fi password is at your place should replace "45GreenCarpet" and you're all set. Hit the Run button!

We've used the colour of the LED to indicate what's happening with the Wi-Fi. While the LED is red the device isn't connected to the Internet. When it connects, the colour changes to green. Similarly, a message is printed out showing what's happening on the device. The line of dots just shows that something's going on. Once connected to the Internet the program stops. What happens when you try it again?

Yes, it connects almost instantly. That's because the WiPy device stays connected to the Wi-Fi network even when it's finished running its program. When we start the program again it's still connected so it doesn't have to wait to have its password accepted to get on the network.

06 Send Light to Adafruit IO

OK, we're nearly at the destination. We can control the LED on the WiPy. We can measure light. We can connect to the Internet. We just need to make Adafruit IO join the party. Here it would be really useful to layout the windows on your screen so half the screen is Atom and the other half is your web browser, like this:

[Image of Atom/Browser Desktop]

  1. Go to Adafruit IO
  2. At the top of the page click Get Started for Free
  3. Fill in your details and click Create Account
  4. You'll likely be bounced back to the Adafruit home page. Go back to the address bar and enter io.adafruit.com.
  5. Using the menu on the left, click View AIO Key
  6. You'll need to copy the Username and Active Key into the 06 Send light to Adafruit IO.py program in Atom. Replace the contents of AIO_USER and AIO_KEY in the program. Don't forget to keep the double-quotes. Replace only the text inside the quotes.
  7. Again you'll need to change the Wi-Fi details as you did for the previous program.

Everything else in our program will work if we set up Adafruit IO with the right configuration. We'll use a communications language called MQTT to talk from our device to Adafruit IO. What MQTT is and how it works we don't care. We just know that it works. Back to Adafruit IO now:

  1. From the left menu, select Feeds
  2. Scroll to the bottom of the page to find the Actions button. Click it and select Create a new Feed. Name it light and click the Create button.
  3. Repeat the process and create feeds called control and colour. Excellent.
  4. Again from the left menu, select Dashboards.
  5. You can create a dashboard or use one that's already there. It doesn't matter what you call it.
  6. From the list of Dasboards below the Actions button, select a dashboard. Ensure when it opens that it's empty. There should only be a row of buttons in the top right corner. Create a new one if you need to.
  7. Use the blue [+] button to add a block to the dashboard.
  8. There are various blocks available. We want to graph our light level, so we should select the Line Chart block.
  9. Now we need to connect the chart to a feed so it has some data to render. Select light, then click Next step
  10. Block settings allows us to change the way data is displayed but the default is fine, click Create block
  11. We now have chart called light. It doesn't display anything and in tiny writing it says There is no data to display. That's fine.
  12. Use the blue button to Create a new block
  13. This time use the Color Picker. Connect it to the colour feed.
  14. Create one last block. Use the Toggle. Connect it to the control feed and use the default settings.

Are you ready? Are you really ready?

In Atom, Run the current program.

>>> 

Traceback (most recent call last):

  File "<stdin>", line 7, in <module>

ImportError: no module named 'umqtt'

MicroPython v1.8.6-849-177b724c on 2018-05-12; WiPy with ESP32

Type "help()" for more information.

>>> 

Bummer. Remember I said we would use MQTT to talk to Adafruit IO? Well, our project has the file umqtt.py hidden in the lib folder, but that file isn't on the device yet. We need to click Upload. This will put all the files from our project onto our device. Now. Now hit Run!

If all is well, your REPL box in Atom is printing out messages and your light graph on Adafruit IO is adding a new point to the graph every 5 seconds. If Adafruit IO hasn't started, refresh the page.

Try the colour picker! You can make the LED on the device any colour you like! What to switch it off? Use the Control slide switch. This is so cool!

Set it Free!

I have only one magic trick left. What if we could ditch that USB cable and make the whole thing work without the computer? Let's do it!

  1. In the Atom project you'll find the file main.py. This program is run automatically when the WiPy starts up.
  2. Open the 06 Send Light to Adafruit IO.py file and copy the entire contents.
  3. Open main.py and paste the code into there.
  4. Save the main.py file
  5. Click Upload to get the new main.py file onto the WiPy
  6. After the upload completes, unplug the USB cable.
  7. Connect the battery to the expansion board. You should see the LED go through the red – green – blue transition to show it's connected to Adafruit IO.

Now pull out your phone and go to Adafruit IO on your phone. Log in with the details you used when you set up your account. Find your dashboard and VOILA! The entire project is now untethered. As long as you stay in range of your wireless network you device will work anywhere!

What do we mean when we talk about the "Internet of Things"? Mostly we're talking about tiny computers that have access to th...

Have a question? Ask the Author of this guide today!