How can I simplify this code into a function

im at the very beginning of a project on WOKWI where im learning about servos. My first step is to connect 4 push buttons (so far only need two) to control a select amount of servos. currently ive made it so if you press the up pushbutton the servo moves to the left and if you press the down one vice versa. I was wondering how i would be able to put this into a function. Yes i've read about functions but cant quite figure out how to create one for this type of code. the part I want to put in a function is the code right after void loop() and before the checkbutton functions. Here is the code - any help would be great

#include <Servo.h>

Servo servo1;

// Define the pins that the pushbuttons are connected to
const int buttonPinYup = 11;
const int buttonPinXr = 10;
const int buttonPinYdown = 9;
const int buttonPinXl = 8;


int servo1_pin = 7;  // declare variable for digital output pin for servo1
int servo2_pin = 12;  // declare variable for digital output pin for servo2

int initial_position = 90;   // declare variable for initial position of servo1
int initial_position1 = 90;  // declare variable for initial position of servo2

int lastButtonState;     // the previous state of button
int currentButtonState;  // the current state of button

void setup() {
  Serial.begin(9600);         // initialize serial communication with baud rate of 9600
  servo1.attach(servo1_pin);  // attach servo1 to its digital output pin

  servo1.write(initial_position);  // set initial position of servo1

  // Set the button pins as inputs with pull-up resistors
  pinMode(buttonPinYup, INPUT_PULLUP);
  pinMode(buttonPinYdown, INPUT_PULLUP);
  pinMode(buttonPinXl, INPUT_PULLUP);
  pinMode(buttonPinXr, INPUT_PULLUP);
}

// this is a function

/*
The function starts by reading the state of the button connected to the given pin number using the 
digitalRead function. The resulting value (HIGH or LOW) is stored in a variable called buttonState.

Next, the function checks if the buttonState is LOW, which indicates that the button is pressed.
 If the button is pressed, the function prints the message to the Serial Monitor using the Serial.println function. This message can be used to identify which button was pressed.

If the button is not pressed (i.e., buttonState is HIGH), nothing happens, and the function returns.

This function is used in the loop function to check the state of each button and print a corresponding
 message to the Serial Monitor if the button is pressed. By calling checkButton for each button, 
 the code avoids duplicating the same lines of code for each button and improves readability and maintainability.
*/
void checkButton(int buttonPin, const char* message) {
  int buttonState = digitalRead(buttonPin);
  if (buttonState == LOW) {
    Serial.println(message);
  }
}




void loop() {

 int currentButtonState = digitalRead(buttonPinYup);  // read new state
  int currentButtonState1 = digitalRead(buttonPinYdown);  // read new state

  if (currentButtonState == LOW) {


    // change angle of servo motor
    if (initial_position < 10) {  // if initial position is less than 10 degrees
    } else {
      initial_position = initial_position - 15;  // decrease initial position by 20 degrees
      servo1.write(initial_position);            // set new position of servo1
      delay(25);                                // wait 100 milliseconds
    }
  }
    if (currentButtonState1 == LOW) {


    // change angle of servo motor
    if (initial_position > 180) {  // if initial position is less than 10 degrees
    } else {
      initial_position = initial_position + 15;  // decrease initial position by 20 degrees
      servo1.write(initial_position);            // set new position of servo1
      delay(25);                                // wait 100 milliseconds
    }
  }

  // Print which button is being pressed to the Serial Monitor
  checkButton(buttonPinYup, "Up");
  checkButton(buttonPinYdown, "Down");
  checkButton(buttonPinXl, "Left");
  checkButton(buttonPinXr, "Right");
  // Wait a short time before reading the button states again
  delay(50);
}

Hello hollandmab

Do you have experience with programming in C++?

The task can easily be realised with an object.
A structured array contains all the information, such as the pin addresses for the I/O devices, as well as the information for the timing.
A single service takes care of this information and initiates the intended action.
The structured array makes the sketch scalable until all I/O pins are used up without having to adapt the code for the service.
It is cool stuff, isn´t it?

What I’m confused?

Did you mean inside loop()? Because there is no code after loop() in your sketch, it's the last function in the file.

This part?

int currentButtonState = digitalRead(buttonPinYup);  // read new state
  int currentButtonState1 = digitalRead(buttonPinYdown);  // read new state

  if (currentButtonState == LOW) {


    // change angle of servo motor
    if (initial_position < 10) {  // if initial position is less than 10 degrees
    } else {
      initial_position = initial_position - 15;  // decrease initial position by 20 degrees
      servo1.write(initial_position);            // set new position of servo1
      delay(25);                                // wait 100 milliseconds
    }
  }
    if (currentButtonState1 == LOW) {


    // change angle of servo motor
    if (initial_position > 180) {  // if initial position is less than 10 degrees
    } else {
      initial_position = initial_position + 15;  // decrease initial position by 20 degrees
      servo1.write(initial_position);            // set new position of servo1
      delay(25);                                // wait 100 milliseconds
    }
  }

This could be made into a function very easily, but what would be the advantage of doing that, other than breaking up the code into more manageable parts?

One of the benefits of using functions is to reduce duplicated code. There is scope for doing that here. Is that what you were hoping to achieve?

What do you mean by " There is scope for doing that here. Is that what you were hoping to achieve?"

I mean there is the possibility, in the code you posted, for reducing duplicated code. You have told us you want to simplify your code. Generally speaking, reducing or removing duplicate code makes it simpler. (However, it's possible to go too far with that idea, making the code so small that it becomes less simple to understand.)

This topic was automatically closed 180 days after the last reply. New replies are no longer allowed.