You are on page 1of 63

Learning Basic Mechatronics concepts g the Arduino Board and MATLAB using

Giampiero Campa Campa, PhD PhD, Technical Evangelist The MathWorks, 400 Continental Blvd, Suite 600-028, El Segundo, CA, 90245 giampiero campa@mathworks com giampiero.campa@mathworks.com
2009 The MathWorks, Inc.

Outline
A few challenges with Mechatronics projects Arduino Ad i I Introduction t d ti & M Motivation ti ti Analog and Digital IO Motor Control Arduino target and Useful Links

Sensing & Data Acquisition


Distance/Range Distance/Range, Position/Orientation Position/Orientation, Force/Pressure Force/Pressure, Touch, Orientation, Motion/Speed, Environment, Optical, Chemical, Flow, Voltage/Current, sensor selection is largely application related but also related to: Data acquisition system (Analog and Digital input)
Number of sensors Ranges A/D conversion issues as Resolution and Sampling Rate Signal Conditioning Delay/Bandwidth

Processing & Programming Platform


External Microcontroller/Microprocessor Board
Development-Prototyping Environment Low-Level Programming Language, Compiler/Assembler Connection to computer (or LCD) for visualization DAQ typically already there Stand Alone Issues, , power p requirements q

Computer
Connection C ti t to DAQ (USB (USB, PCI PCI, S Serial, i l Wi Wireless) l ) Programming-Analysis Environment OS / Drivers (Real Time ?) Embedded / Small Form Factor Computer
4

Acting (Digital & Analog Outputs, Outputs PWM)


Relays Motors
DC/Steppers/Servos Si Signal l Amplification A lifi ti Power Suppliers, Batteries Forward/Reverse, H-Bridges

Displays

Lots of (interrelated) choices


Driving Factors: Cost y of Use Easy Flexibility Non trivial process even for simple projects Some challenges are inherent to the multidisciplinary nat re of the field and its good for st nature students dents to str struggle ggle with them (e.g. sensors, actuators, power, design) Some are not ( (e.g. g debugging gg g C code, , drivers issues, , hardware limitations, unreadable manuals, high costs)
6

Outline
A few challenges with Mechatronics projects Arduino Ad i I Introduction t d ti & Motivation M ti ti Analog and Digital IO Motor Control Arduino target and Useful Links

Arduino
Arduino is an open-source microcontroller board, with an associated development environment.

Philosophy
The schematics and the software are released under the Creative Commons License Manufacturing and Distributing an official Arduino product is subject to a few restrictions (basically the authors need to be contacted) to make sure that:
Things work properly. The Th product d t fits fit i into t th the overall ll project. j t It is manufactured under reasonably fair labor conditions.

Some form of contribution might be traded in this case


9

Specifications (Arduino 2009)


ATmega328 g microcontroller 16 MHz, 32 KB FLASH, 2KB SRAM, 1K EEPROM 19 DIO pins (6 can be 8-bits 500Hz PWM outputs) 6 analog inputs (10 bits over 0-5V range, 15kSPS) 5V operating voltage, 40 mA DC Current per IO Pin I2C C( (TWI) )f fully supported and SPI S partially supported USB connection (FTDI chip converts USB to Serial) FTDI Drivers provide a virtual com port to the OS Power jack and optional 9V power supplier

10

Shields
Shields are boards to be mounted on top of the Arduino They extend its functionality to control different devices, acquire data, and so on Examples:
Motor/Stepper/Servo M t /St /S Shields Shi ld (Motor (M t Control) C t l) Multichannel Analog and Digital IO Shields Prototyping Shields Ethernet and Wireless communication Shields Wave Shields (Audio) GPS Logging and Accelerometer Shields Relay Control Shields
11

Outline
A few challenges with Mechatronics projects Arduino Ad i I Introduction t d ti & Motivation M ti ti Analog and Digital IO Motor Control Arduino target and Useful Links

12

What is Arduino good for ?


Projects requiring Analog and Digital IO Mechatronics Projects using Servo, DC or Stepper Motors Projects with volume/size and/or budget constraints P Projects j t requiring i i some amount t of f flexibility fl ibilit and d adaptability (i.e. changing code and functions on the fly)

13

What is Arduino good for ?


Basically any Mechatronics project requiring sensing and acting, provided that computational requirements are not too high (e.g. cant do image processing with it) Ideal for undergraduate/graduate Mechatronics Labs and Projects There is a very large community of people using it for all kind of projects, and a very lively forum where it is possible to get timely support
14

MathWorks Solutions
Arduino IO Package: Used to perform analog and digital input and output as well as motor control from the MATLAB command line

Arduino Target: Used to compile and download Simulink code directly to th A the Arduino d i b board d

15

Arduino IO : Concept

16

Using MATLAB vs vs. IDE Environment


MATLAB is more interactive, results from Digital/Analog I/O instructions can be seen immediately without needing to program compile upload execute each time time. It is a good idea even just for algorithm prototyping MATLAB code is generally more compact and easier to understand than C (higher-abstraction data types, vectorization no need for initialization/allocation, vectorization, initialization/allocation less lines of code) which means: ) MATLAB scales better with p project j complexity p y a) b) People get the job done faster in MATLAB
17

