bizarre picaxe arithmetic; 630 = 118

moorea21

Senior Member
This program:-
Code:
init: pause 500
main: serout B.1,N2400,(254,1)
	pause 30
	low B.0 low B.2
	pause 200
	serout B.1,N2400,(254,192)
	serout B.1,N2400,("init")
	pause 300
	readadc B.4,b1
	pause 30
	serout B.1,N2400,(254,128)
	serout B.1,N2400, ("init is")
	serout B.1,N2400, (#b1)
	pause 2500
	high B.2
	pause 2500
	low B.2
	serout B.1,N2400,(254,192)
	serout B.1,N2400,("after")
	pause 940
	readadc B.4,b2
	pause 100
	serout B.1,N2400,(254,192)
	serout B.1,N2400, ("after ")
	serout B.1,N2400, (#b2)
		b3 = b1 * 100 / b2
	serout B.1,N2400, (" ")
	serout B.1,N2400, (#b3)	
	pause 2500
	if b3 > 155 then
		serout B.1,N2400, (" OK")
		high B.0 low B.2
	else
		serout B.1,N2400, (" RPT")
		low B.0 high B.2
	end if
pause 700
'goto main
end
Tells me that:

b3 = b1 * 100/b2
b3 = 252 * 100/40
b3 = 25200/40
b3 = 118

On my planet, the answer is 630.

I have no clue why this is coming out with such weirdness, can anyone tell me what on earth is going on?

Thanks
 
Last edited by a moderator:

pxgator

Senior Member
b3 is an 8 bit variable and 630 is way more than 255 which is a full 8 bits.
The results are truncated to 8 bits. Proof: 630 AND 255 = 118.

Cheers to all

P.S. If you use a 16 bit variable the results will be correct.

W2 = 25200/40
W2 will now = 630
 
Last edited:

moorea21

Senior Member
I was about to delete this thread, having gone for a walk and realised that 256 + 256 + 118 =630...
Can an ADC write directly to a word variable?
 

hippy

Technical Support
Staff member
Also no need to use READADC10. While that needs a word variable to store the full 0 to 1023 result, one can still use word variables to store the result of a READADC. They will simply hold value 0 to 255.

It's only the result of "b1 * 100 / b2" which needs storing in a word variable. All maths processing is done to 16-bits regardless of whether operands are byte or word values. So this is fine ...

Code:
readadc B.4,b1
readadc B.4,b2
[b]w3[/b] = b1 * 100 / b2
As would be ...

Code:
readadc B.4,w1
readadc B.4,w2
w3 = w1 * 100 / w2
But there's no great benefit in using word values. Using READADC10 will also introduce problems because 100 * 1023 will overflow 16 bits.
 
Top