/*********************************************************************
* Function: void SYSTEM_Initialize( SYSTEM_STATE state )
*
* Overview: Initializes the system.
*
* PreCondition: None
*
* Input:  SYSTEM_STATE - the state to initialize the system into
*
* Output: None
*
********************************************************************/
void SYSTEM_Initialize( SYSTEM_STATE state )
{
    switch(state)
    {
        case SYSTEM_STATE_USB_START:
		
            //Configure oscillator settings for clock settings compatible with USB
            //operation.  Note: Proper settings depends on USB speed (full or low).
            #if(USB_SPEED_OPTION == USB_FULL_SPEED)
                OSCTUNE = 0x80; //3X PLL ratio mode selected
                OSCCON = 0x70;  //Switch to 16MHz HFINTOSC
                OSCCON2 = 0x10; //Enable PLL, SOSC, PRI OSC drivers turned off
                while(OSCCON2bits.PLLRDY != 1);   //Wait for PLL lock
                ACTCON = 0x90;  //Enable active clock tuning for USB operation
            #endif
			
            LED_Enable(LED_USB_DEVICE_STATE);
            LED_Enable(LED_USB_DEVICE_HID_CUSTOM);
            LED_Enable(LED_D2);
            BUTTON_Enable(BUTTON_USB_DEVICE_HID_CUSTOM);
            
            ADC_SetConfiguration(ADC_CONFIGURATION_DEFAULT);
            ADC_Enable(ADC_CHANNEL_POTENTIOMETER);
            ADC_Enable(ADC_CHANNEL_1);
            break;
            
        case SYSTEM_STATE_USB_SUSPEND:
            break;
            
        case SYSTEM_STATE_USB_RESUME:
            break;
    }
}
Example #2
0
/*********************************************************************
* Function: void SYSTEM_Initialize( SYSTEM_STATE state )
*
* Overview: Initializes the system.
*
* PreCondition: None
*
* Input:  SYSTEM_STATE - the state to initialize the system into
*
* Output: None
*
********************************************************************/
void SYSTEM_Initialize( SYSTEM_STATE state )
{
    switch(state)
    {
        case SYSTEM_STATE_USB_START:
            LED_Enable(LED_USB_DEVICE_STATE);
            LED_Enable(LED_D2);
            LED_Enable(LED_D3);
            LED_Enable(LED_D4);
            BUTTON_Enable(BUTTON_S1);
            BUTTON_Enable(BUTTON_S2);
            BUTTON_Enable(BUTTON_S3);
            ADC_Enable(ADC_CHANNEL_1);
            ADC_Enable(ADC_CHANNEL_2);
            ADC_Enable(ADC_CHANNEL_3);
            ADC_SetConfiguration(ADC_CONFIGURATION_DEFAULT);
            break;
			
        case SYSTEM_STATE_USB_SUSPEND: 
            break;
            
        case SYSTEM_STATE_USB_RESUME:
            break;
    }
}
Example #3
0
/**
  * @brief  Configure ADC Configuration.
  * @param  None
  * @retval None
  */
void ADC_OVERConfiguration(void)
{
    /* Configure ADC ----------------------------------------------------------*/
    ADC_InitPara ADC_InitStructure;

    ADC_InitStructure.ADC_Mode_Scan = DISABLE ;
    ADC_InitStructure.ADC_Mode_Continuous = DISABLE;
    ADC_InitStructure.ADC_Trig_External = ADC_EXTERNAL_TRIGGER_MODE_NONE;
    ADC_InitStructure.ADC_Data_Align = ADC_DATAALIGN_RIGHT;
    ADC_InitStructure.ADC_Channel_Number = 1;
    ADC_Init(&ADC_InitStructure);

    /* ADC regular channels configuration */
    ADC_RegularChannel_Config(ADC_CHANNEL_10, 1,ADC_SAMPLETIME_55POINT5);

    ADC_OversamplingRatio_Config(ADC_OVERSAMPLING_RATIO_4X);
    ADC_OversamplingShift_Config(ADC_OVERSAMPLING_SHIFT_NONE);
    ADC_Oversampler_Enable(ENABLE);

    /* Enable ADC */
    ADC_Enable(ENABLE);
    ADC_Calibration();

    /* Start ADC Software Conversion */
    ADC_SoftwareStartConv_Enable(ENABLE);
}
Example #4
0
/*  This function get the offset of the ADC
 *
 *   This function makes an internal coupling to the same pin and calculate
 *   the internal offset in the ADC.
 *
 *  \note This function only return the low byte of the 12-bit convertion,
 *        because the offset should never be more than +-8 LSB off.
 *
 *  \param adc Pointer to the ADC to calculate offset from.
 *
 *  \return Offset on the selected ADC
 */
