0

I’m trying to output a frequency that can be increased and decreased by using 2 buttons. I’m trying to first of all configure the first button (which increases the frequency). I’m trying to also add button denouncing to not get incorrect button states. I’ve commented out anything that relates to button 2.

#include <TimerOne.h>
//Button States
boolean buttonState = LOW;
//boolean buttonState2 = LOW;

 boolean oldbutton1state = LOW;
//boolean oldbutton2state = LOW;

boolean newbutton1state = LOW;
//boolean newbutton2state = LOW;


//Time period in ms (T)
int period = 1000;
//int period2 = 1000;
float period_float = 1000.0;

//Output pins
int sig_out = 9;
//int sig_out2 = 10;

//Input Pins 
int button =2;
//int button2 =3;

void setup() 
{
  Serial.begin(9600);
  pinMode(button,INPUT_PULLUP);
  //pinMode(button2,INPUT_PULLUP);
  pinMode(sig_out, OUTPUT);
  //pinMode(sig_out2, OUTPUT);
  Timer1.initialize(1000);
  Timer1.pwm(sig_out,512,period);
  //Timer1.pwm(sig_out2,512,period2);
 }

void loop() 
{
   buttonState = digitalRead(button);
   //buttonState2 = digitalRead(button2);
   newbutton1state = debounceButton(buttonState);

    if ((newbutton1state != oldbutton1state) && (newbutton1state == HIGH)) 
 {
       oldbutton1state = newbutton1state;  

     float freq_change = 100.0/1000000.0;
  Serial.println(freq_change);

  period_float = (period_float)/(1+(period_float*freq_change));
  Timer1.setPeriod(period_float);
  Serial.println(period_float);

  Timer1.pwm(9, 512);
  buttonState=LOW;
  Serial.print("Signal 1 Frequency: ");
  float freq = 1000000.0/(period_float);
  Serial.print(freq);
  Serial.println("Hz");

  delay(100);   
   }
}

boolean debounceButton(boolean state)
{
  boolean stateNow = digitalRead(button);
  if(state!=stateNow)
  {
    delay(50);
    stateNow = digitalRead(button);
  }
  return stateNow;
}

The issue is, when I load the code onto the Arduino, a 1KHz signal is being outputted, but every time I press button, nothing happens. I just wanted to know if anyone could shed light onto this issue. I think it may be due to the debouncing function (that it doesn’t work properly).

  • 1
    Did you try using a debouncing library? – Edgar Bonet Sep 13 at 8:22
  • 2
    why do you compare to HIGH? you have INPUT_PULLUP. the input should be always HIGH unless the button grounds the pin – Juraj Sep 13 at 9:16
  • Should i compare to LOW? – Neamus Sep 13 at 9:30
  • 1
    how did you wire the buttons? do hey have pull-up or pull-down or do you want to use the internal pull-up? – Juraj Sep 13 at 9:42
  • 1
    I have used the pull up formation for the button. So one button pin to ground and a pull up resistor at the other pin – Neamus Sep 13 at 10:05

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Browse other questions tagged or ask your own question.