first commit

This commit is contained in:
pandacraft 2025-03-21 16:04:17 +01:00
commit a5a0434432
1126 changed files with 439481 additions and 0 deletions

170
Software/Cpp/README.md Normal file
View file

@ -0,0 +1,170 @@
### License
The MIT License (MIT)
GrovePi for the Raspberry Pi: an open source platform for connecting Grove Sensors to the Raspberry Pi.
Copyright (C) 2017 Dexter Industries
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in
all copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
THE SOFTWARE.
---
# GrovePi C++ library
This library provides the basic functions for using the GrovePi in C++.
See more about the GrovePi here: https://www.nuget.org/packages/GrovePi/
### To install package:
First of all, you have to `cd` to `../GrovePi/Software/Cpp`
```
$ tar -xzvf grovepicpp_0.1.1.tar.gz
$ cd grovepicpp_0.1.1
$ sudo dpkg --install ./grovepicpp_0.1.1.deb
```
The package contains the following sources:
* grovepi.cpp
* grove_dht_pro.cpp
* grove_rgb_lcd.cpp
### To uninstall package:
```
$ sudo dpkg --remove grovepicpp
```
### To compile with package installed:
```
g++ -Wall [dependencies[,..]].cpp -lgrovepicpp -o [program_name].out// the general format
```
```
g++ -Wall grove_relay.cpp -lgrovepicpp -o grove_relay.out // a trivial example
```
### To compile without package:
```
g++ -Wall grovepi.cpp [dependencies[,..]].cpp -o [program_name].out // the general format
```
```
g++ -Wall grovepi.cpp grove_relay.cpp -o grove_relay.out // a trivial example
```
### Then run the executable:
```
$ ./[program_name].out
```
---
# The basic library functionalities of GrovePi are:
* `initGrovePi()` : function for initializing communication w/ the GrovePi. It uses the implicit address of `0x04`
* `initDevice(uint8_t address)` : function for initializing communication with a device at a specific `address`
* `delay(milliseconds`) : function for delaying given milliseconds
* `pinMode(uint8_t pin, uint8_t mode)`: function for setting a digital/analog port accordingly. `mode` = `INPUT` / `OUTPUT`
* `digitalWrite(uint8_t pin, bool value)` : function for writing `HIGH`/`LOW` values to a digital port
* `digitalRead(uint8_t pin)` : function for returning the digital value (either `HIGH`/`LOW`) read on the given pin
* `analogWrite(uint8_t pin, uint8_t value)` : function for writing an analog value from 0-255 to a given pin
* `analogRead(uint8_t pin)` : function for reading the value on a given pin and which returns a value from 0-255
* `ultrasonicRead(uint8_t pin)` : function for returning the distance in centimeters an ultrasonic sensor reads on a given digital port pin
* `setMaxI2CRetries(int _max_i2c_retries)` : function for setting the maximum number of retries before quitting current operation - **you should not use it**
* `setGrovePiAddress(uint8_t addr)` : change the implicit GrovePi address -> this doesn't change the GrovePi's address (firmware-wise & physically), but it's only setting the address at which GrovePi is reachable - **you should not use it**
* `writeBlock(uint8_t command, uint8_t pin_number, uint8_t opt1 = 0, uint8_t opt2 = 0)` : function for issuing a command to the GrovePi. The command is targeting a certain pin. The optional arguments can be anything depending on the command. (for example for analogWriting, we would use opt1 for sending the value we want to write)
* `writeByte(uint8_t byte_val)` : it only sends a byte to the GrovePi. You can compose the `writeBlock` function by using multiple calls of this function
* `readBlock(uint8_t *data_block)` : returns via the pointer the read data from GrovePi. The length of the array is returned by the function
* `readByte()` : returns a byte from GrovePi
# Attention:
* it's currently not supported to use multiple I2C devices with this library, unless you reinitialize communication with the device you want to talk to (w/ `initgrovePi()` or `initDevice(uint8_t address)`
* for any of the given functions in this library, if an error occurs on the I2C line, a `GrovePi::I2CError()` is thrown. `GrovePi::I2CError()` is derived from `std::runtime_error`
* the library is included in `GrovePi` namespace, so don't forget to use the resolution operator or the `using` command.
# How to create a deb package:
Extract the `tar package` and `cd` into its directory. The folders' hierarchy is this.
![archive folder structure](tar_archive.PNG)
----------
You'll see that in the `source` folder there are the source files along with the `.o` object files and `.so` files (which are the shared libraries).
In order to generate the **shared libraries** we need to follow the next steps
### **Step 1**
Compile all the `.cpp` files into position independent code (object files) which are required for creating a shared library:
g++ -C -Wall -Werror -fpic [cppfile]
Run the following command to create a shared library:
g++ -shared -o libshared.so [list of .o files]
The name of the library **must** have at all times the prefix `lib` and the suffix `.so`. The rest of it is the name of the library. This means that this `libgrovepicpp.so` file name suggests that our library is called `grovepicpp`.
After we're done with it, we have to copy the shared library to the `grovepicpp_x.y.z/usr/lib` folder.
----------
### **Step 2**
Copy all the header files from the `source` folder to `grovepicpp_x.y.z/usr/include` (make sure you clean the `include` folder).
----------
### **Step 3**
Open `control` file from `grovepicpp_x.y.z/DEBIAN/` folder and modify the version accordingly.
Let's say we have a version like this: `0.2.1`:
1. the first digit represents a major release: like a complete redesign or architecture. It's generally accepted that `0` as a "major release" actually means that the release it's yet to be completed. We'll have it this way as long as we don't have a versioning scheme in all of our repo(s)
2. the second digit represents a new feature added to the current architectural scheme
3. the third digit represents a bug-fix / a really small change / and so on.
Also, please modify all the other folders name according to the version number.
----------
### **Step 4**
Go at the directory level where you can see the 2 main folders: `grovepicpp_x.y.z` & `source`.
We need to create the actual package and and we'll type:
dpkg-deb --build grovepicpp_x.y.z/
----------
### **Step 5**
`cd` out of that folder and archive the folder (with its all files) with the command:
tar -csvf grovepicpp_x.y.z.tar.gz grovepicpp_x.y.z/
----------
### Voilà! You now have a package ready to be delivered.

View file

@ -0,0 +1,73 @@
//
// GrovePi Example for using the Grove Button (http://www.seeedstudio.com/wiki/Grove_-_Button)
//
// The GrovePi connects the Raspberry Pi and Grove sensors. You can learn more about GrovePi here: http://www.dexterindustries.com/GrovePi
//
// Have a question about this example? Ask on the forums here: http://forum.dexterindustries.com/c/grovepi
//
/*
## License
The MIT License (MIT)
GrovePi for the Raspberry Pi: an open source platform for connecting Grove Sensors to the Raspberry Pi.
Copyright (C) 2017 Dexter Industries
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in
all copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
THE SOFTWARE.
*/
#include "grovepi.h"
using namespace GrovePi;
// sudo g++ -Wall grovepi.cpp grove_button.cpp -o grove_button.out -> without grovepicpp package installed
// sudo g++ -Wall -lgrovepicpp grove_button.cpp -o grove_button.out -> with grovepicpp package installed
int main()
{
int button_pin = 4; // Grove Button is connected to digital port D4 on the GrovePi
int button_state; // variable to hold the current state of the button
try
{
initGrovePi(); // initialize communications w/ GrovePi
pinMode(button_pin, INPUT); // set the button_pin (D3) as INPUT
// do this indefinitely
while(true)
{
button_state = digitalRead(button_pin); // read the button state
printf("[pin %d][button state = ", button_pin); // and print it on the terminal screen
if(button_state == 0)
printf("not pressed]\n");
else
printf("pressed]\n");
delay(100); // wait 100 ms for the next reading
}
}
catch (I2CError &error)
{
printf(error.detail());
return -1;
}
return 0;
}

