#include <arduino.h>
#include <sr_74hc165.h>

/*
 * Init a shift register structure.
 * prms:
 *  shreg - shift reg struct
 *  pin_load  - load pin (SH/LD)
 *  pin_clock - clock pin (CLK)
 *  pin_data  - data pin (Qh)
 */
void
sr_74hc165_init(struct sr_74hc165 *shreg, uint8_t pin_load, uint8_t pin_clock,
uint8_t pin_data)
{
	shreg->pin_load = pin_load;
	pin_mode(pin_load, OUTPUT);
	shreg->pin_clock = pin_clock;
	pin_mode(pin_clock, OUTPUT);
	shreg->pin_data = pin_data;
	pin_mode(pin_data, INPUT);

	pin_write(pin_load, 1);
	pin_write(pin_clock, 0);
}

/*
 * Load data into a specified register.
 * prms:
 *  shreg - shift reg struct
 */
void
sr_74hc165_load(struct sr_74hc165 *shreg)
{
	pin_write(shreg->pin_clock, 0);
	pin_write(shreg->pin_load, 0);
	pin_write(shreg->pin_load, 1);
}

/*
 * Read the next bit of data from specified shift reg.
 * prms:
 *  shreg - shift reg struct
 * ret:
 *  VAL - a one bit
 *
 * After a bit is read a reg data is shifted (prepared for the next function call).
 */
uint8_t
sr_74hc165_read_nextbit(struct sr_74hc165 *shreg)
{
	uint8_t ret;

	ret = pin_read(shreg->pin_data);
	pin_write(shreg->pin_clock, 1);
	pin_write(shreg->pin_clock, 0);
	return ret;
}

/*
 * Read the next byte of data from specified shift reg.
 * prms:
 *  shreg - shift reg struct
 * ret:
 *  VAL - a one byte
 */
uint8_t
sr_74hc165_read_nextbyte(struct sr_74hc165 *shreg)
{
	uint8_t i, ret = 0;

	for(i = 0; i < 8; i++) {
		ret |= sr_74hc165_read_nextbit(shreg) << i;
		_delay_ms(10);
	}
	return ret;
}

