HPM6750有4个CAN控制器,支持CANFD,目前在工业上用的还是CAN2.0比较多,本次测评使用CAN1控制器。CAN驱动芯片使用TI的VD230,电脑端使用了一个USB转CAN调试器,带有调试上位机软件。
连线如下:
1.初始化CAN引脚和时钟
HPM_IOC->PAD[IOC_PAD_PE31].FUNC_CTL = IOC_PE31_FUNC_CTL_CAN1_TXD;
HPM_IOC->PAD[IOC_PAD_PE30].FUNC_CTL = IOC_PE30_FUNC_CTL_CAN1_RXD;
/* Set the CAN1 peripheral clock to 80MHz */
clock_set_source_divider(clock_can1, clk_src_pll1_clk1, 5);
freq = clock_get_frequency(clock_can1);
2.初始化CAN
can_config_t can_config;
can_get_default_config(&can_config);
can_config.baudrate = 500000; /* 500kbps */
can_config.mode = can_mode_normal;
board_init_can(HPM_CAN1);
uint32_t can_src_clk_freq = board_init_can_clock(BOARD_APP_CAN_BASE);
hpm_stat_t status = can_init(HPM_CAN1, &can_config, can_src_clk_freq);
if (status != status_success) {
printf("CAN initialization failed, error code: %d\n", status);
return;
}
3.设置CAN中断
can_enable_tx_rx_irq(HPM_CAN1, CAN_EVENT_RECEIVE);
intc_m_enable_irq_with_priority(IRQn_CAN1, 1);
4.CAN中断
SDK_DECLARE_EXT_ISR_M(IRQn_CAN1, test_can1_isr);
void test_can1_isr(void)
{
uint8_t flags = can_get_tx_rx_flags(HPM_CAN1);
if ((flags & CAN_EVENT_RECEIVE) != 0) {
can_read_received_message(HPM_CAN1, (can_receive_buf_t *)&s_can_rx_buf);
has_new_rcv_msg = true;
}
if ((flags & (CAN_EVENT_TX_PRIMARY_BUF | CAN_EVENT_TX_SECONDARY_BUF))) {
has_sent_out = true;
}
if ((flags & CAN_EVENT_ERROR) != 0) {
has_error = true;
}
can_clear_tx_rx_flags(HPM_CAN1, flags);
error_flags = can_get_error_interrupt_flags(HPM_CAN1);
can_clear_error_interrupt_flags(HPM_CAN1, error_flags);
}
5.CAN发送接收到的数据
while (!has_new_rcv_msg) {
}
has_new_rcv_msg = false;
show_received_can_message((const can_receive_buf_t *)&s_can_rx_buf);
can_transmit_buf_t tx_buf;
memset(&tx_buf, 0, sizeof(tx_buf));
tx_buf.dlc = s_can_rx_buf.dlc;
tx_buf.id = 0x321;
uint32_t msg_len = can_get_data_bytes_from_dlc(s_can_rx_buf.dlc);
memcpy(&tx_buf.data, (uint8_t *)&s_can_rx_buf.data, msg_len);
status = can_send_message_blocking(BOARD_APP_CAN_BASE, &tx_buf);
if (status != status_success) {
printf("CAN sent message failed, error_code:%d\n", status);
return;
}
6.测试程序,设置CAN调试器为CA2.0,波特率500k,标准模式,依次发送数据,接收均正常。
|