View file

@ -0,0 +1,74 @@
//
// GrovePi Example for using the Grove Buzzer (http://www.seeedstudio.com/wiki/Grove_-_Buzzer)
//
// The GrovePi connects the Raspberry Pi and Grove sensors. You can learn more about GrovePi here: http://www.dexterindustries.com/GrovePi
//
// Have a question about this example? Ask on the forums here: http://forum.dexterindustries.com/c/grovepi
//
/*
## License
The MIT License (MIT)
GrovePi for the Raspberry Pi: an open source platform for connecting Grove Sensors to the Raspberry Pi.
Copyright (C) 2017 Dexter Industries
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in
all copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
THE SOFTWARE.
*/
#include "grovepi.h"
using namespace GrovePi;
// sudo g++ -Wall grovepi.cpp grove_buzzer.cpp -o grove_buzzer.out -> without grovepicpp package installed
// sudo g++ -Wall -lgrovepicpp grove_buzzer.cpp -o grove_buzzer.out -> with grovepicpp package installed
int main()
{
int buzzer_pin = 8; // Grove Buzzer is connected to digital port D8 on the GrovePi
try
{
initGrovePi(); // initialize communication with the GrovePi
pinMode(buzzer_pin, OUTPUT); // set the buzzer_pin as OUTPUT (we have a buzzer)
// do indefinitely
while(true)
{
// turn ON the buzzer for 1000 ms (1 sec)
// and put the state on the screen
digitalWrite(buzzer_pin, HIGH);
printf("[pin %d][buzzer ON]\n", buzzer_pin);
delay(1000);
// and then OFF for another 1000 ms (1 sec)
// and put the state on the screen
digitalWrite(buzzer_pin, LOW);
printf("[pin %d][buzzer OFF]\n", buzzer_pin);
delay(1000);
}
}
catch(I2CError &error)
{
printf(error.detail());
return -1;
}
return 0;
}

View file

@ -0,0 +1,89 @@
//
// GrovePi Example for using the Grove Temperature & Humidity Sensor Pro
// (http://www.seeedstudio.com/wiki/Grove_-_Temperature_and_Humidity_Sensor_Pro)
//
// The GrovePi connects the Raspberry Pi and Grove sensors.
// You can learn more about GrovePi here: http://www.dexterindustries.com/GrovePi
//
// Have a question about this example? Ask on the forums here: http://forum.dexterindustries.com/c/grovepi
//
/*
## License
The MIT License (MIT)
GrovePi for the Raspberry Pi: an open source platform for connecting Grove Sensors to the Raspberry Pi.
Copyright (C) 2017 Dexter Industries
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in
all copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
THE SOFTWARE.
*/
#include "grovepi.h"
#include "grove_dht_pro.h"
using GrovePi::DHT;
using GrovePi::delay;
using GrovePi::I2CError;
// sudo g++ -Wall grovepi.cpp grove_dht_pro.cpp grove_dht_example.cpp -o grove_dht_example.out -> without grovepicpp package installed
// sudo g++ -Wall -lgrovepicpp grove_dht_pro.cpp grove_dht_example.cpp -o grove_dht_example.out -> with grovepicpp package installed
int main()
{
int sensorPin = 4; // digital port (D4) to which we have DTH serial sensor connected
float temp = 0, humidity = 0; // variables to hold data from the DHT sensor
// initialize the BLUE module (got from the GrovePi kit)
// and use digital port 4 for the DHT sensor
DHT dht = DHT(DHT::BLUE_MODULE, sensorPin);
try
{
dht.init(); // same as initGrovePi
// do this indefinitely
while(true)
{
// read the DHT sensor values
dht.getSafeData(temp, humidity);
// and print them on the screen
printf("[temp = %.02f C][humidity = %.02f%%]\n", temp, humidity);
// and wait 100 before the other reading
// so we don't overflow the terminal
delay(100);
}
}
catch(I2CError &error)
{
// I2C error while reading / writing
printf(error.detail());
return -1;
}
catch(std::runtime_error &e)
{
// catch error on number values
// NaN & bad value readings
printf(e.what());
return -2;
}
return 0;
}

View file

@ -0,0 +1,105 @@
#include "grove_dht_pro.h"
using std::runtime_error;
using GrovePi::DHT;
/**
* function for connecting to the GrovePi
* doesn't matter whether you call it multiple times
* just check with the isConnected() function to see if you got a connection
*/
void DHT::init()
{
initGrovePi();
}
/**
* returns via its parameters the temperature and humidity
* this function is NaN-proof
* it always gives "accepted" values
*
* if bad values are read, then it will retry reading them
* and check if they are okay for a number of [MAX_RETRIES] times
* before throwing a [runtime_error] exception
*
* @param temp in Celsius degrees
* @param humidity in percentage values
*/
void DHT::getSafeData(float &temp, float &humidity)
{
int current_retry = 0;
this->getUnsafeData(temp, humidity); // read data from GrovePi once
// while values got are not okay / accepteed
while((std::isnan(temp) || std::isnan(humidity) || !this->areGoodReadings(temp, humidity))
&& current_retry < this->MAX_RETRIES)
{
// reread them again
current_retry += 1;
this->getUnsafeData(temp, humidity);
}
// if even after [MAX_RETRIES] attempts at getting good values
// nothing good came, then throw one of the bottom exceptions
if(std::isnan(temp) || std::isnan(humidity))
throw runtime_error("[GroveDHT NaN readings - check analog port]\n");
if(!DHT::areGoodReadings(temp, humidity))
throw runtime_error("[GroveDHT bad readings - check analog port]\n");
}
/**
* function for returning via its arguments the temperature & humidity
* it's not recommended to use this function since it might throw
* some NaN or out-of-interval values
*
* use it if you come with your own implementation
* or if you need it for some debugging
*
* @param temp in Celsius degrees
* @param humidity in percentage values
*/
void DHT::getUnsafeData(float &temp, float &humidity)
{
writeBlock(this->DHT_TEMP_CMD, this->pin, this->module_type);
readByte();
uint8_t data_block[33];
readBlock(data_block);
temp = DHT::fourBytesToFloat(data_block + 1);
humidity = DHT::fourBytesToFloat(data_block + 5);
}
/**
* function for converting 4 unsigned bytes of data
* into a single float
* @param byte_data array to hold the 4 data sets
* @return the float converted data
*/
const float DHT::fourBytesToFloat(uint8_t *byte_data)
{
float output;
// reinterpret_cast guarantees that if you cast a pointer
// to a different type, and then reinterpret_cast it back
// to the original type, you get the original value.
//
// as opposed to the static_cast where it only guarantees
// the address is preserved
//
// so we take the 1st address &byte_data[0],
// the 5th address &byte_data[4] (the end address)
// and translate the output into a unsigned byte type
std::copy(reinterpret_cast<const uint8_t*>(&byte_data[0]),
reinterpret_cast<const uint8_t*>(&byte_data[4]),
reinterpret_cast<uint8_t*>(&output));
return output;
}
const bool DHT::areGoodReadings(int temp, int humidity)
{
return (temp > -100.0 && temp < 150.0 && humidity >= 0.0 && humidity <= 100.0);
}

