prettyprint

2023年8月6日 星期日

[Raspberry Pi Pico] nRF24L01+ Ep. 2 : Various types of network topologies

 本文章介紹nRF24L01(+)除了標準的Multiceiver的網路應用外,另外實作

  1. One PTX and multi PRX. 
  2. One PTX broadcast to multi PRX
  3. PTX & PRX role exchange: packet transmission of ring or ping-pong type。
nRF24L01簡介與驅動程式,請參閱前篇文章說明。 
  • 成果影片:



一、Multiceiver:

multiceiver.c
 #include <stdio.h>
#include "pico/stdlib.h"
#include "nRF24L01.h"
#include "string.h"

//#define RECV_NODE   // define for PRX

uint8_t transnode=1;  //PTX node 0 ~ 5

uint8_t role;
uint8_t can_send=false;
uint8_t send_buffer[33];

uint8_t addr[6][5] = {"0node", "1node", "2node","3node","4node","5node"};

uint8_t send_buffer[33];
uint32_t cnt=0;

void irq_callback(uint8_t event_type, uint8_t datapipe, uint8_t* data, uint8_t width) {
    static uint32_t ack_payload=0;
    uint8_t ack_buff[15];
      switch(event_type) {
        case EVENT_RX_DR:
                data[width]='\0';
                printf("RECV== pipe:%d, width:%d, %s\n", datapipe, width, data);
                gpio_put(datapipe*2, !gpio_get(datapipe*2));
        break;
        case EVENT_TX_DS:
            can_send=true;
            printf("event_data_sent:%d\n", datapipe);
        break;
        case EVENT_MAX_RT:
        //nRF24_flush_tx();
        //can_send=true;
        busy_wait_ms(2);
        printf("event_max_rt:%d, can_sent:%d\n", datapipe, can_send);
        break;
    }
}



void keydown() {
    if (gpio_get_irq_event_mask(15) == GPIO_IRQ_EDGE_RISE) {
        gpio_acknowledge_irq(15, GPIO_IRQ_EDGE_RISE);
        gpio_set_irq_enabled(15, GPIO_IRQ_EDGE_RISE, false);
        
        nRF24_write_payload(send_buffer,strlen(send_buffer));
        sprintf(send_buffer, "keydown");
        busy_wait_ms(100);
        can_send=true;
        
        //gpio_set_irq_enabled(gpio, event_mask, true);
        printf("keydown:%s\n",send_buffer);
        gpio_set_irq_enabled(15,GPIO_IRQ_EDGE_RISE, true);
    }
    //gpio_set_irq_enabled(gpio,GPIO_IRQ_EDGE_FALL, true);
    

}

int main()
{
    stdio_init_all();
    sleep_ms(2000);
    gpio_init(2);
    gpio_init(4);
    gpio_init(6);

    gpio_set_dir(2, true);
    gpio_set_dir(4, true);
    gpio_set_dir(6, true);

    uint8_t status;
    nRF24_spi_default_init(20, 21, irq_callback);
    //nRF24_set_RF_channel(0x1F);
    #ifdef RECV_NODE
        role=RECEIVER;
    #else   
        role = TRANSMITTER;
    #endif
    nRF24_config_mode(role);

    nRF24_enable_feature(FEATURE_EN_DPL, true);
    //nRF24_enable_feature(FEATURE_EN_ACK_PAY, true);
    //nRF24_enable_feature(FEATURE_EN_DYN_ACK, true);
#ifdef RECV_NODE
    nRF24_enable_RXADDR(0b00001111);
    nRF24_set_RX_addr(0, addr[0], 5);
    nRF24_set_RX_addr(1, addr[1], 5);
    nRF24_set_RX_addr(2, addr[2], 5);
    nRF24_set_RX_addr(3, addr[3], 5);

    nRF24_enable_data_pipe_dynamic_payload_length(0, true);
    nRF24_enable_data_pipe_dynamic_payload_length(1, true);
    nRF24_enable_data_pipe_dynamic_payload_length(2, true);
    nRF24_enable_data_pipe_dynamic_payload_length(3, true);
#else
    nRF24_set_TX_addr(addr[transnode], 5);
    nRF24_set_RX_addr(0, addr[transnode], 5);
    nRF24_enable_data_pipe_dynamic_payload_length(0, true);

    gpio_pull_down(15);
    gpio_add_raw_irq_handler(15, keydown);
    gpio_set_irq_enabled(15, GPIO_IRQ_EDGE_RISE, true);
    
#endif

    can_send=false;
     while(1) {
#ifndef RECV_NODE

if (can_send) {
    can_send=false;

    nRF24_write_payload(send_buffer, strlen(send_buffer));


}
#endif

      tight_loop_contents();
        
    }

    return 0;
}
CMakeLists.txt
 # Generated Cmake Pico project file

cmake_minimum_required(VERSION 3.13)

set(CMAKE_C_STANDARD 11)
set(CMAKE_CXX_STANDARD 17)

# Initialise pico_sdk from installed location
# (note this can come from environment, CMake cache etc)
set(PICO_SDK_PATH "/home/duser/pico/pico-sdk")

set(PICO_BOARD pico CACHE STRING "Board type")

# Pull in Raspberry Pi Pico SDK (must be before project)
include(pico_sdk_import.cmake)

if (PICO_SDK_VERSION_STRING VERSION_LESS "1.4.0")
  message(FATAL_ERROR "Raspberry Pi Pico SDK version 1.4.0 (or later) required. Your version is ${PICO_SDK_VERSION_STRING}")
endif()

project(nRF24L01 C CXX ASM)

# Initialise the Raspberry Pi Pico SDK
pico_sdk_init()

# Add executable. Default name is the project name, version 0.1

add_executable(nRF24L01 multiceive.c )

pico_set_program_name(nRF24L01 "nRF24L01")
pico_set_program_version(nRF24L01 "0.1")

pico_enable_stdio_uart(nRF24L01 0)
pico_enable_stdio_usb(nRF24L01 1)

# Add the standard library to the build
target_link_libraries(nRF24L01
        pico_stdlib)

# Add the standard include files to the build
target_include_directories(nRF24L01 PRIVATE
  ${CMAKE_CURRENT_LIST_DIR}
  ${CMAKE_CURRENT_LIST_DIR}/.. # for our common lwipopts or any other standard includes, if required
)

# Add any user requested libraries
target_link_libraries(nRF24L01 
        hardware_spi
        )

add_subdirectory(nRF24L01)
target_link_libraries(nRF24L01
        nRF24L01_drv)
pico_add_extra_outputs(nRF24L01)
二、One PTX and multi PRX
1_T_n_R.c
 #include <stdio.h>
#include "pico/stdlib.h"
#include "nRF24L01.h"
#include "string.h"

#define SENDER  // define for one PTX

uint8_t node_id=2;  // define for PRX node 0~5

uint8_t role;
uint8_t can_send=false;
uint8_t send_buffer[33];

uint8_t addr[5][5] = {"0node", "1node", "2node","3node","4node", "5node"};


void irq_callback(uint8_t event_type, uint8_t datapipe, uint8_t* data, uint8_t width) {
    static uint32_t ack_payload=0;
    uint8_t ack_buff[15];
      switch(event_type) {
        case EVENT_RX_DR:
            data[width]='\0';
            printf("RECV== pipe:%d, width:%d, %s\n", datapipe, width, data);
            gpio_put(2, !gpio_get(2));
        break;
        case EVENT_TX_DS:
        //can_send=true;
            printf("event_data_sent:%d\n", datapipe);
        break;
        case EVENT_MAX_RT:
        //nRF24_flush_tx();
        //can_send=true;
        printf("event_max_rt:%d, can_sent:%d\n", datapipe, can_send);
        break;
    }
}



void keydown() {
    uint8_t irq_pin=0;
    
    if (gpio_get_irq_event_mask(13) == GPIO_IRQ_EDGE_RISE) {
        irq_pin=13;
        nRF24_set_TX_addr(addr[0],5);
        nRF24_set_RX_addr(0, addr[0],5);
    }
    if (gpio_get_irq_event_mask(14) == GPIO_IRQ_EDGE_RISE) {
        irq_pin=14;
        nRF24_set_TX_addr(addr[1],5);
        nRF24_set_RX_addr(0, addr[1],5);
    }
    if (gpio_get_irq_event_mask(15) == GPIO_IRQ_EDGE_RISE) {
        irq_pin=15;
        nRF24_set_TX_addr(addr[2],5);
        nRF24_set_RX_addr(0, addr[2],5);
    }
    if (irq_pin == 13 || irq_pin==14 || irq_pin==15) {
        gpio_acknowledge_irq(irq_pin, GPIO_IRQ_EDGE_RISE);
        gpio_set_irq_enabled(irq_pin,GPIO_IRQ_EDGE_RISE, false);
        nRF24_write_payload(send_buffer,strlen(send_buffer));
        sprintf(send_buffer, "keydown");
        busy_wait_ms(100);
        can_send=true;

        printf("keydown:%s\n",send_buffer);
        gpio_set_irq_enabled(irq_pin,GPIO_IRQ_EDGE_RISE, true);
    }
    

}

int main()
{
    stdio_init_all();
    sleep_ms(2000);
    gpio_init(2);
    gpio_init(4);
    gpio_init(6);

    gpio_set_dir(2, true);
    gpio_set_dir(4, true);
    gpio_set_dir(6, true);

    uint8_t status;
    nRF24_spi_default_init(20, 21, irq_callback);

    //nRF24_set_RF_channel(0x1F);

    #ifdef SENDER
        role = TRANSMITTER;
    #else   
        role=RECEIVER;
    #endif
    nRF24_config_mode(role);

    nRF24_enable_feature(FEATURE_EN_DPL, true);
    //nRF24_enable_feature(FEATURE_EN_ACK_PAY, true);
    //nRF24_enable_feature(FEATURE_EN_DYN_ACK, true);
#ifdef SENDER
    nRF24_enable_data_pipe_dynamic_payload_length(0, true);
    gpio_pull_down(13);
    gpio_add_raw_irq_handler(13, keydown);
    gpio_set_irq_enabled(13, GPIO_IRQ_EDGE_RISE, true);
    
    gpio_pull_down(14);
    gpio_set_irq_enabled(14, GPIO_IRQ_EDGE_RISE, true);
    gpio_pull_down(15); 
    gpio_set_irq_enabled(15, GPIO_IRQ_EDGE_RISE, true);


#else
    nRF24_set_RX_addr(0, addr[node_id], 5);
    nRF24_enable_data_pipe_dynamic_payload_length(0, true);
    
#endif
   
    can_send=true;
    while(1) {
#ifndef RECV_NODE

//if (can_send) {
//    can_send=false;
//    printf("send\n");
 // nRF24_write_payload("keydown",7);
  
////   sleep_ms(500);
//}
#endif
      tight_loop_contents();
        
    }

    return 0;
}

三、Broadcast:

broadcast.c
 #include <stdio.h>
#include "pico/stdlib.h"
#include "nRF24L01.h"
#include "string.h"

//#define BROADCASTER  // define if BROADCASTER (PTX)

#define LED_PIN 2

uint8_t addr[5][5] = {"0ode1", "1node", "2node", "3node", "4node"};

uint8_t send_buffer[33];

void irq_callback(uint8_t event_type, uint8_t datapipe, uint8_t* data, uint8_t width) 
      switch(event_type) {
        case EVENT_RX_DR:
            gpio_put(LED_PIN, !gpio_get(LED_PIN));
            data[width]='\0';
            printf("RECV== pipe:%d, width:%d, %s\n", datapipe, width, data);
        break;
        case EVENT_TX_DS:
            printf("event_data_sent:%d\n", datapipe);
        break;
        case EVENT_MAX_RT:
            //nRF24_flush_tx();
            //can_send=true;
            printf("event_max_rt:%d\n", datapipe);
        break;
    }
}

void keydown() {
    if (gpio_get_irq_event_mask(15) == GPIO_IRQ_EDGE_RISE) {
        gpio_acknowledge_irq(15, GPIO_IRQ_EDGE_RISE);
        gpio_set_irq_enabled(15, GPIO_IRQ_EDGE_RISE, false);
        
        nRF24_write_payload(send_buffer,strlen(send_buffer));
        sprintf(send_buffer, "keydown");
        busy_wait_ms(100);
        //can_send=true;

        printf("keydown:%s\n",send_buffer);
        gpio_set_irq_enabled(15,GPIO_IRQ_EDGE_RISE, true);
    }
  

}

int main()
{
    stdio_init_all();
    sleep_ms(2000);
    
    gpio_init(LED_PIN);
    gpio_set_dir(LED_PIN, true);
    nRF24_spi_default_init(20, 21, irq_callback);

    nRF24_enable_feature(FEATURE_EN_DPL, true);
    //nRF24_enable_feature(FEATURE_EN_ACK_PAY, true);
#ifdef BROADCASTER
    nRF24_config_mode(TRANSMITTER);
    nRF24_enable_feature(FEATURE_EN_DYN_ACK, true);
    nRF24_set_TX_addr(addr[0], 5);

    gpio_pull_down(15);
    gpio_add_raw_irq_handler(15, keydown);
    gpio_set_irq_enabled(15, GPIO_IRQ_EDGE_RISE, true);
    
#else   
    nRF24_config_mode(RECEIVER);
#endif
    nRF24_set_RX_addr(0, addr[0], 5);
    nRF24_enable_data_pipe_dynamic_payload_length(0, true);

    uint32_t dc=0;
    uint8_t send_buffer[32];
    uint32_t count=0;
    
    while(1) {
      
#ifdef BROADCASTER
        //sprintf(send_buffer, "broadcast:%d", count++);
        //count %=10000;
        //nRF24_write_payload_no_ack(send_buffer,strlen(send_buffer));     
#endif
       
        sleep_ms(500);

    }

    return 0;
}

