Fan Project Complete - Web.cecs.pdx.edu

Transcription

Desktop Fan Projectfor theArduino Inventors KitEAS 199A, Fall 2010Gerald RecktenwaldPortland State Universitygerry@me.pdx.eduGoal Build a desktop fan from parts in the Arduino Inventor’s Kit Work in teams of two Learn new skills Controlling a servo and DC motorMake a 2D drawing with SolidworksSend drawings to Laser cutterSoldering Due in two weeks In-class demonstration of your working fanDesktop fan: EAS 199A2Tasks Measure servo and DC motors prepare for structural designlearn how to use your calipers Sketch design of supportstructure on paper Create Solidworks model of thebase and DC motor support Cut acrylic parts Re-solder the DC motor leads Assemble the system Write Arduino program tocontrol servo and DC motorDesktop fan: EAS 199A3

Propellor and motors from Inventor’s KitDesktop fan: EAS 199A4Acrylic parts after cutting and bendingDesktop fan: EAS 199A5One idea for a base designDesktop fan: EAS 199A6

Alternative base designsDesktop fan: EAS 199A7Servo motor partsDesktop fan: EAS 199A8Fan Project: First Steps1.2.3.4.5.Make a hand sketch of the structural partsMeasure the servo and mounting screwsUse measurements to add dimensions to the sketchRedraw the sketch as a 2D “flat” drawing in SolidworksEmail the drawing to the instructora. Laser cutter works on thin sheets in 2Db. Use the acrylic bender after parts are cutWatch this video to see the laser cutter and acrylic benderin action:http://www.youtube.com/watch?v DJA8EmBUfLoDesktop fan: EAS 199A9

Soldering Leads to theDC MotorDesktop fan projectEAS 199A, Fall 2010OverviewThe DC motor that comes with the Arduino Inventor’sKit has short and delicate leads. We need to replace theleads with more robust wiring and solderedconnectionsDesktop fan: EAS 199A11Temperature-controlled soldering iron and fluxDesktop fan: EAS 199A12

Soldering work surface with vise*!!"!"# %%&'"()*' ,)- ."())!!"0 %%)1232)!"# !!"1/"234567849"&!!"%!!" !!"#!!"!"' "( ##") #") #"* #!"* %!", #,"#! ,"/ (')Desktop fan: EAS 199A13Helping HandsDesktop fan: EAS 199A14Procedure1.2.3.4.5.Cut a length of wireStrip and tin the ends of the wireMake note of polarity and remove leads from DC motorInsert tinned wire through tabs and bend into positionSecure new leads by soldering to motor tabsDesktop fan: EAS 199A15

Cut new lead wiresDesktop fan: EAS 199A16Strip the leadsDesktop fan: EAS 199A17Tin the leadsDesktop fan: EAS 199A18

Remove the old leads and note the polarity*!!"!"# %%&'"()*' ,)- ."())!!"0 %%)1232)!"# !!"1/"234567849"&!!"%!!" !!"#!!"!"' "( ##") #") #"* #!"* %!", #,"#! ,"/ (')Desktop fan: EAS 199A19Motor supported. Extension wires in placeDesktop fan: EAS 199A20Bend the tinned wires around the supportsDesktop fan: EAS 199A21

Secure the leads with solderDesktop fan: EAS 199A22Basic DC Motor CircuitsDesktop fan projectEAS 199A, Fall 2010Simplest DC Motor CircuitsConnect the motor to a DC power supply 5V 5VISwitch closedDesktop fan: EAS 199A24

Current continues after switch is openedOpening the switch does not immediately stop currentin the motor windings.Desktop fan: EAS 199A25Reverse currentCharge build-up can cause damage 5VICurrent surge through– the voltage supply Arc acrossthe switchDesktop fan: EAS 199A26Motor ModelSimple model of a DC motor: Windings have inductance and resistanceInductor causes a storage of electrical charge in the windingsWe need to provide a way to safely dissipate the charge stored inthe motor windings 5V 5VIDesktop fan: EAS 199A27

Flyback DiodeA flyback diode allows the stored charge to dissipatesafelyDesktop fan: EAS 199A28Replace the Switch with a TransistorA transistor allows on/off control to be automated 5VmotorPin330ΩDesktop fan: EAS 199A29Control the DC motor with PWM Output//////Function:PWM outputPWM output to control a DC motorintmotor pin 5;void setup(){pinMode(motor pin,}// must be a PWM digital outputOUTPUT)void loop(){int motor speed 200;// must be 0 and 255analogWrite( motor pin, motor speed);}Desktop fan: EAS 199A30

