PDA

View Full Version : Solved Getting at a byte's bits - reading a byte from porta, but using at it as 8 bits

Stempile
04-01-2012, 10:40 PM
My project reads a sensor with 8 pins (binary data) . I am doing 3 functions over the data, initially I read the pins for each function, but am concerned about values changing between reads of INA so started looking at how to read it once to a VAR, then do same process with a VAR rather then INA.

Working example using INA:

bit_count = 0
sensor0_pin = 0

SensorValue = ina[(sensor0_pin..sensor0_pin +7)]

repeat bit_count from 0 to 7 'repeat for each pin's bit read off of sensor

average += ina[(sensor0_pin + bit_count)] * ((bit_count * 2) + 2) 'check each bit, add weighted value

average_denom += ina[(sensor0_pin + bit_count)] 'determine how many bits were high to determine total number calculate in average

return average /= average_denom 'calculate average of weighted bits from sensor

With the working example, the algorithm an ina[0..7] = 255 (1111111) will yield an average of 9.

My attempt was confused by looking at BYTE [offset] as the bits, but it is really a BYTE array:

bit_count = 0
sensor0_pin = 0

SensorValue = ina[(sensor0_pin..sensor0_pin +7)]

repeat bit_count from 0 to 7 'repeat for each bit read off of sensor
average += BYTE[sensorValue][bit_count] * ((bit_count * 2) + 2) 'check each bit, add weighted value
average_denom += BYTE[sensorValue][bit_count] 'determine how many bits were high to determine total number calculate in average

return average /= average_denom 'calculate average of weighted bits from sensor

Thanks for the suggestions...

kuroneko
04-02-2012, 12:36 AM
Bit addressing is only available for special purpose registers (SPR), e.g. ina, outa etc. As a quick fix you could use an unused (no h/w connection) SPR say outb and use this instead of SensorValue. Untested (note the sensor0 offset is not required):

bit_count = 0
sensor0_pin = 0

outb[0..7] = ina[(sensor0_pin..sensor0_pin +7)]

repeat bit_count from 0 to 7 'repeat for each pin's bit read off of sensor

average += outb[bit_count] * ((bit_count * 2) + 2) 'check each bit, add weighted value

average_denom += outb[bit_count] 'determine how many bits were high to determine total number calculate in average

return average /= average_denom 'calculate average of weighted bits from sensor

As an alternative you'd have to extract the bits from the byte, e.g. (value >> bit_number) & 1.

Stempile
04-02-2012, 03:21 AM
@kuroneko

WOW. I am gonna have to squire that idea away for stuff later... Seems perhaps you have bumped into this case before?

Tested a couple different ways, and worked for what I was thinking. I had to change the methods around. Going to keep thinking about it.

Thanks. Solved.