# circular buffering-problem

Status
Not open for further replies.

#### Ma3ix

##### Member level 2
Hi, I need help for my code. Im trying to do filtering (running average from circular buffer) from adc reading.
I wrote this code and tested it from bascom 8051 compiler and it works fine :

Code:
**circular buffer**

Dim array(3) As Byte
Dim P As Byte
Dim sum As Byte
Dim X As Byte
Dim counter As Byte
Dim average As Single

counter = 0
P = 0
sum = 0

Do

sum = sum - array(p)
Input "Input number:" , X
array(p) = X
sum = Sum + X
counter=counter + x
P = P + 1
P = P Mod 3
If counter = 3 Then
average = Sum / 3

counter = 2
End If
Loop

**
If I enter 5 numbers , for example array= (x1=1, x2=3; x3=5; x4=7; x5=8)
i will get 3 averages:
average_1= x1 + x2 + x3
average_2= x2 + x3 + x4
average_3= x3 + x4 + x5
which is fine cause I want to replace the oldest input with newest.

When I put this code in my project(thermometer) it does not work!Only first average is fine on display, I guess that second line of this code "sum=sum-array(p)"
does not work with project.:/
Project works fine without circular buffering.

The logic is same

Do

- do calculation for temperature
- send data to displays

loop

im coding in Bascom 8051

Last edited by a moderator:

#### FvM

##### Super Moderator
Staff member
I wrote this code and tested it from bascom 8051 compiler and it works fine
Means it's compiled without errors? O.K. but does it mean the code is correct?

Suggest to trace code operation with pencil and paper method, just writing down the results for every loop iteration. You surely see why it's not working as expected.

#### Ma3ix

##### Member level 2
Means it's compiled without errors? O.K. but does it mean the code is correct?

Suggest to trace code operation with pencil and paper method, just writing down the results for every loop iteration. You surely see why it's not working as expected.

I tested this part of code in Bascom simulator and it works (giving me correct results for running average)..

In Proteus simulation and in reality it gives me totally incorrect results:roll:

It seems to me that mcu does not remember elements of array after first average?:idea:

#### FvM

##### Super Moderator
Staff member
Looks definitely wrong
Code:
counter=counter + x

#### Ma3ix

##### Member level 2
Looks definitely wrong
Code:
counter=counter + x

sorry, wrong pasted code;
it is counter=counter + 1

Status
Not open for further replies.

Replies
1
Views
3K
Replies
3
Views
1K
Replies
1
Views
854
Replies
1
Views
962
Replies
5
Views
7K