Esempio n. 1
0
/**
 * \internal
 * \brief Setup Function: ADC average mode test.
 *
 * This function initializes the ADC in averaging mode.
 *
 * \param test Current test case.
 */
static void setup_adc_average_mode_test(const struct test_case *test)
{
	enum status_code status = STATUS_ERR_IO;

	/* Skip test if ADC initialization failed */
	test_assert_true(test, adc_init_success,
			"Skipping test due to failed initialization");

	/* Disable ADC before initialization */
	adc_disable(&adc_inst);
	struct adc_config config;
	adc_get_config_defaults(&config);
	config.positive_input     = ADC_POSITIVE_INPUT_PIN2;
	config.negative_input     = ADC_NEGATIVE_INPUT_GND;
#if (SAML21)
	config.reference          = ADC_REFERENCE_INTREF;
#else
	config.reference          = ADC_REFERENCE_INT1V;
#endif
	config.clock_source       = GCLK_GENERATOR_3;
#if !(SAML21)
	config.gain_factor        = ADC_GAIN_FACTOR_1X;
#endif

	/* Re-initialize & enable ADC */
	status = adc_init(&adc_inst, ADC, &config);
	test_assert_true(test, status == STATUS_OK,
			"ADC initialization failed");
	status = adc_enable(&adc_inst);
	test_assert_true(test, status == STATUS_OK,
			"ADC enabling failed");
}
Esempio n. 2
0
void main(void)
{
	struct device *adc;
	struct nano_timer timer;
	uint32_t data[2] = {0, 0};

	DBG("ADC sample started on %s\n", ADC_DEVICE_NAME);

	adc = device_get_binding(ADC_DEVICE_NAME);
	if (!adc) {
		DBG("Cannot get adc controller\n");
		return;
	}

	nano_timer_init(&timer, data);
	adc_enable(adc);
	while (1) {
		if (adc_read(adc, &table) != DEV_OK) {
			DBG("Sampling could not proceed, an error occurred\n");
		} else {
			DBG("Sampling is done\n");
			_print_sample_in_hex(seq_buffer, BUFFER_SIZE);
		}
		nano_timer_start(&timer, SLEEPTICKS);
		nano_timer_test(&timer, TICKS_UNLIMITED);
	}
	adc_disable(adc);
}
Esempio n. 3
0
uint8_t batt_read_lvl(void)
{
		uint8_t batt_lvl;
		uint16_t adc_sample;
		volatile int i;

	adc_init();
	
//	for (i = 0; i<=1000; i++); //delay
	
	adc_enable_channel(0x07);
	
	adc_sample = adc_get_sample();
	
	adc_disable();
			  
	//calculate remaining battery life 
	if (adc_sample > 0x308)
		batt_lvl = 100;
	else if (adc_sample <= 0x308 && adc_sample > 0x2D6) 
		batt_lvl = 28 + (uint8_t)(((float)((float)(adc_sample - 0x2D6)/(float)(0x308 - 0x2D6))) * 72) ;
	else if (adc_sample <= 0x2D6 && adc_sample > 0x26C) 
		batt_lvl = 4 + (uint8_t)(((float)((float)(adc_sample - 0x26C)/(float)(0x2D6 - 0x26C))) * 24) ;
	else if (adc_sample <= 0x26C && adc_sample > 0x205) 
		batt_lvl = (uint8_t)(((float)((float)(adc_sample - 0x205)/(float)(0x26C - 0x205))) * 4) ;
	else 
		batt_lvl = 0;
		
	return batt_lvl;	
}
Esempio n. 4
0
/**
 * \brief Callback function for ADC interrupts
 *
 * \param adc Pointer to ADC module.
 * \param channel ADC channel number.
 * \param result Conversion result from ADC channel.
 */
static void adc_handler(ADC_t *adc, uint8_t channel, adc_result_t result)
{
	switch (adc_conv[adc_mux_index].in) {
		case EXT_VIN_ADC_INPUT:
			ext_voltage=result;
			adc_mux_index++;

			//start new measurement
			adc_disable(&EXT_VIN_ADC_MODULE);
			adc_set_conversion_parameters(&adc_conf
					,ADC_SIGN_OFF
					,ADC_RES_12
					,adc_conv[adc_mux_index].ref);
			adc_write_configuration(
					&POTENTIOMETER_ADC_MODULE
					, &adc_conf);
			adc_enable(&POTENTIOMETER_ADC_MODULE);
			adcch_set_input(&adcch_conf
					,adc_conv[adc_mux_index].in
					,ADCCH_NEG_NONE,1);
			adcch_write_configuration(
					&POTENTIOMETER_ADC_MODULE
					, ADC_CH0, &adcch_conf);
			adc_start_conversion(&POTENTIOMETER_ADC_MODULE
					, ADC_CH0);
			break;
		case POTENTIOMETER_ADC_INPUT:
			potentiometer=result;
		break;

		default:
		break;
	}
}
Esempio n. 5
0
/**
 * @brief Perform a single synchronous software triggered conversion on a
 * channel.
 * @param dev ADC device to use for reading.
 * @param channel channel to convert
 * @return conversion result
 */
uint16_t adc_read(const adc_dev *dev, uint8_t channel)
{
  adc_data_ready = false;
  
#ifdef INTERNAL_VREF
  uint16_t vrefint = vref_read();
  float vref_V = 1.204 * 4095.0 / (float)vrefint;
#endif

  adc_disable(dev);
 
  /* ADC regular channel14 configuration */
  ADC_RegularChannelConfig(dev->ADCx, channel, 1, ADC_SampleTime_28Cycles5);
  adc_enable(dev);
      
  /* Start ADC Software Conversion */
  ADC_SoftwareStartConvCmd(dev->ADCx, ENABLE);
 
  /* Wait until ADC Channel end of conversion */  
  while (ADC_GetFlagStatus(dev->ADCx, ADC_FLAG_EOC) == RESET);
  
  /* Read ADC conversion result */
  uint16_t value = ADC_GetConversionValue(dev->ADCx);

#ifdef INTERNAL_VREF
  value = (uint16_t)((float)value * vref_V / 3.3);
#endif

  return value;
}
Esempio n. 6
0
/**
 ****************************************************************************************
 * @brief Gets ADC sample from VBAT1V or VBAT3V power supplies.
 *
 * @param[in] sample_vbat1v :true = sample VBAT1V, false = sample VBAT3V
 *
 * @return ADC VBAT1V or VBAT3V sample
 ****************************************************************************************
 */
uint32_t adc_get_vbat_sample(bool sample_vbat1v)
{
    uint32_t adc_sample;
    
    adc_init(GP_ADC_SE, GP_ADC_SIGN);

    if (sample_vbat1v)
        adc_enable_channel(ADC_CHANNEL_VBAT1V);
    else
        adc_enable_channel(ADC_CHANNEL_VBAT3V);

    adc_sample = adc_get_sample();

    adc_init(GP_ADC_SE, 0);

    if (sample_vbat1v)
        adc_enable_channel(ADC_CHANNEL_VBAT1V);
    else
        adc_enable_channel(ADC_CHANNEL_VBAT3V);

    adc_sample += adc_get_sample();

    adc_disable();

    return adc_sample;
}
Esempio n. 7
0
void ui_powerdown(void)
{
	backlight_stop_pwm();
	backlight_off();
	adc_disable(&LIGHT_SENSOR_ADC_MODULE);
	led_power_off();
}
Esempio n. 8
0
void main(void)
{
  struct nano_timer timer;
	uint32_t data[2] = {0, 0};

  struct device *tmp36;

  PRINT("Zephyr WebBluetooth demo\n");

  if ((tmp36 = device_get_binding(ADC_DEVICE_NAME)) == NULL) {
      printk("device_get_binding: failed for ADC\n");
      printk("Temperature (celsius): %d\n\n\n", tmp36_read());
  }

	nano_timer_init(&timer, data);
	adc_enable(tmp36);

  while (1) {
    tmp36_read();

    nano_timer_start(&timer, SLEEPTICKS);
    nano_timer_test(&timer, TICKS_UNLIMITED);
  }

  adc_disable(tmp36);
}
Esempio n. 9
0
/**
 * \brief Configure the ADC for DAC calibration
 */