四、PTX & PRX role swap: ping-pong mode


 #include <stdio.h>
#include "pico/stdlib.h"
#include "nRF24L01.h"
#include "string.h"

#define LED_PIN 2

#define NODE_A

uint8_t addr_a[2][5] = {"1a---", "2a---"};
uint8_t addr_b[2][5] = {"1b---", "2b---"};
bool can_send=true;
uint8_t role, new_role;

void irq_callback(uint8_t event_type, uint8_t datapipe, uint8_t* data, uint8_t width) {

      switch(event_type) {
        case EVENT_RX_DR:
            data[width]='\0';
            printf("RECV== pipe:%d, width:%d, %s\n", datapipe, width, data);
            gpio_put(LED_PIN, true);
            can_send=true;
            new_role = TRANSMITTER;
        break;
        case EVENT_TX_DS:
        puts("TX_DS");
            new_role=RECEIVER;
            gpio_put(LED_PIN, false);
            can_send=false;
        break;
        case EVENT_MAX_RT:
        //nRF24_flush_tx();
        //can_send=true;
        //printf("event_max_rt:%d, can_sent:%d\n", datapipe, can_send);
        break;
    }
}




int main()
{
    stdio_init_all();
    gpio_init(LED_PIN);
    gpio_set_dir(LED_PIN, true);

    uint8_t status;
    nRF24_spi_default_init(20, 21, irq_callback);
    #ifdef NODE_A
    role=TRANSMITTER;
    new_role=TRANSMITTER;
    nRF24_config_mode(TRANSMITTER);
    can_send=true;

    nRF24_set_TX_addr(addr_b[0], 5);
    nRF24_set_RX_addr(0, addr_b[0], 5);
    nRF24_set_RX_addr(1, addr_a[0], 5);
    #else
    role = RECEIVER;
    new_role = RECEIVER;
    nRF24_config_mode(RECEIVER);
    can_send=false;

    nRF24_set_TX_addr(addr_a[0], 5);
    nRF24_set_RX_addr(0, addr_a[0], 5);
    nRF24_set_RX_addr(1, addr_b[0], 5);
    #endif

    nRF24_enable_feature(FEATURE_EN_DPL, true);
 
    uint32_t count=0;
    uint8_t send_buff[32];
  
    nRF24_enable_data_pipe_dynamic_payload_length(0, true);
    nRF24_enable_data_pipe_dynamic_payload_length(1, true);
   
    uint32_t dc=0;
    while(1) {
        if (role != new_role) {
            role = new_role;
            nRF24_config_mode(role);
        }
        if (can_send && role==TRANSMITTER) {
            can_send=false;
            sprintf(send_buff, "0:abcdefgh%d", count++);
            count %=10000;
            nRF24_write_payload(send_buff,strlen(send_buff)); 
        }
    
        sleep_ms(500);
    }

    return 0;
}

五、PTX & PRX role swap: ring mode


 #include <stdio.h>
#include "pico/stdlib.h"
#include "nRF24L01.h"
#include "string.h"

#define LED_PIN 2
uint8_t node_id=3;  // node id: 0~5 for each node
uint8_t total_nodes=4; // total nodes in the ring 
uint8_t addr[6][5] = {"0node","1node", "2node", "3node", "4node", "5node"};
bool can_send=false;
uint8_t role, new_role;

void irq_callback(uint8_t event_type, uint8_t datapipe, uint8_t* data, uint8_t width) {
    static uint32_t ack_payload=0;
    uint8_t ack_buff[15];
      switch(event_type) {
        case EVENT_RX_DR:
            gpio_put(LED_PIN, true);
            data[width]='\0';
            printf("RECV== pipe:%d, width:%d, %s\n", datapipe, width, data);
            can_send=true;
            new_role = TRANSMITTER;
        break;
        case EVENT_TX_DS:
        puts("TX_DS");
            new_role=RECEIVER;
            gpio_put(LED_PIN, false);
            can_send=false;
        break;
        case EVENT_MAX_RT:
        //nRF24_flush_tx();
        //can_send=true;
        //printf("event_max_rt:%d, can_sent:%d\n", datapipe, can_send);
        break;
    }
}




int main()
{
    stdio_init_all();
    
    gpio_init(LED_PIN);
    gpio_set_dir(LED_PIN, true);

    uint8_t status;
    nRF24_spi_default_init(20, 21, irq_callback);
    if (node_id==0) { 
    role=TRANSMITTER;
    new_role=TRANSMITTER;
    nRF24_config_mode(TRANSMITTER);
    can_send=true;

    nRF24_set_TX_addr(addr[1], 5);
    nRF24_set_RX_addr(0, addr[1], 5);
    nRF24_set_RX_addr(1, addr[0], 5);
    } else {
        role = RECEIVER;
        new_role = RECEIVER;
        nRF24_config_mode(RECEIVER);
        can_send=false;
        nRF24_set_TX_addr(addr[(node_id+1)%total_nodes], 5);
        nRF24_set_RX_addr(0, addr[(node_id+1)%total_nodes], 5);
        nRF24_set_RX_addr(1, addr[node_id], 5);
    }

    nRF24_enable_feature(FEATURE_EN_DPL, true);
 
    uint32_t count=0;
    uint8_t send_buff[32];
  
    nRF24_enable_data_pipe_dynamic_payload_length(0, true);
    nRF24_enable_data_pipe_dynamic_payload_length(1, true);
   
    uint32_t dc=0;
    while(1) {
        if (role != new_role) {
            role = new_role;
            nRF24_config_mode(role);
        }
        if (can_send && role==TRANSMITTER) {
            can_send=false;
            sprintf(send_buff, "0:abcdefgh%d", count++);
            count %=10000;
            nRF24_write_payload(send_buff,strlen(send_buff)); 
        }
    
        sleep_ms(500);
    }

    return 0;
}

[Raspberry Pi Pico] nRF24L01+ Ep. 1 : Pico-SDK C-code driver using IRQ

本文章介紹Raspberry Pi Pico 的nRF24L01(+) C code驅動程式製作,以利於在Pico SDK開發環境下使用。

本驅動程式需要使用nRF24L01(+)上的IRQ pin。

當有Payload發送或接收後觸發interrupt,取代polling以節省CPU時間。

