Combining two sketches into one

Hi,

I’m new to Arduino, and need guidance to combine two sketches.
I’m planning to have two Arduino nano’s to do separate jobs but if I can combine two sketches together that would be great.

Sketch 1: Drone Antenna Tracker
(Arduino, connected to Antenna tracker and servo. Servo, spins around to track where the drone antenna is going)

Sketch 2: Drone RSSI Finder
(Arduino, connected to antenna tracker and a screen to show how high the connection is. Doubles as a drone finder)

Is this possible?

I know my code below is wrong. I tried fixing it but I couldnt get it to work. Should I just use 2 arduino’s?

Thanks

#include <Arduino.h>
#include <U8x8lib.h>
  /*Finder*/
#include <Servo.h>
#include <Timer.h>
  /*Tracker*/

  /*Start Finder*/
#ifdef U8X8_HAVE_HW_SPI
#include <SPI.h>
#endif
#ifdef U8X8_HAVE_HW_I2C
#include <Wire.h>
#endif

int Rssi = 0;    
int maxR = 150;   
int minR = 70;  
int Per;  
int pp = 5;     

U8X8_SH1106_128X64_NONAME_HW_I2C u8x8(/* reset=*/ U8X8_PIN_NONE);
int Pin = 0;     // pin where rssi is connected
  /*End Finder*/

  /*Start Tracker*/
#define SIGMOID             // Best
#define SIGMOID_SLOPE       1
#define SIGMOID_OFFSET      4
#if !defined(EXPONENTIAL) ^ !defined(SIGMOID) ^ !defined(PROPORTIONAL) ^ !defined(RELATIVE)
// all good
#else
  #error "Please define ONE tracking curve: EXPONENTIAL, SIGMOID, PROPORTIONAL, RELATIVE"
#endif

#define LEFT_RSSI_PIN       0     // analog RSSI measurement pin
#define RIGHT_RSSI_PIN      1
#define PAN_SERVO_PIN       5     // Pan servo pin
#define RSSI_OFFSET_RIGHT   0
#define RSSI_OFFSET_LEFT    0
#define RSSI_MAX            400
#define RSSI_MIN            120
#define SERVO_MAX_STEP      5
#define SERVO_MIN_STEP      0.09     // prevents windup and servo crawl
#define DEADBAND            5
#define SERVO_DIRECTION     1
#define FIR_SIZE            10
#define LAST                FIR_SIZE - 1

uint16_t rssi_left_array[FIR_SIZE];
uint16_t rssi_right_array[FIR_SIZE];

float anglePan = 90;
boolean debug = false;

Timer timer;
Servo servoPan;
  /*End Tracker*/



  /*VOID SETUP FINDER - TRACKER*/

void setup()
/*Start Finder Void*/
{
Serial.begin(9600);
  u8x8.begin();

}

void pre(void)
{
  u8x8.setFont(u8x8_font_amstrad_cpc_extended_f);    
  u8x8.clear();

  u8x8.inverse();
  u8x8.print(" U8x8 Library ");
  u8x8.setFont(u8x8_font_chroma48medium8_r);  
  u8x8.noInverse();
  u8x8.setCursor(0,1);
}

void draw_bar(uint8_t c, uint8_t is_inverse)
{ 
  uint8_t r;
  u8x8.setInverseFont(is_inverse);
  for( r = 0; r < u8x8.getRows(); r++ )
  {
    u8x8.setCursor(c, r);
    u8x8.print(" ");
  }
}

void draw_ascii_row(uint8_t r, int start)
{
  int a;
  uint8_t c;
  for( c = 0; c < u8x8.getCols(); c++ )
  {
    u8x8.setCursor(c,r);
    a = start + c;
    if ( a <= 255 )
      u8x8.write(a);
  }
}
/*End Finder Void*/
/*Start Tracker Void*/

  {
  servoPan.attach(PAN_SERVO_PIN);
  servoPan.write(90);

  // wipe array
  for (int i = 0; i < FIR_SIZE; i++) {
    rssi_right_array[i] = 0;
    rssi_left_array[i] = 0;
  }

  Serial.begin(115200);
  while (!debug) {
    delay(3000);
    debug = true;
  }


  timer.every(50, mainLoop);
  timer.every(5, measureRSSI);
}
/*End Tracker Void*/

void loop()
/*Start Finder Void Loop*/

{
  int i;
  uint8_t c, r, d;
 
 // pre();
  Rssi = analogRead(Pin); // read RSSI values

Per = map(Rssi, minR, maxR, 0, 15);   // Scale them into 0-100 range,
//Per = Per/1.5;
if (Per > 15){
  draw_bar(15, 1);
  }else if (Per < 1){
    draw_bar(1, 1);
    }else{draw_bar(Per, 1);}

Serial.println(Per);
Serial.println("Rssi");
Serial.println(Rssi);
//draw_bar(0, 1);

//draw_bar(15, 1);

delay(20);
  u8x8.clear();
}

/*End Finder Void Loop*/
/*Start Tracker Void Loop*/

timer.update();

}