View file

@ -0,0 +1,52 @@
#ifndef GROVE_RGB_LCD_H
#define GROVE_RGB_LCD_H
#include <stdlib.h>
#include <stdio.h>
#include <string.h>
#include <linux/i2c-dev.h>
#include <fcntl.h>
#include <sys/ioctl.h>
#include <sys/types.h>
#include <sys/stat.h>
#include <stdint.h>
#include <stdexcept>
#include <cmath>
#include "grovepi.h"
namespace GrovePi
{
class DHT
{
public:
const static uint8_t BLUE_MODULE = 0;
const static uint8_t WHITE_MODULE = 1;
DHT(const uint8_t _module_type = BLUE_MODULE, const uint8_t _pin = 4)
: module_type(_module_type), pin(_pin) {
}
void init();
void getSafeData(float &temp, float &humidity);
void getUnsafeData(float &temp, float &humidity);
private:
uint8_t DEVICE_FILE; // I2C device file
const uint8_t module_type;
const uint8_t pin;
const static uint8_t DHT_TEMP_CMD = 40; // command for reaching DTH sensor on the GrovePi
const static int MAX_RETRIES = 3;
// converts the first 4 bytes of the array
// into a float
static const float fourBytesToFloat(uint8_t *data);
static const bool areGoodReadings(int temp, int humidity);
};
}
#endif

View file

@ -0,0 +1,78 @@
//
// GrovePi LED blink Example for the Grove LED Socket (http://www.seeedstudio.com/wiki/Grove_-_LED_Socket_Kit)
//
// The GrovePi connects the Raspberry Pi and Grove sensors. You can learn more about GrovePi here: http://www.dexterindustries.com/GrovePi
//
// Have a question about this example? Ask on the forums here: http://forum.dexterindustries.com/c/grovepi
//
/*
## License
The MIT License (MIT)
GrovePi for the Raspberry Pi: an open source platform for connecting Grove Sensors to the Raspberry Pi.
Copyright (C) 2017 Dexter Industries
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in
all copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
THE SOFTWARE.
*/
#include "grovepi.h"
using namespace GrovePi;
// sudo g++ -Wall grovepi.cpp grove_led_blink.cpp -o grove_led_blink.out -> without grovepicpp package installed
// sudo g++ -Wall -lgrovepicpp grove_led_blink.cpp -o grove_led_blink.out -> with grovepicpp package installed
int main()
{
int LED_pin = 4; // Grove LED is connected to digital port D4 on the GrovePi
try
{
initGrovePi(); // initialize communication w/ GrovePi
pinMode(LED_pin, OUTPUT); // set the LED pin as OUTPUT on the GrovePi
delay(1000); // wait 1 second
printf("This example will blink a Grove LED connected to the GrovePi+ on the port labeled D4.\n");
printf("If you're having trouble seeing the LED blink, be sure to check the LED connection and the port number.\n");
printf("You may also try reversing the direction of the LED on the sensor.\n\n");
printf("Connect the LED to the port label D4!\n");
// do indefinitely
while(true)
{
// 1 second the LED is HIGH -> ON
digitalWrite(LED_pin, HIGH);
printf("[pin %d][LED ON]\n", LED_pin);
delay(1000);
// and another second LED is LOW -> OFF
digitalWrite(LED_pin, LOW);
printf("[pin %d][LED OFF]\n", LED_pin);
delay(1000);
}
}
catch(I2CError &error)
{
printf(error.detail());
return -1;
}
return 0;
}

View file

@ -0,0 +1,79 @@
//
// GrovePi Example for using the Grove LED for LED Fade effect (http://www.seeedstudio.com/wiki/Grove_-_LED_Socket_Kit)
//
// The GrovePi connects the Raspberry Pi and Grove sensors. You can learn more about GrovePi here: http://www.dexterindustries.com/GrovePi
//
// Have a question about this example? Ask on the forums here: http://forum.dexterindustries.com/c/grovepi
//
/*
## License
The MIT License (MIT)
GrovePi for the Raspberry Pi: an open source platform for connecting Grove Sensors to the Raspberry Pi.
Copyright (C) 2017 Dexter Industries
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in
all copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
THE SOFTWARE.
*/
#include "grovepi.h"
using namespace GrovePi;
// sudo g++ -Wall grovepi.cpp grove_led_fade.cpp -o grove_led_fade.out -> without grovepicpp package installed
// sudo g++ -Wall -lgrovepicpp grove_led_fade.cpp -o grove_led_fade.out -> with grovepicpp package installed
int main()
{
int LED_pin = 5; // Grove LED is connected to digital port D5 on the GrovePi
int brigthness = 0; // initial brigthness of 0 (0 to 255)
try
{
initGrovePi();
pinMode(LED_pin, OUTPUT); // set the LED pin as OUTPUT
delay(1000); // and wait a second
// do indefinitely
while(true)
{
// reset if above 255
// the GrovePi has 8-bit DAC
if(brigthness > 255)
brigthness = 0;
// and set the LED brigthness
analogWrite(LED_pin, brigthness);
float percentage_brightness = 100 * float(brigthness) / 255;
printf("[pin %d][led brigthness = %.2f%%]\n", LED_pin, percentage_brightness);
// increment brigthness for next iteration
brigthness += 10;
delay(50);
}
}
catch(I2CError &error)
{
printf(error.detail());
return -1;
}
return 0;
}

View file

