This sketch is a very simple sketch to show how you set up communication between your Raspberry Pi and the TapHat Arduino (compatible) board.

Here are the steps to take to make your Raspberry Pi work as a Tap controller:
1. Preparing Raspberry Pi
2. Testing the TapHat / Pi connection – Arduino side
3. Testing the TapHat / Pi connection – Pi side
4. Connecting your Hardware
5. Configuring your TapHat and valves
6. Tap Control from the Internet
7. Finishing our Python Tap Control program

Now that you have finished installing your Raspberry Pi, time to check your TapHat.
First have a look at the source code below (I2C_Test_PiTapHat example).

/*
 * J.A. Korten
 * JKSOFT Educational
 * I2C_Test_PiTapHat.ino
 * 
 * Example: Arduino side i2c communication
 * V1.0 July 12, 2017
 */

#include <Wire.h>

void setup()
{
  initLEDs();                   // See second tab (download our library)

  Wire.begin(0x10);             // Pi will see the TapHat on 0x10
  Wire.onReceive(receiveEvent); // register event
  Serial.begin(115200);         // start serial for output
  delay(1000);
  Serial.println("TapHat Communication Example");
}

void loop() {
  delay(100);
  heartBeat();
}

void receiveEvent(int howMany) {
  while (Wire.available() > 0)
  {
    byte in = Wire.read();
    if (in == 0x3A) {
      toggleAmberLed();
    }
  }
}

Explanation (skip if you are an Arduino pro)

Line 10 includes the library Wire.h to be able to communicate with the Pi using i2c. We will not discuss i2c in detail here but there is a lot of information on the Arduino.cc website and the rest of the web on that.

General
Every Arduino sketch has a setup and loop method. The setup is executed once, just after startup and the loop is executed after that and runs as long as you Arduino runs.

In setup we do ‘initLEDs()’ in the example sketch you should have a second tab “HeartBeat”. That file has the initLEDs method implemented: the blue LED (digital pin 13) and yellow/amber LED (digital pin 14) are then ready for usage.

If you use the toggleAmberLed() method, the yellow LED will turn on if it was first off and vice versa every time you call it. The heartBeat method will blink the blue LED.

Step by step
In the setup method you see Wire.begin(0x10). This means that this Arduino will show itself as an i2c Slave to the Raspberry Pi.

To receive messages from the Pi,  the sketch has an extra method (receiveEvent) that is called when the Arduino TapHat receives bytes on the i2c port.

In the receiveEvent you see two things: if a byte is available, we ‘eat it up’ by calling byte in = Wire.read(); and it then ends upon in in. We then check the byte: if the byte is 0x3A we toggle the amber LED. Note: we chose 0x3A randomly.

Finishing off
Now upload the example to the TapHat Arduino: the blue LED should be blinking. The amber LED should be on.

Next: 3. Testing the TapHat / Pi connection – Pi side