uint8_t ADC_Offset_Get(ADC_t * adc)
{
	uint8_t offset;

  	// Set up ADC to get offset.  
  	ADC_ConvMode_and_Resolution_Config(adc, true, ADC_RESOLUTION_12BIT_gc);

	ADC_Prescaler_Config(adc , ADC_PRESCALER_DIV8_gc);

	ADC_Referance_Config(adc , ADC_REFSEL_INT1V_gc);

	ADC_Ch_InputMode_and_Gain_Config(&(adc->CH0),
	                                 ADC_CH_INPUTMODE_DIFF_gc,
	                                 ADC_CH_GAIN_1X_gc);

	ADC_Ch_InputMux_Config(&(adc->CH0), ADC_CH_MUXPOS_PIN0_gc, ADC_CH_MUXNEG_PIN0_gc);

	// Enable ADC.  
	ADC_Enable(adc);

	// Wait until ADC is ready.  
	ADC_Wait_32MHz(adc);

	// Do one conversion to find offset.  
	ADC_Ch_Conversion_Start(&(adc->CH0));

	do{
	}while(!ADC_Ch_Conversion_Complete(&(adc->CH0)));
	offset = ADC_ResultCh_GetLowByte(&(adc->CH0), 0x00);

	// Disable ADC.  
	ADC_Disable(adc);

	return offset;
}
Example #5
0
int main (void)
{

	DIO_init();

	LCD_init();
	LCD_gotoxy(1,1);
	printf("AVR ADC Tutorial");
	LCD_gotoxy(1,2);

	ADC_init();
	ADC_Configure_Reference(VREFERENCE_VALUE);
	ADC_Configure_PRESCALAR(PRESCALAR_VALUE);
	ADC_Enable();
	ADC_start();

	while(1)
	{
		LCD_gotoxy(1,2);
		adc_read=ADC_read_8bits(ADC0);
		printf("%d",adc_read);
		printf ("                  " );
		TO_DELAY(500);
	}

	return(0);

}
Example #6
0
/*! \brief  Detect Board Revision
  *
  * @retval Version Number of Board
*/
uint8_t BOARD_Detect_Revision(void)
{
  ADC_Result  result;
  uint16_t    revision_value;
  uint8_t     i;
  
  PGA_SetChannel(SPI_DEVICE_AMP_V_I_DCBUS, CHANNEL1);
  
  ADC_Enable(TSB_ADB);  
  ADC_SetClk(TSB_ADB, ADC_HOLD_FIX, ADC_FC_DIVIDE_LEVEL_2);
  ADC_SetSWTrg(TSB_ADB, ADC_REG2, TRG_ENABLE(ADC_REG2));
  ADC_Start(TSB_ADB, ADC_TRG_SW);
  while (ADC_GetConvertState(TSB_ADB, ADC_TRG_SW) == BUSY);
  result=ADC_GetConvertResult(TSB_ADB, ADC_REG2);
  ADC_Disable(TSB_ADB);  

  PGA_SetChannel(SPI_DEVICE_AMP_V_I_DCBUS, CHANNEL0);
  
  for (i=0;i<sizeof(revisions)/sizeof(revisions[0]);i++)
  {
    revision_value = result.Bit.ADResult*10/gaintable[ChannelValues[1].gain_current_measure];
    if (abs((revisions[i][0]-revision_value)<100))
      break;
  }
  return revisions[i][1];
}
Example #7
0
static void AD_Reset()
{
	ADC_InitTypeDef ADC_InitStructure;

	ADC_DeInit(ADC1);

	/* ADC configuration ------------------------------------------------------*/
	ADC_InitStructure.ADC_Mode = ADC_Mode_RegInjecSimult; //ADC_Mode_RegSimult;
	ADC_InitStructure.ADC_ScanConvMode = ENABLE;
	ADC_InitStructure.ADC_ContinuousConvMode = DISABLE;
	ADC_InitStructure.ADC_ExternalTrigConv = ADC_ExternalTrigConv_T3_TRGO;
	ADC_InitStructure.ADC_DataAlign = ADC_DataAlign_Right;
	ADC_InitStructure.ADC_NbrOfChannel = 1;

	ADC_Init(ADC1, &ADC_InitStructure);

	ADC_ExternalTrigConvCmd(ADC1, ENABLE);

	ADC_RegularChannelConfig(ADC1, ADC_Channel_1, 1, ADC_SampleTime_239Cycles5);

	ADC_ClearITPendingBit(ADC1, ADC_IT_EOC);
	ADC_ITConfig(ADC1, ADC_IT_EOC, ENABLE);

	/* enable and calibrate ADCs */
	ADC_Enable(ADC1);

}
Example #8
0
/*********************************************************************
* Function: void SYSTEM_Initialize( SYSTEM_STATE state )
*
* Overview: Initializes the system.
*
* PreCondition: None
*
* Input:  SYSTEM_STATE - the state to initialize the system into
*
* Output: None
*
********************************************************************/
void SYSTEM_Initialize( SYSTEM_STATE state )
{
    switch(state)
    {
        case SYSTEM_STATE_USB_START:
            #if defined(USE_INTERNAL_OSC)
                //Make sure to turn on active clock tuning for USB full speed 
                //operation from the INTOSC
                OSCCON = 0xFC;  //HFINTOSC @ 16MHz, 3X PLL, PLL enabled
                ACTCON = 0x90;  //Active clock tuning enabled for USB
            #endif
            LED_Enable(LED_USB_DEVICE_STATE);
            LED_Enable(LED_USB_DEVICE_HID_CUSTOM);
            
            BUTTON_Enable(BUTTON_USB_DEVICE_HID_CUSTOM);
            
            ADC_SetConfiguration(ADC_CONFIGURATION_DEFAULT);
            ADC_Enable(ADC_CHANNEL_POTENTIOMETER);
            break;
            
        case SYSTEM_STATE_USB_SUSPEND: 
            break;
            
        case SYSTEM_STATE_USB_RESUME:
            break;
    }
}
Example #9
0
/**
  * @brief  Enables ADC, starts conversion of injected group with interruption.
  *          - JEOC (end of conversion of injected group)
  *         Each of these interruptions has its dedicated callback function.
  * @param  hadc: ADC handle
  * @retval HAL status.
  */
HAL_StatusTypeDef HAL_ADCEx_InjectedStart_IT(ADC_HandleTypeDef* hadc)
{
  HAL_StatusTypeDef tmp_hal_status = HAL_OK;
  
  /* Check the parameters */
  assert_param(IS_ADC_ALL_INSTANCE(hadc->Instance));
  
  /* Process locked */
  __HAL_LOCK(hadc);
    
  /* Enable the ADC peripheral */
  tmp_hal_status = ADC_Enable(hadc);
  
  /* Start conversion if ADC is effectively enabled */
  if (tmp_hal_status != HAL_ERROR)
  {
    /* Check if a regular conversion is ongoing */
    if(hadc->State == HAL_ADC_STATE_BUSY_REG)
    {
      /* Change ADC state */
      hadc->State = HAL_ADC_STATE_BUSY_INJ_REG;  
    }
    else
    {
      /* Change ADC state */
      hadc->State = HAL_ADC_STATE_BUSY_INJ;
    }
    
    /* Process unlocked */
    /* Unlock before starting ADC conversions: in case of potential           */
    /* interruption, to let the process to ADC IRQ Handler.                   */
    __HAL_UNLOCK(hadc);
    
    /* Set ADC error code to none */
    ADC_CLEAR_ERRORCODE(hadc);
    
    /* Clear injected group conversion flag */
    /* (To ensure of no unknown state from potential previous ADC operations) */
    __HAL_ADC_CLEAR_FLAG(hadc, ADC_FLAG_JEOC);
    
    /* Enable end of conversion interrupt for injected channels */
    __HAL_ADC_ENABLE_IT(hadc, ADC_IT_JEOC);
   
    /* Enable conversion of injected group.                                   */
    /* If software start has been selected, conversion starts immediately.    */
    /* If external trigger has been selected, conversion will start at next   */
    /* trigger event.                                                         */
    /* If automatic injected conversion is enabled, conversion will start     */
    /* after next regular group conversion.                                   */
    if (ADC_IS_SOFTWARE_START_INJECTED(hadc)              && 
        HAL_IS_BIT_CLR(hadc->Instance->CR1, ADC_CR1_JAUTO)  )
    {
      /* Enable ADC software conversion for injected channels */
      SET_BIT(hadc->Instance->CR2, ADC_CR2_JSWSTART);
    }
  }
  
  /* Return function status */
  return tmp_hal_status;
}
Example #10
0
void initAdc (ADC_t * adc) {
	ADC_CalibrationValues_Load (adc);
  	ADC_ConvMode_and_Resolution_Config (adc, ADC_ConvMode_Unsigned, ADC_RESOLUTION_8BIT_gc);
	ADC_Prescaler_Config (adc, ADC_PRESCALER_DIV16_gc); // Fadc = 250khz
	ADC_Reference_Config (adc, ADC_REFSEL_INT1V_gc); // vref = internal 1v
    
    /* Setup channel 0, 1, 2 and 3 to have single ended input and 1x gain. */
	ADC_Ch_InputMode_and_Gain_Config (&(adc->CH0),
	                                 ADC_CH_INPUTMODE_SINGLEENDED_gc,
	                                 ADC_CH_GAIN_1X_gc);

	ADC_Ch_InputMode_and_Gain_Config (&(adc->CH1),
	                                 ADC_CH_INPUTMODE_SINGLEENDED_gc,
	                                 ADC_CH_GAIN_1X_gc);

	ADC_Ch_InputMode_and_Gain_Config (&(adc->CH2),
	                                 ADC_CH_INPUTMODE_SINGLEENDED_gc,
	                                 ADC_CH_GAIN_1X_gc);

	ADC_Ch_InputMode_and_Gain_Config (&(adc->CH3),
	                                 ADC_CH_INPUTMODE_SINGLEENDED_gc,
	                                 ADC_CH_GAIN_1X_gc);

	/* Enable high level sample complete interrupt for channel 3 */
	ADC_Ch_Interrupts_Config (&(adc->CH0), ADC_CH_INTMODE_COMPLETE_gc, ADC_CH_INTLVL_LO_gc);
	ADC_Ch_Interrupts_Config (&(adc->CH1), ADC_CH_INTMODE_COMPLETE_gc, ADC_CH_INTLVL_LO_gc);
	ADC_Ch_Interrupts_Config (&(adc->CH2), ADC_CH_INTMODE_COMPLETE_gc, ADC_CH_INTLVL_LO_gc);
	ADC_Ch_Interrupts_Config (&(adc->CH3), ADC_CH_INTMODE_COMPLETE_gc, ADC_CH_INTLVL_LO_gc);

	PMIC.CTRL |= PMIC_HILVLEN_bm; // Enable low level interrupts
	ADC_Enable (adc); // Enable ADC A with free running mode
	ADC_Wait_32MHz (adc); // Wait until common mode voltage is stable
}
Example #11
0
/*********************************************************************
* Function: void SYSTEM_Initialize( SYSTEM_STATE state )
*
* Overview: Initializes the system.
*
* PreCondition: None
*
* Input:  SYSTEM_STATE - the state to initialize the system into
*
* Output: None
*
********************************************************************/
void SYSTEM_Initialize( SYSTEM_STATE state )
{
    switch(state)
    {
        case SYSTEM_STATE_USB_START:
             #if(USB_SPEED_OPTION == USB_FULL_SPEED)

                 //Enable INTOSC active clock tuning if full speed
                 ACTCON = 0x90; //Enable active clock self tuning for USB operation
                 while(OSCCON2bits.LOCK == 0);   //Make sure PLL is locked/frequency is compatible
                                        //with USB operation (ex: if using two speed
                                        //startup or otherwise performing clock switching)
             #endif
			 
            LED_Enable(LED_USB_DEVICE_STATE);
            
            BUTTON_Enable(BUTTON_USB_DEVICE_HID_JOYSTICK);
            
            ADC_SetConfiguration(ADC_CONFIGURATION_DEFAULT);
            ADC_Enable(ADC_CHANNEL_POTENTIOMETER);
            break;
        case SYSTEM_STATE_USB_SUSPEND:
            break;
            
        case SYSTEM_STATE_USB_RESUME:
            break;
    }
}
Example #12
0
/*********************************************************************
* Function: void SYSTEM_Tasks(void)
*
* Overview: Runs system level tasks that keep the system running
*
* PreCondition: System has been initalized with SYSTEM_Initialize()
*
* Input: None
*
* Output: None
*
********************************************************************/
void SYSTEM_Tasks(void)
{
    switch(softStartStatus)
    {
        case SOFT_START_POWER_OFF:
            break;

        case SOFT_START_POWER_START:
            if(USBGetDeviceState() != CONFIGURED_STATE)
            {
                break;
            }
            
            AppPowerEnable();
            softStartStatus = SOFT_START_POWER_ENABLED;
            break;

        case SOFT_START_POWER_ENABLED:
            if(AppPowerReady() == true)
            {
                softStartStatus = SOFT_START_POWER_READY;
                LED_Enable(LED_USB_DEVICE_STATE);
                LED_Enable(LED_USB_DEVICE_HID_CUSTOM);
				
                ADC_SetConfiguration(ADC_CONFIGURATION_DEFAULT);
                ADC_Enable(ADC_CHANNEL_POTENTIOMETER);
            }
            break;
            
        case SOFT_START_POWER_READY:
            break;
    }
}
Example #13
0
/*******************************************************************************
* Function Name: ADC_Start
********************************************************************************
*
* Summary:
*  Performs all required initialization for this component
*  and enables the power. The power will be set to the appropriate
*  power based on the clock frequency.
*
* Parameters:
*  None.
*
* Return:
*  None.
*
* Global variables:
*  The ADC_initVar variable is used to indicate when/if initial
*  configuration of this component has happened. The variable is initialized to
*  zero and set to 1 the first time ADC_Start() is called. This allows for
*  component Re-Start without re-initialization in all subsequent calls to the
*  ADC_Start() routine.
*  If re-initialization of the component is required the variable should be set
*  to zero before call of ADC_Start() routine, or the user may call
*  ADC_Init() and ADC_Enable() as done in the
*  ADC_Start() routine.
*
*******************************************************************************/
void ADC_Start(void)
{
    /* If not Initialized then initialize all required hardware and software */
    if(ADC_initVar == 0u)
    {
        ADC_Init();
        ADC_initVar = 1u;
    }
    ADC_Enable();
}
Example #14
0
uint16_t readADC(){
    uint16_t ADC_result = 0;
    int8_t offset;
 	/* Move stored calibration values to ADC B */
	ADC_CalibrationValues_Load(&ADCA);
   
    /* Set up ADC B to have signed conversion mode and 12 bit resolution. */
  	ADC_ConvMode_and_Resolution_Config(&ADCA, true, ADC_RESOLUTION_12BIT_gc);

    // The ADC has different voltage reference options, controlled by the REFSEL bits in the
    // REFCTRL register. Here the internal reference is selected 
	ADC_Reference_Config(&ADCA, ADC_REFSEL_VCC_gc);

	// The clock into the ADC decide the maximum sample rate and the conversion time, and
    // this is controlled by the PRESCALER bits in the PRESCALER register. Here, the
    // Peripheral Clock is divided by 8 ( gives 250 KSPS with 2Mhz clock )
	ADC_Prescaler_Config(&ADCA, ADC_PRESCALER_DIV8_gc);

    // The used Virtual Channel (CH0) must be set in the correct mode
    // In this task we will use single ended input, so this mode is selected 
  
    /* Setup channel 0 to have single ended input. */
	ADC_Ch_InputMode_and_Gain_Config(&ADCA.CH0,
	                                 ADC_CH_INPUTMODE_DIFF_gc,
                                     ADC_CH_GAIN_1X_gc);
     // Setting up the which pins to convert.
    // Note that the negative pin is internally connected to ground  
	ADC_Ch_InputMux_Config(&ADCA.CH0, ADC_CH_MUXPOS_PIN0_gc, ADC_CH_MUXNEG_PIN1_gc);
  

    // Before the ADC can be used it must be enabled 
	ADC_Enable(&ADCA);


    // Wait until the ADC is ready
    ADC_Wait_32MHz(&ADCA);

    // In the while(1) loop, a conversion is started on CH0 and the 8 MSB of the result is
    // ouput on the LEDPORT when the conversion is done   

	/* Get offset value for ADC B.  */
	offset = ADC_Offset_Get_Unsigned(&ADCA, &(ADCA.CH0), true);  
	
	for(int i = 0; i<5; i++){
	
         ADC_Ch_Conversion_Start(&ADCA.CH0);
           
         while(!ADC_Ch_Conversion_Complete(&ADCA.CH0));
                
            //ADCB.INTFLAGS = ADC_CH0IF_bm;     // Clear CH0IF by writing a one to it
         ADC_result += ADCA.CH0RES;// - offset;
    }
    
    return ADC_result/5;
}
Example #15
0
static void setupADC(void)
{
	ADC_SelectPrescaler(LIB_ADC_PRESCALER_DIV64);
	ADC_SelectReference(LIB_ADC_REF_VCC);
	ADC_Enable(true);
	ADC_EnableInterrupts(true);

	adc.busy = false;
	adc.channel = BATT_ADC_CHANNEL;
	adc.conversionComplete = false;
}
Example #16
0
void adc_init(void)
{	  
    DMA_InitPara DMA_InitStructure;
    ADC_InitPara ADC_InitStructure;
    
    RCC_APB2PeriphClock_Enable(RCC_APB2PERIPH_ADC1, ENABLE);	  

    RCC_ADCCLKConfig(RCC_ADCCLK_APB2_DIV6);

    RCC_AHBPeriphClock_Enable(RCC_AHBPERIPH_DMA1, ENABLE);		     

    DMA_InitStructure.DMA_PeripheralBaseAddr = 0x4001244C; 
    DMA_InitStructure.DMA_MemoryBaseAddr = (uint32_t)adcarray; 
    DMA_InitStructure.DMA_DIR = DMA_DIR_PERIPHERALSRC;  
    DMA_InitStructure.DMA_BufferSize = 4;	
    DMA_InitStructure.DMA_PeripheralInc = DMA_PERIPHERALINC_DISABLE;	
    DMA_InitStructure.DMA_MemoryInc = DMA_MEMORYINC_ENABLE;	
    DMA_InitStructure.DMA_PeripheralDataSize = DMA_PERIPHERALDATASIZE_HALFWORD; 
    DMA_InitStructure.DMA_MemoryDataSize = DMA_MEMORYDATASIZE_HALFWORD; 
    DMA_InitStructure.DMA_Mode = DMA_MODE_CIRCULAR; 
    DMA_InitStructure.DMA_Priority = DMA_PRIORITY_HIGH;
    DMA_InitStructure.DMA_MTOM = DMA_MEMTOMEM_DISABLE; 
		
    DMA_Init(DMA1_CHANNEL1, &DMA_InitStructure);	 
  
    DMA_Enable(DMA1_CHANNEL1, ENABLE);  
    
  //  ADC_DeInit(&ADC_InitStructure);
		
    ADC_InitStructure.ADC_Mode_Scan = ENABLE;		 
    ADC_InitStructure.ADC_Mode_Continuous = ENABLE;  
    ADC_InitStructure.ADC_Trig_External = ADC_EXTERNAL_TRIGGER_MODE_NONE;  
    ADC_InitStructure.ADC_Data_Align = ADC_DATAALIGN_RIGHT;	
    ADC_InitStructure.ADC_Channel_Number = 4;  
		
    ADC_Init(&ADC_InitStructure);  
    // current?
    ADC_RegularChannel_Config(ADC_CHANNEL_7, 1, ADC_SAMPLETIME_239POINT5);
		// battery channel
    ADC_RegularChannel_Config(ADC_CHANNEL_5, 2, ADC_SAMPLETIME_239POINT5);

    ADC_RegularChannel_Config(ADC_CHANNEL_4, 3, ADC_SAMPLETIME_239POINT5);
    ADC_RegularChannel_Config(ADC_CHANNEL_1, 4, ADC_SAMPLETIME_239POINT5);

    ADC_DMA_Enable(ENABLE);	 
    
    ADC_Enable(ENABLE); 
		
    ADC_Calibration();
    
    ADC_SoftwareStartConv_Enable(ENABLE);  
}
Example #17
0
/**
  * @brief  Main program.
  * @param  None
  * @retval None
  */
int main(void)
{
    /* Configure System clocks -----------------------------------------------*/
    RCC_Configuration();
    
    /* Configure GPIO ports --------------------------------------------------*/
    GPIO_Configuration();
    
    /* Configure DMA1 channel1 -----------------------------------------------*/
    DMA_DeInit(DMA1_CHANNEL1);
    DMA_InitStructure.DMA_PeripheralBaseAddr = ADC_RDTR_Address;
    DMA_InitStructure.DMA_MemoryBaseAddr = (uint32_t)&ADCConvertedValue;
    DMA_InitStructure.DMA_DIR = DMA_DIR_PERIPHERALSRC;
    DMA_InitStructure.DMA_BufferSize = 1;
    DMA_InitStructure.DMA_PeripheralInc = DMA_PERIPHERALINC_DISABLE;
    DMA_InitStructure.DMA_MemoryInc = DMA_MEMORYINC_DISABLE;
    DMA_InitStructure.DMA_PeripheralDataSize = DMA_PERIPHERALDATASIZE_HALFWORD;
    DMA_InitStructure.DMA_MemoryDataSize = DMA_MEMORYDATASIZE_HALFWORD;
    DMA_InitStructure.DMA_Mode = DMA_MODE_CIRCULAR;
    DMA_InitStructure.DMA_Priority = DMA_PRIORITY_HIGH;
    DMA_InitStructure.DMA_MTOM = DMA_MEMTOMEM_DISABLE;
    DMA_Init(DMA1_CHANNEL1, &DMA_InitStructure);
    
    /* Enable DMA1 channel1 */
    DMA_Enable(DMA1_CHANNEL1, ENABLE);
    
    /* Configure ADC ---------------------------------------------------------*/
    ADC_InitStructure.ADC_Mode_Scan = DISABLE;
    ADC_InitStructure.ADC_Mode_Continuous = ENABLE;
    ADC_InitStructure.ADC_Trig_External = ADC_EXTERNAL_TRIGGER_MODE_NONE;
    ADC_InitStructure.ADC_Data_Align = ADC_DATAALIGN_RIGHT;
    ADC_InitStructure.ADC_Channel_Number = 1;
    ADC_Init(&ADC_InitStructure);
    
    /* Configure ADC regular channelx */ 
    ADC_RegularChannel_Config( BOARD_ADC_CHANNEL, 1, ADC_SAMPLETIME_239POINT5);
    
    /* Enable ADC DMA */
    ADC_DMA_Enable(ENABLE);
    
    /* Enable ADC */
    ADC_Enable(ENABLE);
    
    ADC_Calibration();
     
    /* Start ADC Software Conversion */ 
    ADC_SoftwareStartConv_Enable(ENABLE);
    
    while (1)
    {
    }
}
Example #18
0
/**
 * Name         : adc_init
 *
 * Synopsis     : void adc_init	(void)
 *
 * Description  : Initialize the main system clock
 * 
 */
void adc_init	(void)
{
	/////////////////FROM XPLAINED 1505////////////////////////////////
	// Variable for use when we read the result from an ADC channel
	//PORTQ.PIN2CTRL = (PORTQ.PIN2CTRL & ~PORT_OPC_gm) | PORT_OPC_PULLDOWN_gc; // This pin must be grounded to "enable" NTC-resistor
	/* Move stored calibration values to ADC B */
	ADC_CalibrationValues_Load(&ADCA);
	/* Set up ADC A to have signed conversion mode and 8 bit resolution. */
	ADC_ConvMode_and_Resolution_Config(&ADCA, true, ADC_RESOLUTION_12BIT_gc);
	// The ADC has different voltage reference options, controlled by the REFSEL bits in the
	// REFCTRL register. Here the internal reference is selected
	ADC_Reference_Config(&ADCA, ADC_REFSEL_VCC_gc);
	// The clock into the ADC decides the maximum sample rate and the conversion time, and
	// this is controlled by the PRESCALER bits in the PRESCALER register. Here, the
	// Peripheral Clock is divided by 8 ( gives 250 KSPS with 2Mhz clock )
	ADC_Prescaler_Config(&ADCA, ADC_PRESCALER_DIV8_gc);
	// The used Virtual Channel (CH0) must be set in the correct mode
	// In this task we will use single ended input, so this mode is selected
	/* Setup channel 0 to have single ended input. */
	ADC_Ch_InputMode_and_Gain_Config(&ADCA.CH0,
	ADC_CH_INPUTMODE_SINGLEENDED_gc,
	ADC_CH_GAIN_1X_gc);
	ADC_Ch_InputMode_and_Gain_Config(&ADCA.CH1,
	ADC_CH_INPUTMODE_SINGLEENDED_gc,
	ADC_CH_GAIN_1X_gc);
	ADC_Ch_InputMode_and_Gain_Config(&ADCA.CH2,
	ADC_CH_INPUTMODE_SINGLEENDED_gc,
	ADC_CH_GAIN_1X_gc);
	
	// Setting up the which pins to convert.
	// Note that the negative pin is internally connected to ground
	//ADC_Ch_InputMux_Config(&ADCB.CH0, ADC_CH_MUXPOS_PIN9_gc, ADC_CH_MUXNEG_PIN1_gc);
	ADCA.CH0.MUXCTRL |= ADC_CH_MUXPOS_PIN0_gc;
	ADCA.CH1.MUXCTRL |= ADC_CH_MUXPOS_PIN1_gc;
	ADCA.CH2.MUXCTRL |= ADC_CH_MUXPOS_PIN2_gc;
	
	// Before the ADC can be used it must be enabled
	ADC_Enable(&ADCA);
	
	// Wait until the ADC is ready
	ADC_Wait_8MHz(&ADCA);
	// In the while(1) loop, a conversion is started on CH0 and the 8 MSB of the result is
	// output on the LEDPORT when the conversion is done
	/* Get offset value for ADC B. */
	adcx.offset = ADC_Offset_Get_Signed(&ADCA, &(ADCA.CH0), true);
	adcy.offset = ADC_Offset_Get_Signed(&ADCA, &(ADCA.CH1), true);
	adcz.offset = ADC_Offset_Get_Signed(&ADCA, &(ADCA.CH2), true);
		
}
Example #19
0
/*******************************************************************************
* Function Name: ADC_Wakeup
********************************************************************************
*
* Summary:
*  Restores the user configuration and enables the power to the block.
*
* Parameters:
*  None
*
* Return:
*  None
*
* Global variables:
*  ADC_backup:  The structure field 'enableState' is used to
*  restore the enable state of block after wakeup from sleep mode.
*
*******************************************************************************/
void ADC_Wakeup(void) 
{
    /* Restore the configuration */
    ADC_RestoreConfig();

    /* Enables the component operation */
    if(ADC_backup.enableState != ADC_DISABLED)
    {
        ADC_Enable();
        if((ADC_backup.enableState & ADC_STARTED) != 0u)
        {
            ADC_StartConvert();
        }
    } /* Do nothing if component was disable before */
}
Example #20
0
/**
 * This method handles the initilization of the project's hardware. Within the
 * hardware are both external and internal peripherals of the microcontroller
 *
 * @PARAM:      None
 * @PRE:        None
 * @POST:       The hardware (Modules and Peripherals) is initialized and is
 *                      ready for use.
 */
void initHardware(void){
	
	// Desactivamos las interrupciones
	cli();
	
	// Inicializamos la USART y habilitamos para transmisión y recepción
	USART_init();
	USART_EnableTx();
	USART_EnableRx();
	
	// Inicializamos y habilitamos el conversor Análogo-Digital
	ADC_Init();
	ADC_Enable();
	
	sei();
}
Example #21
0
/*******************************************************************************
* Function Name: ADC_Wakeup
********************************************************************************
*
* Summary:
*  Restores the component enable state and configuration registers.
*  This should be called just after awaking from sleep mode.
*
* Parameters:
*  None.
*
* Return:
*  None.
*
* Global Variables:
*  ADC_backup - used.
*
*******************************************************************************/
void ADC_Wakeup(void)
{
    ADC_SAR_DFT_CTRL_REG &= (uint32)~ADC_ADFT_OVERRIDE;
    if(ADC_backup.enableState != ADC_DISABLED)
    {
        /* Enable the SAR internal pump  */
        if((ADC_backup.enableState & ADC_BOOSTPUMP_ENABLED) != 0u)
        {
            ADC_SAR_CTRL_REG |= ADC_BOOSTPUMP_EN;
        }
        ADC_Enable();
        if((ADC_backup.enableState & ADC_STARTED) != 0u)
        {
            ADC_StartConvert();
        }
    }
}
Example #22
0
void TS_Setup(void)
{
	ADC_SelectPrescaler(LIB_ADC_PRESCALER_DIV64);
	ADC_SelectReference(LIB_ADC_REF_VCC);
	ADC_Enable(true);
	ADC_EnableInterrupts(true);

	currentSensor = SENSOR_OUTFLOW;
	
	adc.busy = false;
	adc.channel = channels[currentSensor];
	adc.conversionComplete = false;
	
	THERMISTOR_Init();
	(void)THERMISTOR_InitDevice(&thermistor, THERMISTOR_BETA, RTHERM);
	(void)POTDIVIDER_Init(&divider, 1023, RPULLUP, PULLUP);
}
Example #23
0
void Example_ADC_ReadData(void)
{
    /* 1. set ADC clock */
    ADC_SetClk(TSB_ADB, ADC_HOLD_FIX, ADC_FC_DIVIDE_LEVEL_2);

    /* 2. select trigger and AD channel, this time we use sofeware trigger, */
    /*    the VR1 is connected to  ADC unit B channel 2, remember to input with macro TRG_ENABLE() */
    ADC_SetSWTrg(TSB_ADB, ADC_REG0, TRG_ENABLE(ADC_AIN2));

    /* 3. enable ADC module */
    ADC_Enable(TSB_ADB);

    /* 4. now start ADC */
    ADC_Start(TSB_ADB, ADC_TRG_SW);

    /* initialize LEDs on M374-SK board before display something */
    LED_Init();

    while (1U) {
        /* check ADC module state */
        adcState = ADC_GetConvertState(TSB_ADB, ADC_TRG_SW);

        if (adcState == DONE) {
            /* read ADC result when it is finished */
            result = ADC_GetConvertResult(TSB_ADB, ADC_REG0);

            /* get the real ADC result without other information */
            /* "/16" is to limit the range of AD value */
            myResult = result.Bit.ADResult / 16U;

            /* software trigger, need to trigger it again */
            ADC_Start(TSB_ADB, ADC_TRG_SW);
        }
        myDelay(myResult);  
        if(idx) 
        {
          LED_Off(LEDs[idx-1]);
        }
        idx &= 0x03U;
        myDelay(myResult); 
        LED_On(LEDs[idx]);
        idx++;
    }
}
void adc_init(void)
{
	ADC_CalibrationValues_Load(&ADCA);
	ADC_ConvMode_and_Resolution_Config(&ADCA, 
		ADC_ConvMode_Unsigned, ADC_RESOLUTION_12BIT_gc);

	ADC_Prescaler_Config(&ADCA, ADC_PRESCALER_DIV16_gc);

	ADC_Reference_Config(&ADCA, ADC_REFSEL_VCC_gc);

	ADC_Ch_InputMode_and_Gain_Config(&ADCA.CH0,
	                                 ADC_CH_INPUTMODE_SINGLEENDED_gc,
                                     ADC_CH_GAIN_1X_gc);

	ADC_Ch_InputMux_Config(&ADCA.CH0, ADC_CH_MUXPOS_PIN7_gc, ADC_CH_MUXNEG_PIN0_gc);

	ADC_Enable(&ADCA);

	ADC_Wait_8MHz(&ADCA);
}
Example #25
0
/*********************************************************************
* Function: void SYSTEM_Initialize( SYSTEM_STATE state )
*
* Overview: Initializes the system.
*
* PreCondition: None
*
* Input:  SYSTEM_STATE - the state to initialize the system into
*
* Output: None
*
********************************************************************/
void SYSTEM_Initialize( SYSTEM_STATE state )
{
    switch(state)
    {
    case SYSTEM_STATE_USB_START:
        LED_Enable(LED_USB_DEVICE_STATE);

        BUTTON_Enable(BUTTON_USB_DEVICE_HID_JOYSTICK);

        ADC_SetConfiguration(ADC_CONFIGURATION_DEFAULT);
        ADC_Enable(ADC_CHANNEL_POTENTIOMETER);
        break;

    case SYSTEM_STATE_USB_SUSPEND:
        break;

    case SYSTEM_STATE_USB_RESUME:
        break;
    }
}
Example #26
0
/**
  * @brief  Configure ADC_12B resolution.
  * @param  None
  * @retval None
  */
