Calculate with 16 bits value

For questions and comments on programming in general. And for any items that don't fit into the forums below.

Moderators: Benj, Mods

Post Reply
Walbeek
Flowcode v5 User
Posts: 68
Joined: Thu Mar 01, 2007 10:48 am
Location: Netherlands
Been thanked: 3 times
Contact:

Calculate with 16 bits value

Post by Walbeek »

Hi there,

I use a external ADC with 16 bit resolution to measure a voltage on the input.
The value is put in two byte´s, value-low and value-hi.
I would like to read the value from the ADC approx. 10 times a second.
After that I would like to calculate the average value of this 10 measurements.
Is it possible to use several values and calculate the average value fir these 16 bits again?
Can you please point me in the right direction.

Rinie
Greetings, Rinie
Flowcode V7 user

User avatar
Benj
Matrix Staff
Posts: 15312
Joined: Mon Oct 16, 2006 10:48 am
Location: Matrix TS Ltd
Has thanked: 4803 times
Been thanked: 4314 times
Contact:

Re: Calculate with 16 bits value

Post by Benj »

Hello Rinie,

First of all you can combine two 8-bit bytes into a 16-bit variable like this.

Code: Select all

Int = (Byte_MSB << 8) + Byte_LSB
This way you can store into 16-bit unsigned integer variables straight away.

You can then perform averaging by doing something like this.

Code: Select all

IntOld = Int
IntOldOld = IntOld
Int = ReadNewSample
Average = Int + IntOld + IntOldOld
This might get messy after say 3 iterations so moving to an array might help.

Code: Select all

//Cycle through array moving new to old
index = 1
numsamples = 10
while index < numsamples
{
 Int[index] = Int[index - 1]
 index = index + 1
}

//Collect latest 16-bit reading
Int[0] = ReadNewSample

//Perform average calculation
index = 0
average = 0
while index < numsamples
{
 average = average + Int[index]
 index = index + 1
}
average = average / numsamples
Hope this helps.

Post Reply