Arduino Programming:PWM Control ofDC motor speedDesktop fan projectEAS 199A, Fall 2010OverviewPart I Circuits and code to control the speed of a small DC motor.Use potentiometer for dynamic user input.Use PWM output from an Arduino to control a transistor.Transistor acts as variable voltage switch for the DC motor.Part II Consolidate code into reusable functions.One function maps 10-bit analog input to 8-bit PWM output.Another function controls the motor speed.Functions developed here are useful for more complex controltasks, e.g. the desktop fan project.Desktop fan: EAS 199A32Part 1: Control motor speed with a potIncrease complexity gradually. Test at each stage.1. Use a potentiometer to generate a voltage signala. Read voltage with analog inputb. Print voltage to serial monitor to verify2. Convert 10-bit voltage scale to 8-bit PWM scalea. Voltage input is in the range 0 to 1023b. PWM output needs to be in the range 0 to 255c. Print voltage to serial monitor to verify3. Connect PWM output to DC motor4. Write a function to linearly scale the data5. Write a function to update the motorDesktop fan: EAS 199A33

Potentiometer CircuitUse the potentiometer from the Arduino Inventor’s Kit5VAnaloginput pinVinVoutDesktop fan: EAS 199A34Code to print potentiometer reading//////Function:read potentiometerRead a potentiometer and print the readingintsensor pin 3;////Wire sweeper of pot toanalog input pin 3void setup(){Serial.begin(9600);}void loop(){int val;val analogRead( sensor pin );Serial.print("reading ");Serial.println( val );}Desktop fan: EAS 199A35DC Motor Control Circuit 5VmotorPin330ΩAdd this to thebreadboard with thepotentiometer circuitDesktop fan: EAS 199A36

DC Motor Control Circuit 5V5VAnaloginput pinmotorPin330ΩArduinoDesktop fan: EAS 199A37Control the DC motor with PWM Output//////Function:DC motor control potUse a potentiometer to control a DC motorintintsensor pin 3;motor pin 5;// must be a PWM digital outputvoid setup(){Serial.begin(9600);pinMode(motor pin, OUTPUT)}Subtle: Don’t use integer values of 255 and1024 here. Aggressive compilers pre-computethe integer division of 255/1024 as zero.void loop(){int pot val, motor speed;pot val analogRead( sensor pin );motor speed pot val*255.0/1024.0;analogWrite( motor pin, motor speed);// Include decimal}Desktop fan: EAS 199A38Part II: Create functions for reusable code//////Function:DC motor control potUse a potentiometer to control a DC motorintintsensor pin 3;motor pin 5;// must be a PWM digital outputvoid setup(){Serial.begin(9600);pinMode(motor pin, OUTPUT)}Adjust motor speedvoid loop(){int pot val, motor speed;pot val analogRead( sensor pin );motor speed pot val*255.0/1024.0;analogWrite( motor pin, motor speed);// Include decimal}Map input values to output scaleDesktop fan: EAS 199A39

Final version of the loop() function//////Function:DC motor control potUse a potentiometer to control a DC motorintintsensor pin 3;motor pin 5;// must be a PWM digital outputvoid setup(){Serial.begin(9600);pinMode(motor pin, OUTPUT)}void loop(){adjust motor speed( sensor pin, motor pin);. // do other useful stuff}adjust motor speed takes careof the two main tasks: reading thepotentiometer outputs and settingthe PWM signal to the transistorDesktop fan: EAS 199A40Using and Writing FunctionsAdditional information on the Arduino web site tionFunctions are reusable code modules: Functions encapsulate tasks into larger building blocksFunctions hide details and variables local to each taskWell-written functions can be reusedFunctions can accept input (or not) and return output (or not)All Arduino sketches have at least two functions‣ setup: runs once to configure the system‣ loop: runs repeatedly after start-up is complete Users can add functions in the main sketch file, or in separate filesDesktop fan: EAS 199A41The setup() FunctionConsider the simple blink sketch“void” means Returns nothingNo inputs////Blink.pde:Turn on an LED for one second, thenoff for one second. Repeat continuously.void setup() {pinMode(13, OUTPUT);}“setup” isvoid loop() {digitalWrite(13, HIGH);delay(1000);digitalWrite(13, LOW);delay(1000);}Desktop fan: EAS 199Athe name of the function////////set the LED onwait for a secondset the LED offwait for a second42

A Function to Translate Linear ScalesLinear scaling from x valuesto y values:ymaxyy f(x)where f is a linear mappingyminxminxxmaxIn words: Given x, xmin, xmax, ymin, and ymax, compute yDesktop fan: EAS 199A43A Function to Translate Linear ScalesEnter the code at the bottom into your sketch The code is not inside any other program block(like setup or void)How would you test that this function is working?int int scale(int x, int xmin, int xmax, int ymin, int ymax){int y;y ymin float(ymax - ymin)*float( x - xmin )/float(xmax - xmin);return(y);}N.B. This code is essentially a reimplementationof the built-in map function.See http://arduino.cc/en/Reference/MapDesktop fan: EAS 199A44A Function to Translate Linear Scalesreturns an intname is int scalefirst input is anint named “x”int int scale(int x, int xmin, int xmax, int ymin, int ymax){int y;y ymin float(ymax - ymin)*float( x - xmin )/float(xmax - xmin);return(y);}Use float for better precisionreturn the value stored in “y”Desktop fan: EAS 199A45

