/* Base unit for my wireless PlayStation Contrller Interface. Target platform
 * is the ATmega128, one of Atmel's AVR microcontrollers.
 * 
 * Receives a radio package with joystick data from the terminal.
 * See radio/protocol.[hc].
 * 
 * $Id: base.c 193 2005-10-01 00:39:43Z anders $
 *
 * Copyright (C) 2005 Anders Dubgaard <anders@dubgaard.net>
 *
 * 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"

#include "uart.h"

void send_psxdata_in_ascii(volatile psx_data *psxp);

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

#ifdef _DEBUG
  uint8_t n = 0;
#endif

	UART_init();
  radio_init();      /* Setup the radio link for receiving */
  start_pwm_timer(); /* Setup the PWM timer */
  package_init();    /* Initialise the package structure for
                        the radio transmission */
	sei();
	while(1){
#ifdef _DEBUG
    printf("%3d: ", n++);
#endif

    do {
      receive_package();               /* Stored in package[] (global var) */  
    } while(! check_package_crc(psx)); /* calculate new crc and compare */

		OCR2 = psx_pwm_calc(psx->l_vert);  /* Calculate a PWM example */
      
#ifdef _DEBUG
		printf("PWM: %2x ", OCR2);
    print_package(package);
#else
    send_psxdata_in_ascii(psx);
#endif

  }
  return 0;
}

/* This function sends (prints) the joystick via the USART to a PC
 * that reads the data with the perl script 'psxmms.pl'.
 * On Unix-like system, stty(8) can be used to set the right baud rate for
 * the serial port device.
 */
void send_psxdata_in_ascii(volatile psx_data *psxp){
	int n;
	uint8_t *psx_arr = (uint8_t *) psxp;

  /* Send data over the UART.
	 */
	for(n = 0; n < PSX_DATA_LEN; n++) {
		printbyte_n(psx_arr[n]);
	}
  putchar('\n');
}
