Need Help Combining Two Sketches

Hey, I'm new here to this forum and have been trying to work something out for a project I have. Been doing some research on combining two of my codes. The main objective is to have a DC motor running as a fan, as its speed is controlled by a potentiometer. This fan is on a servo motor that controls its swivel. What I'd like is to combine my working fan code to one that uses the RGB LED. as the potentiometer increases/decreases the speed of the DC motor, I'd like the colors to change. I was able to get the potentiometer to do so in controlling the multicolor LED but I am struggling in combining the two working codes into one. I'm running out of time for this project (school related) and some advice or examples would be greatly appreciated.

Thank you so much for your time!!!

Items used:
One potentiometer
One Servo
One DC Motor
Arduino Uno board
One RGB LED

Below are my codes:

Fan Sketch:

#include <Servo.h>

int potPin = A0;
int motorPin = 11;
int potValue = 0;
int motorValue = 0;
int pos;
Servo myservo;

void setup(){
 myservo.attach(3);
 pinMode(7, OUTPUT);
 pinMode(6, OUTPUT);
}

void loop(){
 potValue = analogRead(potPin);
 motorValue = map(potValue,0,1023,0,255);
 analogWrite(motorPin, motorValue);
 
 if (motorValue >= 150) digitalWrite (7, HIGH);
 else digitalWrite(7, LOW);
 if (motorValue <= 150) digitalWrite (6, HIGH);
 else digitalWrite(6,LOW);
 
 for(pos=0;pos<=180;pos+=1)
 {
   myservo.write(pos);
   delay(20);
 }
 for(pos=180;pos>=0;pos-=1)
 {
   myservo.write(pos);
   delay(20);
 }
}

RGB Potentiometer Control:

int potPin = 0; 
int potVal = 0; 

int redPin = 9;
int grnPin = 10;
int bluPin = 11;

int redVal = 0;
int grnVal = 0;
int bluVal = 0;

int DEBUG = 1;

void setup()
{
 pinMode(redPin, OUTPUT);
 pinMode(grnPin, OUTPUT);   
 pinMode(bluPin, OUTPUT); 

 if (DEBUG) {
   Serial.begin(9600);
 }
}

void loop()
{
 potVal = analogRead(potPin);

 if (potVal < 341)
 {                  
   potVal = (potVal * 3) / 4;

   redVal = 256 - potVal;
   grnVal = potVal;
   bluVal = 1;
 }
 else if (potVal < 682)
 {
   potVal = ( (potVal-341) * 3) / 4;

   redVal = 1;
   grnVal = 256 - potVal;
   bluVal = potVal;
 }
 else
 {
   potVal = ( (potVal-683) * 3) / 4;

   redVal = potVal;
   grnVal = 1;
   bluVal = 256 - potVal;
 }
 analogWrite(redPin, redVal);
 analogWrite(grnPin, grnVal); 
 analogWrite(bluPin, bluVal);  

 if (DEBUG) {
   DEBUG += 1;
   if (DEBUG > 100)
   {
     DEBUG = 1;

     Serial.print("R:");
     Serial.print(redVal);
     Serial.print("\t");
     Serial.print("G:");
     Serial.print(grnVal);
     Serial.print("\t");    
     Serial.print("B:");    
     Serial.println(bluVal);
   }
 }
}

I'm not a good enough programmer to analyze or re-write your code, plus I'm too lazy...

You need to do all of your initialization & setup() once. Then, make one main loop.

I could be wrong, but it looks like you never get out of the main (servo) loop, so none of the LED code ever gets executed... Is that the symptom you're getting? Nothing happens with the LEDs and you never get any of the debug information from the serial port?

If the servo stuff is working, I'd start by adding the variable initialization & setup for the LEDs. That won't "do" anything but you can make sure it compiles without errors before adding the actual LED stuff.

Then, add some of the code to light-up the LED at the end of the main loop (but inside the loop, of course). You don't have to write all of the LED code at once... Do a little at a time, maybe one color at a time until everything is debugged & working.

Thank you for your time!

I am trying to work on adding it together like that but it all seems to get disorganized and non of the functions work in the ways I try to do. The orders I've used haven't been working probably because I'm still new and not really understanding where I can fit what where.

