Arduino and Perl

So just started learning Perl (because, well, why not?), and in trying to find something to do with it, I found a module on CPAN for using serial with an Arduino. Now if you have followed this blog at all, you will know that the Arduino is the first device I go to when I need some hardware controlling, so learning a new programming language to then control said hardware was not much of a massive leap. So with that, I pulled out an Arduino, booted up gedit, and set to work!

The first thing to do was to create the Arduino program. This one was quite simple, just accepts characters on the serial port, and then turns on or off its LED depending on what it was sent.


void setup() {
Serial.begin(9600);
Serial.println("Ready!!!");
}

char in;

void loop() {
if(Serial.available() > 0) {
in = Serial.read();
switch(in) {
case 'a':
digitalWrite(13, HIGH);
break;
case 'b':
digitalWrite(13, LOW);
break;
default:
Serial.println("Invalid Character");
break;
}
}
}

As you can see, just a very simple switch that turns the LED on 13 on or off depending on what it reads. So, on to the Perl part!


#! /usr/bin/perl

use strict;
use warnings;

use Device::SerialPort::Arduino;

my $Arduino = Device::SerialPort::Arduino->new(
 port => '/dev/ttyUSB0',
 baudrate => 9600,

databits => 8,
 parity => 'none',
 );

my $in;

print("a or b, q to exit\n");

do {
 $in = <>;
 if(length ($in) > 2) {
 print("Too long!!!\n");
 } elsif($in ne "\n") {
 $Arduino->communicate($in);
 }

} while($in ne "q\n");

Now, this bit is also very simple, at the moment. After calling the module (Device::SerialPort::Arduino) and initialising it, the ‘do, while’ loop just takes and input, and only sends it if it is 2 characters long (a character, and a newline).

Using these two, if I send an ‘a’, the light turns on, and if I send a ‘b’ the light turns off! and if I type in ‘q’ it ends the program. Now, as I’ve said, this is quite a simple piece. So to extend this, I’m going to create a ‘proper’ interface (read: a gui that turns it on and off!). Tune in next time!

Leave a Comment

Your email address will not be published. Required fields are marked *

This site uses Akismet to reduce spam. Learn how your comment data is processed.