This is a silly program that blinks the green and red LEDs lights on Rasberry Pi 3 models (probably works for RPI 4 too). It is written in perl, but frankly, you don’t need anything more than shell commands.
#!/usr/bin/env perl
use strict;
use warnings;
# https://www.raspberrypi.org/forums/viewtopic.php?p=136266#p136266
main();
sub main {
if ( $> != 0 ) {
die( "Must run as root\n" );
}
unset_led0_mode();
unset_led1_mode();
for ( 1 .. 3 ) {
led0_on();
print STDOUT "on\n";
led1_off();
sleep 1;
led0_off();
led1_on();
print STDOUT "off\n";
sleep 2;
}
reset_default_led0_mode();
reset_default_led1_mode();
}
sub set_led_trigger_mode {
my ( $led, $mode ) = @_;
$led //= 'led0';
do {
local $|;
open( my $out, '>', '/sys/class/leds/$led/trigger' )
|| warn( $! );
select $out;
$|++;
print $out $mode;
close $out;
};
}
sub unset_led0_mode {
set_led_trigger_mode( 'led0', 'none' );
}
sub unset_led1_mode {
set_led_trigger_mode( 'led1', 'node' );
}
sub reset_default_led0_mode {
set_led_trigger_mode( 'led0', 'mmc0' );
}
sub reset_default_led1_mode {
set_led_trigger_mode( 'led1', 'default-on' );
}
sub change_led {
my ( $led, $state ) = @_;
$led //= 'led0';
$state = $state ? 1 : 0;
do {
local $|;
open( my $out, '>', '/sys/class/leds/$led/brightness' )
|| warn( $! );
select $out;
$|++;
printf $out "%d\n", $state;
close $out;
};
}
sub led0_on {
change_led( 'led0', 1 );
}
sub led0_off {
change_led( 'led0', 0 );
}
sub led1_on {
change_led( 'led1', 1 );
}
sub led1_off {
change_led( 'led1', 0 );
}