Skip to content

Instantly share code, notes, and snippets.

@adlerweb adlerweb/geomag.php
Created Sep 18, 2017

Embed
What would you like to do?
<?php
$port = STDIN;
$out = array();
$b=0;
$dlc = -1;
$buffer = array();
while(!feof($port)) {
$curByte = ord(fread($port, 1));
//echo '<< 0x'.dechex($curByte)."\n";
$buffer[] = $curByte;
while(count($buffer) > 0 && $buffer[0] != 0xAA) {
array_shift($buffer);
}
if(count($buffer) < 2) continue;
if($dlc == -1) $dlc = $buffer[1];
if(count($buffer) < ($dlc+3)) continue;
switch($buffer[2]) {
case 0x03: //Status Report
if($buffer[1] != 8) {
echo 'Status report with DLC != 8 - no idea what to do…'."\n";
}
echo 'Unique sensor ID is: 0x'.dechex($buffer[5]).dechex($buffer[4]).dechex($buffer[3])."\n";
echo 'Status: 0x'.dechex($buffer[6]).' (';
switch($buffer[6]) {
case 0x00: echo 'No Car detected'; break;
case 0x01: echo 'Car detected'; break;
case 0x02: echo 'Not calibrated'; break;
default: echo 'unknown';
}
echo ")\n";
$voltage = $buffer[7] / 10;
echo 'Supply voltage: (0x'.dechex($buffer[7]).') -> '.$voltage."V\n";
$field = (($buffer[9] << 8) | $buffer[8]);
echo 'Magnetic field: (0x'.dechex($buffer[9]).'-'.dechex($buffer[8]).') -> '.(int)$field."\n";
echo 'Checksum: 0x'.dechex($buffer[10]).' - ';
$chk = 0xBB;
for($i=0; $i<($dlc+2); $i++) $chk ^= $buffer[$i];
if($chk == $buffer[10]) {
echo 'OK';
}else{
echo '!= 0x'.dechex($chk).' ERR!';
}
echo "\n";
for($i=0; $i<$dlc+3; $i++) array_shift($buffer);
break;
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
You can’t perform that action at this time.