Using MATLAB vs vs. IDE Environment


For wider-breadth p projects j ( (that might g include data analysis, signal processing, calculations, simulation, statistics, control design ) MATLAB is better suited Engineering Departments typically need to introduce MATLAB during the first years, so this package will allow professors to keep the same environment and students to practice more MATLAB People might already be more familiar with MATLAB than with C, both in industry and university
18

Outline
A few challenges with Mechatronics projects Arduino Ad i I Introduction t d ti & M Motivation ti ti Analog and Digital IO Motor Control Arduino target and Useful Links

19

Analog & Digital IO: Workflow

Plug board Connect

USE: Assign Pin Mode Digital Input Digital Output Analog Input A l O Analog Output t t

Disconnect Unplug p g

20

Connect
Use the command a=arduino(port), with the right COM port as a string input argument, to connect MATLAB with the board and create an arduino object in the workspace: >> a=arduino(COM5);

21

Assign Pin Mode (input/output)


Use the command a.pinMode(pin,str) to get or set the mode of a specified pin: Examples: >> a.pinMode(11,'output') >> a.pinMode(10,'input') >> val=a.pinMode(10) >> a.pinMode(5) >> a.pinMode;

22

Digital Read (digital input)


Use the command a.digitalRead(pin) to read the digital status of a pin: Examples: >> val=a.digitalRead(4) This returns the value (0 or 1) of the digital pin number 4

23

Digital Read Example

>> a.digitalRead(4) ans =

Command executed while button is released Command executed while b tt is button i pressed d

MATLAB Command Window

0 >> a.digitalRead (4) ans = 1 24

Digital Write (digital output)


Use the command a.digitalWrite(pin,val) with the pin as first argument and the value (0 or 1) as second argument: Examples: a.digitalWrite(13,1); % sets pin #13 high a.digitalWrite(13,0); % sets pin #13 low

25

Digital Write Example

MATLAB Command Window


>> a.digitalWrite(9,1) >> a.digitalWrite(9,0) di it lW it (9 0)

Led Off

Led On

26

Analog Read (analog input)


Use the command val=a.analogRead(pin) with the pin as an integer argument: Example: val=a.analogRead(0); g ( ); % reads analog g p pin # 0 The returned argument ranges from 0 to 1023 Note that 6 analog input pins (0 to 5) coincide with the di it l pins digital i 14 t to 19 and d are l located t d on th the b bottom tt right i ht corner of the board
27

Analog Read Example

MATLAB Command Window

>> a.analogRead(3) ans = 285 >> a.analogRead(3) ans = 855

28

Analog Write (analog output)


Use the command a.analogWrite(pin,val) with the pin as first argument and the value (0 to 255) as second argument: Examples: a.analogWrite(11,90); % sets pin #11 to 90 a.analogWrite(3,10); % sets pin #3 to 10

29

Analog Write Example

MATLAB Command Window


>> a.analogWrite(9,10) >> a.analogWrite(9,50) l W it (9 50)

Led On (4%)

Led On (20%)

30

Disconnect
Use the command delete(a) to disconnect the MATLAB session from the Arduino board: >> delete(a); This renders the serial port available for other sessions or the IDE environment

31

Example : The blink challenge project


This challenge is described in the last part of the Ladyada Arduino tutorial, http://www.ladyada.net/learn/arduino/ and it consists in designing a circuit with 5 LEDs and 4 modes (user switches mode by pushing a button): 1. All LEDs Off 2. All LEDs On 3 LEDs 3. LED bli blinking ki simultaneously i lt l with ith variable i bl f frequency regulated by a potentiometer 4 LEDs blinking one after the other (wave like) with 4. variable speed regulated by a potentiometer
32

Schematics

33

MATLAB
INPUTS

Information Flow
OUTPUTS

USER
34

MATLAB Code
% initialize pins disp('Initializing p( g Pins ...'); ) % sets digital input pins a.pinMode(2, 'INPUT'); a.pinMode(3, 'INPUT'); a.pinMode(4, 'INPUT'); a.pinMode(7, 'INPUT'); a.pinMode(8, 'INPUT'); % sets digital and analog (pwm) output pins a.pinMode(5, 'OUTPUT'); % pwm available here a pinMode(6 'OUTPUT'); a.pinMode(6, OUTPUT ); % pwm available here a.pinMode(9, 'OUTPUT'); % pwm available here a.pinMode(10,'OUTPUT'); % pwm available here a.pinMode(11,'OUTPUT'); % pwm available here a.pinMode(12,'OUTPUT'); a.pinMode(13,'OUTPUT'); % button pin and analog pin bPin=2;aPin=2; % initialize state state=0; t t 0 % get previous state prev=a.digitalRead(bPin); % start loop disp('Starting main loop, push button to change state ...'); % loop for 1 minute tic while toc/60 < 1 % read analog input ain=a.analogRead(aPin); v=100*ain/1024; ; % read current button value % note that button has to be kept pressed a few seconds to make sure % the program reaches this point and changes the current button value curr=a.digitalRead(bPin); % button is being released, change state % delay corresponds to the "on" time of each led in state 3 (wave) if (curr==1 && prev==0), state=mod(state+1,4); disp(['state disp([ state = ' num2str(state) ', delay = ' num2str(v/200)]); end

