Basics before Migtrating to Arduino Who is this for? Written by Storming Robots Last update: Oct 11 th, 2013 This document is meant for preparing students who have already good amount of programming knowledge, including simple data structure, file I/O, binary/hex, and most importantly must be self-motivated learners. This is not meant to focus on learning electronic, but prepare competition teams for migrating to Arduino Platform. This includes topics that you should know before you start to work on Arduino robot. Table of Contents 1- A few Basics in electronics... 3 Voltage... 3 Current... 3 Resistors... 3 How to measure the resistance:... 4 Voltage Divider (VDR)... 5 Basic Symbols... 6 2- Basic Digital / Analog Input... 6 Exercises:... 6 3- Motor Interface... 7 Pulse Width Modulation(PWM) and AnalogWrite... 8 Pulse Width Modulation(PWM)... 8 Exercises... 11 DC motor interface - PWM... 11 Simple Servo motor inteface... 13 4- With Ping range... 14 Exercises:... 14 Reference... 14 5- I2C device Communication... 15 With I2C Compass... 15 With I2C Mux... 15 With Thermal... 15 6- Inter-processors serial communication... 18 Sample: Interface via Software Serial between 2 controllers... 18 1
7- Other Basics you should know... 19 debouncing... 19 Software debouncing:... 19 About Fritzing Electronic Design Automation Software... 19 8- Interface with NXT devices... 20 Know the Cable... 20 Sample I2C Schematic... 20 NXT via I2C a Uno/Nano, etc. sensors / motors... 20 9- What NOT to do?... 21 Exceeding the voltage allowed... 21 Shorting Circuit... 22 Missing Voltage Regulator... 22 10- Misc... 23 What is a Capacitor?... 23 What is an inductor?... 23 What is an transistor?... 24 2
Resistor 1- A few Basics in electronics Summary of Voltage / Current / Resistance Voltage : the force of electricity; measured in volts (V). Current : amount of flow of electrons; measured in amperes (A). Resistance (from resistor) : a material's opposition to the flow of electric current; measured in ohms (Ω).The resistance increases as the diameter of the wire decreases. Ohm's Law can be written as R = V/I. Voltage Name Math Symbol Unit Unit Symbol voltage V or E volt V current I ampere (amp) A resistance R ohm Ω - Electrical force caused by the flow of electrons. - Something cause the push of electrons, that causes energy,that causes current (see below) - Also called potential difference (but rarely used) - E.g. in batteries, chemical action within the battery causes the push Current - The flow of charge through wire, like the flow of water through pipes. - Voltage is the Cause, Current is the Effect - current will flow if the circuit is complete Resistors - hindrance to the flow of charge - the frictional affects between water and the pipe surfaces - what affects resistor: o wire length resistance o Temperature resistance o Width resistance o Conducting ability of a material resistance Now, put all three together: Voltage (Volt) Current (Amp) 3
How to measure the resistance: There are 2 configurations Series and Parallel: (again, think about them like water flow thru a pipe) In Series: R total = R 1 + R 2 + + R n V = I * R total Current remains the same at each Resistor even when each resister measures different. The amount of current (think about amount of water) going through each resistor (think about various sizes or same size of pipes) will remain the same. I R1 == I R2 == == I Rn even if all R n measure different. In Parallel: R total = Current will be different at various Resistor if these resistors measure different. The amount of current going through each resistor may be the different. I R1!= I R2!=!= I Rn if all R n measure different ohms. 4
Voltage Divider (VDR) There are plenty of learning resources online. But I personally thought this video is very easy to understand and fun to watch - http://www.youtube.com/watch?v=xxlkfazrhbm) VDR is circuit configuration, NOT a device. VDR determines the voltage drop across a resistance within a series circuit. Voltage divider is also known as a potential divider. V V V I R I R Almost all analog sensors have voltage divider. The feedback value (from Vout) reflects the variable voltage as a result of a voltage divider with at least one variable resistor. Provided: Vin = 5V, R1=2k, R2 = 3k (we know V = I * R) I = Vin / (R1+R2) (amp) I = 5v/(5000ohmz) = 0.001 amp = 1 milliamp V R2 = I * R2 = 1 ma * 3000 ohmz = 3 V V R1 = I * R1 = 1 ma * 2000 ohmz = 2 V so = Vout = Vin * Suggested steps for wiring: R1 directly connected to Vin R1 on the same bus with R2 R2 directly connected to Gnd Vout in-between R1 and R2 Vout = Vin ( ) Vout = Vin ( ) Reference: http://www.afrotechmods.com/ 5
Basic Symbols 2- Basic Digital / Analog Input With photocell With potentiometer Exercises: - Blink program blink onboard LED (pin 13) with digitalwrite. - Modified Blink program - Use Fritzing diagram to hook up LED to pin 9. - Dim program - Dim and brighten LED on pin 9 using analogwrite(). - Hello World with Serial objects. Show them how to view output with Serial monitor. - Potentiometer Reading in the value of a potentiometer with analogread(). Display value using Serial.println(). - Push button Hook up a push button and display message when button is pushed. - Line Sensor module reader Read in the value from the line sensor module. - Make your own Multimeter. Create a voltage divider with two resistors. Read the "Vout" from your voltage divider into an Analog port on the Arduino. Read the value in and convert it to a voltage (analogread produces values from 0 to 1023. 0 is 0 volts, 1023 is 5 volts). Optional: Hook up an RGB LED and write a program to change the LED color. 6
3- Motor Interface H-Bridge: - A circuit, an H-like configuration, used for controlling motors. - This is implemented onto a motor controller / motor shield. - Usually one H-bridge for each DC motor. Some other kinds may need two. - A single controller may have multiple H-Bridges. Quick review: Diagram from modularcircuits.com Q1..Q4 : switches element transistors D1..D4 : diode Q1+Q4== on == motor A on Q2+Q3== on == motor B on Damage!!!! There are 9 valid configuration: (0==open, 1==closed) Q1 Q2 Q3 Q4 0 0 0 0 0 0 0 1 0 0 1 0 0 1 0 0 1 0 0 0 1 0 0 1 1 0 1 0 1 1 0 0 0 1 0 1 0 1 1 0 0 0 1 1 7
Pulse Width Modulation(PWM) and AnalogWrite - Arduino circuitry cannot send variable (analog) voltage. - AnalogWrite sends on/off pulses. The voltage ends up being the average voltage. - use oscilloscope to see the pulses. (if you get one!) Pulse Width Modulation(PWM) 0% Duty Cycle analogywrite(0) 25% Duty Cycle analogwrite(63) ; // out of 255 50% Duty Cycle analogwrite(127) ; // out of 255 75% Duty Cycle analogywrite(192) 100% Duty Cycle analogywrite(255) Things to Remember: analogwrite(pin,value) pin is the pine to write out to, value is a number between 0 255. 0 sends out 0 volts and 255 sends out the max voltage of 5 volts. A number in between would send out a fraction of the voltage such as voltage. As you recall we used the analogwrite() function to send a variable voltage to both dim an LED and to control the amount of power going to our motor. But that isn't exactly what is happening. The chip on the Arduino Uno, the ATmel 328P, is incapable of generating a true variable voltage. Like most digital devices, it can only create a HIGH signal at 5 volts or a LOW signal at 0 volts. Example: a) Use analogwrite to dim The Arduino's chip is able to mimic voltages in between 0 and 5 volts by using a series of timed pulses that will average out to the desired voltage. analogwrite (127) == half of maximum brightness. The Arduino will then send a series of timed pulses where the HIGH signal is sent for half the time (50%) and a LOW signal is send for the other half of the time (50%). By doing this, the Arduino creates an "average voltage" on the wire of 2.5 volts. Half the time the LED is powered at 5 volts and the other half it is turned off. 8
Here is a screen shot from an oscilloscope hooked up to pin 10 and we called analogwrite(10,127): The oscilloscope shows various statistics about these pulses. Look at the values Vmax, Vmin and Vavg. Vmax is the maximum voltage at 5.04 volts. Vmin is the lowest voltage at -80 mvolts (essentially 0 volts). You can see that Vavg is 2.5 volts which is what we want. The last two statistics that are important are the +Duty and Duty (together they describe what is called the duty cycle). +Duty is the percent of the time the voltage is at its highest and Duty is the percent where it is at its lowest.+duty is 51.0% and Duty is 49.0% ( these end up being roughly 50% each). So as stated earlier our signal is high half of the time and low the other half of the time. So what would the signal look like if we passed different values to analogwrite. Let s say we wanted to dim our LED to 25% so we would pass a value or 255 * 0.25 which rounds to 64. We should see an average 1.25 volts (5 volts * 0.25). So calling analogwrite(10,64) our oscilloscope shows: As you can see Vavg is 1.25 volts. Also notice our +Duty stat is 25.5% and our Duty state is 74.5%. So on average our pin is switched to HIGH for 25.5% of the time and LOW for the other 74.5% (which is very close to 25% off and 75% on). 9
Say we want to dim to 75% (255 * 0.75 = 191.25). So we call analogwrite(10,191) and get And analogwrite(10,255) which is the max value we obviously get: Ok this might be neat but why is this important to know? AnalogWrite is used (indirectly) to power motors. Motors are physical devices that may or may not respond well with the pulsing of voltages. In our class the motors we use will probably not have this problem for they are small and the load on them is negligible. Also our motor shield will utilize capacitors to smooth out the pulses (this is what capacitors do). However we hope you continue to build robots going forward and understanding PWM can help troubleshoot some non-obvious problems. 10
Exercises DC motor interface - PWM Mount an Arduino duel channel motor shield and get it to run.. /************************************************************* Arduino Dual channel Motor Shield for 2 DC Motors Demo by Storming Robots *************************************************************/ const int RmADir = 12; const int RmAbrake = 9; const int RmApwm = 3; const int RmCurrent = A0; const int LmBDir = 13; const int LmBbrake = 8; const int LmBpwm = 11; const int LmCurrent = A1; enum { FD=1, BD, LT, RT, BRK, CST, DIRLAST DIR ; char sdir[dirlast][20] = {"forward", "backward", "LeftTurn", "RightTurn", "Brake", "Coast"; void setup() { //Setup Channel A pinmode(rmadir, OUTPUT); //Initiates Motor Channel A pin pinmode(rmabrake, OUTPUT); //Initiates Brake Channel B pin //Setup Channel B pinmode(lmbdir, OUTPUT); //Initiates Motor Channel B pin pinmode(lmbbrake, OUTPUT); //Initiates Brake Channel B pin Serial.begin(9600); void loop(){ 11 gostraight(fd); delay(2000); gostraight(bd); delay(2000); goturn(lt); delay(2000); gostraight(rt); delay(2000); tostop(brk); delay(20000); //============================================= // gostraight(...) : enable forward or backward // dir : FD = forward // dir : BD = backward void gostraight(int dir) { Serial.println(sDir[dir]); if (dir == FD) { //Motor A forward @ full speed digitalwrite(rmadir, HIGH); //Establishes forward direction of Channel A digitalwrite(rmabrake, LOW); //Disengage the Brake for Channel A analogwrite(rmapwm, 255); //Spins the motor on Channel A at full speed //Motor B forward @ full speed
digitalwrite(lmbdir, HIGH); digitalwrite(lmbbrake, LOW); analogwrite(lmbpwm, 255); else { //Motor A forward @ full speed digitalwrite(rmadir, LOW); digitalwrite(rmabrake, LOW); analogwrite(rmapwm, 255); //Establishes backward direction of Channel A //Motor B backward @ full speed digitalwrite(lmbdir, LOW); digitalwrite(lmbbrake, LOW); analogwrite(lmbpwm, 255); return; //============================================= // goturn(...) : Enable pivot turn // dir : LT = left pivot turn // dir : RT = right pivot turn void goturn(int dir) { Serial.println(sDir[dir]); 12 if (dir == RT) { digitalwrite(rmadir, LOW); digitalwrite(rmabrake, LOW); analogwrite(rmapwm, 255); digitalwrite(lmbdir, HIGH); digitalwrite(lmbbrake, LOW); analogwrite(lmbpwm, 255); else { digitalwrite(rmadir, HIGH); digitalwrite(rmabrake, LOW); analogwrite(rmapwm, 255); digitalwrite(lmbdir, LOW); digitalwrite(lmbbrake, LOW); analogwrite(lmbpwm, 255); return; //============================================= // tostop(...) : brake or coast to stop // type : BRK = brake to stop // type : CST = coast to stop //============================================= void tostop(int type) { if (type==brk) { digitalwrite(rmabrake, HIGH); //Engage the Brake for Channel A digitalwrite(lmbbrake, HIGH); //Engage the Brake for Channel B else { digitalwrite(rmabrake, LOW); digitalwrite(lmbbrake, LOW);
Simple Servo motor inteface To be updated!!! Exercise: Servo control - Intro to Servos and the Servo library. Servo Control 2 - Use a potentiometer to control your servo. 13
4- With Ping range How does a Ping sensor works? How do you hook it up? How do you generate a pulse? Review Appendix D with instructor Look at Arduino pulsein() function does some of work for you http://arduino.cc/en/reference/pulsein Things needed to know: o Speed of Sound o How long Sound takes to travel 1 cm o Note: Remember sound is traveling twice as far (from robot and reflected back from object) Exercises: Wall Avoidance Follow line until you come to an L-shaped wall. Use servo to look both ways. One way will have another wall, the other will not. Turn to face the way that has no wall. Wall Tracing - Get your line tracing robot to perform "wall tracing" when it sees a wall. Follow the wall until you see the line again. Reference http://arduino.cc/en/reference/libraries 14
5- I2C device Communication Play with the Wire samples from the Sketch software first. Read the Wire Library Reference. With I2C Compass LSM303DLHC - digital 3-axis accelerometer and 3-axis magnetometer - With tilt compensation. With I2C Mux With Thermal Sample code. (to be updated) 15
16
With I2C Thermal With I2C Mux 17
6- Inter-processors serial communication Connect two controllers via hardware serial - Simply use Serial, UART or USART - http://arduino.cc/en/reference/serial - Some controllers have multiple serial lines, such as Mega which has 4, Serial 0, 1, 2, 3. Sample: Interface via Software Serial between 2 controllers Another serial device RX, Tx to D4, Secondary Uno RX, Tx to D6, Master Uno // this is a simple sample for the secondary Uno; // connect its pin D3 & 4 to another serial device s TX and RX ports // it also connects to master Uno via RX, TX #include <SoftwareSerial.h> const int spd = 9600; SoftwareSerial myserial(3,4); // RX, TX void setup() { Serial.begin(spd); Serial.println("Send "); myserial.begin(spd); myserial.println("recv "); void loop() { char ch; if (myserial.available() ) // data from another serial device { ch = myserial.read(); Serial.print (ch); // send data to another controller ** a more pragmatic set up Compass 1 Compass 2 *** Reference: RX, Tx to D4, D3 RX, Tx to D6, D5 Secondary Uno as the module which will collect and process sensors data such as RX, Tx to other pins Master Uno SerialControl - Remote control other Arduinos over a serial connection XBee - for communicating with XBees in API mode 18
7- Other Basics you should know debouncing Debouncing is a provision in electronic/electrical devices having switches to prevent the spikes in output. Details: When we press any switch manually and release it, it bounces due to inherent elasticity, this causes multiple make and break of electrical contact. If the response time is very large then it won't create any problem, but if it is small then we get multiple responses for a single keypress. Software debouncing: int ledpin = 13; int inputpin = 2; int val = 0; int bouncecheck = 0; void setup() { pinmode(ledpin, OUTPUT); pinmode(inputpin, INPUT); // choose the pin for the LED // choose the input pin (for a pushbutton) // variable for reading the pin status // variable for debouncing // declare LED as output // declare pushbutton as input void loop(){ val = digitalread(inputpin); delay(10); bouncecheck = digitalread(inputpin); if(val == bouncecheck){ if (val == HIGH) { digitalwrite(ledpin, LOW); else { digitalwrite(ledpin, HIGH); //read input value //wait 10ms //check again //if val is the same then not a bounce //check if the input is HIGH //turn LED OFF //turn LED ON Reference: http://playground.arduino.cc/code/debounce http://arduino.cc/en/tutorial/debounce About Fritzing Electronic Design Automation Software Fritzing is an Electronic Design Automation (EDA) software which allows users to design and document their circuits particularly with Arduino and other electronic-based prototypes. This allows you to create printed circuit board (PCB) layouts for turning it into a robust PCB yourself or by help of a manufacturer. Download here: http://fritzing.org/download/. 19
8- Interface with NXT devices Know the Cable blue = data yellow = clock green = power black = gnd red = gnd white = 3.3V blue = digital I/O yellow = digital I/O green = 4.3 Volt black = gnd red = gnd white = analog input NXT cable white Black Red Green Yellow Blue Motor1 Motor2 GND 4.3 Volts Tach01 Tach02 Sample I2C Schematic NXT ultrasonic sensor yes it is an i2c device. NXT via I2C a Uno/Nano, etc. sensors / motors. 20
9- What NOT to do? Exceeding the voltage allowed 21
Shorting Circuit Short circuit refers to a circuit that does not have a electrical impedance (resistance). For example, if the lamp is connected to the circuit but a direct connection is present between the battery's negative terminal and its positive terminal, too Missing Voltage Regulator When you decide to create your own power source, you do need to look in voltage regulator. More images will be posted here. 22
10- Misc Since this is not meant to be an electronic lesson plan, there are many fundamentals in electronic is not covered. For example, we most likely will not need to build our own controller board, or our own power supply, or a really sophisticated intelligent sensor module. Instead, we buy a good one. However, I think it will be good to simply mention the terms and if you have time and interest, you can explore on your own if you are a die-hard electonic individual. What is a Capacitor? Is a deviec that stores energy in the form of static charge Resist sudden change in voltage What is an inductor? Inductor : - is a device that temporarily stores energy in the form of magnetic field usually is a coil of wire. When current flows through a coil of wire, it creates magnetic energy. - When current stops flowing, o the magnetic field starts to collapse o magnetic energy turns back into electrical energy - resists sudden change in current Diagram from http://www.afrotechmods.com/ With 1KHz With 1KhZ after adding an inductor With 10 KHz after adding an inductor 23
With 100KHz inductor starts to average out the current over time. What is an transistor? 24