Combining Codes

Hi community,

I have a problem with programming. I have currently been working with Servo and DC motors, as I need both of them for my project, an automatic dog feeder. I will be using one servo, and one DC motor. The servo will be opening a door, which will let the food fall down from a hopper. The DC motor will be attached to a mini Archimedes screw, and turn to move the food outwards. The problem is that I only know how to do each code separately. Is it possible to make the servo run first, then the DC motor run right after the servo finishes running?

Here is the code for the Servo:

[code] //Simple Motor Speed Control Program

const int MOTOR=9;    //Motor on Digital Pin 9

void setup()
{ 
   pinMode (MOTOR, OUTPUT); 
   
} 

void loop()
{
   for (int i=0; i<265; i++)
   { 
       analogWrite(MOTOR, i);
       delay(10);
   }
   delay(2000);
   for (int i =255; i>=0; i--)
   {
      analogWrite(MOTOR, i);
      delay(10);
    
   }
   delay(2000);
}

[/code]
Here is the code for the Dc motor:

const int motorPin = 9;


void setup()
{
  // Set up the motor pin to be an output:

  pinMode(motorPin, OUTPUT);

  // Set up the serial port:

  Serial.begin(9600);
}


void loop()
{
  // Here we've used comments to disable some of the examples.
  // To try different things, uncomment one of the following lines
  // and comment the other ones. See the functions below to learn
  // what they do and how they work.

  // motorOnThenOff();
  // motorOnThenOffWithSpeed();
  // motorAcceleration();
     serialSpeed();
}


// This function turns the motor on and off like the blinking LED.
// Try different values to affect the timing.

void motorOnThenOff()
{
  int onTime = 3000;  // milliseconds to turn the motor on
  int offTime = 3000; // milliseconds to turn the motor off
  
  digitalWrite(motorPin, HIGH); // turn the motor on (full speed)
  delay(onTime);                // delay for onTime milliseconds
  digitalWrite(motorPin, LOW);  // turn the motor off
  delay(offTime);               // delay for offTime milliseconds
}


// This function alternates between two speeds.
// Try different values to affect the timing and speed.

void motorOnThenOffWithSpeed()
{
  int Speed1 = 200;  // between 0 (stopped) and 255 (full speed)
  int Time1 = 3000;  // milliseconds for speed 1
  
  int Speed2 = 50;   // between 0 (stopped) and 255 (full speed)
  int Time2 = 3000;  // milliseconds to turn the motor off
  
  analogWrite(motorPin, Speed1);  // turns the motor On
  delay(Time1);                   // delay for onTime milliseconds
  analogWrite(motorPin, Speed2);  // turns the motor Off
  delay(Time2);                   // delay for offTime milliseconds
}


// This function slowly accelerates the motor to full speed,
// then back down to zero.

void motorAcceleration()
{
  int speed;
  int delayTime = 20; // milliseconds between each speed step
  
  // accelerate the motor

  for(speed = 0; speed <= 255; speed++)
  {
    analogWrite(motorPin,speed);	// set the new speed
    delay(delayTime);           	// delay between speed steps
  }
  
  // decelerate the motor

  for(speed = 255; speed >= 0; speed--)
  {
    analogWrite(motorPin,speed);	// set the new speed
    delay(delayTime);           	// delay between speed steps
  }
}


// This function will let you type a speed into the serial
// monitor window. Open the serial monitor using the magnifying-
// glass icon at the top right of the Arduino window. Then
// type your desired speed into the small text entry bar at the
// top of the window and click "Send" or press return. The motor
// will then operate at that speed. The valid range is 0 to 255.

void serialSpeed()
{
  int speed;
  
  Serial.println("Type a speed (0-255) into the box above,");
  Serial.println("then click [send] or press [return]");
  Serial.println();  // Print a blank line

  // In order to type out the above message only once,
  // we'll run the rest of this function in an infinite loop:

  while(true)  // "true" is always true, so this will loop forever.
  {
    // First we check to see if incoming data is available:
  
    while (Serial.available() > 0)
    {
      // If it is, we'll use parseInt() to pull out any numbers:
      
      speed = Serial.parseInt();
  
      // Because analogWrite() only works with numbers from
      // 0 to 255, we'll be sure the input is in that range:
  
      speed = constrain(speed, 0, 255);
      
      // We'll print out a message to let you know that the
      // number was received:
      
      Serial.print("Setting speed to ");
      Serial.println(speed);
  
      // And finally, we'll set the speed of the motor!
      
      analogWrite(motorPin, speed);
    }
  }
}

Any help would be greatly appreciated. :open_mouth:

