#include <stdio.h>
#include <unistd.h>

#include "../hubolib.h"
#include "../hubocfg.h" // Required for changing default I2C device.

using namespace HuboLib;

/*
Compile and link: 
	g++ DigitalSlaveOutput1.cpp -L../ -lhubo -lpthread -lrt -o DigitalSlaveOutput1.out
Run:
	sudo ./DigitalSlaveOutput1.out
Purpose:
	Set all digital outputs of the i2c slave 0 (0x21) in one go or one by one.
*/

int main(void)
{
	// If required - set the I2C device to work with. The Raspberry Pi uses "/dev/i2c-1" which is default, the Banana Pi uses "/dev/i2c-0"
	#ifdef BPI
	    g_I2CConfig.m_sI2CDevice = "/dev/i2c-0";
	#endif

	// Initialize the library once in your program.
	if (!Initialize())
	{
		printf ("Error: Initialize\n");
		return 1;
	}
	
	int slaveNo = 0;
	
	// Reset all channels.
	printf ("Clearing all channels\n");
	Set_Slave_DO_Channels(slaveNo, 0x00);
	usleep (1000000);
	
	// Set one channel after the other.
	for (int i=0; i<8; i++)
	{
		// Turn on channel i.
		printf ("Setting channel %d\n", i);
		Set_Slave_DO_Channel(slaveNo, i, 1);
		usleep (1000000);
	}

	// Clear one channel after the other.
	for (int i=0; i<8; i++)
	{
		// Turn off channel i.
		printf ("Clearing channel %d\n", i);
		Set_Slave_DO_Channel(slaveNo, i, 0);
		usleep (1000000);
	}
	
	// Set all channels.
	printf ("Setting all channels\n");
	Set_Slave_DO_Channels(slaveNo, 0xFF);

	// If you omit this "wait" then it might happen that the last call to Set_Slave_DO_Channels(0xFF) is not 
	// sent to the hardware anymore since the Uninitialize() call below has terminated before!
	usleep (1000000);
	
	// Free library resources.
	Uninitialize();
	
	return 0;
}
