Need to power small dc motor car for specific distance and stop

I am a middle school teacher writing on behalf of a group of students. I have a G&T class that has a task to power 5 small cars for a specific distance using different power sources and stop within an 18" square . No return, just go when switched on and stop on their own.
We have a small RC car and an Arduino for one of the cars.
We want to use the Arduino as a timer to send power to a relay to switch on the motor and switch it off after a specified time. We plan to test for run time / distance to hopefully get consistent results.
We have a very basic knowledge of programming but we have done a few blinking led sketches from a book.
Can someone please answer the following questions?
Is there a template that we can follow that will do this task?
What relay should we use?
Can we power the Arduino from the 2 AAA car batteries or should we use a 9v battery?
Is there a better way to do this with these components?
Thanks in advance
FT DI

Do you have a Arduino Uno ?
That runs at 16MHz, and because of that it needs 5V.
The microcontroller ATmega328P on the Arduino Uno can run on 2 AAA batteries, but only with a lower clock speed.

The relay depends on how much current is switched.
A small cheap 5V relay would be probably be good enough.
You could also use a logical power mosfet or a (darlington) transistor.

To measure the distance, you would need to measure the rotation of an axis or a wheel. This can be done with a magnet and a hall sensor or optical. If you have it working it would be nice to stick a white dot to a wheel and try to measure it with the Arduino and a optical sensor.

Welcome.... usually it's the students asking for help 8)

Have a look at these tutorials: This one drives a motor with a transistor, and this one drives a relay. One day you can get fancy and have speed and direction control, like this!

I'm thinking for simplicity, use the transistor one.... You'll see from the pic that the transistor is switched by an Arduino digital pin via a resistor: that's really no different from the Arduino driving a LED. Don't leave out that diode.....

You can't power the Arduino from 2x AAAs, that's only 3V, so yes you could use a 9V PP3 on the barrel jack, and power the motor from the car battery.

Edit... You could use a delay in the code between switching on and off, adjusting the delay value as your experimenting dictates. Put the code in setup() not loop() so that it only runs once:

write a high to the digital pin
delay for x time, ie have motor running for x
write a low to the pin.

Or as Krodal says, get really fancy with distance measuring but I got the impression you'll home in on an "on-time" by trial and error?

I have a G&T class

I'm guessing that's not "gin and tonic"?

Basically any relay will do since it appears it's quite a small DC motor. A transistor would most likely be sufficient as well.

However, I wouldn't rely on timing and guessing the run, but rather monitor it. A magnet on a wheel and a reed switch on the chassis will give you a signal for each rotation of the wheel (or, if you want even better precision, put multiple magnets). Multiply number of signals by the circumference of the wheel (or part of the circumference if you use multiple magnets) and you get the distance traveled more consistently than with timing (batteries deplete, motor runs more slowly, car doesn't cover the desired distance).

AWOL:

I have a G&T class

I'm guessing that's not "gin and tonic"?

.... that's in the Staff Room, not the Class Room

Thanks for the input so far. To answer a few questions. The device is an Uno. G&T = Gifted and Talented. The kids are mostly 5th graders that were recommended for the program by their teachers. They are doing this for a Destination Imagination competition. I'm writing on their behalf because of our districts restrictions on the use of social media at school.
We don't meet again until next week so hopefully there will be lots of suggestions for them to try. In the mean time I plan to pick up whatever relay or transistors we need over the weekend. I think we will try the timer config first because it was their idea and seems simpler to start out. Then if time allows we'll look at more precise options.

Thanks again, all suggestions are appreciated.
FT DI Team

Why don't you ask the kids to come up with ways to measure the distance traveled?
Serving them the answer sounds more "gifted" than "talented".

Then ask them to write the algorithm. Not the actual code, but what happens when and what is triggered in which condition.
When you have that writing the actual code, in this situation, is a breeze.
Make them compete against each other to see who can come up with the simplest method and way for each part of the problem.

Shpaget, perhaps the kids are using the internet during the weekend and reading this. I can think of ten ways to drive a toy car a certain distance. Let them come up with twenty ways.

Shpaget:
Why don't you ask the kids to come up with ways to measure the distance traveled?
Serving them the answer sounds more "gifted" than "talented".

Then ask them to write the algorithm. Not the actual code, but what happens when and what is triggered in which condition.
When you have that writing the actual code, in this situation, is a breeze.
Make them compete against each other to see who can come up with the simplest method and way for each part of the problem.