35

MATLAB Code
% toggle state all on or off if (state<2), (state<2) for i=9:13, a.digitalWrite(i,state); end end % wave if (state==3), f i=4:8, for i 48 a.digitalWrite(9+mod(i,5),0); a.digitalWrite(9+mod(i+1,5),1); pause(v/200); end a.digitalWrite(13,0); end

% blink all leds with variable delay if (state==2), for j=0:1, % analog output pins f i=9:11, for i 9 11 a.analogWrite(i,20*(i-8)*j); end % digital output only pins for i=12:13, a digitalWrite(i j); a.digitalWrite(i,j); end pause((15*v*(1-j)+4*v*j)/1000); end end

% update state prev=curr; end

% turn everything off for i=9:13, a.digitalWrite(i,0); g ( ) end

36

Prototyping Shield
The schematics was implemented using the prototyping shield:

This shield allows for an easy prototyping of projects based on the Arduino board
37

Implementation

Pot to regulate on/off LEDs delay

Button to change mode

Arduino Board underneath

38

Outline
A few challenges with Mechatronics projects Arduino Ad i I Introduction t d ti & M Motivation ti ti Analog and Digital IO Motor Control Arduino target and Useful Links

39

Motor Shield
Servo Ports #1&2

Motor Ports #1&2 Stepper Port #1

Motor Ports #3&4 Stepper pp Port #2

External Power Connector

Jumper on == same power source for both Arduino and motor shield

Arduino Board underneath


40

Motor Shield characteristics


2 connections for 5V 'hobby' hobby servos connected to the Arduino's high-resolution dedicated timer Up to 4 bi-directional DC motors with individual 8-bit speed selection Up to 2 stepper motors (unipolar or bipolar) with single coil, double coil, interleaved or micro-stepping. 4 H-Bridges: L293D chipset provides 0.6A per bridge (1 2A peak) (1.2A k) with ith th thermal l shutdown h td protection, t ti 4 4.5V 5V t to 36V
41

Servo motors Workflow

Plug Board Connect Plug Servo

USE: Servo Attach Servo Status Servo Write Servo Read S Servo D t h Detach

Unplug Servo Disconnect U l B Unplug Board d

42

Servo Status (attached/detached)


Use the command val=a.servoStatus(num) to get the status of a servo, which can be either: attached tt h d (ready ( d for f read d or write) it ) detached (pin 9 or 10 can be otherwise used) Examples: val=a.servoStatus(1); a.servoStatus(2); a.servoStatus;

43

Servo Attach
Use the command a.servoAttach(num) to attach a servo to the corresponding pwm pin (servo #1 uses pin #10 servo #2 uses pin #9) #10, #9). Examples: a.servoAttach(1); % attach servo #1 a.servoAttach(2); % attach servo #2

44

Servo Read
Use the command val=a.servoRead(num) to read the angle from a servo. The argument is the number of the servo. servo The returned value is the angle in degrees, yp y from 0 to 180. typically

Examples: val=a.servoRead(1); % read angle servo #1 val=a.servoRead(2); val a.servoRead(2); % read angle servo #2
45

Servo Write
Use the command a.servoWrite(num,val) to rotate a servo of a given angle. The Th first fi t argument t is i the th number b of f the th servo, the th second d is the angle.

Examples: a.servoWrite(1,45); % rotates 45 servo #1

46

Servo Detach
Use the command a.servoDetach(num) to detach a servo from the corresponding pwm pin. Examples: a.servoDetach(1); ( ); % detach servo # #1 a.servoDetach(2); % detach servo #2

47

Servo Example
MATLAB Command Wi d Window:
>> a.servoAttach(2) >> a a.servoWrite(2,5) servoWrite(2 5) >> a.servoWrite(2,180) >> a.servoRead(2) ans =

Power Jumper on (suggested)

External Power: 6V Lantern Battery

Servo #2

180

48

DC and Stepper motors Workflow

Plug Board Connect Wire Motor

USE:

Set S t Speed S d Run (or Step)

Unwire Disconnect U l Unplug

49

DC Motor Speed
Use the command val=a.motorSpeed(num,val); p , to get or set the speed of a DC motor. The first argument, num, is the number of the motor (1 to 4) the th second d argument ti is th the speed d (0 t to 255) Examples: a.motorSpeed(4,200); val=a.motorSpeed(1); a.motorSpeed(3); t S d(3) a.motorSpeed; Note: nothing moves unless we issue a run command
50

DC Motor Run
Use the command a.motorRun(num,str); a motorRun(num str); to run a given DC motor. The first argument, num, is the number of the motor (1 to 4) the second argument is a string that can be either forward, backward, release Examples: a.motorRun(1,'forward'); a.motorRun(3,'backward'); a.motorRun(1,'release');

51

DC Motor: Example
MATLAB Command Window:
>> a.motorSpeed(3,100) t S d(3 100) >> a.motorRun(3,forward)

(running)

Motor #3

52

Stepper Motor Speed


Use the command val=a.stepperSpeed(num,val); pp p , to get or set the speed of a stepper motor. The first argument, num, is the number of the motor (1 to 4) the th second d argument t is i the th speed d in i RPM (0 t to 255) Examples: a.stepperSpeed(2,50) val=a.stepperSpeed(1); a.stepperSpeed(3); t S d(3) a.stepperSpeed; Again, nothing moves unless we issue a step command ...
53

Stepper Motor Step


Use the command a.stepperStep(num,str,sty,steps); to advance a stepper motor of a certain number of steps. Where Wh num is i th the number b of f th the stepper t (1 or 2) 2), str can be either forward, backward, release, sty is the style g , double, , interleave, , of motion and can be single, microstep, steps is the number of steps (0 to 255) Examples: a.stepperStep(1,'forward,interleave,50); pp p( , , , ); a.stepperStep(1,backward,double,200); a.stepperStep(1,'release');
54

Stepper Motor: Example


MATLAB Command Window:
>> a.stepperSpeed(1,50) t S d(1 50) >> a.stepperStep(1,'backward','microstep',100)

Arduino Target, Links, Conclusion

Stepper #1

Coil #1

Coil #2

55

Outline
A few challenges with Mechatronics projects Arduino Ad i I Introduction t d ti & M Motivation ti ti Analog and Digital IO Motor Control Arduino target and Useful Links

56

Arduino Target
Arduino IO: Used to perform analog and digital input and output from the MATLAB command line Arduino Target: Used to compile and download Simulink code directly to the Arduino board

57

Arduino Target Library

58

Arduino Examples

59

Useful Links: Buying an Arduino


An extensive list of sites where you can buy an Arduino is here: http://www arduino cc/en/Main/Buy http://www.arduino.cc/en/Main/Buy In the US, Adafruit industries http://www.adafruit.com/ provides a starter pack that includes pretty much everything that you need to get started with the board board.

60

Useful Links: Buying Motors


RC Servos from Pololu: http://www.pololu.com/catalog/category/23 DC Motors from Pololu: http://www.pololu.com/catalog/category/51 Jameco for Stepper Motors and pretty much everything: http://www.jameco.com/ List of Hobbyist and Surplus Stores: htt // http://www.ladyada.net/library/procure/hobbyist.html l d d t/lib / /h bb i t ht l
61

Useful Links: Getting Started Guides


Official Arduino web site: http://arduino.cc/en/ Knowledge base: http://www.freeduino.org/ Official Getting Started guide: http://arduino.cc/en/Guide/HomePage The LadyAda Tutorial: http://www.ladyada.net/learn/arduino/ MATLAB ArduinoIO package, send me an email here: giampiero.campa@mathworks.com Simulink Si li k A Arduino d i T Target: t search hf for i in MATLAB Central C t l (or google for Arduino Target)
62

Conclusion
Arduino is an inexpensive open-source microcontroller board, well suited for a wide range of projects Arduino + ArduinoIO package + MATLAB = inexpensive and interactive Analog and Digital IO from the MATLAB command line Arduino + Motor Shield + ArduinoIO package + MATLAB = inexpensive and interactive Motor Control from the MATLAB command line
63

You might also like