static void configure_adc(void)
{
	struct adc_config adc_conf;
	struct adc_channel_config adcch_conf;

	adc_read_configuration(&CALIBRATION_ADC, &adc_conf);
	adcch_read_configuration(&CALIBRATION_ADC, ADC_CH_TO_DAC_CH0, &adcch_conf);

	adc_set_conversion_parameters(&adc_conf, ADC_SIGN_ON, ADC_RES_12, ADC_REF_VCC);
	adc_set_conversion_trigger(&adc_conf, ADC_TRIG_MANUAL, 2, 0);
	adc_set_clock_rate(&adc_conf, 62500UL);

	adcch_set_input(&adcch_conf, ADCCH_POS_PIN1, ADCCH_NEG_PIN1, 1);

	adc_write_configuration(&CALIBRATION_ADC, &adc_conf);
	adcch_write_configuration(&CALIBRATION_ADC, ADC_CH_TO_DAC_CH0, &adcch_conf);

	/* Find the offset of the ADC */
	adc_enable(&CALIBRATION_ADC);
	adc_offset = adc_get_sample_avg(ADC_CH_TO_DAC_CH0, 128);
	adc_disable(&CALIBRATION_ADC);

	/* Switch input to the DAC output pin PB3, i.e. ADC pin 11 */
	adcch_set_input(&adcch_conf, ADCCH_POS_PIN10, ADCCH_NEG_PAD_GND, 1);
	adcch_write_configuration(&CALIBRATION_ADC, ADC_CH_TO_DAC_CH0, &adcch_conf);

	adcch_set_input(&adcch_conf, ADCCH_POS_PIN11, ADCCH_NEG_PAD_GND, 1);
	adcch_write_configuration(&CALIBRATION_ADC, ADC_CH_TO_DAC_CH1, &adcch_conf);

	adc_enable(&CALIBRATION_ADC);

}
Esempio n. 10
0
static void acc_get_value (
   volatile avr32_adc_t * adc
,  xyz_t* val ) {

  // get value for adc channel
  adc_enable(adc,  ADC_CHANNEL_X);
  adc_start(adc) ;
  val->x = ( adc_get_value(adc, ADC_CHANNEL_X) >> ACC_SHIFT ) ;
  adc_disable(adc, ADC_CHANNEL_X);

  adc_enable(adc,  ADC_CHANNEL_Y);
  adc_start(adc) ;
  val->y = ( adc_get_value(adc, ADC_CHANNEL_Y) >> ACC_SHIFT ) ;
  adc_disable(adc, ADC_CHANNEL_Y);

  adc_enable(adc,  ADC_CHANNEL_Z);
  adc_start(adc) ;
  val->z = ( adc_get_value(adc, ADC_CHANNEL_Z) >> ACC_SHIFT ) ;
  adc_disable(adc, ADC_CHANNEL_Z);
}
Esempio n. 11
0
/**
 * \internal
 * \brief Test averaging conversion in 12-bit mode using the DAC
 *
 * These values are then measured using the ADC on the pins that are connected
 * to the DAC channel, and the results are compared and checked to see if they
 * are within the acceptable average of values that passes the test.
 *
 * \param test Current test case.
 */
static void run_averaging_conversion_test(
		const struct test_case *test)
{
	int16_t volt_output;
	int16_t volt_min, volt_max, volt_input;

	/* ADC module configuration structure */
	struct adc_config adc_conf;
	/* ADC channel configuration structure */
	struct adc_channel_config adcch_conf;

	adc_disable(&ADCA);

	/* Change resolution parameter to accept averaging */
	adc_read_configuration(&ADCA, &adc_conf);
	adc_set_conversion_parameters(&adc_conf, ADC_SIGN_ON, ADC_RES_MT12,
			ADC_REF_VCC);
	adc_write_configuration(&ADCA, &adc_conf);

	/* Enable averaging */
	adcch_read_configuration(&ADCA, ADC_CH0, &adcch_conf);
	adcch_enable_averaging(&adcch_conf, ADC_SAMPNUM_1024X);
	adcch_write_configuration(&ADCA, ADC_CH0, &adcch_conf);

	adc_enable(&ADCA);
	adc_wait_for_interrupt_flag(&ADCA, ADC_CH0);

	/* Check values */
	for (volt_output = -CONV_MAX_VOLTAGE;
			volt_output <= CONV_MAX_VOLTAGE;
			volt_output += CONV_VOLTAGE_STEP) {
		main_dac_output(volt_output);
		/* first capture */
		volt_input = main_adc_input();
		volt_min = volt_max = volt_input;
		/* several capture */
		for (uint8_t i = 0; i < 5; i++) {
			volt_input = main_adc_input();
			if (volt_min > volt_input) {
				volt_min = volt_input;
			}

			if (volt_max < volt_input) {
				volt_max = volt_input;
			}
		}

		test_assert_true(test,
				(volt_max - volt_min) < CONF_TEST_ACCEPT_DELTA_AVERAGING,
				"ADC result is not in acceptable stable range (Min %dmV, Max %dmV)",
				volt_min, volt_max);
	}
}
Esempio n. 12
0
/**
 * \internal
 * \brief Setup Function: ADC window mode test.
 *
 * This function initializes the ADC in window mode.
 * Upper and lower threshold values are provided.
 * It also registers & enables callback for window detection.
 *
 * \param test Current test case.
 */
static void setup_adc_window_mode_test(const struct test_case *test)
{
	enum status_code status = STATUS_ERR_IO;

	interrupt_flag = false;

	/* Set 0.5V DAC output */
	dac_chan_write(&dac_inst, DAC_CHANNEL_0, DAC_VAL_HALF_VOLT);
	delay_ms(1);

	/* Skip test if ADC initialization failed */
	test_assert_true(test, adc_init_success,
			"Skipping test due to failed initialization");

	/* Disable ADC before initialization */
	adc_disable(&adc_inst);
	struct adc_config config;
	adc_get_config_defaults(&config);
	config.positive_input = ADC_POSITIVE_INPUT_PIN2;
	config.negative_input = ADC_NEGATIVE_INPUT_GND;
#if (SAML21)
	config.reference      = ADC_REFERENCE_INTREF;
	config.clock_prescaler = ADC_CLOCK_PRESCALER_DIV16;
#else
	config.reference      = ADC_REFERENCE_INT1V;
#endif
	config.clock_source   = GCLK_GENERATOR_3;
#if !(SAML21)
	config.gain_factor    = ADC_GAIN_FACTOR_1X;
#endif
	config.resolution     = ADC_RESOLUTION_12BIT;
	config.freerunning    = true;
	config.window.window_mode = ADC_WINDOW_MODE_BETWEEN_INVERTED;
	config.window.window_lower_value = (ADC_VAL_DAC_HALF_OUTPUT - ADC_OFFSET);
	config.window.window_upper_value = (ADC_VAL_DAC_HALF_OUTPUT + ADC_OFFSET);

	/* Re-initialize & enable ADC */
	status = adc_init(&adc_inst, ADC, &config);
	test_assert_true(test, status == STATUS_OK,
			"ADC initialization failed");
	status = adc_enable(&adc_inst);
	test_assert_true(test, status == STATUS_OK,
			"ADC enabling failed");

	/* Register and enable window mode callback */
	adc_register_callback(&adc_inst, adc_user_callback,
			ADC_CALLBACK_WINDOW);
	adc_enable_callback(&adc_inst, ADC_CALLBACK_WINDOW);

	/* Start ADC conversion */
	adc_start_conversion(&adc_inst);
}
Esempio n. 13
0
/**
 * \brief Timer Counter Overflow interrupt callback function
 *
 * This function is called when an overflow interrupt has occurred on
 * TCC0.
 */
