Search code examples
c++arduinoesp32

How can I assign a const unsigned char value to a variable inside a condition in c++?


I am using C++ for programming a microcontroller, and I have this situation.

I have several const unsigned char in a .h file. Ex:

const unsigned char epd_bitmap_icon1 [] = {...
const unsigned char epd_bitmap_icon2 [] = {...

I have a function that takes one of this variables:

void drawBitmap(int16_t x, int16_t y, uint8_t *bitmap, int16_t w, int16_t h, uint16_t color);

In this case, I need to conditionally pass a different bitmap based on a certain value.

In python would be something like this:

if value > 80:
    icon = epd_bitmap_icon1
elif value > 30:
    icon = epd_bitmap_icon2
else:
    icon = edp_bitmap_icon3

and later pass the icon value to drawBitmap as the third argument.

I don't know how to do it in C++, I have tried this:

    if (batteryChargePercent > 80) {
        unsigned char* icon = epd_bitmap_icon1;
    }
    else if (batteryChargePercent > 30) {
        unsigned char* icon = epd_bitmap_icon2;

    } else {
        unsigned char* icon = epd_bitmap_icon3;
    }

But I get this error:

error: invalid conversion from 'const unsigned char*' to 'unsigned char*' [-fpermissive]

Solution

  • Declare the variable once outside the if, and assign it in the if.

    const unsigned char *icon;
    if (batteryChargePercent > 80) {
        icon = epd_bitmap_icon1;
    } else if (batteryChargePercent > 30) {
        icon = epd_bitmap_icon2;
    } else {
        icon = epd_bitmap_icon3;
    }
    

    You need to use const in the pointer declaration to solve the error message.