一、nRF24L01產品規格簡要介紹與使用驅動程式相對應指令。 

  1. 收發角色:
    Primary Transmitter(PTX):發送角色。
    Primary Receiver(PRX): 接收角色。
    使用本驅動程式function:
    nRF24_config_mode(role) 1: PRX, 0:PTX。
  2. 定址方式:分為3,4或5byte長度,在REGISTER SETUP_AW(0x03)中定義。
    nRF24_set_address_width(uint8_t aw)
    RX Address:共有6 data pipes,意即可同時接收6 個data pipes,在RX_ADDR_P0(0x0A)、RX_ADDR_P1(0x0B)、RX_ADDR_P2(0x0C)、RX_ADDR_P3(0x0D)、RX_ADDR_P4(0x0E)、RX_ADDR_P5(0x0F)中定義,RX_ADDR_P2~P5 register為一個byte長度,高位元4bytes同RX_ADDR_P1。如下圖所示。
    function: 
    nRF24_set_RX_addr(uint8_t data_pipe, uint8_t *addr, uint8_t len);
    TX address:一般定義同為RX_ADDR_P0。
    nRF24_set_TX_addr(uint8_t *addr, uint8_t len);

    (source from nRF24L01 Product Specification)
    PTX與PRX如下圖:

    (source from nRF24L01 Product Specification)
  3. 傳送資料格式:分為static 與dynamic payload。如下圖所示:
    Dynamic Payload length在packet Control Field的前6 bits定義。(source from nRF24L01 Product Specification)
    Static payload:
    nRF24_set_recv_payload_width();
    Dynamic payload:
    (a) enable feature:
        nRF24_enable_feature(FEATURE_EN_DPL, true)
    (b) enable data pipe: 
         nRF24_enable_data_pipe_dynamic_payload_length(uint8_t data_pipe, bool enable);
    (c) 接收端取得dynamic payload width:
        nRF24_get_RX_payload_width(uint8_t *width)
    (d)發送端亦需設定  data pipe 0:
         nRF24_enable_data_pipe_dynamic_payload_length(0, true)

  4. SPI read/write operations如下圖所示:
  5. 有資料接收時nRF24L01 IRQ pin active low。
    nRF24_spi_default_init(20, 21, irq_callback);
    irq_callback為user自行定義。用於處理RX_RD(receive data ready), TX_DS(transmitter data sent), MAX_RT(Maximum number of TX retransmits interrupt
    )
    範例:
     void irq_callback(uint8_t event_type, uint8_t datapipe, uint8_t* data, uint8_t width) {
        static uint32_t ack_payload=0;
        uint8_t ack_buff[15];
          switch(event_type) {
            case EVENT_RX_DR:
                ...(data: received data, width: data width)
            break;
            case EVENT_TX_DS:
                ...(data sent)
            break;
            case EVENT_MAX_RT:
            //nRF24_flush_tx();
                ...
            break;
        }
    }
    若程式中有使用GPIO IRQ請使用下列設定 gpio irq:
    void user_gpio_irq_handler {
        if (gpio_get_irq_event_mask(gpio_no) == (enum gpio irq level) {
            gpio_acknowledge_irq(gpio_no, (enum gpio irq level));
            gpio_set_irq_enabled(gpio_no, (enum gpio irq level), false);
                ...
            gpio_set_irq_enabled(gpio_no, (enum gpio irq level), true);
        }
    }
    
    
    gpio_add_raw_irq_handler(gpio_no, user_gpio_irq_handler);
    gpio_set_irq_enabled(gpio_no, (enum) gpio_irq_level, true);

二、使用驅動程式範例

下列為簡要主程式結構,其他nRF24L01(+)網路拓撲(network topology)應用範例將在下一篇文章介紹。
  • 主程式範例:
 #include <stdio.h>
#include "pico/stdlib.h"
#include "nRF24L01.h"
#include "string.h"

#define TX_MODE
uint8_t role;
uint8_t addr[5][5] = {"0node", "1node", "2node","3node","4node"};

void irq_callback(uint8_t event_type, uint8_t datapipe, uint8_t* data, uint8_t width) {
      switch(event_type) {
        case EVENT_RX_DR:
            
        break;
        case EVENT_TX_DS:
        
        break;
        case EVENT_MAX_RT:
        //nRF24_flush_tx();
        
        break;
    }
}

void user_gpio_irq_handler() {
    if (gpio_get_irq_event_mask(gpio_no) == (enum gpio irq level) {
        gpio_acknowledge_irq(gpio_no, (enum gpio irq level));
        gpio_set_irq_enabled(gpio_no, (enum gpio irq level), false);
           // ...
        gpio_set_irq_enabled(gpio_no, (enum gpio irq level), true);
    }
}

int main()
{
    stdio_init_all();
    
    nRF24_spi_default_init(20, 21, irq_callback);

#ifdef TX_MODE
        role=TRANSMITTER;
#else   
        role = RECEIVER;
#endif
    nRF24_config_mode(role);
    nRF24_enable_feature(FEATURE_EN_DPL, true);
    //nRF24_enable_feature(FEATURE_EN_ACK_PAY, true);
    //nRF24_enable_feature(FEATURE_EN_DYN_ACK, true);
#ifdef TX_MODE
    nRF24_set_TX_addr(addr[0], 5);
    nRF24_set_RX_addr(0, addr[0], 5);
    nRF24_enable_data_pipe_dynamic_payload_length(0, true);
#else
   nRF24_enable_RXADDR(0b00001111);
    nRF24_set_RX_addr(0, addr[0], 5);
    nRF24_set_RX_addr(1, addr[1], 5);
    nRF24_set_RX_addr(2, addr[2], 5);
    nRF24_set_RX_addr(3, addr[3], 5);
    nRF24_enable_data_pipe_dynamic_payload_length(0, true);
    nRF24_enable_data_pipe_dynamic_payload_length(1, true);
    nRF24_enable_data_pipe_dynamic_payload_length(2, true);
    nRF24_enable_data_pipe_dynamic_payload_length(3, true);
#endif
     
    while(1) {
      
        
    }

    return 0;
}
  • 主程式CMakeLists.txt 包含:
add_subdirectory(project_name)
target_link_libraries(project_name
        nRF24L01_drv) 

三、程式碼:

  • nRF24L01.c
 #include <stdio.h>
#include "pico/stdlib.h"
#include "nRF24L01.h"
#include "string.h"


// SPI Defines
// We are going to use SPI 0, and allocate it to the following GPIO pins
// Pins can be changed, see the GPIO function select table in the datasheet for information on GPIO assignments
static spi_inst_t*  SPI_PORT= spi0;
static uint PIN_MISO=16;
static uint PIN_CS=17;
static uint PIN_SCK=18;
static uint PIN_MOSI=19;
static uint SPI_SPEED=1000*1000;
static uint nRF24_CE;
static uint nRF24_IRQ;

nRF24_irq_callback_t nRF24_callback;
static uint8_t nRF24_data_buffer[260];

static void nRF24_standby_to_txrx_mode();
static void nRF24_standby_I();
static uint8_t nRF24_fifo_rx_full(uint8_t *full);
static uint8_t nRF24_fifo_tx_empty(uint8_t *empty);
static uint8_t nRF24_fifo_rx_empty(uint8_t *empty);

/*!
* \brief nRF24L01 IRQ callback function
* \param gpio: gpio number
* \param event_mask
*/
static void gpio_irq_callback(uint gpio, uint32_t event_mask) {
    if (gpio == nRF24_IRQ && event_mask == GPIO_IRQ_EDGE_FALL) {
        gpio_acknowledge_irq(gpio, event_mask);
        //gpio_set_irq_enabled(gpio, GPIO_IRQ_LEVEL_LOW, false);
        uint8_t status;
        uint8_t event_type, datapipe;
        uint8_t data_buffer[32];
        uint8_t width;
        nRF24_status(&status);
        memset(nRF24_data_buffer,0, 32);
        datapipe = (status & 0x0E) >> 1;
        if ((status & 0x40) >> EVENT_RX_DR) {  // RX_DR
            event_type = EVENT_RX_DR;

           if (nRF24_get_RX_payload_width(&width)) {
                if (width > 32) { // in nRF24L01+ product specification
                    printf("...in driver width > 32 datapipe:%d:%d\n", datapipe, width);
                    nRF24_standby_I();  
                  
                    nRF24_flush_rx();       //
        
                    nRF24_standby_to_txrx_mode(); 
                }
                else {
                    nRF24_read_payload(nRF24_data_buffer, width);
                    nRF24_callback(event_type, datapipe, nRF24_data_buffer, width);
                }
                nRF24_clear_RX_DR();
            }
        }

        if ((status & 0x20) >> EVENT_TX_DS) {  // TX_DS
            event_type = EVENT_TX_DS;
            nRF24_callback(event_type, datapipe, nRF24_data_buffer, 0);
            nRF24_clear_TX_DS();
        }

        if ((status & 0x10) >> EVENT_MAX_RT) {  // MAX_RT
            event_type = EVENT_MAX_RT;
            nRF24_callback(event_type, datapipe, nRF24_data_buffer, 0);
            nRF24_clear_MAX_RT();
        }
        //gpio_set_irq_enabled(gpio, GPIO_IRQ_LEVEL_LOW, true);
    }
}
/*!
* \brief set nRF24L01 PWR_UP in CONFIG register
*/
static void nRF24_config_PWR_UP() {
    uint8_t ret;
    uint8_t mode;
    
    ret = nRF24_read_REGISTER(CONFIG, &mode,1);
    if (ret) {
        mode  |= (0x02);
        ret = nRF24_write_REGISTER(CONFIG, &mode,1);
    }
}

/*!
* \brief enable CE
* \param enable true: set CE high, false: set CE low
*/
static void nRF24_enable_CE(bool enable) {
    gpio_put(nRF24_CE, enable);
}

static void nRF24_standby_I() {
    nRF24_enable_CE(false);
}

/*!
* \brief nRF24L01 active FEATURE. nRF24L01+ does not need this function
*/
static uint8_t nRF24_activate() {
    uint8_t ret;
    uint8_t status;
    uint8_t cmd[2]={ACTIVATE, 0x73};
    
    nRF24_spi_enable(true);
    
    ret = spi_write_blocking(SPI_PORT, cmd, 2);
  
    nRF24_spi_enable(false);
    return ret;
}

/*!
* \brief 1. set SPI pin and initialize.  
*         2.set nRF24L01 to standby-I mode
* \param CE nRF24L01 CE pin no
* \param IRQ nRF24L01 IRQ pin no
* \param callbak IRQ active callback funcion
*/
void nRF24_spi_default_init(uint CE, uint IRQ,  nRF24_irq_callback_t callback) {
    spi_init(SPI_PORT, SPI_SPEED);
    gpio_set_function(PIN_MISO, GPIO_FUNC_SPI);
    gpio_set_function(PIN_CS,   GPIO_FUNC_SIO);
    gpio_set_function(PIN_SCK,  GPIO_FUNC_SPI);
    gpio_set_function(PIN_MOSI, GPIO_FUNC_SPI);

    nRF24_callback = callback;

    gpio_set_dir(PIN_CS, GPIO_OUT);
    gpio_put(PIN_CS, 1);

    nRF24_CE = CE;
    gpio_init(nRF24_CE);
    gpio_set_dir(nRF24_CE, GPIO_OUT);

    nRF24_activate();   //nRF24L01 Product Specification

    nRF24_config_PWR_UP();
    nRF24_enable_CE(false);  //standby-I
    sleep_us(100);

    nRF24_IRQ = IRQ;

    gpio_pull_up(nRF24_IRQ);
    gpio_set_irq_enabled_with_callback(nRF24_IRQ, GPIO_IRQ_EDGE_FALL, true, gpio_irq_callback);
}
/*!
* \brief 1. set SPI pin and initialize.  
*         2.set nRF24L01 to standby-I mode
* \param spi_port SPI port number
* \param miso MISO pin no
* \param cs CS pin no
* \param ce nRF24L01 CE pin no
* \param speed SPI speed
* \param IRQ nRF24L01 IRQ pin no
* \param callbak IRQ active callback funcion
*/
void nRF24_spi_init(spi_inst_t* spi_port, uint miso, uint  mosi, uint  cs, uint  ce, uint speed, uint IRQ, nRF24_irq_callback_t callback) {
    SPI_PORT = spi_port;
    PIN_MISO=miso;
    PIN_MOSI=mosi;
    PIN_CS=cs;
    nRF24_CE = ce;
    SPI_SPEED=speed;
    nRF24_spi_default_init(ce, IRQ, callback);
}
/*!
* \brief enable SPI
* \param true: active, set CS LOW. false deactive, set CS HIGH
*/
void nRF24_spi_enable(bool enable) {
    gpio_put(PIN_CS, !enable);
}

/*!
* \brief read nRF24L01 register
* \param REGISTER register address
* \param value read out data
* \param len read out bytes
* \return 0: failure, other successful
*/
uint8_t  nRF24_read_REGISTER(uint8_t REGISTER, uint8_t *value, uint8_t len) {
    uint8_t ret;
    uint8_t status;
    uint8_t cmd=R_REGISTER|REGISTER;
    
    nRF24_spi_enable(true);
    ret = spi_write_read_blocking(SPI_PORT, &cmd, &status, 1);
    if (ret) {
        ret = spi_read_blocking(SPI_PORT, NOP, value, len);
    }
    nRF24_spi_enable(false);
    return ret;
}

/*!
* \brief write data into  nRF24L01 register
* \param REGISTER register address
* \param value write data
* \param len write bytes
* \return 0: failure, other successful
*/
uint8_t nRF24_write_REGISTER(uint8_t REGISTER, uint8_t *value, uint8_t len) {
    uint8_t ret;
    uint8_t buff[len+1];
    buff[0]=W_REGISTER | REGISTER;
    memcpy(buff+1, value, len);
    nRF24_spi_enable(true);
    ret = spi_write_blocking(SPI_PORT, buff,  len+1);
    nRF24_spi_enable(false);
    return ret;
}

/*!
* \brief R_RX_PL_WIN: nRF24L01 received payload width
*/
uint8_t nRF24_get_RX_payload_width(uint8_t *width) {
    uint8_t ret;
    uint8_t status;
    uint8_t cmd=R_RX_PL_WID;
    
    nRF24_spi_enable(true);
    ret = spi_write_read_blocking(SPI_PORT, &cmd, &status, 1);
    if (ret) {
        ret = spi_read_blocking(SPI_PORT, NOP, width, 1);
    }
    nRF24_spi_enable(false);
    return ret;
}

/*!
* \brief R_RX_PAYLOAD: received payload
* \param payload received payload
* \param len received number of bytes 
* \return 0:failure, others: successful
*/
uint8_t nRF24_read_payload(uint8_t *payload, uint8_t len) {
    uint8_t ret;
    uint8_t status;
    uint8_t cmd=R_RX_PAYLOAD;
    
    nRF24_spi_enable(true);
    ret = spi_write_read_blocking(SPI_PORT, &cmd, &status, 1);
    if (ret) {
        ret = spi_read_blocking(SPI_PORT, NOP, payload, len);
    }
    nRF24_spi_enable(false);
    return ret;
}

/*!
* \brief W_TX_PAYLOAD: write payload
* \param payload received payload
* \param len received number of bytes 
* \return 0:failure, others: successful
*/
uint8_t nRF24_write_payload(uint8_t *payload, uint8_t len) {
    uint8_t ret;
    uint8_t buff[len+1];
   
    buff[0] = W_TX_PAYLOAD;
   
    memcpy(buff+1, payload, len);
    
    nRF24_spi_enable(true);
    ret = spi_write_blocking(SPI_PORT, buff,  len+1);
    nRF24_spi_enable(false);
    return ret;
}

/*!
* \brief W_TX_PAYLOAD_NOACK: write payload without acknowledgment. enable EN_DYN_ACK in FEATURE 
* \param payload received payload
* \param len received number of bytes 
* \return 0:failure, others: successful
*/
uint8_t nRF24_write_payload_no_ack(uint8_t *payload, uint8_t len) {
    uint8_t ret;
    uint8_t buff[len+1];
    buff[0]=W_TX_PAYLOAD_NOACK;
    memcpy(buff+1, payload, len);
    
    nRF24_spi_enable(true);
    ret = spi_write_blocking(SPI_PORT, buff,  len+1);
    nRF24_spi_enable(false);
    return ret;
}

/*!
* \brief FLUSH RX FIFO
*/
uint8_t nRF24_flush_rx() {
    uint8_t ret;
    uint8_t cmd=FLUSH_RX;
    uint8_t status;
    nRF24_spi_enable(true);
    ret = spi_write_read_blocking(SPI_PORT, &cmd, &status, 1);
    nRF24_spi_enable(false);
    return ret;
}

/*!
* \brief FLUSH TX FIFO
*/
uint8_t nRF24_flush_tx() {
    uint8_t ret;
    uint8_t cmd=FLUSH_TX;
    uint8_t status;
    nRF24_spi_enable(true);
    ret = spi_write_read_blocking(SPI_PORT, &cmd, &status, 1);
    nRF24_spi_enable(false);
    return ret;
}

uint8_t nRF24_reuse_tx_pl() {
    uint8_t ret;
    uint8_t cmd=REUSE_TX_PL;
    uint8_t status;
    nRF24_spi_enable(true);
    ret = spi_write_read_blocking(SPI_PORT, &cmd, &status, 1);
    nRF24_spi_enable(false);
    return ret;
}

/*!
* \brief W_ACK_PAYLOAD
*/
uint8_t nRF24_write_ack_payload(uint8_t data_pipe, uint8_t *payload, uint8_t len) {
    uint8_t ret;
    uint8_t buff[len+2];
    buff[0]=W_ACK_PAYLOAD | (data_pipe&0x07);
    memcpy(buff+1, payload, len);

    nRF24_spi_enable(true);
    ret = spi_write_blocking(SPI_PORT, buff,  len+1);
    nRF24_spi_enable(false);
    return ret;
}

uint8_t nRF24_set_TX_addr(uint8_t *addr, uint8_t len) {
    
    return (nRF24_write_REGISTER(TX_ADDR, addr, len));
}

uint8_t nRF24_get_TX_addr(uint8_t *addr, uint8_t len) {
    return (nRF24_read_REGISTER(TX_ADDR, addr, len));
}

uint8_t nRF24_set_RX_addr(uint8_t data_pipe, uint8_t *addr, uint8_t len) {
    uint8_t rx_addr_reg = RX_ADDR_P0 + data_pipe;
    if (data_pipe > 1) len = 1;
    return (nRF24_write_REGISTER(rx_addr_reg, addr, len));
}

uint8_t nRF24_get_RX_addr(uint8_t data_pipe, uint8_t *addr, uint8_t len) {
    uint8_t rx_addr_reg = RX_ADDR_P0 + data_pipe;
    if (data_pipe > 1) len = 1;
    return (nRF24_read_REGISTER(rx_addr_reg, addr, len));
}

uint8_t nRF24_status(uint8_t *status) {
    uint8_t ret;
    uint8_t cmd = NOP;
    nRF24_spi_enable(true);
    ret = spi_write_read_blocking(SPI_PORT, &cmd, status, 1);
    nRF24_spi_enable(false);
    return ret;
}
/*!
* \param channel 0~125
*/
uint8_t nRF24_set_RF_channel(uint8_t channel) {
    if (channel > 125) channel = 125;
    return (nRF24_write_REGISTER(RF_CH, &channel,1));
}

/*!
* \param pa: PA_0dBM, PA_m_6dBm(-6dBm), PA_m_12dBm, PA_m_18dBm
*/
uint8_t nRF24_set_power_amplifier(uint8_t pa) {
    uint8_t rf_setup;
    if(!nRF24_read_REGISTER(RF_SETUP, &rf_setup,1)) return false;
    rf_setup &= 0xF9;
    switch(pa) {
        case PA_0dBm:
            rf_setup |= 0x06;
        break;
        case PA_m_6dBm:
            rf_setup |= 0x04;
        break;
        case PA_m_12dBm:
            rf_setup |= 0x02;
        break;
        case PA_m_18dBm:
            rf_setup |= 0x00;
        break;
    }
    return (nRF24_write_REGISTER(RF_SETUP, &rf_setup,1));
}

/*!
* \param aw 3~5
*/
uint8_t nRF24_set_address_width(uint8_t aw) {
    if (aw >=3 && aw <= 5 ) {
        aw -= 2;
        return (nRF24_write_REGISTER(SETUP_AW, &aw,1));
    }
    else 
        return false;
}

uint8_t nRF24_get_address_width(uint8_t *aw) {
    if (!nRF24_read_REGISTER(SETUP_AW, aw,1)) {
        *aw=0;
        return false;
    }
    *aw = *aw+2;
    return true;
    
}

/*!
* \brief EN_AA register
*/
uint8_t nRF24_enable_auto_ack(uint8_t data_pipe, bool enable) {
    uint8_t aa;
    uint8_t mask;
    if (data_pipe < 0 || data_pipe > 5) return false;
    mask = 0x1 << data_pipe;
    if(!nRF24_read_REGISTER(EN_AA, &aa, 1)) return false;
    if (enable) {
        aa |= mask;
    } else {
        aa &= (mask^0xFF);
    }
    return (nRF24_write_REGISTER(EN_AA, &aa,1));
}

/*!
* \param feature FEATURE_EN_DYN_ACK, FEATURE_EN_ACK_PAY, FEATURE_EN_DPL
* \param enable true:enable, false:disable
*/
uint8_t nRF24_enable_feature(uint8_t feature, bool enable) {
    uint8_t buff;
    
    if(!nRF24_read_REGISTER(FEATURE, &buff, 1)) return false;
    if (enable) {
        buff |= (0x01 << feature);
    } else {
        buff &= ((0x01 << feature) ^ 0xFF);
    }
    return (nRF24_write_REGISTER(FEATURE, &buff,1));
}

/*!
* \brief DYNPD register
 */
uint8_t nRF24_enable_data_pipe_dynamic_payload_length(uint8_t data_pipe, bool enable) {
    if (data_pipe < 0 || data_pipe > 5) return false;
    if (!nRF24_enable_feature(FEATURE_EN_DPL, true)) return false;
    if (!nRF24_enable_auto_ack(data_pipe, true)) return false;

    uint8_t dynpd;
    uint8_t mask;
    
    mask = 0x1 << data_pipe;
    if(!nRF24_read_REGISTER(DYNPD, &dynpd, 1)) return false;
    if (enable) {
        dynpd |= mask;
    } else {
        dynpd &= (mask^0xff);
    }
    return (nRF24_write_REGISTER(DYNPD, &dynpd,1));
}

/*!
* \brief Received Power Detector (RPD)
*/
uint8_t nRF24_get_RPD(uint8_t *rpd_value) {
    return (nRF24_read_REGISTER(RPD, rpd_value, 1));
}

/*!
* \brief RX_PW_Px register, Number of bytes in RX payload in data pipe Px
*/
uint8_t nRF24_set_recv_payload_width(uint8_t data_pipe, uint8_t width) {
    if (width > 32 || width < 0) return false;
    uint8_t rx_pw_px = RX_PW_P0+data_pipe;
    return (nRF24_write_REGISTER(rx_pw_px, &width, 1));
}
/*!
* \brief enable RX Address at data pipe x
* \param mask 0b00xxxxxx: ex. 0b00010111 enable p0~2 & p4
*/
uint8_t nRF24_enable_RXADDR(uint8_t mask) {
    return (nRF24_write_REGISTER(EN_RXADDR, &mask, 1));
}

uint8_t nRF24_set_data_rate(uint8_t rate) {
    uint8_t rf_setup;
    if(!nRF24_read_REGISTER(RF_SETUP, &rf_setup, 1)) return false;
    rf_setup &= 0xD7;
    switch(rate) {
        case DATA_RATE_250K:
            rf_setup |= 0x20;
        break;
        case DATA_RATE_1M:
            rf_setup |= 0x00;
        break;
        case DATA_RATE_2M:
            rf_setup |= 0x08;
        break;
    }
    return (nRF24_write_REGISTER(RF_SETUP, &rf_setup,1));
    
}
/*!
* \brief set nRF24L01+ mode
* \param PRIM_RX 1:PRX, 0: PTX
* \return 0: falure, other success
*/
uint8_t nRF24_config_mode(uint8_t PRIM_RX) {
    
    uint8_t ret;
    uint8_t mode;
    
    ret = nRF24_read_REGISTER(CONFIG, &mode, 1);
    if (ret) {
        nRF24_enable_CE(false);
        sleep_us(10);
        mode = (mode & 0xFE) | (PRIM_RX & 0x01);
        ret = nRF24_write_REGISTER(CONFIG, &mode,1);
        nRF24_enable_CE(true);
        sleep_us(2000);
    }
    return ret;
}

/*!
* \param irq_type EVENT_MAX_RT, EVENT_TX_DS, EVENT_RX_DR
* \param enable
*/
uint8_t nRF24_enable_IRQ(uint8_t irq_type, bool enable) {
    if (irq_type < EVENT_MAX_RT || irq_type > EVENT_RX_DR) return 0;

    uint8_t config;
    uint8_t mask=0x01 << irq_type;
    
    if (!nRF24_read_REGISTER(CONFIG, &config, 1)) return 0;
    if (enable) {
        config &= (mask ^ 0xFF);
    } else {
        config |= mask;
    }
    return nRF24_write_REGISTER(CONFIG, &config, 1);
}
/*!
* \brief clear MAX_RT interrupt
*/
uint8_t nRF24_clear_MAX_RT() {
    uint8_t status;
    if (!nRF24_status(&status)) return 0;
    if (status & 0x10) {
        status |= 0x10;
        return (nRF24_write_REGISTER(STATUS, &status, 1));
    }
    return 0;
}
/*!
* \brief clear TX_DS interrupt
*/
uint8_t nRF24_clear_TX_DS() {
    uint8_t status;
    if (!nRF24_status(&status)) return 0;
    if (status & 0x20) {
        status |= 0x20;
        return (nRF24_write_REGISTER(STATUS, &status, 1));
    }
    return 0;
}

/*!
* \brief clear RX_DR interrupt
*/
uint8_t nRF24_clear_RX_DR() {
    uint8_t status;
    if (!nRF24_status(&status)) return 0;
    if (status & 0x40) {
        status |= 0x40;
        return (nRF24_write_REGISTER(STATUS, &status, 1));
    }
    return 0;
}

static void nRF24_standby_to_txrx_mode(){
    nRF24_enable_CE(true);
    busy_wait_us(140);  // Standby modes --> TX/RX mode : max 130us. 
                        // Delay from CE positive edge to CSN low : min 4us
}

/*!
* \brief set SETUP_RETR register bit 7:4 Auto Retransmit Delay
* \param delay time = 250us*(delay+1), value:0x00~0x0f
*/
uint8_t nRF24_set_auto_retransmit_delay(uint8_t delay) {
    uint8_t ard;
    if (delay > 0x0f) delay = 0x0f;
    if (nRF24_read_REGISTER(SETUP_RETR, &ard,1)) {
        ard = (ard&0x0f) | delay << 4;
        return (nRF24_write_REGISTER(SETUP_RETR, &ard, 1));
    }
    return false;
}

uint8_t nRF24_fifo_tx_full(uint8_t *full) {
    uint8_t fifo_status;
    uint8_t ret;
    ret = nRF24_read_REGISTER(FIFO_STATUS, &fifo_status, 1);
    if (ret) {
        fifo_status &= 0x20;
        *full = fifo_status >> 5; 
    }
    return ret;
}

static uint8_t nRF24_fifo_tx_empty(uint8_t *empty) {
    uint8_t fifo_status;
    uint8_t ret;
    ret = nRF24_read_REGISTER(FIFO_STATUS, &fifo_status, 1);
    if (ret) {
        fifo_status &= 0x10;
        *empty = fifo_status >> 4; 
    }
    return ret;
}

static uint8_t nRF24_fifo_rx_full(uint8_t *full) {
    uint8_t fifo_status;
    uint8_t ret;
    ret = nRF24_read_REGISTER(FIFO_STATUS, &fifo_status, 1);
    if (ret) {
        fifo_status &= 0x02;
        *full = fifo_status  >> 1; 
    }
    return ret;
}

static uint8_t nRF24_fifo_rx_empty(uint8_t *empty) {
    uint8_t fifo_status;
    uint8_t ret;
    ret = nRF24_read_REGISTER(FIFO_STATUS, &fifo_status, 1);
    if (ret) {
        fifo_status &= 0x01;
        *empty = fifo_status;
    }
    return ret;
}

  • nRF24L01.h
#ifndef __nRF24L01_H__
#define __nRF24L01_H__
#include "hardware/spi.h" 

// Command
#define R_REGISTER          0b00000000
#define W_REGISTER          0b00100000
#define R_RX_PAYLOAD        0b01100001
#define W_TX_PAYLOAD        0b10100000
#define FLUSH_TX            0b11100001
#define FLUSH_RX            0b11100010
#define REUSE_TX_PL         0b11100011
#define ACTIVATE            0b01010000      //nRF24L01 Product Specification
#define R_RX_PL_WID         0b01100000
#define W_ACK_PAYLOAD       0b10101000      // 0b10100PPP
#define W_TX_PAYLOAD_NOACK  0b10110000
#define NOP                 0b11111111

//Registers
#define CONFIG              0x00
#define EN_AA               0x01
#define EN_RXADDR           0x02
#define SETUP_AW            0x03
#define SETUP_RETR          0x04
#define RF_CH               0x05
#define RF_SETUP            0x06
#define STATUS              0x07
#define OBSERVE_TX          0x08
#define RPD                 0x09
#define RX_ADDR_P0          0x0A
#define RX_ADDR_P1          0x0B
#define RX_ADDR_P2          0x0C
#define RX_ADDR_P3          0x0D
#define RX_ADDR_P4          0x0E
#define RX_ADDR_P5          0x0F
#define TX_ADDR             0x10
#define RX_PW_P0            0x11
#define RX_PW_P1            0x12
#define RX_PW_P2            0x13
#define RX_PW_P3            0x14
#define RX_PW_P4            0x15
#define RX_PW_P5            0x16
#define FIFO_STATUS         0x17
#define DYNPD               0x1C
#define FEATURE             0x1D

#define TRANSMITTER         0
#define RECEIVER            1

enum {
    DATA_RATE_250K=0,
    DATA_RATE_1M,
    DATA_RATE_2M
} nRF24_DATA_RATE;

enum {
    PA_0dBm=0,
    PA_m_6dBm,
    PA_m_12dBm,
    PA_m_18dBm,
} nRF24_PA;

enum {
    AW_3=1,
    AW_4,
    AW_5,
} nRF24_ADDRESS_WIDTH;

enum {
    FEATURE_EN_DYN_ACK=0,  // W_TX_PAYLOAD_NOACK
    FEATURE_EN_ACK_PAY,
    FEATURE_EN_DPL,
}nRF24_FEATURE_MASK;

enum {
    EVENT_MAX_RT=4,
    EVENT_TX_DS,
    EVENT_RX_DR,
} nRF24_IRQ_EVENT;

typedef void (*nRF24_irq_callback_t)(uint8_t evant_type, uint8_t datapipe, uint8_t* data, uint8_t width);

void nRF24_spi_default_init(uint CE, uint IRQ, nRF24_irq_callback_t callback);
void nRF24_spi_init(spi_inst_t* spi_port, uint miso, uint  mosi, uint  cs, uint  ce, uint speed, uint IRQ, nRF24_irq_callback_t callback);
void nRF24_spi_enable(bool enable);
uint8_t nRF24_status(uint8_t *status);
uint8_t  nRF24_read_REGISTER(uint8_t REGISTER, uint8_t *value, uint8_t len);
uint8_t  nRF24_write_REGISTER(uint8_t REGISTER, uint8_t *value, uint8_t len);
uint8_t nRF24_config_mode(uint8_t PRIM_RX);

uint8_t nRF24_set_data_rate(uint8_t rate);
uint8_t nRF24_set_RF_channel(uint8_t channel);
uint8_t nRF24_set_power_amplifier(uint8_t pa);
uint8_t nRF24_set_address_width(uint8_t aw);
uint8_t nRF24_set_recv_payload_width(uint8_t data_pipe, uint8_t width);
uint8_t nRF24_set_RX_addr(uint8_t data_pipe, uint8_t *addr, uint8_t len);
uint8_t nRF24_set_TX_addr(uint8_t *addr, uint8_t len);

uint8_t nRF24_get_RPD(uint8_t *rpd_value);
uint8_t nRF24_get_RX_payload_width(uint8_t *width);
uint8_t nRF24_get_address_width(uint8_t *aw);
uint8_t nRF24_get_RX_addr(uint8_t data_pipe, uint8_t *addr, uint8_t len);
uint8_t nRF24_get_TX_addr(uint8_t *addr, uint8_t len);

uint8_t nRF24_enable_auto_ack(uint8_t data_pipe, bool enable);
uint8_t nRF24_enable_data_pipe_dynamic_payload_length(uint8_t data_pipe, bool enable);
uint8_t nRF24_enable_feature(uint8_t feature, bool enable);
uint8_t nRF24_enable_RXADDR(uint8_t mask);

uint8_t nRF24_read_payload(uint8_t *payload, uint8_t len);
uint8_t nRF24_write_payload(uint8_t *payload, uint8_t len);
uint8_t nRF24_write_payload_no_ack(uint8_t *payload, uint8_t len);

uint8_t nRF24_flush_rx();
uint8_t nRF24_flush_tx();
uint8_t nRF24_reuse_tx_pl();
uint8_t nRF24_write_ack_payload(uint8_t data_pipe, uint8_t *payload, uint8_t len);

uint8_t nRF24_clear_MAX_RT();
uint8_t nRF24_clear_TX_DS();
uint8_t nRF24_clear_RX_DR();

void nRF24_standby_I();
#endif
  • CMakeLists.txt
add_library(nRF24L01_drv INTERFACE)
target_sources(nRF24L01_drv INTERFACE
    ${CMAKE_CURRENT_LIST_DIR}/nRF24L01.c
)

target_include_directories(nRF24L01_drv INTERFACE
    ${CMAKE_CURRENT_LIST_DIR}
)

target_link_libraries(nRF24L01_drv INTERFACE
        hardware_spi
)

2023年7月25日 星期二

[Raspberry Pi Pico W] BTstack BLE Ep 4. HID over GATT -- Custom keypad HID device

本篇文章介紹HID over GATT device的製作。在前篇文章介紹classic HID custom keypad製作,但是若HID device移除電源後再接上電源,HID host不能再次自動連上。修改HID SDP paramter hid_reconnect_initiate=0後,雖然在Android與Linux Debian能運作正常,但在iPhone與Windows下卻無法正常運作。

本篇文章測試HID over GATT是否能正常運作。

一、HID over GATT:

在HID over GATT profile文件中說明, HID device需具備三個必要services: HID service, battery service and device information service。 如下圖所示。

(source SIG HID over GATT profile)
 此三種service在BTstack library中均有implement。宣告GATT service時直接import即可。
在CMakeLists.txt中加pico_btstack_make_gatt_header指令產生ATT database。

二、定義hid advertising data:

HID device Class of service UUID and HID keyboard APPERANCE可由SIG assigned numbers文件查出,別為0x1812與0x03C1。

三、定義HID device keyboard descriptior:

hid keyboard descriptor定義input data為:modifier(1 byte), reserved byte(1 byte)與keycode(6 bytes)。output data為:5 bits+3 bits。

四、定義輸入ascii character與scan code對照表:

由HID report input 輸入的character需轉為scan code。

五、初始化所需的driver與註冊event handler:


六、程式主要流程:

  1. 由keypad輸入字元:get_new_keypad_value() :定義在4x4 keypad driver中。
  2. 字元存入ring buffer中,並呼叫hids_device_request_can_send_now_event(): key_input()。
  3. 在HIDS_SUBEVENT_CAN_SEND_NOW將字元的modifier與keycode送出:typing_can_send_now();
  4. typing_can_send_now():由ring buffer讀取輸入的字元,查表取得modifier與keycode,呼叫send_report(modifier, keycode),送出hid report後,再次呼叫hids_device_request_can_send_now_event()執行下次送出hid report。
  5. send_report():
    uint8_t report[] = {  modifier, 0, keycode, 0, 0, 0, 0, 0};
    送出HID descriptor所定義的input的8 bytes。
詳細程式碼附於文末。

七、成果展示影片:




八、程式碼:

    pico_keypad library程式碼,請參閱前篇文章內容。

  • hog_custom_keypad.c
/* this file was modified from hog_keyboard_demo.c */
/*
 * Copyright (C) 2014 BlueKitchen GmbH
 *
 * Redistribution and use in source and binary forms, with or without
 * modification, are permitted provided that the following conditions
 * are met:
 *
 * 1. Redistributions of source code must retain the above copyright
 *    notice, this list of conditions and the following disclaimer.
 * 2. Redistributions in binary form must reproduce the above copyright
 *    notice, this list of conditions and the following disclaimer in the
 *    documentation and/or other materials provided with the distribution.
 * 3. Neither the name of the copyright holders nor the names of
 *    contributors may be used to endorse or promote products derived
 *    from this software without specific prior written permission.
 * 4. Any redistribution, use, or modification is done solely for
 *    personal benefit and not for any commercial purpose or for
 *    monetary gain.
 *
 * THIS SOFTWARE IS PROVIDED BY BLUEKITCHEN GMBH AND CONTRIBUTORS
 * ``AS IS'' AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
 * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS
 * FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL BLUEKITCHEN
 * GMBH OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT,
 * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING,
 * BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS
 * OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED
 * AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,
 * OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF
 * THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
 * SUCH DAMAGE.
 *
 * Please inquire about commercial licensing options at
 * contact@bluekitchen-gmbh.com
 *
 */
 #include <stdio.h>
#include "pico/stdlib.h"
#include "pico/cyw43_arch.h"
#include "btstack.h"

#include "ble/gatt-service/battery_service_server.h"
#include "ble/gatt-service/device_information_service_server.h"
#include "ble/gatt-service/hids_device.h"

#include "hog_custom_keypad.h"
#include "inttypes.h"
#include "keypad.h"

#define BACKSPACE_BUTTON   16
#define RETURN_BUTTON 17

// from USB HID Specification 1.1, Appendix B.1
const uint8_t hid_descriptor_keyboard_boot_mode[] = {

    0x05, 0x01,                    // Usage Page (Generic Desktop)
    0x09, 0x06,                    // Usage (Keyboard)
    0xa1, 0x01,                    // Collection (Application)

    0x85,  0x01,                   // Report ID 1

    // Modifier byte

    0x75, 0x01,                    //   Report Size (1)
    0x95, 0x08,                    //   Report Count (8)
    0x05, 0x07,                    //   Usage Page (Key codes)
    0x19, 0xe0,                    //   Usage Minimum (Keyboard LeftControl)
    0x29, 0xe7,                    //   Usage Maxium (Keyboard Right GUI)
    0x15, 0x00,                    //   Logical Minimum (0)
    0x25, 0x01,                    //   Logical Maximum (1)
    0x81, 0x02,                    //   Input (Data, Variable, Absolute)

    // Reserved byte

    0x75, 0x01,                    //   Report Size (1)
    0x95, 0x08,                    //   Report Count (8)
    0x81, 0x03,                    //   Input (Constant, Variable, Absolute)

    // LED report + padding

    0x95, 0x05,                    //   Report Count (5)
    0x75, 0x01,                    //   Report Size (1)
    0x05, 0x08,                    //   Usage Page (LEDs)
    0x19, 0x01,                    //   Usage Minimum (Num Lock)
    0x29, 0x05,                    //   Usage Maxium (Kana)
    0x91, 0x02,                    //   Output (Data, Variable, Absolute)

    0x95, 0x01,                    //   Report Count (1)
    0x75, 0x03,                    //   Report Size (3)
    0x91, 0x03,                    //   Output (Constant, Variable, Absolute)

    // Keycodes

    0x95, 0x06,                    //   Report Count (6)
    0x75, 0x08,                    //   Report Size (8)
    0x15, 0x00,                    //   Logical Minimum (0)
    0x25, 0xff,                    //   Logical Maximum (1)
    0x05, 0x07,                    //   Usage Page (Key codes)
    0x19, 0x00,                    //   Usage Minimum (Reserved (no event indicated))
    0x29, 0xff,                    //   Usage Maxium (Reserved)
    0x81, 0x00,                    //   Input (Data, Array)

    0xc0,                          // End collection
};

//
#define CHAR_ILLEGAL     0xff
#define CHAR_RETURN     '\n'
#define CHAR_ESCAPE      27
#define CHAR_TAB         '\t'
#define CHAR_BACKSPACE   0x7f

// Simplified US Keyboard with Shift modifier

/**
 * English (US)
 */
static const uint8_t keytable_us_none [] = {
    CHAR_ILLEGAL, CHAR_ILLEGAL, CHAR_ILLEGAL, CHAR_ILLEGAL,             /*   0-3 */
    'a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i', 'j',                   /*  4-13 */
    'k', 'l', 'm', 'n', 'o', 'p', 'q', 'r', 's', 't',                   /* 14-23 */
    'u', 'v', 'w', 'x', 'y', 'z',                                       /* 24-29 */
    '1', '2', '3', '4', '5', '6', '7', '8', '9', '0',                   /* 30-39 */
    CHAR_RETURN, CHAR_ESCAPE, CHAR_BACKSPACE, CHAR_TAB, ' ',            /* 40-44 */
    '-', '=', '[', ']', '\\', CHAR_ILLEGAL, ';', '\'', 0x60, ',',       /* 45-54 */
    '.', '/', CHAR_ILLEGAL, CHAR_ILLEGAL, CHAR_ILLEGAL, CHAR_ILLEGAL,   /* 55-60 */
    CHAR_ILLEGAL, CHAR_ILLEGAL, CHAR_ILLEGAL, CHAR_ILLEGAL,             /* 61-64 */
    CHAR_ILLEGAL, CHAR_ILLEGAL, CHAR_ILLEGAL, CHAR_ILLEGAL,             /* 65-68 */
    CHAR_ILLEGAL, CHAR_ILLEGAL, CHAR_ILLEGAL, CHAR_ILLEGAL,             /* 69-72 */
    CHAR_ILLEGAL, CHAR_ILLEGAL, CHAR_ILLEGAL, CHAR_ILLEGAL,             /* 73-76 */
    CHAR_ILLEGAL, CHAR_ILLEGAL, CHAR_ILLEGAL, CHAR_ILLEGAL,             /* 77-80 */
    CHAR_ILLEGAL, CHAR_ILLEGAL, CHAR_ILLEGAL, CHAR_ILLEGAL,             /* 81-84 */
    '*', '-', '+', '\n', '1', '2', '3', '4', '5',                       /* 85-97 */
    '6', '7', '8', '9', '0', '.', 0xa7,                                 /* 97-100 */
};

static const uint8_t keytable_us_shift[] = {
    CHAR_ILLEGAL, CHAR_ILLEGAL, CHAR_ILLEGAL, CHAR_ILLEGAL,             /*  0-3  */
    'A', 'B', 'C', 'D', 'E', 'F', 'G', 'H', 'I', 'J',                   /*  4-13 */
    'K', 'L', 'M', 'N', 'O', 'P', 'Q', 'R', 'S', 'T',                   /* 14-23 */
    'U', 'V', 'W', 'X', 'Y', 'Z',                                       /* 24-29 */
    '!', '@', '#', '$', '%', '^', '&', '*', '(', ')',                   /* 30-39 */
    CHAR_RETURN, CHAR_ESCAPE, CHAR_BACKSPACE, CHAR_TAB, ' ',            /* 40-44 */
    '_', '+', '{', '}', '|', CHAR_ILLEGAL, ':', '"', 0x7E, '<',         /* 45-54 */
    '>', '?', CHAR_ILLEGAL, CHAR_ILLEGAL, CHAR_ILLEGAL, CHAR_ILLEGAL,   /* 55-60 */
    CHAR_ILLEGAL, CHAR_ILLEGAL, CHAR_ILLEGAL, CHAR_ILLEGAL,             /* 61-64 */
    CHAR_ILLEGAL, CHAR_ILLEGAL, CHAR_ILLEGAL, CHAR_ILLEGAL,             /* 65-68 */
    CHAR_ILLEGAL, CHAR_ILLEGAL, CHAR_ILLEGAL, CHAR_ILLEGAL,             /* 69-72 */
    CHAR_ILLEGAL, CHAR_ILLEGAL, CHAR_ILLEGAL, CHAR_ILLEGAL,             /* 73-76 */
    CHAR_ILLEGAL, CHAR_ILLEGAL, CHAR_ILLEGAL, CHAR_ILLEGAL,             /* 77-80 */
    CHAR_ILLEGAL, CHAR_ILLEGAL, CHAR_ILLEGAL, CHAR_ILLEGAL,             /* 81-84 */
    '*', '-', '+', '\n', '1', '2', '3', '4', '5',                       /* 85-97 */
    '6', '7', '8', '9', '0', '.', 0xb1,                                 /* 97-100 */
};

static btstack_packet_callback_registration_t hci_event_callback_registration;
static btstack_packet_callback_registration_t sm_event_callback_registration;
static uint8_t battery = 100;
static hci_con_handle_t con_handle = HCI_CON_HANDLE_INVALID;
static uint8_t protocol_mode = HID_PROTOCOL_MODE_REPORT;

const uint8_t adv_data[] = {
    // Flags general discoverable, BR/EDR not supported
    0x02, BLUETOOTH_DATA_TYPE_FLAGS, 0x06,
    // Name
    0x0d, BLUETOOTH_DATA_TYPE_COMPLETE_LOCAL_NAME, 'H', 'I', 'D', ' ', 'K', 'e', 'y', 'b', 'o', 'a', 'r', 'd',
    // 16-bit Service UUIDs
    0x03, BLUETOOTH_DATA_TYPE_COMPLETE_LIST_OF_16_BIT_SERVICE_CLASS_UUIDS, 
                ORG_BLUETOOTH_SERVICE_HUMAN_INTERFACE_DEVICE & 0xff, ORG_BLUETOOTH_SERVICE_HUMAN_INTERFACE_DEVICE >> 8,
    // Appearance HID - Keyboard (Category 15, Sub-Category 1)
    0x03, BLUETOOTH_DATA_TYPE_APPEARANCE, 0xC1, 0x03,
};
const uint8_t adv_data_len = sizeof(adv_data);

// Buffer for 30 characters
static uint8_t key_input_storage[30];
static btstack_ring_buffer_t key_input_buffer;

// HID Keyboard lookup
static int lookup_keycode(uint8_t character, const uint8_t * table, int size, uint8_t * keycode){
    int i;
    for (i=0;i<size;i++){
        if (table[i] != character) continue;
        *keycode = i;
        return 1;
    }
    return 0;
}

static int keycode_and_modifer_us_for_character(uint8_t character, uint8_t * keycode, uint8_t * modifier){
    int found;
    found = lookup_keycode(character, keytable_us_none, sizeof(keytable_us_none), keycode);
    if (found) {
        *modifier = 0;  // none
        return 1;
    }
    found = lookup_keycode(character, keytable_us_shift, sizeof(keytable_us_shift), keycode);
    if (found) {
        *modifier = 2;  // shift
        return 1;
    }
    return 0;
}

// HID Report sending
static void send_report(int modifier, int keycode){
    uint8_t report[] = {  modifier, 0, keycode, 0, 0, 0, 0, 0};
    switch (protocol_mode){
        case 0:
            hids_device_send_boot_keyboard_input_report(con_handle, report, sizeof(report));
            break;
        case 1:
           hids_device_send_input_report(con_handle, report, sizeof(report));
           break;
        default:
            break;
    }
}

static enum {
    W4_INPUT,
    W4_CAN_SEND_FROM_BUFFER,
    W4_CAN_SEND_KEY_UP,
} state;


static void typing_can_send_now(void){
    switch (state){
        case W4_CAN_SEND_FROM_BUFFER:
            while (1){
                uint8_t c;
                uint32_t num_bytes_read;

                btstack_ring_buffer_read(&key_input_buffer, &c, 1, &num_bytes_read);
                if (num_bytes_read == 0){
                    state = W4_INPUT;
                    break;
                }

                uint8_t modifier;
                uint8_t keycode;
                int found = keycode_and_modifer_us_for_character(c, &keycode, &modifier);
                if (!found) continue;

                printf("sending: %c\n", c);

                send_report(modifier, keycode);
                state = W4_CAN_SEND_KEY_UP;
                hids_device_request_can_send_now_event(con_handle);
                break;
            }
            break;
        case W4_CAN_SEND_KEY_UP:
            send_report(0, 0);
            if (btstack_ring_buffer_bytes_available(&key_input_buffer)){
                state = W4_CAN_SEND_FROM_BUFFER;
                hids_device_request_can_send_now_event(con_handle);
            } else {
                state = W4_INPUT;
            }
            break;
        default:
            break;
    }
}

void key_input(char character){
    uint8_t c = character;
    btstack_ring_buffer_write(&key_input_buffer, &c, 1);
    // start sending
    if (state == W4_INPUT && con_handle != HCI_CON_HANDLE_INVALID){
        state = W4_CAN_SEND_FROM_BUFFER;
        hids_device_request_can_send_now_event(con_handle);
    }
}

static void packet_handler (uint8_t packet_type, uint16_t channel, uint8_t *packet, uint16_t size){
    UNUSED(channel);
    UNUSED(size);

    if (packet_type != HCI_EVENT_PACKET) return;

    switch (hci_event_packet_get_type(packet)) {
        case HCI_EVENT_DISCONNECTION_COMPLETE:
            con_handle = HCI_CON_HANDLE_INVALID;
            printf("Disconnected\n");
            break;
        case SM_EVENT_JUST_WORKS_REQUEST:
            printf("Just Works requested\n");
            sm_just_works_confirm(sm_event_just_works_request_get_handle(packet));
            break;
        case SM_EVENT_NUMERIC_COMPARISON_REQUEST:
            printf("Confirming numeric comparison: %"PRIu32"\n", sm_event_numeric_comparison_request_get_passkey(packet));
            sm_numeric_comparison_confirm(sm_event_passkey_display_number_get_handle(packet));
            break;
        case SM_EVENT_PASSKEY_DISPLAY_NUMBER:
            printf("Display Passkey: %"PRIu32"\n", sm_event_passkey_display_number_get_passkey(packet));
            break;
        case HCI_EVENT_HIDS_META:
            switch (hci_event_hids_meta_get_subevent_code(packet)){
                case HIDS_SUBEVENT_INPUT_REPORT_ENABLE:
                    con_handle = hids_subevent_input_report_enable_get_con_handle(packet);
                    printf("Report Characteristic Subscribed %u\n", hids_subevent_input_report_enable_get_enable(packet));
                    break;
                case HIDS_SUBEVENT_BOOT_KEYBOARD_INPUT_REPORT_ENABLE:
                    con_handle = hids_subevent_boot_keyboard_input_report_enable_get_con_handle(packet);
                    printf("Boot Keyboard Characteristic Subscribed %u\n", hids_subevent_boot_keyboard_input_report_enable_get_enable(packet));
                    break;
                case HIDS_SUBEVENT_PROTOCOL_MODE:
                    protocol_mode = hids_subevent_protocol_mode_get_protocol_mode(packet);
                    printf("Protocol Mode: %s mode\n", hids_subevent_protocol_mode_get_protocol_mode(packet) ? "Report" : "Boot");
                    break;
                case HIDS_SUBEVENT_CAN_SEND_NOW:
                    typing_can_send_now();
                    break;
                default:
                    break;
            }
            break;
            
        default:
            break;
    }
}

void key_button_callback(uint gpio, uint32_t events) {
    gpio_set_irq_enabled(gpio, GPIO_IRQ_EDGE_FALL, false);
    gpio_acknowledge_irq(gpio, events);
    
    if (gpio == BACKSPACE_BUTTON ) {       
        busy_wait_ms(100);
        printf("%d\n", events);
        
        key_input(CHAR_BACKSPACE); //Backspace key
        
    }
    if (gpio == RETURN_BUTTON) {
        busy_wait_ms(200);
        key_input(CHAR_RETURN); // return key
        
    }
    gpio_set_irq_enabled(gpio, GPIO_IRQ_EDGE_FALL, true);

}


int main()
{
    stdio_init_all();
    if (cyw43_arch_init()) {
        printf("cyw43_arch_init error\n");
        return 0;
    }
    //0. initialize keypad
    keypad_init();

    // backspace & return key
    gpio_init(BACKSPACE_BUTTON);
    gpio_init(RETURN_BUTTON);
    gpio_pull_up(BACKSPACE_BUTTON);
    gpio_pull_up(RETURN_BUTTON);
    gpio_set_irq_enabled_with_callback(BACKSPACE_BUTTON, GPIO_IRQ_EDGE_FALL, true, key_button_callback);
    gpio_set_irq_enabled_with_callback(RETURN_BUTTON, GPIO_IRQ_EDGE_FALL, true, key_button_callback);

    //1. initialize ring buffer for key input
    btstack_ring_buffer_init(&key_input_buffer, key_input_storage, sizeof(key_input_storage));
    
    //2. l2cap initialize
    l2cap_init();

    //3. setup SM: Display only
    sm_init();
    sm_set_io_capabilities(IO_CAPABILITY_NO_INPUT_NO_OUTPUT);
    sm_set_authentication_requirements(SM_AUTHREQ_SECURE_CONNECTION | SM_AUTHREQ_BONDING);

    //4. setup ATT server
    att_server_init(profile_data, NULL, NULL);

    //5. setup battery service
    battery_service_server_init(battery);

    //6. setup device information service
    device_information_service_server_init();

    //7. setup HID Device service
    hids_device_init(0, hid_descriptor_keyboard_boot_mode, sizeof(hid_descriptor_keyboard_boot_mode));

    //8. setup advertisements
    uint16_t adv_int_min = 0x0030;
    uint16_t adv_int_max = 0x0030;
    uint8_t adv_type = 0;
    bd_addr_t null_addr;
    memset(null_addr, 0, 6);
    gap_advertisements_set_params(adv_int_min, adv_int_max, adv_type, 0, null_addr, 0x07, 0x00);
    gap_advertisements_set_data(adv_data_len, (uint8_t*) adv_data);
    gap_advertisements_enable(1);

    //9. register for HCI events
    hci_event_callback_registration.callback = &packet_handler;
    hci_add_event_handler(&hci_event_callback_registration);

    //10. register for SM events
    sm_event_callback_registration.callback = &packet_handler;
    sm_add_event_handler(&sm_event_callback_registration);

    //11. register for HIDS
    hids_device_register_packet_handler(packet_handler);

    hci_power_control(HCI_POWER_ON);

    uint8_t c;
    while(1) {
        if (con_handle == HCI_CON_HANDLE_INVALID) continue;
        c=get_new_keypad_value();
        if (c) {
            key_input(c);
        }
    }

    return 0;
}
  • hog_custom_keypad.gatt
PRIMARY_SERVICE, GAP_SERVICE
CHARACTERISTIC, GAP_DEVICE_NAME, READ, "HID Keyboard"
CHARACTERISTIC, GATT_DATABASE_HASH, READ,

// add Battery Service
#import <battery_service.gatt>

// add Device ID Service
#import <device_information_service.gatt>

// add HID Service
#import <hids.gatt>
  • CMakeLists.txt
# Generated Cmake Pico project file

cmake_minimum_required(VERSION 3.13)

set(CMAKE_C_STANDARD 11)
set(CMAKE_CXX_STANDARD 17)

# Initialise pico_sdk from installed location
# (note this can come from environment, CMake cache etc)
set(PICO_SDK_PATH "/home/duser/pico/pico-sdk")

set(PICO_BOARD pico_w CACHE STRING "Board type")

# Pull in Raspberry Pi Pico SDK (must be before project)
include(pico_sdk_import.cmake)

if (PICO_SDK_VERSION_STRING VERSION_LESS "1.4.0")
  message(FATAL_ERROR "Raspberry Pi Pico SDK version 1.4.0 (or later) required. Your version is ${PICO_SDK_VERSION_STRING}")
endif()

project(hog_custom_keypad C CXX ASM)

# Initialise the Raspberry Pi Pico SDK
pico_sdk_init()

# Add executable. Default name is the project name, version 0.1

add_executable(hog_custom_keypad hog_custom_keypad.c )

pico_set_program_name(hog_custom_keypad "hog_custom_keypad")
pico_set_program_version(hog_custom_keypad "0.1")

pico_enable_stdio_uart(hog_custom_keypad 1)
pico_enable_stdio_usb(hog_custom_keypad 0)

# Add the standard library to the build
target_link_libraries(hog_custom_keypad
        pico_stdlib
        pico_cyw43_arch_none
        pico_btstack_cyw43
        pico_btstack_ble)

# Add the standard include files to the build
target_include_directories(hog_custom_keypad PRIVATE
  ${CMAKE_CURRENT_LIST_DIR}
  ${CMAKE_CURRENT_LIST_DIR}/.. # for our common lwipopts or any other standard includes, if required
)
pico_btstack_make_gatt_header(hog_custom_keypad PRIVATE "${CMAKE_CURRENT_LIST_DIR}/hog_custom_keypad.gatt")


# Add any user requested libraries
add_subdirectory(pico_keypad)
target_link_libraries(hog_custom_keypad 
        pico_keypad)
        
pico_add_extra_outputs(hog_custom_keypad)
  • btstack_config.h
#ifndef _PICO_BTSTACK_BTSTACK_CONFIG_H
#define _PICO_BTSTACK_BTSTACK_CONFIG_H

// BTstack features that can be enabled
#ifdef ENABLE_BLE
#define ENABLE_LE_PERIPHERAL
#define ENABLE_LE_CENTRAL
#define ENABLE_L2CAP_LE_CREDIT_BASED_FLOW_CONTROL_MODE
#endif

#ifdef ENABLE_MESH
// Mesh Config
#define ENABLE_MESH_ADV_BEARER
#define ENABLE_MESH_GATT_BEARER
#define ENABLE_MESH_PB_ADV
#define ENABLE_MESH_PB_GATT
#define ENABLE_MESH_PROXY_SERVER
#define ENABLE_MESH_RELAY

#define ENABLE_MESH_PROVISIONER

#define MAX_NR_MESH_SUBNETS            2
#define MAX_NR_MESH_TRANSPORT_KEYS    16
#define MAX_NR_MESH_VIRTUAL_ADDRESSES 16
// allow for one NetKey update
#define MAX_NR_MESH_NETWORK_KEYS      (MAX_NR_MESH_SUBNETS+1)
#endif 


#define ENABLE_LOG_INFO
#define ENABLE_LOG_ERROR
#define ENABLE_PRINTF_HEXDUMP
#define ENABLE_SCO_OVER_HCI

// BTstack configuration. buffers, sizes, ...
#define HCI_OUTGOING_PRE_BUFFER_SIZE 4
#define HCI_ACL_PAYLOAD_SIZE (1691 + 4)
#define HCI_ACL_CHUNK_SIZE_ALIGNMENT 4
#define MAX_NR_AVDTP_CONNECTIONS 1
#define MAX_NR_AVDTP_STREAM_ENDPOINTS 1
#define MAX_NR_AVRCP_CONNECTIONS 2
#define MAX_NR_BNEP_CHANNELS 1
#define MAX_NR_BNEP_SERVICES 1
#define MAX_NR_BTSTACK_LINK_KEY_DB_MEMORY_ENTRIES  2
#define MAX_NR_GATT_CLIENTS 1
#define MAX_NR_HCI_CONNECTIONS 2
#define MAX_NR_HID_HOST_CONNECTIONS 1
#define MAX_NR_HIDS_CLIENTS 1
#define MAX_NR_HFP_CONNECTIONS 1
#define MAX_NR_L2CAP_CHANNELS  4
#define MAX_NR_L2CAP_SERVICES  3
#define MAX_NR_RFCOMM_CHANNELS 1
#define MAX_NR_RFCOMM_MULTIPLEXERS 1
#define MAX_NR_RFCOMM_SERVICES 1
#define MAX_NR_SERVICE_RECORD_ITEMS 4
#define MAX_NR_SM_LOOKUP_ENTRIES 3
#define MAX_NR_WHITELIST_ENTRIES 16
#define MAX_NR_LE_DEVICE_DB_ENTRIES 16

// Limit number of ACL/SCO Buffer to use by stack to avoid cyw43 shared bus overrun
#define MAX_NR_CONTROLLER_ACL_BUFFERS 3
#define MAX_NR_CONTROLLER_SCO_PACKETS 3

// Enable and configure HCI Controller to Host Flow Control to avoid cyw43 shared bus overrun
#define ENABLE_HCI_CONTROLLER_TO_HOST_FLOW_CONTROL
#define HCI_HOST_ACL_PACKET_LEN 1024
#define HCI_HOST_ACL_PACKET_NUM 3
#define HCI_HOST_SCO_PACKET_LEN 120
#define HCI_HOST_SCO_PACKET_NUM 3

// Link Key DB and LE Device DB using TLV on top of Flash Sector interface
#define NVM_NUM_DEVICE_DB_ENTRIES 16
#define NVM_NUM_LINK_KEYS 16

// We don't give btstack a malloc, so use a fixed-size ATT DB.
#define MAX_ATT_DB_SIZE 512

// BTstack HAL configuration
#define HAVE_EMBEDDED_TIME_MS

// map btstack_assert onto Pico SDK assert()
#define HAVE_ASSERT

// Some USB dongles take longer to respond to HCI reset (e.g. BCM20702A).
#define HCI_RESET_RESEND_TIMEOUT_MS 1000

#define ENABLE_SOFTWARE_AES128
#define ENABLE_MICRO_ECC_FOR_LE_SECURE_CONNECTIONS

//#define HAVE_BTSTACK_STDIN

// To get the audio demos working even with HCI dump at 115200, this truncates long ACL packets
//#define HCI_DUMP_STDOUT_MAX_SIZE_ACL 100

#ifdef ENABLE_CLASSIC
#define ENABLE_L2CAP_ENHANCED_RETRANSMISSION_MODE
#endif

#define HAVE_MALLOC

// BTstack configuration. buffers, sizes, ...

#define HCI_INCOMING_PRE_BUFFER_SIZE 6


  #endif // _PICO_BTSTACK_BTSTACK_CONFIG_H

2023年7月10日 星期一

[Raspberry Pi Pico W] BTstack: Ep 5. Bluetooth HID Host

本篇文章介紹Bluetooth HID host的製作,修改BTstack hid_host_deco.c example code。

hid device(hid keyboard)使用前篇文章介紹,hid host接受hid device送來hid report顯示字元在tft display上,當按下F1鍵按鈕時清除tft display內容。

詳細製作過程請參閱「成果影片」。
詳細程式碼附於文章末尾。

  • 成果影片


  • 程式碼
  • btstack_config.h
 #ifndef _PICO_BTSTACK_BTSTACK_CONFIG_H
#define _PICO_BTSTACK_BTSTACK_CONFIG_H

// BTstack features that can be enabled
#ifdef ENABLE_BLE
#define ENABLE_LE_PERIPHERAL
#define ENABLE_LE_CENTRAL
#define ENABLE_L2CAP_LE_CREDIT_BASED_FLOW_CONTROL_MODE
#endif

#ifdef ENABLE_MESH
// Mesh Config
#define ENABLE_MESH_ADV_BEARER
#define ENABLE_MESH_GATT_BEARER
#define ENABLE_MESH_PB_ADV
#define ENABLE_MESH_PB_GATT
#define ENABLE_MESH_PROXY_SERVER
#define ENABLE_MESH_RELAY

#define ENABLE_MESH_PROVISIONER

#define MAX_NR_MESH_SUBNETS            2
#define MAX_NR_MESH_TRANSPORT_KEYS    16
#define MAX_NR_MESH_VIRTUAL_ADDRESSES 16
// allow for one NetKey update
#define MAX_NR_MESH_NETWORK_KEYS      (MAX_NR_MESH_SUBNETS+1)
#endif 


#define ENABLE_LOG_INFO
#define ENABLE_LOG_ERROR
#define ENABLE_PRINTF_HEXDUMP
#define ENABLE_SCO_OVER_HCI

// BTstack configuration. buffers, sizes, ...
#define HCI_OUTGOING_PRE_BUFFER_SIZE 4
#define HCI_ACL_PAYLOAD_SIZE (1691 + 4)
#define HCI_ACL_CHUNK_SIZE_ALIGNMENT 4
#define MAX_NR_AVDTP_CONNECTIONS 1
#define MAX_NR_AVDTP_STREAM_ENDPOINTS 1
#define MAX_NR_AVRCP_CONNECTIONS 2
#define MAX_NR_BNEP_CHANNELS 1
#define MAX_NR_BNEP_SERVICES 1
#define MAX_NR_BTSTACK_LINK_KEY_DB_MEMORY_ENTRIES  2
#define MAX_NR_GATT_CLIENTS 1
#define MAX_NR_HCI_CONNECTIONS 2
#define MAX_NR_HID_HOST_CONNECTIONS 1
#define MAX_NR_HIDS_CLIENTS 1
#define MAX_NR_HFP_CONNECTIONS 1
#define MAX_NR_L2CAP_CHANNELS  4
#define MAX_NR_L2CAP_SERVICES  3
#define MAX_NR_RFCOMM_CHANNELS 1
#define MAX_NR_RFCOMM_MULTIPLEXERS 1
#define MAX_NR_RFCOMM_SERVICES 1
#define MAX_NR_SERVICE_RECORD_ITEMS 4
#define MAX_NR_SM_LOOKUP_ENTRIES 3
#define MAX_NR_WHITELIST_ENTRIES 16
#define MAX_NR_LE_DEVICE_DB_ENTRIES 16

// Limit number of ACL/SCO Buffer to use by stack to avoid cyw43 shared bus overrun
#define MAX_NR_CONTROLLER_ACL_BUFFERS 3
#define MAX_NR_CONTROLLER_SCO_PACKETS 3

// Enable and configure HCI Controller to Host Flow Control to avoid cyw43 shared bus overrun
#define ENABLE_HCI_CONTROLLER_TO_HOST_FLOW_CONTROL
#define HCI_HOST_ACL_PACKET_LEN 1024
#define HCI_HOST_ACL_PACKET_NUM 3
#define HCI_HOST_SCO_PACKET_LEN 120
#define HCI_HOST_SCO_PACKET_NUM 3

// Link Key DB and LE Device DB using TLV on top of Flash Sector interface
#define NVM_NUM_DEVICE_DB_ENTRIES 16
#define NVM_NUM_LINK_KEYS 16

// We don't give btstack a malloc, so use a fixed-size ATT DB.
#define MAX_ATT_DB_SIZE 512

// BTstack HAL configuration
#define HAVE_EMBEDDED_TIME_MS

// map btstack_assert onto Pico SDK assert()
#define HAVE_ASSERT

// Some USB dongles take longer to respond to HCI reset (e.g. BCM20702A).
#define HCI_RESET_RESEND_TIMEOUT_MS 1000

#define ENABLE_SOFTWARE_AES128
#define ENABLE_MICRO_ECC_FOR_LE_SECURE_CONNECTIONS

//#define HAVE_BTSTACK_STDIN

// To get the audio demos working even with HCI dump at 115200, this truncates long ACL packets
//#define HCI_DUMP_STDOUT_MAX_SIZE_ACL 100

#ifdef ENABLE_CLASSIC
#define ENABLE_L2CAP_ENHANCED_RETRANSMISSION_MODE
#endif

#define HAVE_MALLOC

#endif // _PICO_BTSTACK_BTSTACK_CONFIG_H

  • CMakeLists.txt
 # Generated Cmake Pico project file

cmake_minimum_required(VERSION 3.13)

set(CMAKE_C_STANDARD 11)
set(CMAKE_CXX_STANDARD 17)

# Initialise pico_sdk from installed location
# (note this can come from environment, CMake cache etc)
set(PICO_SDK_PATH "/home/duser/pico/pico-sdk")

set(PICO_BOARD pico_w CACHE STRING "Board type")

# Pull in Raspberry Pi Pico SDK (must be before project)
include(pico_sdk_import.cmake)

if (PICO_SDK_VERSION_STRING VERSION_LESS "1.4.0")
  message(FATAL_ERROR "Raspberry Pi Pico SDK version 1.4.0 (or later) required. Your version is ${PICO_SDK_VERSION_STRING}")
endif()

project(picow_hid_host C CXX ASM)

# Initialise the Raspberry Pi Pico SDK
pico_sdk_init()

# Add executable. Default name is the project name, version 0.1

add_executable(picow_hid_host picow_hid_host.c hid_host_demo.c)

pico_set_program_name(picow_hid_host "picow_hid_host")
pico_set_program_version(picow_hid_host "0.1")

pico_enable_stdio_uart(picow_hid_host 0)
pico_enable_stdio_usb(picow_hid_host 1)

# Add the standard library to the build
target_link_libraries(picow_hid_host
        pico_stdlib
        pico_cyw43_arch_none
        pico_btstack_cyw43
        pico_btstack_classic)

# Add the standard include files to the build
target_include_directories(picow_hid_host PRIVATE
  ${CMAKE_CURRENT_LIST_DIR}
  ${CMAKE_CURRENT_LIST_DIR}/.. # for our common lwipopts or any other standard includes, if required
)
# add user library
add_subdirectory(pico_tft)
target_link_libraries(picow_hid_host
      pico_tft)

pico_add_extra_outputs(picow_hid_host)
  • picow_hid_host.c
 #include <stdio.h>
#include "pico/stdlib.h"
#include "pico/cyw43_arch.h"

#include "pico_tft.h"

extern int btstack_main(int argc, const char * argv[]);
int main()
{
    stdio_init_all();
    if (cyw43_arch_init()) {
        puts("cyw43 init error");
        return 0;

    }
   
    tft_init();
    
    btstack_main(0, NULL);


    while(1) {
        tight_loop_contents();
    }


    return 0;
}
  • hid_host_demo.c(modified)
 /*
 * Copyright (C) 2017 BlueKitchen GmbH
 *
 * Redistribution and use in source and binary forms, with or without
 * modification, are permitted provided that the following conditions
 * are met:
 *
 * 1. Redistributions of source code must retain the above copyright
 *    notice, this list of conditions and the following disclaimer.
 * 2. Redistributions in binary form must reproduce the above copyright
 *    notice, this list of conditions and the following disclaimer in the
 *    documentation and/or other materials provided with the distribution.
 * 3. Neither the name of the copyright holders nor the names of
 *    contributors may be used to endorse or promote products derived
 *    from this software without specific prior written permission.
 * 4. Any redistribution, use, or modification is done solely for
 *    personal benefit and not for any commercial purpose or for
 *    monetary gain.
 *
 * THIS SOFTWARE IS PROVIDED BY BLUEKITCHEN GMBH AND CONTRIBUTORS
 * ``AS IS'' AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
 * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS
 * FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL BLUEKITCHEN
 * GMBH OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT,
 * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING,
 * BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS
 * OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED
 * AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,
 * OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF
 * THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
 * SUCH DAMAGE.
 *
 * Please inquire about commercial licensing options at 
 * contact@bluekitchen-gmbh.com
 *
 */

#define BTSTACK_FILE__ "hid_host_demo.c"

/*
 * hid_host_demo.c
 */

/* EXAMPLE_START(hid_host_demo): HID Host Classic
 *
 * @text This example implements a HID Host. For now, it connects to a fixed device.
 * It will connect in Report protocol mode if this mode is supported by the HID Device,
 * otherwise it will fall back to BOOT protocol mode. 
 */

#include <inttypes.h>
#include <stdio.h>

#include "btstack_config.h"
#include "btstack.h"

#define MAX_ATTRIBUTE_VALUE_SIZE 300

// HID device Bluetooth device address
/* modify begin */
static const char * remote_addr_string = "28:CD:C1:01:XX:XX";
/* modify end */
/* ===add tft display begin===*/
#include "pico_tft.h"
#include "tft_string.h"
#include "fonts/font_fixedsys_mono_24.h"

#define F1_KEY_SCAN_CODE           0x3a          // F1 key scan code
static uint8_t tft_x=0, tft_y=0;
void tft_dislplay_clean() {
    tft_fill_rect(0,0, TFT_WIDTH, TFT_HEIGHT, 0xffff);
    tft_x=0;
    tft_y=0;
}
void tft_display(uint8_t ch) {
    
    uint8_t ch_str[2];
    
    if (ch == '\n') {
        tft_x=0; tft_y+=25;
    } else {
        sprintf(ch_str, "%c", ch);
        tft_draw_string(tft_x, tft_y, ch_str, 0x001f, &font_fixedsys_mono_24);
        tft_x+=13;
        if (tft_x > TFT_WIDTH-13) {
            tft_y+=25;
            tft_x=0;
        }
    }
    if (tft_y > TFT_HEIGHT-25) tft_y=0;

}
/* ===add tft display end===*/
static bd_addr_t remote_addr;

static btstack_packet_callback_registration_t hci_event_callback_registration;

// Simplified US Keyboard with Shift modifier

#define CHAR_ILLEGAL     0xff
#define CHAR_RETURN     '\n'
#define CHAR_ESCAPE      27
#define CHAR_TAB         '\t'
#define CHAR_BACKSPACE   0x7f

/**
 * English (US)
 */
static const uint8_t keytable_us_none [] = {
    CHAR_ILLEGAL, CHAR_ILLEGAL, CHAR_ILLEGAL, CHAR_ILLEGAL,             /*   0-3 */
    'a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i', 'j',                   /*  4-13 */
    'k', 'l', 'm', 'n', 'o', 'p', 'q', 'r', 's', 't',                   /* 14-23 */
    'u', 'v', 'w', 'x', 'y', 'z',                                       /* 24-29 */
    '1', '2', '3', '4', '5', '6', '7', '8', '9', '0',                   /* 30-39 */
    CHAR_RETURN, CHAR_ESCAPE, CHAR_BACKSPACE, CHAR_TAB, ' ',            /* 40-44 */
    '-', '=', '[', ']', '\\', CHAR_ILLEGAL, ';', '\'', 0x60, ',',       /* 45-54 */
    '.', '/', CHAR_ILLEGAL, CHAR_ILLEGAL, CHAR_ILLEGAL, CHAR_ILLEGAL,   /* 55-60 */
    CHAR_ILLEGAL, CHAR_ILLEGAL, CHAR_ILLEGAL, CHAR_ILLEGAL,             /* 61-64 */
    CHAR_ILLEGAL, CHAR_ILLEGAL, CHAR_ILLEGAL, CHAR_ILLEGAL,             /* 65-68 */
    CHAR_ILLEGAL, CHAR_ILLEGAL, CHAR_ILLEGAL, CHAR_ILLEGAL,             /* 69-72 */
    CHAR_ILLEGAL, CHAR_ILLEGAL, CHAR_ILLEGAL, CHAR_ILLEGAL,             /* 73-76 */
    CHAR_ILLEGAL, CHAR_ILLEGAL, CHAR_ILLEGAL, CHAR_ILLEGAL,             /* 77-80 */
    CHAR_ILLEGAL, CHAR_ILLEGAL, CHAR_ILLEGAL, CHAR_ILLEGAL,             /* 81-84 */
    '*', '-', '+', '\n', '1', '2', '3', '4', '5',                       /* 85-97 */
    '6', '7', '8', '9', '0', '.', 0xa7,                                 /* 97-100 */
}; 

static const uint8_t keytable_us_shift[] = {
    CHAR_ILLEGAL, CHAR_ILLEGAL, CHAR_ILLEGAL, CHAR_ILLEGAL,             /*  0-3  */
    'A', 'B', 'C', 'D', 'E', 'F', 'G', 'H', 'I', 'J',                   /*  4-13 */
    'K', 'L', 'M', 'N', 'O', 'P', 'Q', 'R', 'S', 'T',                   /* 14-23 */
    'U', 'V', 'W', 'X', 'Y', 'Z',                                       /* 24-29 */
    '!', '@', '#', '$', '%', '^', '&', '*', '(', ')',                   /* 30-39 */
    CHAR_RETURN, CHAR_ESCAPE, CHAR_BACKSPACE, CHAR_TAB, ' ',            /* 40-44 */
    '_', '+', '{', '}', '|', CHAR_ILLEGAL, ':', '"', 0x7E, '<',         /* 45-54 */
    '>', '?', CHAR_ILLEGAL, CHAR_ILLEGAL, CHAR_ILLEGAL, CHAR_ILLEGAL,   /* 55-60 */
    CHAR_ILLEGAL, CHAR_ILLEGAL, CHAR_ILLEGAL, CHAR_ILLEGAL,             /* 61-64 */
    CHAR_ILLEGAL, CHAR_ILLEGAL, CHAR_ILLEGAL, CHAR_ILLEGAL,             /* 65-68 */
    CHAR_ILLEGAL, CHAR_ILLEGAL, CHAR_ILLEGAL, CHAR_ILLEGAL,             /* 69-72 */
    CHAR_ILLEGAL, CHAR_ILLEGAL, CHAR_ILLEGAL, CHAR_ILLEGAL,             /* 73-76 */
    CHAR_ILLEGAL, CHAR_ILLEGAL, CHAR_ILLEGAL, CHAR_ILLEGAL,             /* 77-80 */
    CHAR_ILLEGAL, CHAR_ILLEGAL, CHAR_ILLEGAL, CHAR_ILLEGAL,             /* 81-84 */
    '*', '-', '+', '\n', '1', '2', '3', '4', '5',                       /* 85-97 */
    '6', '7', '8', '9', '0', '.', 0xb1,                                 /* 97-100 */
}; 

// SDP
static uint8_t hid_descriptor_storage[MAX_ATTRIBUTE_VALUE_SIZE];

// App
static enum {
    APP_IDLE,
    APP_CONNECTED
} app_state = APP_IDLE;

static uint16_t hid_host_cid = 0;
static bool     hid_host_descriptor_available = false;
//static hid_protocol_mode_t hid_host_report_mode = HID_PROTOCOL_MODE_REPORT_WITH_FALLBACK_TO_BOOT;
/* ===modify protocol begin=== */
static hid_protocol_mode_t hid_host_report_mode = HID_PROTOCOL_MODE_REPORT;   ////////////
/* ===modify protocol end=== */

/* @section Main application configuration
 *
 * @text In the application configuration, L2CAP and HID host are initialized, and the link policies 
 * are set to allow sniff mode and role change. 
 */

/* LISTING_START(PanuSetup): Panu setup */
static void packet_handler (uint8_t packet_type, uint16_t channel, uint8_t *packet, uint16_t size);

static void hid_host_setup(void){

    // Initialize L2CAP
    l2cap_init();

#ifdef ENABLE_BLE
    // Initialize LE Security Manager. Needed for cross-transport key derivation
    sm_init();
#endif

    // Initialize HID Host
    hid_host_init(hid_descriptor_storage, sizeof(hid_descriptor_storage));
    hid_host_register_packet_handler(packet_handler);

    // Allow sniff mode requests by HID device and support role switch
    gap_set_default_link_policy_settings(LM_LINK_POLICY_ENABLE_SNIFF_MODE | LM_LINK_POLICY_ENABLE_ROLE_SWITCH);

    // try to become master on incoming connections
    hci_set_master_slave_policy(HCI_ROLE_MASTER);

    // register for HCI events
    hci_event_callback_registration.callback = &packet_handler;
    hci_add_event_handler(&hci_event_callback_registration);

    // Disable stdout buffering

    /* uncomment */
    //setvbuf(stdin, NULL, _IONBF, 0);
}
/* LISTING_END */

/*
 * @section HID Report Handler
 * 
 * @text Use BTstack's compact HID Parser to process incoming HID Report in Report protocol mode. 
 * Iterate over all fields and process fields with usage page = 0x07 / Keyboard
 * Check if SHIFT is down and process first character (don't handle multiple key presses)
 * 
 */

#define NUM_KEYS 12
static uint8_t last_keys[NUM_KEYS];
static void hid_host_handle_interrupt_report(const uint8_t * report, uint16_t report_len){
    // check if HID Input Report
    if (report_len < 1) return;
    if (*report != 0xa1) return;   
    report++;
    report_len--;
    
    btstack_hid_parser_t parser;
    btstack_hid_parser_init(&parser, 
        hid_descriptor_storage_get_descriptor_data(hid_host_cid), 
        hid_descriptor_storage_get_descriptor_len(hid_host_cid), 
        HID_REPORT_TYPE_INPUT, report, report_len);

    int shift = 0;
    uint8_t new_keys[NUM_KEYS];
    memset(new_keys, 0, sizeof(new_keys));
    int     new_keys_count = 0;
    while (btstack_hid_parser_has_more(&parser)){
        uint16_t usage_page;
        uint16_t usage;
        int32_t  value;
        btstack_hid_parser_get_field(&parser, &usage_page, &usage, &value);
        if (usage_page != 0x07) continue;   
        switch (usage){
            case 0xe1:
            case 0xe6:
                if (value){
                    shift = 1;
                }
                continue;
            case 0x00:
                continue;
            default:
                break;
        }
        if (usage >= sizeof(keytable_us_none)) continue;

        // store new keys
        new_keys[new_keys_count++] = (uint8_t) usage;

        // check if usage was used last time (and ignore in that case)
        int i;
        for (i=0;i<NUM_KEYS;i++){
            if (usage == last_keys[i]){
                usage = 0;
            }
        }
        if (usage == 0) continue;

        uint8_t key;
        /* ===check F1_KEY====*/
        if (usage == F1_KEY_SCAN_CODE) { 
            tft_dislplay_clean();
            continue;
        }
        /* ===check F1_KEY====*/
        if (shift){
            key = keytable_us_shift[usage];
        } else {
            key = keytable_us_none[usage];
        }
        if (key == CHAR_ILLEGAL) continue;
        if (key == CHAR_BACKSPACE){ 
            printf("\b \b");    // go back one char, print space, go back one char again
            continue;
        }
        printf("%c", key);
        /* === modify for our Application begin===*/  
        tft_display(key);
        /* === modify for our Application end===*/
    }
    memcpy(last_keys, new_keys, NUM_KEYS);
}

/*
 * @section Packet Handler
 * 
 * @text The packet handler responds to various HID events.
 */

/* LISTING_START(packetHandler): Packet Handler */
static void packet_handler (uint8_t packet_type, uint16_t channel, uint8_t *packet, uint16_t size)
{
    /* LISTING_PAUSE */
    UNUSED(channel);
    UNUSED(size);

    uint8_t   event;
    bd_addr_t event_addr;
    uint8_t   status;

    /* LISTING_RESUME */
    switch (packet_type) {
		case HCI_EVENT_PACKET:
            event = hci_event_packet_get_type(packet);
            
            switch (event) {            
#ifndef HAVE_BTSTACK_STDIN
                /* @text When BTSTACK_EVENT_STATE with state HCI_STATE_WORKING
                 * is received and the example is started in client mode, the remote SDP HID query is started.
                 */
                case BTSTACK_EVENT_STATE:
                    if (btstack_event_state_get_state(packet) == HCI_STATE_WORKING){
                        status = hid_host_connect(remote_addr, hid_host_report_mode, &hid_host_cid);
                        if (status != ERROR_CODE_SUCCESS){
                            printf("HID host connect failed, status 0x%02x.\n", status);
                        } 
                    }
                    break;
#endif
                /* LISTING_PAUSE */
                case HCI_EVENT_PIN_CODE_REQUEST:
					// inform about pin code request
                    printf("Pin code request - using '0000'\n");
                    hci_event_pin_code_request_get_bd_addr(packet, event_addr);
                    gap_pin_code_response(event_addr, "0000");
					break;

                case HCI_EVENT_USER_CONFIRMATION_REQUEST:
                    // inform about user confirmation request
                    printf("SSP User Confirmation Request with numeric value '%"PRIu32"'\n", little_endian_read_32(packet, 8));
                    printf("SSP User Confirmation Auto accept\n");
                    break;

                /* LISTING_RESUME */
                case HCI_EVENT_HID_META:
                    switch (hci_event_hid_meta_get_subevent_code(packet)){

                        case HID_SUBEVENT_INCOMING_CONNECTION:
                            // There is an incoming connection: we can accept it or decline it.
                            // The hid_host_report_mode in the hid_host_accept_connection function 
                            // allows the application to request a protocol mode. 
                            // For available protocol modes, see hid_protocol_mode_t in btstack_hid.h file. 
                            hid_host_accept_connection(hid_subevent_incoming_connection_get_hid_cid(packet), hid_host_report_mode);
                            break;
                        
                        case HID_SUBEVENT_CONNECTION_OPENED:
                            // The status field of this event indicates if the control and interrupt
                            // connections were opened successfully.
                            status = hid_subevent_connection_opened_get_status(packet);
                            if (status != ERROR_CODE_SUCCESS) {
                                printf("Connection failed, status 0x%02x\n", status);
                                
                                app_state = APP_IDLE;
                                hid_host_cid = 0;
                                return;
                            }
                            app_state = APP_CONNECTED;
                            hid_host_descriptor_available = false;
                            hid_host_cid = hid_subevent_connection_opened_get_hid_cid(packet);
                            printf("HID Host connected.\n");
                            break;

                        case HID_SUBEVENT_DESCRIPTOR_AVAILABLE:
                            // This event will follows HID_SUBEVENT_CONNECTION_OPENED event. 
                            // For incoming connections, i.e. HID Device initiating the connection,
                            // the HID_SUBEVENT_DESCRIPTOR_AVAILABLE is delayed, and some HID  
                            // reports may be received via HID_SUBEVENT_REPORT event. It is up to 
                            // the application if these reports should be buffered or ignored until 
                            // the HID descriptor is available.
                            status = hid_subevent_descriptor_available_get_status(packet);
                            if (status == ERROR_CODE_SUCCESS){
                                hid_host_descriptor_available = true;
                                printf("HID Descriptor available, please start typing.\n");
                                tft_dislplay_clean();
                            } else {
                                printf("Cannot handle input report, HID Descriptor is not available, status 0x%02x\n", status);
                            }
                            break;

                        case HID_SUBEVENT_REPORT:
                            // Handle input report.
                            if (hid_host_descriptor_available){
                                hid_host_handle_interrupt_report(hid_subevent_report_get_report(packet), hid_subevent_report_get_report_len(packet));
                            } else {
                                printf_hexdump(hid_subevent_report_get_report(packet), hid_subevent_report_get_report_len(packet));
                            }
                            break;

                        case HID_SUBEVENT_SET_PROTOCOL_RESPONSE:
                            // For incoming connections, the library will set the protocol mode of the
                            // HID Device as requested in the call to hid_host_accept_connection. The event 
                            // reports the result. For connections initiated by calling hid_host_connect, 
                            // this event will occur only if the established report mode is boot mode.
                            status = hid_subevent_set_protocol_response_get_handshake_status(packet);
                            if (status != HID_HANDSHAKE_PARAM_TYPE_SUCCESSFUL){
                                printf("Error set protocol, status 0x%02x\n", status);
                                break;
                            }
                            switch ((hid_protocol_mode_t)hid_subevent_set_protocol_response_get_protocol_mode(packet)){
                                case HID_PROTOCOL_MODE_BOOT:
                                    printf("Protocol mode set: BOOT.\n");
                                    break;  
                                case HID_PROTOCOL_MODE_REPORT:
                                    printf("Protocol mode set: REPORT.\n");
                                    break;
                                default:
                                    printf("Unknown protocol mode.\n");
                                    break; 
                            }
                            break;

                        case HID_SUBEVENT_CONNECTION_CLOSED:
                            // The connection was closed.
                            hid_host_cid = 0;
                            hid_host_descriptor_available = false;
                            printf("HID Host disconnected.\n");
                            break;
                        
                        default:
                            break;
                    }
                    break;
                default:
                    break;
            }
            break;
        default:
            break;
    }
}
/* LISTING_END */

#ifdef HAVE_BTSTACK_STDIN
static void show_usage(void){
    bd_addr_t      iut_address;
    gap_local_bd_addr(iut_address);
    printf("\n--- Bluetooth HID Host Console %s ---\n", bd_addr_to_str(iut_address));
    printf("c      - Connect to %s in report mode, with fallback to boot mode.\n", remote_addr_string);
    printf("C      - Disconnect\n");
    
    printf("\n");
    printf("Ctrl-c - exit\n");
    printf("---\n");
}

static void stdin_process(char cmd){
    uint8_t status = ERROR_CODE_SUCCESS;
    switch (cmd){
        case 'c':
            printf("Connect to %s in report mode, with fallback to boot mode.\n", remote_addr_string);
            status = hid_host_connect(remote_addr, hid_host_report_mode, &hid_host_cid);
            break;
        case 'C':
            printf("Disconnect...\n");
            hid_host_disconnect(hid_host_cid);
            break;
        case '\n':
        case '\r':
            break;
        default:
            show_usage();
            break;
    }
    if (status != ERROR_CODE_SUCCESS){
        printf("HID host cmd \'%c\' failed, status 0x%02x\n", cmd, status);
    }
}
#endif

int btstack_main(int argc, const char * argv[]);
int btstack_main(int argc, const char * argv[]){

    (void)argc;
    (void)argv;

    hid_host_setup();

    // parse human readable Bluetooth address
    sscanf_bd_addr(remote_addr_string, remote_addr);

#ifdef HAVE_BTSTACK_STDIN
    btstack_stdin_setup(stdin_process);
#endif

    // Turn on the device 
    hci_power_control(HCI_POWER_ON);
    return 0;
}

/* EXAMPLE_END */