Skip to content

Instantly share code, notes, and snippets.

@Xhendos
Created June 25, 2016 14:16
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save Xhendos/dc217e3cd8610aacc76333e17df52c6b to your computer and use it in GitHub Desktop.
Save Xhendos/dc217e3cd8610aacc76333e17df52c6b to your computer and use it in GitHub Desktop.
#include <stdlib.h>
#include <unistd.h>
#include <linux/i2c-dev.h>
#include <sys/ioctl.h>
#include <fcntl.h>
#include <string.h>
#include <stdio.h>
#include <iostream>
#include </home/pi/Programming/C++/I2C/include/I2C.h>
using namespace std;
int main()
{
int file;
int address = 0x36;
int time_us;
double multiplier = 0.171500;
unsigned char writeBuffer[4];
unsigned char readBuffer[4];
/*
*
*Attempt to open the file & start I2C communications.
*"Also contains a check."
*
*
*/
file = open("/dev/i2c-1", O_RDWR);
if(file < 0)
{
std::cout << "[SYSTEM] Error to open file " << file << std::endl;
}
ioctl(file, I2C_SLAVE, address);
cout << "[SYSTEM] Succesfully made a connection to the SLAVES" << endl;
/*
*
*Build and send the command.
*
*/
int length = 1;
writeBuffer[0] = UB_COMMAND_GET_FILTER_USM1;
if(write(file, writeBuffer, length) != length)
{
cout << "[SYSTEM] Error sending command." << endl;
}
/*
*
*Read the reply.
*
*/
if(read(file, readBuffer, length) == length)
{
time_us = ((unsigned int) readBuffer[1] << 8) + (unsigned int) readBuffer[2];
cout << "readBuffer[1] " <<(unsigned int) readBuffer[1] << endl;
cout << ((unsigned int) readBuffer[1] << 8) << endl;
cout << "readBuffer[2] " << (unsigned int) readBuffer[2] << endl;
cout << "readBuffer[3] " << (unsigned int) readBuffer[3] << endl;
cout << "readBuffer[4] " << (unsigned int) readBuffer[4] << endl;
cout << "Value: " << time_us << endl;
} else
{
cout << "[SYSTEM] Failed to read the reply." << endl;
}
double result = (double)time_us * multiplier;
cout << "Distance (mm): " << result << endl;
return 0;
}
@Xhendos
Copy link
Author

Xhendos commented Jun 27, 2016

Problem solved.
int length should not be 1 but 4 because the array need to hold 4 places.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment