Go Down

Topic: incrementing an unsigned long (Read 126 times) previous topic - next topic

alanj100


I have a program that produces a square wave at a chosen frequency and a  chosen duty cycle . They are both unsiged longs




unsigned long Freq = 6; // the chosen frequency in Hz
unsigned long Duty = 30; // the chosen duty cycle in %

What I would like to do is increment the frequency between 1hz and 6hz say 10pulses at 1hz........ 10pulses an 6 hzs and then back to 1 .
I've been looking into how to increment unsigned longs but not really got anywere.

sherzaad

#1
Apr 17, 2019, 12:49 pm Last Edit: Apr 17, 2019, 12:57 pm by sherzaad
since is 1...6 and 10 pulses, WHY are you using 'unsigned long'. a uint8_t would be more that enough!

regarding your request now, is this something like this you after:

Code: [Select]
uint8_t freq_Hz[6] = {1,2,3,4,5,6};
uint8_t pulses = 10;
uint8_t duty = 30;

unsigned long period_ms;
unsigned long OnTime;

for(uint8_t i=0; i<6;++i){ //cycle through the 6 elements of freq_Hz array
period_ms = 1000/freq_Hz[i]; //calculate the period in ms of freq_Hz[i]
OnTime = (period_ms*100)/duty; //calculate from % duty cycle the ON time in ms;

for(uint8_t j=0; j<pulses;++j){
digitalWrite(out_pin, HIGH); //you define what your output pin is
delay(OnTime);
digitalWrite(out_pin, LOW);
delay(period_ms - OnTime);
}
}


depending on you requirements, you could implement using 'millis()' if you need an non-blocking code...

hope that helps.

alanj100


UKHeliBob

#3
Apr 17, 2019, 04:23 pm Last Edit: Apr 17, 2019, 05:42 pm by UKHeliBob
Quote
I've been looking into how to increment unsigned longs but not really got anywere.
Although you don't need to use unsigned longs I would be fascinated to see what you tried
Please do not send me PMs asking for help.  Post in the forum then everyone will benefit from seeing the questions and answers.

alanj100

This program works excatly how I want . just had to alter one thing

 OnTime = (period_ms*duty)/100;
   The duty and 100 were around the wrong way.
Thanks again

jremington

#5
Apr 17, 2019, 05:04 pm Last Edit: Apr 17, 2019, 05:40 pm by jremington
Quote
I've been looking into how to increment unsigned longs but not really got anywere.
Using a construct like "x++" did not work for you?

Go Up