001 /****************************************************************************
002 Definition for debugging
003  ***************************************************************************/
004 #define DEBUGGING_STATE 			// print out farmer's current state
005 #define DEBUGGING_EVENT 			// print out current event
006 //#define DEMO_MANUAL_MODE 			// trigger event by keyboard input
007 //#define DEBUGGING_ENCRYPTION_KEY 	// print out encryption key
008 //#define CALCULATE_1
009 #define CALCULATE_2
010 #define AUTOMATIC_POW_RELAY_ON
011 //#define DEBUGGING_IMU_DATA		// print out IMU value
012 #define NORMAL_OP_MODE 			// trigger event from controller input and timer
013 //#define DEBUGGING_TX_DATA 		// print out transfer data packet
014 //#define DEBUGGING_SAMPLE_DATA 	// use sample data packet for transfer
015 
016 /* To do for DOG
017 1. Update Execute command method
018 */
019 
020 /****************************************************************************
021  Module
022    DOG_TX.c
023 
024  Description
025    This is the top service for DOG which acts as a controller of the DOG
026 	 as well as its transmitter module
027 
028 ****************************************************************************/
029 
030 /*----------------------------- Include Files -----------------------------
031 */
032 /* include header files for the framework and this service
033 */
034 #include "ES_Configure.h"
035 #include "ES_Framework.h"
036 #include "ES_DeferRecall.h"
037 #include "DOG_TX.h"
038 #include "UART_Init.h"
039 #include "DOG_RX.h"
040 #include "XBEE_DEFS.h"
041 #include "inc/hw_memmap.h"
042 #include "inc/hw_types.h"
043 #include "inc/hw_gpio.h"
044 #include "inc/hw_sysctl.h"
045 #include "driverlib/sysctl.h"
046 #include "driverlib/pin_map.h"	// Define PART_TM4C123GH6PM in project
047 #include "driverlib/gpio.h"
048 #include "ES_ShortTimer.h"
049 #include "inc/hw_types.h"
050 #include "inc/hw_uart.h"
051 #include "inc/hw_nvic.h"
052 #include "inc/hw_timer.h"
053 #include "IMU_Service_SPI.h"
054 #include "ESC_Control.h"
055 #include "Servo_Control.h"
056 #include <stdlib.h>
057 #include "AnalogRead.h"
058 /*----------------------------- Module Defines ----------------------------
059 */
060 // these times assume a 1.000mS/tick timing
061 #define ONE_SEC 1000
062 #define HALF_SEC (ONE_SEC/2)
063 #define TWO_SEC (ONE_SEC*2)
064 #define FIVE_SEC (ONE_SEC*5)
065 #define LOST_COMM_TIME ONE_SEC
066 #define DIRECTION_CHANGE_TIME 100
067 
068 // packet byte definition
069 #define	START_BYTE 						0x7E
070 #define API_TX_ID 						0x01
071 #define OPTION_BYTE 					0x00
072 #define	MSB_LEN 							0x00
073 #define MAX_XBEE_PACKET_SIZE 	9
074 #define PAIR_RESPONSE_DATA_LEN 1
075 #define CHECKSUM_OFFSET				0xFF
076 #define XBEE_OVERHEAD_LEN			9
077 #define DATA_OVERHEAD_LEN			5
078 #define LARGEST_FRAME_DATA 		100
079 #define ACCEL_X_INDEX					0
080 #define ACCEL_Y_INDEX					1
081 #define ACCEL_Z_INDEX					2
082 #define GYRO_X_INDEX					3
083 #define GYRO_Y_INDEX					4
084 #define GYRO_Z_INDEX					5
085 #define	MSB_MASK							0xFF00
086 #define LSB_MASK							0x00FF
087 #define BRAKE_MASK						0x02
088 #define SPECIAL_FUNC_MASK			0x01
089 #define BRAKE_SERVO_CHANNEL		2
090 #define UNBRAKE_ANGLE 				65
091 #define BRAKE_ANGLE 					90
092 #define FORWARD_DIR 					1
093 #define BACKWARD_DIR 					2
094 #define AD_CHANNEL_NUM				1
095 /*---------------------------- Module Functions ---------------------------
096 */
097 /* prototypes for private functions for this service.They should be 
098 functions
099    relevant to the behavior of this service
100 */
101 static bool TransmitPacket();
102 static void ClearDataPacket(void);
103 static void WriteToUART(void);
104 static void ConstructPacket(void);
105 static void TurnFanOn(void);
106 static void TurnFanOff(void);
107 static void SetFarmerAddress(uint16_t input);
108 static void ResetFarmerAddress(void);
109 static void Send_PairResponse(void);
110 static void Send_StatusMessage(void);
111 static void Send_EncryptionReset(void);
112 static void ExecuteCommand(uint32_t cmd);
113 static void ConStructStatusMessage(void);
114 static void Init_Port(void);
115 static void StopMotor_Left(void);
116 static void SetMotor_Left(float input);
117 static void StopMotor_Right(void);
118 static void SetMotor_Right(float input);
119 static void SetPowerRelay(bool input);
120 static void SetLeftFan_Forward();
121 static void SetRightFan_Forward();
122 static void SetLeftFan_Backward();
123 static void SetRightFan_Backward();
124 static void Calculate_Motor_Speed(uint8_t cmd1, uint8_t cmd2);
125 static void SetBrakeOn(void);
126 static void SetBrakeOff(void);
127 static void SetSpecialFnOn(void);
128 static void SetSpecialFnOff(void);
129 static float MapToPeriod(float input);
130 static void ClearRXDataPacket(void);
131 static void ClearRXDataPacket(void);
132 static void ClearRXBuffer(void);
133 static void CopyToBuffer(void);
134 static void ReadDogTag(void);
135 static void SwitchSong(void);
136 static void playUnpairedSound(void);
137 static void playPairedSound(void);
138 /*---------------------------- Module Variables ---------------------------
139 */
140 // with the introduction of Gen2, we need a module level Priority variable
141 static uint8_t MyPriority;
142 DogTXState_t CurrentState;	//define currentstate variable for this SM
143 DogRXState_t CurrentRXState;	//define currentstate variable for this SM
144 static uint8_t DataPacket[LARGEST_FRAME_DATA]; //define datapacket array
145 static uint8_t XbeePacket[LARGEST_FRAME_DATA + MAX_XBEE_PACKET_SIZE];
146 static uint8_t DataPacket_Length;
147 static uint8_t XbeePacket_Length;
148 static uint8_t CheckSum = 0x00;
149 static uint8_t frame_id = 0x01;
150 static uint8_t byte_remaining = 0x00;
151 static uint8_t MSB_RX_ADDRESS = 0x00;
152 static uint8_t LSB_RX_ADDRESS = 0x00;
153 static uint8_t FanState = 0x01;
154 static uint8_t ACCEL_X_MSB = 0x01;
155 static uint8_t ACCEL_X_LSB = 0x02;
156 static uint8_t ACCEL_Y_MSB = 0x03;
157 static uint8_t ACCEL_Y_LSB = 0x04;
158 static uint8_t ACCEL_Z_MSB = 0x05;
159 static uint8_t ACCEL_Z_LSB = 0x06;
160 static uint8_t GYRO_X_MSB = 0x07;
161 static uint8_t GYRO_X_LSB = 0x08;
162 static uint8_t GYRO_Y_MSB = 0x09;
163 static uint8_t GYRO_Y_LSB = 0x0a;
164 static uint8_t GYRO_Z_MSB = 0x0b;
165 static uint8_t GYRO_Z_LSB = 0x0c;
166 static int index = 0;
167 static const int STATUS_MESSAGE_LEN = 13;
168 static const int ENCR_RESET_LEN = 1;
169 static uint16_t paired_farmer_address = 0x2189;
170 static uint16_t ACCEL_X_VALUE = 0;
171 static uint16_t ACCEL_Y_VALUE = 0;
172 static uint16_t ACCEL_Z_VALUE = 0;
173 static uint16_t GYRO_X_VALUE = 0;
174 static uint16_t GYRO_Y_VALUE = 0;
175 static uint16_t GYRO_Z_VALUE = 0;
176 
177 static const float MAX_CTRL_OFFSET = 1.2;
178 static const float STOP_CTRL_VALUE	= 0.8;
179 static const float MIN_CTRL_VALUE	= 1;
180 static const float MID_CTRL_VALUE	= 1.4;
181 static const float MAX_CTRL_VALUE	= 1.8;
182 static const float alpha_multiplier = 0.5;
183 static const float beta_multiplier = 1 - alpha_multiplier;
184 static float left_pow = 0.0;
185 static float right_pow = 0.0;
186 static int Ctrl_Offset = 127;
187 static int Ctrl_Stop_Tol = 15;
188 static const float left_power_percent = 1;
189 static const float right_power_percent = 0.9;
190 
191 /* Received side parameters */
192 static uint8_t RX_DataPacket_Length;
193 static uint8_t RX_CheckSum = 0x00;
194 static uint8_t Received_RX_CheckSum = 0x00;
195 static uint8_t RX_Message_MSB_Len = 0;
196 static uint8_t RX_Message_LSB_Len = 0; 
197 static uint8_t RX_DataPacket[LARGEST_FRAME_DATA] = {0}; //define datapacket 
198 array
199 static uint8_t RX_Buffer_Array[LARGEST_FRAME_DATA] = {0}; //define 
200 datapacket array
201 static int rx_index = 0;
202 
203 static bool change_dir_complete = true;
204 static int prev_direction_right = 0;
205 static int prev_direction_left = 0;
206 static int cur_direction_right = 0;
207 static int cur_direction_left = 0;
208 static uint32_t current_cmd = 0;
209 /*------------------------------ Module Code ------------------------------
210 */
211 /****************************************************************************
212  Function
213      InitDogTX
214 
215  Parameters
216      uint8_t : the priorty of this service
217 
218  Returns
219      bool, false if error in initialization, true otherwise
220 
221  Description
222      Saves away the priority, and does any 
223      other required initialization for this service
224 
225 ****************************************************************************/
226 bool InitDogTX ( uint8_t Priority )
227 {
228 		ES_Event ThisEvent;
229 		
230 		MyPriority = Priority;
231 	
232 		/********************************************
233 		 Initialization Code
234 		 *******************************************/
235 	
236 		// set up I/O lines for debugging
237 		SysCtlPeripheralEnable(SYSCTL_PERIPH_GPIOB);
238 		GPIOPinTypeGPIOOutput(GPIO_PORTB_BASE, GPIO_PIN_2);
239 	
240 		// start with the lines low
241 		GPIOPinWrite(GPIO_PORTB_BASE, GPIO_PIN_2, BIT2LO);  
242 	  
243 	
244 		// initialize current state to waiting to pair
245 		CurrentState = WaitToPair;
246 	  CurrentRXState = WaitFor7E;
247 		
248 		// Initialize variable to 0
249 		DataPacket_Length = 0;
250 		XbeePacket_Length = 0;
251 
252 		// Initialize UART
253 		Init_UART();	// this is for Xbee
254 		Init_UART_ModuleFive(); // this is for talking to TREAT
255 		
256 		// Initialize Servo
257 		InitServo();
258 		
259 		// Init PF0 and one shot timer for ESC control
260 		Init_Port();
261 		// Initialize one shot interrupt for ESC left and right
262 		InitOneShotInt_ESC_Left();
263 		InitOneShotInt_ESC_Right();
264 		
265 		// Initialize A/D Channel
266 		ADC_MultiInit(AD_CHANNEL_NUM);
267 		
268 		// Release brake
269 		SetBrakeOff();
270 		
271 		// also need to enable NVIC and enable global interrupt
272 		HWREG(NVIC_EN0) |= BIT6HI; // from page 104, this is for UART1 (vector 22, 
273 		bit 6)
274 		__enable_irq();
275 		
276 		// turn power relay off
277 		#ifdef AUTOMATIC_POW_RELAY_ON
278 		SetPowerRelay(true);
279 		#endif
280 		
281 		// turning fan off initially
282 		TurnFanOff();
283 		
284 		//play the unpaird sound
285 		playUnpairedSound();
286 		
287 		// print out initializing completion
288 		printf("Finished initializing Dog TX Service\r\n");
289 
290 		// post the initial transition event
291 		ThisEvent.EventType = ES_INIT;
292 		if (ES_PostToService( MyPriority, ThisEvent) == true)
293 		{
294 				return true;
295 		}else
296 		{
297 				return false;
298 		}
299 }
300 
301 /****************************************************************************
302  Function
303      PostDogTX
304 
305  Parameters
306      EF_Event ThisEvent ,the event to post to the queue
307 
308  Returns
309      bool false if the Enqueue operation failed, true otherwise
310 
311  Description
312      Posts an event to this state machine's queue
313 
314 ****************************************************************************/
315 bool PostDogTX( ES_Event ThisEvent )
316 {
317   return ES_PostToService( MyPriority, ThisEvent);
318 }
319 
320 /****************************************************************************
321  Function
322     RunDogTX
323 
324  Parameters
325    ES_Event : the event to process
326 
327  Returns
328    ES_Event, ES_NO_EVENT if no error ES_ERROR otherwise
329 
330  Description
331    add your description here
332 
333 ****************************************************************************/
334 ES_Event RunDogTX( ES_Event ThisEvent )
335 {
336   ES_Event ReturnEvent;
337   ReturnEvent.EventType = ES_NO_EVENT; // assume no errors
338   DogTXState_t NextState = CurrentState;
339   
340   switch (CurrentState){
341 			// if current state is wait to pair
342 			case WaitToPair:
343 					// if receive pair request message from the FARMER
344 					if(ThisEvent.EventType == PAIR_REQUEST_RECEIVED){
345 							#ifdef DEBUGGING_EVENT
346 							printf("DOG: Received pairing request message through Zigbee\r\n");
347 							#endif
348 							// reset farmer address
349 							ResetFarmerAddress();
350 							// set farmer address
351 							SetFarmerAddress(ThisEvent.EventParam);
352 							// Transmit pair ack packet
353 							Send_PairResponse();
354 					}
355 					// if receive ack for pair response message
356 					else if((ThisEvent.EventType == ACK_RECEIVED) && (ThisEvent.EventParam 
357 					== PAIR_RESPONSE_FRAME_ID)){
358 							// start 1s incoming transmission time
359 							ES_Timer_InitTimer(LOST_COMM_TIMER, LOST_COMM_TIME);
360 							// turn on Treat fan
361 							TurnFanOn();
362 						  playPairedSound();
363 							// set next state to paired wait for key
364 							NextState = PairedWaitForKey;
365 							#ifdef DEBUGGING_STATE
366 							printf("DOG state: PAIRED WAIT FOR KEY\r\n");
367 							#endif
368 					}
369 					// if receive nack for pair response message
370 					else if((ThisEvent.EventType == NACK_RECEIVED)&& (ThisEvent.EventParam 
371 					== PAIR_RESPONSE_FRAME_ID)){
372 							// resend pair response message
373 							Send_PairResponse();
374 					}
375 					
376 					// the following code is for testing fan control and motor control
377 					#ifdef DEMO_MANUAL_MODE 
378 					else if((ThisEvent.EventType == ES_NEW_KEY) && (ThisEvent.EventParam == 
379 					'o')){
380 							// turn on Treat fan
381 							TurnFanOn();
382 							playPairedSound();
383 					}
384 					else if((ThisEvent.EventType == ES_NEW_KEY) && (ThisEvent.EventParam == 
385 					'p')){
386 							// turn off Treat fan
387 							TurnFanOff();
388 							playUnpairedSound();
389 					}
390 					else if((ThisEvent.EventType == ES_NEW_KEY) && (ThisEvent.EventParam == 
391 					's')){
392 							// stop motor
393 							StopMotor_Left();
394 							StopMotor_Right();
395 					}
396 					else if((ThisEvent.EventType == ES_NEW_KEY) && (ThisEvent.EventParam == 
397 					'd')){
398 							// set motor speed minimum
399 							SetMotor_Left(MIN_CTRL_VALUE);
400 							SetMotor_Right(MIN_CTRL_VALUE);
401 					}
402 					else if((ThisEvent.EventType == ES_NEW_KEY) && (ThisEvent.EventParam == 
403 					'f')){
404 							// set motor speed maximum
405 							SetMotor_Left(MID_CTRL_VALUE);
406 							SetMotor_Right(MID_CTRL_VALUE);
407 					}
408 					else if((ThisEvent.EventType == ES_NEW_KEY) && (ThisEvent.EventParam == 
409 					'g')){
410 							// set motor speed maximum
411 							SetMotor_Left(MAX_CTRL_VALUE);
412 							SetMotor_Right(MAX_CTRL_VALUE);
413 					}
414 					else if((ThisEvent.EventType == ES_NEW_KEY) && (ThisEvent.EventParam == 
415 					'q')){
416 							// set motor speed maximum
417 							SetPowerRelay(false);
418 					}
419 					else if((ThisEvent.EventType == ES_NEW_KEY) && (ThisEvent.EventParam == 
420 					'w')){
421 							// set motor speed maximum
422 							SetPowerRelay(true);
423 					}
424 					else if((ThisEvent.EventType == ES_NEW_KEY) && (ThisEvent.EventParam == 
425 					'n')){
426 							// set motor speed maximum
427 							SetLeftFan_Forward();
428 							SetRightFan_Forward();
429 					}
430 					else if((ThisEvent.EventType == ES_NEW_KEY) && (ThisEvent.EventParam == 
431 					'm')){
432 							// set motor speed maximum
433 							SetLeftFan_Backward();
434 							SetRightFan_Backward();
435 					}
436 					else if((ThisEvent.EventType == ES_NEW_KEY) && (ThisEvent.EventParam == 
437 					'l')){
438 							Calculate_Motor_Speed(255, 255);
439 							Calculate_Motor_Speed(255, 0);
440 							Calculate_Motor_Speed(255, 127);
441 							Calculate_Motor_Speed(127, 255);
442 							Calculate_Motor_Speed(0, 255);
443 							Calculate_Motor_Speed(0, 0);
444 							Calculate_Motor_Speed(0, 127);
445 							Calculate_Motor_Speed(127,127);
446 					}
447 					
448 					else if((ThisEvent.EventType == ES_NEW_KEY) && (ThisEvent.EventParam == 
449 					'b')){
450 							SetBrakeOn();
451 					}
452 					
453 					else if((ThisEvent.EventType == ES_NEW_KEY) && (ThisEvent.EventParam == 
454 					'v')){
455 							SetBrakeOff();
456 					}
457 					
458 					else if((ThisEvent.EventType == ES_NEW_KEY) && (ThisEvent.EventParam == 
459 					'1')){
460 							ExecuteCommand(0x00FFFF00);
461 					}
462 					
463 					else if((ThisEvent.EventType == ES_NEW_KEY) && (ThisEvent.EventParam == 
464 					'2')){
465 							ExecuteCommand(0x00FF0000);
466 					}
467 					
468 					else if((ThisEvent.EventType == ES_NEW_KEY) && (ThisEvent.EventParam == 
469 					'3')){
470 							ExecuteCommand(0x00FF7F00);
471 					}
472 					
473 					else if((ThisEvent.EventType == ES_NEW_KEY) && (ThisEvent.EventParam == 
474 					'4')){
475 							ExecuteCommand(0x007FFF00);
476 					}
477 					
478 					else if((ThisEvent.EventType == ES_NEW_KEY) && (ThisEvent.EventParam == 
479 					'5')){
480 							ExecuteCommand(0x0000FF00);
481 					}
482 					
483 					else if((ThisEvent.EventType == ES_NEW_KEY) && (ThisEvent.EventParam == 
484 					'6')){
485 							ExecuteCommand(0x00000000);
486 					}
487 					
488 					else if((ThisEvent.EventType == ES_NEW_KEY) && (ThisEvent.EventParam == 
489 					'7')){
490 							ExecuteCommand(0x00007F00);
491 					}
492 					
493 					else if((ThisEvent.EventType == ES_NEW_KEY) && (ThisEvent.EventParam == 
494 					'8')){
495 							ExecuteCommand(0x007F7F00);
496 					}
497 					
498 					else if((ThisEvent.EventType == ES_NEW_KEY) && (ThisEvent.EventParam == 
499 					'9')){
500 							ReadID();
501 					}
502 					#endif
503 					
504 					break;
505 					
506 			// if current state is paired wait for key
507 			case PairedWaitForKey:\
508 					// if don't hear back from Farmer with in 1 second
509 					if((ThisEvent.EventType == ES_TIMEOUT) && (ThisEvent.EventParam == 
510 					LOST_COMM_TIMER)){
511 							#ifdef DEBUGGING_STATE
512 							printf("DOG: One second timeout, return to WaitToPair\r\n");
513 							playUnpairedSound();
514 							#endif
515 							// turn off Treat Fan
516 							TurnFanOff();
517 							// if timeout, go back to wait to pair state
518 							NextState = WaitToPair;
519 							// Disable Lost Communication timer
520 							ES_Timer_StopTimer(LOST_COMM_TIMER);
521 							#ifdef DEBUGGING_STATE
522 							printf("DOG STATE: WaitForKey --> WaitToPair\r\n");
523 							#endif
524 					}
525 					
526 					// if receive encryption key message
527 					if(ThisEvent.EventType ==  ENCRYPTION_KEY_RECEIVED){
528 							// encryption keys are stored in DOG_RX
529 							// restart lost comm timer
530 							ES_Timer_InitTimer(LOST_COMM_TIMER, LOST_COMM_TIME);
531 							// set RX_state to be in control mode (all received data will first 
532 							be decrypted)
533 							SetInControlMode(true);
534 							// set next state to paired
535 							NextState = Paired;
536 //						  playPairedSound();
537 							// switch song
538 							//SwitchSong();
539 							#ifdef DEBUGGING_STATE
540 							printf("DOG STATE: Paired with %.4x\r\n", ThisEvent.EventParam);
541 							#endif
542 					}
543 					break;
544 			
545 			// if current state is paired
546 			case Paired:
547 					// #ifdef NORMAL_OP_MODE
548 					// if 1s timeout
549 					if((ThisEvent.EventType == ES_TIMEOUT) && (ThisEvent.EventParam == 
550 					LOST_COMM_TIMER)){
551 							// set RX state to not be in control mode, rx packet will not be 
552 							decrypted
553 							SetInControlMode(false);
554 							#ifdef DEBUGGING_EVENT
555 							printf("DOG: One second timeout, return to WaitToPair\r\n");
556 							#endif
557 							// turn off Treat Fan
558 							TurnFanOff();
559 							// if timeout, go back to wait to pair state
560 							NextState = WaitToPair;
561 							// switch song
562 							playUnpairedSound();
563 							// reset encryption index key
564 							ResetEncryptKeyIndex();
565 							// Stop motor
566 							StopMotor_Left();
567 							StopMotor_Right();
568 							// Disable Lost Communication timer
569 							ES_Timer_StopTimer(LOST_COMM_TIMER);
570 							#ifdef DEBUGGING_STATE
571 							printf("DOG STATE: Paired --> WaitToPair\r\n");
572 							#endif
573 					}
574 					
575 					// if this is direction change timer timeout, set change direction 
576 					variable and execute current command
577 					else if((ThisEvent.EventType == ES_TIMEOUT) && (ThisEvent.EventParam == 
578 					DIRECTION_CHANGE_TIMER)){
579 							change_dir_complete = true;
580 							ExecuteCommand(current_cmd);
581 					}
582 					// #endif
583 					
584 					#ifdef MANUAL_OP_MODE
585 					// if x is pressed
586 					if((ThisEvent.EventType == ES_NEW_KEY) && (ThisEvent.EventParam == 'x'))
587 					{
588 							// set RX state to not be in control mode, rx packet will not be 
589 							decrypted
590 							SetInControlMode(false);
591 							#ifdef DEBUGGING_EVENT
592 							printf("DOG: One second timeout, return to WaitToPair\r\n");
593 							#endif
594 							// turn off Treat Fan
595 							TurnFanOff();
596 							// switch song
597 							playUnpairedSound();
598 							// if timeout, go back to wait to pair state
599 							NextState = WaitToPair;
600 							// reset encryption index key
601 							ResetEncryptKeyIndex();
602 							// Disable Lost Communication timer
603 							ES_Timer_StopTimer(LOST_COMM_TIMER);
604 							#ifdef DEBUGGING_STATE
605 							printf("DOG STATE: WaitToPair\r\n");
606 							#endif
607 					}
608 					#endif
609 					
610 					// if received control message
611 					else if((ThisEvent.EventType == CTRL_COMMAND_RECEIVED) && 
612 					change_dir_complete){
613 							// restart lost comm timer
614 							ES_Timer_InitTimer(LOST_COMM_TIMER, LOST_COMM_TIME);
615 							// Set current command
616 							current_cmd = GetControlMessage();
617 							// excecute command
618 							ExecuteCommand(current_cmd);
619 							// transmit status
620 							Send_StatusMessage();
621 					}
622 					// if received invalid control message
623 					else if(ThisEvent.EventType == INVALID_CTRL_COMMAND_RECEIVED){
624 							// make sure rx state is still in control mode
625 							//SetInControlMode(false);
626 							// restart lost comm timer
627 							ES_Timer_InitTimer(LOST_COMM_TIMER, LOST_COMM_TIME);
628 							// transmit reset encryption index request
629 							ResetEncryptKeyIndex();
630 							// send encryption key reset message to farmer
631 							Send_EncryptionReset();
632 							// Stop motor
633 							StopMotor_Left();
634 							StopMotor_Right();
635 					}
636 					
637 					// if receive nack for the control message
638 					else if((ThisEvent.EventType == ACK_RECEIVED) && (ThisEvent.EventParam 
639 					== frame_id)){
640 							// test restart lost comm timer when getting ack
641 							ES_Timer_InitTimer(LOST_COMM_TIMER, LOST_COMM_TIME);
642 							#ifdef DEBUGGING_EVENT
643 							printf("Correctly received control message ack with correct frame id: 
644 							%.2x\r\n", frame_id);
645 							#endif
646 					}
647 					
648 					// if receive nack for the control message
649 					else if((ThisEvent.EventType == NACK_RECEIVED) && (ThisEvent.EventParam 
650 					== frame_id)){
651 							// test restart lost comm timer when getting nack
652 							ES_Timer_InitTimer(LOST_COMM_TIMER, LOST_COMM_TIME);
653 							// send control packet
654 							Send_StatusMessage();
655 							#ifdef DEBUGGING_EVENT
656 							printf("Incorrectly received control message nack with correct frame 
657 							id: %.2x\r\n", frame_id);
658 							#endif
659 					}
660 					break;
661 
662 			default :
663 				break;
664   }
665 	// update current state
666 	CurrentState = NextState;
667   return ReturnEvent;
668 }
669 
670 /***************************************************************************
671  private functions
672  ***************************************************************************/
673 
674 static void StopMotor_Left(){
675 		printf("Stop motor\r\n");
676 		SetCurrentTimeout_Left(STOP_CTRL_VALUE);
677 }
678 
679 static void SetMotor_Left(float input){
680 		printf("Set pulse period to: %f ms\r\n", input);
681 		SetCurrentTimeout_Left(input * left_power_percent);
682 }
683 
684 static void StopMotor_Right(){
685 		printf("Stop motor\r\n");
686 		SetCurrentTimeout_Right(STOP_CTRL_VALUE);
687 }
688 
689 static void SetMotor_Right(float input){
690 		printf("Set pulse period to: %f ms\r\n", input);
691 		SetCurrentTimeout_Right(input * right_power_percent);
692 }
693 
694 static void SetPowerRelay(bool input){
695 		if(input){
696 			printf("Turn on Power Relay\r\n");
697 			GPIOPinWrite(GPIO_PORTF_BASE, GPIO_PIN_4, BIT4HI);
698 		}
699 		else{
700 			printf("Turn off Power Relay\r\n");
701 			GPIOPinWrite(GPIO_PORTF_BASE, GPIO_PIN_4, BIT4LO);
702 		}
703 }
704 
705 static void SetLeftFan_Backward(){
706 		printf("Switch Left Fan Relay: Backward\r\n");
707 		GPIOPinWrite(GPIO_PORTF_BASE, GPIO_PIN_1, BIT1LO);
708 }
709 
710 static void SetLeftFan_Forward(){
711 		printf("Switch Left Fan Relay: Forward\r\n");
712 		GPIOPinWrite(GPIO_PORTF_BASE, GPIO_PIN_1, BIT1HI);
713 }
714 
715 static void SetRightFan_Backward(){
716 		printf("Switch Right Fan Relay: Backward\r\n");
717 		GPIOPinWrite(GPIO_PORTF_BASE, GPIO_PIN_2, BIT2LO);
718 }
719 
720 static void SetRightFan_Forward(){
721 		printf("Switch Right Fan Relay: Forward\r\n");
722 		GPIOPinWrite(GPIO_PORTF_BASE, GPIO_PIN_2, BIT2HI);
723 }
724 
725 static void SetBrakeOn(){
726 		printf("Brake On\r\n");
727 		moveToAngle(BRAKE_ANGLE, BRAKE_SERVO_CHANNEL);
728 }
729 
730 static void SetBrakeOff(){
731 		printf("Brake Off\r\n");
732 		moveToAngle(UNBRAKE_ANGLE, BRAKE_SERVO_CHANNEL);
733 }
734 
735 static void SetSpecialFnOn(){
736 		printf("If you read this, you are special.\r\n");
737 }
738 
739 static void SetSpecialFnOff(){
740 		printf("If you read this, you are also special.\r\n");
741 }
742 
743 static void SwitchSong(){
744 	GPIOPinWrite(GPIO_PORTB_BASE, GPIO_PIN_2, BIT2HI);
745 	printf("This is a delay message to make some time for dog\r\n");
746 	GPIOPinWrite(GPIO_PORTB_BASE, GPIO_PIN_2, BIT2LO);
747 }
748 
749 static void playUnpairedSound(){
750 	GPIOPinWrite(GPIO_PORTB_BASE, GPIO_PIN_2, BIT2LO);
751 }
752 
753 static void playPairedSound(){
754 	GPIOPinWrite(GPIO_PORTB_BASE, GPIO_PIN_2, BIT2HI);
755 }
756 
757 /*
758  *	This function write 0x01 to UART5 to turn fan on
759  */
760 static void TurnFanOn(){
761 			printf("Turn fan on\r\n");
762 			if((HWREG(UART5_BASE + UART_O_FR) & UART_FR_TXFE) == UART_FR_TXFE){
763 				// write 0x01 to PE5 UART to turn on fan
764 				FanState = 0x01;
765 			}
766 			// write data to UART
767 			HWREG(UART5_BASE + UART_O_DR) = (HWREG(UART5_BASE + UART_O_DR) & 
768 			~UART_DR_DATA_M) + FanState;
769 }
770 
771 /*
772  *	This function write 0x00 to UART5 to turn fan on
773  */
774 static void TurnFanOff(){
775 			printf("Turn fan off\r\n");
776 			if((HWREG(UART5_BASE + UART_O_FR) & UART_FR_TXFE) == UART_FR_TXFE){
777 				// write 0x00 to PE5 UART to turn off fan
778 				FanState = 0x00;
779 			}
780 			// write data to UART
781 			HWREG(UART5_BASE + UART_O_DR) = (HWREG(UART5_BASE + UART_O_DR) & 
782 			~UART_DR_DATA_M) + FanState;
783 }
784 
785 /*
786  *	This function clears farmer address
787  */
788 static void ResetFarmerAddress(){
789 		paired_farmer_address = 0x0000;
790 }
791 
792 /*
793  *	This function sets farmer address
794  */
795 static void SetFarmerAddress(uint16_t input){
796 		paired_farmer_address = input;
797 }
798 
799 /*
800  *	This function execute the control command sent by farmer
801  */
802 static void ExecuteCommand(uint32_t cmd){
803 		#ifdef DEBUGGING_EVENT
804 		printf("Executing control command\r\n");
805 		#endif
806 		printf("Execute command: %.8x\r\n", cmd);
807 		uint8_t cmd1 = (cmd & 0x00ff0000) >> 16; // forward and backward cmd
808 		uint8_t cmd2 = (cmd & 0x0000ff00) >> 8;  // left and right cmd
809 		uint8_t cmd3 = (cmd & 0x000000ff);		 // digital cmd
810 		printf("Control 1 is: %.2x\r\n", cmd1);
811 	
812 		// first calculate the left and right power value for the motors
813 		Calculate_Motor_Speed(cmd1, cmd2);
814 		// set left fan direction and magnitude
815 		if(left_pow < 0){
816 			cur_direction_left = BACKWARD_DIR;
817 		}
818 		else{
819 			cur_direction_left = FORWARD_DIR;
820 		}
821 		
822 		// set right fan direction and magnitude
823 		if(right_pow < 0){
824 			cur_direction_right = BACKWARD_DIR;
825 		}
826 		else{
827 			cur_direction_right = FORWARD_DIR;
828 		}
829 
830 		// check if new direction is different than the previous direction
831 		if((cur_direction_left != prev_direction_left) || (cur_direction_right != 
832 		prev_direction_right)){
833 			StopMotor_Left();
834 			StopMotor_Right();
835 			ES_Timer_InitTimer(DIRECTION_CHANGE_TIMER, DIRECTION_CHANGE_TIME);
836 			change_dir_complete = false;
837 		}
838 		else{
839 			// set left fan direction and magnitude
840 			if(left_pow < 0){
841 				SetLeftFan_Backward();
842 				SetMotor_Left(MapToPeriod(left_pow*-1));
843 			}
844 			else{
845 				SetLeftFan_Forward();
846 				SetMotor_Left(MapToPeriod(left_pow));
847 			}
848 			
849 			// set right fan direction and magnitude
850 			if(right_pow < 0){
851 				SetRightFan_Backward();
852 				SetMotor_Right(MapToPeriod(right_pow*-1));
853 			}
854 			else{
855 				SetRightFan_Forward();
856 				SetMotor_Right(MapToPeriod(right_pow));
857 			}
858 		}
859 		
860 		// update previous direction
861 		prev_direction_left = cur_direction_left;
862 		prev_direction_right = cur_direction_right;
863 		
864 		// Execute brake
865 		if((cmd3 & BRAKE_MASK) == BRAKE_MASK){
866 			SetBrakeOn();
867 		}
868 		else{
869 			SetBrakeOff();
870 		}
871 
872 		// Execute Special function
873 		if((cmd3 & SPECIAL_FUNC_MASK) == SPECIAL_FUNC_MASK){
874 			SetSpecialFnOn();
875 		}
876 		else{
877 			SetSpecialFnOff();
878 		}
879 }
880 
881 static void Calculate_Motor_Speed(uint8_t cmd1, uint8_t cmd2){
882 		printf("CMD1 is: %d\r\n", cmd1);
883 		printf("CMD2 is: %d\r\n", cmd2);
884 	
885 		// is the control value is between the stop window, set it to 127
886 		if((cmd1 <= Ctrl_Offset + Ctrl_Stop_Tol) && (cmd1 >= Ctrl_Offset - 
887 		Ctrl_Stop_Tol)){
888 			cmd1 = Ctrl_Offset;
889 		}
890 		
891 		#ifdef CALCULATE_1
892 		// magnitude of the power
893 		float alpha = ((cmd1 - 127)*100)/127;
894 		// beta in this place is the differnce between left and right 
895 		float beta = ((cmd2 -127)*100)/127;
896 		printf("Alpha is: %f\r\n", alpha);
897 		printf("Beta is: %f\r\n", beta);
898 		left_pow = ((alpha-beta)/2);
899 		right_pow = ((alpha+beta)/2);
900 		printf("Left power is: %f\r\n", left_pow);
901 		printf("Right power is: %f\r\n", right_pow);
902 		#endif
903 		
904 		#ifdef CALCULATE_2
905 		if(cmd1 == 127 && cmd2 == 127){
906 			left_pow = 0;
907 			right_pow = 0;
908 		}
909 		else{
910 			// magnitude of the power
911 			float alpha = ((float)cmd1 - 127)/127;
912 			// beta in this place is the differnce between left and right 
913 			float beta = ((float)cmd2 -127)/127;
914 			float abs_alpha = alpha;
915 			float abs_beta = beta;
916 			
917 			// calculate the absolute value of alpha and beta
918 			if(alpha < 0){
919 				abs_alpha *= -1;
920 			}
921 			if(beta < 0){
922 				abs_beta *= -1;
923 			}
924 			
925 			left_pow = 100 * (alpha*abs_alpha + beta*abs_beta)/(abs_alpha+abs_beta);
926 			right_pow = 100 * (alpha*abs_alpha - beta*abs_beta)/(abs_alpha+abs_beta);
927 		}
928 		printf("Left power is: %f\r\n", left_pow);
929 		printf("Right power is: %f\r\n", right_pow);
930 		#endif
931 		printf("*************************\r\n");
932 }
933 
934 static float MapToPeriod(float input){
935 		// mapping input to output (0.8 is the base value with maximum value of 1.
936 		5)
937 		return (input*MAX_CTRL_OFFSET)/100 +  STOP_CTRL_VALUE;
938 }
939 
940 /*
941  *	This function construct a pair response message
942  */
943 static void Send_PairResponse(){
944 		#ifdef DEBUGGING_EVENT
945 		printf("DOG: Send pairing response message\r\n");
946 		#endif
947 		// first clear the data packet
948 		ClearDataPacket();
949 		// request to pair packet has length of 2 bytes
950 		DataPacket_Length = PAIR_RESPONSE_DATA_LEN;
951 		// first byte is the header
952 		DataPacket[0] = PAIR_ACK;
953 		// set Destination address
954 		MSB_RX_ADDRESS = (paired_farmer_address >> 8);
955 		LSB_RX_ADDRESS = (paired_farmer_address & 0x00ff);
956 		// set frame id
957 		frame_id = PAIR_RESPONSE_FRAME_ID;
958 		// construct packet
959 		ConstructPacket();
960 		// call transmit function to transmit data
961 		TransmitPacket();
962 }
963 
964 /*
965  *	This function construct a status xbee message
966  */
967 static void Send_StatusMessage(){
968 		#ifdef DEBUGGING_EVENT
969 		printf("DOG: Send status report message\r\n");
970 		#endif
971 		// first clear the data packet
972 		ClearDataPacket();
973 		// request to pair packet has length of 2 bytes
974 		DataPacket_Length = STATUS_MESSAGE_LEN;
975 		// first byte is the header
976 		ConStructStatusMessage();
977 		// set Destination address
978 		MSB_RX_ADDRESS = (paired_farmer_address >> 8);
979 		LSB_RX_ADDRESS = (paired_farmer_address & 0x00ff);
980 		// increment frame id by 1 every time we send status
981 		frame_id ++;
982 		// construct packet
983 		ConstructPacket();
984 		// call transmit function to transmit data
985 		TransmitPacket();
986 }
987 
988 /*
989  *	This function construct an encryption reset packet
990  */
991 static void Send_EncryptionReset(){
992 		#ifdef DEBUGGING_EVENT
993 		printf("DOG: Send reset encryption message\r\n");
994 		#endif
995 		// first clear the data packet
996 		ClearDataPacket();
997 		// request to pair packet has length of 2 bytes
998 		DataPacket_Length = ENCR_RESET_LEN;
999 		// first byte is the header
1000 		DataPacket[0] = ENCR_RESET;
1001 		// set frame id
1002 		frame_id = ENCR_RESET_FRAME_ID;
1003 		// set Destination address
1004 		MSB_RX_ADDRESS = (paired_farmer_address >> 8);
1005 		LSB_RX_ADDRESS = (paired_farmer_address & 0x00ff);
1006 		// construct packet
1007 		ConstructPacket();
1008 		// call transmit function to transmit data
1009 		TransmitPacket();
1010 }
1011 
1012 /*
1013  *	This function construct a status data packet
1014  */
1015 static void ConStructStatusMessage(){
1016 		// read the value from the IMU Service module
1017 		ACCEL_X_VALUE = GetIMUData(ACCEL_X_INDEX);
1018 		ACCEL_Y_VALUE = GetIMUData(ACCEL_Y_INDEX);
1019 		ACCEL_Z_VALUE = GetIMUData(ACCEL_Z_INDEX);
1020 		GYRO_X_VALUE = GetIMUData(GYRO_X_INDEX);
1021 		GYRO_Y_VALUE = GetIMUData(GYRO_Y_INDEX);
1022 		GYRO_Z_VALUE = GetIMUData(GYRO_Z_INDEX);
1023 	
1024 		#ifdef DEBUGGING_IMU_DATA
1025 		printf("accel x value: %.4x\r\n", ACCEL_X_VALUE);
1026 		printf("accel y value: %.4x\r\n", ACCEL_Y_VALUE);
1027 		printf("accel z value: %.4x\r\n", ACCEL_Z_VALUE);
1028 		printf("gyro x value: %.4x\r\n", GYRO_X_VALUE);
1029 		printf("gyro y value: %.4x\r\n", GYRO_Y_VALUE);
1030 		printf("gyro z value: %.4x\r\n", GYRO_Z_VALUE);
1031 		#endif
1032 		
1033 		// construct the packet
1034 		DataPacket[0] = STATUS;
1035 		DataPacket[1] = (ACCEL_X_VALUE & MSB_MASK) >> 8;
1036 		DataPacket[2] = (ACCEL_X_VALUE & LSB_MASK);
1037 		DataPacket[3] = (ACCEL_Y_VALUE & MSB_MASK) >> 8;
1038 		DataPacket[4] = (ACCEL_Y_VALUE & LSB_MASK);
1039 		DataPacket[5] = (ACCEL_Z_VALUE & MSB_MASK) >> 8;
1040 		DataPacket[6] = (ACCEL_Z_VALUE & LSB_MASK);
1041 		DataPacket[7] = (GYRO_X_VALUE & MSB_MASK) >> 8;
1042 		DataPacket[8] = (GYRO_X_VALUE & LSB_MASK);
1043 		DataPacket[9] = (GYRO_Y_VALUE & MSB_MASK) >> 8;
1044 		DataPacket[10] = (GYRO_Y_VALUE & LSB_MASK);
1045 		DataPacket[11] = (GYRO_Z_VALUE & MSB_MASK) >> 8;
1046 		DataPacket[12] = (GYRO_Z_VALUE & LSB_MASK);
1047 }
1048 
1049 /*
1050  *	This function construct a packet to be transmitted with option of
1051  *	broadcasting to all listenning devices
1052  */
1053 static void ConstructPacket(){
1054 		XbeePacket[0] = START_BYTE;
1055 		XbeePacket[1] = MSB_LEN;
1056 		XbeePacket[2] = DataPacket_Length + DATA_OVERHEAD_LEN;
1057 		XbeePacket[3] = API_TX_ID;
1058 		CheckSum = API_TX_ID; // start increment checksum
1059 		XbeePacket[4] = frame_id;
1060 		CheckSum += frame_id;
1061 		XbeePacket[5] = MSB_RX_ADDRESS;
1062 		CheckSum += MSB_RX_ADDRESS;
1063 		XbeePacket[6] = LSB_RX_ADDRESS;
1064 		CheckSum += LSB_RX_ADDRESS;
1065 		XbeePacket[7] = OPTION_BYTE;
1066 		CheckSum += OPTION_BYTE;
1067 		// now move data packet to the xbee packet
1068 		for(int i = 0; i < DataPacket_Length; i++){
1069 			XbeePacket[i+8] = DataPacket[i];
1070 			CheckSum += DataPacket[i];
1071 		}
1072 		// calculate checksum value
1073 		XbeePacket[DataPacket_Length + 8] = CHECKSUM_OFFSET - CheckSum;
1074 		//frame_id += 1; // increment fram id number
1075 		XbeePacket_Length = DataPacket_Length + XBEE_OVERHEAD_LEN;
1076 }
1077 
1078 /*
1079  *	This function clear the content of data packet array
1080  */
1081 static void ClearDataPacket(){
1082 		for(int i = 0; i < LARGEST_FRAME_DATA; i++){
1083 			// set all index of data packet to 0
1084 			DataPacket[i] = i;
1085 		}
1086 }
1087 
1088 /*
1089  *	This function transmit packet by start writing to UART pin out
1090  *  We need to call ConstructPacket before calling this function
1091  */
1092 static bool TransmitPacket(){
1093 		// set remaining number of byte to transmit to the xbee packet length
1094 		byte_remaining = XbeePacket_Length;
1095 		// reset index to 0
1096 		index = 0;
1097 		
1098 		// check if UART Transmit FIFO empty bit is set, this mean we can send
1099 		if((HWREG(UART1_BASE + UART_O_FR) & UART_FR_TXFE) == UART_FR_TXFE){
1100 			// write data to UART
1101 			WriteToUART();
1102 			
1103 			// this if loop is for increasing effciency of trasmitting
1104 			if ((HWREG(UART1_BASE + UART_O_FR) & UART_FR_TXFE) == UART_FR_TXFE){
1105 				// write data to UART
1106 				WriteToUART();
1107 			}
1108 			//enable TX interrupt
1109 			HWREG(UART1_BASE + UART_O_IM) |= UART_IM_TXIM;
1110 			//return success
1111 			return true;
1112 		}
1113 		else{
1114 			// else return failure
1115 			return false;
1116 		}
1117 }
1118 
1119 /*
1120  *	This function copy data from xbeepacket array to the UART pin out
1121  */
1122 static void WriteToUART(){
1123 		// write XbeePacket[tx_index] to UARTDR
1124 		HWREG(UART1_BASE + UART_O_DR) = (HWREG(UART1_BASE + UART_O_DR) & 
1125 		~UART_DR_DATA_M) + XbeePacket[index];
1126 		// decrement byte remaining
1127 		byte_remaining--;
1128 		// increment index
1129 		index++;
1130 }
1131 
1132 static void Init_Port(){
1133 		//Initialize Port F
1134 		SysCtlPeripheralEnable(SYSCTL_PERIPH_GPIOF);
1135 	
1136 		//Initialize PF0 for left fan ESC Control
1137 	  HWREG(GPIO_PORTF_BASE + GPIO_O_PUR) = HWREG(GPIO_PORTF_BASE + GPIO_O_PUR) 
1138 	  | (1<<0);
1139     HWREG(GPIO_PORTF_BASE + GPIO_O_LOCK) = GPIO_LOCK_KEY;
1140     HWREG(GPIO_PORTF_BASE + GPIO_O_CR) = (1<<0);
1141 		GPIOPinTypeGPIOOutput(GPIO_PORTF_BASE, GPIO_PIN_0);
1142 	
1143 		//Initialize PF1 for left fan direction relay
1144 		HWREG(GPIO_PORTF_BASE + GPIO_O_PUR) = HWREG(GPIO_PORTF_BASE + GPIO_O_PUR) 
1145 		| (1<<1);
1146     HWREG(GPIO_PORTF_BASE + GPIO_O_LOCK) = GPIO_LOCK_KEY;
1147     HWREG(GPIO_PORTF_BASE + GPIO_O_CR) = (1<<0);
1148 		GPIOPinTypeGPIOOutput(GPIO_PORTF_BASE, GPIO_PIN_1);
1149 		
1150 		//Initialize PF2 for right fan ESC Control
1151 		GPIOPinTypeGPIOOutput(GPIO_PORTF_BASE, GPIO_PIN_2);
1152 	
1153 		//Initialize PF3 for right fan direction relay
1154 		GPIOPinTypeGPIOOutput(GPIO_PORTF_BASE, GPIO_PIN_3);
1155 	
1156 		//Initialize PF4 for Power Relay
1157 		GPIOPinTypeGPIOOutput(GPIO_PORTF_BASE, GPIO_PIN_4);
1158 }
1159 
1160 
1161 /*
1162  *	This function is the ISR for the UART1 module
1163  */
1164 void DOG_UART1_ISR(){
1165 		// check if UART1 interrupt flag for receiver is set
1166 		//if ((HWREG(UART1_BASE + UART_O_RIS) & UART_RIS_RXRIS) > 0){
1167 		if (HWREG(UART1_BASE+UART_O_MIS)& UART_MIS_RXMIS){
1168 			// clear RX interrupt flag
1169 			HWREG(UART1_BASE + UART_O_ICR) = UART_ICR_RXIC;
1170 			uint8_t Received_byte = HWREG(UART1_BASE + UART_O_DR);
1171 			
1172 			// RX State Machine in ISR
1173 			DogRXState_t NextRXState = CurrentRXState;
1174 			switch (CurrentRXState){
1175 				case WaitFor7E:
1176 						// if receive incoming start byte
1177 						if(Received_byte == START_BYTE){
1178 								//#ifdef DEBUGGING_EVENT
1179 								//printf("Received start bytes: %.2x\r\n", Received_byte);
1180 								//#endif
1181 								// first clear current data packet
1182 								ClearRXDataPacket();
1183 								// reset Checksums, received index to 0
1184 								RX_CheckSum = 0;
1185 								Received_RX_CheckSum = 0;
1186 								rx_index = 0;
1187 								// set next state to wait for msb
1188 								NextRXState = WaitForMSBLen;
1189 						}
1190 						// if receive byte other than 0x7E
1191 						else{
1192 								//#ifdef DEBUGGING_EVENT
1193 								//printf("Received invalid start bytes: %.2x\r\n", Received_byte);
1194 								//#endif
1195 						}
1196 						break;
1197 						
1198 				// if current state is wait for MSB
1199 				case WaitForMSBLen:
1200 							// save msb length of the received packet
1201 							RX_Message_MSB_Len = Received_byte;
1202 							// set next state to wait for lsb
1203 							NextRXState = WaitForLSBLen;
1204 						break;
1205 					
1206 				// if current state is wait for LSB
1207 				case WaitForLSBLen:
1208 							// save lsb length of the received packet
1209 							RX_Message_LSB_Len = Received_byte;
1210 							// form data packet length from the received msb and lsb
1211 							RX_DataPacket_Length = (RX_Message_MSB_Len << 8) + RX_Message_LSB_Len;
1212 							// set next state to get data packet
1213 							NextRXState = GetDataPacket;
1214 						break;
1215 						
1216 				// if current state is wait for get data packet
1217 				case GetDataPacket:
1218 							// put received data into DataPacket array
1219 							RX_DataPacket[rx_index] = Received_byte;
1220 							// add the data up to check sum
1221 							RX_CheckSum += Received_byte;
1222 							// increment the received index
1223 							rx_index++;
1224 							// compare index to the received index, if equal go to check sum 
1225 							state
1226 							if(rx_index == RX_DataPacket_Length){
1227 								// compute final check sum by subtracting from 0xFF
1228 								RX_CheckSum = CHECKSUM_OFFSET - RX_CheckSum;
1229 								// set next state to get check sum
1230 								NextRXState = GetCheckSum;
1231 							}
1232 						break;
1233 
1234 				// if current state is get check sum
1235 				case GetCheckSum:
1236 						// set check sum to the byte received
1237 						Received_RX_CheckSum = Received_byte;
1238 						// check if it equal to our calculated check sum
1239 						if(Received_RX_CheckSum == RX_CheckSum){
1240 							CopyToBuffer();
1241 							// post received byte to FARMER_RX service
1242 							ES_Event ThisEvent;
1243 							ThisEvent.EventType = VALID_PACKET_RECEIVED;
1244 							ThisEvent.EventParam = RX_DataPacket_Length;
1245 							PostDogRX(ThisEvent);
1246 							
1247 							//#ifdef DEBUGGING_EVENT
1248 							//printf("Received Good Checksum. Post VALID_PACKET_RECEIVED event 
1249 							with length %d\r\n", RX_DataPacket_Length);
1250 							//#endif
1251 						}else{
1252 							//#ifdef DEBUGGING_EVENT
1253 							//printf("Received Bad Checksum. Did not post VALID_PACKET_RECEIVED 
1254 							event\r\n");
1255 							//#endif
1256 						}
1257 						// set next state to wait for start delimiter bytes
1258 						NextRXState = WaitFor7E;
1259 						break;
1260 				
1261 				default:
1262 						break;
1263 			}
1264 			CurrentRXState = NextRXState;
1265 			
1266 		}
1267 	
1268 		// check if UART1 interrupt flag for transmitter is set
1269 		else if(HWREG(UART1_BASE+UART_O_MIS)& UART_MIS_TXMIS){
1270 			
1271 			// write data to UART but first wait till FIFO empty
1272 			if((HWREG(UART1_BASE + UART_O_FR) & UART_FR_TXFE) == UART_FR_TXFE){
1273 					// clear TX interrupt flag	
1274 					HWREG(UART1_BASE + UART_O_ICR) = UART_ICR_TXIC;
1275 					// write data to UART
1276 					WriteToUART();
1277 			}
1278 			// check number of byte remaining
1279 			if(byte_remaining == 0){
1280 				// if byte remaining is zero, disable interrupt on TX
1281 				HWREG(UART1_BASE + UART_O_IM) &= ~UART_IM_TXIM;
1282 				#ifdef DEBUGGING_EVENT
1283 				printf("A Packet has been sent\r\n");
1284 				#endif
1285 			}
1286 		}
1287 }
1288 
1289 /*
1290  *	This function clears data packet ocntent
1291  */
1292 static void ClearRXDataPacket(){
1293 	for(int i = 0; i < LARGEST_FRAME_DATA; i++){
1294 		// set all index of data packet to 0
1295 		RX_DataPacket[i] = 0;
1296 	}
1297 }
1298 
1299 static void ClearRXBuffer(){
1300 	for(int i = 0; i < LARGEST_FRAME_DATA; i++){
1301 		// set all index of data packet to 0
1302 		RX_Buffer_Array[i] = 0;
1303 	}
1304 }
1305 
1306 static void CopyToBuffer(){
1307 	// ClearRXBuffer();
1308 	for(int i = 0; i < LARGEST_FRAME_DATA; i++){
1309 		// set all index of data packet to 0
1310 		RX_Buffer_Array[i] = RX_DataPacket[i];
1311 	}
1312 }
1313 
1314 uint8_t GetRXBuffer(int index){
1315 	return RX_Buffer_Array[index];
1316 }
1317 /*------------------------------- Footnotes -------------------------------
1318 */
1319 /*------------------------------ End of file ------------------------------
1320 */
1321