I just wasn't sure if there is a place where I can insert an if statement where if all the fan code happens begin this code and loop it all, anything like that?

Thanks again! I truly appreciate it!

This demo shows a simple way to merge two programs. Of course you may run into problems such as both programs trying to use the same I/O pin and you will have to resolve that yourself.

...R

Also, please go back to your original post, select "modify", highlight each of your code samples in turn and use the "code" icon - the scroll thingy - to mark them as such.

That makes it much more practical to examine your code.

You may try this code

#include <Servo.h>

int potPin = A0;
int motorPin = 11;
int potValue = 0;
int motorValue = 0;

Servo myservo;   // create servo object to control a servo 

const int servoMinDegrees = 0; // the limits to servo movement
const int servoMaxDegrees = 180;

int servoPosition = 0;     // the current angle of the servo - starting at 0.
int servoInterval = 20; // initial millisecs between servo moves
int servoDegrees = 1;       // amount servo moves at each step 
                            //    will be changed to negative value for movement in the other direction


unsigned long currentMillis = 0;    // stores the value of millis() in each iteration of loop()
unsigned long previousServoMillis = 0; // the time when the servo was last moved
							
//RGB Potentiometer Control:

int potVal = 0; 

int redPin = 9;
int grnPin = 10;
int bluPin = 11;

int redVal = 0;
int grnVal = 0;
int bluVal = 0;

int DEBUG = 1;


void setup(){
  myservo.write(servoPosition); // sets the initial position

  myservo.attach(3);
  pinMode(7, OUTPUT);
  pinMode(6, OUTPUT);
  // For RGB Potentiometer Control:
  pinMode(redPin, OUTPUT);
  pinMode(grnPin, OUTPUT);   
  pinMode(bluPin, OUTPUT); 

  if (DEBUG) {
    Serial.begin(9600);
  }

}


void RGB_LED_Control()
{
  potVal = analogRead(potPin);

  if (potVal < 341)
  {                  
    potVal = (potVal * 3) / 4;

    redVal = 256 - potVal;
    grnVal = potVal;
    bluVal = 1;
  }
  else if (potVal < 682)
  {
    potVal = ( (potVal-341) * 3) / 4;

    redVal = 1;
    grnVal = 256 - potVal;
    bluVal = potVal;
  }
  else
  {
    potVal = ( (potVal-683) * 3) / 4;

    redVal = potVal;
    grnVal = 1;
    bluVal = 256 - potVal;
  }
  analogWrite(redPin, redVal);
  analogWrite(grnPin, grnVal); 
  analogWrite(bluPin, bluVal);  

  if (DEBUG) {
    DEBUG += 1;
    if (DEBUG > 100)
    {
      DEBUG = 1;

      Serial.print("R:");
      Serial.print(redVal);
      Serial.print("\t");
      Serial.print("G:");
      Serial.print(grnVal);
      Serial.print("\t");    
      Serial.print("B:");    
      Serial.println(bluVal);
    }
  }
}

//======================================

void servoSweep() {

      // this is similar to the servo sweep example except that it uses millis() rather than delay()

      // nothing happens unless the interval has expired
      // the value of currentMillis was set in loop()
  
  if (currentMillis - previousServoMillis >= servoInterval) {
        // its time for another move
    previousServoMillis += servoInterval;
    
    servoPosition = servoPosition + servoDegrees; // servoDegrees might be negative

    if ((servoPosition >= servoMaxDegrees) || (servoPosition <= servoMinDegrees))  {
          // if the servo is at either extreme change the sign of the degrees to make it move the other way
      servoDegrees = - servoDegrees; // reverse direction
          // and update the position to ensure it is within range
      servoPosition = servoPosition + servoDegrees; 
    }
    
        // make the servo move to the next position
    myservo.write(servoPosition);
        // and record the time when the move happened

  }
  
}


void loop(){
  currentMillis = millis();   // capture the latest value of millis()
                              //   this is equivalent to noting the time from a clock
                              //   use the same time for all LED flashes to keep them synchronized
	
  potValue = analogRead(potPin);
  motorValue = map(potValue,0,1023,0,255);
  analogWrite(motorPin, motorValue);
  
  if (motorValue >= 150) digitalWrite (7, HIGH);
  else digitalWrite(7, LOW);
  if (motorValue <= 150) digitalWrite (6, HIGH);
  else digitalWrite(6,LOW);
 
  servoSweep(); // servo sweep
 
  RGB_LED_Control();
}

Hi,

Sorry if I post this code a little too late, I had a lot of fun trying to rewrite your code, Theres a few things that I think need clarification. Mainly in merging both your code, was wondering if it require 2 pot or 1 is sufficient? I made the code below with 2 pot in mind, if somehow you only use 1 pot go to line 80 and change this line
int potVal = analogPin[1].analogValue; into

int potVal = analogPin[0].analogValue;

the complete code below

#include <Servo.h>

//only edit this part for your program--//
const byte servoPin = 3; // Which ever pin you hook the servo
const byte pinAnalog[] = { A0, A1 }; //if 2 pot else just delete one, If only one go to line 80 and change 1 become 0
const byte pinDigital[] = { 7, 6 }; // This one change to what ever the fan code means
const byte pinPWM[] = { 6, 9, 10, 11 };//pin in sequence Motor,R, G, B LED. 
const unsigned long servoDelay = 20; //delay time for servo Update
const unsigned long debugDelay = 100;//refresh rate for debug mode
const boolean debugMode = true; //false if do not need DebugMode
const boolean outputLogic = true; //true means HIGH mean Active, false means Low mean Active
//Until here only.. dont touch anything below except line 80 if only 1 Pot 
const byte noOfAnalogInput = sizeof(pinAnalog) / sizeof(byte);
const byte noOfDigitalOutput = sizeof(pinDigital) / sizeof(byte);
const byte noOfPWMOutput = sizeof(pinPWM) / sizeof(byte);

struct analogInput {
  byte analogPin;
  int analogValue;
};

struct output {
  byte outputPin;
  boolean outputState;
};

struct PWMOutput {
  byte PWMPin;
  byte PWMValue;
};

analogInput analogPin[noOfAnalogInput];
output outputPin[noOfDigitalOutput];
PWMOutput PWMPin[noOfPWMOutput];
Servo myServo;

void setup()
{
  myServo.attach(3);
  for ( byte i = 0; i <  noOfAnalogInput; i++)
  {
    analogPin[i].analogPin = pinAnalog[i];
    analogPin[i].analogValue = 0;
    pinMode ( analogPin[i].analogPin, INPUT);
  }
  for ( byte i = 0; i < noOfDigitalOutput; i++)
  {
    outputPin[i].outputPin = pinDigital[i];
    outputPin[i].outputState = !outputLogic;
    pinMode ( outputPin[i].outputPin, OUTPUT);
    digitalWrite ( outputPin[i].outputPin, outputPin[i].outputState);
  }
  for ( byte i = 0; i < noOfPWMOutput; i++)
  {
    PWMPin[i].PWMPin = pinPWM[i];
    PWMPin[i].PWMValue = 0;
    pinMode ( PWMPin[i].PWMPin, OUTPUT);
    analogWrite ( PWMPin[i].PWMPin, PWMPin[i].PWMValue);
  }
  if ( debugMode )
  {
    Serial.begin ( 9600);
    Serial.println ( "Debug mode active");
  }
}


