/********* Pleasedontcode.com **********

	Pleasedontcode thanks you for automatic code generation! Enjoy your code!

	- Terms and Conditions:
	You have a non-exclusive, revocable, worldwide, royalty-free license
	for personal and commercial use. Attribution is optional; modifications
	are allowed, but you're responsible for code maintenance. We're not
	liable for any loss or damage. For full terms,
	please visit pleasedontcode.com/termsandconditions.

	- Project: Servo Control
	- Source Code NOT compiled for: Arduino Uno
	- Source Code created on: 2024-05-28 09:56:13

********* Pleasedontcode.com **********/

/****** SYSTEM REQUIREMENTS *****/
/****** SYSTEM REQUIREMENT 1 *****/
	/* I want to add a pushputton that controls the servo */
	/* motor */
/****** END SYSTEM REQUIREMENTS *****/

/****** DEFINITION OF LIBRARIES *****/
#include <Servo.h>  //https://github.com/arduino-libraries/Servo

/****** FUNCTION PROTOTYPES *****/
void setup(void);
void loop(void);
void updateOutputs(void);

/***** DEFINITION OF PWM OUTPUT PINS *****/
const uint8_t mypush_Servomotor_PWMSignal_PIN_D9 = 9;  // Changed to pin 9 as per the example
const uint8_t potpin = A0;  // Potentiometer pin
const uint8_t buttonPin = 2;  // Push button pin

/***** DEFINITION OF OUTPUT RAW VARIABLES *****/
/***** used to store raw data *****/
uint8_t mypush_Servomotor_PWMSignal_PIN_D9_rawData = 0;

/***** DEFINITION OF OUTPUT PHYSICAL VARIABLES *****/
/***** used to store data after characteristic curve transformation *****/
float mypush_Servomotor_PWMSignal_PIN_D9_phyData = 0.0;

/****** DEFINITION OF LIBRARIES CLASS INSTANCES*****/
Servo myservo;  // Create servo object to control a servo

void setup(void)
{
  // put your setup code here, to run once:
  myservo.attach(mypush_Servomotor_PWMSignal_PIN_D9);  // Attaches the servo on pin 9 to the servo object
  pinMode(buttonPin, INPUT);  // Set the button pin as an input
}

void loop(void)
{
  // put your main code here, to run repeatedly:
  updateOutputs();  // Refresh output data
}

void updateOutputs()
{
  static bool buttonPressed = false;  // Variable to store the button state

  // Read the button state
  if (digitalRead(buttonPin) == HIGH) {
    buttonPressed = !buttonPressed;  // Toggle the button state
    delay(200);  // Debounce delay
  }

  if (buttonPressed) {
    int val = analogRead(potpin);  // Read the value of the potentiometer
    val = map(val, 0, 1023, 0, 180);  // Scale it to use it with the servo (value between 0 and 180)
    myservo.write(val);  // Set the servo position according to the scaled value
  } else {
    myservo.write(90);  // Set the servo to the neutral position (90 degrees) when the button is not pressed
  }

  delay(15);  // Wait for the servo to reach the position
}

/* END CODE */