Can anyone pls help me merge this two arduino codes so that they can work together?

//1stcode(its for a motor to work while sensing sound)

#include <Servo.h> //servo library
Servo servo;

int servoPin = 7;

const int soundSensorPin = A0; // Define the analog pin for sound sensor

void setup() {
Serial.begin(9600);
pinMode(soundSensorPin,INPUT);
servo.attach(servoPin);
servo.write(0); //close cap on power on
delay(100);
servo.detach();
}

void loop() {

int sensorValue = analogRead(soundSensorPin);
if (sensorValue < 750 || sensorValue > 840)
{
Serial.print("clap detected");
Serial.println(sensorValue);
servo.attach(servoPin);
delay(1);
servo.write(0);
delay(3000);
servo.write(150);
delay(1000);
servo.detach();
}
delay(10);
}

//2nd code(its for sensing various things and uploading to thingspeak)

#include <WiFiNINA.h>
#include <WiFiSSLClient.h>
#include <DHT.h>

// Replace with your network credentials
const char* ssid = "snekib";
const char* password = "snekib654";

// Replace with your ThingSpeak API key
String apiKey = "yourapikey";

// Replace with your ThingSpeak channel ID
const unsigned long channelId = ''yourid'';

// Set DHT22 sensor pin
const int dhtPin = 4;

// Set MQ-7 sensor pin
const int mq7Pin = A1;

// Set HC-SR04 sensor pins
const int TRIG_PIN = 6;
const int ECHO_PIN = 5;
float duration_us, distance_cm;
long DustbinL = 60, trashlvl;

// Initialize DHT sensor
DHT dht(dhtPin, DHT22);

// Initialize WiFi client
WiFiSSLClient client;

// ThingSpeak server details
const char* server = "api.thingspeak.com";
const int httpsPort = 443;

void setup() {
// Start serial communication
Serial.begin(9600);

pinMode(TRIG_PIN, OUTPUT); // set arduino pin to output mode
pinMode(ECHO_PIN, INPUT); // set arduino pin to input mode

// Connect to Wi-Fi network
WiFi.begin(ssid, password);
while (WiFi.status() != WL_CONNECTED) {
delay(1000);
Serial.println("Connecting to WiFi...");
}
Serial.println("Connected to WiFi");

// Initialize DHT sensor
dht.begin();
}

void loop() {
// Wait a few seconds between measurements
delay(5000);

// Read temperature and humidity from DHT22 sensor
float temperature = dht.readTemperature();
float humidity = dht.readHumidity();

// Print temperature and humidity to serial monitor
Serial.print("Temperature: ");
Serial.print(temperature);
Serial.print(" °C");
Serial.print("\t");
Serial.print("Humidity: ");
Serial.print(humidity);
Serial.print(" %");
Serial.println();

// Read carbon monoxide data from MQ-7 sensor
int mq7Value = analogRead(mq7Pin);

// Convert analog reading to ppm using MQ-7 sensor curve
float mq7Voltage = mq7Value * (5.0 / 1023.0);
float mq7Resistance = (5.0 - mq7Voltage) / mq7Voltage;
float mq7PPM = pow(10.0, ((log10(mq7Resistance) - 1.65) / (-2.63)));

// Print carbon monoxide data to serial monitor
Serial.print("Carbon Monoxide: ");
Serial.print(mq7PPM);
Serial.print(" ppm");
Serial.println();

// Read distance from HC-SR04 sensor
// generate 10-microsecond pulse to TRIG pin
digitalWrite(TRIG_PIN, HIGH);
delayMicroseconds(10);
digitalWrite(TRIG_PIN, LOW);

// measure duration of pulse from ECHO pin
duration_us = pulseIn(ECHO_PIN, HIGH);
// calculate the distance
distance_cm = 0.017 * duration_us;
trashlvl = ((DustbinL - distance_cm)/DustbinL)*100;

// print the value to Serial Monitor
Serial.print("distance: ");
Serial.print(distance_cm);
Serial.println(" cm");
Serial.print("Trash level: ");
Serial.print(trashlvl);
Serial.println(" %");

// Build HTTP request URL with sensor data
String url = "/update?api_key=";
url += apiKey;
url += "&field1=";
url += String(temperature);
url += "&field2=";
url += String(humidity);
url += "&field3=";
url += String(mq7PPM);
url += "&field4=";
url += String(trashlvl);

// Send HTTP request to ThingSpeak
if (client.connect(server, httpsPort)) {
Serial.println("Sending data to ThingSpeak...");
client.print(String("GET ") + url + " HTTP/1.1\r\n" +
"Host: " + server + "\r\n" +
"User-Agent: Arduino/1.0\r\n" +
"Connection: close\r\n\r\n");
} else {
Serial.println("Failed to connect to ThingSpeak");
}

// Wait for server response
while (client.connected()) {
String line = client.readStringUntil('\r');
if (line.startsWith("HTTP/1.1")) {
if (line.indexOf("200 OK") == -1) {
Serial.println("ThingSpeak server error");
}
}
}

// Close connection
client.stop();
}