void loop()
{
  unsigned long timeNow = millis();
  static byte pos = 0;
  static boolean dir = true;
  static unsigned long servoPreviousTime = 0;
  for ( byte i = 0; i <  noOfAnalogInput; i++)
  {
    analogPin[i].analogValue = analogRead ( analogPin[i].analogPin);
  }
  PWMPin[0].PWMValue = map ( analogPin[0].analogValue, 0, 1023, 0, 255);
  ( PWMPin[0].PWMValue >= 150) ? ( outputPin[0].outputState = outputLogic) : ( outputPin[0].outputState = !outputLogic);
  ( PWMPin[0].PWMValue <= 150) ? ( outputPin[1].outputState = outputLogic) : ( outputPin[1].outputState = !outputLogic);
  int potVal = analogPin[1].analogValue; //<--Line 80
  if (potVal < 341)
  {
    potVal = ( potVal * 3) / 4;
    PWMPin[1].PWMValue = 256 - potVal;
    PWMPin[2].PWMValue = potVal;
    PWMPin[3].PWMValue = 1;
  }
  else if ( potVal < 682)
  {
    potVal = ( ( potVal - 341) * 3) / 4;

    PWMPin[1].PWMValue = 1;
    PWMPin[2].PWMValue = 256 - potVal;
    PWMPin[3].PWMValue = potVal;
  }
  else
  {
    potVal = ( (potVal - 683) * 3) / 4;

    PWMPin[1].PWMValue = potVal;
    PWMPin[2].PWMValue = 1;
    PWMPin[3].PWMValue = 256 - potVal;
  }
  if ( timeNow - servoPreviousTime >= servoDelay)
  {
    ( dir ) ? pos++ : pos--;
    if ( pos > 180 || pos < 0 ) dir = !dir;
    myServo.write(pos);
    servoPreviousTime = timeNow;
  }
  for ( byte i = 0; i < noOfPWMOutput; i++)
  {
    analogWrite ( PWMPin[i].PWMPin, PWMPin[i].PWMValue);
  }
  if ( debugMode)
  {
    static unsigned long debugPreviousTime = 0;
    if ( timeNow - servoPreviousTime >= debugDelay)
    {
      servoPreviousTime = timeNow;
      Serial.print("R:");
      Serial.print(PWMPin[1].PWMValue);
      Serial.print("\tG:");
      Serial.print(PWMPin[2].PWMValue);
      Serial.print("\tB:");    
      Serial.println(PWMPin[3].PWMValue);
    }
  }
}

I am beyond amazed on all the support and help I have received. Thank you all so much I feel so special and like I actually have someone for support. Thanks again so much for your guys time, truly means a lot to me.

On the serious matter, I have updated the code to now have an interrupt phase with one button, all its doing is stopping the sweep on the servo and starts back up nothing too special. I'm using one potentiometer (pot) in the whole process so now I'm wondering how i can implement your guys written code into this one now. Any ideas on how I can add the interrupt with one button to stop and start the sweep of the servo from the code y'all provided?

Thank you so much again for your time. I feel so blessed!!! :cry: :o :smiley:

New Code I wrote up:

#include <Servo.h>
int  servo_interrupt = 0;  //pin 2
int  toggle_on = false;
int  button_presses = 0;
int potPin = A0;
int motorPin = 11;
int potValue = 0;
int motorValue = 0;
int pos;
Servo myservo;

void setup(){
  myservo.attach(3);
    attachInterrupt(servo_interrupt, push_button, RISING);
}

void loop(){
  potValue = analogRead(potPin);
  motorValue = map(potValue,0,1023,0,255);
  analogWrite(motorPin, motorValue);
 
 if (toggle_on){
  for(pos=0;pos<=180;pos+=1)
  {
    myservo.write(pos);
    delay(20);
  }
  for(pos=180;pos>=0;pos-=1)
  {
    myservo.write(pos);
    delay(20);
  }
  }else{
    myservo.write(pos==pos);}
}

void push_button(){
  static unsigned long last_interrupt_time=0;
  unsigned long interrupt_time=millis();
  if(interrupt_time - last_interrupt_time > 200) {
    toggle_on=!toggle_on;
    button_presses++;
  }
  last_interrupt_time=interrupt_time;
}

alvarez6:
I have updated the code to now have an interrupt phase with one button,

Why do you need an interrupt?

...R

It's like a bonus if we can use a button to stop the servo from swiveling then back on after you press is again.

alvarez6:
It's like a bonus if we can use a button to stop the servo from swiveling then back on after you press is again.

The button is the bonus. There is no need for an interrupt just to read a button pressed by a person. Check the state of the button with digitalRead() each time that loop() repeats.

Interrupt programming and debugging can be very complex. If you want to learn about interrupts do that is a short sketch that does nothing else.

...R

@ alvarez6:

1st of all i want to know if my code work for your application and needs?
if it does I think i have answer the need of your original question.

2nd, I think you should learn how to do multitask in Arduino.

3rd your wasting precious resource by using interrupt for something as mundane as toggle a state, but hey if it work, it works.

4th ISR usually must be as compact as possible, the variable must be volatile and as I recall, millis() function is disable when in ISR.. or is it the TIMER interrupt that increment the millis() is disable, urm I might be wrong, Hope some of the more experience can correct me if I'm wrong .