Binary / Hex counter.

Hi all. Picked up my board 5 days ago and enjoyed playing with LED chasers and LCD library. Here is a little test I put together over the weekend for a bit of fun. All it does is repeatedly count from 0 to 255 in either binary or hex and swaps display mode when the button is pressed.

Hardware setup is jut the LCD example from this site with a button wired onto pin 10.

Feel free to critique (constrictively! :slight_smile: ) and provide ideas of how this can be cleaned up. My next step is to move the conversion functions into a library for re-use in future projects.

/**
 *  Binary/Hex count with mode button.
 *  Some code courtesy of arduino.cc, rest is my own!
 */

/* include the library code: */
#include <string.h>
#include <LiquidCrystal.h>

/* Constants */
#define BIN 0
#define HEX 1 
#define BUTTONPIN   10
#define MAXVAL      256
#define BOUNCEDELAY 50
#define COUNTDELAY  1000

/* Initialize the library with the numbers of the interface pins */
LiquidCrystal lcd(12, 11, 5, 4, 3, 2);
byte countmode;
byte buttonstate;
byte prevstate;
byte current;
long int lastupdate;
long int currenttime;

void setup()
{
    /* set up the LCD's number of rows and columns */
    lcd.begin(16, 2);

    /* Configure the pushbutton pin */
    pinMode(BUTTONPIN, INPUT);

    /* Initialise variable values */
    lastupdate = 0;
    prevstate = LOW;
    countmode = BIN;
    current = 0;

    /* Print a message to the LCD */
    printheader(countmode);
}

void loop()
{
    /* Handle the button */
    buttonstate = digitalRead(BUTTONPIN);

    if (buttonstate != prevstate)
    {
        /* Pause to allow noise to pass */
        delay(BOUNCEDELAY);

        if (buttonstate == HIGH)
        {
            /* Switch modes */
            lcd.clear();
            countmode = !countmode;
            printheader(countmode);
            prevstate = HIGH;
        }
        else
            prevstate = LOW;
    }

    printval(current, countmode);

    currenttime = millis();
    if (currenttime - lastupdate > COUNTDELAY)
    {
      lastupdate = currenttime;
      current = (current + 1) % MAXVAL;
    }
      
}

void tobin(int dec, char *bin)
{
    byte bitval = 128;

    for (byte count = 0; count < 8; count++)
    {
        if (dec & bitval)
            bin[count] = '1';
        else
            bin[count] = '0';

        bitval >>= 1;
    }

    bin[8] = '\0';

}

void tohex(int toprint, char *hex)
{
    hex[0] = hexchar(toprint >> 4);
    hex[1] = hexchar(toprint & 0x0f);
    hex[2] = 0;
}

char hexchar(char inval)
{
    if (inval <= 9)
        return inval + 48;
    else
        return inval + 55;
}

void printheader(byte mode)
{
    if (mode == BIN)
        lcd.print("Binary Counter");
    else
        lcd.print("Hex Counter   ");
}

void printval(int val, byte mode)
{
    char bitstring[9];
    
    lcd.setCursor(0, 1);

    if (mode == BIN)
        tobin(val, bitstring);
    else
        tohex(val, bitstring);

    lcd.print(bitstring);
}