Missing one bit

I’m a beginner with arduino and programming. I’m trying to teach myself by creating some tasks for exercise only.

I have a pot at A0 so I can get analogread 0-1023. Now I try to convert this decimal value to binary by a loop of successive modulo divisions.
My problem is, where is the last bit (LSB)? I use the Serial monitor to observe the result, the last “for” clause is for reversing the bits so I get the MSB to the left.

I’ve tried changing the number of steps in the loop etc. but it doesn’t help.

I guess there is some basic error in my reasoning, but I can’t see it.

void setup() {
  // put your setup code here, to run once:
Serial.begin (9600);
}

void loop() {
 int decimal = analogRead (A0);

Serial.print ( " : " );
Serial.println ( decimal );

 int binary;  
 int tmp;
 int myBins[10];

for (tmp=0; tmp<9; tmp++){
decimal = decimal/2;
binary = decimal%2;
 if ( binary > 0 )
    {
        myBins[tmp] =  1;
    }
    else
    {
       myBins[tmp] =  0;
    }
}
 int i;
 for(int i = 8; i >=0; i--)
{
  Serial.print(myBins[i]);
} 
delay ( 2000 );
}

You need to do the modulo operation before the division.

Great! Thank you!

Ankel:
I have a pot at A0 so I can get analogread 0-1023. Now I try to convert this decimal value to binary by a loop of successive modulo divisions.

WHY ?

The number is in binary inside the Arduino already.

...R

Hi,
Put this line in your code after Serial.println ( decimal );

for (int i = 9; i >= 0; i--)
  {
    Serial.print(bitRead(decimal, i));
  }
  Serial.println();

Tom... :slight_smile:

My task was to learn how to handle "for" statements and modulo division but now I learned something about Bitread as well :slight_smile:

Thank you all.