Skip to content

Instantly share code, notes, and snippets.

@basbloemsaat
Created February 24, 2013 09:34
Show Gist options
  • Select an option

  • Save basbloemsaat/5023239 to your computer and use it in GitHub Desktop.

Select an option

Save basbloemsaat/5023239 to your computer and use it in GitHub Desktop.
Set random colors on an LED on the RPi GPIO pins. Does not work as well as kiglow.pl because the frequency is too low to actually do PWM.
#!/usr/bin/env perl
use 5.014;
use constant STEPS => 50;
our $pins = {
red => 17,
green => 27,
blue => 22,
};
initpins($pins);
$SIG{'INT'} = sub {
say " exiting...";
foreach (qw(red green blue)) {
setpin($pins->{$_},0);
};
uninitpins($pins);
exit;
};
while (1) {
my $randomcolor = {
red => int(rand(STEPS)),
green => int(rand(STEPS)),
blue => int(rand(STEPS)),
};
foreach my $i (0..10) {
setColor(color => $randomcolor);
}
}
exit;
sub setColor {
my $args = {
color => {
red => 0,
green => 0,
blue => 0,
},
@_
};
my $color = $args->{color};
my $i=0;
foreach $i (0 .. STEPS) {
foreach (qw(red green blue)) {
if($color->{$_} == 0) {
setpin($pins->{$_},0);
} elsif ((($i * STEPS) % int((STEPS**2)/$color->{$_})) < STEPS) {
setpin($pins->{$_},1);
} else {
setpin($pins->{$_},0);
}
}
}
}
sub setpin {
open my $pinvalue, '>', '/sys/class/gpio/gpio' . shift . '/value';
print $pinvalue shift;
close $pinvalue;
}
sub initpins {
my $pins = shift;
foreach my $pin (values(%$pins)) {
open my $export, '>', '/sys/class/gpio/export';
say $export "$pin";
close $export;
open my $pindirection, '>', '/sys/class/gpio/gpio' . $pin . '/direction';
print $pindirection 'out';
close $pindirection;
}
}
sub uninitpins {
my $pins = shift;
foreach my $pin (values(%$pins)) {
open my $unexport, ">", "/sys/class/gpio/unexport";
say $unexport "$pin";
close $unexport;
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment