How to run two codes at the same time?

Hi everyone,

I'm fairly new when it comes to programming and am currently working on a project. I have two separate codes that are working perfectly but I would like to join them together into the one code. The first code runs two motors at the push of a button and the second is a hall effect sensor to detect the rotation of a wheel. I'm just wondering how I would be able to do that and whats the best way to go about it.

 int E1 = 5;     
int E2 = 6;    
int M1 = 4;   
int M2 = 7;    
int pushButton = 2;

void setup() 
{
pinMode(pushButton, INPUT);
Serial.begin(9600);
}

void loop() 
{
int buttonState = digitalRead(pushButton);

int potValue = analogRead(A0);
int pwmOutput = map(potValue, 0, 1023 , 0 , 255);
buttonState = HIGH;
if (buttonState == HIGH)
digitalWrite(M1, HIGH);
else
digitalWrite(M1, LOW);

analogWrite(E1, pwmOutput);
analogWrite(E2, pwmOutput);

}
 volatile byte half_revolutions;
 unsigned int rpm;
 unsigned long timeold;
 void setup()
 {
   Serial.begin(9600);
   attachInterrupt(0, magnet_detect, RISING);
   half_revolutions = 0;
   rpm = 0;
   timeold = 0;
 }
 void loop()//Measure RPM
 {
   if (half_revolutions >= 20) { 
     rpm = 30*1000/(millis() - timeold)*half_revolutions;
     timeold = millis();
     half_revolutions = 0;
     //Serial.println(rpm,DEC);
   }
 }
 void magnet_detect()
 {
   half_revolutions++;
   Serial.println("detect");
 }

Copy the variable declarations for both programs into a new program

Copy the code in each setup() into setup() in the combined program

Resolve any resource conflicts

Put the code from loop() of each program in there own function and call them sequentially from loop() in the combined program.

buttonState = HIGH;
if (buttonState == HIGH)
digitalWrite(M1, HIGH);
else
digitalWrite(M1, LOW);

is a very long-winded way of writingdigitalWrite (M1, HIGH);

Hi, Here is a suggested approach to this:

Combining Arduino Sketches:
This is often difficult. Here is an approach that may help you be successful:

http://arduino-info.wikispaces.com/CombiningArduinoSketches

Tirumse

microcontrollers like Arduino, unlike computers, are unable to run several programs concurrently.

computers can run several programs at the same time.

that does not preclude arduino to run several programs in ONE SKETCH.

i have joined several modules/sketches in one sketch which runs effectively.

UNO has 32k (the memory used to land the lunar module on the moon!)
flash memory but MEGA has 256K memory.

especially when you use a display say LCD or OLED will use a lot of memory
and choke an UNO but not a MEGA.