void ADC_12BConfiguration(void)
{
    /* Configure ADC ----------------------------------------------------------*/
    ADC_InitStructure.ADC_Mode_Scan = DISABLE;
    ADC_InitStructure.ADC_Mode_Continuous = DISABLE;
    ADC_InitStructure.ADC_Trig_External = ADC_EXTERNAL_TRIGGER_MODE_NONE;
    ADC_InitStructure.ADC_Data_Align = ADC_DATAALIGN_RIGHT;
    ADC_InitStructure.ADC_Channel_Number = 1;
    ADC_Init(&ADC_InitStructure);

    /* Configure ADC regular channel10 */
    ADC_RegularChannel_Config(ADC_CHANNEL_10, 1, ADC_SAMPLETIME_55POINT5);
    /* Enable ADC DMA */
    ADC_DMA_Enable(ENABLE);
    ADC_Resolution_Config(ADC_RESOLUTION_12B);
    /* Enable ADC */
    ADC_Enable(ENABLE);
    ADC_Calibration();
    /* Start ADC Software Conversion */
    ADC_SoftwareStartConv_Enable(ENABLE);
}
Example #27
0
/*********************************************************************
* Function: void SYSTEM_Initialize( SYSTEM_STATE state )
*
* Overview: Initializes the system.
*
* PreCondition: None
*
* Input:  SYSTEM_STATE - the state to initialize the system into
*
* Output: None
*
********************************************************************/
void SYSTEM_Initialize( SYSTEM_STATE state )
{
    int  value;
	
    switch(state)
    {
        case SYSTEM_STATE_USB_START:
            value = SYSTEMConfigWaitStatesAndPB( 64000000UL );

            // Enable the cache for the best performance
            CheKseg0CacheOn();

            INTEnableSystemMultiVectoredInt();

            value = OSCCON;
            while (!(value & 0x00000020))
            {
                value = OSCCON;    // Wait for PLL lock to stabilize
            }

            //Disable JTAG
            DDPCONbits.JTAGEN = 0;

            LED_Enable(LED_USB_DEVICE_STATE);
            LED_Enable(LED_USB_DEVICE_HID_CUSTOM);
            
            BUTTON_Enable(BUTTON_USB_DEVICE_HID_CUSTOM);
            
            ADC_SetConfiguration(ADC_CONFIGURATION_DEFAULT);
            ADC_Enable(ADC_CHANNEL_POTENTIOMETER);
            break;
            
        case SYSTEM_STATE_USB_SUSPEND:
            break;
            
        case SYSTEM_STATE_USB_RESUME:
            break;
    }
}
void adc_temp_init(void)
{
	// enable 1V reference and temperature modules
	ADC_BandgapReference_Enable(&ADCB);
	ADC_TempReference_Enable(&ADCB);

	// load calibration from signature bytes
	ADC_CalibrationValues_Load(&ADCB);

	// Conversion mode and resolution (12 bit right-aligned)
	ADC_ConvMode_and_Resolution_Config(&ADCB, 
		ADC_ConvMode_Unsigned, ADC_RESOLUTION_12BIT_gc);

	// prescaler from system clock (fastest)
	ADC_Prescaler_Config(&ADCB, ADC_PRESCALER_DIV4_gc);

	// internal 1V reference
	ADC_Reference_Config(&ADCB, ADC_REFSEL_INT1V_gc);

	// channel 0 for temperature
	ADC_Ch_InputMode_and_Gain_Config(&ADCB.CH0,
	                                 ADC_CH_INPUTMODE_INTERNAL_gc,
                                     ADC_CH_GAIN_1X_gc);

	ADC_Ch_InputMux_Config(&ADCB.CH0, ADC_CH_MUXINT_TEMP_gc, ADC_CH_MUXNEG_PIN0_gc);

	// channel 1 for VCC/10
	ADC_Ch_InputMode_and_Gain_Config(&ADCB.CH1,
	                                 ADC_CH_INPUTMODE_INTERNAL_gc,
                                     ADC_CH_GAIN_1X_gc);

	ADC_Ch_InputMux_Config(&ADCB.CH1, ADC_CH_MUXINT_SCALEDVCC_gc, ADC_CH_MUXNEG_PIN0_gc);

	ADC_Enable(&ADCB);

	ADC_Wait_8MHz(&ADCB);
}
Example #29
0
void InitADC( ADC_t *ADC_Pointer )
{
    // Initialize sweep for channel 0, 1, 2 and 3
    ADC_SweepChannels_Config( ADC_Pointer, ADC_SWEEP_0123_gc );

    // Setup event to start synchronized sweep
    ADC_Events_Config( ADC_Pointer, ADC_EVSEL_0123_gc, ADC_EVACT_SYNCHSWEEP_gc );

    // Initialize the four channels to convert in single ended mode
    ADC_Ch_InputMode_and_Gain_Config( &ADC_Pointer->CH0, ADC_CH_INPUTMODE_SINGLEENDED_gc, ADC_CH_GAIN_1X_gc );
    ADC_Ch_InputMode_and_Gain_Config( &ADC_Pointer->CH1, ADC_CH_INPUTMODE_SINGLEENDED_gc, ADC_CH_GAIN_1X_gc );
    ADC_Ch_InputMode_and_Gain_Config( &ADC_Pointer->CH2, ADC_CH_INPUTMODE_SINGLEENDED_gc, ADC_CH_GAIN_1X_gc );
    ADC_Ch_InputMode_and_Gain_Config( &ADC_Pointer->CH3, ADC_CH_INPUTMODE_SINGLEENDED_gc, ADC_CH_GAIN_1X_gc );

    // Route the channels to different pins
    // Note that in Single Ended Mode, there is no negative input
    ADC_Ch_InputMux_Config( &ADC_Pointer->CH0, ADC_CH_MUXPOS_PIN1_gc, 0 );
    ADC_Ch_InputMux_Config( &ADC_Pointer->CH1, ADC_CH_MUXPOS_PIN2_gc, 0 );
    ADC_Ch_InputMux_Config( &ADC_Pointer->CH2, ADC_CH_MUXPOS_PIN3_gc, 0 );
    ADC_Ch_InputMux_Config( &ADC_Pointer->CH3, ADC_CH_MUXPOS_PIN4_gc, 0 );
           
    // Sample rate is CPUFREQ / 32. @ 2 MHz this equals 62,5ksps
	ADC_Prescaler_Config( ADC_Pointer, ADC_PRESCALER_DIV32_gc);
   
    // Set up ADCx  to have unsigned conversion mode and 8 bit resolution
  	ADC_ConvMode_and_Resolution_Config( ADC_Pointer, false, ADC_RESOLUTION_8BIT_gc );
    
    // Set reference voltage on ADCx to be VCC/1.6 V
	ADC_Reference_Config( ADC_Pointer, ADC_REFSEL_VCC_gc );
   
    // Enable the ADC
	ADC_Enable( ADC_Pointer );
     
    // Wait until common mode voltage is stable. Default clk is 2MHz and
    // therefore within the maximum frequency to use this function. 
    ADC_Wait_8MHz( ADC_Pointer );
}
/**
  * @brief  Enables ADC, starts conversion of regular group and transfers result
  *         through DMA.
  *         Multimode must have been previously configured using 
  *         HAL_ADCEx_MultiModeConfigChannel() function.
  *         Interruptions enabled in this function:
  *          - DMA transfer complete
  *          - DMA half transfer
  *         Each of these interruptions has its dedicated callback function.
  * @note:  On STM32F1 devices, ADC slave regular group must be configured 
  *         with conversion trigger ADC_SOFTWARE_START.
  * @note:  ADC slave can be enabled preliminarily using single-mode  
  *         HAL_ADC_Start() function.
  * @param  hadc: ADC handle of ADC master (handle of ADC slave must not be used)
  * @param  pData: The destination Buffer address.
  * @param  Length: The length of data to be transferred from ADC peripheral to memory.
  * @retval None
  */