@ -0,0 +1,96 @@
//
// GrovePi Example for using the Grove Light Sensor and the LED together to turn the LED On and OFF if the background light is greater than a threshold.
// Modules:
// http://www.seeedstudio.com/wiki/Grove_-_Light_Sensor
// http://www.seeedstudio.com/wiki/Grove_-_LED_Socket_Kit
//
// The GrovePi connects the Raspberry Pi and Grove sensors. You can learn more about GrovePi here: http://www.dexterindustries.com/GrovePi
//
// Have a question about this example? Ask on the forums here: http://forum.dexterindustries.com/c/grovepi
//
/*
## License
The MIT License (MIT)
GrovePi for the Raspberry Pi: an open source platform for connecting Grove Sensors to the Raspberry Pi.
Copyright (C) 2017 Dexter Industries
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in
all copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
THE SOFTWARE.
*/
#include "grovepi.h"
using namespace GrovePi;
// sudo g++ -Wall grovepi.cpp grove_light_sensor.cpp -o grove_ligh_sensor.out -> without grovepicpp package installed
// sudo g++ -Wall -lgrovepicpp grove_light_sensor.cpp -o grove_ligh_sensor.out -> with grovepicpp package installed
int main()
{
int light_sensor_pin = 0; // analog port A0 for the Grove Light Sensor
int LED_pin = 4; // digital port D4 for the Grove LED
int threshold = 10; // threshold value in kOhm for the Grove Light Sensor
int sensor_value; // variable to hold the Grove Light Sensor value
float resistance; // variable to hold the Grove Light Sensor's resistance value
try
{
// initialize communication with the GrovePi
initGrovePi();
// set the LED & Light pins accordingly
pinMode(light_sensor_pin, INPUT);
pinMode(LED_pin, OUTPUT);
while(true)
{
// start reading the value on the Light Sensor
sensor_value = analogRead(light_sensor_pin);
resistance = (float)(1023 - sensor_value) * 10 / sensor_value;
printf("[led pin %d][light pin %d][sensor value = %d][resistance = %.2f]", LED_pin, light_sensor_pin, sensor_value, resistance);
// check if the resistance gets beyond the threshold
// value in kOhm (check how a light sensor works)
// and turn ON/OFF the LED on the associated pin accordingly
if(resistance > threshold)
{
digitalWrite(LED_pin, HIGH);
printf("[led ON]\n");
}
else
{
digitalWrite(LED_pin, LOW);
printf("[led OFF]\n");
}
// wait 200 ms for the next reading
delay(200);
}
}
catch(I2CError &error)
{
printf(error.detail());
return -1;
}
return 0;
}

View file

@ -0,0 +1,78 @@
//
// GrovePi Example for using the Grove Relay (http://www.seeedstudio.com/wiki/Grove_-_Relay)
//
// The GrovePi connects the Raspberry Pi and Grove sensors. You can learn more about GrovePi here: http://www.dexterindustries.com/GrovePi
//
// Have a question about this example? Ask on the forums here: http://forum.dexterindustries.com/c/grovepi
//
/*
## License
The MIT License (MIT)
GrovePi for the Raspberry Pi: an open source platform for connecting Grove Sensors to the Raspberry Pi.
Copyright (C) 2017 Dexter Industries
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in
all copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
THE SOFTWARE.
*/
#include "grovepi.h"
using namespace GrovePi;
// sudo g++ -Wall grovepi.cpp grove_relay.cpp -o grove_relay.out -> without grovepicpp package installed
// sudo g++ -Wall -lgrovepicpp grove_relay.cpp -o grove_relay.out -> with grovepicpp package installed
int main()
{
int relay_pin = 4; // Grove Relay is connected to digital port D4 on the GrovePi
try
{
initGrovePi(); // initialize communication with the GrovePi
pinMode(relay_pin, OUTPUT); // set the relay's pin as OUTPUT
// do this indefinitely
while(true)
{
// turn it ON
digitalWrite(relay_pin, HIGH);
printf("[pin %d][relay ON]\n", relay_pin);
// for 5 seconds
delay(5000);
// and turn it OFF
digitalWrite(relay_pin, LOW);
printf("[pin %d][relay OFF]\n", relay_pin);
// for another 5 seconds
delay(5000);
// and repeat
}
}
catch(I2CError &error)
{
printf(error.detail());
return -1;
}
return 0;
}

View file

@ -0,0 +1,128 @@
#include "grove_rgb_lcd.h"
using GrovePi::LCD;
uint8_t LCD::DISPLAY_RGB_ADDR = 0x62;
uint8_t LCD::DISPLAY_TEXT_ADDR = 0x3e;
uint8_t LCD::CLEAR_DISPLAY = 0x01;
uint8_t LCD::DISPLAY_ON = 0x08;
uint8_t LCD::NO_CURSOR = 0x04;
uint8_t LCD::ENABLE_2ROWS = 0x28;
uint8_t LCD::PROGRAM_MODE = 0x80;
uint8_t LCD::NEW_ROW = 0xc0;
uint8_t LCD::DISPLAY_CHAR = 0x40;
uint8_t LCD::MAX_NO_CHARS = 32;
void LCD::connect()
{
// initializing with a random address
// it's just important to get the device file
this->DEVICE_FILE = initDevice(LCD::DISPLAY_TEXT_ADDR);
}
/**
* set rgb color
* if there are writes errors, then it throws exception
* @param red 8-bit
* @param green 8-bit
* @param blue 8-bit
*/
void LCD::setRGB(uint8_t red, uint8_t green, uint8_t blue)
{
this->selectSlave(LCD::DISPLAY_RGB_ADDR);
this->sendCommand(0x00, 0x00);
this->sendCommand(0x01, 0x00);
this->sendCommand(0x08, 0xaa);
this->sendCommand(0x04, red);
this->sendCommand(0x03, green);
this->sendCommand(0x02, blue);
}
/**
* Grove RGB LCD
*
* | Column
* ------------------------------------------------------
* Row | 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16
* ------------------------------------------------------
* 1 | x x x x x x x x x x x x x x x x
* 2 | x x x x x x x x x x x x x x x x
* ------------------------------------------------------
*
* Whatever text is sent to the LCD via the [str] variable
* Gets printed on the screen.
* The limit of text is determined by the amount of available
* Characters on the LCD screen.
*
* Every newline char ['\n'] takes the cursor onto the next line
* (aka on the row no. 2) and uses that space
* This means that if we have a text such "Hello\n World!",
* The first 5 characters of the word "Hello" get printed on the first line,
* whilst the rest of the string gets printed onto the 2nd line.
* So, if you use the newline char ['\n'] before the row ends,
* You will end up with less space to put the rest of the characters (aka the last line)
*
* If the text your putting occupies more than the LCD is capable of showing,
* Than the LCD will display only the first 16x2 characters.
*
* @param string of maximum 32 characters excluding the NULL character.
*/
void LCD::setText(const char *str)
{
this->selectSlave(LCD::DISPLAY_TEXT_ADDR);
this->sendCommand(LCD::PROGRAM_MODE, LCD::CLEAR_DISPLAY);
delay(50);
this->sendCommand(LCD::PROGRAM_MODE, LCD::DISPLAY_ON | LCD::NO_CURSOR);
this->sendCommand(LCD::PROGRAM_MODE, LCD::ENABLE_2ROWS);
delay(50);
int length = strlen(str);
bool already_had_newline = false;
for(int i = 0; i < length && i < LCD::MAX_NO_CHARS; i++)
{
if(i == 16 || str[i] == '\n')
{
if(!already_had_newline)
{
already_had_newline = true;
this->sendCommand(LCD::PROGRAM_MODE, LCD::NEW_ROW);
if(str[i] == '\n')
continue;
}
else if(str[i] == '\n')
break;
}
this->sendCommand(LCD::DISPLAY_CHAR, uint8_t(str[i]));
}
}
/**
* function for sending data to GrovePi RGB LCD
* @param mode see the constants defined up top
* @param command see the constants defined up top
*/
void LCD::sendCommand(uint8_t mode, uint8_t command)
{
int error = i2c_smbus_write_byte_data(this->DEVICE_FILE, mode, command);
if(error == -1)
throw I2CError("[I2CError writing data: check LCD wirings]\n");
}
/**
* the LCD has 2 slaves
* 1 for the RGB backlight color
* 1 for the actual text
* therefore there are 2 adresses
* @param slave 7-bit address
*/
void LCD::selectSlave(uint8_t slave)
{
int error = ioctl(this->DEVICE_FILE, I2C_SLAVE, slave);
if(error == -1)
throw I2CError("[I2CError selecting LCD address]\n");
}

