How do I fix the cycle time for the canbus signal?

I have the time set I thought for both Canbus msgs but it seems one is perfect 5.0 and the other is 0.2. I need them both 5.0 and I'm a little bit stumped as coding is not my strong suit. Actually I'm really stumped and coding is not even a suit in my world but I'm trying.

#include <FlexCAN_T4.h>


const int ledPin = 13;

FlexCAN_T4<CAN1, RX_SIZE_256, TX_SIZE_16> Can1;


void setup() {
// put your setup code here, to run once:
Serial.begin(9600);
pinMode(ledPin, OUTPUT);

Can1.begin();
Can1.setBaudRate(500*1000);


}

void loop() {
// put your main code here, to run repeatedly:
CAN_message_t frame;
frame.id = 0x201;
frame.len = 8;
frame.buf[0] = 0x0C;
frame.buf[1] = 0x80;
frame.buf[2] = 0x00;
frame.buf[3] = 0x00;
frame.buf[4] = 0x27;
frame.buf[5] = 0x10;
frame.buf[6] = 0x14;
frame.buf[7] = 0x00;
Can1.write(frame);


frame.id = 0x432;
frame.len = 8;
frame.buf[0] = 0x00;
frame.buf[1] = 0x00;
frame.buf[2] = 0x00;
frame.buf[3] = 0x00;
frame.buf[4] = 0x00;
frame.buf[5] = 0x00;
frame.buf[6] = 0x00;
frame.buf[7] = 0x08;
Can1.write(frame);


;Can1.write(frame);

if ( Can1.read(frame) )
{
Serial.print("CAN1 ");
Serial.print(" ID: 0x"); Serial.print(frame.id, HEX );
}



digitalWrite(ledPin, !digitalRead(ledPin));
delay (5);
}


This is what happens. I don't see why the cycle times are different.

IMG_4593.JPG
 
I would remove the delay(5) and use millis() so it doesn't block your loop.

in the loop():
Code:
static uint32_t t = millis();
if ( millis() -t > 5000 ) {
  // write your Can1 frames here... non blocking every 5 seconds.
  t = millis(); // reset 5 second counter
}

the Can1.read() can be ran outside of that scope as it doesn't need a delay
 
I ended up commenting out this line. Once I did that it ran perfect and turned on the unit. Works beautiful.

//;Can1.write(frame);

Thank you Tony for your help.
 
I would remove the delay(5) and use millis() so it doesn't block your loop.

in the loop():
Code:
static uint32_t t = millis();
if ( millis() -t > 5000 ) {
  // write your Can1 frames here... non blocking every 5 seconds.
  t = millis(); // reset 5 second counter
}

the Can1.read() can be ran outside of that scope as it doesn't need a delay

I am also going to try your way tomorrow with the millis. It is a better way.
 
anywhere in the loop(), outside of your timer scope. it doesn't need delays

Code:
void loop() {
  Can1.events();
  // other code
}
 
Back
Top