在 main 目錄中創建一個名為 main.cpp 的檔案,並添加以下程式碼:
#include <iostream>
#include "driver/uart.h"
#include "freertos/FreeRTOS.h"
#include "freertos/task.h"
#include "string.h"
#include "esp_log.h" // Include the ESP-IDF log library
// Define a tag for logging
static const char *TAG = "UART_LOG"; // Tag for identifying log messages
class UART {
private:
uart_port_t uart_num;
public:
// Constructor: Initialize UART port
UART(uart_port_t uart_num, int tx_pin, int rx_pin, int baud_rate) : uart_num(uart_num) {
uart_config_t uart_config = {
.baud_rate = baud_rate,
.data_bits = UART_DATA_8_BITS,
.parity = UART_PARITY_DISABLE,
.stop_bits = UART_STOP_BITS_1,
.flow_ctrl = UART_HW_FLOWCTRL_DISABLE
};
// Configure UART parameters
esp_err_t err = uart_param_config(uart_num, &uart_config);
if (err != ESP_OK) {
ESP_LOGE(TAG, "Failed to configure UART parameters: %s", esp_err_to_name(err));
}
err = uart_set_pin(uart_num, tx_pin, rx_pin, UART_PIN_NO_CHANGE, UART_PIN_NO_CHANGE);
if (err != ESP_OK) {
ESP_LOGE(TAG, "Failed to set UART pins: %s", esp_err_to_name(err));
}
err = uart_driver_install(uart_num, 1024 * 2, 0, 0, NULL, 0);
if (err != ESP_OK) {
ESP_LOGE(TAG, "Failed to install UART driver: %s", esp_err_to_name(err));
}
}
// Method to send data
void sendData(const char *data) {
int len = uart_write_bytes(uart_num, data, strlen(data));
ESP_LOGI(TAG, "Sent %d bytes: %s", len, data);
}
// Method to receive data
void receiveData() {
uint8_t data[128];
int length = uart_read_bytes(uart_num, data, sizeof(data) - 1, 100 / portTICK_PERIOD_MS);
if (length > 0) {
data[length] = '\0'; // Null-terminate the received data
ESP_LOGI(TAG, "Received: %s", data);
}
}
};
extern "C" void app_main() {
// Create UART object, configure UART1, and specify TX and RX pins
UART uart(UART_NUM_1, GPIO_NUM_17, GPIO_NUM_16, 115200);
// Send data every 2 seconds
while (true) {
uart.sendData("Hello, UART!\n");
uart.receiveData(); // Receive data
vTaskDelay(2000 / portTICK_PERIOD_MS);
}
}
說明 : 1. UART 類別和建構子:在 main.cpp 中定義 UART 類別,並使用建構子初始化 UART 參數。 2. 參數配置:建構子使用 uart_param_config 設置 UART 參數,並使用 uart_set_pin 指定 TX 和 RX 引腳。 3. 資料傳輸與接收:sendData 方法用於通過 UART 發送字串,receiveData 方法用於接收資料並輸出。