HAL_StatusTypeDef HAL_ADCEx_MultiModeStart_DMA(ADC_HandleTypeDef* hadc, uint32_t* pData, uint32_t Length)
{
  HAL_StatusTypeDef tmp_hal_status = HAL_OK;
  ADC_HandleTypeDef tmphadcSlave;

  /* Check the parameters */
  assert_param(IS_ADC_MULTIMODE_MASTER_INSTANCE(hadc->Instance));
  assert_param(IS_FUNCTIONAL_STATE(hadc->Init.ContinuousConvMode));
  
  /* Process locked */
  __HAL_LOCK(hadc);

  /* Set a temporary handle of the ADC slave associated to the ADC master     */
  ADC_MULTI_SLAVE(hadc, &tmphadcSlave);
  
  /* On STM32F1 devices, ADC slave regular group must be configured with      */
  /* conversion trigger ADC_SOFTWARE_START.                                   */
  /* Note: External trigger of ADC slave must be enabled, it is already done  */
  /*       into function "HAL_ADC_Init()".                                    */
  if ((tmphadcSlave.Instance == NULL)                 ||
      (! ADC_IS_SOFTWARE_START_REGULAR(&tmphadcSlave))  )
  {
    /* Update ADC state machine to error */
    hadc->State = HAL_ADC_STATE_ERROR;
    
    /* Process unlocked */
    __HAL_UNLOCK(hadc);
    
    return HAL_ERROR;
  }

  /* Enable the ADC peripherals: master and slave (in case if not already     */
  /* enabled previously)                                                      */
  tmp_hal_status = ADC_Enable(hadc);
  if (tmp_hal_status != HAL_ERROR)
  {
    tmp_hal_status = ADC_Enable(&tmphadcSlave);
  }
  
  /* Start conversion all ADCs of multimode are effectively enabled */
  if (tmp_hal_status != HAL_ERROR)
  {
    /* State machine update (ADC master): Check if an injected conversion is  */
    /* ongoing.                                                               */
    if(hadc->State == HAL_ADC_STATE_BUSY_INJ)
    {
      /* Change ADC state */
      hadc->State = HAL_ADC_STATE_BUSY_INJ_REG;
    }
    else
    {
      /* Change ADC state */
      hadc->State = HAL_ADC_STATE_BUSY_REG;
    }
      
    /* Process unlocked */
    /* Unlock before starting ADC conversions: in case of potential           */
    /* interruption, to let the process to ADC IRQ Handler.                   */
    __HAL_UNLOCK(hadc);
  
    /* Set ADC error code to none */
    ADC_CLEAR_ERRORCODE(hadc);
    
    
    /* Set the DMA transfer complete callback */
    hadc->DMA_Handle->XferCpltCallback = ADC_DMAConvCplt;
       
    /* Set the DMA half transfer complete callback */
    hadc->DMA_Handle->XferHalfCpltCallback = ADC_DMAHalfConvCplt;
    
    /* Set the DMA error callback */
    hadc->DMA_Handle->XferErrorCallback = ADC_DMAError;

    
    /* Manage ADC and DMA start: ADC overrun interruption, DMA start, ADC     */
    /* start (in case of SW start):                                           */
    
    /* Clear regular group conversion flag and overrun flag */
    /* (To ensure of no unknown state from potential previous ADC operations) */
    __HAL_ADC_CLEAR_FLAG(hadc, ADC_FLAG_EOC);
    
    /* Enable ADC DMA mode of ADC master */
    SET_BIT(hadc->Instance->CR2, ADC_CR2_DMA);
    
    /* Start the DMA channel */
    HAL_DMA_Start_IT(hadc->DMA_Handle, (uint32_t)&hadc->Instance->DR, (uint32_t)pData, Length);
    
    /* Start conversion of regular group if software start has been selected. */
    /* If external trigger has been selected, conversion will start at next   */
    /* trigger event.                                                         */
    /* Note: Alternate trigger for single conversion could be to force an     */
    /*       additional set of bit ADON "hadc->Instance->CR2 |= ADC_CR2_ADON;"*/
    if (ADC_IS_SOFTWARE_START_REGULAR(hadc))
    {
      /* Start ADC conversion on regular group with SW start */
      SET_BIT(hadc->Instance->CR2, (ADC_CR2_SWSTART | ADC_CR2_EXTTRIG));
    }
    else
    {
      /* Start ADC conversion on regular group with external trigger */
      SET_BIT(hadc->Instance->CR2, ADC_CR2_EXTTRIG);
    }
  }
  else
  {
    /* Process unlocked */
    __HAL_UNLOCK(hadc);
  }
  
  /* Return function status */
  return tmp_hal_status;
}