Search code examples
arrayscarduinobytebit

Combining two bytes of value from an array and putting into one and printing it


Hello actually I want to combine second and third byte of the array and assign to the variable name that is StartBit, I have written and added a boolean value TxtBit to check the condition and output the value but when i output the value I am getting the first byte value completely zero and second byte value as it is. It would be great if anyone help me out.

#include <SoftwareSerial.h>

byte TxData[] = {
    0b00000001, 0b00000010, 0b00000011, 0b00000100, 0b000000101,
    0b00000110, 0b00000111, 0b00001000, 0b00001001, 0b11111111,
};

int  bytePos;
bool TxBit;
int  bitPos;
char ControlBit;
char StartBit;

void setup()
{
    Serial.begin(1200);
}

void loop()
{
    receiveddata();
}

void receiveddata()
{
    Serial.println("Bytes Received: ");

    for (bytePos = 0; bytePos < 1; bytePos++)
    {
        ControlBit = TxData[bytePos];
    }

    for (bitPos = 0; bitPos < 8; bitPos++)
    {
        TxBit = ControlBit & (0x80 >> bitPos);
        // Serial.println(TxBit);
    }

    for (bytePos = 1; bytePos <= 2; bytePos++)
    {
        StartBit = TxData[bytePos];
    }

    for (bitPos = 0; bitPos < 16; bitPos++)
    {
        TxBit = (StartBit) & (0x8000 >> bitPos);
        Serial.print(TxBit);
    }

    Serial.println("");
}

Solution

  • According to your comment, the code

    for (bytePos = 1; bytePos <= 2; bytePos++)
    {
        StartBit = TxData[bytePos];
    }
    

    should be replaced by:

    StartBit = (TxData[1] << 8) + TxData[2];
    

    and importantly, StartBit must be define as an int or short not a char because it must contain 16 bits.

    Later in your code, you computation with TxBit has not much sense either. You should clarify the intended goal.