Combine two sketches

Hi everybody,

It’s my first time working with Arduino and coding.
For school I have a project with an lcd, 2 servos, an ultrasonic ranger and a button.
I split the code in two different sketches, but when I tried combining them it doesn’t work. I’ve tried different things like changing the order but it won’t work.

I was wondering if somebody could help me and/or point me in the right direction. I would very grateful.

I have an Arduino Uno and I’m using a Grove Ultrasonic ranger and button. I have the servos connected to a breadboard. The sketches don’t give me any errors.

Sketch 1:

#include <Wire.h>
#include "rgb_lcd.h"
#include "Ultrasonic.h"
#include <PWMServo.h>

rgb_lcd lcd;
Ultrasonic ultrasonic(7);
PWMServo myservo2;

void setup() {
  lcd.begin(16,2);
  myservo2.attach(SERVO_PIN_B);

  Serial.begin(9600);
}

void loop() {  
  long RangeInCentimeters;
  RangeInCentimeters = ultrasonic.MeasureInCentimeters();
  myservo2.write(180);

  if(RangeInCentimeters >= 10) {
    lcd.clear();
  }

  if(RangeInCentimeters == 10) {
    delay(10);
    lcd.print("Beker ontvangen");
    lcd.setCursor(0, 1);
    lcd.print("Token");
    delay(1000);
    myservo2.write(90);
    delay(500);
    myservo2.write(180);
    delay(5000);   
  }

  Serial.print(RangeInCentimeters);
}

Sketch 2:

#include <PWMServo.h>
#include <Wire.h>
#include "rgb_lcd.h"

rgb_lcd lcd;
PWMServo myservo;

int switchPin = 4;
int val = 0;
int buttonState= 0;
int buttonPresses = 0;


void setup() {
  lcd.begin(16,2);
  pinMode(switchPin, INPUT);
  buttonState = digitalRead(switchPin);
  myservo.attach(SERVO_PIN_A); 

  Serial.begin(9600);
}

void loop () {
  val = digitalRead(switchPin);   //read input value and store it in val
  if (val != buttonState) {
    if (val == LOW) {
      buttonPresses++;
      Serial.print("button has been pressed ");
      Serial.print(buttonPresses);
      Serial.println(" times");
    }
  }
  buttonState = val;    //save the new state in our variable

  if (buttonPresses >= 3) {
    buttonPresses = 0;
  }

  if (buttonPresses == 1) {
    delay(10);
    lcd.clear();
    lcd.print("Standby");
    delay(15);
    myservo.write(5);
  }

  if (buttonPresses == 2) {
    delay(10);
    lcd.clear();
    lcd.print("Ready");
    delay(15);
    myservo.write(180);
    buttonPresses++;
  }

}

Show the combined sketch; does that compile?

Explain what you expect the combined code to do and what it does not do (assuming it compiles).

Hi,

See THIS PAGE about combining sketches. It's a common problem.