Functions are not nested//Contents of sketch, e.g. motor control.pdevoid setup(){.}void loop(){.}int int scale(int x, int xmin, int xmax, int ymin, int ymax){.}Desktop fan: EAS 199A46Functions call other functions//Contents of sketch, e.g. motor control.pdevoid setup(){.}void loop(){.motor speed int scale( pot val, 0, 1024, 0, 255);}int int scale(int x, int xmin, int xmax, int ymin, int ymax){.return( y );}Desktop fan: EAS 199A47Functions call other functions//Contents of sketch, e.g. motor control.pdevoid setup(){.}void loop(){.motor speed int scale( pot val, 0, 1024, 0, 255);}int int scale(int x, int xmin, int xmax, int ymin, int ymax){.return( y );}Desktop fan: EAS 199A48

Use the int scale function//////Function:DC motor control potUse a potentiometer to control a DC motorintintsensor pin 3;motor pin 5;// must be a PWM digital outputvoid setup(){Serial.begin(9600);pinMode(motor pin, OUTPUT)}void loop(){int pot val, motor speed;pot val analogRead( sensor pin );motor speed int scale( pot val, 0, 1024, 0, 255;analogWrite( motor pin, motor speed);}int int scale(int x, int xmin, int xmax, int ymin, int ymax){int y;y ymin float(ymax - ymin)*float( x - xmin )/float(xmax - xmin);return(y);}Desktop fan: EAS 199A49A Function to update motor speedInputs sensor pinmotor output pinTasks: Read potentiometer voltageConvert voltage from 10 bit to 8 bit scalesChange motor speedvoid adjust motor speed(int sensor pin, int motor pin){int motor speed, sensor value;sensor value analogRead(sensor pin);motor speed int scale(sensor value, 0, 1024, 0, 255);analogWrite( motor pin, motor speed);Serial.print("Pot input, motor output ");Serial.print(sensor value);Serial.print(" "); Serial.println(motor speed);}Desktop fan: EAS 199A50Functions call functions, call functions, .//Contents of sketch, e.g. motor control.pdevoid setup(){.}void loop(){.adjust motor speed( ., . )}void adjust motor speed(int sensor pin, int motor pin){.motor speed int scale( ., ., ., ., . );}int int scale(int x, int xmin, int xmax, int ymin, int ymax){.return( y );}Desktop fan: EAS 199A51

Button Input:On/off state changeDesktop fan projectEAS 199A, Fall 2010User input features of the fan Potentiometer for speed control Continually variable input makes sense for speed controlPreviously discussed Start/stop Could use a conventional power switchPush button (momentary) switch Lock or limit rotation angle Button click to hold/release fan in one positionPotentiometer to set range limitDesktop fan: EAS 199A53Conventional on/off switchBasic light switch or rocker switch Makes or breaks connection to powerSwitch stays in position: On or OffToggle position indicates the stateNOT in the Arduino Inventors KitImage from sparkfun.comDesktop fan: EAS 199AImage from lowes.com54

Momentary or push-button switches Temporary “click” input Two types: normally closed or normally open Normally open electrical contact is made when button is pressed Normally closed electrical contact is broken when button is pressed Internal spring returns button to its un-pressed stateOpenClosedImage from sparkfun.comDesktop fan: EAS 199A55Momentary Button and LED CircuitDigital input with a pull-down resistor When switch is open (button not pressed):‣ Digital input pin is tied to ground‣ No current flows, so there is no voltagedifference from input pin to ground‣ Reading on digital input is LOW 5VLEDPush-buttonswitchWhen switch is closed (button is pressed):‣ Current flows from 5V to ground, causing LEDto light up.‣ The 330Ω resistor limits the current draw bythe input pin.‣ The 10k resistor causes a large voltage dropbetween 5V and ground, which causes thedigital input pin to be closer to 5V.‣ Reading on digital input is HIGH330 Ω10 kΩDesktop fan: EAS 199ADigitalinput pin56Programs for the LED/Button Circuit1. Continuous monitor of button state Program is completely occupied by monitoring the buttonUsed as a demonstration — not practically useful2. Wait for button input Blocks execution while waitingMay be useful as a start button3. Interrupt Handler Most versatileDoes not block executionInterrupt is used to change a flag that indicates stateRegular code in loop function checks the sate of the flagAll three programs use the same electrical circuitDesktop fan: EAS 199A57

Continuous monitor of button stateintbutton pin 4;// pin used to read the buttonvoid setup() {pinMode( button pin, INPUT);Serial.begin(9600);// Button state is sent to host}void loop() {int button;button digitalRead( button pin );if ( button HIGH ) {Serial.println("on");Serial monitor shows} else {a continuous streamSerial.println("off");}of “on” or “off”}This program does not control the LEDDesktop fan: EAS 199A58Wait for button inputintbutton pin 4;// pin used to read the buttonvoid setup() {int start click LOW;//Initial state: no click yetpinMode( button pin, INPUT);Serial.begin(9600);while ( !start click ) {start click digitalRead( button pin );Serial.println("Waiting for button press");}while loop continuesas long as start clickis FALSE}void loop() {int button;button digitalRead( button pin );if ( button HIGH ) {Serial.println("on");} else {Serial.println("off");}Same loop()function asbefore}Desktop fan: EAS 199A59Interrupt handler for button inputintintbutton interrupt 0;toggle on false;////Interrupt 0 is on pin 2 !!Button click switches statevoid setup() {Serial.begin(9600);attachInterrupt( button interrupt, handle click, RISING);}// Register handlervoid loop() {if ( toggle on ) {Serial.println("on");} else {Serial.println("off");}}void handle click(){static unsigned long last interrupt time 0;unsigned long interrupt time millis();if ( interrupt time - last interrupt time 200 ) {toggle on !toggle on;}last interrupt time interrupt time;//Zero only at start// Read the clock// Ignore when 200 msec}Desktop fan: EAS 199A60

Interrupt handler for button inputintintbutton interrupt 0;toggle on false;//Interrupt 0 is on pin 2 !!Interrupthandlermustbe registered// Buttonclickswitchesstate when program startsvoid setup() {Serial.begin(9600);attachInterrupt( button interrupt, handle click, RISING);}void loop() is{ the IDbutton interruptif ( toggle on ) {or numberof the interrupt.Serial.println("on");It mustbe {0 or 1} else// Register handlerA RISING interrupt occurs when thepin changes from LOW to HIGHSerial.println("off");}}void handle click(){static unsigned long last interrupt time 0;The interrupt handler, handle click,is a user-written function that iscalled when an interrupt is detected//unsigned long interrupt time millis();if ( interrupt time - last interrupt time 200 ) {toggle on !toggle on;}last interrupt time interrupt time;Zero only at start// Read the clock// Ignore when 200 msec}Desktop fan: EAS 199A61Interrupt handler for button inputintintbutton interrupt 0;toggle on false;////Interrupt 0 is on pin 2 !!Button click switches statetoggle on is a global variable that remembersvoid setup() {the “state”. It is either true or false (1 or 0).Serial.begin(9600);attachInterrupt( button interrupt, handle click, RISING); // Register handler}void loop() {if ( toggle on ) {Serial.println("on");} else {Serial.println("off");}}The loop() function only checks the stateof toggle on. The value of toggle on isset in the interrupt handler, handle click.void handle click(){static unsigned long last interrupt time 0;//Zero only at startunsigned long interrupt time millis();// Read the clockif ( interrupt time - last interrupt time 200 ) { // Ignore when 200 msectoggle on !toggle on;}The value of toggle on is flipped onlylast interrupt time interrupt time;when a true interrupt even occurs. Debouncing is described in the next slide.}Desktop fan: EAS 199A62Interrupt handler for button inputintintbutton interrupt 0;toggle on false;////Interrupt 0 is on pin 2 !!Button click switches statevoid setup() {Serial.begin(9600);attachInterrupt( button interrupt, handle click, RISING);}// Register handlerValue of a static variable is always retainedvoid loop() {if ( toggle on ) {Serial.println("on");} else {Serial.println("off");}}Use long: the time value inmilliseconds can become largeClock time when current interrupt occursvoid handle click(){static unsigned long last interrupt time 0;Ignore events that occur in less than200 msec from each other. These are// Zero only at startlikely to be mechanical bounces.unsigned long interrupt time millis();if ( interrupt time - last interrupt time 200 ) {toggle on !toggle on;}last interrupt time interrupt time;}Desktop fan: EAS 199A// Read the clock// Ignore when 200 msecSave current time as the new “last” time63

Other referencesLadyada tutorial Excellent and n5.htmlArduino reference Minimal explanation Using interrupts‣ http://www.arduino.cc/en/Tutorial/Button‣ o-interrupts/‣ Desktop fan: EAS 199A64

Arduino Programming: PWM Control of DC motor speed Desktop fan project EAS 199A, Fall 2010 Desktop fan: EAS 199A Overview Part I Circuits and code to control the speed of a small DC motor. Use potentiometer for dynamic user input. Use PWM output from an Arduino to control a transistor. Tra