chibios 16.1.9
Code: Select all
#include "ch.h"
#include "hal.h"
#define MODULE_ID 222
#define CAN_BUFFER_SIZE 32
mailbox_t can_send_mailbox;
msg_t can_send_buffer[CAN_BUFFER_SIZE];
static const CANConfig cancfg = {CAN_MCR_ABOM | CAN_MCR_AWUM | CAN_MCR_TXFP,
CAN_BTR_SJW(1) | CAN_BTR_TS2(1)
| CAN_BTR_TS1(6) | CAN_BTR_BRP(179)};
/*
* Receiver thread.
*/
static THD_WORKING_AREA(can_rx_wa, 256);
static THD_FUNCTION(can_rx, p) {
event_listener_t el;
CANRxFrame rxmsg;
(void)p;
chRegSetThreadName("receiver");
chEvtRegister(&CAND1.rxfull_event, &el, 0);
while (!chThdShouldTerminateX()) {
if (chEvtWaitAnyTimeout(ALL_EVENTS, MS2ST(100)) == 0)
continue;
while (canReceive(&CAND1, CAN_ANY_MAILBOX, &rxmsg, TIME_IMMEDIATE) == MSG_OK ) {
palTogglePad(IOPORT3, GPIOC_LED);
}
}
chEvtUnregister(&CAND1.rxfull_event, &el);
}
/*
* Transmitter thread.
*/
static THD_WORKING_AREA(can_tx_wa, 256);
static THD_FUNCTION(can_tx, p) {
CANTxFrame txmsg;
uint8_t *pbuf; // буфер сообщений
(void)p;
chRegSetThreadName("transmitter");
txmsg.IDE = CAN_IDE_EXT;
txmsg.EID = 0x01234567;
txmsg.RTR = CAN_RTR_DATA;
txmsg.DLC = 8;
txmsg.data32[0] = 0x55AA55AA;
txmsg.data32[1] = 0x00FF00FF;
while (!chThdShouldTerminateX()) {
// вот здесь тред останавливается и ждет пока не появятся в майлбоксе сообщения
chMBFetch(&can_send_mailbox, (msg_t *)&pbuf, TIME_INFINITE);
txmsg.EID = (uint32_t)(1 << 24 | 2 << 16 | 0 << 8 | pbuf[0]);
canTransmit(&CAND1, CAN_ANY_MAILBOX, &txmsg, MS2ST(100));
chThdSleepMilliseconds(30); // calculate = 1 / can_speed * 600
}
}
int main(void) {
halInit();
chSysInit();
// create CAN send mailbox
chMBObjectInit(&can_send_mailbox, can_send_buffer, CAN_BUFFER_SIZE);
canStart(&CAND1, &cancfg);
chThdCreateStatic(can_rx_wa, sizeof(can_rx_wa), NORMALPRIO + 7, can_rx, NULL);
chThdCreateStatic(can_tx_wa, sizeof(can_tx_wa), NORMALPRIO + 7, can_tx, NULL);
uint8_t buff[1];
uint8_t i = 0;
while (true) {
if(i > 99) i = 0;
buff[0] = i;
chMBPost(&can_send_mailbox, (msg_t)buff, TIME_INFINITE);
i++;
palTogglePad(IOPORT3, GPIOC_LED);
}
return 0;
}
Generate a message on the CAN bus.
The first message passes, the remaining 32 disappear in the mailbox.
The number of missing messages is equal to the size of the mailbox buffer (32)
Can log:
02064.0.0041 | 170.085.170.085.255.000.255.000 17:59:21.945
02064.0.0040 | 170.085.170.085.255.000.255.000 17:59:21.915
02064.0.0039 | 170.085.170.085.255.000.255.000 17:59:21.883
02064.0.0038 | 170.085.170.085.255.000.255.000 17:59:21.853
02064.0.0037 | 170.085.170.085.255.000.255.000 17:59:21.824
02064.0.0036 | 170.085.170.085.255.000.255.000 17:59:21.793
02064.0.0035 | 170.085.170.085.255.000.255.000 17:59:21.765
02064.0.0034 | 170.085.170.085.255.000.255.000 17:59:21.734
02064.0.0033 | 170.085.170.085.255.000.255.000 17:59:21.704
02064.0.0000 | 170.085.170.085.255.000.255.000 17:59:21.677