Square pulses with variable frequency(1Hz-100Hz)

hi!!
i'm beginner here :roll_eyes:, can anyone tell me about how to generate square pulses having freq range 1hz-100hz & am working on stimulator for human body & for this i want to generate using potentiometer, also having variable amplitude.

your help will be very helpful for me.
Thanks in advace

Blink without delay.
Use micros()

Other than a learning experience, a terrible waste of a duino.....
How about a 555, some resistors, a cap, and some simple math?

Generating the squarewave is pretty easy using blink without delay style programming. We'll use an analog input to select the frequency.

int analogIn; // hold pot value
byte squareOut = 2; // output pin, PORTD bit 2 on an Uno
unsigned long halfPeriod; // 32 bit data to hold frequency = halfPeriod x 2
unsigned long currentMillis; // 32 bit value for time comparison
unsigned long elapsedMillis;  // 32 bit value for time comparison
unsigned long previousMillis; // 32 bit value for time comparison

void setup(){
pinMode (squareOut, OUTPUT);
// Serial.begin(115200); // send messages to serial monitor for debugging
}

void loop(){
// read the pot, which has one outer leg wired to +5, the other to Gnd, the wiper to A0
analogIn = analogRead(A0);  // number from 0 to 1023
// 100 Hz = 10mS period, change level every 5mS, or 5,000uS
// 1Hz = 1000mS period, change level every 500mS, or 500,000uS
// everything else is in between
if (analogIn <=10){
analogIn = 5; // max speed
}
if (analogIn >=1000){
halfPeriod = 500; // min speed
}
if ( (analogIn >10) & analogIn<1000){
halfPeriod = analogIn/2; // everything else
}

// see if time to change output level
currentMillis = millis(); // capture the current 'time'
elapsedMillis = currentMillis - previousMillis; // how much 'time' has passed since last capture
if (elapsedMillis >= halfPeriod){ // enough has passed: do something
previousMillis = previousMillis + halfPeriod; // set up for next level change
PIND = 0b00000100; // flips D2 from Hi to Lo, or Lo to Hi
}
// do other stuff while waiting for next half period
} // end loop

For amplitude variation:
Connect D2 to one leg of a 1k or 5K pot, other leg to Gnd, wiper is the variable level output.

Thank you soo much :slight_smile:
Let me try to understand it and practically implement this then if i'll have any query i'll ask you again.
thanks again for this great help:)

I didn't compile that, but it should be fairly close.

i'll fix those minor issues :slight_smile: thanks

@
CrossRoads

I want to ask, can i use any value of potentiometer for frequency selection let say 1k, does it matter on values in code?

No, does not matter.
Lower value will just use more current.
5V/1000 ohm = 5mA.
Voltage level at analog input will be the same.

Thank You soo much for your guidance :slight_smile:

You're welcome.

@
CrossRoads

Hi!!
one thing more i want to ask can i used the above code output for mega on digital pin 45(PORT D bit 2) ?

Sure.