10 years, 5 months ago.

Sampling values from a 50Hz sine wave??

Hi

I have a program here which I am measuring a 50Hz sine wave using a Ticker which is calling my sampling function every 0.000625 seconds i.e period of waveform is 0.02 then dividing this by 32 to get 32 samples per waveform it requires to sample every 0.000625 seconds. The Ticker seems to be calling the ADC function correctly 32 times per period but when I try to read the values from the sampling of 4 waveforms they are wrong could somebody tell me why my below code isn't displaying the correct values?

Thanks

  1. include "mbed.h" Serial pc(USBTX, USBRX);

**Global variables***

AnalogIn AinV(p16);

float ADC_Voltage_data;

float ADC_sampling_rate;

Ticker ADC_set;

float samples[128]; array to save 128 samples of data ie four waveforms of data

int ADC_Count;

DigitalOut sample_pulse(p17);

**Function prototype's

void ADC();

*Main Function**

int main() { sample_pulse=0;

ADC_Count=0;

ADC_set.attach(&ADC,0.000625); attach a ticker ADC-set to call ADC function at the sampling rate calculated to allow 32 samples per period

if (ADC_Count <128) {

}

for (int i=0;i<128;i++)

{

printf("%f\n\r", samples[ADC_Count]); }

}

*function to display analog input as voltage on LCD***

void ADC() {

sample_pulse=1;

ADC_Voltage_data=AinV*3.3; multiplyed by 3.3 to give the correct voltage reading

samples[ADC_Count]=ADC_Voltage_data; Save voltage reading within an array named ADC_count

sample_pulse=0;

}

1 Answer

10 years, 5 months ago.

It has been replied numerous times, but please use <<code>> and <</code>> tags around your posted code to keep it readable....

There are several problems with your code:

  • You dont seem to increment ADC_Count in the ADC interrupt routine. All samples are stored in array location 0.
  • The if test on ADC_Count is empty and has no meaning. It will probably be optimised out and does not wait until the 128 samples are completed, which I assume is your intention. Use a while loop instead.
  • The printf loop iterates over i from 0 to 127, but the index into the array is always ADC_Count which remains at 0 as mentioned above.
  • ADC_Count should be declared as volatile otherwise the compiler may not understand that it is updated in an interrupt routine

Are you sure that the analog input value is between 0V and 3V3. It should never be negative or exceed 3V3 The ADC will have noise and may have some incorrect values due to issues with the mbed hardware. Be prepared for some unexpected values.

Accepted Answer

Thanks much appreciated

posted by Alan Carson 09 Nov 2013