uart7联同rs485 通信的例子
程序如下:主程序main.c 和rs485.c 初始代码由cube产生 所以产生部分代码就不拿出来了 问题在最下面 麻烦直接跳到下面看问题 谢谢!
main.c如下
int main(void)
{
/* USER CODE BEGIN 1 */
/* USER CODE END 1 */
/* MCU Configuration----------------------------------------------------------*/
/* Reset of all peripherals, Initializes the Flash interface and the Systick. */
HAL_Init();
/* Configure the system clock */
SystemClock_Config();
/* Initialize all configured peripherals */
MX_GPIO_Init();
MX_UART7_Init();
/* USER CODE BEGIN 2 */
/* USER CODE END 2 */
/* Infinite loop */
/* USER CODE BEGIN WHILE */
while (1)
{
/* USER CODE END WHILE */
/* USER CODE BEGIN 3 */
uart_read(receive_data,&len); //这段看着2句
uart_send(receive_data,len);
}
/* USER CODE END 3 */
}
static void MX_UART7_Init(void)
{
huart7.Instance = UART7;
huart7.Init.BaudRate = 115200;
huart7.Init.WordLength = UART_WORDLENGTH_8B;
huart7.Init.StopBits = UART_STOPBITS_1;
huart7.Init.Parity = UART_PARITY_NONE;
huart7.Init.Mode = UART_MODE_TX_RX;
huart7.Init.HwFlowCtl = UART_HWCONTROL_NONE;
huart7.Init.OverSampling = UART_OVERSAMPLING_16;
huart7.Init.OneBitSampling = UART_ONE_BIT_SAMPLE_DISABLE;
huart7.AdvancedInit.AdvFeatureInit = UART_ADVFEATURE_NO_INIT;
if (HAL_UART_Init(&huart7) != HAL_OK)
{
Error_Handler();
}
if(HAL_UART_Receive_IT(&huart7,(uint8_t *)aRxbuffer,1) != HAL_OK) //这里是进入中断的放在while之前的
{
Error_Handler();
}
}
rs485.c如下
void HAL_UART_RxCpltCallback(UART_HandleTypeDef *huart7) //回调函数 接收数据放入aRxbuffer,RS485_RX_CNT为接收的个数
{
uint8_t ret = HAL_OK;
/* Set transmission flag: trasfer complete*/
do
{
++RS485_RX_CNT;
ret = HAL_UART_Receive_IT(huart7,&aRxbuffer[RS485_RX_CNT],1);
}while((ret !=HAL_OK));
}
void uart_read(uint8_t *buf,uint8_t *len)
{
uint8_t rxlen=RS485_RX_CNT;
uint8_t i=0;
*len=0;
HAL_Delay(100);
if((rxlen==(RS485_RX_CNT)) && rxlen ) //接收完成后数据放入buf[]里,将RS485_RX_CNT传出并置零
{
for(i=0;i<rxlen+1;i++)
{
buf[i]=aRxbuffer[i];
}
*len=RS485_RX_CNT+1;
RS485_RX_CNT=0; //置零之后 下次接收应该从数组aRxbuffer[0]开始放数据啊
}
}
void uart_send(uint8_t *buf,uint8_t len) //将buf的数据打印
{
uint8_t i;
HAL_GPIO_WritePin(GPIOE,DE_Pin, GPIO_PIN_SET);
for(i=0;i<len;i++)
{
while(HAL_UART_GetState(&huart7)==RESET);
printf("%c",buf[i]);
}
while(HAL_UART_GetState(&huart7)==RESET);
HAL_GPIO_WritePin(GPIOE,DE_Pin, GPIO_PIN_RESET);
//RS485_RX_CNT=0;
}
遇到问题: 我想实现将接收的数据原样输出,现在是下载程序后 发送ABC,循环输出ABC,再向它发送abc,循环输出ABCabc
想不通为啥RS485_RX_CNT=0;这句不起作用吗 我是短路了,请教下局外“旁观者清”
一周热门 更多>