I need to write a program that takes a user inputted HEX value and converts it to binary, then an LED blinks according to the number of 1's in the binary. For instance, if the value is 0xABC then there are number of 1's are 7 so LED will blink 7 times.
I only just started Arduino so not sure how to let user input a value nor do I know how to convert HEX to BIN but I'm assuming that once I convert the HEX to BIN I can just use a loop to count the number of 1's yet I'm unsure as to actually how to do that. This is what I've written so far.
byte val=0xABC;
int ledPin=13;
int countSetBits(unsigned int n)
{
unsigned int c;
for (c=0;n>0;n=n&(n-1))
c++;
return c;
}
void blink(int n)
{
for (int i = 0; i < n; i++)
{
digitalWrite(ledPin,HIGH);
delay(500);
digitalWrite(ledPin, LOW);
delay(500);
}
}
void setup()
{
Serial.begin(9600);
pinMode(ledPin,OUTPUT);
blink(countSetBits(val));
}
void loop()
{ }
Any help would be appreciated. EDIT: If I want to take a number from a user and then make the LED blink according to the number of 1's in its binary form, how would I implement that?
byte val=0xABC;
that's not going to fit in a byte. Use an int instead (int val=0xABC;
)