That servo code doesn't look like servo code to me: as its comment says, it's speed control of a normal motor.... speeds it up then slows down.

But if it was servo code, it would be quite easy to do what you want: in loop() you just do the servo movement followed by the dc motor stuff. edit.... Making sure firstly, that you don't have a clash on pin assignments and variable names.

Get that servo part sorted first though: maybe you just posted the wrong code?

Oh, and please use code tags so that

your code;
looks
{
like
this
}

[code][/code]

JimboZA:
That servo code doesn't look like servo code to me: as its comment says, it's speed control of a normal motor.... speeds it up then slows down.

But if it was servo code, it would be quite easy to do what you want: in loop() you just do the servo movement followed by the dc motor stuff. edit.... Making sure firstly, that you don't have a clash on pin assignments and variable names.

Get that servo part sorted first though: maybe you just posted the wrong code?

Oh, and please use code tags so that

your code;

looks
{
like
this
}

:stuck_out_tongue: Whoops wrong code. The Servo code is here:

/*


void setup()
{
 
  servo1.attach(9);
}


void loop()
{
  int position;
  
    servo1.write(90);   
  delay(1000);         
  servo1.write(180);   
  delay(1000);        
  servo1.write(0);    
  delay(1000);         
  
    for(position = 0; position < 180; position += 2)
  {
    servo1.write(position);  
    delay(20);               
  }

    for(position = 180; position >= 0; position -= 1)
  {                                
    servo1.write(position);  
    delay(20);               
  }
}

Thanks a lot!! :slight_smile: :slight_smile:

Robin2 has this demo about merging codes. Give it a try yourself, or show us what you have tried so far and explain what's not working properly.

Basically, in the combined code, you:

  • Edit: just added this bullet....Think about the interaction you need between the two parts: in your case what will each of the motors (the servo and the dc) be doing, and when. Get that clear in your mind first.
  • Put above setup() all the stuff above setup() from both sketches, taking care of any clashes like variable names
  • Put in setup() all the stuff from setup() from both sketches, taking care of any clashes
  • Put in loop() all the stuff from loop() from both sketches, taking care of any clashes and taking care of the logical sequence of what happens when

For a start, you have both the servo and the dc motor on the same pin so you'll have to change one of them....

PLEASE put your code in the code tags, it's impossible to read otherwise. Select the text that is to be code, and hit the # above the :sweat_smile: smily next to the typewriter. You can go back and Modify your existing posts.

When you combine the programs please be aware that using the servo library prevents the use of PWM on pins 9 and 10 on boards other than the Mega.

JimboZA:
Robin2 has this demo about merging codes. Give it a try yourself, or show us what you have tried so far and explain what's not working properly.

Basically, in the combined code, you:

  • Edit: just added this bullet....Think about the interaction you need between the two parts: in your case what will each of the motors (the servo and the dc) be doing, and when. Get that clear in your mind first.
  • Put above setup() all the stuff above setup() from both sketches, taking care of any clashes like variable names
  • Put in setup() all the stuff from setup() from both sketches, taking care of any clashes
  • Put in loop() all the stuff from loop() from both sketches, taking care of any clashes and taking care of the logical sequence of what happens when

For a start, you have both the servo and the dc motor on the same pin so you'll have to change one of them....

PLEASE put your code in the code tags, it's impossible to read otherwise. Select the text that is to be code, and hit the # above the :sweat_smile: smily next to the typewriter. You can go back and Modify your existing posts.

I'm extremely sorry for the misunderstanding! Thanks, now I know how to use code tags ;). I haven't actually tried merging the codes yet, only testing each code separately. What will happen when I put the servo motor on a different pin? Will it still work the same? Sorry for being so inexperienced, I really am a beginner. :frowning:

UKHeliBob:
When you combine the programs please be aware that using the servo library prevents the use of PWM on pins 9 and 10 on boards other than the Mega.

Alright, thanks!

What will happen when I put the servo motor on a different pin? Will it still work the same? Sorry for being so inexperienced, I really am a beginner.

Yep it will... just change the servo.attach(put the right pin number here)

JimboZA:

What will happen when I put the servo motor on a different pin? Will it still work the same? Sorry for being so inexperienced, I really am a beginner.

Yep it will... just change the servo.attach(put the right pin number here)

Thanks! :smiley:

UKHeliBob:
When you combine the programs please be aware that using the servo library prevents the use of PWM on pins 9 and 10 on boards other than the Mega.

Alright. XD

I have run into a problem here. Both DC and Servo motors need to be plugged into 5v, and there is only one on the Arduino Uno. What can I do as an alternative? :~

FattyPatty01:
I have run into a problem here. Both DC and Servo motors need to be plugged into 5v, and there is only one on the Arduino Uno. What can I do as an alternative? :~

you won't be powering the servo or the motor off the Arduino, so that's not a problem.

AWOL:

FattyPatty01:
I have run into a problem here. Both DC and Servo motors need to be plugged into 5v, and there is only one on the Arduino Uno. What can I do as an alternative? :~

you won't be powering the servo or the motor off the Arduino, so that's not a problem.

Okay, I see. :sweat_smile:

Implication there is that you've been testing your dc motor code with the motor powered from the Arduino, is that correct? That's dangerous, since it may (read as: probably did) draw too much current. It's also a pity that, iirc, the tutorial here on the Arduino site shows a servo powered from the 5V. Bad....

This tutorial shows connecting a motor with a transistor. The Arduino controls the transistor (which is basically an electronic switch): when the Arduino pin is high, the transistor is closed and the motor current flows; when Arduino pin is off, transistor is open and motor is off. You can read about transistors here.

The attached schematic shows how you should (or could...) connect. Pin numbers random: choose your own. You also need that diode.

ps... if you don't have a breadboard, you should probably get one. Makes it easy to connect a bunch of things to + on one side and ground on the other.

dcmotor and servo.png

JimboZA:
Implication there is that you've been testing your dc motor code with the motor powered from the Arduino, is that correct? That's dangerous, since it may (read as: probably did) draw too much current. It's also a pity that, iirc, the tutorial here on the Arduino site shows a servo powered from the 5V. Bad....

This tutorial shows connecting a motor with a transistor. The Arduino controls the transistor (which is basically an electronic switch): when the Arduino pin is high, the transistor is closed and the motor current flows; when Arduino pin is off, transistor is open and motor is off. You can read about transistors here.

The attached schematic shows how you should (or could...) connect. Pin numbers random: choose your own. You also need that diode.

ps... if you don't have a breadboard, you should probably get one. Makes it easy to connect a bunch of things to + on one side and ground on the other.

Yes, I ordered the Vilros ultimate starter pack, which came with the breadboard. I have always been using the breadboard. For the DC motor I have been using a transistor and diode, but I'm not sure about the Servo. Anyways, thanks a lot for the help! :slight_smile:

FattyPatty01:
Yes, I ordered the Vilros ultimate starter pack, which came with the breadboard. I have always been using the breadboard. For the DC motor I have been using a transistor and diode, but I'm not sure about the Servo. Anyways, thanks a lot for the help! :slight_smile:

Great.

The servo doesn't need any other components- as my schematic shows.

One thing that's easy to forget, is that all the GNDs must be connected.

Pic attached here shows how you would do many servos.

Many servos- small V2.jpg

I have yet another question :~. I have ordered a DS1307 RTC for timing. I plan to use this to activate a motor at a certain time, but I'm not sure how to do it. How will I make it work, or what else could I use to activate the motor?

FattyPatty01:
I have yet another question :~. I have ordered a DS1307 RTC for timing. I plan to use this to activate a motor at a certain time, but I'm not sure how to do it. How will I make it work, or what else could I use to activate the motor?

Hi again...

I've read about there being an alarm library I think, although I've never used it. With my 1307, I just read the time everytime through loop() and see if the time is what I want. I write the time and temperature to an eeprom on the hour and half-past every hour.

It's a cumbersome method, since I need to use a flag to say the action is done, and check for that on subsequent loops, else if the time is still correct- and loop() is very fast to it checks the time before the seconds change!- it would do the action again.

So it's do-able with code in long-hand so to speak, but I'm pretty sure there are some short-hand ways- look in the Playground for alarm or similar terms, bound to be something. If not, Google "arduino 1307 alarm" or somesuch.

Worst case is to write stuff from scratch and I'll post my code if you need it.

I've read about there being an alarm library I think, although I've never used it

TimeAlarms is probably what you are thinking of. Very easy to use.

UKHeliBob:

I've read about there being an alarm library I think, although I've never used it

TimeAlarms is probably what you are thinking of. Very easy to use.

I was just looking at it, yep looks simple.

But the example I saw used the time library but not an RTC- so time is from reset as far as I could make out. Can TimeAlarms use time from an RTC as well?
Edit.... I'm guessing (and will test tomorrow) that since the RTC library and the alarms library both use the time library, that setting the time in the rtc has the same effect as setting it directly in the time library, and so the time will be visible to the alarm library?

Later edit.... I see there's an example to sync system time to rtc time, in which case then those alarms, which use system time, will actually be using rtc time. So @FP01, there's your answer: dead simple. I'm going to try that tomorrow...