0

In my current project which integrates Arduino/avr IC with Raspberry-Pi, and each communicating via serial, I'm looking to send a byte of data to the Arduino from the RPi, which then would be iterated over, bit by bit.

Each bit represents a setting. If a bit is 0, then the Arduino would turn that respective device off, if a bit is 1, then Arduino would turn that respective device on. For example, a byte such as: 01100110, would mean the Arduino would have to turn four devices off, and four devices on.

I'm looking for information on how to take a byte over serial, and iterate over that byte bit by bit, and have the Arduino make decisions based on the value of each bit.

Excuse my post for lacking much technical detail, I'm refraining from using terms that are still very vague to me.

Regards.

closed as off-topic by jsotola, MichaelT, VE7JRO, MatsK, sempaiscuba Jan 29 at 8:43

This question appears to be off-topic. The users who voted to close gave this specific reason:

  • "This question does not appear to be about Arduino, within the scope defined in the help center." – jsotola, MichaelT, VE7JRO, MatsK, sempaiscuba
If this question can be reworded to fit the rules in the help center, please edit the question.

  • 1
    your question is a C++ programming question ..... it is not related to the Arduino specifically – jsotola Jan 29 at 6:41
1

In all the examples below, value is the value of the byte

LSB -> MSB - so 00001111 would turn ON the first 4 devices and turn OFF the last 4

for(int i = 0, mask = 1; i < 8; i++, mask = mask << 1)
{
    if (value & mask) 
    {
        // bit is on
    }
    else
    {
        // bit is off
    }
}

Alternatively, you can do the following, but value will be altered

for(int i = 0; i < 8; i++, value = value >> 1)
{
    if (value & 1) 
    {
        // bit is on
    }
    else
    {
        // bit is off
    }
}

Working the other way around in each byte:
MSB -> LSB - so 00001111 would turn OFF the first 4 devices and turn ON the last 4

for(int i = 0, mask = 128; i < 8; i++, mask = mask >> 1)
{
    if (value & mask) 
    {
        // bit "i" is on
    }
    else
    {
        // bit "i" is off
    }
}

Alternatively, you can do the following, but value will be altered

for(int i = 0; i < 8; i++, value = value << 1)
{
    if (value & 128) 
    {
        // bit is on
    }
    else
    {
        // bit is off
    }
}

Not the answer you're looking for? Browse other questions tagged or ask your own question.