Here’s a weekend project I recently cooked up to see how difficult it would be to control an Arduino microcontroller over the internet with a Raspberry PI.
In this project I have 24 LEDs and a 4×7 segment display controlled by an Arduino Leonardo via 4x74HC595 Shift Registers.
Here’s a quick video of just the Arduino and LEDs in action:
The Arduino is running a sketch that automatically cycles through a series of LED animations I wrote and intermittently updates a 4×7 segment display (which you’ll see in a moment) with a random number.
Cool, but what would be cooler is if we could allow someone to control the Arduino say from their phone, over the internet!
So I spun up a quick Node.js webserver on my Raspberry PI to serve a simple GUI I built using Twitter Bootstrap that would allow users to send some commands to the Arduino from a webpage like so:
Turns out there is a fantastic library already out there called node-serialport that does all the heavy lifting for you. You just need to detect the USB port the Arduino is connected to and you can start sending messages to it via 8-bit bytes wrapped in a Node.js buffer object.
It’s actually a lot simpler that it sounds.
Here’s the basic setup of how all the parts are connected:
- The Raspberry PI runs a Node.js application that listens for client connections at the PI’s IP address, e.g. 192.168.2.1:8080
- A client connects via their web browser and Node.js serves them the web GUI.
- Once connected I generate a random # from 1-9999 and print it at the top of their screen.
- This same number is sent back to the Node.js app running on the PI which routes it to the Arduino which displays it on the 4×7 segment display.
- Now the user knows they are connected to the Arduino as the number in the GUI and the 4×7 segment display are the same.
- The user can now select an animation from the webpage which sends an integer representing that animation (1-5) to the Node.js app which forwards it to the Arduino to update the LEDs.
There’s also an “auto mode” that when selected tells the Arduino to cycle through the five animations automatically on a slight delay. What’s particularly cool is that whenever the Arduino changes to a new animation it sends out a message via Serial.println(‘MODE#’) which is heard by the Node.js app which broadcasts the animation change to all connected clients so their GUI stays in sync with the Arduino.
Alas, simple two way communication between a web app and an Arduino!
Here’s the final build with the Raspberry PI and Arduino controlling the LEDs and 4×7 Segment Display:
Animating some LEDs is just the start.
What else do you guys think would be cool to control with a Raspberry PI & and an Arduino?