Serial Print and PWM signals

Hey all,

I would like some advice on the best approach to program my project.

I basically have some coils being driven with PWM signals, and an optical encoder attached to an interrupt.
In my main loop I output angle of rotation and RPM of the encoder using Serial print, and send PWM to my coils.

I am trying to serial print the encoder values, every 1 second for example from the main loop, but the way I was running my PWM coil signals is by using delay to keep sending the same pulse. What other way can I do this?

I.e. how can make my serial.print independent of any of the delays I may be using in my code? Should I make a PWM function that I pass the duty cycle and period I want that cycle to run for? how would I implement period size control of the PWM signal?

I hope Im making sense,

Thank y'all!

Use a millis() based approach.

E.g.

got you!

should I keep the main loop for just serial printing, and then call functions for all other actions on the board? like sending signals to PWM & reading encoders?

I read something about adding the interval vs. doing the different between current milli's, with regards to ensuring a consistent period of the same size, could you elaborate on that for me please?

Thanks!!

When you do not use any delays in the rest of your unknown code you could do a simple "Blink Without Delay" based function to print something every second.

void onceASecond()  {
  static uint32_t previousMillis = 0;
  if (millis() - previousMillis > 1000) {
    previousMillis = millis();
    Serial.print(F("something=")); Serial.println(rpm); //  rpm needs to be a global variable.
  }
}

call

onceASecond();

in your loop and you will see that something gets printed once a second.