This a guest post from Anmol Agrawal, an India-based UX/UI & Interaction Designer, and Full Stack Developer with Rails. Over the week, we’ll be publishing Anmol’s RubyBits, a blog series on hardware programming and the Internet of Things using Ruby.
Welcome back! We are on a roll. We started with nothing but blinking an LED, then controlling it through button and sensors, then taking that control to an application. You can see the pattern developing. We are slowly increasing the complexity. I am feeling ambitious. So ambitious, I want to do something ‘Big Bang Theory’ stuff.
Believe it or not, we are actually make this today! Here’s what we’ll be doing today:
Continuing to work with Dino gem, let’s get it started.
Step 1. Install Dino Gem
If you have already installed the Dino gem, you don’t need to reinstall it. If not, go to first part of RubyBits series to see how to install Dino gem.
2. Write the Code
This is going to be very similar to what we did in controlling the LED through button but this time, we will make it work using PubNub.
1. Run in terminal
gem install pubnub.
2. Create a new file and put the following code:
This is the same as what we have been doing already.
3. Now we initialize and set up our pubnub instance variable.
You’ll need your pub/sub keys. To get your unique pub/sub keys, you’ll first need to sign up for a PubNub account. Once you sign up, you can get your unique PubNub keys in the PubNub Developer Dashboard. Our free Sandbox tier should give you all the bandwidth you need to build and test your messaging app with the web messaging API.
Going through the PubNub Ruby SDK docs, we see that publish_key is used for publishing the messages to the channel and subscribe key is used for subscribing to the messages in the channel.
4. Next up, we specify what message is to be sent to PubNub on a particular user’s event. (Here, pressing up and down the button).
As you can see, here I am sending/publishing the message
"button_status" => "PRESSED" to the channel
We can only send messages through channel, then we run the run the logic on those messages on the side which is subscribed to the channel and then make something happen.
5. Now we are going to run the logic on the messages that we receive from the channel through subscribe.
data is a JSON object. We are extracting the value of
button_status key from message payload and checking it’s value and then making LED on/off based on that.
Save file as
3. Run the Code in Terminal
Go into the directory where the file is located inside the terminal. Run
Take a bow. You’ve just programmed the Arduino with the modular power of Ruby.
If you have a button in India which is connected to a channel through arduino and you got a lamp which is connected to the same channel half-way round the world, now you can control it with these 50 lines code under 0.25 seconds!