Please read the forum guide in the sticky post at the top of most forum sections to find out how to post code correctly on the forum. Then edit and fix your post above. Thanks.

Hi, @xinless
Welcome to the forum.

Thanks.. Tom... :grinning: :+1: :coffee: :australia:

There is a good tutorial here about combining 2 sketches into one: http://www.thebox.myzen.co.uk/Tutorial/Merging_Code.html

The first thing I notice about your code is both sketches are full of delays, this makes combining them pretty much impossible because when a delay is running everything else stops, so the delays in one sketch prevent the other from doing anything.

The solution is to re-write without delays (or while loops). Here are some tutorials to help you understand how to do that:
Start with the blink without delay example in the IDE, then study these:

Using millis for timing
Demonstration for several things at the same time
Finite state machine tutorial

If you don't understand the tutorials come here and ask.

Oh, and please format your code properly as Tom suggested.

When compiling is attempted, this error occurs:

In file included from /libraries/WiFiNINA/src/WiFiStorage.h:23:0,
                 from /libraries/WiFiNINA/src/WiFi.h:38,
                 from /libraries/WiFiNINA/src/WiFiNINA.h:23,
                 from sketch.ino:9:
/libraries/WiFiNINA/src/utility/wifi_drv.h:293:12: error: 'PinStatus' does not name a type
     static PinStatus digitalRead(uint8_t pin);
            ^~~~~~~~~

The web says to get the ESP WiFi.h library (I do not have it, I have a generic WiFi.h)... but here is your mashup. Learn to format your code and paste it in a code block, like this (for easier reading):

//1stcode(its for a motor to work while sensing sound)
#include <Servo.h> //servo library
Servo servo;
int servoPin = 7;
const int soundSensorPin = A0; // Define the analog pin for sound sensor

//2nd code(its for sensing various things and uploading to thingspeak)
#include <WiFiNINA.h>
#include <WiFiSSLClient.h>
#include <DHT.h>

// Replace with your network credentials
const char* ssid = "snekib";
const char* password = "snekib654";

// Replace with your ThingSpeak API key
String apiKey = "yourapikey";

// Replace with your ThingSpeak channel ID
const unsigned long channelId = "yourid";
// const unsigned long channelId = ''yourid''; // needed double quotes

// Set DHT22 sensor pin
const int dhtPin = 4;

// Set MQ-7 sensor pin
const int mq7Pin = A1;

// Set HC-SR04 sensor pins
const int TRIG_PIN = 6;
const int ECHO_PIN = 5;
float duration_us, distance_cm;
long DustbinL = 60, trashlvl;

// Initialize DHT sensor
DHT dht(dhtPin, DHT22);

// Initialize WiFi client
WiFiSSLClient client;

// ThingSpeak server details
const char* server = "api.thingspeak.com";
const int httpsPort = 443;

