Topic outline
- General
- Topic 1
Topic 1
Introduction
The object of this is to make a first robot. This can then be used to learn about programming, motors, sensors, power etc. The project we are attempting is a system. A system can be thought of a set of things working together. Our project has three main parts.
- Engineering (making)
- Connecting (the Arduino to the motors and sensors)
- Actuating (programming the arduino)
The dilema comes when you are constrained by a classroom, assessment deadlines and a lack of proper equipment. The real fun is when you have a workshop set up, a range of electronic components at hand and a bunch of junk you can cut up and hack to make stuff.
Massimo Banzi, co founder of the Arduino, sets out his thoughts in his book "Getting started with Arduino".
hh Before you start, take a time to pause, Read through the cousre, leaf through Massimo Banzi's book, think a bit.
Remember, this is only a guide. Change what ever you like. Become a "Bricoleur"
- Topic 2
Topic 2
Problem definition : The very simple robot
Instructables web site Instructables web site hello
- Topic 3
Topic 3
Problem definition : Parts of the robot
These simple robots can be sourced from Ebay, Aliexpress or Deal Extreme.
It is a great place to start.
One strategy is to only use local sources, but occassionally what you want is either not available or too expensive to buy multiples.
One fun way to souce components, especially wheels is the local swapmeet or car boot sale. Toy cars routinely sell for a dollar and four wheels become very cheap.
Be on the lookout for old cd rom drives and such.
Another good places to fossick around are the periodic chuckouts run by local councils. Old dvd players and especially printers are a goldmine for stepper motors and components.
Parts list
- arduino clone
- L298N motors driver
- 2 geared motors
- 2 Optical Slot Switch
- hc-sr04 ultrasonic sensor
- hc-sr04 ultrasonic sensor holder
- sg90 9g servo motor
- plastic plates to build a chassis
- 2 * 65 mm wheels (yellow)
- 1 jockey wheel
- 4 * m-f leads
- required number of AA batteries
- battery holder
- 2.1 cm male jack
- toggle on/off switch
- USB cable
- M3 screws of varying lengths
- Wires : black and red
- perpex platform
Tools
- electric drill
- m3 drill bit
- wire
- wire strippers
- soldering iron, solder, cleaning station
- hands free or large bulldog clip
- wire cutters, pliers
- philips screw driver
- 6.5 mm plastic wall plugs or brass risers
- Topic 4
Topic 4
System Design : Primary build
Assemble robot as shown.
Solder wire to each motor, give yourself a little extra that can be cut back later
Plan what your final build will look like.
Add battery pack, switch and arduino in a convenient configuration.
- Topic 5
Topic 5
Subsystems : The electonics
- Topic 6
Topic 6
Substem : Power
There are many ways to power an Arduino and a robot.
eg
- Pack of 1.5v AA batteries (2,4,6,8)
- Pack of 2 3.7v batteries
- Rechargeable
Be aware that an Arduino needs 5 volts to run, so a 4 AA battery solution has a limited life - Topic 7
Topic 7
Subsystem : The motors and wheels
The wheels and motors are all about one thing : torque, the ability of a force to rotate an object about an axle.
This is all about levers, forces and fulcrums. The lesson to be learned here is that small electric motors cannot drag robots across carpets etc, unles they are given a torque advantage by gears.
It is also important to note these are DC motors.
They have a positive and negative input, so it is possible to get them to turn around by reversing the polarity on the battery.
Geared motors are the way to go and if buying of ebay, get the combo kit that has the wheels attatched.
Of course, it is cheating, but you can purchase the whole kit complete.
However, experience suggests that kids really like the drilling, using a screwdriver and soldering.
Thats sort of the point of bricoleur
- Topic 8
Topic 8
Sub system : Controlling motors : l29x
A motor should be able to spin two ways. To accomplish this, there are a number of ways.
- transistors
- h briges
- relays
The l293 is a board that enables a motor to spin in two different directions, based on the commands from the Arduino.The motor driver is an important part of controlling a robot.Note : When we start to add components to the Arduino, we are actually creating systems. - Topic 9
Topic 9
Subsystems : programming
void setup() {
// put your setup code here, to run once:}
void loop() {
// put your main code here, to run repeatedly:
} - Topic 10
Topic 10
Assignment : Soldering your motor leads
At some stage you will need to get two motors you intend to use for your robot and solder leads onto them.
Have some practice goes with spare wire, use a hands free or a bulldog clip to hold the wires firmly while you "tin" them and don't forget the heat-shrink to both protect the joint and insulate it from accidental short circuits.
Screw the motors and jockey wheels onto the chassis.
Soldering is defined as "the joining of metals by a fusion of alloys which have relatively low melting points".
In other words, you use a metal that has a low melting point to adhere the surfaces to be soldered together. Consider that soldering is more like gluing with molten metal, unlike welding where the base metals are actually melted and combined.
Soldering is also a must have skill for all sorts of electrical and electronics work. It is also a skill that must be taught correctly and developed with practice.
- Topic 11
Topic 11
Mr Weber's heads up : connect the motor driver
OK
This is the part where the taklking gets much less and the doing gets more.
First thing is to get your robot to move in a predictable way.
Program it to move
- forward
- back
- left (spin)
- left (sweep)
- right (spin)
- right (sweep)
- reverse
- halt
Later we will add a sonic sensor to see if it can avoid obstacles.
l The L297N H bridge
Smarty pants kids will by now realise they can find examples on the web as well as code.
Sites like
- instructables
- thingaverse
- youtube
will give you ideas.There are also- personal learning networks (PLN's)
- forums
- other kids
Time to get cracking.The next part of the jouney is to go completely rogue and try to figure out how you can control a robot by
- infra red
- touch sensors
- wireless
- gps
- anything
Regard you robot not as a one off device but a starting point o investigate how all this fits together.
- Topic 12
Topic 12
Challenge 1 : Getting it to run and stop
Copy and paste the following code into your Arduino IDE.
The objective is to make sure the wheel motors are plugged into the motor driver so they propel the vehicle forward.
Check int 1 is connected to pin 9 etc. If the robot does not go forward, reverse the leads on motor a and/or b.
Note : it is not unusual for your robot not to travel in a straight line. You need to balance the load on both motors. There are several techniques, and we will cover one, pulse width modulation, later.
/*
Robot 1 : Documentation
This is the first program for running the simple robot.
We just want to make sure the motors spin the right way and the robot moves forward.Note the use of the ena, enb. In the old version of l298, there were 6 inputs. ena and enb
are set to HIGH. these can be set by hardware and hence are commented out.Depending on your driver, you can compile these commands or not. Use find
and replace to remove the comment out directive if you wish.
*/// int ena = 4;
int int1 = 5;
int int2 = 6;// int enb = 8;
int int3 =9;
int int4 = 10;int timex = 3000; //runs for 3 seconds
boolean run;void setup() {
//pinMode (ena,OUTPUT);
pinMode (int1,OUTPUT);
pinMode (int2,OUTPUT);//pinMode (enb,OUTPUT);
pinMode (int3,OUTPUT);
pinMode (int4,OUTPUT);run = true;
}void loop() {
if (run)
{
forward(); // sets the robot forward.
// check motors are spinning in same direction
delay(timex);
halt(); // stops the code running
run = false;
}
}void forward() // forward sub proceedure
{
//digitalWrite(ena,HIGH);
digitalWrite(int1,HIGH);
digitalWrite(int2,LOW);//digitalWrite(enb, HIGH);
digitalWrite(int3,HIGH);
digitalWrite(int4,LOW);}
void halt() // halt sub proceedure
{
//digitalWrite(ena,HIGH);
digitalWrite(int1,LOW);
digitalWrite(int2,LOW);//digitalWrite(enb,HIGH);
digitalWrite(int3,LOW);
digitalWrite(int4,LOW);}
Solder a switch on the positive (red) wire, between the battery pack and the boards. drill and appropriately sized hole and screw the switch in.
This is a useful innovation for conrolling your device during testing.
- Topic 13
Topic 13
Forward, reverse, left and right
/*Robot 1
This is the first program for running the simple robot.
We just want to make sure the motors spin the right and left correctly
and the robot moves forward .Note the use of the ena, enb. In the old version of L298, there were 6 inputs. ena and enb
are set to HIGH. these can be set by hardware and hence are commented out.Depending on your driver, you can compile these commands or not. Use find
and replace to remove the comment out directive if you wish.
*/// int ena = 4;
int int1 = 5;
int int2 = 6;// int enb = 8;
int int3 =9;
int int4 = 10;int timex = 3000; //global variable runs for 3 seconds
boolean run;void setup() {
//pinMode (ena,OUTPUT);
pinMode (int1,OUTPUT);
pinMode (int2,OUTPUT);//pinMode (enb,OUTPUT);
pinMode (int3,OUTPUT);
pinMode (int4,OUTPUT);run = true;
}void loop() {
if (run)
{ // parameter passed as a valueforward(3000); // sets the robot forward.
// check motors are spinning in same direction
//delay(timex);
halt(); // stops motors running
left(3000); // sets the robot forward.
// check motors are spinning in same direction
//delay(timex);
halt(); // stops motors running
right(3000); // sets the robot forward.
// check motors are spinning in same direction
//delay(timex);
reverse(3000); // sets the robot forward.
// check motors are spinning in same direction
//delay(timex);
halt(); // stops the motors running
run = false; // halts the code
}
}void reverse(int wait){ // reverse sub procedure
//digitalWrite(ena,HIGH);
digitalWrite(int1,LOW);
digitalWrite(int2,HIGH);//digitalWrite(enb, HIGH);
digitalWrite(int3,LOW);
digitalWrite(int4,HIGH);delay(wait);
}
void forward(int wait){ // forward sub procedure
//digitalWrite(ena,HIGH);
digitalWrite(int1,HIGH);
digitalWrite(int2,LOW);//digitalWrite(enb, HIGH);
digitalWrite(int3,HIGH);
digitalWrite(int4,LOW);delay(wait);
}
void halt() // halt sub proceedure
{
//digitalWrite(ena,HIGH);
digitalWrite(int1,LOW);
digitalWrite(int2,LOW);//digitalWrite(enb,HIGH);
digitalWrite(int3,LOW);
digitalWrite(int4,LOW);
}
void right(int wait){
//digitalWrite(ena, HIGH);
digitalWrite(int1,LOW);
digitalWrite(int2,HIGH);//digitalWrite(enb, HIGH);
digitalWrite(int3,HIGH);
digitalWrite(int4,LOW);delay(wait);
}void left(int wait){
//digitalWrite(ena, HIGH);
digitalWrite(int1,HIGH);
digitalWrite(int2,LOW);//digitalWrite(enb, HIGH);
digitalWrite(int3,LOW);
digitalWrite(int4,HIGH);delay(wait);
} - Topic 14
Topic 14
Getting the robot to go straight : PWM
For various reasons, the voltage supplied to each motor is different. There is a way to vary the voltage using pulse width modulation. For a full explanation, check out youtube.
The key to understanding PWM is to understand the difference between a digital and analog signal. The commands for each are
digitalWrte(ledPin, HIGH);
analogWrite(ledPin,i);
where i changes from a value of 0 to 255
A digital signal in Arduino is either a 5v or 0v prot. An analog signal in Arduino is 5v spread between 0 - 255 steps. Analog can be reprogrammed in pins 3,5,6, 9, 10, 11 or accessed directly with pins A0 - A5.
Here is some code that demonstrates the use of PWM using an Arduino, 2 motors and an L298n motor driver.
A techy introduction Knowlege : the difference between analog and digital.
/* This is a first attempt to get my tank robot to go straight.
* It seems to meed more power on the starboard side than the port.
* It is usefull to define forward motion in terms of port (left)
* and starboard (right).
*
* This invlved pulse width modulation. not the difference between
* analogWrite() and digitalWrite() commands
*
* Note if the PWM is not high enough, there might not be enough power
* to turn over your motors
*
* mrweber
* 14/5/16
*/
// int ena = 4;
int int1 = 5;
int int2 = 6;// int enb = 8;
int int3 =9;
int int4 = 10;int timex = 3000; //runs for 3 seconds
boolean run;void setup() {
//pinMode (ena,OUTPUT);
pinMode (int1,OUTPUT);
pinMode (int2,OUTPUT);//pinMode (enb,OUTPUT);
pinMode (int3,OUTPUT);
pinMode (int4,OUTPUT);run = true;
}void loop()
{
delay(3000);
if (run)
{
forward();
delay (4000);
halt();
run = false; // runs only one time
}
}void forward() // forward sub proceedure
{
//starboard motor
analogWrite(int1,180); // <==== 100%
digitalWrite(int2,LOW);//port motor
analogWrite(int3,150); // < === 83% this balances the load
analogWrite(int4,LOW);}
void halt() // halt sub proceedure
{
//digitalWrite(ena,HIGH);
digitalWrite(int1,LOW);
digitalWrite(int2,LOW);//digitalWrite(enb,HIGH);
digitalWrite(int3,LOW);
digitalWrite(int4,LOW);}
Skill : be able to write subroutines in C and call them from the main program. Extra for experts : servo motors
The dont argue : relays
Skill : Be able to search out a datasheet on the web and deduce from information. - Topic 15
Topic 15
Using the HC-SR04 sonic sensor
/*
HC-SR04 Ping distance sensor]
VCC to arduino 5v GND to arduino GND
Echo to Arduino pin 13 Trig to Arduino pin 12
*/#define trigPin 13
#define echoPin 12int duration;
int distance;void setup() {
Serial.begin (9600);
pinMode(trigPin, OUTPUT);
pinMode(echoPin, INPUT);
}void loop() {
long duration, distance;
digitalWrite(trigPin, LOW);
delayMicroseconds(20);
digitalWrite(trigPin, HIGH);
delayMicroseconds(20);
digitalWrite(trigPin, LOW);
duration = pulseIn(echoPin, HIGH);
distance = (duration/2) / 29.1;Serial.print(distance);
Serial.println(" cm");delay(500);
} - Topic 16
Topic 16
Running a robot with sonic sensor
The hc-sr04 needs 5 volts to operate. Take the Vcc from the L297d motor driver NOT the Arduino board.
/*
Mr Weber's fifth robot program.the robot goes forwards for 2 seconds then stops,
turns left 90 degrees,stops, then right 90 degrees, stops,
then back and stops.hint : The hc-sr04 needs 5 volts to operate. Take the Vcc from the L297d motor driver NOT the Arduino board.
author mark weber
date 6/4/14
*/int ena = 3; // these relate to the h bridge (L293 chip)
int int1 = 4; // to drive the motors
int int2 = 5;int enb = 8;
int int3 =9;
int int4 = 10;int trigPin = 12; // check the hc-sr04 sonic sensor
int echoPin = 11; // for the pinoutslong duration, distance;
long x = 0;
void setup() {
Serial.begin (9600);
pinMode(trigPin, OUTPUT);
pinMode(echoPin, INPUT);pinMode (ena,OUTPUT);
pinMode (int1,OUTPUT);
pinMode (int2,OUTPUT);
pinMode (enb,OUTPUT);
pinMode (int3,OUTPUT);
pinMode (int4,OUTPUT);}
void loop()
{
distance = sonic(x);
if (distance >= 200 || distance <= 0){ // testing
Serial.println("Out of range main");
}
else {
Serial.print(distance); // function working
Serial.println(" cm main");
}if (distance > 10)
{
forward();
}
else
{
halt();
back();
halt();
left();
}
delay(500);
}long sonic(long x) // calls the function sonic here
{
digitalWrite(trigPin, LOW); // Added this line
delayMicroseconds(2); // Added this line
digitalWrite(trigPin, HIGH);
delayMicroseconds(10); // Added this line
digitalWrite(trigPin, LOW);
duration = pulseIn(echoPin, HIGH);
distance = (duration/2) / 29.1;
if (distance >= 200 || distance <= 0){
Serial.println("Out of range");
}
else {
Serial.print(distance);
Serial.println(" cm");
}
delay(500);
return distance;
}
void halt()
{
digitalWrite(ena,HIGH);
digitalWrite(int1,LOW);
digitalWrite(int2,LOW);
digitalWrite(enb,HIGH);
digitalWrite(int3,LOW);
digitalWrite(int4,LOW);
delay(500);
}
void back()
{
digitalWrite(ena, HIGH);
digitalWrite(int1,LOW);
digitalWrite(int2,HIGH);
digitalWrite(enb,HIGH);
digitalWrite(int1,LOW);
digitalWrite(int4,HIGH);
delay(500);
}void left()
// goes right
{
digitalWrite(ena, HIGH);
digitalWrite(int1,LOW);
digitalWrite(int2,HIGH);
digitalWrite(enb, HIGH);
digitalWrite(int3,HIGH);
digitalWrite(int4,LOW);
delay(500);
}void right()
// goes backwards
{digitalWrite(ena, HIGH);
digitalWrite(int1,HIGH);
digitalWrite(int2,LOW);
digitalWrite(enb, HIGH);
digitalWrite(int3,LOW);
digitalWrite(int4,HIGH);}
void forward()
{
digitalWrite(ena, HIGH);
digitalWrite(int1,HIGH);
digitalWrite(int2,LOW);
digitalWrite(enb, HIGH);
digitalWrite(int3,HIGH);
digitalWrite(int4,LOW);
delay(500); // this is shorter
} - Topic 17
Topic 17
IR detector
TCRT5000
//this is a program to test if we can read a sensor
//we used a tcrt5000 sensor i bought off alibaba
//in a set with an ir led
//the key to the exercise was the balance between the two resistors in the circuit diagramint sensor; // use an integer and read it continually
void setup()
{
Serial.begin(9600); //read serial port
}void loop()
{
sensor=analogRead (A0); // note use of Arduino analog port
Serial.println(sensor);
delay(1000);
if (sensor < 500)
{
Serial.println("hello less than 500, it must be light");
}
else
{
Serial.println("we are in the dark, greater than 500");
}
}Data sheet - Topic 18
- Topic 19
Topic 19
Putting it together : Obstacle avoiding code
One of the great strengths and weaknesses of the robot is that it only processes on series of commands at a time.
One way to get around this is to execute a series of commands very quickly to give the appearence of them working together. So by setting the motors forward ever 30/1000 of a second then moving the servo you can give the appearence of the system working harmonously.
Pulse width modulation works in this way.
/*
This uses the above code to turn a servo through
65 - 114 degreesthis can now be put in as part of a loop to run in conjuction
with a motorised robotmrweber
261115
*/#include <Servo.h>
Servo myservo;int count = 45;
int sentinal =1;// int ena = 4;
int int1 = 5;
int int2 = 6;// int enb = 8;
int int3 =9;
int int4 = 10;#define trigPin 13
#define echoPin 12void setup() {
// put your setup code here, to run once:
Serial.begin(9600);pinMode(trigPin, OUTPUT);
pinMode(echoPin, INPUT);
myservo.attach(3);
}void loop() {
forward (30);
sg90();
delay(20);
pinger();}
void pinger() {
long duration, distance;
digitalWrite(trigPin, LOW); // Added this line
delayMicroseconds(2); // Added this line
digitalWrite(trigPin, HIGH);
delayMicroseconds(10);
digitalWrite(trigPin, LOW);
duration = pulseIn(echoPin, HIGH);
distance = (duration/2) / 29.1; // there and back is 2*distance
Serial.println(distance);
if (distance < 10){
halt(100);
reverse(1000);
halt(100);
right(500);
halt(100);
}
}
void reverse(int wait){ // reverse sub procedure
//digitalWrite(ena,HIGH);
digitalWrite(int1,LOW);
digitalWrite(int2,HIGH);//digitalWrite(enb, HIGH);
digitalWrite(int3,LOW);
digitalWrite(int4,HIGH);delay(wait);
}void forward(int wait){ // forward sub procedure
//digitalWrite(ena,HIGH);
digitalWrite(int1,HIGH);
digitalWrite(int2,LOW);//digitalWrite(enb, HIGH);
digitalWrite(int3,HIGH);
digitalWrite(int4,LOW);delay(wait);
}
void halt(int wait) // halt sub proceedure
{
//digitalWrite(ena,HIGH);
digitalWrite(int1,LOW);
digitalWrite(int2,LOW);//digitalWrite(enb,HIGH);
digitalWrite(int3,LOW);
digitalWrite(int4,LOW);
delay(wait);
}
void right(int wait){
//digitalWrite(ena, HIGH);
digitalWrite(int1,LOW);
digitalWrite(int2,HIGH);//digitalWrite(enb, HIGH);
digitalWrite(int3,HIGH);
digitalWrite(int4,LOW);delay(wait);
}void left(int wait){
//digitalWrite(ena, HIGH);
digitalWrite(int1,HIGH);
digitalWrite(int2,LOW);//digitalWrite(enb, HIGH);
digitalWrite(int3,LOW);
digitalWrite(int4,HIGH);delay(wait);
}
void sg90(){
// here increases count
if ((sentinal == 1) && (count <=114)){
count = count + 1; // loop increments to 65
sentinal = 1; // sentinal
myservo.write(count);
}
else {
sentinal = -1;
}
// changes over and decreases count
if ((sentinal == -1) && (count >= 60) ){
count = count - 1;
sentinal = -1; // sentinal
myservo.write(count);
}
else {
sentinal = 1;
}
} - Topic 20
Topic 20
- Topic 21
Topic 21
Line following robot
If you are using 1 sensor, then your code should be something like:
Void loop {
If(sensorvalue < threshold){
Turn left
};
If(sensorvalue > threshold){
Turn right
};
}
This will cause your robot to wiggle side to side while riding the edge of the line.Line following robot - Topic 22
Topic 22
Sample code for line following robot
/*
marks little line followerwith a little bit of mucking around. this code will balance robot speed
and the speed of turn to follow a line.the problem comes when it reaches the end and turns around.
the next step is to investigate Proportional-Integral-Derivative Control (PID).
PID is a feedback loop that adjest a process around a set condition.*/
int left_motor_1 = 5;
int left_motor_2 = 6; // these pins support pwmint right_motor_1 = 9;
int right_motor_2 = 10;
int analogPinx = A0;
int digiPin = 13;
int val = 100; // variable to store the value readint threshhold = 500; // between 0 - 1024
boolean run = true;
void setup(){
pinMode (right_motor_1,OUTPUT);
pinMode (right_motor_2,OUTPUT);
pinMode (left_motor_1,OUTPUT);
pinMode (left_motor_2,OUTPUT);pinMode (digiPin,OUTPUT);
Serial.begin(9600); // setup serial
}
void loop()
{
val = analogRead(analogPinx); // read the input pin
Serial.println(val); // debug value
delay(1000);
digitalWrite(digiPin,HIGH);forward();
delay(500);
while (run == true) // uses == the equality evaluator
{ // run is never set to false so is infinite
if (val > threshhold) // wiggle left
{
left();
delay (20);
forward();
delay(20);
val = analogRead(analogPinx);
} // the use of 'x' in case
// analogPin is reserved word
else
{
right(); // wiggle right
delay (20);
forward();
delay(20);
val = analogRead(analogPinx);
}
}
}
void halt()
{
digitalWrite(left_motor_1,LOW);
digitalWrite(left_motor_2,LOW);
digitalWrite(right_motor_1,LOW);
digitalWrite(right_motor_2,LOW);}
void back()
{digitalWrite(left_motor_1,LOW);
digitalWrite(left_motor_2,HIGH);
digitalWrite(left_motor_1,LOW);
digitalWrite(right_motor_2,HIGH);}
void left()
{
digitalWrite(left_motor_1,LOW);
analogWrite(left_motor_2,125); // uses an analog signal to control speeddigitalWrite(right_motor_1,HIGH);
analogWrite(right_motor_2,125); // better andled with a variable}
void right()
{
analogWrite(left_motor_1,125);
digitalWrite(left_motor_2,LOW);digitalWrite(right_motor_1,LOW);
analogWrite(right_motor_2,125);}
void forward()
{
analogWrite(left_motor_1,125);
digitalWrite(left_motor_2,LOW);analogWrite(right_motor_1,125);
digitalWrite(right_motor_2,LOW);}
- Topic 23
Topic 23
Line avoiding robot
/*
Robot 1
This is the first program for running the simple robot.
We just want to make sure the motors spin the right way and the robot moves forward.Note the use of the ena, enb. In the old version of l298, there were 6 inputs. ena and enb
are set to HIGH. these can be set by hardware and hence are commented out.Depending on your driver, you can compile these commands or not. Use find
and replace to remove the comment out directive if you wish.
*/// int ena = 4;
int int1 = 5;
int int2 = 6;// int enb = 8;
int int3 =9;
int int4 = 10;int timex = 3000; //runs for 3 seconds
boolean run;void setup() {
//pinMode (ena,OUTPUT);
pinMode (int1,OUTPUT);
pinMode (int2,OUTPUT);//pinMode (enb,OUTPUT);
pinMode (int3,OUTPUT);
pinMode (int4,OUTPUT);run = true;
}void loop() {
if (run)
{
forward(); // sets the robot forward.
// check motors are spinning in same direction
delay(timex);
halt(); // stops the code running
run = false;
}
}void forward() // forward sub proceedure
{
//digitalWrite(ena,HIGH);
digitalWrite(int1,HIGH);
digitalWrite(int2,LOW);//digitalWrite(enb, HIGH);
digitalWrite(int3,HIGH);
digitalWrite(int4,LOW);}
void halt() // halt sub proceedure
{
//digitalWrite(ena,HIGH);
digitalWrite(int1,LOW);
digitalWrite(int2,LOW);//digitalWrite(enb,HIGH);
digitalWrite(int3,LOW);
digitalWrite(int4,LOW);}
- Topic 24
- Topic 25
Topic 25
Code alert : global variables
/*
This piece of code demonstrates the use of global variables. Global variables maintain their assigned value anywhere in the code. If it changes in a function, it retains its value.Some things to be concidered
1. arduino deals with functions not subprocedures
2. a global variable is any variable declared *outside* a function
3. a counter can increment to keep track of the number of times code runs.
4. a sentinal value can be used to a switch between code fragmentsmrweber
261115
*/int count = 0 ; // declared outside function
int sentinal = 1;void setup() {
// put your setup code here, to run once:
Serial.begin(9600);
}void loop() {
sg90();
Serial.print(count);
Serial.print(" ");
Serial.println(sentinal);
delay(2000);
}void sg90(){
count = count + 1; // increments here
if (count <= 10){
sentinal = 1; // sentinal
}
if (count > 10){
sentinal = -1;// sentinal changes
}
if (count > 20){ // all is reset
count = 0;
sentinal = 1;
}
} - Topic 26
- Topic 27
Topic 27
Code alert : back and forward
/*
This piece of code demonstrates the use of global variables. Global variables
maintain their assigned value anywhere in the code. If it changes in a function, it
retains its value.Some things to be concidered
1. arduino deals with functions not subprocedures
2. a global variable is any variable declared *outside* a function
3. a counter can increment to keep track of the number of times code runs.
4. a sentinal value can be used to a switch between code fragmentsmrweber
261115
*/int count = 45;
int sentinal =1;void setup() {
// put your setup code here, to run once:
Serial.begin(9600);
}void loop() {
sg90();
Serial.print(count);
Serial.print(" ");
Serial.println(sentinal);
delay(1000);
}void sg90(){
// here increases count
if ((sentinal == 1) && (count <=64)){
count = count + 1; // loop increments to 65
sentinal = 1; // sentinal
}
else {
sentinal = -1;
}
// changes over and decreases count
if ((sentinal == -1) && (count >= 46) ){
count = count - 1;
sentinal = -1; // sentinal
}
else {
sentinal = 1;
}
}
- Topic 28
Topic 28
Running a servo motor
Servo motors (or servos) are self-contained electric devices that rotate or push parts of a machine with great precision. Servos are found in many places: from toys to home electronics to cars and airplanes.
It consists of a motor coupled to a sensor for position feedback. It also requires a servo drive to complete the system. The drive uses the feedback sensor to precisely control the rotary position of the motor.
The motor is run by the red and black/brown wires and the feedback sensor is the orange.
Arduino tutorial /* Sweep
modified 8 Nov 2013
by Scott Fitzgerald
http://www.arduino.cc/en/Tutorial/Sweep
*/#include <Servo.h>
Servo myservo; // create servo object to control a servo
// twelve servo objects can be created on most boards
int servoPin = 3;int pos = 90; // variable to store the servo position
void setup() {
myservo.attach(servoPin); // attaches the servo pin to the servo object}
void loop() {
for (pos = 45; pos <= 135; pos += 1) { // goes from 0 degrees to 180 degrees
// in steps of 1 degree
myservo.write(pos); // tell servo to go to position in variable 'pos'
delay(15); // waits 15ms for the servo to reach the position
}
for (pos = 135; pos >= 45; pos -= 1) { // goes from 180 degrees to 0 degrees
myservo.write(pos); // tell servo to go to position in variable 'pos'
delay(15); // waits 15ms for the servo to reach the position
}
} - Topic 29
Topic 29
Code alert : turning a servo using counter and a sentinal values
/*
This uses the above code to turn a servo through
45 - 135 degreesthis can now be put in as part of a loop to run in conjuction
with a motorised robotmrweber
261115
*/#include <Servo.h>
Servo myservo;int count = 45;
int sentinal =1;void setup() {
// put your setup code here, to run once:
Serial.begin(9600);
myservo.attach(3);
}
void loop() {
sg90();
delay(50);
}
void sg90(){
// here increases count
if ((sentinal == 1) && (count <=134)){
count = count + 1; // loop increments to 65
sentinal = 1; // sentinal
myservo.write(count);
}
else {
sentinal = -1;
}
// changes over and decreases count
if ((sentinal == -1) && (count >= 46) ){
count = count - 1;
sentinal = -1; // sentinal
myservo.write(count);
}
else {
sentinal = 1;
}
} - Topic 30
Topic 30
Code alert : returning a value from a function
A function is defined as a sub procedure that returns only *one result*
The line int g = add(1,2); is an example.
/*
Passing variables
This code demonstrates an important concept.
x is declared at the start of the sketch and is available
all over the sketch.
w is only declared for use only in the function two
y is declared in the main loop as a functionmrweber
031215
*/int x; // global variable
boolean run; // so we can run the loop once onlyvoid setup() {
Serial.begin(9600);
run = true;
x =2; // assign a value
}void loop() {
while(run){
Serial.println(x); // x value passedinto the loop
one();
Serial.println(x); // x comes out
int y =two(20); // a value is passed here as a value
Serial.println(y); // print the value of the function
y =two(x); // a value is passed here as a varible
Serial.println(y); // print the value of the function
run = false; // halts the code
}
}
void one(){
x = 2*x; // read this as "x becomes"
Serial.println(x);
}
int two(int w){ // function is declared here as "int"
w = 3 * w; // w only is valid in this function
Serial.println(w); // note the value of w is local to two
return (w); // this function can be used more than once
}/*
return a value from a function by passing two values 1,2.another way to run code once is to run it in setup. the use of booleans is more formal.
mrweber
271115
*/
void setup() { // put your setup code here, to run once:
Serial.begin(9600);
int g = add(1,2); // define variable g as a function. 1,2 passed as values
Serial.println(g);
}int add(int x,int y){ // define a function that will add two numbers
int z;
z = x+y;
Serial.println(z);
return(z); // returns the sum of 1,2 as a value assigned to g
}
void loop() {
/* put your main code here, to run repeatedly
* only needs to run once in setup
*/
}