#include "stepper_strip.h"
#include "AI8051U_I2C.h"
#include "string.h"
#include "intrins.h"

StepperStripHandleTypeDef stepper_strip;


static void stepper_strip_delay()
{
	unsigned long edata i;

	_nop_();
	_nop_();
	i = 9999998UL;
	while (i) i--;
}


void stepper_strip_init()
{
	i2c_init();
	stepper_strip_delay();
	memset(&stepper_strip, 0, sizeof(StepperStripHandleTypeDef));

	stepper_strip.remain_steps = MAX_DIV_8_STEPS;
	if(read_motor_is_reposition() == 0)
	{
		set_motor_reposition();
		while(1)
		{
			stepper_strip_delay();
			if(read_motor_is_reposition() == 1)
			{
				set_motor_subdivision(SUBDIVISION_8);
				break;
			}
		}
	}
}

int8_t read_motor_is_reposition()
{
	i2c_read_data(STEPPER_STRIP_ADDR << 1, MOTOR_AUTO_REPOSITION_REG, &stepper_strip.is_reset, sizeof(stepper_strip.is_reset));

	return stepper_strip.is_reset;
}

void set_motor_reposition()
{
	uint8_t set_value = 1;
	
	i2c_write_data(STEPPER_STRIP_ADDR << 1, MOTOR_AUTO_REPOSITION_REG, &set_value, sizeof(set_value));
}

void set_motor_subdivision(uint8_t num)
{
	uint8_t set_subdivision = num;
	
	i2c_write_data(STEPPER_STRIP_ADDR << 1, MOTOR_STEPS_DRIVER_MODE_REG, &set_subdivision, sizeof(set_subdivision));
}

void set_motor_move(int32_t step)
{
	stepper_strip.steps = step;
	
	i2c_write_data(STEPPER_STRIP_ADDR << 1, MOTOR_STEPS_REG, (uint8_t*)&stepper_strip.steps, sizeof(stepper_strip.steps));
}
