Contents Up Previous Next

Callback Example

#!/usr/bin/perl

# If using interupts the HiPi::Interrupt module should be used
# before anything else in your script. This is because the
# module loads threads to handle interrupts for pins managed
# by HiPi::Device::GPIO, HiPi::BCM2835 and HiPi::Wiring.
# Loading first reduces your memory footprint and avoids issues
# with modules you may use that are not thread safe.

use HiPi::Interrupt;

# Some basic modules loaded

use 5.14.0;
use strict;
use warnings;
use HiPi::Device::GPIO;
use HiPi::Constant qw( :raspberry );

# instead of deriving a class we use HiPi::Interrupt::Handler 
# directly and register callbacks for one or more of: 
#
#     start, add, remove, interrupt,
#     error, continue, stop

use HiPi::Interrupt::Handler;

my $handler = HiPi::Interrupt::Handler->new;

# register a callback for interrupts

$handler->register_callback('interrupt', sub {
    my ($self, $msg ) = @_;
    say'--------------------------------';
    my $output =  ( $msg->error ) ? 'ERROR MESSAGE' : uc($msg->action) . ' HANDLED';
    say $output;
    say qq(  action    : ) . $msg->action;
    say qq(  pinid     : ) . $msg->pinid;
    say qq(  error     : ) . $msg->error;
    say qq(  value     : ) . $msg->value;
    say qq(  timestamp : ) . $msg->timestamp;
    say qq(  msgtext   : ) . $msg->msgtext;
    say qq(  pinclass  : ) . $msg->pinclass;
    say'--------------------------------';
  });

# register a callback for start

$handler->register_callback('start', sub {
    my ($self) = @_;
    say 'INTERRUPT HANDLING STARTED';
  });

# register a callback for stop

$handler->register_callback('stop', sub {
    my ($self) = @_;
    say 'INTERRUPT HANDLING STOPPED';
  }); 

# Create the pin monitoring

{
    # the pins we are going to use
    my $pinid1 = RPI_PAD1_PIN_13;
    my $pinid2 = RPI_PAD1_PIN_11;
    
    my $dev = HiPi::Device::GPIO->new;

    # setup a pin as input with a pull up
    # resistor and falling edge interrupt
    # using HiPi::Device::GPIO
    
    $dev->export_pin($pinid1);
    my $pin1 = $dev->get_pin($pinid1);
    $pin1->mode(RPI_PINMODE_INPT);
    $pin1->set_pud(RPI_PUD_OFF);
    $pin1->set_pud(RPI_PUD_UP);
    $pin1->interrupt( RPI_INT_FALL );

    # setup a pin as input with a pull down
    # resistor and rising edge interrupt
    # using HiPi::Device::GPIO
    
    # use the pin obj returned from
    # the export_pin method
    
    my $pin2 = $dev->export_pin($pinid2);
    
    $pin2->mode(RPI_PINMODE_INPT);
    $pin2->set_pud(RPI_PUD_OFF);
    $pin2->set_pud(RPI_PUD_DOWN);
    $pin2->interrupt( RPI_INT_RISE );

    # add as many pins as we want
    $handler->add_pin($pin1);
    $handler->add_pin($pin2);
}

# run the application loop
$handler->poll();

1;




Contents Up Previous Next


HiPi Modules Copyright © 2013 Mark Dootson