Logic of the function 'number()' used in USBHOSTHidKdb firmware code

StackOverflow https://stackoverflow.com/questions/19581999

  •  01-07-2022
  •  | 
  •  

Вопрос

I was looking for Keyboard firmware codes on FTDI website. I came across few codes such as USBHostHIDKdb, USBHostHID and USBHostHid2. In all the firmware codes I have noticed number function. But I am not getting the logic of it. Below I have written its code. Please check it and help me understand its logic.

/*
** number
**
** Print a character in the terminal application.
**
** Parameters:  val - Byte to be printed
** Returns: void
** Comments:
*/
void number(unsigned char val)
{
    unsigned char nibble;

    nibble = (val >> 4) + '0';
    if (nibble > '9') nibble += ('A' - '9' - 1);

    vos_dev_write(hUART, &nibble, (uint16) 1, NULL);

    nibble = (val & 15) + '0';
    if (nibble > '9') nibble += ('A' - '9' - 1);

    vos_dev_write(hUART, &nibble, (uint16) 1, NULL);
}

Function where number() is used in USBHostHIDkdb.c. The code attaches driver to the host. And writes the keyboard usage ids to the UART when the key stroke event happens.

void firmware()
{

    do
    {
        open_drivers();

        if (status == PORT_STATE_ENUMERATED)
        {
            message("Enumeration complete\r\n");

            attach_drivers();

            // get report descriptor code, set idle code, get idle code

if (status == USBHOSTHID_OK) { while (1) { if (vos_dev_read(hUSBHOST_HID, buf, 8, &num_read) == USBHOSTHID_OK) {

                        for (byteCount = 0; byteCount < num_read; byteCount++)
                        {
                            number(buf[byteCount]);
                        }
                        message(eol);
                    }

                }
                }

} while (1);

}

Это было полезно?

Решение

number() takes a byte, and writes its value in hex (as two characters).

Let's examine some parts of the code.

The following extract the high nibble of val:

(val >> 4)

The following extract the low nibble of val:

(val & 15)

The following coverts a value between 0 and 15 to the hex digit (0..9, A..F):

nibble = (...) + '0';
if (nibble > '9') nibble += ('A' - '9' - 1);
Лицензировано под: CC-BY-SA с атрибуция
Не связан с StackOverflow
scroll top