Mentally Reframing Ruby – Part 2

What the What with the Gmail

After my first experiment with Ruby and Arduino, I wanted to try writing a sketch that would build off of the code I had written from the blinking LED test. Using the blinking LED as an indicator, I thought it would be interesting to see if I could get my Ardunio talking with Gmail to alert me if I had any unread inbox messages. After doing some research, I found a Ruby gem called Gmail that allows me to do just that.


Requiring the Right Gems

Here we’re going to set up the sketch with the gems we’ll be running.

1
2
3
require 'bundler/setup'
require 'gmail'
require 'dino'

Board in the USA

Dino requires us to define our board, tell it that we’ll be inputing and outputing data, and tell it that we’re using a serial connection (since my Ardunio is hooked up via USB). Next, we’ll be defining our LED variable, which should be easy since it was in the previous sketch.Note: Dino also offers a good directory full of example code for setting up any given component.

Setting up dino

1
2
board = Dino::Board.new(Dino::TxRx::Serial.new)
led = Dino::Components::Led.new(pin: 13, board: board)

You’ve Got Mail

In the next few lines of code we: call on Gmail to let us access our inbox, check if our inbox is empty, set the led variable to a resting state, and define a variable equal to the number of unread emails. Note: In the code listed below, you’d actually pass in your real email address and password.

1
2
3
4
Gmail.connect("user@gmail.com", "password") do |gmail|
led.off
puts "Total Unread Emails: #{gmail.inbox.count(:unread)}"
has_unread = gmail.inbox.count(:unread) !=0

Ruby Slippers

Now that we have access to our inbox, we can finish up this sketch by writing an if statement to blink our led when our inbox is not at zero.

1
2
3
4
5
6
7
if has_unread != 0
[:on, :off].cycle do |switch|
led.send(switch)
sleep 0.5
end
end
end

Next Steps

I’m hoping to take this further by:

  • Writting in a delay and loop so that the sketch runs every 5-10 min
  • Adding an rgbLED so that I can light up a red LED when the inbox is full and a green LED when the inbox is empty.