View file

@ -0,0 +1,56 @@
// Copyright Dexter Industries, 2017
// http://dexterindustries.com/grovepi
#ifndef GROVE_RGB_LCD_H
#define GROVE_RGB_LCD_H
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <unistd.h>
#include <string.h>
#include <linux/i2c-dev.h>
#include <fcntl.h>
#include <sys/ioctl.h>
#include <sys/types.h>
#include <sys/stat.h>
#include <stdbool.h>
#include <stdint.h>
#include "grovepi.h"
namespace GrovePi
{
class LCD
{
public:
LCD() {
};
void connect();
void setRGB(uint8_t red, uint8_t green, uint8_t blue);
void setText(const char *str);
private:
void sendCommand(uint8_t mode, uint8_t command);
void selectSlave(uint8_t slave);
uint8_t DEVICE_FILE;
bool connected;
static uint8_t DISPLAY_RGB_ADDR;
static uint8_t DISPLAY_TEXT_ADDR;
static uint8_t CLEAR_DISPLAY;
static uint8_t DISPLAY_ON;
static uint8_t NO_CURSOR;
static uint8_t ENABLE_2ROWS;
static uint8_t PROGRAM_MODE;
static uint8_t NEW_ROW;
static uint8_t DISPLAY_CHAR;
static uint8_t MAX_NO_CHARS;
};
}
#endif

View file

@ -0,0 +1,78 @@
//
// GrovePi Example for using the Grove - LCD RGB Backlight (http://www.seeedstudio.com/wiki/Grove_-_LCD_RGB_Backlight)
//
// The GrovePi connects the Raspberry Pi and Grove sensors. You can learn more about GrovePi here: http://www.dexterindustries.com/GrovePi
//
// Have a question about this example? Ask on the forums here: http://forum.dexterindustries.com/c/grovepi
//
/*
## License
The MIT License (MIT)
GrovePi for the Raspberry Pi: an open source platform for connecting Grove Sensors to the Raspberry Pi.
Copyright (C) 2017 Dexter Industries
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in
all copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
THE SOFTWARE.
*/
#include "grovepi.h"
#include "grove_rgb_lcd.h"
#include <stdlib.h>
#include <stdio.h>
using namespace GrovePi;
// sudo g++ -Wall grovepi.cpp grove_rgb_lcd.cpp grove_rgb_lcd_example.cpp -o grove_rgb_lcd_example.out -> without grovepicpp package installed
// sudo g++ -Wall -lgrovepicpp grove_rgb_lcd.cpp grove_rgb_lcd_example.cpp -o grove_rgb_lcd_example.out -> with grovepicpp package installed
int main()
{
LCD lcd; // initialize new Grove LCD RGB device
try
{
// connect to the i2c-line
lcd.connect();
// set text and RGB color on the LCD
lcd.setText("Hello world!\nThis is an LCD.");
lcd.setRGB(0, 128, 64);
// continuously change color for roughly 2.5 seconds
for(int value = 0; value < 256; value++)
{
lcd.setRGB(value, 255 - value, 0);
delay(10);
}
// set final color
lcd.setRGB(0, 255, 0);
// and display a last minute text
lcd.setText("Bye bye!\nThis is line 2");
}
catch(I2CError &error)
{
printf(error.detail());
return -1;
}
return 0;
}

View file

@ -0,0 +1,96 @@
// GrovePi Example for using the Grove Rotary Angle Sensor (Potentiometer) and the Grove LED to create LED sweep
//
// Modules:
// http://www.seeedstudio.com/wiki/Grove_-_Rotary_Angle_Sensor
// http://www.seeedstudio.com/wiki/Grove_-_LED_Socket_Kit
// The GrovePi connects the Raspberry Pi and Grove sensors. You can learn more about GrovePi here: http://www.dexterindustries.com/GrovePi
//
// Have a question about this example? Ask on the forums here: http://forum.dexterindustries.com/c/grovepi
//
/*
## License
The MIT License (MIT)
GrovePi for the Raspberry Pi: an open source platform for connecting Grove Sensors to the Raspberry Pi.
Copyright (C) 2017 Dexter Industries
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in
all copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
THE SOFTWARE.
*/
#include "grovepi.h"
using namespace GrovePi;
// sudo g++ -Wall grovepi.cpp grove_rotary_angle_sensor.cpp -o grove_rotary_angle_sensor.out -> without grovepicpp package installed
// sudo g++ -Wall -lgrovepicpp grove_rotary_angle_sensor.cpp -o grove_rotary_angle_sensor.out -> with grovepicpp package installed
int main()
{
int potentiometer_pin = 0; // potentiometer is connected to A0 port
int LED_pin = 5; // potentiometer is connected to D5 port
int adc_ref = 5; // reference voltage of ADC is 5V
int grove_ref_vcc = 5; // Grove's reference voltage is 5V, regularly
int full_angle = 300; // max turning angle for the potentiomater (almost a complete turn)
try
{
initGrovePi();
pinMode(potentiometer_pin, INPUT);
pinMode(LED_pin, OUTPUT);
// do this indefinitely
while(true)
{
// start reading potentiometer's values
int sensor_value = analogRead(potentiometer_pin);
// calculate voltage
float voltage = (float)(sensor_value) * adc_ref / 1023;
// calculate rotation in degrees (0 to 300)
float degrees = voltage * full_angle / grove_ref_vcc;
// and calculate brightness for the LED
// basically we map values 0->300 to 0->255
int brightness = int(degrees / full_angle * 255);
float percentage_brightness = 100 * float(brightness) / 255;
// and give a PWM output to the LED
analogWrite(LED_pin, brightness);
// and display status data onto the terminal
printf("[rotar pin %d][led pin %d][sensor value = %d][voltage = %.2f][degrees = %.1f][brightness = %.2f%%]\n",
potentiometer_pin, LED_pin, sensor_value, voltage, degrees, percentage_brightness);
}
}
catch(I2CError &error)
{
printf(error.detail());
return -1;
}
// wait 20 ms for the next reading
// this equates to a rate of 50Hz
// so there are 50 reads / second -> more than enough
delay(20);
return 0;
}

View file

