[En-Nut-Discussion] Sample Code???

Peter Sodermanns peter.sodermanns at aixcon.de
Fri Mar 3 14:08:17 CET 2006


saime aley schrieb:

> It will be highly appericiated if you can send me simple codes with some
> description or documentation,

Hi Saime,

this is a short piece of code (stripped down to the necessary) I use in 
my program. It reads 2 channels with a frequency of 10 Hz each, and 
delivers the average of 10 conversions (see defines).
To understand how ad-conversion works see mega128 documentation.

Hope you can use it.

Regards
                Peter



#include <sys/atom.h>

#define		MAX_ADW_CHANNEL		2			// number of analogue input channels
#define		MAX_ADW_COUNT		10			// number of values to average

// declared in main
			u_int			adw[8];			// measurement results of analogue channels (2.56V 
= 1024)


void ADCSetChannel(u_char adc_channel)
{
u_char current_admux;

	current_admux = inb(ADMUX) & 0xF8;
	outb(ADMUX, (current_admux | adc_channel));
}


THREAD(ADW_Service, arg)
{
u_int ad_count = 0;
u_char ad_channel = 0;
u_int ad_values[MAX_ADW_CHANNEL][MAX_ADW_COUNT];
u_char i,j;
u_int ad_tmpval;
u_char sensor_ok = 0;

	NutThreadSetPriority(96);
	// wait for stable voltage supply
	NutSleep(50);

	// initialize
	// prescaler = CPU-clock / 128
	sbi(ADCSR, ADPS2);
	sbi(ADCSR, ADPS1);
	sbi(ADCSR, ADPS0);
	// single conversion mode
	cbi(ADCSR, ADFR);
	// internal 2.56V-reference
	sbi(ADMUX, REFS1);
	sbi(ADMUX, REFS0);
     // Enable ADC
     sbi(ADCSR, ADEN);

	// start with ADC0
	ad_channel = 0;
	NutSleep(50);

	// cycle through analogue inputs
	for (;;) {
	// switch multiplexer
	ADCSetChannel(ad_channel);
	// wait til settled
	NutSleep(10);
	// start conversion
	sbi(ADCSR, ADSC);
	// wait for result
	NutSleep(10);
	// adc value into filter array
	ad_values[ad_channel][ad_count] = inw(ADCW);
//	printf_P(PSTR("%d: channel %d, value = %d\n"), ad_count, ad_channel, 
gv->adw[ad_channel]);
	// next input channel
	ad_channel++;
	// if last: start over
	if (ad_channel >= MAX_ADW_CHANNEL) {
		ad_channel = 0;
		ad_count++;
		// if enough values per channel
		if (ad_count >= MAX_ADW_COUNT) {
			// loop over all channels
			for (i=0; i<MAX_ADW_CHANNEL; i++) {
				ad_tmpval = 0;
				// and over all values of that channel
				for (j=0; j<MAX_ADW_COUNT; j++)
					ad_tmpval += ad_values[i][j];
				// calculate mean value
				gv->adw[i] = ad_tmpval / ad_count;
//				printf_P(PSTR("channel %d, count %d, Sum = %5d, mean = %4d\n"), i, 
j, ad_tmpval, gv->adw[i]);
			}
			ad_count = 0;
		}
		// 20 conversions per second
		NutSleep(30);
	}
}


More information about the En-Nut-Discussion mailing list