how to join two different codes (ARDUINO)

Thread Starter

nessatinuviel

Joined Dec 1, 2020
3
I’m dabbling in Arduino and having trouble running two sketches on my Arduino UNO simultaneously. The first is about a program that reads temperature and relative humidity and the second is a program that reads barometric pressure. Both programs work independently, but when I try to combine the two, No.
help :(

this is the code for temperature and relative humidity:
Temp and RH:
#include <Adafruit_Sensor.h>
#include <LiquidCrystal.h>
#include <DHT.h>
#include <DHT_U.h>

//VARIABLES
//Asignación de los pines digitales
int SENSOR = 2; //Este es el pin #2
int RS = 4;
int E = 5;
int D4 = 6;
int D5 = 7;
int D6 = 8;
int D7 = 9;
//Variables de lectura de tempratura y humedad
int temp;
int hume;
//Creación de variables para el sensor y el display
DHT dht(SENSOR,DHT11);                    //Formato general: DHT <var_name>(PIN, MODELO DEL SENSOR)
LiquidCrystal lcd(RS, E, D4, D5, D6, D7); // Formato general: LiquidCrystal <var_name>(RS, RW, ENABLE, D0, D1, D2, D3, D4, D5, D6, D7)
//Variable para salida del abanico
int motor = 12;

void setup(){
 
  //Iniciar el sensor de temp
  dht.begin();
  //Iniciar el LCD
  lcd.begin(16,2); //(tipo 16 columnas, 2 líneas)
  //Setea el Pin 12 como salida
  pinMode(motor,OUTPUT);
        
}

void loop(){ //Este es el buclé principal del programa

  //Lee valores físicos
  hume = dht.readHumidity();
  temp = dht.readTemperature();

  //Limpia el LCD
  lcd.clear(); //esta instrucción coloca el cursor en la pos 0,0 (columna, fila)
  lcd.setCursor(0,0); //(no necesaria porque la linea de arriba ya lo hace)
  //Escribe los valores leídos en el LCD
  lcd.print("TEMPERATURA: ");
  lcd.print(temp);
  lcd.print("C");
  lcd.setCursor(0,1); //esta instrucción coloca el cursor en la pos 0,1 (columna, fila)
  lcd.print("HUMEDAD: ");
  lcd.print(hume);
  lcd.print("%");

  //Activa el motor si la temperatura pasa el valor deseado
  if(temp>=30){ // Compara si la temp ya es 30 grados
    digitalWrite(motor,HIGH); //Si lo es manda un 1 lógico a teavés del pin digital #12
  }
  else{
    digitalWrite(motor,LOW);// sino, manda un 0, lo que apagaría el motor
  }

  delay(2000);//valor en milisengundos para que repita el ciclo

}
and this is the barometric pressure code:
barometric pressure:
#include <Wire.h>
#include <Adafruit_BMP085.h>

// Connect VCC of the BMP085 sensor to 3.3V (NOT 5.0V!)
// Connect GND to Ground
// Connect SCL to i2c clock - on '168/'328 Arduino Uno/Duemilanove/etc thats Analog 5
// Connect SDA to i2c data - on '168/'328 Arduino Uno/Duemilanove/etc thats Analog 4
// EOC is not used, it signifies an end of conversion
// XCLR is a reset pin, also not used here

Adafruit_BMP085 bmp;
 
void setup() {
  Serial.begin(9600);
  if (!bmp.begin()) {
    Serial.println("Could not find a valid BMP085 sensor, check wiring!");
    while (1) {}
  }
}
 
void loop() {
    Serial.print("Temperature = ");
    Serial.print(bmp.readTemperature());
    Serial.println(" *C");
    
    Serial.print("Pressure = ");
    Serial.print(bmp.readPressure());
    Serial.println(" Pa");
    
    // Calculate altitude assuming 'standard' barometric
    // pressure of 1013.25 millibar = 101325 Pascal
    Serial.print("Altitude = ");
    Serial.print(bmp.readAltitude());
    Serial.println(" meters");

    Serial.print("Pressure at sealevel (calculated) = ");
    Serial.print(bmp.readSealevelPressure());
    Serial.println(" Pa");

  // you can get a more precise measurement of altitude
  // if you know the current sea level pressure which will
  // vary with weather and such. If it is 1015 millibars
  // that is equal to 101500 Pascals.
    Serial.print("Real altitude = ");
    Serial.print(bmp.readAltitude(101500));
    Serial.println(" meters");
    
    Serial.println();
    delay(500);
}
 

Wolframore

Joined Jan 21, 2019
2,273
Sounds like he’s trying to combine two codes into one. You have some issues with the I/O in the two separate codes which are conflicting. Resolve those conflict. Then you will have to make sure there’s no conflict with variables and one code isn’t locking out the other in a loop. It might be easier to rewrite it from scratch.
 

SamR

Joined Mar 19, 2019
3,405
I don't see any conflicts between the 2 programs so it should be simple to combine them into one program.
 

Thread Starter

nessatinuviel

Joined Dec 1, 2020
3
hi ness,
Please post your version of the combined code, so that we can check for coding conflicts.
E
[/CITAR]
what happens is that I am simulating this assembly in Proteus, and the barometric pressure part should automatically open (as soon as I run the simulation) a window with the displayed values. and I can't get him to do it. The part of the temperata and relative humidity if it runs well.

this was my attempt::
#include <Wire.h>
#include <Adafruit_BMP085.h>
#include <Adafruit_Sensor.h>
#include <LiquidCrystal.h>
#include <DHT.h>
#include <DHT_U.h>

Adafruit_BMP085 bmp;

//VARIABLES
//Asignación de los pines digitales
int SENSOR = 2; //Este es el pin #2
int RS = 4;
int E = 5;
int D4 = 6;
int D5 = 7;
int D6 = 8;
int D7 = 9;
//Variables de lectura de tempratura y humedad
int temp;
int hume;
//Creación de variables para el sensor y el display
DHT dht(SENSOR,DHT11);                    //Formato general: DHT <var_name>(PIN, MODELO DEL SENSOR)
LiquidCrystal lcd(RS, E, D4, D5, D6, D7); // Formato general: LiquidCrystal <var_name>(RS, RW, ENABLE, D0, D1, D2, D3, D4, D5, D6, D7)
//Variable para salida del abanico
int motor = 12;

void setup()
{
    Serial.begin(9600);
 
    //Iniciar el sensor de temp
    dht.begin();
    //Iniciar el LCD
    lcd.begin(16,2); //(tipo 16 columnas, 2 líneas)
    //Setea el Pin 12 como salida
    pinMode(motor,OUTPUT);

    if (!bmp.begin())
    {
        Serial.println("Could not find a valid BMP085 sensor, check wiring!");
        while(1);
      
    }//if
        
}

void loop()
{
    //Este es el buclé principal del programa
    //Lee valores físicos
    hume = dht.readHumidity();
    temp = dht.readTemperature();

    //Limpia el LCD
    lcd.clear(); //esta instrucción coloca el cursor en la pos 0,0 (columna, fila)
    lcd.setCursor(0,0); //(no necesaria porque la linea de arriba ya lo hace)
  
    //Escribe los valores leídos en el LCD
    lcd.print("TEMPERATURA: ");
    lcd.print(temp);
    lcd.print("C");
    lcd.setCursor(0,1); //esta instrucción coloca el cursor en la pos 0,1 (columna, fila)
  
    lcd.print("HUMEDAD: ");
    lcd.print(hume);
    lcd.print("%");

    //Activa el motor si la temperatura pasa el valor deseado
    if(temp>=30)
    { // Compara si la temp ya es 30 grados
        digitalWrite(motor,HIGH); //Si lo es manda un 1 lógico a teavés del pin digital #12
    }
    else
    {
        digitalWrite(motor,LOW);// sino, manda un 0, lo que apagaría el motor
    }

    PrintBaroParms();
  
    delay(2000);//valor en milisengundos para que repita el ciclo
    
}

void PrintBaroParms( void )
{
    Serial.print("Temperature = ");
    Serial.print(bmp.readTemperature());
    Serial.println(" *C");
  
    Serial.print("Pressure = ");
    Serial.print(bmp.readPressure());
    Serial.println(" Pa");
  
    // Calculate altitude assuming 'standard' barometric
    // pressure of 1013.25 millibar = 101325 Pascal
    Serial.print("Altitude = ");
    Serial.print(bmp.readAltitude());
    Serial.println(" meters");

    Serial.print("Pressure at sealevel (calculated) = ");
    Serial.print(bmp.readSealevelPressure());
    Serial.println(" Pa");

    // you can get a more precise measurement of altitude
    // if you know the current sea level pressure which will
    // vary with weather and such. If it is 1015 millibars
    // that is equal to 101500 Pascals.
    Serial.print("Real altitude = ");
    Serial.print(bmp.readAltitude(101500));
    Serial.println(" meters");
  
    Serial.println();
}
 

BobTPH

Joined Jun 5, 2013
3,308
Okay, the first program is writing the temperature and humidity to an LCD and turning a motor on if the temp is over 30C. The second is writing the temperature and pressure to a serial line and then calculating the altitude two ways and writing these out.

What does the combined program do?

Bob
 

andrewmm

Joined Feb 25, 2011
1,464
Ok, take step back.

Processors are ( generally ) inherently single threaded. Especially MCUs such as the arduino.

You can run things like a OS, that allows multiple programs ( threads ) to run,
but that's a big step, and tends to need a bit more grunt of the processor,
Arduinos tend to have low grunt , these are about the fastest I know of,
https://www.pjrc.com/store/teensy40.html


Without the OS, you are inherently limited to one main loop.

You need to re think your code as how to do things sequentially,
do one thing ,then the other, then back to the start of the main loop.

Or you could use an interrupt type structure,

Its really a new bit of code though,

You could use procedures / functions to isolate parts of the design and make it more readable,
but you still only have one main loop.
 

RH3

Joined Nov 14, 2016
1
I’m dabbling in Arduino and having trouble running two sketches on my Arduino UNO simultaneously. The first is about a program that reads temperature and relative humidity and the second is a program that reads barometric pressure. Both programs work independently, but when I try to combine the two, No.
help
It’s very easy to do. Only one sketch can be run at a time. But if you add all the variables, defines etc from the second sketch within the Setup() section of the first and do the same with the Loop() section.

Make sure all your variables are unique.
The Delay() in your first sketch will impact the second and vice-versa but you will only need the one to delay between each sample of both sensors.
There is away to give the effect of running two sketches and not being effected by Delay() holding up processing by using the Millis() function. Have a check of the Guides on www.adafruit.com.
 

Phil-S

Joined Dec 4, 2015
205
You can't just tack two bits of code together.
You have two separate "sketches" each would run in it's own right.
An Arduino sketch has a setup() function and a loop() function which are declared once.
By tacking them together, you have two setup()s and two loops()s and that won't work.
 

Wolframore

Joined Jan 21, 2019
2,273
You can combine the setup and organize the two loops into one or as one loop running separate functions. Its done all the time. There are a lot of housekeeping needed but is entirely possible.
 

vanderghast

Joined Jun 14, 2018
55
Merge the declarations (the code before the setup) without duplication. Check that NO PIN has two different roles to play. You are on your own to solve any conflicting pin usage. If an #include is mentionned in each original module, use it just once. If the same variable name is used in each original module, rename one so that the name will be unique. Propagate that name refactorisation, if any is done, in the code within that initial module.

Rename the two original setup() as setup1 and setup2. In the new single setup(), run setup1 and, next, on another line, setup2, s if you were calling two different procedures, one after the other.

Rename the two original loop() as loop1 and loop2. In the new single loop, run loop1 and next, loop2 (same observation).

If you need to handle data from the two original codes, with NEW code of your own, bring the required variable name in the section before the setup, if they are not already there.

If you have a delay, check if it is still required since now, loop2 will be a delay for the execution of loop1 and vice-versa.

You may fall on a problem of speed or having not enough memory, in that case, I can only suggest to change for a bigger Arduino, or a bigger compatible MCU.
 
Top