@ -0,0 +1,95 @@
//
// GrovePi Example for using the Grove Sound Sensor and the Grove LED
//
// The GrovePi connects the Raspberry Pi and Grove sensors. You can learn more about GrovePi here: http://www.dexterindustries.com/GrovePi
//
// Modules:
// http://www.seeedstudio.com/wiki/Grove_-_Sound_Sensor
// http://www.seeedstudio.com/wiki/Grove_-_LED_Socket_Kit
//
// Have a question about this example? Ask on the forums here: http://forum.dexterindustries.com/c/grovepi
//
/*
## License
The MIT License (MIT)
GrovePi for the Raspberry Pi: an open source platform for connecting Grove Sensors to the Raspberry Pi.
Copyright (C) 2017 Dexter Industries
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in
all copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
THE SOFTWARE.
*/
#include "grovepi.h"
using namespace GrovePi;
// sudo g++ -Wall grovepi.cpp grove_sound_sensor.cpp -o grove_sound_sensor.out -> without grovepicpp package installed
// sudo g++ -Wall -lgrovepicpp grove_sound_sensor.cpp -o grove_sound_sensor.out -> with grovepicpp package installed
int main()
{
int sound_sensor_pin = 0; // analog port A0 for the Grove Sound Sensor
int LED_pin = 5; // digital port D5 for the Grove LED
int threshold_value = 400; // threshold value for the sound levels (values from 0 -> 1023)
int sensor_value; // variable to hold the Sound Sensor's value
try
{
// initialize communication with the GrovePi
initGrovePi();
// set the LED & Sound pins accordingly
pinMode(sound_sensor_pin, INPUT);
pinMode(LED_pin, OUTPUT);
// do this indefinitely
while(true)
{
// read the value on the sound sensor
sensor_value = analogRead(sound_sensor_pin);
// check whether we turn the LED ON or OFF
// based on the threshold value
// and print the sensor value onto the terminal
printf("[pin %d][sensor value = %d]", sound_sensor_pin, sensor_value);
if(sensor_value > threshold_value)
{
digitalWrite(LED_pin, HIGH);
printf("[led ON]\n");
}
else
{
digitalWrite(LED_pin, LOW);
printf("[led OFF]\n");
}
// and wait 200 ms for the next reading
delay(200);
sensor_value = analogRead(sound_sensor_pin);
}
}
catch(I2CError &error)
{
printf(error.detail());
return -1;
}
return 0;
}

416
Software/Cpp/grovepi.cpp Normal file
View file

@ -0,0 +1,416 @@
// GrovePi C++ library
// v0.2
//
// This library provides the basic functions for using the GrovePi in C
//
// The GrovePi connects the Raspberry Pi and Grove sensors. You can learn more about GrovePi here: http://www.dexterindustries.com/GrovePi
//
// Have a question about this example? Ask on the forums here: http://forum.dexterindustries.com/c/grovepi
//
// History
// ------------------------------------------------
// Author Date Comments
// Karan 28 Dec 2015 Initial Authoring
// Robert April 2017 Continuing
/*
License
The MIT License (MIT)
GrovePi for the Raspberry Pi: an open source platform for connecting Grove Sensors to the Raspberry Pi.
Copyright (C) 2017 Dexter Industries
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in
all copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
THE SOFTWARE.
*/
#include "grovepi.h"
static const bool DEBUG = false;
static const int RBUFFER_SIZE = 32;
static const int WBUFFER_SIZE = 4;
static int file_device = 0;
static int max_i2c_retries = 5;
static const uint8_t DIGITAL_READ = 1;
static const uint8_t DIGITAL_WRITE = 2;
static const uint8_t ANALOG_READ = 3;
static const uint8_t ANALOG_WRITE = 4;
static const uint8_t PIN_MODE = 5;
static const uint8_t USONIC_READ = 7;
namespace GrovePi
{
// variables which can be used
// in the user-program
const uint8_t INPUT = 0;
const uint8_t OUTPUT = 1;
const bool LOW = false;
const bool HIGH = true;
uint8_t GROVE_ADDRESS = 0x04;
}
/**
* determines the revision of the raspberry hardware
* @return revision number
*/
static uint8_t gpioHardwareRevision()
{
int revision = 0;
FILE * filp = fopen("/proc/cpuinfo", "r");
char buffer[512];
char term;
if(filp != NULL)
{
while(fgets(buffer,sizeof(buffer),filp) != NULL)
{
if(!strncasecmp("revision\t", buffer, 9))
{
if(sscanf(buffer + strlen(buffer) - 5, "%x%c", &revision, &term) == 2)
{
if(term == '\n')
break;
revision = 0;
}
}
}
fclose(filp);
}
return revision;
}
/**
* determines wheter I2C is found at "/dev/i2c-0" or "/dev/i2c-1"
* depending on the raspberry model
*
* @param smbus_name string to hold the filename
*
* hw_rev 0 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15
* Type.1 X X - - X - - X X X X X - - X X
* Type.2 - - X X X - - X X X X X - - X X
* Type.3 X X X X X X X X X X X X X X
*
* hw_rev 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31
* Type.1 - X X - - X X X X X - - - - - -
* Type.2 - X X - - - X X X X - X X X X X
* Type.3 X X X X X X X X X X X X - - - -
*
*/
void GrovePi::SMBusName(char *smbus_name)
{
unsigned int hw_revision = gpioHardwareRevision();
unsigned int smbus_rev;
if(hw_revision < 4)
// type 1
smbus_rev = 1;
else if(hw_revision < 16)
// type 2
smbus_rev = 2;
else
// type 3
smbus_rev = 3;
if(smbus_rev == 2 || smbus_rev == 3)
strcpy(smbus_name, "/dev/i2c-1");
else
strcpy(smbus_name, "/dev/i2c-0");
}
/**
* sets the threshold limit
* at which an exception is thrown
* @param _max_i2c_retries number of retries
*/
void GrovePi::setMaxI2CRetries(int _max_i2c_retries)
{
// each failed retry takes 1 second
// so the number of [max_i2c_retries]
// represents the timeout on a
// transaction / connection in seconds
max_i2c_retries = _max_i2c_retries;
}
/**
* tries to get communication w/ the GrovePi
* throws I2CError on failing to establish communication
* @param 7-bit address of the slave device
*/
void GrovePi::initGrovePi()
{
file_device = initDevice(GROVE_ADDRESS);
}
/**
* for setting the address of an I2C device
* @param address 7-bit address of the slave device
*/
int GrovePi::initDevice(uint8_t address)
{
char filename[11]; // enough to hold "/dev/i2c-x"
int current_retry = 0;
int i2c_file_device;
SMBusName(filename);
// try to connect for a number of times
while(current_retry < max_i2c_retries)
{
// increase the counter
current_retry += 1;
// open port for read/write operation
if((i2c_file_device = open(filename, O_RDWR)) < 0)
{
printf("[failed to open i2c port]\n");
// try in the next loop to connect
continue;
}
// setting up port options and address of the device
if(ioctl(i2c_file_device, I2C_SLAVE, address) < 0)
{
printf("[unable to get bus access to talk to slave]\n");
// try in the next loop to connect
continue;
}
// if it got connected, then exit
break;
}
// if connection couldn't be established
// throw exception
if(current_retry == max_i2c_retries)
throw I2CError("[I2CError on opening port]\n");
return i2c_file_device;
}
void GrovePi::setGrovePiAddress(uint8_t address)
{
GROVE_ADDRESS = address;
}
/**
* writes a block of [WBUFFER_SIZE] bytes to the slave i2c device
* throws I2CError on failing to send data
* @param command command to send to GrovePi
* @param pin_number number
* @param opt1 optional argument depending on sensor/actuator/etc
* @param opt2 optional argument depending on sensor/actuator/etc
*/
void GrovePi::writeBlock(uint8_t command, uint8_t pin_number, uint8_t opt1, uint8_t opt2)
{
int output_code = -1;
int current_retry = 0;
uint8_t data_block[WBUFFER_SIZE] = {command, pin_number, opt1, opt2};
// repeat until it writes the data
// or until it fails sending it
while(output_code == -1 && current_retry < max_i2c_retries)
{
output_code = i2c_smbus_write_i2c_block_data(file_device, 1, WBUFFER_SIZE, &data_block[0]);
current_retry += 1;
}
// if the error persisted
// after retrying for [max_i2c_retries] retries
// then throw exception
if(output_code == -1)
throw I2CError("[I2CError writing block: max retries reached]\n");
}
/**
* sends a single byte to the i2c slave
* throws I2CError on failing to send data
* @param byte_val byte to be sent
*/
void GrovePi::writeByte(uint8_t byte_val)
{
uint8_t data_block[WBUFFER_SIZE] = {byte_val};
uint8_t length = 1;
int current_retry = 0;
int output_code = 0;
// repeat until it writes the data
// or until it fails sending it
while(output_code != length && current_retry < max_i2c_retries)
{
output_code = write(file_device, data_block, length);
current_retry += 1;
}
// if the error persisted
// after retrying for [max_i2c_retries] retries
// then throw exception
if(output_code != length)
throw I2CError("[I2CError writing byte: max retries reached]\n");
}
/**
* reads a block of [RBUFFER_SIZE] bytes from the slave device
* throws I2CError on failing to read data
* @param data_block pointer to hold the read data
* @return number of bytes read
*/
uint8_t GrovePi::readBlock(uint8_t *data_block)
{
int current_retry = 0;
int output_code = 0;
// repeat until it reads the data
// or until it fails sending it
while(output_code == 0 && current_retry < max_i2c_retries)
{
output_code = i2c_smbus_read_i2c_block_data(file_device, 1, RBUFFER_SIZE, data_block);
current_retry += 1;
}
// if the error persisted
// after retrying for [max_i2c_retries] retries
// then throw exception
if(output_code == 0)
throw I2CError("[I2CError reading block: max retries reached]\n");
return output_code;
}
/**
* reads 1 byte from the slave device
* throws I2CError on failing to read data
* @return value read from the slave device
*/
uint8_t GrovePi::readByte()
{
int current_retry = 0;
int output_code = -1;
// repeat until it reads the data
// or until it fails sending it
while((output_code < 0 || output_code == 255) && current_retry < max_i2c_retries)
{
output_code = i2c_smbus_read_byte(file_device);
current_retry += 1;
}
// if the error persisted
// after retrying for [max_i2c_retries] retries
// then throw exception
if(output_code < 0 || output_code == 255)
throw I2CError("[I2CError reading byte: max retries reached]\n");
return output_code;
}
/**
* sleep raspberry
* @param milliseconds time
*/
void GrovePi::delay(unsigned int milliseconds)
{
usleep(milliseconds * 1000);
}
/**
* set pin as OUTPUT or INPUT
* @param pin number
* @param mode OUTPUT/INPUT
*/
void GrovePi::pinMode(uint8_t pin, uint8_t mode)
{
writeBlock(PIN_MODE, pin, mode);
}
/**
* set a pin as HIGH or LOW
* @param pin number
* @param value HIGH or LOW
*/
void GrovePi::digitalWrite(uint8_t pin, bool value)
{
writeBlock(DIGITAL_WRITE, pin, (uint8_t)value);
}
/**
* reads whether a pin is HIGH or LOW
* @param pin number
* @return HIGH or LOW
*/
bool GrovePi::digitalRead(uint8_t pin)
{
writeBlock(DIGITAL_READ, pin);
return readByte();
}
/**
* describe at a desired pin a voltage between 0 and VCC
* @param pin number
* @param value 0-255
*/
void GrovePi::analogWrite(uint8_t pin, uint8_t value)
{
writeBlock(ANALOG_WRITE, pin, value);
}
/**
* reads analog data from grovepi sensor(s)
* @param pin number
* @return 16-bit data
*/
short GrovePi::analogRead(uint8_t pin)
{
uint8_t data[32];
writeBlock(ANALOG_READ, pin);
readBlock(data);
short output = (data[1] << 8) + data[2];
if(output == 65535)
output = -1;
return output;
}
/**
* to be completed
* @param pin number
* @return time taken for the sound to travel back?
*/
short GrovePi::ultrasonicRead(uint8_t pin)
{
uint8_t incoming[32];
short output;
writeBlock(USONIC_READ, pin);
delay(60);
readByte();
readBlock(incoming);
output = (incoming[1] << 8) + incoming[2];
if(output == (2 << 16) - 1)
output = -1;
return output;
}
const char* GrovePi::I2CError::detail()
{
return this->what();
}