static void tcc0_ovf_interrupt_callback(void)
{
	adc_mux_index=0;
	adc_disable(&EXT_VIN_ADC_MODULE);
	adc_set_conversion_parameters(&adc_conf, ADC_SIGN_OFF, ADC_RES_12
			,adc_conv[adc_mux_index].ref);
	adc_write_configuration(&EXT_VIN_ADC_MODULE, &adc_conf);
	adc_enable(&EXT_VIN_ADC_MODULE);
	adcch_set_input(&adcch_conf, adc_conv[adc_mux_index].in
			, ADCCH_NEG_NONE,1);
	adcch_write_configuration(&EXT_VIN_ADC_MODULE, ADC_CH0, &adcch_conf);
	adc_start_conversion(&EXT_VIN_ADC_MODULE, ADC_CH0);
}
Esempio n. 14
0
uint8_t battery_get_lvl(uint8_t batt_type)
{
	uint8_t batt_lvl;
	uint16_t adc_sample;
	volatile int i;

	adc_init(GP_ADC_SE, GP_ADC_SIGN);
	
#if JPLUS_BAT_TYPE
	adc_enable_channel(ADC_CHANNEL_P01);//ADC_CHANNEL_VBAT3V
#else	
	adc_enable_channel(ADC_CHANNEL_VBAT3V);//ADC_CHANNEL_P00
#endif
	
  adc_sample = adc_get_sample();

	adc_init(GP_ADC_SE, 0);
  
#if JPLUS_BAT_TYPE
	adc_enable_channel(ADC_CHANNEL_P01);//ADC_CHANNEL_VBAT3V
#else	
	adc_enable_channel(ADC_CHANNEL_VBAT3V);//ADC_CHANNEL_P00
#endif

	adc_sample += adc_get_sample();
	
	adc_disable();
	
    adc_sample >>= 4;
    adc_sample <<= 4;
    
    if(old_batt_level == 0)
        old_batt_level = 0xFF;
    
    if(batt_lvl > old_batt_level)
        batt_lvl = old_batt_level;
    
    switch (batt_type)
    {
        case BATT_CR2032:
            batt_lvl = batt_cal_cr2032(adc_sample);
            break;
				case BATT_JPLUS:		//gsx,custom.
            batt_lvl = batt_cal_jplus(adc_sample);
            break;
        default:
            batt_lvl = 0;
    }   
    
	return batt_lvl;
}
Esempio n. 15
0
/**
 * @brief disable all subsystem functions.  Will turn off
 *  the DAC, ADC, PWM, and counter mode subsystem modes if
 *  any of them are active. 
 * 
 */
void disable_all(void)
{
	// disable TLV563x SPI DAC
	tlv563x_disable();
	
	// disable PWM
	pwm_disable();
	
	// disable ADC
	adc_disable();
	
	// disable counter
	counter_disable();
}
Esempio n. 16
0
OSStatus platform_adc_deinit( const platform_adc_t* adc )
{
  OSStatus    err = kNoErr;
  
  platform_mcu_powersave_disable();
  
  require_action_quiet( adc != NULL, exit, err = kParamErr);
  
  adc_disable();
  
  initialized = false;
  
exit:
  platform_mcu_powersave_enable();
  return err;  
}
Esempio n. 17
0
/**
 * \brief Test interrupt is getting triggered in various Sleep mode.
 *
 * This function put the device in Idle and Power Save sleep mode and check
 * whether the ADC conversion complete interrupt is executed only in Idle sleep
 * mode.
 * The device will wakeup from power save mode when Timer/Counter2 overflow
 * occur.
 *
 * \param test Current test case.
 */
static void run_sleep_trigger_test(const struct test_case *test)
{
    /* Disable Global interrupt */
    cpu_irq_disable();
    /* Initialize the lock counts */
    sleepmgr_init();
    /* Initialize the ADC */
    adc_initialisation();
    /* Initialize the Timer/Counter2 */
    timer2_initialisation();
    /* Lock Idle Sleep mode */
    sleepmgr_lock_mode(SLEEPMGR_IDLE);
    /* Clear Timer/Counter2 Register */
    TCNT2 = 0;
    /* Wait for TCNT2 register to get updated */
    while (ASSR & (1 << TCN2UB)) {
    }
    /* Start ADC Conversion */
    adc_start_conversion();
    /* Enable Global interrupt */
    cpu_irq_enable();
    /* Go to sleep in the deepest allowed mode */
    sleepmgr_enter_sleep();
    /* Unlock Idle Sleep mode */
    sleepmgr_unlock_mode(SLEEPMGR_IDLE);
    /* Lock Power Save mode */
    sleepmgr_lock_mode(SLEEPMGR_PSAVE);
    /* Clear Timer/Counter2 Register */
    TCNT2 = 0;
    /* Wait for TCNT2 register to get updated */
    while (ASSR & (1 << TCN2UB)) {
    }
    /* Start ADC Conversion */
    adc_start_conversion();
    /* Go to sleep in the deepest allowed mode */
    sleepmgr_enter_sleep();
    /* Disable ADC */
    adc_disable();
    /* Unlock Power Save mode */
    sleepmgr_unlock_mode(SLEEPMGR_PSAVE);

    /* Disable Global interrupt */
    cpu_irq_disable();

    test_assert_true(test, trigger_count == 2,
                     "ADC interrupt trigger failed.");
}
Esempio n. 18
0
static int poti_configure(int type, int c) 
{
	switch (type) {
	case SENSORS_HW_INIT:
		if (c) 
		{
			adc_disable();
		} 
		else 
		{
			adc_enable();
			adc_init();
			adc_setup_chan( ADC_PIN );
		}
		return 1;
	}
	return 0;
}
Esempio n. 19
0
/**
 * \brief Function for calibration the DAC using the internal ADC
 *
 * This function will calibrate the DAC using the internal ADC, please be aware
 * that signals will be outputted on the DAC pins.
 *
 * When calibrating always start with the offset then do gain calibration.
 *
 */
static void dac_calibrate(void)
{
	/* Configure the DAC output pins */
	configure_pins();

	/* Configure the DAC for this calibration sequence */
	configure_dac();

	/* Configure the ADC for this calibration sequence */
	configure_adc();

	/* Calibrate offset and gain for DAC CH0 */
	dac_calibrate_offset(DAC_CH0);
	dac_calibrate_gain(DAC_CH0);

	/* Calibrate offset and gain for DAC CH1 */
	dac_calibrate_offset(DAC_CH1);
	dac_calibrate_gain(DAC_CH1);

	adc_disable(&CALIBRATION_ADC);
}
Esempio n. 20
0
// Beep and blink every once in a while if battery is low
static void low_battery_check(void)
{
  if (--batt_check_counter == 0) {
    adc_init();
    uint8_t voltage = read_voltage();
    adc_disable();
    set_extra_url_data(voltage);
    if (is_battery_low(voltage)) {
      beep_n_times_and_wait(4);
      // The battery_dead threshold should be set high enough to avoid dropping
      // the AVR into BOD when the RF field is on, because the processor may
      // stop with the field on, which drains the battery rapidly.
      if (is_battery_dead(voltage)) {
        // Turn off the NFC module to minimize power consumption
        module_power_down();
        wdt_disable();
        sleep_forever();
      }
    }
    batt_check_counter = SECS2COUNT(CHECK_BATT_EVERY_NSECS);
  }
}
Esempio n. 21
0
/**
 * \brief Enables averaging
 */
static void main_adc_averaging(void)
{
	/* ADC module configuration structure */
	struct adc_config adc_conf;
	/* ADC channel configuration structure */
	struct adc_channel_config adcch_conf;

	adc_disable(&ADCA);

	/* Change resolution parameter to accept averaging */
	adc_read_configuration(&ADCA, &adc_conf);
	adc_set_conversion_parameters(&adc_conf, ADC_SIGN_ON, ADC_RES_MT12,
			ADC_REF_VCC);
	adc_write_configuration(&ADCA, &adc_conf);

	/* Enable averaging */
	adcch_read_configuration(&ADCA, ADC_CH0, &adcch_conf);
	adcch_enable_averaging(&adcch_conf, ADC_SAMPNUM_1024X);
	adcch_write_configuration(&ADCA, ADC_CH0, &adcch_conf);

	adc_enable(&ADCA);
	adc_wait_for_interrupt_flag(&ADCA, ADC_CH0);
}
/**
 * \brief Disables over-sampling
 */
