Binary Output

Hi everyone,

I am working on a project speed measurement.

I am getting output as below:

Speed = 13 Km/H
Binary Code = 01101

I have converted it to Binary Code.

I am using Controllino mini hardware for my project which has 8 digital output Pins D0 to D7.

I need to start LED as per the result I got in Binary code.

For 01101 → D0, D2, D3 will be ON and D1, D4 will be OFF

How can I do this?

look for the program I have attached for better Idea

Thank you Guys!

Geschwindigkeitmessung.ino (1.17 KB)

Use bitwise-and to determine if a bit is set

for example:

  00001101 (13)
& 00001000 (1 << 3)
==========
  00001000 <-- value is not 0, therefore the bit was set

You could also use bitRead(), so bitRead(13, 3) will return true

Try this program to get a better understanding

void setup() {
  Serial.begin(9600);

  byte value = 13;
  for(byte i = 0; i < 8; i++) {
    Serial.println((value & (1 << i)) ? "ON" : "OFF");
  }
}

void loop() {
}

Thank you for your reply.

It works with your code.

But as you can see in my logic, I have a string for binary output

and your code is for Byte.

my result will be change everytime and it will give a string output

// Conversion from Decimal to Binary
{
int myNum = velocity;
int zeros = String(myNum,BIN).length();

String myStr;
for (int i=0; i<zeros; i++) {
myStr = myStr + “0”;
}
myStr = myStr + String(myNum,BIN);
Serial.print(“Binar Codiert :”);
Serial.println(myStr);
//delay(1000);

As I print myStr will be for example : 01101

with your code I am not able to get the result.

look at the code and guide me

It would be a great help for me.

I should warn you that using String is highly frowned upon in the Arduino community because it can lead to serious issues such as memory problems. It is much more recommended that you use char arrays.

Also, if you just want to print the number in binary and have no need to store it in a string / char array, then simply print it like this

Serial.print(value, BIN); //this will print the result in binary

You could also do this

byte value = 13;
for(byte i = 0; i < 8; i++) {
  Serial.print((value & (1 << i)) ? 1 : 0);
  //Serial.print(!!(value & (1 << i))); //this should also work
}
Serial.println();

There’s no need to convert it to binary, since every variable already ís binary.

Can just use the variable to directly write to the outputs, either using bitRead , or using direct port manipulation.

Ps991’s method:

for (byte i = 0; i < 8; i++) {
    if ((value & (1 << i) == 0) {
        digitalWrite(i, 0);
    } else {
        digitalWrite(i, 1);
    }
}

bitRead:

for (byte i = 0; i < 8; i++) {
    if (bitRead(value, i) == 0) {
        digitalWrite(i, 0);
    } else {
        digitalWrite(i, 1);
    }
}

Direct Port Manipulation:

PORTD = value; // PORTD is the output register of pins 0-7 on an Arduino Uno and also the Controllino

Note: the Arduino Uno uses pins 0 and 1 for serial communication with the computer (to upload sketches and to do things like Serial.print() ), so if you use these pins as normal I/O, you can’t open a Serial connection at the same time.
Also, this Direct Port Manipulation example only works for the Uno or compatible boards, like the Controllino. And finally, your value should be of type byte, since there’s only 8 pins.

@PieterP

I tried your code.

But it is showing below error:

"Error compiling for board Controllino MINI"

What could be the cause?

Thank you

You'll have to post the entire error, just "Error compiling ..." doesn't say anything.

In file included from sketch\sketch_aug24c.ino.cpp:1:0:

C:\Users\Administrator\Documents\Arduino\sketch_aug24c\sketch_aug24c.ino: In function 'float GetSpeed(long unsigned int, long unsigned int, float)':

C:\Users\Administrator\Documents\Arduino\hardware\controllino\avr\cores\arduino/Arduino.h:103:46: error: invalid operands of types 'float' and 'byte {aka unsigned char}' to binary 'operator>>'

#define bitRead(value, bit) (((value) >> (bit)) & 0x01)

^

C:\Users\Administrator\Documents\Arduino\sketch_aug24c\sketch_aug24c.ino:60:9: note: in expansion of macro 'bitRead'

if (bitRead(KMH/tmp, i) == 0) {

^

exit status 1
Error compiling for board Controllino MINI.

Try this:

for (int i = 0; i < 8; i++) {
    if (bitRead((int) value, i) == 0) {
        digitalWrite(i, 0);
    } else {
        digitalWrite(i, 1);
    }
}

@PieterP

Thank you for your kind support.

Your code is working properly for Numerical(Decimal) values as I shown in attachment 1

But I need to convert it with string as shown in attachment 2

I can not enter manually numeric values everytime.

have attached code for your consideration.

Unbenannt.PNG

Unbenannt1.PNG

MPH.ino (1.86 KB)

String To Int

No, there’s just no need to convert it to a string, and even less need to convert it back from string to int: for the Arduino, 13 = B1101 = 0b1101 = B00001101 = 0b00000000001101 = 0xD =0x0D, it’s all the same.

If you really want the leading zeroes in your binary representation in the serial monitor, you can keep that piece of code, and the use of a string is fine, but you already have the speed as a float, so you can just output it like I said before. (But since you use the serial port, you can’t use pins 0 and 1).

#define FPS_to_KMH 1.09728 // scale factor
#define DISTANCE 7 // distance between the two sensors   in feet.

int SensorOnePin = A0;
int SensorTwoPin = A1;
int Byte1 = 4;
byte SensorOneState;
byte SensorTwoState;
float Speed = 0, KMH = 0, tmp = 0;
boolean GotSecondSensor = false;
unsigned long SensorOne_timer = 0, SensorTwo_timer = 0;

void setup()
{
  Serial.begin(9600);
  pinMode(SensorOnePin, INPUT);
  pinMode(SensorTwoPin, INPUT);
  pinMode(Byte1, OUTPUT);
  DDRD = B11111100 | DDRD; // Data Direction Register D (pins 0-7): all outputs, but keep pins 0 and 1 how they are (Serial connection)
}

void loop()
{
  SensorOneState = digitalRead(SensorOnePin);
  SensorTwoState = digitalRead(SensorTwoPin);

  if (SensorOneState && GotSecondSensor == false) // Train drives through first "sensor"
  {
    SensorOne_timer = millis(); // record time
    GotSecondSensor = true; // lockout this IF statement and unlock the next IF statement
  }

  if (SensorTwoState && GotSecondSensor == true)
  {
    SensorTwo_timer = millis(); //record the time the train reaches the second gate
    Speed = GetSpeed(SensorOne_timer, SensorTwo_timer, DISTANCE); // send the times and the distance into the function.
    PORTD = PORTD | (((uint8_t)Speed) << 2); // write the binary representation of the speed to digital pins 2-7
    Serial.print("KMH: ");
    Serial.println(Speed);
    GotSecondSensor = false; // unlock first IF statement and lockout this IF statement.
  }
}

float GetSpeed(unsigned long T1, unsigned long T2, float distance)
{
  KMH = distance * (FPS_to_KMH); // "(FPS_to_MPH)" -> conversion factor, feet per second to miles per hour
  tmp = (T2 - T1) / 1000.00; // since the time we are using is in milliseconds, we need to convert milliseconds to seconds
  Serial.print("Time (seconds): ");
  Serial.println(tmp);

  int myNum = KMH / tmp;
  int zeros = String(myNum, BIN).length();
  String myStr;
  for (int i = 0; i < zeros; i++)
    myStr = myStr + "0";

  myStr = myStr + String(myNum, BIN);
  Serial.print("Binar Codiert :");
  Serial.println(myStr);

  return (KMH / tmp); //return the speed of the car in MPH
}

Note: DDRD = B11111100 | DDRD; is equivalent to

pinMode(2,OUTPUT);
pinMode(3,OUTPUT);
pinMode(4,OUTPUT);
pinMode(5,OUTPUT);
pinMode(6,OUTPUT);
pinMode(7,OUTPUT);

I agreed with you.

There is no need to convert into string

I did it without string and getting result as I want.

Thank you

#define FPS_to_KMH 1.09728 // scale factor
#define DISTANCE 7 // distance between the two sensors   in feet.
#define LED1 4  //  constants LED Pin numbers
#define LED2 5
#define LED3 6
#define LED4 7
#define LED5 8


int SensorOnePin = A0;
int SensorTwoPin = A1;

byte SensorOneState;
byte SensorTwoState;
float Speed = 0, KMH = 0, tmp = 0;
boolean GotSecondSensor = false;
unsigned long SensorOne_timer = 0, SensorTwo_timer = 0;

void setup()
{
 Serial.begin(9600);
 pinMode(SensorOnePin, INPUT);
 pinMode(SensorTwoPin, INPUT);
 pinMode(LED1, OUTPUT);
 pinMode(LED2, OUTPUT);
 pinMode(LED3, OUTPUT);
 pinMode(LED4, OUTPUT);
 pinMode(LED5, OUTPUT);
 
}

void loop()
{
 SensorOneState = digitalRead(SensorOnePin);
 SensorTwoState = digitalRead(SensorTwoPin);

 if(SensorOneState && GotSecondSensor == false)  // Train drives through first "sensor"
 {
   SensorOne_timer = millis(); // record time
   GotSecondSensor = true; // lockout this IF statement and unlock the next IF statement
 }
 
 if(SensorTwoState && GotSecondSensor == true)
 {
   SensorTwo_timer = millis(); //record the time the train reaches the second gate
   Speed = GetSpeed(SensorOne_timer, SensorTwo_timer, DISTANCE); // send the times and the distance into the function.
   Serial.print("Geschwindigkeit im KM/H: ");
   Serial.println(Speed);
   GotSecondSensor = false; // unlock first IF statement and lockout this IF statement.
 }
}

int GetSpeed(unsigned long T1, unsigned long T2, float distance)
{
 KMH = distance * (FPS_to_KMH); // "(FPS_to_MPH)" -> conversion factor, feet per second to miles per hour
 tmp = (T2 - T1)/1000.00; // since the time we are using is in milliseconds, we need to convert milliseconds to seconds
 Serial.print("Time (seconds): ");
 Serial.println(tmp);

  int myNum = KMH/tmp;
        
byte pins[5] = { LED1, LED2, LED3, LED4, LED5} ;
for (byte i = 0 ; i < sizeof(pins) ; i++)
    digitalWrite (pins[i], ( myNum & (1<<i)) != 0 ? HIGH : LOW) ;
 
 Serial.print("Binar Codiert :");
 Serial.println(myNum, BIN);
 Serial.println("Richtung : vordere");


return (myNum);
}