nrf52官方串口例程

nrf52开发板拿到手快半年了,之前只跑过一次官方例程,然后就放一边了,现在准备学习一下,首先从串口开始。


串口例程有两个,这里直接使用ble_app_uart这个例程,这是基于ble的例程,可以通过ble主机和开发版进行通讯,收发数据通过串口实现。

看了初始化函数,知道了默认波特率是38400,(可以通过修改宏改变波特率),然后将例程编译烧录,例程跑起来了,但是串口助手却没有输出任何数据,很奇怪,于是开关串口助手,偶尔会打印出来一个字符,不知道哪里的问题,于是换了一个串口助手,还是一样,拿手机可以连接ble,并且单步调试也是可以运行的,一时不知道怎么回事了,于是在网上找资料,看到一篇51串口讲解的,串口配置图都有,对比了一下,发下里面还配置了  串口中断超时100ms,以前从来没有调过这个参数,然后找到自己助手里有读间隔超时1ms,改为100ms,奇迹出现了,串口好了(自己已经改了波特率115200了),这个问题是字符传输间隔时间过程导致了超时。


串口通了,可以继续学习nrf52了


将uart添加到其它工程非常方便,当然下面这样操作是不推荐的,最快捷添加uart的方式是直接往main函数上面添加如下代码:




struct ble_nus_s;


/* Forward declaration of the ble_nus_t type. */
typedef struct ble_nus_s ble_nus_t;


/**@brief Nordic UART Service event handler type. */
typedef void (*ble_nus_data_handler_t) (ble_nus_t * p_nus, uint8_t * p_data, uint16_t length);




struct ble_nus_s
{
    uint8_t                  uuid_type;               /**< UUID type for Nordic UART Service Base UUID. */
    uint16_t                 service_handle;          /**< Handle of Nordic UART Service (as provided by the S110 SoftDevice). */
    ble_gatts_char_handles_t tx_handles;              /**< Handles related to the TX characteristic (as provided by the S110 SoftDevice). */
    ble_gatts_char_handles_t rx_handles;              /**< Handles related to the RX characteristic (as provided by the S110 SoftDevice). */
    uint16_t                 conn_handle;             /**< Handle of the current connection (as provided by the S110 SoftDevice). BLE_CONN_HANDLE_INVALID if not in a connection. */
    bool                     is_notification_enabled; /**< Variable to indicate if the peer has enabled notification of the RX characteristic.*/
    ble_nus_data_handler_t   data_handler;            /**< Event handler to be called for handling received data. */
};


/* Forward declaration of the ble_nus_t type. */
typedef struct ble_nus_s ble_nus_t;


#define BLE_UUID_NUS_SERVICE 0x0001                      /**< The UUID of the Nordic UART Service. */
#define BLE_NUS_MAX_DATA_LEN (GATT_MTU_SIZE_DEFAULT - 3) /**< Maximum length of data (in bytes) that can be transmitted to the peer by the Nordic UART service module. */


static ble_nus_t                        m_nus;                                      /**< Structure to identify the Nordic UART Service. */


/**@brief   Function for handling app_uart events.
 *
 * @details This function will receive a single character from the app_uart module and append it to 
 *          a string. The string will be be sent over BLE when the last character received was a 
 *          'new line' i.e '\n' (hex 0x0D) or if the string has reached a length of 
 *          @ref NUS_MAX_DATA_LENGTH.
 */
/**@snippet [Handling the data received over UART] */
void uart_event_handle(app_uart_evt_t * p_event)
{
    static uint8_t data_array[BLE_NUS_MAX_DATA_LEN];
    static uint8_t index = 0;
    uint32_t       err_code;


    switch (p_event->evt_type)
    {
        case APP_UART_DATA_READY:
            UNUSED_VARIABLE(app_uart_get(&data_array[index]));
            index++;


            if ((data_array[index - 1] == '\n') || (index >= (BLE_NUS_MAX_DATA_LEN)))
            {
               // err_code = ble_nus_string_send(&m_nus, data_array, index);
                if (err_code != NRF_ERROR_INVALID_STATE)
                {
                    APP_ERROR_CHECK(err_code);
                }
                
                index = 0;
            }
            break;


        case APP_UART_COMMUNICATION_ERROR:
            APP_ERROR_HANDLER(p_event->data.error_communication);
            break;


        case APP_UART_FIFO_ERROR:
            APP_ERROR_HANDLER(p_event->data.error_code);
            break;


        default:
            break;
    }
}
/**@snippet [Handling the data received over UART] */