static void main_adc_oversampling_stop(void)
{
    /* ADC module configuration structure */
    struct adc_config adc_conf;
    /* ADC channel configuration structure */
    struct adc_channel_config adcch_conf;

    adc_disable(&ADCA);

    /* Set default resolution parameter */
    adc_read_configuration(&ADCA, &adc_conf);
    adc_set_conversion_parameters(&adc_conf, ADC_SIGN_OFF, ADC_RES_12,
                                  ADC_REF_VCCDIV2);
    adc_write_configuration(&ADCA, &adc_conf);

    /* Disable over-sampling */
    adcch_read_configuration(&ADCA, ADC_CH0, &adcch_conf);
    adcch_disable_oversampling(&adcch_conf);
    adcch_write_configuration(&ADCA, ADC_CH0, &adcch_conf);

    adc_enable(&ADCA);
    printf("\n\r* ADC over-sampling disabled\n\r");
}
/**
 * \brief Enables over-sampling
 */
static void main_adc_oversampling_start(void)
{
    /* ADC module configuration structure */
    struct adc_config adc_conf;
    /* ADC channel configuration structure */
    struct adc_channel_config adcch_conf;

    adc_disable(&ADCA);

    /* Change resolution parameter to accept over-sampling */
    adc_read_configuration(&ADCA, &adc_conf);
    adc_set_conversion_parameters(&adc_conf, ADC_SIGN_OFF, ADC_RES_MT12,
                                  ADC_REF_VCCDIV2);
    adc_write_configuration(&ADCA, &adc_conf);

    /* Enable over-sampling */
    adcch_read_configuration(&ADCA, ADC_CH0, &adcch_conf);
    adcch_enable_oversampling(&adcch_conf, ADC_SAMPNUM_1024X, 16);
    adcch_write_configuration(&ADCA, ADC_CH0, &adcch_conf);

    adc_enable(&ADCA);
    printf("\n\r* ADC over-sampling enabled\n\r");
}
Esempio n. 24
0
File: s_light.c Progetto: avrxml/asf
/*!
 *  \brief Get the current light sensor value.
 *
 *  \param buf char buffer in which the light sensor value is stored.
 *  \param result returns the light sensor value.
 *
 *  \return true upon success, false if error.
 */
bool b_light_get_value( char* buf, U32* result )
{
   int i_current_val;


   /* enable channel for sensor */
   adc_enable( adc, ADC_LIGHT_CHANNEL );
   /* start conversion */
   adc_start( adc );
   /* get value for sensor */
   i_current_val = (
#ifdef EVK1100_REVA
                     ADC_MAX_VALUE -
#endif
                     adc_get_value( adc, ADC_LIGHT_CHANNEL )) * 100 / ADC_MAX_VALUE;
   /* Disable channel for sensor */
   adc_disable( adc, ADC_LIGHT_CHANNEL );

   sprintf( buf, "%d%%\r\n", i_current_val);

   *result= i_current_val;
   return true;
}
Esempio n. 25
0
/**
 * \internal
 * \brief Measure differential input MUX combinations on channel
 *
 * Measures a set of input MUX combinations on a single channel, using averaging
 * of the number of samples specified with \ref NUM_AVERAGE_SAMPLES.
 *
 * \pre This function does not configure the ADC, only the ADC channel, and
 * therefore the specified ADC needs to be configured before this function
 * is run.
 *
 * \param adc Pointer to ADC to measure with.
 * \param ch_mask Mask for channel to measure with.
 * \param mux_pos_inputs Pointer to array of positive input MUX settings.
 * \param mux_neg_inputs Pointer to array of negative input MUX settings.
 * \param num_inputs Number of input MUX setting pairs.
 * \param results Pointer to array to store results in.
 * \param gain Gain to use for all measurements.
 *
 * \note The array which \e results points to must have at least \e num_inputs
 * elements.
 */
static void differential_signed_average(ADC_t *adc, uint8_t ch_mask,
		const uint8_t *mux_pos_inputs, const uint8_t *mux_neg_inputs,
		uint8_t num_inputs, int16_t *results, uint8_t gain)
{
	struct adc_channel_config adcch_conf;
	uint8_t input;
	uint8_t i;
	int32_t sum;

	memset(&adcch_conf, 0, sizeof(struct adc_channel_config));

	// Common configuration
	adcch_set_interrupt_mode(&adcch_conf, ADCCH_MODE_COMPLETE);
	adcch_disable_interrupt(&adcch_conf);

	for (input = 0; input < num_inputs; input++) {
		adcch_set_input(&adcch_conf, mux_pos_inputs[input],
				mux_neg_inputs[input], gain);
		adcch_write_configuration(adc, ch_mask, &adcch_conf);

		// Enable and do dummy conversion
		adc_enable(adc);
		adc_start_conversion(adc, ch_mask);
		adc_wait_for_interrupt_flag(adc, ch_mask);

		// Read an average
		sum = 0;
		for (i = 0; i < NUM_AVERAGE_SAMPLES; i++) {
			adc_start_conversion(adc, ch_mask);
			adc_wait_for_interrupt_flag(adc, ch_mask);
			sum += (int16_t)adc_get_result(adc, ch_mask);
		}
		adc_disable(adc);

		results[input] = sum / NUM_AVERAGE_SAMPLES;
	}
}
Esempio n. 26
0
static void adc_test(void)
{
	int result = TC_FAIL;
	struct device *adc;
	unsigned int loops = 10;
	unsigned int bufi0 = ~0, bufi;

	adc = device_get_binding(ADC_DEVICE_NAME);
	zassert_not_null(adc, "Cannot get adc controller\n");

	adc_enable(adc);
	while (loops--) {
		bufi = loops & 0x1;
		/* .buffer should be void * ... */
		sample.buffer = (void *) seq_buffer[bufi];
		result = adc_read(adc, &table);
		zassert_equal(result, 0, "Sampling could not proceed, "
			"an error occurred\n");
		printk("loop %u: sampling done to buffer #%u\n", loops, bufi);
		_print_sample_in_hex(seq_buffer[bufi], BUFFER_SIZE);
		if (bufi0 != ~0) {
			unsigned int cnt;
			long delta;

			for (cnt = 0; cnt < BUFFER_SIZE; cnt++) {
				delta = _abs((long)seq_buffer[bufi][cnt]
					     - seq_buffer[bufi0][cnt]);
				printk("loop %u delta %u = %ld\n",
				       loops, cnt, delta);
			}
		}
		k_sleep(SLEEPTIME);
		bufi0 = bufi;
	}
	adc_disable(adc);
}
Esempio n. 27
0
/*!
 *  \brief Get the current temperature value.
 *
 *  \param pxLog a Log structure.
 *
 *  \return true upon success, false if error.
 */
