#include <stdio.h>
#include <stdlib.h>
#include "freertos/FreeRTOS.h"
#include "freertos/task.h"
#include "freertos/semphr.h"
#include "esp_err.h"
#include "esp_log.h"
#include "driver/twai.h"
#include "esp_rom_sys.h"
static char *TAG = "Can";
#include "esp_timer.h"
//延时函数
void delay(int count)
{
int i;
for(i=1;i<=count;i++)
;
}
static const twai_general_config_t g_config = TWAI_GENERAL_CONFIG_DEFAULT(48, 47, TWAI_MODE_NORMAL);
static const twai_timing_config_t t_config = TWAI_TIMING_CONFIG_5KBITS();
static const twai_filter_config_t f_config = TWAI_FILTER_CONFIG_ACCEPT_ALL();
void CANSendData(uint8_t *buff, uint8_t len)
{
twai_message_t message;
message.identifier = 0x0101;
message.extd = 1;
if (len > 8)
{
len = 8;
}
message.data_length_code = len;
for (int i = 0; i < len; i++)
{
message.data[i] = buff[i];
}
// Queue message for transmission
esp_err_t reti=twai_transmit(&message, pdMS_TO_TICKS(1000));
if (reti==ESP_OK){
// ShowLog(TAG,"Send to Can",(char *)message.data,message.data_length_code,1);
printf("sucess");
}else{
ESP_LOGI(TAG, "Send to Can Error:%d", reti);
}
}
// void CANSendData(uint8_t *buff, uint8_t len)
// {
// twai_message_t message;
// message.identifier = 0x0101;
// message.extd = 0;
// if (len > 8)
// {
// len = 8;
// }
// message.data_length_code = len;
// for (int i = 0; i < len; i++)
// {
// message.data[i] = buff[i];
// }
// esp_err_t reti=twai_transmit(&message, 1000);
// if (reti==ESP_OK){
// ESP_LOGI(TAG, "Send to Can ok:%d", reti);
// // 传输完成后再次打印发送的数据
// ESP_LOGI(TAG, "Data transmission completed. Sent data:");
// for (int i = 0; i < len; i++)
// {
// ESP_LOGI(TAG, "Data[%d]: %02X", i, message.data[i]);
// }
// }else{
// ESP_LOGI(TAG, "Send to Can Error:%d", reti);
// }
// }
void CANREData(void){
twai_message_t rmessage;
if (twai_receive(&rmessage, 10000) == ESP_OK)
{
printf("re_secess");
}
else{
printf("re_unsecess");
}
}
void Can_task(void *pvParameters)
{
twai_message_t message;
// uint8_t dat[8]={1,2,3,4,5,6,7,8};
vTaskDelay(pdMS_TO_TICKS(1000));
while (1)
{
vTaskDelay(pdMS_TO_TICKS(500));
// CANSendData(dat, 8);
if (twai_receive(&message, pdMS_TO_TICKS(10000)) == ESP_OK)
{
for (int i = 0; i < 8; i++)
{
ESP_LOGI(TAG, "reData[%d]: %02X", i, message.data[i]);
}
// ShowLog(TAG,"Read from Can",(char *)message.data,message.data_length_code,1);
// Deal_ZhuangData(message.identifier,message.data,message.data_length_code);
if ((!message.extd) && (!message.rtr))
{
//ShowLog(TAG,"Read from Can",(char *)message.data,message.data_length_code,1);
}
}
}
vTaskDelete(NULL);
}
void app_main(void)
{
// Install TWAI driver
if (twai_driver_install(&g_config, &t_config, &f_config) == ESP_OK)
{
printf("Driver installed\n");
}
else
{
printf("Failed to install driver\n");
return;
}
// Start TWAI driver
if (twai_start() == ESP_OK)
{
printf("Driver started\n");
}
else
{
printf("Failed to start driver\n");
return;
}
xTaskCreate(Can_task, "ccTask", 4096, NULL, 8, NULL);
}
can串口随意发送:
结果如下: