-
Notifications
You must be signed in to change notification settings - Fork 2
/
phpi2c.php
80 lines (66 loc) · 2.43 KB
/
phpi2c.php
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
<?php
/* ------------------------------------------------------------------------------------------------
Copyright © 2016, Viacheslav Baczynski, @V_Baczynski
License: MIT License
PHP IIC Library, v1.0
Simple functions to read from and write to registers on device via I2C bus using i2c-tools.
TODO:
Define the following variables in your file:
$block // Block name for the I2C device on the system
$i2c_address // I2C slave address (address of the device)
------------------------------------------------------------------------------------------------ */
# READ FUNCTIONS ----------------------------------------------------------------------------------
function read_register(
$register // register in the i2c device
){
return trim( shell_exec( 'i2cget -y ' . $GLOBALS['block'] . ' ' . $GLOBALS['i2c_address'] . ' ' . $register . ' b' ) );
}
function read_short(
$reg_msb // register with most significant byte
){
$msb = intval( read_register( $reg_msb++ ), 16 );
$lsb = intval( read_register( $reg_msb ), 16 );
$val = ( $msb << 8 ) | $lsb;
$arr = unpack( 's', pack( n, $val ) );
$dec_val = $arr[1];
//echo "DEBUG(read_short): " . $dec_val . "\n";
return $dec_val;
}
function read_ushort(
$reg_msb // register with most significant byte
){
$msb = intval( read_register( $reg_msb++ ), 16 );
$lsb = intval( read_register( $reg_msb ), 16 );
$val = ( $msb << 8 ) | $lsb;
$arr = unpack( 'S', pack( n, $val ) );
$dec_val = $arr[1];
//echo "DEBUG(read_ushort): " . $dec_val . "\n";
return $dec_val;
}
function read_ulong(
$reg_msb // register with most significant byte
){
$msb= intval( read_register( $reg_msb++ ), 16 );
$lsb= intval( read_register( $reg_msb++ ), 16 );
$xlsb = intval( read_register( $reg_msb ), 16 );
$val = ( $msb << 16 ) | ( $lsb << 8 ) | $xlsb;
$arr = unpack( 'l', pack( N, $val ) );
$dec_val = $arr[1];
//echo "DEBUG(read_ulong): " . $dec_val . "\n";
return $dec_val;
}
# WRITE FUNCTIONS ---------------------------------------------------------------------------------
function write_register(
$register, // register address
$value // data to be written
){
shell_exec( 'i2cset -y ' . $GLOBALS['block'] . ' ' . $GLOBALS['i2c_address'] . ' ' . $register . ' ' . $value . ' b' );
}
function write_short(
$register, // register address
$value // data to be written
){
$value = $value & 0xFF;
write_register( $register, $value );
}
?>