void mainLoop() {

  uint16_t avgLeft = max(avg(rssi_left_array, FIR_SIZE) + RSSI_OFFSET_LEFT, RSSI_MIN);
  uint16_t avgRight = max(avg(rssi_right_array, FIR_SIZE) + RSSI_OFFSET_RIGHT, RSSI_MIN);

//  If avg RSSI is above 90%, don't move
//  if ((avgRight + avgLeft) / 2 > 360) {
//    return;
//  }

  /*
     the lower total RSSI is, the lower deadband gets
     allows more precise tracking when target is far away
  */
  uint8_t dynamicDeadband = (float(avgRight + avgLeft) / 2 - RSSI_MIN) / (RSSI_MAX - RSSI_MIN) * DEADBAND;

  // if target is in the middle, don't move
  if (abs(avgRight - avgLeft) < dynamicDeadband ) {
    return;
  }

  float ang = 0;

  // move towards stronger signal
  if (avgRight > avgLeft) {
  
  #if defined(EXPONENTIAL)
    float x = float(avgRight - avgLeft);
    x = x * x / 500;
    ang = x * SERVO_DIRECTION * -1;
  #endif

  #if defined(RELATIVE)
    ang = float(avgRight / avgLeft) * (SERVO_DIRECTION * -1);
  #endif

  #if defined(SIGMOID)
    float x = float(avgRight - avgLeft) / 10;
    x = SERVO_MAX_STEP / (1+ exp(-SIGMOID_SLOPE * x + SIGMOID_OFFSET));
    ang = x * SERVO_DIRECTION * -1;
  #endif
    
  #if defined(PROPORTIONAL)
    float x = float(avgRight - avgLeft) / 10;
    ang = x * SERVO_DIRECTION * -1;  
  #endif
  }
  else {

  #if defined(EXPONENTIAL)
    float x = float(avgLeft - avgRight);
    x = x * x / 500;
    ang = x * SERVO_DIRECTION;
  #endif

  #if defined(RELATIVE)
    ang = float(avgLeft / avgRight) * SERVO_DIRECTION;
  #endif

  #if defined(SIGMOID)
    float x = float(avgLeft - avgRight) / 10;
    x = SERVO_MAX_STEP / (1+ exp(-SIGMOID_SLOPE * x + SIGMOID_OFFSET));
    ang = x * SERVO_DIRECTION;
  #endif
    
  #if defined(PROPORTIONAL)
    float x = float(avgLeft - avgRight) / 10;
    ang = x * SERVO_DIRECTION;  
  #endif
  }

  // upper and lower limit for angle step
  ang = (abs(ang) > SERVO_MAX_STEP ? SERVO_MAX_STEP * ang/abs(ang) : ang);
  ang = (abs(ang) < SERVO_MIN_STEP ? 0 : ang);

  // move servo by n degrees
  movePanBy(ang);


  if (debug) {
//    Serial.print("RSSI%: ");
//    Serial.print(map(avgLeft, RSSI_MIN, RSSI_MAX, 0, 100));
//    Serial.print(", ");
//    Serial.print(map(avgRight, RSSI_MIN, RSSI_MAX, 0, 100));

    // raw rssi values, use these for RSSI_MIN and RSSI_MAX
    Serial.print("Calibration - left: ");
    Serial.print(avgLeft);
    Serial.print(" right: ");
    Serial.print(avgRight);

    Serial.print(" servo-angle: ");
    Serial.println(anglePan);
  }
}

void movePanBy(float angle) {

  anglePan += angle;
  anglePan = limit(SERVO_MIN, SERVO_MAX, anglePan);
  servoPan.write(anglePan);
}

void measureRSSI() {

  advanceArray(rssi_left_array, FIR_SIZE);
  advanceArray(rssi_right_array, FIR_SIZE);

  rssi_left_array[LAST] = analogRead(LEFT_RSSI_PIN);
  rssi_right_array[LAST] = analogRead(RIGHT_RSSI_PIN);
}

uint16_t avg(uint16_t samples[], uint8_t n) {

  uint32_t summ = 0;
  for (uint8_t i = 0; i < n; i++) {
    summ += samples[i];
  }

  return uint16_t(summ / n);
}

void advanceArray(uint16_t *samples, uint8_t n) {

  for (uint8_t i = 0; i < n - 1; i++) {
    samples[i] = samples[i + 1];
  }
}


float limit(float lowerLimit, float upperLimit, float var) {

  return min(max(var, lowerLimit), upperLimit);
}
/*End Tracker Void Loop*/

OK, a couple of things here.

Remove all instances of "delay()". If you need to understand how to do that, see this tutorial. You cannot use "while" either.

There is no such thing as a "void loop" or "void function". Remove the word "void" from all comments. "void" is a descriptor which specifies something about the function, it is not a part of the name.

There is only one "loop()". Rename anything else that you called any sort of "loop". This will avoid confusion.

These things may not seem important, but they will assist you to understand what you are doing. It is reasonably straightforward to combine code as long as there are no clashes in resources (that is, where you need to share some device) and as long as you realise that nothing must cause the loop() to wait in any fashion, then the loop() sections of the two original codes will simply alternate smoothly.

Probably the most troublesome problem with timing will be the use if the serial port. If you expect to use it at all, then every part of your code must be prepared to accept the delays it introduces.

Hi,
Welcome to the forum.

Do you have the two sketches working?
Can you post those separately please?

Can you please post a copy of your circuit, in CAD or a picture of a hand drawn circuit in jpg, png?

Thanks.. Tom... :slight_smile:

Please post the code for two separately.

Just to make sure, you want them to run at the same time and not one or the other?

Delay() has few places. Very few.
Great to use in startup when you need to force a pause and need stop everything.

In your running program it can cause lots of problems.