本帖最后由 小宏121 于 2024-7-17 23:39 编辑
复制官方的例程“UART_Transmit_and_Receive”到自己的工程目录下,并且修改为my_uart_test
点击添加新的工程,选择工程所在的目录
等待一段时间,让MTB构建好工程
修改代码,让MCU接收到字符串 "Hello, CYW920829." 后会返回 "Hi, my friend!"
#include "cyhal.h"
#include "cybsp.h"
#include "cy_retarget_io.h"
#include <string.h>
/*******************************************************************************
* Function Name: handle_error
********************************************************************************
* Summary:
* User defined error handling function.
*
* Parameters:
* void
*
* Return:
* void
*
*******************************************************************************/
void handle_error(void)
{
/* Disable all interrupts. */
__disable_irq();
CY_ASSERT(0);
}
/*******************************************************************************
* Function Name: main
********************************************************************************
* Summary:
* This is the main function.
* Reads one byte from the serial terminal and echoes back the read byte.
*
* Parameters:
* void
*
* Return:
* int
*
*******************************************************************************/
int main(void)
{
cy_rslt_t result;
#if defined(CY_DEVICE_SECURE)
cyhal_wdt_t wdt_obj;
/* Clear watchdog timer so that it doesn't trigger a reset */
result = cyhal_wdt_init(&wdt_obj, cyhal_wdt_get_max_timeout_ms());
CY_ASSERT(CY_RSLT_SUCCESS == result);
cyhal_wdt_free(&wdt_obj);
#endif
uint8_t read_data; /* Variable to store the received character
* through terminal */
uint8_t str_buff[50] = {0};
char * cmp_str = "Hello, CYW920829.";
char * my_ack = "Hi, my friend!";
uint8_t index = 0;
uint8_t start_recv = 1;
/* Initialize the device and board peripherals */
result = cybsp_init();
if (result != CY_RSLT_SUCCESS)
{
handle_error();
}
/* Initialize retarget-io to use the debug UART port */
result = cy_retarget_io_init_fc(CYBSP_DEBUG_UART_TX,
CYBSP_DEBUG_UART_RX,
CYBSP_DEBUG_UART_CTS,
CYBSP_DEBUG_UART_RTS,
CY_RETARGET_IO_BAUDRATE);
if (result != CY_RSLT_SUCCESS)
{
handle_error();
}
/* \x1b[2J\x1b[;H - ANSI ESC sequence for clear screen */
printf("\x1b[2J\x1b[;H");
printf("***********************************************************\r\n");
printf("HAL: UART Transmit and Receive\r\n");
printf("***********************************************************\r\n\n");
printf(">> Start typing to see the echo on the screen \r\n\n");
__enable_irq();
for (;;)
{
if (CY_RSLT_SUCCESS == cyhal_uart_getc(&cy_retarget_io_uart_obj,
&read_data, 0))
{
if (read_data == cmp_str[0])
{
index = 0;
start_recv = 0;
memset(str_buff, 0, sizeof(str_buff));
}
if (start_recv == 0)
{
str_buff[index++] = read_data;
if (index == strlen(cmp_str))
{
start_recv = 1;
if(0 == strcmp((char *)str_buff, cmp_str))
{
for (uint8_t i=0; i < (strlen(my_ack) - 1); ++i)
{
cyhal_uart_putc(&cy_retarget_io_uart_obj, my_ack[i]);
}
printf("\r\n");
}
else
{
printf("request err\r\n");
}
}
}
}
else
{
handle_error();
}
}
}
测试效果如下:
|