Running two programs together

Hello,

I have two sketches which work separately but I cannot think of a way in which they would work together. I want sketch 1 to run when sketch 2 is running.

Sketch 1:

int dataPin = 2;        //Define which pins will be used for the Shift Register control
int latchPin = 3;
int clockPin = 4;

int bits[] = {B10101010,B01010101};     //The byte sequence

void setup()
{
   pinMode(dataPin, OUTPUT);       //Configure each IO Pin
   pinMode(latchPin, OUTPUT);
   pinMode(clockPin, OUTPUT);
}

void loop()
{
   for (int n = 0; n < 2; n++)
   {
       digitalWrite(latchPin, LOW);             //Pull latch LOW to start sending data
       shiftOut(dataPin, clockPin, MSBFIRST, bits[n]);          //Send the data
       digitalWrite(latchPin, HIGH);            //Pull latch HIGH to stop sending data
       delay(100);
   }
}

Sketch 2:

#include <Servo.h>

const int  buttonPin = 2;
int buttonState = 0;

Servo myservo;  // create servo object to control a servo
                            // a maximum of eight servo objects can be created
int pos;                // variable to store the servo position




void setup()
{
 pinMode(buttonPin, INPUT);
 myservo.attach(9);  // attaches the servo on pin 9 to the servo object

}

void loop()
{
 buttonState = digitalRead(buttonPin);  // Read the button position
 if (buttonState == HIGH) {
    for(pos = myservo.read(); pos >=20; pos -= 1) { // goes from 90 degrees to 20 degrees in 1 step                                   
      myservo.write(pos);                        // tell servo to go to position in variable 'ONpos'
      delay(15);                                        // randomize wait time for the servo to reach the position
    }
 }
 else {

    for(pos = myservo.read(); pos <=90; pos += 1) {// goes from 20 degrees to 90 degrees in 1 step                            
      myservo.write(pos);                         // tell servo to go to position in variable 'OFFpos'                
      delay(15);                                         // randomize wait time for the servo to reach the position
    }
 }


}

Continue reading here... Combining two codes - Programming Questions - Arduino Forum

Thanks for the suggestions, but I still can't seem to find any solution without either the lights not functioning correctly or the button not working. Any further suggestions?

Here's a hint that might help.

When you want to put in a delay(?), rethink things so you read the current time and add to that the amount you want to delay. Save this result in a global. Maybe in some way save that you are waiting for X. Then go on. Next time through loop() check to see if the time is up. current time > result. If so, do the next step.

This is a very common thinking process for any digitally controlled mechanical device. You start actions then check over and over again to see if A) It completed B) The time is up or C) Something failed. While you are checking you can also be checking if the user did something, something else is running etc.

Once you get rid of the delay(?) calls, known as blocking, you will be able to merge the two together. In fact you will be able to merge lots of stuff together and have way more fun.

Hope this helps.

-jim lee

See also Demonstration code for several things at the same time

RuralGam3r:
Thanks for the suggestions, but I still can't seem to find any solution without either the lights not functioning correctly or the button not working. Any further suggestions?

So, just because 2 sketches could be merged together does not mean that they should be merged.

Rather, you probably should just redesign from the start by gathering requirements, doing a state-diagram, and then building a non-blocking skeleton... this last part being critical to your success.

Often when you look at something simple, like in this case the two sketches, but cannot get them to combine and function then you are at a critical point in your understanding of programming - not Arduino specific, but a gap of a more general nature. Some folks find a way to jump the gap and continue and others find it a bit too wide of a gap to jump without assistance. My belief is that learning how to overcome the gap in knowledge is critical to advancing your ability to grow as a programmer. @sterretje has provided a great reference link, but if you read the thread and it does not make sense, then you are likely to get frustrated. I'm going to try and explain a bit what the 'big deal' is all about...

The Arduino line of hobby boards use a microcontroller that is single threaded. This is the way PCs were made back in the DOS days except they used a microprocessor instead of a microcontroller: The distinctions are many but for our simple view just consider a microprocessor as a chip with memory, I/O, and firmware all external to the processor chip. The take-away concept here is that of "single threaded" and that distills to the idea that all things that are done in a single step and then the uC moves to the next step to be done. One, two, three, four .... until the last step in loop() and then repeat.

Our sketch code is laid out line - by - line like this:

void loop()
{
 // line 1;
 // line 2;
  delay ( 1000 );
 // line 3;
 // line x;
}

The delay between line 2 and line 3 causes all command processing to cease for 1 second. Any command that stops the sequence of progression line by line is called a "blocking" command. Blocking is bad because, in the above, line 3 may need to do something immediately after line 2 but cannot.

What we as programmers really want to do, is to take all of our things and line them up, one after another so that #1 to #2 to #3 to #4 can all happen as quickly as the uC can execute instructions. If we can rewrite our sketches to eliminate the need to stop or pause for a long period, then the code is said to be non-blocking.

In your case, you need to define global variables that need to be shared between sketch #1 and sketch #2 ... IF ANYTHING needs to be shared.

void setup() need to be combined so that you properly initialize whatever needs to be utilized, both #1 and #2.

Since you only have 2 BIG things that need to be done, loop() will now look something like:

// define Global variables for use ....

void setup()
{
     // setup printer, Input/Output pins, etc;
}


void loop() {
     function1();
     function2();
}

void function1 (void)
{
     // your logic to do stuff with Global variables;
}

void function2(void)
{
     // your logic to do stuff with Global variables;
}

Global variables will not always be the most proper way to do things, but usually they are more appropriate than not. As you progress in your skills, you can use private variables in your functions as needed.

Good luck,

Ray

Thanks everyone for your help, I've managed to solve the issue now.