
#include "DB101_IF.h"





/*! Send a string over USART. Polled version.
 *
 * \param  data    Data to send.
 * \param  length  Length of string to send.
 */
void SendCommand(U8 * data_ptr, U8 length)
{
	U8 i = 0;
	while (i < length) {
		uart_putcharD101(data_ptr[i++]);
	}
}


void UpdateScreen(void){
	static U8 Line0[21] = {"Motor Control Demo\n\n\r"};
	static U8 Line1[17] = {"Speed: 0000 RPM\n\r"};
	static U8 Line2[16] = {"Dir: Forwards \n\r"};
	static U8 Line3[16] = {"Dir: Backwards\n\r"};
	static U8 Line4[17] = {"Status: Running\n\r"};
	static U8 Line5[17] = {"Status: Stopped\n\r"};
	static U8 Line6[21] = {"Speed Ref: 0000 RPM\n\r"};	
	U32 SpeedCalc = mci_get_measured_speed()*27;
	U32 SpeedRef = mc_get_potentiometer_value();        
	/* Convert numbers to ASCII */
	BCD_Convert(&Line1[7], (U32) SpeedCalc, 4);
	BCD_Convert(&Line6[11], (U32) SpeedRef, 4);
	
	/* Send commands.*/
	SendCommand(&clearScreen[0], 4);
	SendCommand(&cursorHome[0], 3);
	SendCommand(&Line0[0], 21);
	SendCommand(&Line1[0], 17);
	if (mci_direction == CW){
		SendCommand(&Line2[0], 16);
	}else{
		SendCommand(&Line3[0], 16);
	}
        if (mci_run_stop == TRUE){
		SendCommand(&Line4[0], 17);
	}else{
		SendCommand(&Line5[0], 17);
	}
	SendCommand(&Line6[0], 21);        
	SendCommand(&cursorEnd[0], 7);

}

/*! Function to convert a hexadecimal number to a string.
 *
 * \param data    Pointer to a string to put the digits in,
 * \param number  A number to convert.
 * \param size    Max size of the string of numbers.
 */
void BCD_Convert(U8 * data_ptr, U32 number, U8 size){
	if (size > 7) {
		data_ptr[size-8] = 48;
		while (number >= 10000000){
			number -= 10000000;
			data_ptr[size-8]++;
		}
	}
	if (size > 6) {
		data_ptr[size-7] = 48;
		while (number >= 1000000){
			number -= 1000000;
			data_ptr[size-7]++;
		}
	}
	if (size > 5) {
		data_ptr[size-6] = 48;
		while (number >= 100000){
			number -= 100000;
			data_ptr[size-6]++;
		}
	}
	if (size > 4) {
		data_ptr[size-5] = 48;
		while (number >= 10000){
			number -= 10000;
			data_ptr[size-5]++;
		}
	}
	if (size > 3) {
		data_ptr[size-4] = 48;
		while (number >= 1000){
			number -= 1000;
			data_ptr[size-4]++;
		}
	}
	if (size > 2) {
		data_ptr[size-3] = 48;
		while (number >= 100){
			number -= 100;
			data_ptr[size-3]++;
		}
	}
	if (size > 1) {
		data_ptr[size-2] = 48;
		while (number >= 10){
			number -= 10;
			data_ptr[size-2]++;
		}
	}
	if (size > 0) {
		data_ptr[size-1] = 48;
		while (number >= 1){
			number -= 1;
			data_ptr[size-1]++;
		}
	}
}
