tags:

views:

40

answers:

3

I'm new to Ruby and need to take 10 character rfid token serial data (from arduino & parallax rfid reader) and convert it to a string. It doesn't look like anything is being added to string. I am getting the rfid token data in the terminal window when I scan the token if that helps.

require 'rubygems'  
require 'serialport'   

 #params for serial port  
 port_str = "/dev/tty.usbserial-A4000ORO"    
 baud_rate = 2400  
 data_bits = 8  
 stop_bits = 1  
 parity = SerialPort::NONE  
 sp = SerialPort.new(port_str, baud_rate, data_bits, stop_bits, parity) 

 rfid_token = String.new 

 while true do  
   sp_char = sp.getc 
   rfid_token[0] = sp_char

   if sp_char  
     printf("%c", sp_char)  
   end  

   if rfid_token.size == 10
     puts "full token"
   end   


 end

  puts rfid_token
A: 

to create a string using getch it's something like

a = ""; a << 36 # => "$"
rogerdpack
A: 

I can't tell what's going wrong in your code, but one thing I see is that you're continually assigning to rfid_token[0]. The string won't grow this way, you're just replacing the first character over and over again. Instead, you'll want to append to the string like this.

rfid_token << sp_char

I've done a few things with the Arduino and Linux you can read about here. I just used gets to read strings. Depending on how the Arduino is sending the data, you could probably do that as well.

AboutRuby
A: 

Here's a code that will work:

 require 'rubygems'  
 require 'serialport'   

 #params for serial port  
 port_str = "/dev/tty.usbserial-A4000ORO"    
 baud_rate = 2400  
 data_bits = 8  
 stop_bits = 1  
 parity = SerialPort::NONE  
 sp = SerialPort.new(port_str, baud_rate, data_bits, stop_bits, parity) 

 rfid_token = "" 

 while true do
   rfid_token << sp.getc

   printf("%c", rfid_token[-1])

   if rfid_token.size == 10
     puts "full token"
     break; #exits loop if you don't want to add more than 10 chars
   end   
 end

 puts rfid_token
Daniel Cukier