That's what we did and the timer idea was the most realistic and attainable in the short run.
These are 5th graders. They have lots of ideas but some of them involve anti gravity.
At this level they pretty much need to read and follow directions.
They searched this forum and others but did not find anything that could readily adapt.
So concrete numbers are more useful than theory for now.

You could use a boost regulator like this: http://www.pololu.com/catalog/product/798 or this: http://www.pololu.com/catalog/product/799 to get 5v out of your AA batteries. Thats assuming the small cars use a small amount of power, the larger regulator is only rated for around 500mA with a 3v input and 5v output.

Part of the kids' learning would be to note that eventually the same on-time gives too short a distance and they would chat about that and conclude it's as the battery goes flat.... then that could lead to a whole new chat and experimentation on different types and brands of batteries, looking into how to overcome the battery problem, solar power and blah and blah. They will, off their own bat, I'm pretty sure experiment on up- and down-slopes, different surfaces like pile carpet.

Pretty soon the 2013 equivalent of a 1970's Mopar fan will have the Arduino equivalent of a 426 Keith Black Hemi in there.

This is an awesome piece of learning... kudos to the G&T program.

Often times I find people on this site while commenting with the best intentions lose track of the target audience. How small are the motors you're using? If they draw less than 50 mA you can drive it directly from the arduino board with no added circuitry. Otherwise, you can use a battery pack (2 AAAs as you mentioned) to drive the motor and a single transistor ( just about any will do, just make sure it can handle the voltages and currents you will need for the dc motor. If it was there idea, it's a great place to start and it will work very well. As people mentioned, the motor will spin slower as the batteries are drained, but that's part of the fun.

