/**

 */

#ifndef _MAIN_H_
#define _MAIN_H_

#include "usb_protocol_cdc.h"
#include "globales.h"
#include "pio.h"
#include "ioport.h"
#include "sam4e.h"
#include <string.h>
#define IFLASH_ADDR       0x00400000
#define IFLASH_SIZE       0x00400000
#define IFLASH_PAGE_SIZE  512
#define USER_PAGE_ADDRESS 0x004FF800//(IFLASH_ADDR + IFLASH_SIZE - IFLASH_PAGE_SIZE * 4)

/* Flash page buffer for alignment */
static uint32_t ul_page_buffer[IFLASH_PAGE_SIZE / sizeof(uint32_t)];
PARAMETROS params;	
uint16_t adc_value;
volatile bool encoder_direction;
volatile uint8_t encoder_pulse_counter;
volatile bool encoder_pulse;
/*! \brief Opens the communication port
 * This is called by CDC interface when USB Host enable it.
 *
 * \retval true if cdc startup is successfully done
 */
bool my_callback_cdc_enable(void);

/*! \brief Closes the communication port
 * This is called by CDC interface when USB Host disable it.
 */
void my_callback_cdc_disable(void);


void usb_data_received(uint8_t port);

void SetupPeripherals(void);
void EncoderPulse(void);
void pioHandler(uint32_t id, uint32_t index);
/**
 * \brief Set input mode for one single IOPORT pin.
 * It will configure port mode and disable pin mode (but enable peripheral).
 * \param pin IOPORT pin to configure
 * \param mode Mode masks to configure for the specified pin (\ref ioport_modes)
 * \param sense Sense for interrupt detection (\ref ioport_sense)
 */
#define ioport_set_pin_input_mode(pin, mode, sense) \
	do {\
		ioport_set_pin_dir(pin, IOPORT_DIR_INPUT);\
		ioport_set_pin_mode(pin, mode);\
		ioport_set_pin_sense_mode(pin, sense);\
	} while (0)

/**
 * \brief Set peripheral mode for one single IOPORT pin.
 * It will configure port mode and disable pin mode (but enable peripheral).
 * \param pin IOPORT pin to configure
 * \param mode Mode masks to configure for the specified pin (\ref ioport_modes)
 */
#define ioport_set_pin_peripheral_mode(pin, mode) \
	do {\
		ioport_set_pin_mode(pin, mode);\
		ioport_disable_pin(pin);\
	} while (0)	
	
	
void save_params_to_flash(void);	
void read_params_from_flash(void);
extern void Pwm_init(void);	
extern void tc0_0_init(void);
//extern void tc0_1_init(void);
//extern void tc1_0_init(void);
//extern void tc1_1_init(void);
extern void twi0_init(void);
extern void SysTick_init(void);
extern void Wdt_init (uint32_t us);
extern void Adc_init(void);    //Initialize MCU Peripherals
extern int16_t read_adc_channel(uint8_t ch);
extern int16_t Adc1_read_adc_channel0(void);
#endif // _MAIN_H_
