2

I am new to coding in C using a Arduino Uno. I would like to do the following:

int randomNumber;
int randomNumberBinairy = 0;

void setup() {
 Serial.begin(9600);
 randomSeed(analogRead(A0));
}

void loop() {
  randomNumber = random(1, 16);
  randomNumberBinairy = ((randomNumber, BIN));
  Serial.println(randomNumberBinairy);
  delay(5000);
}

This prints out:

2
2
2
2
etc..

However I would like it to print out the random number (between 1 and 16) in binary. So it should look something like:

101
1100
110
10
etc..

Any help on this please?

too honest for this site
  • 12,050
  • 4
  • 30
  • 52
Jim
  • 23
  • 2

3 Answers3

1

in arduino you can use the function bitRead(x, n)

int randomNumber;

void setup() {
 Serial.begin(9600);
 randomSeed(analogRead(A0));
}

void loop() {
  randomNumber = random(1, 16);
  Serial.print(bitRead(randomNumber, 0));
  Serial.print(bitRead(randomNumber, 1));
  Serial.print(bitRead(randomNumber, 2));
  Serial.println(bitRead(randomNumber, 3));
  delay(5000);
}
a.costa
  • 1,029
  • 1
  • 9
  • 19
  • I think this is unnecessarily convoluted, **Serial.print** already provides an optional argument *format* which allows you to choose the format of the printed number. – Patrick Trentin Nov 22 '16 at 08:49
0

If you are sure it will be always 0 to 15 you can write a switch-case block that handles 16 different probability. That works faster than bitread(x, n) for each bit.

t.m.
  • 1,430
  • 16
  • 29
0

Just for your own reference, the documentation of Serial.print says:

Serial.print(78, BIN) gives "1001110"

Serial.print(78, OCT) gives "116"

Serial.print(78, DEC) gives "78"

Serial.print(78, HEX) gives "4E"

That is, if you want to print something in binary then you only need to write

Serial.print(randomNumber, BIN);
or
Serial.println(randomNumber, BIN);

It's simple as that.

Community
  • 1
  • 1
Patrick Trentin
  • 7,126
  • 3
  • 23
  • 40