Created
April 15, 2016 22:04
-
-
Save simondlevy/b48e4a97e2c74da3c7ee4f20b943c460 to your computer and use it in GitHub Desktop.
Read from MaxBotix MB1242 ultransonic rangefinder using WiringPi
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// Compile with gcc -o readsonar mb1242_wiringpi.c -lwiringPi -lpthread | |
#include <wiringPiI2C.h> | |
#include <wiringPi.h> | |
#include <stdio.h> | |
#include <stdlib.h> | |
#include <stdint.h> | |
#include <stdbool.h> | |
// Updates a timed task | |
static bool check_and_update_timed_task(uint32_t * usec, uint32_t period) | |
{ | |
bool result = (int32_t)(micros() - *usec) >= 0; | |
if (result) | |
*usec = micros() + period; | |
return result; | |
} | |
int main(int argc, char ** argv) | |
{ | |
// Connect to MB1242 at seven-bit address 0x70 | |
int fd = wiringPiI2CSetup (0x70); | |
if (fd < 0) { | |
perror(""); | |
exit(1); | |
} | |
// Initialize a timed task to wait a fixed period between request and read | |
uint32_t tasktime = 0; | |
while (true) | |
// Wait 50000 microseconds between request and read | |
if (check_and_update_timed_task(&tasktime, 50000)) { | |
// Read two-byte value from the MB1242 | |
uint16_t tmp = wiringPiI2CReadReg16 (fd, 0x8F); | |
// Reverse endianness to get distance | |
int16_t distance_cm = (tmp>>8) | (tmp<<8); | |
printf("%d\n", distance_cm); | |
// Make a new request | |
wiringPiI2CWriteReg8 (fd, 0x00, 0x51) ; | |
} | |
return 0; |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment