This post is older than 2 years and might not be relevant anymore
More Info: Consider searching for newer posts

AN36 charcteristics clarification

    
    attr_char_value.p_uuid       = &ble_uuid;
    attr_char_value.p_attr_md    = &attr_md;
    attr_char_value.init_len     = sizeof(uint8_t);
    attr_char_value.init_offs    = 0;
    attr_char_value.max_len      = sizeof(uint8_t);
    attr_char_value.p_value      = NULL;

This is original code used for both LED and BUTTON characteristis. It this replacement is valid( the way I understand the intend)?


typedef enum {LED_OFF, LED_ON} led_state_t; 
...
    attr_char_value.init_len     = sizeof(led_state_t);
    attr_char_value.max_len      = sizeof(led_state_t);
...
typedef enum {BUTTON_PRESSED, BUTTON_RELEASED } button_state_t; 
...
    attr_char_value.init_len     = sizeof(button_state_t);
    attr_char_value.max_len      = sizeof(button_state_t);
...

I do realize that using enum makes such types compiler and its options dependent and using uint8_t may save memory. There are other possible implementations like typedef bool led_state_t; or even typedef uint8_t led_state_t; and so on but at least I can see what exactly type is used and don't hyave to guess what uint8_t is representing is every case.

Thank you.

  • This would most definitely be possible, and I agree that it makes the code look nicer.

    However, remember that the value actually used must be the same as the peer device uses. What you're actually defining here is what value the peer device have to send over the air to set the LED, and hence I'd say that it makes more sense to use a uint8_t directly instead of an enum or a bool, since that makes it explicit what size value you should send from the Central device to this characteristic.

    For your own applications, you can define this in any way you want.

  • "... it makes more sense to use a uint8_t directly" Disagree. If the characteristic is commonly known/used that it has been already defined/templated. If not than it is proprietary anyways and as you've said "For your own applications, you can define this in any way you want". Using customized type via shared .h file is as a good common practice.
    I did also suggest a compromise:
    typedef uint8_t led_state_t; which do not change anything but do indeed make code nicer and which is more important readable and understandable. Thank you.

Related