/* PlayStation Controller Interface Implementation for the ATmega8 with radio
 * communication support for the ATmega8, one of Atmel's AVR
 * microcontrollers. It should be easily portable, especially to other
 * ATmegas, like the '128. 
 *
 * Sends the data that has been read from the PS joystick to the "base" unit.
 *
 * $Id: terminal.c 193 2005-10-01 00:39:43Z anders $
 * 
 * Copyright (C) 2005 by Anders Dubgaard <anders@dubgaard.net>
 *                   and Tórur Andreassen <ta@imada.sdu.dk>
 *
 * Credits and references:
 *
 * Andrew J. McCubbin (andrewm@quicknet.com.au),
 *   http://www.gamesx.com/controldata/psxcont/psxcont.htm
 *   - which is a mirror of the original site,
 *   http://home.quicknet.com.au/andrewm/electron/psxcont.html
 *
 * Michael Barr for the CRC implementation,
 *   http://www.embedded.com/2000/0001/0001connect.htm
 *
 * This program is free software; you can redistribute it and/or modify
 * it under the terms of the GNU General Public License as published by
 * the Free Software Foundation; either version 2 of the License, or
 * (at your option) any later version.
 *
 * This program is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 * GNU General Public License for more details.
 *
 * You should have received a copy of the GNU General Public License
 * along with this program; if not, write to the Free Software
 * Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA  02110-1301  USA
 */

#include <avr/interrupt.h>
#include <radio/protocol.h>
#include <radio/radio.h>
#include "common.h"
#include "timer.h"
#include "psx.h"

#ifdef _DEBUG
  #include "uart.h"
#endif

int main(void){
  /* psx is a pointer to the joystick data struct */
  volatile psx_data *psx = &joydata;
	/*uint8_t *psx_arr = (uint8_t *) psx;
   * Access the psx data via:
   *   joydata.Member
   *   psx->Member
   *   psx_arr[n] */

	psx_init();        /* Setup the connection to the PS Joystick*/
	radio_init();      /* Setup the radio connection */
  start_pwm_timer(); /* Setup the PWM timer */
	package_init();    /* Initialise the package structure for
                        the radio transmission */

#ifdef _DEBUG
	UART_init();       /* Enable printing to std. out via. the UART */
  uint8_t n = 0;
#endif

	sei();
	while(1){

#ifdef _DEBUG
    printf("%3d: ", n++);
#endif

		psx = get_psx_data();             /* Get data from the joystick */
		update_package(psx);              /* Update the package, new data and CRC16 */
		send_package();                   /* Pass the data to the airwaves */

		OCR2 = psx_pwm_calc(psx->l_vert); /* Calculate a PWM example */

#ifdef _DEBUG
		printf("PWM: %2x ", OCR2);
    print_package(package);
#endif

	}
	return 0;
}