bool b_temperature_get_value( xLogDef *pxLog )
{
   int i_current_val, value, index = 0;


   /* enable channel for sensor */
   adc_enable( adc, ADC_TEMPERATURE_CHANNEL );
   // start conversion
   adc_start( adc );
   // get value for sensor
   value = adc_get_value( adc, ADC_TEMPERATURE_CHANNEL );
   /* Disable channel for sensor */
   adc_disable( adc, ADC_TEMPERATURE_CHANNEL );

   if(value > temperature_code[0])
   {
        i_current_val = -20;
   }
   else
   {
      while(temperature_code[index++] > value);
      i_current_val = (index - 1 - 20);
   }

   // Alloc memory for the log string.
   pxLog->pcStringLog = pvPortMalloc( 12*sizeof( char ) );
   if( NULL == pxLog->pcStringLog )
   {
      return( false );
   }
   pxLog->pfFreeStringLog = vPortFree; // Because pvPortMalloc() was used to
                                       // alloc the log string.

   // Build the log string.
   if( i_current_val <= l_temp_min )
   {
      sprintf( pxLog->pcStringLog, "%3dC | min", i_current_val );
      // if alarms have to be checked and no alarm for min was pending
      if (( b_temp_alarm == pdTRUE ) && ( b_temp_alarm_min == pdFALSE ))
      {
        // alarm has been taken into account,
        // don't reenter this test before leaving min area
        b_temp_alarm_min = pdTRUE;
        // allow alarm if max is reached
        b_temp_alarm_max = pdFALSE;
        // post alarm to SMTP task
        v_SMTP_Post("Min Temp Alarm", NULL);
      }
   }
   else if( i_current_val >= l_temp_max )
   {
      sprintf( pxLog->pcStringLog, "%3dC | max", i_current_val );
      // if alarms have to be checked and no alarm for max was pending
      if (( b_temp_alarm == pdTRUE ) && ( b_temp_alarm_max == pdFALSE ))
      {
        // alarm has been taken into account,
        // don't reenter this test before leaving max area
        b_temp_alarm_max = pdTRUE;
        // allow alarm if min is reached
        b_temp_alarm_min = pdFALSE;
        // post alarm to SMTP task
        v_SMTP_Post("Max Temp Alarm", NULL);
      }
   }
   else
   {
      sprintf( pxLog->pcStringLog, "%3dC", i_current_val );
      // if alarms have to be checked
      if ( b_temp_alarm == pdTRUE )
      {
        // no alarm is pending
        b_temp_alarm_max = pdFALSE;
        b_temp_alarm_min = pdFALSE;
      }
   }

   return( true );
}
Esempio n. 28
0
int main(void)
{
  disable_unused_circuits();
  _delay_ms(50);

#ifdef HAS_CHARGER
  reset_on_power_change();
#endif /* HAS_CHARGER */

  /* Shut off right away if battery is very low. Do not power on NFC module */
  adc_init();
  (void)read_voltage();
  // Read one more time in case first reading is corrupted
  uint8_t voltage = read_voltage();
  adc_disable();
  if (is_battery_dead(voltage)) {
    //beep_n_times_and_wait(4);
    //sleep_forever();
  }

  lcd_init();
  print_idle();

  // Initialize and self-test
  module_power_up();
  led_on();
#ifdef WITH_TARGET
  // We may have come out of target power down mode
  //(void)pasori_wake_up();
#endif

  while (!rcs956_reset()) {};

  if (!eeprom_has_station_info()) {
    beep_n_times_and_wait(3);
    sleep_forever();
  }
  if (is_on_external_power()) {
    play_song_and_wait(melody_start_up_external,
                       sizeof(melody_start_up_external) / sizeof(struct note));
  } else {
    play_song_and_wait(melody_start_up_battery,
                       sizeof(melody_start_up_battery) / sizeof(struct note));
  }
  led_off();
  initiator_set_defaults();
  watchdog_start();

  for (;;) {
    watchdog_reset();
    // initiator exits after polling times out (false) or URL is pushed (true)
    if (initiator(PUSH_URL_LABEL)) {
      lcd_puts(0, "PUSH SLEEP");
      play_url_push_success_song_and_wait();
    }
#ifdef WITH_TARGET
    uint8_t loop;
    // Loop here to not skip watchdog timer
    for (loop = 0; loop < TARGET_MODE_RETRY; loop++) {
      watchdog_reset();
      (void)rcs956_reset();
      enum target_res res = target(PUSH_URL_LABEL_ENGLISH);
      if (res == TGT_COMPLETE) {
        led_off();
        play_url_push_success_song_and_wait();
        break;
      } else if (res == TGT_TIMEOUT || res == TGT_ERROR) {
        break;
      } // loop on TGT_RETRY
    }
    led_off();
    (void)rcs956_reset();
    low_battery_check();
#else /* !WITH_TARGET */
    // Check battery level while RF field is still on
    low_battery_check();
    sleep_after_timeout();
#endif /* WITH_TARGET */

    // Reconfigure Felica module if communication timed out,
    // e.g. due to temporary disconnect.
    if (protocol_errno == TIMEOUT) {
      initiator_set_defaults();
      eeprom_increment_usart_fail();
    }
    protocol_errno = SUCCESS;
  }

  /* NOT REACHABLE */
  return 0;
}
Esempio n. 29
0
/*---------------------------------------------------------------------------*/
static
PT_THREAD(ajax_call(struct httpd_state *s, char *ptr))
{
  static struct timer t;
  static int iter;
  static char buf[128];
  static uint8_t numprinted;
  
  PSOCK_BEGIN(&s->sout);
/*TODO:pick up time from ? parameter */
  timer_set(&t, 2*CLOCK_SECOND);
  iter = 0;
  
  while(1) {
  	iter++;

#if CONTIKI_TARGET_SKY
    SENSORS_ACTIVATE(sht11_sensor);
    SENSORS_ACTIVATE(light_sensor);
    numprinted = snprintf(buf, sizeof(buf),
	     "t(%d);h(%d);l1(%d);l2(%d);",
	     sht11_sensor.value(SHT11_SENSOR_TEMP),
	     sht11_sensor.value(SHT11_SENSOR_HUMIDITY),
         light_sensor.value(LIGHT_SENSOR_PHOTOSYNTHETIC),
         light_sensor.value(LIGHT_SENSOR_TOTAL_SOLAR));
    SENSORS_DEACTIVATE(sht11_sensor);
    SENSORS_DEACTIVATE(light_sensor);

#elif CONTIKI_TARGET_MB851
  SENSORS_ACTIVATE(acc_sensor);    
  numprinted = snprintf(buf, sizeof(buf),"t(%d);ax(%d);ay(%d);az(%d);",
	     temperature_sensor.value(0),
	     acc_sensor.value(ACC_X_AXIS),
	     acc_sensor.value(ACC_Y_AXIS),
	     acc_sensor.value(ACC_Z_AXIS));   
  SENSORS_DEACTIVATE(acc_sensor);

#elif CONTIKI_TARGET_REDBEE_ECONOTAG
{	uint8_t c;
	adc_reading[8]=0;
	adc_init();
	while (adc_reading[8]==0) adc_service();
    adc_disable();
    numprinted = snprintf(buf, sizeof(buf),"b(%u);adc(%u,%u,%u,%u,%u,%u,%u,%u);",
        1200*0xfff/adc_reading[8],adc_reading[0],adc_reading[1],adc_reading[2],adc_reading[3],adc_reading[4],adc_reading[5],adc_reading[6],adc_reading[7]);
}
		
#elif CONTIKI_TARGET_MINIMAL_NET
static uint16_t c0=0x3ff,c1=0x3ff,c2=0x3ff,c3=0x3ff,c4=0x3ff,c5=0x3ff,c6=0x3ff,c7=0x3ff;
    numprinted = snprintf(buf, sizeof(buf), "t(%d);b(%u);v(%u);",273+(rand()&0x3f),3300-iter/10,iter);
	numprinted += snprintf(buf+numprinted, sizeof(buf)-numprinted,"adc(%u,%u,%u,%u,%u,%u,%u,%u);",c0,c1,c2,c3,c4,c5,c6,c7);
	c0+=(rand()&0xf)-8;
	c1+=(rand()&0xf)-8;
	c2+=(rand()&0xf)-7;
	c3+=(rand()&0x1f)-15;
	c4+=(rand()&0x3)-1;
	c5+=(rand()&0xf)-8;
	c6+=(rand()&0xf)-8;
	c7+=(rand()&0xf)-8;
  if (iter==1) {
    static const char httpd_cgi_ajax11[] HTTPD_STRING_ATTR = "wt('Minimal-net ";
	static const char httpd_cgi_ajax12[] HTTPD_STRING_ATTR = "');";
    numprinted += httpd_snprintf(buf+numprinted, sizeof(buf)-numprinted,httpd_cgi_ajax11);
#if WEBSERVER_CONF_PRINTADDR
/* Note address table is filled from the end down */
{int i;
    for (i=0; i<UIP_DS6_ADDR_NB;i++) {
      if (uip_ds6_if.addr_list[i].isused) {
	    numprinted += httpd_cgi_sprint_ip6(uip_ds6_if.addr_list[i].ipaddr, buf + numprinted);
	    break;
	  }
    }
}
#endif
	numprinted += httpd_snprintf(buf+numprinted, sizeof(buf)-numprinted,httpd_cgi_ajax12);
  }

#elif CONTIKI_TARGET_AVR_ATMEGA128RFA1
{ uint8_t i;int16_t tmp,bat;
  BATMON = 16; //give BATMON time to stabilize at highest range and lowest voltage
/* Measure internal temperature sensor, see atmega128rfa1 datasheet */
/* This code disabled by default for safety.
   Selecting an internal reference will short it to anything connected to the AREF pin
 */
#if 1
  ADCSRB|=1<<MUX5;          //this bit buffered till ADMUX written to!
  ADMUX =0xc9;              // Select internal 1.6 volt ref, temperature sensor ADC channel
  ADCSRA=0x85;              //Enable ADC, not free running, interrupt disabled, clock divider 32 (250 KHz@ 8 MHz)
//  while ((ADCSRB&(1<<AVDDOK))==0);  //wait for AVDD ok
//  while ((ADCSRB&(1<<REFOK))==0);  //wait for ref ok 
  ADCSRA|=1<<ADSC;          //Start throwaway conversion
  while (ADCSRA&(1<<ADSC)); //Wait till done
  ADCSRA|=1<<ADSC;          //Start another conversion
  while (ADCSRA&(1<<ADSC)); //Wait till done
  tmp=ADC;                  //Read adc
  tmp=11*tmp-2728+(tmp>>2); //Convert to celcius*10 (should be 11.3*h, approximate with 11.25*h)
  ADCSRA=0;                 //disable ADC
  ADMUX=0;                  //turn off internal vref      
#endif
/* Bandgap can't be measured against supply voltage in this chip. */
/* Use BATMON register instead */
  for ( i=16; i<31; i++) {
    BATMON = i;
    if ((BATMON&(1<<BATMON_OK))==0) break;
  }
  bat=2550-75*16-75+75*i;  //-75 to take the floor of the 75 mv transition window
  static const char httpd_cgi_ajax10[] HTTPD_STRING_ATTR ="t(%u),b(%u);adc(%d,%d,%u,%u,%u,%u,%u,%lu);";
  numprinted = httpd_snprintf(buf, sizeof(buf),httpd_cgi_ajax10,tmp,bat,iter,tmp,bat,sleepcount,OCR2A,0,clock_time(),clock_seconds());
  if (iter==1) {
    static const char httpd_cgi_ajax11[] HTTPD_STRING_ATTR = "wt('128rfa1 [";
	static const char httpd_cgi_ajax12[] HTTPD_STRING_ATTR = "]');";
    numprinted += httpd_snprintf(buf+numprinted, sizeof(buf)-numprinted,httpd_cgi_ajax11);
#if WEBSERVER_CONF_PRINTADDR
/* Note address table is filled from the end down */
{int i;
    for (i=0; i<UIP_DS6_ADDR_NB;i++) {
      if (uip_ds6_if.addr_list[i].isused) {
	    numprinted += httpd_cgi_sprint_ip6(uip_ds6_if.addr_list[i].ipaddr, buf + numprinted);
	    break;
	  }
    }
}
#endif
	numprinted += httpd_snprintf(buf+numprinted, sizeof(buf)-numprinted,httpd_cgi_ajax12);
  }
}
#elif CONTIKI_TARGET_AVR_RAVEN
{ int16_t tmp,bat;
#if 1
/* Usual way to get AVR supply voltage, measure 1.1v bandgap using Vcc as reference.
 * This connects the bandgap to the AREF pin, so enable only if there is no external AREF!
 * A capacitor may be connected to this pin to reduce reference noise.
 */
  ADMUX =0x5E;              //Select AVCC as reference, measure 1.1 volt bandgap reference.
  ADCSRA=0x87;              //Enable ADC, not free running, interrupt disabled, clock divider  128 (62 KHz@ 8 MHz)
  ADCSRA|=1<<ADSC;          //Start throwaway conversion
  while (ADCSRA&(1<<ADSC)); //Wait till done
  ADCSRA|=1<<ADSC;          //Start another conversion
  while (ADCSRA&(1<<ADSC)); //Wait till done
//bat=1126400UL/ADC;        //Get supply voltage (factor nominally 1100*1024)
  bat=1198070UL/ADC;        //My Raven
  ADCSRA=0;                 //disable ADC
  ADMUX=0;                  //turn off internal vref
#else
  bat=3300;  
#endif
   
  tmp=420;
  
  static const char httpd_cgi_ajax10[] HTTPD_STRING_ATTR ="t(%u),b(%u);adc(%d,%d,%u,%u,%u,%u,%u,%lu);";
  numprinted = httpd_snprintf(buf, sizeof(buf),httpd_cgi_ajax10,tmp,bat,iter,tmp,bat,sleepcount,OCR2A,0,clock_time(),clock_seconds());
  if (iter<3) {
    static const char httpd_cgi_ajax11[] HTTPD_STRING_ATTR = "wt('Raven [";
	static const char httpd_cgi_ajax12[] HTTPD_STRING_ATTR = "]');";
    numprinted += httpd_snprintf(buf+numprinted, sizeof(buf)-numprinted,httpd_cgi_ajax11);
#if WEBSERVER_CONF_PRINTADDR
/* Note address table is filled from the end down */
{int i;
    for (i=0; i<UIP_DS6_ADDR_NB;i++) {
      if (uip_ds6_if.addr_list[i].isused) {
	    numprinted += httpd_cgi_sprint_ip6(uip_ds6_if.addr_list[i].ipaddr, buf + numprinted);
	    break;
	  }
    }
}
#endif
	numprinted += httpd_snprintf(buf+numprinted, sizeof(buf)-numprinted,httpd_cgi_ajax12);
  }
}

//#elif CONTIKI_TARGET_IS_SOMETHING_ELSE
#else
{
  static const char httpd_cgi_ajax10[] HTTPD_STRING_ATTR ="v(%u);";
  numprinted = httpd_snprintf(buf, sizeof(buf),httpd_cgi_ajax10,iter);
  if (iter==1) {
    static const char httpd_cgi_ajax11[] HTTPD_STRING_ATTR = "wt('Contiki Ajax ";
	static const char httpd_cgi_ajax12[] HTTPD_STRING_ATTR = "');";
    numprinted += httpd_snprintf(buf+numprinted, sizeof(buf)-numprinted,httpd_cgi_ajax11);
#if WEBSERVER_CONF_PRINTADDR
/* Note address table is filled from the end down */
{int i;
    for (i=0; i<UIP_DS6_ADDR_NB;i++) {
      if (uip_ds6_if.addr_list[i].isused) {
	    numprinted += httpd_cgi_sprint_ip6(uip_ds6_if.addr_list[i].ipaddr, buf + numprinted);
	    break;
	  }
    }
}
#endif
	numprinted += httpd_snprintf(buf+numprinted, sizeof(buf)-numprinted,httpd_cgi_ajax12);
  }
}
#endif
 
#if CONTIKIMAC_CONF_COMPOWER
#include "sys/compower.h"
{
//sl=compower_idle_activity.transmit/RTIMER_ARCH_SECOND;
//sl=compower_idle_activity.listen/RTIMER_ARCH_SECOND;
}
#endif

#if RIMESTATS_CONF_ON

#include "net/rime/rimestats.h"
    static const char httpd_cgi_ajaxr1[] HTTPD_STRING_ATTR ="rime(%lu,%lu,%lu,%lu);";
    numprinted += httpd_snprintf(buf+numprinted, sizeof(buf)-numprinted,httpd_cgi_ajaxr1,
		rimestats.tx,rimestats.rx,rimestats.lltx-rimestats.tx,rimestats.llrx-rimestats.rx);
#endif

#if ENERGEST_CONF_ON
{
#if 1
/* Send on times in percent since last update. Handle 16 bit rtimer wraparound. */
/* Javascript must convert based on platform cpu, tx, rx power, e.g. 20ma*3v3=66mW*(% on time/100) */
	static rtimer_clock_t last_send;
	rtimer_clock_t delta_time;
    static unsigned long last_cpu, last_lpm, last_listen, last_transmit;
    energest_flush();
	delta_time=RTIMER_NOW()-last_send;
	if (RTIMER_CLOCK_LT(RTIMER_NOW(),last_send)) delta_time+=RTIMER_ARCH_SECOND;
	last_send=RTIMER_NOW();
    static const char httpd_cgi_ajaxe1[] HTTPD_STRING_ATTR = "p(%lu,%lu,%lu,%lu);";	
    numprinted += httpd_snprintf(buf+numprinted, sizeof(buf)-numprinted,httpd_cgi_ajaxe1,
	    (100UL*(energest_total_time[ENERGEST_TYPE_CPU].current - last_cpu))/delta_time,
		(100UL*(energest_total_time[ENERGEST_TYPE_LPM].current - last_lpm))/delta_time,
        (100UL*(energest_total_time[ENERGEST_TYPE_TRANSMIT].current - last_transmit))/delta_time,
        (100UL*(energest_total_time[ENERGEST_TYPE_LISTEN].current - last_listen))/delta_time);
    last_cpu = energest_total_time[ENERGEST_TYPE_CPU].current;
    last_lpm = energest_total_time[ENERGEST_TYPE_LPM].current;
    last_transmit = energest_total_time[ENERGEST_TYPE_TRANSMIT].current;
    last_listen = energest_total_time[ENERGEST_TYPE_LISTEN].current;
#endif
#if 1
/* Send cumulative on times in percent*100 */
	uint16_t cpp,txp,rxp;
	uint32_t sl,clockseconds=clock_seconds();
//	energest_flush();
//	sl=((10000UL*energest_total_time[ENERGEST_TYPE_CPU].current)/RTIMER_ARCH_SECOND)/clockseconds;
    sl=energest_total_time[ENERGEST_TYPE_CPU].current/RTIMER_ARCH_SECOND;
    cpp=(10000UL*sl)/clockseconds;
//    txp=((10000UL*energest_total_time[ENERGEST_TYPE_TRANSMIT].current)/RTIMER_ARCH_SECOND)/clockseconds;
    sl=energest_total_time[ENERGEST_TYPE_TRANSMIT].current/RTIMER_ARCH_SECOND;
    txp=(10000UL*sl)/clockseconds;

 //   rxp=((10000UL*energest_total_time[ENERGEST_TYPE_LISTEN].current)/RTIMER_ARCH_SECOND)/clockseconds;
    sl=energest_total_time[ENERGEST_TYPE_LISTEN].current/RTIMER_ARCH_SECOND;
    rxp=(10000UL*sl)/clockseconds;

    static const char httpd_cgi_ajaxe2[] HTTPD_STRING_ATTR = "ener(%u,%u,%u);";	
    numprinted += httpd_snprintf(buf+numprinted, sizeof(buf)-numprinted,httpd_cgi_ajaxe2,cpp,txp,rxp);
#endif
}
#endif /* ENERGEST_CONF_ON */
 
    PSOCK_SEND_STR(&s->sout, buf);
    timer_restart(&t);
	PSOCK_WAIT_UNTIL(&s->sout, timer_expired(&t));
}
  PSOCK_END(&s->sout);
}
Esempio n. 30
0
/*---------------------------------------------------------------------------*/
static unsigned short
generate_sensor_readings(void *arg)
{
  uint16_t numprinted;
  uint16_t days,h,m,s;
  unsigned long seconds=clock_seconds();
  static const char httpd_cgi_sensor0[] HTTPD_STRING_ATTR = "[Updated %d seconds ago]<br><br>";
  static const char httpd_cgi_sensor1[] HTTPD_STRING_ATTR = "<pre><em>Temperature:</em> %s\n";
  static const char httpd_cgi_sensor2[] HTTPD_STRING_ATTR = "<em>Battery    :</em> %s\n";
//  static const char httpd_cgi_sensr12[] HTTPD_STRING_ATTR = "<em>Temperature:</em> %s   <em>Battery:</em> %s<br>";
  static const char httpd_cgi_sensor3[] HTTPD_STRING_ATTR = "<em>Uptime     :</em> %02d:%02d:%02d\n";
  static const char httpd_cgi_sensor3d[] HTTPD_STRING_ATTR = "<em>Uptime    :</em> %u days %02u:%02u:%02u/n";
// static const char httpd_cgi_sensor4[] HTTPD_STRING_ATTR = "<em>Sleeping time :</em> %02d:%02d:%02d (%d%%)<br>";

  numprinted=0;
  /* Generate temperature and voltage strings for each platform */
#if CONTIKI_TARGET_AVR_ATMEGA128RFA1  
{uint8_t i;
  BATMON = 16; //give BATMON time to stabilize at highest range and lowest voltage

/* Measure internal temperature sensor, see atmega128rfa1 datasheet */
/* This code disabled by default for safety.
   Selecting an internal reference will short it to anything connected to the AREF pin
 */
#if 0
  ADCSRB|=1<<MUX5;          //this bit buffered till ADMUX written to!
  ADMUX =0xc9;              // Select internal 1.6 volt ref, temperature sensor ADC channel
  ADCSRA=0x85;              //Enable ADC, not free running, interrupt disabled, clock divider 32 (250 KHz@ 8 MHz)
//  while ((ADCSRB&(1<<AVDDOK))==0);  //wait for AVDD ok
//  while ((ADCSRB&(1<<REFOK))==0);  //wait for ref ok 
  ADCSRA|=1<<ADSC;          //Start throwaway conversion
  while (ADCSRA&(1<<ADSC)); //Wait till done
  ADCSRA|=1<<ADSC;          //Start another conversion
  while (ADCSRA&(1<<ADSC)); //Wait till done
  h=ADC;                    //Read adc
  h=11*h-2728+(h>>2);       //Convert to celcius*10 (should be 11.3*h, approximate with 11.25*h)
  ADCSRA=0;                 //disable ADC
  ADMUX=0;                  //turn off internal vref      
  m=h/10;s=h-10*m;
  static const char httpd_cgi_sensor1_printf[] HTTPD_STRING_ATTR = "%d.%d C";
  httpd_snprintf(sensor_temperature,sizeof(sensor_temperature),httpd_cgi_sensor1_printf,m,s);
#endif

/* Bandgap can't be measured against supply voltage in this chip. */
/* Use BATMON register instead */
  for ( i=16; i<31; i++) {
    BATMON = i;
    if ((BATMON&(1<<BATMON_OK))==0) break;
  }
  h=2550-75*16-75+75*i; //-75 to take the floor of the 75 mv transition window
  static const char httpd_cgi_sensor2_printf[] HTTPD_STRING_ATTR = "%u mv";
  httpd_snprintf(sensor_extvoltage,sizeof(sensor_extvoltage),httpd_cgi_sensor2_printf,h);
}
#elif CONTIKI_TARGET_AVR_RAVEN
{
#if 1
/* Usual way to get AVR supply voltage, measure 1.1v bandgap using Vcc as reference.
 * This connects the bandgap to the AREF pin, so enable only if there is no external AREF!
 * A capacitor may be connected to this pin to reduce reference noise.
 */
  ADMUX =0x5E;              //Select AVCC as reference, measure 1.1 volt bandgap reference.
  ADCSRA=0x87;              //Enable ADC, not free running, interrupt disabled, clock divider  128 (62 KHz@ 8 MHz)
  ADCSRA|=1<<ADSC;          //Start throwaway conversion
  while (ADCSRA&(1<<ADSC)); //Wait till done
  ADCSRA|=1<<ADSC;          //Start another conversion
  while (ADCSRA&(1<<ADSC)); //Wait till done
//h=1126400UL/ADC;          //Get supply voltage (factor nominally 1100*1024)
  h=1198070UL/ADC;          //My Raven
  ADCSRA=0;                 //disable ADC
  ADMUX=0;                  //turn off internal vref    

  static const char httpd_cgi_sensor2_printf[] HTTPD_STRING_ATTR = "%u mv";
  httpd_snprintf(sensor_extvoltage,sizeof(sensor_extvoltage),httpd_cgi_sensor2_printf,h);
#endif
}
#elif CONTIKI_TARGET_REDBEE_ECONOTAG
//#include "adc.h"
{
uint8_t c;
		adc_reading[8]=0;
		adc_init();
		while (adc_reading[8]==0) adc_service();
	//	for (c=0; c<NUM_ADC_CHAN; c++) printf("%u %04u\r\n", c, adc_reading[c]);
		adc_disable();
		snprintf(sensor_extvoltage, sizeof(sensor_extvoltage),"%u mV",1200*0xfff/adc_reading[8]);

		static const char httpd_cgi_sensorv[] HTTPD_STRING_ATTR = "<em>ADC chans  :</em> %u %u %u %u %u %u %u %u \n";
	    numprinted+=httpd_snprintf((char *)uip_appdata+numprinted, uip_mss()-numprinted, httpd_cgi_sensorv,
		    adc_reading[0],adc_reading[1],adc_reading[2],adc_reading[3],adc_reading[4],adc_reading[5],adc_reading[6],adc_reading[7]);

}
#endif
 
  if (last_tempupdate) {
    numprinted =httpd_snprintf((char *)uip_appdata, uip_mss(), httpd_cgi_sensor0,(unsigned int) (seconds-last_tempupdate));
  }
  numprinted+=httpd_snprintf((char *)uip_appdata+numprinted, uip_mss()-numprinted, httpd_cgi_sensor1, sensor_temperature);
  numprinted+=httpd_snprintf((char *)uip_appdata+numprinted, uip_mss()-numprinted, httpd_cgi_sensor2, sensor_extvoltage);
//   numprinted+=httpd_snprintf((char *)uip_appdata+numprinted, uip_mss()-numprinted, httpd_cgi_sensr12, sensor_temperature,sensor_extvoltage);

#if RADIOSTATS
  /* Remember radioontime for display below - slow connection might make it report longer than cpu ontime! */
  savedradioontime = radioontime;
#endif
  h=seconds/3600;s=seconds-h*3600;m=s/60;s=s-m*60;
  days=h/24;
  if (days == 0) {
    numprinted+=httpd_snprintf((char *)uip_appdata + numprinted, uip_mss() - numprinted, httpd_cgi_sensor3, h,m,s);
  } else {
  	h=h-days*24;	
	numprinted+=httpd_snprintf((char *)uip_appdata + numprinted, uip_mss() - numprinted, httpd_cgi_sensor3d, days,h,m,s);
  }
	
#if 0
  if (sleepseconds) {
	uint8_t p1;
	p1=100UL*sleepseconds/seconds;h=sleepseconds/3600;s=sleepseconds-h*3600;m=s/60;s=s-m*60;
    numprinted+=httpd_snprintf((char *)uip_appdata + numprinted, uip_mss() - numprinted, httpd_cgi_sensor4, h,m,s,p1);
  }
#endif

#if ENERGEST_CONF_ON
{uint8_t p1,p2;
 uint32_t sl;
#if 0
/* Update all the timers to get current values */
  for (p1=1;p1<ENERGEST_TYPE_MAX;p1++) {
    if (energest_current_mode[p1]) {
      ENERGEST_OFF(p1);
      ENERGEST_ON(p1);
    }
  }
#else
  energest_flush();
#endif
  static const char httpd_cgi_sensor4[] HTTPD_STRING_ATTR =  "<em>CPU time   (ENERGEST):</em> %02u:%02u:%02u (%u.%02u%%)\n";
  static const char httpd_cgi_sensor10[] HTTPD_STRING_ATTR = "<em>Radio      (ENERGEST):</em> Tx %02u:%02u:%02u (%u.%02u%%)  ";
  static const char httpd_cgi_sensor11[] HTTPD_STRING_ATTR = "Rx %02u:%02u:%02u (%u.%02u%%)\n";
  sl=energest_total_time[ENERGEST_TYPE_CPU].current/RTIMER_ARCH_SECOND;
  h=(10000UL*sl)/seconds;p1=h/100;p2=h-p1*100;h=sl/3600;s=sl-h*3600;m=s/60;s=s-m*60;
  numprinted+=httpd_snprintf((char *)uip_appdata+numprinted, uip_mss()-numprinted, httpd_cgi_sensor4, h,m,s,p1,p2);

  sl=energest_total_time[ENERGEST_TYPE_TRANSMIT].current/RTIMER_ARCH_SECOND;
  h=(10000UL*sl)/seconds;p1=h/100;p2=h-p1*100;h=sl/3600;s=sl-h*3600;m=s/60;s=s-m*60;
  numprinted+=httpd_snprintf((char *)uip_appdata+numprinted, uip_mss()-numprinted, httpd_cgi_sensor10, h,m,s,p1,p2);

  sl=energest_total_time[ENERGEST_TYPE_LISTEN].current/RTIMER_ARCH_SECOND;
  h=(10000UL*sl)/seconds;p1=h/100;p2=h-p1*100;h=sl/3600;s=sl-h*3600;m=s/60;s=s-m*60;
  numprinted+=httpd_snprintf((char *)uip_appdata+numprinted, uip_mss()-numprinted, httpd_cgi_sensor11, h,m,s,p1,p2);
}
#endif /* ENERGEST_CONF_ON */

#if CONTIKIMAC_CONF_COMPOWER
#include "sys/compower.h"
{uint8_t p1,p2;
 // extern struct compower_activity current_packet;
  static const char httpd_cgi_sensor31[] HTTPD_STRING_ATTR = "<em>ContikiMAC (COMPOWER):</em> Tx %02u:%02u:%02u (%u.%02u%%)  ";
  static const char httpd_cgi_sensor32[] HTTPD_STRING_ATTR = "Rx %02u:%02u:%02u (%u.%02u%%)\n";

  s=compower_idle_activity.transmit/RTIMER_ARCH_SECOND;
  h=((10000UL*compower_idle_activity.transmit)/RTIMER_ARCH_SECOND)/seconds;
  p1=h/100;p2=h-p1*100;h=s/3600;s=s-h*3600;m=s/60;s=s-m*60;
  numprinted+=httpd_snprintf((char *)uip_appdata+numprinted, uip_mss()-numprinted, httpd_cgi_sensor31, h,m,s,p1,p2);

  s=compower_idle_activity.listen/RTIMER_ARCH_SECOND;
  h=((10000UL*compower_idle_activity.listen)/RTIMER_ARCH_SECOND)/seconds;
  p1=h/100;p2=h-p1*100;h=s/3600;s=s-h*3600;m=s/60;s=s-m*60;
  numprinted+=httpd_snprintf((char *)uip_appdata+numprinted, uip_mss()-numprinted, httpd_cgi_sensor32, h,m,s,p1,p2);

}
#endif

#if RIMESTATS_CONF_ON
#include "net/rime/rimestats.h"
  static const char httpd_cgi_sensor21[] HTTPD_STRING_ATTR = "<em>Packets   (RIMESTATS):</em> Tx=%5lu  Rx=%5lu   TxL=%4lu  RxL=%4lu\n";
  numprinted+=httpd_snprintf((char *)uip_appdata+numprinted, uip_mss()-numprinted, httpd_cgi_sensor21,
		rimestats.tx,rimestats.rx,rimestats.lltx-rimestats.tx,rimestats.llrx-rimestats.rx);
#endif
  static const char httpd_cgi_sensor99[] HTTPD_STRING_ATTR = "</pre>";
  numprinted+=httpd_snprintf((char *)uip_appdata+numprinted, uip_mss()-numprinted, httpd_cgi_sensor99);

  return numprinted;

}