PDA

View Full Version : Window Comparator and Direction



Zapman
- 30th March 2023, 19:24
I know this has been asked and I looked at many of the replies but at 75 years young I am having a bit of trouble wrapping my head around the best way to do this. I have an adc value that I am trying to maintain in a window. I am comparing an adc reading to a reference and trying to decide if it is in a +/- 40 count range. If not, I need to determine the direction to run, i.e. Vadc - Vref is positive or negative result. What I am having trouble with is the possibility of the answer being negative (PBP returning 65536-value) and therefore looking greater than the reference because of the way negative numbers are handled and getting a wrong direction. I suppose I could use Long variables since I am using a PIC18F but I am just looking to understand the logic.
Thanks for helping with my post-retirement education.

richard
- 30th March 2023, 22:11
maybe like this , the msb of a var is the sign bit
to convert between unsigned an signed use abs() or vice versa var=~var+1



Vadc var word
Vref var word
vDif var word
aDif var word


vDif = Vref - Vadc ;signed difference
adif= abs(Vref - Vadc);absoloute unsigned difference


if vDif.15 then
do negative stuff
else
do positive stuff
endif

Zapman
- 31st March 2023, 00:02
Thanks Richard,

it's the format of the ABS that has been confusing me. According to what I read in the manual, the ABS function for a word variable returns 65536 - value. So if I had a negative number and did the ABS() of that, it could return a number that is larger than the number I was taking the ABS value of. If my number was -40 for example. That would be 1111111111011000 in binary. (-40) If I do the ABS value function I think it returns :eek: 0000000000101000 which is 40! Wow, I was subtracting from 65535 not 65536. The light just went on! Thanks again Richard, sorry to ask such a dumb question!

:)

Ioannis
- 1st April 2023, 11:04
If your ADC is the ADC inside the PIC then it is a possitive value.

If you use external ADC then I guess it can be negative also.

Ioannis

Zapman
- 2nd April 2023, 19:53
If your ADC is the ADC inside the PIC then it is a possitive value.

If you use external ADC then I guess it can be negative also.

Ioannis

I am using the internal ADC on the PIC18F45K80 but the question I was having was determining if I was inside a window of +/- 40 counts. I was concerned that RefPosition - CurPosition could give me a negative result but I see how to handle it now. Thanks for all the help.