65
Software/Cpp/grovepi.h Normal file
View file

@ -0,0 +1,65 @@
// Copyright Dexter Industries, 2016
// http://dexterindustries.com/grovepi
#ifndef GROVEPI_H
#define GROVEPI_H
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <unistd.h>
#include <linux/i2c-dev.h>
#include <fcntl.h>
#include <string.h>
#include <sys/ioctl.h>
#include <sys/types.h>
#include <sys/stat.h>
#include <stdbool.h>
#include <stdint.h>
#include <stdexcept>
#include <time.h>
namespace GrovePi
{
extern const uint8_t INPUT;
extern const uint8_t OUTPUT;
extern const bool LOW;
extern const bool HIGH;
extern uint8_t GROVE_ADDRESS;
void SMBusName(char *smbus_name);
void initGrovePi();
int initDevice(uint8_t address);
void setMaxI2CRetries(int _max_i2c_retries);
void setGrovePiAddress(uint8_t addr);
void writeBlock(uint8_t command, uint8_t pin_number, uint8_t opt1 = 0, uint8_t opt2 = 0);
void writeByte(uint8_t byte_val);
uint8_t readBlock(uint8_t *data_block);
uint8_t readByte();
void delay(unsigned int milliseconds);
void pinMode(uint8_t pin, uint8_t mode);
void digitalWrite(uint8_t pin, bool value);
bool digitalRead(uint8_t pin);
void analogWrite(uint8_t pin, uint8_t value);
short analogRead(uint8_t pin);
short ultrasonicRead(uint8_t pin);
// this class purpose is to give a more meaningful
// description of problem that's encountered
// and to redefine the function name for getting error details
// (as suggested by Karan)
class I2CError : public std::runtime_error
{
public:
explicit I2CError(const char *str) : std::runtime_error(str) {
}
const char* detail();
};
}
#endif

View file