void setup() {
  Serial.begin(9600);
  pinMode(soundSensorPin, INPUT);
  servo.attach(servoPin);
  servo.write(0); //close cap on power on
  delay(100);
  servo.detach();

  pinMode(TRIG_PIN, OUTPUT); // set arduino pin to output mode
  pinMode(ECHO_PIN, INPUT); // set arduino pin to input mode
  // Connect to Wi-Fi network
  WiFi.begin(ssid, password);
  while (WiFi.status() != WL_CONNECTED) {
    delay(1000);
    Serial.println("Connecting to WiFi...");
  }
  Serial.println("Connected to WiFi");

  // Initialize DHT sensor
  dht.begin();
}

void loop() {
  // Wait a few seconds between measurements
  delay(5000);

  int sensorValue = analogRead(soundSensorPin);
  if (sensorValue < 750 || sensorValue > 840)
  {
    Serial.print("clap detected");
    Serial.println(sensorValue);
    servo.attach(servoPin);
    delay(1);
    servo.write(0);
    delay(3000);
    servo.write(150);
    delay(1000);
    servo.detach();
  }
  delay(10);
  // Read temperature and humidity from DHT22 sensor
  float temperature = dht.readTemperature();
  float humidity = dht.readHumidity();

  // Print temperature and humidity to serial monitor
  Serial.print("Temperature: ");
  Serial.print(temperature);
  Serial.print(" °C");
  Serial.print("\t");
  Serial.print("Humidity: ");
  Serial.print(humidity);
  Serial.print(" %");
  Serial.println();

  // Read carbon monoxide data from MQ-7 sensor
  int mq7Value = analogRead(mq7Pin);

  // Convert analog reading to ppm using MQ-7 sensor curve
  float mq7Voltage = mq7Value * (5.0 / 1023.0);
  float mq7Resistance = (5.0 - mq7Voltage) / mq7Voltage;
  float mq7PPM = pow(10.0, ((log10(mq7Resistance) - 1.65) / (-2.63)));

  // Print carbon monoxide data to serial monitor
  Serial.print("Carbon Monoxide: ");
  Serial.print(mq7PPM);
  Serial.print(" ppm");
  Serial.println();

  // Read distance from HC-SR04 sensor
  // generate 10-microsecond pulse to TRIG pin
  digitalWrite(TRIG_PIN, HIGH);
  delayMicroseconds(10);
  digitalWrite(TRIG_PIN, LOW);

  // measure duration of pulse from ECHO pin
  duration_us = pulseIn(ECHO_PIN, HIGH);
  // calculate the distance
  distance_cm = 0.017 * duration_us;
  trashlvl = ((DustbinL - distance_cm) / DustbinL) * 100;

  // print the value to Serial Monitor
  Serial.print("distance: ");
  Serial.print(distance_cm);
  Serial.println(" cm");
  Serial.print("Trash level: ");
  Serial.print(trashlvl);
  Serial.println(" %");

  // Build HTTP request URL with sensor data
  String url = "/update?api_key=";
  url += apiKey;
  url += "&field1=";
  url += String(temperature);
  url += "&field2=";
  url += String(humidity);
  url += "&field3=";
  url += String(mq7PPM);
  url += "&field4=";
  url += String(trashlvl);

  // Send HTTP request to ThingSpeak
  if (client.connect(server, httpsPort)) {
    Serial.println("Sending data to ThingSpeak...");
    client.print(String("GET ") + url + " HTTP/1.1\r\n" +
                 "Host: " + server + "\r\n" +
                 "User-Agent: Arduino/1.0\r\n" +
                 "Connection: close\r\n\r\n");
  } else {
    Serial.println("Failed to connect to ThingSpeak");
  }

  // Wait for server response
  while (client.connected()) {
    String line = client.readStringUntil('\r');
    if (line.startsWith("HTTP/1.1")) {
      if (line.indexOf("200 OK") == -1) {
        Serial.println("ThingSpeak server error");
      }
    }
  }

  // Close connection
  client.stop();
}