Convert int to binary Array

Hi!
Is there an easy way (or function) to convert a integer ( 1 to 128) to an 7bit Binary code array?

I found the following function String(myInt,BIN) which works (tried it with the Serial.println() function). But how can i put this into a String (or better a string array)?

The next thing is to write the String to the digital Out Pins ( Pin 13 to 19). This can easily be done with a for loop.

So, how do I convert my integer to an Array?

regards

tsaG

bitRead
Please, don't use String

Check out the bitRead function:

const byte numPins = 7;
byte pins[] = {13, 14, 15, 16, 17, 18, 19};
void setup() {
  Serial.begin(115200);
}

void loop() {
  while(!Serial.available()); // Do nothing until serial input is received
  byte num = Serial.read(); // Get num from somewhere
  for (byte i=0; i<numPins; i++) {
    byte state = bitRead(num, i);
    digitalWrite(pins[i], state);
    Serial.print(state);
  }
  Serial.println();
}
2 Likes

Thank you! exactly what I was looking for.

Arduino has an implementation of itoa() which can also be used for this purpose

Just a quick example

void setup()
{
  Serial.begin(115200);
  for(byte i = 0; i < 7; i++){
    pinMode(i+13,OUTPUT);
  }

  byte someValue = 20; //For this example, lets convert the number 20
  
  
  char binary[9] = {0}; //This is where the binary representation will be stored
  someValue += 128; //Adding 128 so that there will always be 8 digits in the string
  itoa(someValue,binary,2); //Conver someValue to a string using base 2 and save it in the array named binary
  char* string = binary + 1; //get rid of the most significant digit as you only want 7 bits


  Serial.println(string); //print out our string.
  for(byte i = 0; i < 7; i++){
    digitalWrite(i+13,string[i] - '0'); //write to the pin (the - '0' converts the bit of the string to HIGH or LOW)
  }
}

void loop()
{
}

Okay, everything works properly. the next problem is to get the command over I2C from the master.

void receiveEvent(int howmany){
string receivestr = wire.receive() //Whole String 
byte comand =bitRead(colcount, 0);
if (comand = 0){
//cut off the comand number and do this
}
else if (comand = 1){
//cut off the comand number and do this
}

}

Just my way of thoughts
So,

  1. how do I receive the whole data. Which is the best type to put it in? I guess its not String.
  2. How do I cut off the first value ( just 0 to 9) of the received data?

Okay, everything works properly. the next problem is to get the command over I2C from the master.

OK, that kind-of assumes we all know what the Hell it is you're talking about.

string receivestr = wire.receive() //Whole String Don't know of any datatypes called "string (and a missing semicolon)

if (comand = 0){I'm betting you didn't mean an assignment.