November 16, 2009 by Dave
    Lately, We've been using the Programmable Arduino Microcontroller with some fun projects. We usually program the Arduino to send data to other devices using Serial Communication. Since we also love ruby, we decided to use Ruby to handle all the communications that the Arduino sends to a computer. With this in mind, I thought I'd share a little tutorial of how you can do this.

In this example, we're going to program the Arduino to send random data(between 0 and 100) over a serial port to a host computer. On the Host computer, we're going to be running a ruby program that will monitor the serial port and print out any data sent to it on the command line. Here's the code(also known as a sketch in arduino lingo) we're going to upload into the Arduino, using the Arduino Software:
/* 
  Feed Simulated data via serial(COM) port to computer.
  This simulated data will be used by a program on the computer to handle serial data from a device.  
*/

void setup() 
{ 
  Serial.begin(9600); 
  Serial.println("Begin Simulated Serial Data Generation!"); 
} 



int interval_time = 500; // Interval between data being sent. (in ms)
int min_num = 1; // min value to generate data, must be above 1
int max_num = 100; // max value to generate
int sim_data = 0; // initialize data var

void loop() 
{ 
  sim_data = random(min_num, max_num);
  Serial.println(sim_data);
  delay(interval_time); // wait
} 
Then, create a new ruby file with following code(we're going to name our ruby file serial_test.rb).
 require 'rubygems'
 require 'serialport' # use Kernel::require on windows, works better.

  #params for serial port
  port_str = "COM3"  #may be different for you
  baud_rate = 9600
  data_bits = 8
  stop_bits = 1
  parity = SerialPort::NONE
  
  sp = SerialPort.new(port_str, baud_rate, data_bits, stop_bits, parity)
  
  #just read forever
  while true do
    sp_char = sp.getc
    if sp_char
      printf("%c", sp_char)
    end
  end
Then execute the script, and you'll see all the data being sent by the Arduino! Here's what you should be seeing:
Begin Simulated Serial Data Generation!
77
35
78
84
86
81
...
You can do anything with the data, depending on your what your goal is. In my case, I'm getting sensor data from the Arduino that I display in a pretty fxruby windows application, then I save the data in a MySQL database for statistical analysis. Fun stuff!

1 Comments

RoseJuliet33

May 27 2010 at 08:34 AM

That is cool that people can get the <a href="http://lowest-rate-loans.com/topics/personal-loans">personal loans</a>
moreover, that opens new possibilities.


Add A Comment





Completely Private, used for Gravatar



example: https://www.whatever.com