Created
June 25, 2016 14:16
-
-
Save Xhendos/dc217e3cd8610aacc76333e17df52c6b to your computer and use it in GitHub Desktop.
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
#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; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Problem solved.
int length should not be 1 but 4 because the array need to hold 4 places.