NAME
RPi::I2C - Interface to the I2C bus on the Raspberry Pi
SYNOPSIS
use RPi::I2C;
my $addr = 0x3c;
my $data = 0xFF;
my $i2c_dev = RPi::I2C->new($addr);
# simple byte write/read (default register, 0x00)
$i2c_dev->write($data);
my $byte = $i2c_dev->read;
# write and read byte from specific register
# ...the register does not have to be specified
# if you're using the default (0x00)
my $register = 0x01;
$i2c_dev->write_byte($data, $register);
$byte = $i2c_dev->read_byte($register);
# write and read two bytes (word) from specific register
$i2c_dev->write_word($data, $register);
my $word = $i2c_dev->read_word($register);
DESCRIPTION
Interface to the I2C bus. This API is designed to operate on the Raspberry Pi platform, but should work on other devices, possibly with some tweaking.
Requires wiringPi v2.36+ to be installed.
METHODS
new($addr)
Instantiates a new I2C device object ready to be read from and written to.
Parameters:
$addr
Mandatory, Integer (in hex): The address of the device on the I2C bus (i2cdetect -y 1
). eg: 0x78
.
read
Performs a simple read of a single byte from the device, and returns it.
read_byte($reg)
Same as "read", but allows you to optionally specify a specific device register to read from.
Parameters:
$reg
Optional, Integer: The device's register to read from. eg: 0x01
. Defaults to 0x0
.
read_word($reg)
Same as read_byte()
, but reads two bytes (16-bit word) instead.
write($data)
Performs a simple write of a single byte to the I2C device.
Parameters:
$data
Mandatory, 8-bit unsigned integer: The byte to send to the device.
write_byte($data, $reg)
Same as write()
, but allows you to optionally specify a specific device register to write to.
Parameters:
$data
Mandatory, 8-bit unsigned integer: The byte to send to the device.
$reg
Optional, Integer: The device's register to write to. eg: 0x01
. Defaults to 0x0
.
write_word($data, $reg)
Same as write_byte()
, but writes two bytes (16-bit word) instead.
fd
Returns the file descriptor of the I2C channel. Do not send anything into this method. It is for read convenience only.
addr
Returns the I2C bus address of the current I2C device object. Do not send anything into this method, or else you'll lose communication with the device.
AUTHOR
Steve Bertrand, <steveb at cpan.org>
LICENSE AND COPYRIGHT
Copyright (C) 2017 by Steve Bertrand
This library is free software; you can redistribute it and/or modify it under the same terms as Perl itself, either Perl version 5.18.2 or, at your option, any later version of Perl 5 you may have available.