/**@brief  Function for initializing the UART module.
 */
/**@snippet [UART Initialization] */
static void uart_init(void)
{
    uint32_t                     err_code;
    const app_uart_comm_params_t comm_params =
    {
        RX_PIN_NUMBER,
        TX_PIN_NUMBER,
        RTS_PIN_NUMBER,
        CTS_PIN_NUMBER,
        APP_UART_FLOW_CONTROL_ENABLED,
        false,
        UART_BAUDRATE_BAUDRATE_Baud115200
    };


    APP_UART_FIFO_INIT( &comm_params,
                       UART_RX_BUF_SIZE,
                       UART_TX_BUF_SIZE,
                       uart_event_handle,
                       APP_IRQ_PRIORITY_LOW,
                       err_code);
    APP_ERROR_CHECK(err_code);
}
/**@snippet [UART Initialization] */




/**@brief Function for application main entry.
 */
int main(void)
{
    bool erase_bonds;
    uint32_t err_code;


    // Initialize.
    app_trace_init();
    timers_init();
    buttons_leds_init(&erase_bonds);
    ble_stack_init();
    scheduler_init();
    device_manager_init(erase_bonds);
    gap_params_init();
    advertising_init();
    services_init();
    sensor_simulator_init();
    conn_params_init();
    buffer_init();
//add by allen
uart_init();


    // Start execution.
    timers_start();
    err_code = ble_advertising_start(BLE_ADV_MODE_FAST);
    APP_ERROR_CHECK(err_code);
printf("hello nordic...\n");
    // Enter main loop.
    for (;;)
    {
        app_sched_execute();
        power_manage();
    }
}


/**
 * @}
 */




这样就能打印了,是不是很方便





阅读源码发现demo里面是自带调试信息的,main函数中app_trace_init();就是初始化调试信息,也就是自带串口驱动的,只需要添加宏ENABLE_DEBUG_LOG_SUPPORT的定义即可打开,看来nordic还是很人性化的,调试起来方便多了。

### nRF52 UART 串口发送数据实现方法 要在 nRF52 上通过 UART 实现串口发送功能,通常需要完成以下几个方面的设置和操作: #### 初始化 UART 配置 在使用 UART 功能之前,必须先对其进行初始化。这包括配置波特率、停止位、校验模式以及中断处理等内容。 以下是基于 Nordic 提供的 `app_uart` 库的一个典型初始化代码示例[^1]: ```c #include "nrf_drv_uart.h" #include "app_error.h" void uart_init(void) { uint32_t err_code; const nrf_drv_uart_config_t uart_config = NRF_DRV_UART_DEFAULT_CONFIG; uart_config.pseltxd = TX_PIN_NUMBER; // 定义TX引脚号 uart_config.pselrxd = RX_PIN_NUMBER; // 定义RX引脚号 (如果不需要接收可忽略) uart_config.baudrate = NRF_UART_BAUDRATE_115200; // 设置波特率为115200 APP_ERROR_CHECK(nrf_drv_uart_init(&uart_instance, &uart_config, NULL)); } ``` 上述代码中定义了 UART 的基本参数,并指定了 TX 和 RX 引脚编号。需要注意的是,默认情况下使用的波特率为 38400bps,但可以通过修改宏来调整到其他速率,例如常见的 9600 或 115200 bps[^3]。 #### 数据发送逻辑 当硬件部分准备就绪之后,就可以利用库函数向外部设备发送数据了。下面展示了一种简单的字符串发送方式[^2]: ```c void send_string(const char *str){ while(*str != '\0'){ app_uart_put(*(uint8_t *) str++); } } int main(){ uart_init(); // 调用前面定义好的初始化函数 send_string("Hello World!\r\n"); // 测试输出消息 while(1); } ``` 这里采用了循环逐字节写入的方法直到遇到终止符为止;其中每次调用 `app_uart_put()` 函数负责实际的数据传递工作。 另外值得注意的一点是,在某些特定条件下可能还需要额外考虑超时机制等问题才能保证通信正常运作。比如曾经有人报告说即使程序能够成功执行却无法正确显示结果的情况就是因为缺少适当的时间延迟控制所致。 综上所述,对于希望快速搭建起基础框架以便进一步开发复杂应用场合下的开发者来说,按照以上步骤应该足以满足大多数常规需求了。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

路人 假

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值