I am trying to convert bytes to a word, what am I doing wrong?

Tyro

Member
I get data from a sensor via a serial link. No problems, this part works fine.
If I include the four lines near the bottom to convert the three bytes into a word I get a large number (about 50,000) instead of the expected 200 to 999. Inspecting the three bytes at the first debug the numbers are as expected.
If I comment out the serin line and use the artificial numbers below the symbols the word is correct (523).
What am I doing wrong?
 

Attachments

lbenson

Senior Member
If your numbers are ascii charactors, "0"-"9", you need to convert to binary before multiplying

b0=b0-"0"*100
b1=b1-"0"*10
b0=b2-"0"
ORPword = b0+b1+b2
 
Last edited:

Flenser

Senior Member
I get a large number (about 50,000) instead of the expected 200 to 999
This is what lbension is referring to. If you are receving the digits 0-9 then it sounds to us they likely are the ascii codes for the characters 0-9 and not the numeric values 0-9.

The ascii code for the character "0" is the decimal value 48, for the character 1 the decimal value 49, for the character 2 the decimal value 50, etc, though to decimal 57 for the character "9" so if you received the character "2" in b0 then 50 * 100 would be 5,000.

Note that if you are getting around 50,000 from your calculation then you cannot be receiving an ascii character in b0 that is in the range "0" - "9".
It is easy enough to investigate. What do you see in the terminal from your code: sertxd(b0,b1,b2,13,10) and what is the "Terminal mode" setting at the bottom of the terminal window, ASCII or raw?
 

Aries

New Member
Code:
        sertxd(b0,b1,b2,13,10)                     'for ORP only

        ORPword = b0 * 100
        b3 = b1 * 0
        ORPword = ORPword + b3
        ORPword = ORPword + b2
(1) b3 = b1*0 has to be wrong, unless you really mean to set it to zero - do you mean 10?
(2) the fact that you are printing the bytes using raw sertxd suggests you are expecting them to be ASCII rather than numbers
(3) to see exactly what the bytes are, use #b0 etc - i.e.
sertxd(#b0," ",#b1," ",#b2,13,10)
 

hippy

Ex-Staff (retired)
The issue does seem to be that you receive ASCII characters so need to convert them to decimal 0-9 bedore use. There are a number of ways to do that -
Code:
b0 = b0 - "0" * 100
b1 = b1 - "0" * 10
b2 = b2 - "0"
ORPword = b0 + b1 + b2
Code:
ORPword = b0 - "0" * 100
ORPword = b1 - "0" * 10  + ORPword
ORPword = b2 - "0"       + ORPword
Code:
ORPword = b0 - "0" * 10 + b1 - "0" * 10 + b2 - "0"
Code:
ORPword = b0 * 10 + b1 * 10 + b2 - 5328
In the last two the first *10 is correct; it should not be 100. Because the PICAXE does maths strictly from left to right the first *10 is multiplied by the subsequent *10 which makes it an effective *100
 

Tyro

Member
Got it. I will not be able to try this until late this afternoon.
The b3 = b1 * 0 is a mistake, I was trying all sorts of things. It should be b3 = b1 * 10 of course.
 
Top