RoboPython
RoboPython

Reputation: 161

Infra Red Arduino Custom Serial

Basically I am looking to make an serial-like system that runs communication between IR LEDs on an arduino. Below the code gets to the point having an array with a collection of 1s and 0s in it. I need to convert this 8 bit array into a single character and output it. But I don't know how to do this. Help would be appreciated.

    int IR_serial_read(){
        int output_val;
        int current_byte[7];
        int counter = 0;
        IR_serial_port = digitalRead(4);
        if (IR_serial_port == HIGH){
            output_val =1;
        }
        if (IR_serial_port == LOW){
            output_val =0;
        }
        current_byte[counter] = output_val;
        counter +=1
}

Upvotes: 0

Views: 95

Answers (1)

Lee Fogg
Lee Fogg

Reputation: 795

This would best be done with bitwise operators, I think the or function would be of best use here as it will set a bit if the input is 1 and not change it if it is 0, could use a loop to loop through your array and set the bits. Looking at your code, are you sure you are receiving all 8 bits? You seem to be saving 7 bits. As you are creating a byte array solely for the purpose of using only 1s and 0s, it suggest immediately setting the bits in the same loop. Here is the code that I suggest:

byte inputByte = 0;                     // Result from IR transfer. Bits are set progressively.
for (byte bit = 0;  bit < 8; bit++) {   // Read the IR receiver once for each bit in the byte
    byte mask = digitalRead(4);         // digitalRead returns 1 or 0 for HIGH and LOW
    mask <<= bit;                       // Shift that 1 or 0 into the bit of the byte we are on
    inputByte |= mask;                  // Set the bit of the byte depending on receive
}

This would also be put inside a loop to read all the bytes in your data stream.
It is designed for readability and can be optimised further. It reads the least significant bit first.
You can also apply the same technique to your array if you wish to keep using an array of bytes just for 1s and 0s, just replace the digitalRead with the array location (current_byte[bit]).

Upvotes: 0

Related Questions