Transistors are very easy to explain to even a 5th grader, you simply use the small current from the arduino to turn a switch on and off that allows the motor to run (might not quite be true, but that's the basic idea). For your own information, just google something like "how do I use a transistor" and look for a tutorial so you can learn about appropriate resistors and voltages.

And I just had A brilliant idea. You can add a small potentiometer to the circuit after the transistor. If you start it out with a moderate resistance, the students can use it to change the speed of the motor to fine tune their distance regardless of battery power (up to some limit obviously). This also prevents you from having to reprogram the arduino every time you want to change the distance.

Good luck with the project, stop back and let us know how it all turns out!

If they draw less than 50 mA you can drive it directly from the arduino board with no added circuitry

You know that tiny motor that just about manages to make your mobile phone vibrate?
That would almost certainly overload an AVR pin ( the limit is 40mA, not 50mA) - I've measured some over 130mA, though 70 to 100 is more likely.
Now imagine that vibra motor moving any kind of car bigger than a Hot Wheels.

Use a transistor.

GrisGris (nice sobriquet)

I would be happy to help you. You have mentioned that the students -- at this time -- just need to read and follow instructions. Thus, you don't seem to have the luxury of the hard knocks method. If I am sensing your situation correctly (and I have been wrong in larger towns than this) here are some resources for you.

The car would have a Hall Effect Detector (HED) (such as this one at Hall-Effect Sensor - US1881 (Latching) - COM-09312 - SparkFun Electronics) attached to the body/frame and a magnet placed on one of the wheels. I would suggest a non-drive wheel so that any slippage due to motor torque does not get counted. If a HED is not available then a reed switch that closes to ground to produce a LOW when the magnet is aligned will do. The HED is much cleaner, more sensitive and reliable.

The DC motor would be connected with a 2n2222 npn transistor (or equivalent -- handling about 200mA max) between the motor and ground. If your motor draws more than 200mA, then TO-220 NPN transistor (like the TIP31) will need to be used. Be sure to place a reversed diode (cathode toward +DCV) in parallel with the motor to handle any back-EMF when the motor is stopped. A 1N4001 is a defacto standard, methinks. Run a 4.7k ohm resistor from the Arduino pin to the base of the transistor (if you decide to use a lower beta power transistor, you might want to use a 1k resistor to assure saturation), the emitter goes to ground, and the collector goes to the bottom (negative) side of the motor. I would place a 0.1uFd capacitor in parallel with the motor and diode just to keep noise down.

Here is the code

/****************************************************************************************************\
** This code is intended to allow an Ardino Uno to control a model car having a small brushed DC motor
** and drive it forward a given distance and then stop
**
** It expects a latching Hall Effect sensor (such as the one at https://www.sparkfun.com/products/9312) 
** attached to the body and a magnet attached to a non-drive wheel so that, as the wheel rotates, the 
** magnet and sensor align once a revolution.
**
** The motor will draw too much current for the Arduino pin so an NPN transistor (such as a 2N2222) 
** is driven through a 4.7k ohm resistor to drive the motor. If the motor draws more than 200mA, use
** a TO-220 power transistor.
**
** It first waits for the wheel to be turned to align the magnet and the sensor.
**
** Once it sees alignment, it turns ON the on-board Arduino LED that is attached to digital pin 13
** to notify the user that it is ready to run.
**
** It then awaits a SPST N.O. momentary switch to be pressed as a signal for the car to go.
**
** When pressed, it does a quick re-check to make sure the wheel is still in a known position.
**
** It starts the motor and then counts wheel revolutions until the required distance has been reached.
**
** It then turns OFF the motor
\****************************************************************************************************/

// pin declarations
// pins chosen to avoid PWM pins to leave them free in case the project is expanded
const int MOTOR_PIN = 7;	// pin 7 is an OUTPUT that has an NPN transistor attached which turns ON and OFF the DC motor
const int GO_PIN = 8;		// pin 8 is an INPUT looking for a LOW signal to start the car
const int WHEEL_PIN = 12;	// pin 12 is an INPUT that has the Hall Effect sensor attached -- LOW = magnet is present
const int READY_PIN = 13;	// pin 13 is an OUTPUT that has an LED which signals that the car is ready for a run
                                        // i.e. magnet is aligned with the Hall Effect sensor

// non-pin declarations
const int MAX_WHEEL = 10;	// number of wheel rotations to the target area -- 10 is a dummy number that needs to be set after experimentation
const int READY = LOW;		// a LOW on the ready pin means that the magnet and hall effect sensor are aligned
const int UNREADY = HIGH;	// a HIGH on the ready pin means that the magnet and hall effect sensor are not aligned

void setup()
{
	// initialize pins
	pinMode( GO_PIN, INPUT_PULLUP );
	pinMode( WHEEL_PIN, INPUT_PULLUP );
	pinMode( MOTOR_PIN, OUTPUT );
	pinMode( READY_PIN, OUTPUT );

        // DEBUG
        Serial.begin(9600);
        Serial.println("---== start ==---");
}

void loop()
{
  	int loop_flg;		// flag to exit do while loop
	int i;			// for loop index

	// turn OFF motor & READY LED
	digitalWrite(MOTOR_PIN, LOW);
	digitalWrite(READY_PIN, LOW);

        Serial.println("init over -- begin looking for wheel");
        
	// LOOP waiting for ready signal -- wheel turned till magnet aligned with Hall Effect sensor
	do
	{
    		loop_flg = digitalRead(WHEEL_PIN);

		// debounce pin
		if( loop_flg == READY )
		{
			delay(150);	// wait 150mS and check again
			loop_flg = digitalRead(WHEEL_PIN);
		}
	} while ( loop_flg == UNREADY );

	// turn ON ready LED
	digitalWrite( READY_PIN, HIGH );

        Serial.println("Found wheel -- turned ON ready led -- looking for go");
        
	// LOOP waiting for GO signal -- LOW on pin 8
	do
	{
    		loop_flg = digitalRead(GO_PIN);

		// debounce pin
		if( loop_flg == READY )
		{
			delay(50);	// wait 50ms and check again
			loop_flg = digitalRead(GO_PIN);
		}
	} while ( loop_flg == UNREADY );

        Serial.println("found go -- rechecking wheel");
        
	//here: we have been waiting for the GO signal, so re-check that wheel is still ready
	loop_flg = digitalRead(WHEEL_PIN);

	if( loop_flg == READY )
	{
                Serial.println("wheel rechecked ok -- turning on motor");
                
		// turn ON the motor
		digitalWrite(MOTOR_PIN, HIGH);

                Serial.println("motor on -- starting count");

		// FOR LOOP counting wheel rotations
		for( i = 0 ; i < MAX_WHEEL ; i++ )
		{
			// LOOP waiting for ready signal to go HIGH -- magnet no longer sensed by Hall Effect sensor
			do
			{
    				loop_flg = digitalRead(WHEEL_PIN);

				// debounce pin
				if( loop_flg == UNREADY )
				{
					delay(50);	// wait 50ms and check again
					loop_flg = digitalRead(WHEEL_PIN);
				}
			} while ( loop_flg == READY );

                        Serial.println("magnet gone");
                        
			//here: the Hall Effect no longer sees the magnet

			// LOOP waiting for ready signal to go LOW -- magnet now aligned with Hall Effect sensor
			do
			{
    				loop_flg = digitalRead(WHEEL_PIN);

				// debounce pin
				if( loop_flg == READY )
				{
					delay(50);	// wait 50ms and check again
					loop_flg = digitalRead(WHEEL_PIN);
				}
			} while ( loop_flg == UNREADY );

			//here: the Hall Effect now sees the magnet = a revolution has been completed
                        // so complete interation of for loop

                        Serial.println("magnet present");
                        Serial.print("revolution number ");
                        Serial.println( i + 1 );
		}
		
		//here: the necessary revolutions have been executed

		// turn OFF motor
		digitalWrite( MOTOR_PIN, LOW );
                Serial.println("motor off");
                Serial.println("---== DONE ==---");
	}
        else
        {
                Serial.println("----- wheel mis-aligned when go was pressed -- redo -----"); 
        }
}

I think that it works, but don't have the hardware to fully test. If you need a schematic, I could rustle one up. For the transistor driving a DC motor look here Tutorial 5 for Arduino: Motors and Transistors – JeremyBlum.com for a cool tutorial thanks to Jeremy Blum. There's a video and everything!

Let us know if you need more help, and let us know how it turns out. Photos or videos would be cool.

Thanks for the input
This car is by far the most complicated. Others are fully mechanical, forced air, mouse trap etc.
Jim, Thanks for the links. We'll try those tutorials in class.
MaJ, thanks for the specifics thats our level of operation. I think we'll go with your suggestions.
I'm sure we'll have more questions in the near future.
Les Bon Ton Roulet

I am attaching a breadboard picture and a crude schematic, which has the motor connected to 3.3V as I believe you are using a 3V pager motor, yes?

You can have the students breadboard the project without the Hall Effect sensor like this:

*Run the wire from D12 to +5V to simulate the wheel being out of alignment.

*Download and run the code. The D13 (READY) should be OFF, indicating that you aren't ready to start.

*Move the D12 wire from +5V to GND, which simulates the magnet aligning. The D13 (READY) LED should come ON to indicate that the wheel is now aligned and we're ready to go.

*Press the GO button. The motor should start running.

*Now move the D12 wire between between GND and +5V ten times.

*After the tenth transition from HIGH to LOW (this number is a constant in the code), the motor should turn OFF.

You can test the setup and get everything working so that, when the Hall Effect comes in, you are already 90% done. Be mindful of the heat of the motor. It might not like running for more than 30 seconds or so.

The breadboard pic is generated by Fritzing here: http://fritzing.org/

motor18_schem2.jpg

Thanks MaJ
That's what we will do today.
The sensor is in the mail as of yesterday.
I'll post back with our results tonight.
We'll probably have more questions too.
In the immortal words of Darnell Turner "That was a straight up Street Ballin move Willie."

BTW, you're going to need small powerful magnets. Like these http://www.amazon.com/Grade-Super-Strong-Neodymium-Magnets/dp/B001ANVAHI/ref=pd_cp_hi_1

They need to be axial. You would glue one with South toward the sensor and three with North toward the sensor.

Using four will balance the wheel and turn OFF the Hall Effect Detector, which is latching.

Willie the postman???

Keep me up updated...

OK we got the sensor and most of the circuit connected. We even think we understand what's going on. But here are our questions so far:

  1. The code says D13 should have a LED to indicate ready but it is not shown in either diagram. We assume that the other end should be grounded but we are not sure of where to put it on the breadboard.
  2. Our sensor has 3 leads the one in the diagram only has 2. According to the datasheet we think D12 should go to the output. The middle leg should go to ground and the input should should connect to 3V. Right? But again we are unsure of how to place it on the board.
  3. Our go button is a spring loaded NO. Is that correct or does it need to operate in a closed position?

Right, Willie the Postman... From the yard sale scene where Joy steals the ball from the game and Willie pops out his glass eye as a replacement.
My other favorite is Billie... “He can still be your brother, he just has to be an outside brother”
Thanks again for the help