@ -0,0 +1,69 @@
// GrovePi Example for using the analog read.
// http://dexterindustries.com/grovepi
/*
## License
The MIT License (MIT)
GrovePi for the Raspberry Pi: an open source platform for connecting Grove Sensors to the Raspberry Pi.
Copyright (C) 2017 Dexter Industries
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in
all copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
THE SOFTWARE.
*/
#include "grovepi.h"
using namespace GrovePi;
// sudo g++ -Wall grovepi.cpp grovepi_analog_read.cpp -o grovepi_analog_read.out -> without grovepicpp package installed
// sudo g++ -Wall -lgrovepicpp grovepi_analog_read.cpp -o grovepi_analog_read.out -> with grovepicpp package installed
int main()
{
int pin = 0; // we use port A0
int incoming; // variable to hold data for reading
try
{
initGrovePi(); //initialize communication w/ GrovePi
// set the pin mode for reading
pinMode(pin, INPUT);
// continuously read data
while(true)
{
// read the data
// receives a 10-bit value which maps to
// 0V -> VCC, where VCC is the supply voltage of GrovePi
incoming = analogRead(pin);
printf("[pin %d][analog read = %d]\n", pin, incoming);
// wait 10 ms so we don't overflow the terminal
delay(10);
}
}
catch (I2CError &error)
{
printf(error.detail());
return -1;
}
return 0;
}

View file

@ -0,0 +1,91 @@
// GrovePi Example for using the analog write
// http://dexterindustries.com/grovepi
/*
## License
The MIT License (MIT)
GrovePi for the Raspberry Pi: an open source platform for connecting Grove Sensors to the Raspberry Pi.
Copyright (C) 2017 Dexter Industries
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in
all copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
THE SOFTWARE.
*/
#include "grovepi.h"
using namespace GrovePi;
// sudo g++ -Wall grovepi.cpp grovepi_analog_write.cpp -o grovepi_analog_write.out -> without grovepicpp package installed
// sudo g++ -Wall -lgrovepicpp grovepi_analog_write.cpp -o grovepi_analog_write.out -> with grovepicpp package installed
int main()
{
int pin = 3; // we use port D3
// for direction = HIGH the value we write increases with each step
// for direction = LOW the value we write decreases with each step
int direction = HIGH;
int increment_value = 3; // step increase for PWN function
int final_value = 0; // variable to hold to value to write to GrovePi
try
{
initGrovePi(); // initialize communication w/ GrovePi
pinMode(pin, OUTPUT); // set the pin mode for writing
// continuously do this
while(true)
{
// iterate the whole range of values
// 0 -> 255 maps to 0V -> VCC, where VCC is the supply voltage on GrovePi
//
// since we're using the a PWM function
// we have a duty cycle that goes from 0% to 100% of VCC voltage
// with an increase/decrease of voltage of 100 * increment_value / 256 = 0.39% / increment
//
// google what a PWM wave is
for(int value = 0; value <= 255; value += increment_value)
{
final_value = 0; // reset it
if(direction == HIGH)
// if direction == HIGH then let the final_value take ascending values
final_value = value;
else if(direction == LOW)
// if direction == LOW then let the final_value take descending values
final_value = 255 - value;
printf("[pin %d][analog write = %d]\n", pin, final_value);
analogWrite(pin, final_value);
delay(5); // wait 5 ms for the next change in pin value
}
// if increment_value = HIGH then change it to increment_value = LOW
// if increment_value = LOW then change it to increment_value = HIGH
direction = (direction == HIGH) ? LOW : HIGH;
}
}
catch (I2CError &error)
{
printf(error.detail());
return -1;
}
return 0;
}

View file

@ -0,0 +1,70 @@
// GrovePi Example for using the digital read command
// http://dexterindustries.com/grovepi
/*
## License
The MIT License (MIT)
GrovePi for the Raspberry Pi: an open source platform for connecting Grove Sensors to the Raspberry Pi.
Copyright (C) 2017 Dexter Industries
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in
all copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
THE SOFTWARE.
*/
#include "grovepi.h"
using namespace GrovePi;
// sudo g++ -Wall grovepi.cpp grovepi_digital_read.cpp -o grovepi_digital_read.out -> without grovepicpp package installed
// sudo g++ -Wall -lgrovepicpp grovepi_digital_read.cpp -o grovepi_digital_read.out -> with grovepicpp package installed
int main()
{
int pin = 4; // use port D4
int state; // variable to hold the ON/OFF state
try
{
initGrovePi(); // initialize communication w/ GrovePi
pinMode(pin, INPUT); // set the pin for reading
// continuously read the data
while(true)
{
// read the data
state = digitalRead(pin);
printf("[pin %d][digital read = ", pin);
if(state == 0)
printf("LOW]\n");
else
printf("HIGH]\n");
// wait 50 ms so that the program doesn't run too fast
delay(50);
}
}
catch (I2CError &error)
{
printf(error.detail());
return -1;
}
return 0;
}

View file

@ -0,0 +1,69 @@
// GrovePi Example for using the digital write command
// http://dexterindustries.com/grovepi
/*
## License
The MIT License (MIT)
GrovePi for the Raspberry Pi: an open source platform for connecting Grove Sensors to the Raspberry Pi.
Copyright (C) 2017 Dexter Industries
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in
all copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
THE SOFTWARE.
*/
#include "grovepi.h"
using namespace GrovePi;
// sudo g++ -Wall grovepi.cpp grovepi_digital_write.cpp -o grovepi_digital_write.out -> without grovepicpp package installed
// sudo g++ -Wall -lgrovepicpp grovepi_digital_write.cpp -o grovepi_digital_write.out -> with grovepicpp package installed
int main()
{
int pin = 4; // we use port D4
int period = 500; // measured in ms
try
{
initGrovePi(); // initialize communication w/ GrovePi
pinMode(pin, OUTPUT); // set the pin for digital writing
// continuously digital write
// good LED Example
// [period] ms OFF / [period] ms ON
while(true)
{
printf("[pin %d][led = ON]\n", pin);
digitalWrite(pin, HIGH);
delay(period);
printf("[pin %d][led = OFF]\n", pin);
digitalWrite(pin, LOW);
delay(period);
}
}
catch (I2CError &error)
{
printf(error.detail());
return -1;
}
return 0;
}

View file

@ -0,0 +1,67 @@
// GrovePi Example for using the digital write command
// http://dexterindustries.com/grovepi
/*
## License
The MIT License (MIT)
GrovePi for the Raspberry Pi: an open source platform for connecting Grove Sensors to the Raspberry Pi.
Copyright (C) 2017 Dexter Industries
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in
all copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
THE SOFTWARE.
*/
#include "grovepi.h"
using namespace GrovePi;
// sudo g++ -Wall grovepi_us_read.cpp grovepi.cpp -o grovepi_us_read.out -> without grovepicpp package installed
// sudo g++ -Wall -lgrovepicpp grovepi_us_read.cpp -o grovepi_us_read.out -> with grovepicpp package installed
int main()
{
int pin = 4; // connected to digital port 4 (D4)
int incoming; // variable to hold the data
try
{
initGrovePi(); // initialize communication with the GrovePi
// do this indefinitely
while(true)
{
// read the processed data from the GrovePi
incoming = ultrasonicRead(pin);
// display it
printf("[pin %d][ultrasonic read = %d cm]\n", pin, incoming);
// and wait 50 ms for the ultrasonic sensor to get a new reading
delay(50);
}
}
catch(I2CError &error)
{
printf(error.detail());
return -1;
}
return 0;
}

Binary file not shown.

Binary file not shown.

After

Width:  |  Height:  |  Size: 24 KiB