Shop OBEX P1 Docs P2 Docs Learn Events
Setting a bit to zero in a loop... — Parallax Forums

Setting a bit to zero in a loop...

FORDFORD Posts: 221
edited 2007-07-28 02:04 in BASIC Stamp
Hi All,

There may be a simple thing I am missing here, but here goes...
I have a byte variable called state, which contains the status of 8 sprinkler stations. (on or off).
When I want to turn one of the stations off, I have the state variable contain 1's for the stationss that are on.
At present, if I want to change a bit, I have to use the station number to then jump to a label contain a statement such as...
state.bit3 = 0

the problem is, it is code hungry and messy to have a branch and 8 labels just to set a bit in a byte.

I would like to be able to do something like...

sprinkler = 3
bit(sprinkler) = 0······· 'which is not possible

or somehow do it in a for/next loop, and shifting bits etc.
eg:
sprinkler·= 3
for counter = 0 to 7
·if counter = sprinkler then state(counter) = 0
next

(I know that wont work, its just the principle I'm trying to achieve).

Anyone have any simple suggestions ?
I've been thinking about this for ages, and I'm sure there must be a simple way in a few lines of code in a loop.

Cheers,
Chris,
West Oz.




·

Comments

  • Tracy AllenTracy Allen Posts: 6,664
    edited 2007-07-28 00:50
    Well, if you have a variable, sprinklerStateByte, with 0 bits for off and 1 bits for on. Then,

    sprinker=3
    sprinklerStateByte.bit0(sprinkler)=0
    will zero bit 3 of the state variable.

    Another way,

    sprinkler=3
    sprinklerStateByte = sprinklerStateByte & ~ DCD sprinkler ' ~DCD 3 creates the mask, %11110111

    ▔▔▔▔▔▔▔▔▔▔▔▔▔▔▔▔▔▔▔▔▔▔▔▔
    Tracy Allen
    www.emesystems.com
  • OzStampOzStamp Posts: 377
    edited 2007-07-28 00:52
    Hi Chris

    Do an AND function with the Bit you wish to turn off.

    Sprinkler··········· 76543210
    So if you have state= %10011111· and you wish to turn sprinkler 4 off

    Do·· "state=state and %11101111"· that will turn bit 4 off and leave the other as is

    Cheers

    Ron Nollet····
  • OzStampOzStamp Posts: 377
    edited 2007-07-28 00:54
    Hi Tracy
    Looks like we were trying to help Chris at the same time.
    Hope you are all okay there .

    All fine here.
    Cheers
    Ronald Nollet
  • FORDFORD Posts: 221
    edited 2007-07-28 02:04
    Thanks Tracy and Ron,

    I will try both and see which one reduces my code space in memory the most.

    Thanks heaps.

    Tracy, Ididnt know you could put an array identifier on the end of the byte variabl, that is very useful.

    Cheers,
    Chris, West Oz.
    ·
Sign In or Register to comment.