Sie sind auf Seite 1von 195

Mechatronics Workshop-in-a-Box

2005 Microchip Technology Incorporated. All Rights Reserved.

Mechatronics Workshop-in-a-Box

Slide 1

Welcome Everybody (If you are presenting this Workshop to a group of people, the Presenter Notes in italics contain special instructions or information for you). Dear Presenter, We are pleased that you are taking the time to teach this WIB to others. At Microchip Technology we are excited about the abundant opportunities for incorporating PIC microcontrollers into mechanical applications. Thank you for joining us in introducing others to this exciting technological frontier. The following presentation includes speaker notes that you can refer to during your presentation. Please pay special attention to the TRANSISTION sentences called out at the end of many of the slide notes. Using these transition sentences will allow the presentation to flow much smoother. We hope you enjoy teaching the class as much as we enjoyed creating it. Have fun with it!

When you walk out of here today you will know Why designing a PIC microcontroller into a mechanical system is beneficial to you How easy it is to get started with Microchip and PIC microcontrollers How to use Microchips low-cost tools to change, adapt and add features to a design How to perform basic mechatronic tasks using a PIC microcontroller

2005 Microchip Technology Incorporated. All Rights Reserved.

Mechatronics Workshop-in-a-Box

Slide 2

The purpose of the slide is to peak the audiences curiosity. Start off early with what they will learn today. There must be a compelling reason for the audience to want to migrate from a mechanical to a mechatronic solution. Well take a look at the benefits of Mechatronics at the beginning of this lecture. We will show you how easy it is to get started with Microchips products with minimal financial and time investment. The reality is that for any engineering project, the requirements will change. Those darn Marketing folks can never make up their mind and will always want something else halfway through the project. One of the biggest advantages of Microchips products is that we offer you a wealth of options and make it easy for you to change and adapt to changing requirements. The consistency in tools and products allow you to add features without starting over every time things change. This is a workshop so that means you get to play! During a large part of this class you will be working on labs that will show you how to make a PIC microcontroller do simple tasks.

Agenda
Introduction to Microchip Technology Inc. Mechatronics examples and benefits PIC Microcontroller Basics
- Hands-On Learning Cycles

Labs
- Simple I/O and Timer 0 - Reading an analog sensor, LCD module - Controlling the speed of a motor

Resources
2005 Microchip Technology Incorporated. All Rights Reserved. Mechatronics Workshop-in-a-Box Slide 3

Go through the basic agenda. There will be a break in the middle

Agenda
Introduction to Microchip Mechatronics examples and benefits PIC Microcontroller Basics
- Hands-On Learning Cycles

Labs
- Simple I/O and Timer 0 - Reading an analog sensor, LCD module - Controlling the speed of a motor

Resources
2005 Microchip Technology Incorporated. All Rights Reserved. Mechatronics Workshop-in-a-Box Slide 4

Lets first take a brief look at who Microchip is and what products they make.

Microchip Technology Inc.


Leading semiconductor manufacturer:
-

of high-performance, field-programmable, 8-bit & 16-bit RISC Microcontrollers of Analog & Interface products of related Memory products for high-volume Embedded Control applications

$847M in net sales in FY05 More than 3,800 employees #1 Unit shipments of 8-bit Microcontrollers*
* Gartner Dataquest, 2003 Microcontroller Market Share & Unit Shipments, Tom Starnes, June 2003.
2005 Microchip Technology Incorporated. All Rights Reserved. Mechatronics Workshop-in-a-Box Slide 5

Introduce Microchip Technology Ask Who knows Microchip? Microchip entered this 8-bit microcontroller market back in 1990 as a virtually unknown company, with a non-standard product architecture and in a market crowded by the worlds largest competitors in the U.S., Europe, Asia and Japan. 1990 rank of #20 achieved with a handful of products. Company was still private until March 1993. Our market share has gone up every year. We are currently at the #2 position, behind the long term industry leader Motorola. I would say that such marketshare gains have never been accomplished in a highly competitive field of well entrenched competitors. And while doing this, we have not lost money in a single quarter in the last 12 years, not even in the recessionary years of 1991, 1996, 1998 and 2001. Currently #1 supplier of 8-bit Microcontrollers in the world by Units shipped
Most important aspect: Microchip has had phenomenal growth over the last 15 years. We grow because customers buy our products We have no internal consumption People buy our products, because it makes them successful in business If our customers are not successful, we are not successful. Transition Question: Lead in to next slide is asking How do we do it? Why do people buy our products?

Microchip Delivers Solutions


Low-risk product development Lower total system cost Faster time to market Dependable delivery High-quality devices Outstanding support through all phases

2005 Microchip Technology Incorporated. All Rights Reserved.

Mechatronics Workshop-in-a-Box

Slide 6

Risk free development environment


Seamless Flash program size expansion -Allows for product feature changes without loss of work already completed Pinout compatibility - Consistent by package, Similar throughout Software development environment consistency Proven Libraries, reference designs and application notes

Lower total system solution cost


Appropriate level of integration - From simple digital to high level of analog on board Vast array of hardware and software peripherals Lower cost of ownership - System level development assistance and optimization

Faster time to market


One consistent hardware and software development environment Seamless migration allows for no lost time due to end product feature creep All platform technologies available from one source - Micro, Analog, Memory, RF

Dependable delivery
Consistently short lead times High-Quality Decade+ of product lifetime, In house manufacturing, World class quality, QS9000 - Best in class Flash reliability - Customer recognized quality

Outstanding Support
Proven Libraries, reference designs and application notes - 25 technical support centers worldwide Global, real-time technical phone and e-mail support - Free On-line product samples Worldwide MASTERS conferences - Technical seminars - Web based technical support Highly consultative sales team

The PIC Microcontroller Family


256 128 Memory (kBytes) 64 32 16 8 4 2 1 6 8 14 18 28 Pins

dsPIC
Digital Signal Controller (DSC) 30 MIPs, Up to 48k Instructions, 18-84 pins

High Performance
10 MIPs, Up to 64k Instructions, 18-84 pins

Mid-Range
5 MIPs, Up to 8k Instructions, 8-64 pins

Baseline
5 MIPs, up to 2k Instructions, 6-40 pins

40

64

84
Slide 7

2005 Microchip Technology Incorporated. All Rights Reserved.

Mechatronics Workshop-in-a-Box

Microchips PIC microcontroller family currently consist of 4 Families or Architectures Baseline Mid-Range High Performance dsPIC digital signal controllers Baseline Products 12-bit Instruction set covering 6-40-Pin and up to 3kByte Program Memory or 2k Instructions Up to 5 MIPS Performance Basic Peripheral set including comparators and A/D Mid-Range Products 14-bit Instruction set covering 8-64-Pin and up to 14kByte Program Memory or 8k Instructions Up to 5 MIPS Performance More Advanced Peripheral set including Serial Communications, Capture/Compare/PWM, LCD, EEPROM, 10-bit A/D Part numbers begin with PIC12, PIC16 High Performance Products 16-bit Instruction set covering 18-84-Pin and up to 128kByte Program Memory or 64k Instructions Up to 10 MIPS Performance with hardware multiply Very Advanced Peripheral set including Advanced Serial Communications (CAN, USB), Capture/Compare/PWM, LCD, EEPROM, 10-bit A/D dsPIC 16-bit Digital Signal Controller Products 24-bit Instruction set covering 18-84-Pin and up to 144kByte Program Memory Up to 30 MIPS Performance with Digital Signal Processing Capability Very Advanced 16-bit Peripheral set including Motor Control, Faster A/D, Serial Communications Extensive Software Library available Point to overlap that allows for migration between different families

Migration between Different Products Example: Mid-Range Parts Pin Compatible within specific pinouts Code Compatible Peripheral Consistency Seamless Migration across more than 200 Products
2005 Microchip Technology Incorporated. All Rights Reserved.

14 - Pin

VDD RA5 RA4 RA3 RC5 RC4 RC3 RC6 RC7 RB7

20 - Pin

8 - Pin

VSS RA0 RA1 RA2 RC0 RC1 RC2 RB4 RB5 RB6

Mechatronics Workshop-in-a-Box

Slide 8

Many of the new microcontrollers in the Baseline and Mid-Range families allow you to easily migrate between devices with different number of pins. This means if you start development with one part, and the requirements for your project change during development or between product revisions, you can easily change to a part that meets your new requirements. This slide shows the migration from 8 to 14 to 20 pins in Microchips Mid-Range family. As you can see the I/O pins and power and ground pins are consistent throughout.

Complete Signal Chain Solutions from Microchip


Digital Pot Op Amp

Sensor

Mux Ref

Filter

A/D

PIC
microcontroller

Performance: Low Power, High Precision Low Cost: System Cost, Low Component count Size: Small Packaging SC70, SOT23, DFN

2005 Microchip Technology Incorporated. All Rights Reserved.

Mechatronics Workshop-in-a-Box

Slide 9

Microchip makes more that just PIC Microcontrollers. Microchip offers a whole range of products in the signal chain that offer: High performance - our op amp performance (GBWP) to current consumption ratio is industry-leading (as good or better than the more well-known analog suppliers) Low Cost Low component count, high integration - The PGA and Digital potentiometers are a good example In very small packages - examples include LDOs, op amps, comparators, supervisors, etc. in SC-70 (~1/2 the size of SOT-23), 12-bit ADCs in SOT23, 2 LDOs + 1 supervisor in one MSOP package, etc.

Analog & Interface Products


Thermal Management
Temperature Sensors Fan Speed Controllers Fan Fault Detectors

Power Management
Linear Regulators Switching Regulators/Controllers Charge Pump DC/DC Converters

Mixed Signal
SAR/Delta-Sigma A/D Converters Dual Slope A/D Converters Display A/D Converters System D/A Converters V/F and F/V Converters Digital Potentiometers

Interface Products
CAN Peripherals Infrared Peripherals LIN Transceivers Serial Peripherals

Linear Products
Single Supply CMOS Op Amps Comparators Linear Integrated Devices Programmable Gain Amplifiers

Voltage References CPU/System Supervisors Voltage Detectors Power MOSFET Drivers Battery Management PWM Controller

2005 Microchip Technology Incorporated. All Rights Reserved.

Mechatronics Workshop-in-a-Box

Slide 10

Shown here are the 5 major product lines in Microchip's stand-alone analog portfolio. They are Power Management, Thermal Management, Linear, Mixed-Signal, and Interface products. The main attribute of these product lines is their excellent performance while focusing on low power (low voltage, low current consumption).

10

Overview of Memory Products


Wide Operating Voltage 1.8V 5.5V High Density 128 1 Mbits

Supports Major Busses Microwire, I2C, SPI

Microchip Serial EEPROM Products


High Endurance 1M Erase/Write Cycles

Small Packaging DFN, SOT-23 TSSOP, MSOP

2005 Microchip Technology Incorporated. All Rights Reserved.

Mechatronics Workshop-in-a-Box

Slide 11

Microchip also offers exceptional memory products

11

Proven Quality Record across all Product Families ISO9001 Certification QS9000 Certification Quality Awards from numerous Fortune 100 customers PPM levels consistently below 10 Field Failures for PIC microcontrollers virtually non-existent
2005 Microchip Technology Incorporated. All Rights Reserved. Mechatronics Workshop-in-a-Box Slide 12

Accolades from customers for quality. Microchip engages the automotive business. DNV comes annually to audit Microchip for quality We are in the process of qualifying for the TS16949 certification and expect to finalize the audit process in August of this year (CY2003)

12

Agenda
Introduction to Microchip Mechatronics examples and benefits PIC Microcontroller Basics
- Hands-On Learning Cycles

Labs
- Simple I/O and Timer 0 - Reading an analog sensor, LCD module - Controlling the speed of a motor

Resources
2005 Microchip Technology Incorporated. All Rights Reserved. Mechatronics Workshop-in-a-Box Slide 13

Now we are going to talk a little about mechatronics and how it benefits you. Pose Question: What is Mechatronics?

13

Mechatronics is:
Implementing electronic controls in a mechanical system Enhancing existing mechanical designs with intelligent controls Replacing mechanical components with an electronic solution A perfect system for a PIC microcontroller!!
2005 Microchip Technology Incorporated. All Rights Reserved. Mechatronics Workshop-in-a-Box Slide 14

Mechatronics can be defined in several ways. Mechatronics is implementing electronic control in a mechanical system. A computer controlled irrigation valve would be an example of this. Second, mechatronics refers to enhancing existing mechanical designs with intelligent controls. An example of this would be the power seats in a high end car. The car remembers the preferred position of the seats for a given key fob. Third, mechatronics is also replacing mechanical components with an electronic solution. The thermometer you have at home for taking a childs temperature is and example of this. The old mercury thermometers have been replaced with an electronic solution. TRANSITION: In order to grasp in more detail what Mechatronics is and why mechatronics benefits you as both a consumer and a manufacturer, we will take a look a three examples in the next few slides.

14

Example 1: Flashlight Switch Traditional Flashlight: On or Off Hybrid Flashlights: Mode selector

LEDs

Xenon Bulb

2005 Microchip Technology Incorporated. All Rights Reserved.

Mechatronics Workshop-in-a-Box

Slide 15

The first example we will be looking at is a flashlight switch. In the traditional flashlight, the switch either slides or is pushed. Contact is being physically broken and made to turn the flashlight off and on. Many new flashlight are hybrids with a xenon bulb for bright spotting applications and white LEDs for a longer-lasting flood light. The switch in these flashlights is typically a tactile switch integrated with a microcontroller that acts as a mode selector.

15

Intelligent Switch
Xenon Bulb

Push Button/ Tactile Switch

PIC Microcontroller

LED

Modes: Xenon bulb on LEDs on (dim) LEDs on (bright)


2005 Microchip Technology Incorporated. All Rights Reserved.

Strobe LEDs Flashlight off

Mechatronics Workshop-in-a-Box

Slide 16

A microcontroller switches on the different lighting elements based on the mode of the system. This slide shows some of the possible modes: 1. Turn on the xenon bulb 2. Turn on the LEDs at half power 3. Turn on the LEDs at full power 4. Strobe the LEDs for to indicate an emergency situation 5. Turn off the flashlight Other possible advanced features: The microcontroller can do things like sequence through the modes when the button in pressed in rapid succession. After a mode is selected and has been used a while the next button press results in the flashlight turning off. The switch can remember the users favorite position an default to that when the flashlight is first turned on. As you can see the design is very flexible! The same switch can be programmed to do any number of things.

16

Switch Comparison
Mechanical Hybrid Control Current Control Programmable Low Battery Detect Strobe Capable Adaptable
2005 Microchip Technology Incorporated. All Rights Reserved.

Intelligent Yes Yes Yes Yes Yes YES!


Slide 17

No No No No No NO!
Mechatronics Workshop-in-a-Box

Here is a comparison between the mechanical and intelligent switch. Clearly the biggest advantage to the Intelligent switch is that it is adaptable. Changing the firmware in the microcontroller can make the same hardware do something else entirely. This flexibility also allows you as the manufacturer add features and options that will make your product stand out on the shelf when the consumer is looking at a row of similar products.

17

Possible Solution: PIC10F20x


SOT-23 package 6 pins:
- 3 Input/Output pins - 1 Input only - 1 Power, 1 Ground

4 MHz internal oscillator


- 2% accuracy over voltage and temperature

one analog comparator


- internal voltage reference

Actual Size

Ultra-low sleep current 8-bit timer 2V to 5V operating range


2005 Microchip Technology Incorporated. All Rights Reserved. Mechatronics Workshop-in-a-Box Slide 18

So what microcontroller would be a good candidate for a design like this. Microchip recently introduced the worlds smallest microcontroller the 6-pin PIC10F20x family. These parts are small really small. The PIC10F20x parts are enclosed in a SOT-23 package, include a 4Mhz internal oscillator, and have an onboard comparator.

18

Example 2: Household Thermostat

2005 Microchip Technology Incorporated. All Rights Reserved.

Mechatronics Workshop-in-a-Box

Slide 19

The next example Ill be discussing in detail is the household thermostat. You may have now, or had growing up, the mechanical thermostat on the left. Modern thermostats are an excellent example of mechatronics. These thermostats perform the same job of the mechanical thermostat but offer many advantages over its predecessor. In the next few slides were going to dissect each of these thermostats and talk about the process of migrating from the mechanical solution to the mechatronic solution.

19

Example Application: Thermostat


Desired Temperature

Dial
60 50 40 70 80 80 70 60 50 40

Current Temperature

To Heating Unit

2005 Microchip Technology Incorporated. All Rights Reserved.

Mechatronics Workshop-in-a-Box

Slide 20

Heres a look a the mechanical thermostat. The thermostat allows the user to set the desired temperature by turning a dial. The current temperature of the room is fed back to the user by a thermometer of some kind.

20

Example Application: Thermostat


Desired Temperature
60 50 40 70 80 80 70 60 50 40

Current Temperature

Sensor/Switch

To Heating Unit

2005 Microchip Technology Incorporated. All Rights Reserved.

Mechatronics Workshop-in-a-Box

Slide 21

If we remove the dial we find a metal coil. This coil expands and contracts with temperature it is the temperature sensor for this system. The coil makes contact with a switch that turns the heating unit on and off. Disadvantages: The thermostat has to be calibrated at the factory. Even after being calibrated the unit typically has plus/minus two or three degrees of error. The resolution of the dial is very poor its user is essentially guesstimating what temperature he or she is setting the dial to. Toxic materials, such as mercury, are used to make the thermostat. The only way for a user to change the temperature of the room is to walk over to the thermostat and turn the dial. No programmability on the users part is available.

If we were going to design a mechatronic version of this thermostat how would we go about doing that? I propose we first break the thermostat down into its components at the system level.

21

Breakdown of Thermostat
60 50 40 70 80

User Feedback

Temperature Sensor

80 70 60 50 40

User Feedback

Switch to turn on Heater

User Input

2005 Microchip Technology Incorporated. All Rights Reserved.

Mechatronics Workshop-in-a-Box

Slide 22

Heres a breakdown of the thermostat. There are several sources of user feedback. First, the dial position tells the user what the desired temperature setpoint is. Secondly, the current temperature is conveyed to the user by the thermometer. User inputs are introduced to the system by the turning of the dial. Temperature information for the system is gathered by the mechanical coil. Finally, the output from the system, namely, turning on and off the heater, is handled by the thermal switch. In our mechatronic solution we would like to eliminate some of the disadvantages discussed in the previous slide. This will mean replacing these components. So what are some of the electronic equivalents of these components?

22

Conversion to Mechatronic Design


User Input
Tactile Switches

LCD

User Feedback

Temperature Sensor
Small IC

Control
PIC Microcontroller

Switch to turn on Heater


MOSFET Regulator

Power

2005 Microchip Technology Incorporated. All Rights Reserved.

Mechatronics Workshop-in-a-Box

Slide 23

Here they are. In the mechatronic solution, feedback to the user, both the desired temperature and current temperature, can be displayed on an Liquid Crystal Display (or LCD). Temperature information can be gathered from a solid-state temperature sensor. Here, weve chosen small IC temperature sensor that varies its analog voltage output proportional to temperature. A microcontroller with a 10-bit ADC can interpret this voltage into tenths of degrees. This is much higher precision than the mechanical thermostat. A MOSFET, controlled by the microcontroller, will switch the heater on an off. User inputs are entered into the system using several tactile switches. More switches can be added for increased functionally. For a direct comparison, Im just showing the two switches. At the center of the system is a microcontroller. Its job is read user inputs from the tactile switches and gather temperature information from the temperature sensor. This information is then displayed on the LCD as the desired temperature and the current temperature. This same information is interpreted by the microcontroller into an output to the MOSFET. One other component remains. A regulator is needed to provide the appropriate DC voltage to the microcontroller, LCD, and temperature sensor.

23

Finished Design
Current Temperature Desired Temperature

74oF

70oF

Higher resolution and accuracy Reduces household heating costs Self calibrating Flexible Design Environmentally Friendly
2005 Microchip Technology Incorporated. All Rights Reserved. Mechatronics Workshop-in-a-Box Slide 24

Heres the finished product! Benefits: This solution will provide higher accuracy due to the precision of the temperature sensor and A/D converter on the PIC microcontroller. The unit can offer a feature that will allow the user to program the unit to automatically lower the temperature setpoint when he or she is away during the day. This offers significant energy savings to the user. The microcontroller can automatically calibrate the sensor input, saving the manufacturer valuable time during the manufacturing process. One of biggest benefits to the manufacturer is that the design is very flexible. Changes to the design can be made by simply reprogramming the microcontroller. This avoids costly design changes should the design parameters change at some point. In addition, the same hardware can be used for models that are produced for countries that use degrees Celsius or degrees Fahrenheit. The mechatronic design is environmentally friendly as it does not employ the use of hazardous materials in its makeup.

24

Possible Solution: PIC16F917


PIC16F917
10-bit ADC LCD Module Internal Oscillator FLASH EEPROM

CCPs

I2C/SSP Comparators

AUSART

2005 Microchip Technology Incorporated. All Rights Reserved.

Mechatronics Workshop-in-a-Box

Slide 25

A suggested PIC microcontroller product for this type of application is the PIC16F91x family of parts. Some key features for these parts are: Drive up to 98 LCD segments 8 MHz internal oscillator 1 or 2 PWM modules Flash program memory (reprogrammable) Wider operating voltage range: 2V - 5.5V We will be using the PIC16F917 during the Labs in this class.

25

Temperature Sensing Options from Microchip


Temperature Sensors

Logic Output TC6501/2/3/4 TC620/1/2/3/4

Voltage Output TC1046 TC1047/47A MCP9700/1

Serial Output

SMBus/I2C TC74 TCN75A MCP9800/1/2/3

SPI TC72 TC77

2005 Microchip Technology Incorporated. All Rights Reserved.

Mechatronics Workshop-in-a-Box

Slide 26

Microchip also offers an assortment of temperature sensors. These sensors can be interfaced to a PIC microcontroller in a number of ways: The first is a logic output You can use a standard I/O to interface to this temp sensors. Logic output temp sensors are 'temp switches'. They provide a logic output (like a fault indication) when an event is detected The second is a voltage output. This can be digitized with a A/D typically found on a microcontroller This is the temperature sensor found on your PICDEM Mechatronics Board in the upper left-hand corner The last way is to have a Serial Output temp sensor Here you can read the temperature value though SMBUS, I2C or SPI.

26

Temperature Sensing Options from Microchip


Temperature Sensors

Logic Output TC6501/2/3/4 TC620/1/2/3/4

Voltage Output TC1046 TC1047/47A MCP9700/1

Serial Output

SMBus/I2C TC74 TCN75A MCP9800/1/2/3

SPI TC72 TC77

2005 Microchip Technology Incorporated. All Rights Reserved.

Mechatronics Workshop-in-a-Box

Slide 27

Lets take a look at the TC1047A for a moment as this is the temperature sensor used on the PICDEM Mechatronics board.

27

Linear Output TC1047A Temperature Sensor


Linear Slope
- 10 mV/C
2 1.8 1.6

-40 to 125C Temperature Range 2C Accurate Low Current Consumption Small Package
- SOT-23

Voltage Out (V)

1.4 1.2 1 0.8 0.6 0.4 0.2 0 -40 -20 0 20 40 60 80 100 120

Temperature (deg C)

2005 Microchip Technology Incorporated. All Rights Reserved.

Mechatronics Workshop-in-a-Box

Slide 28

The voltage output of the TC1047A changes linearly with corresponding changes in temperature. The TC1047A transfer function have a slope of 10 mV for every degC change and can detect a range of -40 to 125 degC. It gives you +/- 2% accuracy and consumes very little current. It is also a nice small package that does not take up a lot of board space (check it out.) Microchip has developed an even smaller analog-out temperature sensor the MCP9700 .

28

Example 3: Washing Machine

User interface

Sensors (door closed, water level, balance sensor) AC Induction Motor Control
2005 Microchip Technology Incorporated. All Rights Reserved. Mechatronics Workshop-in-a-Box Slide 29

In our final example we are going to look at a mechatronic example that incorporates several microcontrollers in its makeup. In large appliances like a washing machine, the user interface and motor control circuits are isolated from one another in order to meet safety standards. In this example a central microcontroller takes user inputs from the cycle select, water level, water temperature, extra rinse, and cycle buzzer buttons and dials. The microcontroller also reads the various sensors: water level sensor, balance sensor, turbidity sensor, door sensor. Another microcontroller controls the AC induction motor and changing between the spin and agitate cycles. The motor control microcontroller takes commands from the central microcontroller.

29

User Interface Improvements

Use standard dials and knobs Same knobs used on different models Reprogramming microcontroller gives knobs different functionality Switches less prone to wear compared to mechanical washing machine
2005 Microchip Technology Incorporated. All Rights Reserved. Mechatronics Workshop-in-a-Box Slide 30

One of the biggest areas of improvement on the washing machine is the user interface. In mechanical washing machines the cycle knob actually had plastic bumps on the back of the dial that acted like the software of the system. The user would turn the dial and a mechanical timer would start running, slowly turning the dial to the off position. As the dial turned the bumps on the back of the dial would come in contact with various switches that would turn on the spin cycle, fill the washer, or any number of other functions. This system worked but it had several drawbacks. First, the dial had to be fabricated for just one washer. When the timing of one of the cycles changed, for instance, a new dial had to be made. Secondly, the plastic bumps would eventually wear down or the mechanical timer would go bad. This meant the knob would have to be replaced. In modern washers, the same knob can be used on different washer models. Instead of configuring a physical knob for a certain washer, now the firmware in the microcontroller is configured for that washer. This standardizes parts and keeps inventory low. Lowering Cost: Cost is an important consideration in all design, however, in the world of appliances, designers will give up almost anything (including their first-born) to shave a penny off of the cost of a product. One of the reasons mechatronic designs are on the rise for appliances is that total system cost is being reduced. In some cases, converting a design to a mechatronic solution may appear to be more expensive on just a part-by-part basis. However, when the whole product solution is considered (including inventory, warranty repairs, customer support, and quantity pricing over all products) the mechatronic solution becomes the more-cost effective solution while making your product more desirable to customers (compared to competitors.)

30

Benefits of Modern Sensors


Turbidity sensor*: How much dirt is in the water? Door position sensor**: Is the door ajar? Balance sensor**: Is the machine unbalanced? Water Level sensor*: Determined by size of load. Benefits: * More efficient washing
- Energy efficient - Water efficient

** Make washing safer (for people and the machine)


2005 Microchip Technology Incorporated. All Rights Reserved. Mechatronics Workshop-in-a-Box Slide 31

With a microcontroller in the system a whole array of sensors can be incorporated into the product to make it safer and more efficient. Turbidity sensor measures how much particles are in the water. These means instead of running a set time in order to clean the closes, the washer now cleans the clothes until there are clean. It also rinses the clothes until all soaps are rinsed from the clothes. The door position sensor ensures the machine will not enter the spin cycle with the door open. This prevents a child from getting harmed by sticking his arm in the machine while it is spinning. A balance sensor monitors the balance of the machine. Should the machine start oscillating violently, the machine shuts itself off in order to prevent harm to the machine and its surroundings. Water level sensor allows the user to set a load size, furthering the water efficiency of the machine. With the addition of sensors, modern high-tech washers use half the energy and water of older machines, in addition to getting clothes cleaner than before.

31

AC Induction Motor Control


Benefits to Microcontroller-based speed control: Smaller motor Standardized motor Higher efficiency Consistency over varying load conditions Precision speed-control (more speeds possible)

2005 Microchip Technology Incorporated. All Rights Reserved.

Mechatronics Workshop-in-a-Box

Slide 32

History: Mechanical washing machines typically use a two speed motor to spin the drum and agitator. Depending on the durability of the load, the motor may run at low speed (for delicates) or high speed (for blue-jeans and towels.) The two speeds are achieved by the number of windings turned on in the motor. In a two winding motor, one winding is turned on for low speed, two are turned on for high speed. Comparison to Modern designs: In a mechatronic washing machine, this two-speed motor is replaced with a standard smaller motor. This motor produces the same power as the two speed design, but because it doesnt have the complexity of the two-speed motor it is smaller. A microcontroller is used to control the speed of this motor by modulating the windings. Compared to the two-speed system, the motor in the modern machine has a far greater number of speed settings. This means the speed of the motor can be set for individual load types (perma-press, delicates, cotton, wool, etc.) In addition, feedback in the system allows the motor to provide a consistent speed independent of the weight of the load. Finally, because more control over the power usage of the motor is now available, the motor can be run at its optimum setting for a given load in order to optimize efficiency.

32

Possible Solution: PIC18F4431


PWM Output: 8 independent channels
- Up to 14-bit resolution - Edge and center-aligned - Programmable dead-time

3-ch Quadrature Encoder Interface 10-bit High-Speed A/D Converter Created from the ground up for precision motor control!
2005 Microchip Technology Incorporated. All Rights Reserved. Mechatronics Workshop-in-a-Box Slide 33

Lets take a look at what Microchip products are being used in these new mechatronic marvels. On the motor control side of the things, Microchips PIC16F4431 microcontroller is an excellent candidate for Brushless DC and AC induction motor control systems. Some of its motor-control specific features are listed on this slide. Basically, what you need to know is that for high-end motor control applications, this is a microcontroller that was built from the ground up to target those applications.

33

Microchip MOSFET Driver Solutions


Power MOSFET Drivers 0.5A Peak Output
TC1410/N single

1.5A Peak Output Single


TC4403 floating load TC4626/7 voltage boost TC4431/2 30V high/low

2A Peak Output
TC1412/N single

6A Peak Output
TC429 TC4420/9 single

1A Peak Output
TC1411/N single

3A Peak Output
TC1413/N single TC4423/4/5 dual

9A Peak Output
TC4421/2 single

1.2A Peak Output


TC1426/7/8 dual TC4467/8/9 quad

Dual
TC4x6/7/8 Enhanced TC442xA matched delay TC4404/5 split out, open drain

2005 Microchip Technology Incorporated. All Rights Reserved.

Mechatronics Workshop-in-a-Box

Slide 34

Microchip is one of the first and leading suppliers of MOSFT Drivers. Our portfolio consists of a wide range of products that can deliver up to 9A peak output current and come in several configurations (single/dual/quad and inverting/non-inverting). Our solutions are very robust: they lead the industry in latch-up immunity/stability. (They are used to drive the high-power devices, like IGBTs, MOSFETs, and Bipolar transistors.)

34

Mechatronics Review
Mechatronics is _________________. What are the benefits to mechatronics?
- How does the consumer benefit? - How does the manufacturer benefit?

What is the worlds smallest microcontroller? What microcontroller can directly drive a LCD?
2005 Microchip Technology Incorporated. All Rights Reserved. Mechatronics Workshop-in-a-Box Slide 35

Review mechatronics with the students: Answers: Mechatronics is implementing electronic control in a mechanical system. It is also replacing mechanical components in a system with electrical components. Benefits: Consumer: more features, more user friendly, more reliable, lower cost, safer, environmentally friendly, more efficient Manufacturer: flexible, lower cost, more market appear, higher resolution, less warranty repairs PIC10F20x family Hint: Its the microcontroller on the PICDEM Mechatronics board the PIC16F91x family

35

Agenda
Introduction to Microchip Mechatronics examples and benefits PIC Microcontroller Basics
- Hands-On Learning Cycles

Labs
- Simple I/O and Timer 0 - Reading an analog sensor, LCD module - Controlling the speed of a motor

Resources
2005 Microchip Technology Incorporated. All Rights Reserved. Mechatronics Workshop-in-a-Box Slide 36

In this next section we will be taking a introductory look at PIC microcontrollers. Rather than just telling you about how a PIC microcontroller works, you will be able to experience the PIC microcontroller working yourself with the tools provided for this class. The knowledge you learn in this section will be tested during the Labs that follow this section.

36

Objectives of PIC Microcontroller Basics


We will learn how to: Create code Compile Test and debug Use MPLAB Integrated Development Environment (IDE)
. . . all with a focus on learning about PIC microcontroller architecture and terms

2005 Microchip Technology Incorporated. All Rights Reserved.

Mechatronics Workshop-in-a-Box

Slide 37

These are the objectives for the PIC Microcontroller Basics section: Create code Compile source code Test and Debug code Use MPLAB Integrated Development Environment (IDE) While we are creating, compiling and testing code you will be becoming familiar with PIC microcontroller architecture and terms

37

What is MPLAB IDE?


MPLAB IDE is the name of Microchips free

Integrated Development Environment


Software that runs on your PC Complete development environment for your embedded system Our basic tool for the rest of this class
2005 Microchip Technology Incorporated. All Rights Reserved. Mechatronics Workshop-in-a-Box Slide 38

I just mentioned we are going to learn how to use MPLAB IDE. What is MPLAB IDE? Microchips Free MPLAB IDE is downloadable from Microchips website, www.microchip.com. MPLAB IDE is a Windows program that runs on your PC. As youll soon see, the software is fairly easy to use.

38

Embedded Software Design Cycle

Build Code

Run Code

Write Code

Debug Code

2005 Microchip Technology Incorporated. All Rights Reserved.

Mechatronics Workshop-in-a-Box

Slide 39

This slide shows the embedded software design cycle. Embedded refers to creating software for a microcontroller or other programmable integrated controller. This Cycle begins with you brainstorming the design at a high level. You may create flowcharts, outlines, or storyboards for the program flow. Next youll write source code. Then youll build the code using MPLAB IDE (or check for errors.) Next you will run the code either in a simulator or on the part using a debugger. Finally, youll test or debug the code. Does the code do what it is supposed to. If the answer is no, then the cycle continues until you have a finished piece of code.

39

Agenda
Introduction to Microchip Mechatronics examples and benefits PIC Microcontroller Basics
- Hands-On Learning Cycles Cycle #1

Labs
- Simple I/O and Timer 0 - Reading an analog sensor, LCD module - Controlling the speed of a motor

Resources
2005 Microchip Technology Incorporated. All Rights Reserved. Mechatronics Workshop-in-a-Box Slide 40

We will be going through several hands-on learning cycles. These cycles will begin with me explaining a piece of PIC microcontroller architecture. Well then write some instructions together to create an application. Finally, well test the application. We will now begin learning cycle #1.

40

Architecture: Overview

Program Memory

Data Memory

Special Features

Input / Output Ports

2005 Microchip Technology Incorporated. All Rights Reserved.

Mechatronics Workshop-in-a-Box

Slide 41

This is a simplified look at PIC microcontroller architecture. There are four major components to the PIC microcontroller architecture: Program memory Data memory Input/Output Ports and Special Features

41

Architecture: Overview

Program Memory

Data Memory

Special Features

I/O Ports

2005 Microchip Technology Incorporated. All Rights Reserved.

Mechatronics Workshop-in-a-Box

Slide 42

We are going to first look at the memory on a PIC microcontroller.

42

Architecture: PIC16F917

Program Memory

Hard Drive

14 bits wide 8192 words

2005 Microchip Technology Incorporated. All Rights Reserved.

Mechatronics Workshop-in-a-Box

Slide 43

The part that we will be using on the PICDEM Mechatronics board is the PIC16F917. Therefore, well be discussing all these architecture components specifically for the PIC16F917. The first component is program memory. Think of program memory as your hard disk drive. The drive contains all the programs you run on your PC. On the PIC16F917 the program memory is 14 bits wide by 8192 words. Commit these numbers to memory for a few moments.

43

Architecture: PIC16F917

Floppy Disk

Data Memory

8 bits wide 512 bytes

2005 Microchip Technology Incorporated. All Rights Reserved.

Mechatronics Workshop-in-a-Box

Slide 44

A microcontroller also has data memory. This memory is memory that is constantly changing. You may think of it as a floppy disk. The data memory is 8 bits wide by 512 bytes. Commit these numbers to memory as well.

44

Hands-on with MPLAB IDE

MPLAB IDE

2005 Microchip Technology Incorporated. All Rights Reserved.

Mechatronics Workshop-in-a-Box

Slide 45

Lets look at both of these memory types on the PIC16F917. Open MPLAB IDE by clicking on these ICON on your desktop.

45

Configure Select Device

2005 Microchip Technology Incorporated. All Rights Reserved.

Mechatronics Workshop-in-a-Box

Slide 46

Choose Configure -> Select Device.

46

Selecting PIC16F917

2005 Microchip Technology Incorporated. All Rights Reserved.

Mechatronics Workshop-in-a-Box

Slide 47

Choose the PIC16F917.

47

Program Memory View

2005 Microchip Technology Incorporated. All Rights Reserved.

Mechatronics Workshop-in-a-Box

Slide 48

We have just set up MPLAB IDE to develop code for the PIC16F917. Do you still remember those numbers I had you commit to memory? Question to Pose: How many bits wide is the Program memory? How many words? Lets look at the program memory. Choose View -> Program Memory

48

Program Memory View

2005 Microchip Technology Incorporated. All Rights Reserved.

Mechatronics Workshop-in-a-Box

Slide 49

A window showing the program memory will appear. Near the bottom of the window click on the Machine tab. Scroll to the last memory location What line is this? Does this number look familiar? Look at the Opcode column. Can anybody tell by how many bits long the opcode is? (Answer: 14)

49

Hexadecimal to Binary

3FFF

11111111111111

2005 Microchip Technology Incorporated. All Rights Reserved.

Mechatronics Workshop-in-a-Box

Slide 50

If youre unfamiliar with hexadecimal numbers bring up the calculator in Windows: Start -> All Programs -> Accessories -> Calculator In Calculator click View -> Scientific Select the Hex radio button near the top left of the window Type in 3FFF Select the Bin radio button How many 1s are in the window? There are 14.

50

Data Memory (File) View

2005 Microchip Technology Incorporated. All Rights Reserved.

Mechatronics Workshop-in-a-Box

Slide 51

Now, lets take a look at the data memory. Data memory is also called file registers. Choose View -> File Registers

51

Data Memory (File) View

8 bits
2005 Microchip Technology Incorporated. All Rights Reserved. Mechatronics Workshop-in-a-Box Slide 52

In the File Registers window, click on the symbolic Tab. Scroll to the end of the memory. The last address is 01FF. What is the number in decimal? (Answer 512.) Use the calculator to show the audience if necessary. How long is each register? Look at binary column. Each 0 represents a bit.

52

Special Function Registers

2005 Microchip Technology Incorporated. All Rights Reserved.

Mechatronics Workshop-in-a-Box

Slide 53

Open your window wide enough so that you can see the symbol name column. Scroll back to the top of the file registers. You can see that some for the data memory has already been assigned a symbol name. These registers are called Special Function Registers or SFRs. You dont need to understand what these registers are yet, however, just remember that they exist because well be learning more about these registers later.

53

Separate Program & Data

Program Memory

Data Memory

Program and Data memory are separate entities Why separate?


2005 Microchip Technology Incorporated. All Rights Reserved. Mechatronics Workshop-in-a-Box Slide 54

As you can see program and data memory are separate entities. Why? What purpose do these different memory entities serve? Answer: Program Memory This is the memory that contains the source code. Its actually the numerical equivalence of source code. This memory is fixed once it is programmed into a PIC microcontroller. Data Memory This memory is dynamic. It is constantly changing. This memory contains variables and information about the current state of input/output pins on the PIC microcontroller.

54

Cycle #1: What Did I Learn?


I learned how to select my target device Program memory is ___ bits by ___ words Data memory is ___ bits by ___ words A file register is just another name for ___ Program and data memory are separate Certain file registers are special function
2005 Microchip Technology Incorporated. All Rights Reserved. Mechatronics Workshop-in-a-Box Slide 55

Lets review Cycle #1. You learned how to select a device in MPLAB Program memory is 14 bits by 8192 words Data memory is 8 bits by 512 words A file register is just another name for Data memory. Program and data memory are separate Certain file registers are Special function registers

55

Agenda
Introduction to Microchip Mechatronics examples and benefits PIC Microcontroller Basics
- Hands-On Learning Cycles Cycle #2

Labs
- Simple I/O and Timer 0 - Reading an analog sensor, LCD module - Controlling the speed of a motor

Resources
2005 Microchip Technology Incorporated. All Rights Reserved. Mechatronics Workshop-in-a-Box Slide 56

We are now ready for hand-on learning cycle #2.

56

Architecture: Overview

Program Memory

Data Memory

Special Features

I/O Ports

2005 Microchip Technology Incorporated. All Rights Reserved.

Mechatronics Workshop-in-a-Box

Slide 57

In this cycle we will be learning about one of the PIC microcontrollers special features.

57

Architecture: W Register

W register is an 8-bit temporary working register


Special Features

W register is used in many instructions


Mechatronics Workshop-in-a-Box Slide 58

2005 Microchip Technology Incorporated. All Rights Reserved.

The W register is an 8-bit temporary working register. The W register is used in many instructions. If you want to add two numbers together, for instance, you will move one number into the W register, then add the other number to W.

58

Hands-on with MPLAB IDE

MPLAB IDE

2005 Microchip Technology Incorporated. All Rights Reserved.

Mechatronics Workshop-in-a-Box

Slide 59

The best way to understand the W register is to use it. Were going to do that now by writing your first PIC microcontroller source code.

59

MPLAB Simulator

2005 Microchip Technology Incorporated. All Rights Reserved.

Mechatronics Workshop-in-a-Box

Slide 60

Lets begin by opening the MPLAB Simulator. The MPLAB Simulator simulates what the PIC16F917 will do on your PC. Its a great tool for learning and trying out new instructions. Its possible to use the simulator to debug a piece of code without ever programming a PIC microcontroller. Choose Debugger -> Select Tool -> MPLAB SIM

60

Creating My First Program


Click on File New Enter the four lines of code below:

addlw 1 movwf 0x20 goto 0 end


2005 Microchip Technology Incorporated. All Rights Reserved. Mechatronics Workshop-in-a-Box Slide 61

We have to write some code for the simulator to simulate. To do this: Choose File -> New Enter the four lines of code below This four lines are included in the Hands-on Guide hand-out. In the Hands-on Guide, each line is commented to tell you how each instruction works.

61

Creating Your First Program


Click on File Save As

c:\h1.asm Project Quickbuild h1.asm


Look in the Output Window for

BUILD SUCCEEDED
2005 Microchip Technology Incorporated. All Rights Reserved. Mechatronics Workshop-in-a-Box Slide 62

Save the file as h1.asm under C:\ Build the project using Project -> Quickbuild h1.asm Verify that the build was successful in the output window

62

Running Your First Program

2005 Microchip Technology Incorporated. All Rights Reserved.

Mechatronics Workshop-in-a-Box

Slide 63

Have the students cursor over the simulator buttons and explain how run, halt, animate, single step, and reset work. Explain the status bar: MPLAB SIM this location shows the tool MPLAB is currently configured for PIC16F917 this location shows the processor MPLAB is currently configured for PC Program Counter This shows the code line of code you are currently executed. W The value of the W register Have the students single-step through that code. What happens to W and PC?

63

Adding a Watch Window


Click on

View Watch

0x20

2005 Microchip Technology Incorporated. All Rights Reserved.

Mechatronics Workshop-in-a-Box

Slide 64

We are moving W to address 0x20. Wed like to see the current state of address 0x20. This can be done by creating a watch window. Create a watch window: Choose View -> Watch In the address column type in 0x20 Optional: In the symbol name column type WREG Let the students single step through the code and see how the instructions work. Show them what happens when they click animate.

64

Cycle #2: What Did I Learn?


W Register Create a .asm file Quickbuild MPLAB SIM step, animate Watch window Status bar Three instructions One assembler directive
2005 Microchip Technology Incorporated. All Rights Reserved. Mechatronics Workshop-in-a-Box Slide 65

In Cycle #2 you learned: About the working register How to create and .asm file How to quickbuild How to use Simulator What a watch window is What the status bar tells you Three instructions movwf, addlw, goto One assembler directive end

65

Agenda
Introduction to Microchip Mechatronics examples and benefits PIC Microcontroller Basics
- Hands-On Learning Cycles Cycle #3

Labs
- Simple I/O and Timer 0 - Reading an analog sensor, LCD module - Controlling the speed of a motor

Resources
2005 Microchip Technology Incorporated. All Rights Reserved. Mechatronics Workshop-in-a-Box Slide 66

Now for cycle #3.

66

Architecture: Overview

Program Memory

Data Memory

Special Features

I/O Ports

2005 Microchip Technology Incorporated. All Rights Reserved.

Mechatronics Workshop-in-a-Box

Slide 67

The Input/Output ports are what enable the microcontroller to receive inputs and output signals. These ports are how the microcontroller interacts with the world around it.

67

I/O Ports: PORTA Register

PORTA 0x05

RA7
2005 Microchip Technology Incorporated. All Rights Reserved. Mechatronics Workshop-in-a-Box

RA0
Slide 68

PORTA is an 8-bit register that controls the state of pins RA0 through RA7. Look at the PICDEM Mechatronics board. Near the top left corner of the PIC16F917 youll see pins labeled RA0, RA1, etc. The state of these pins is controlled by PORTA. On this slide everything in the dashed box is inside the PIC microcontroller. Everything outside this box represents what is outside the microcontroller, namely the pins. PORTA is memory location 0x05.

68

I/O Ports: PORTA Register

1 0 0 0 0 1 1 1

5V 0V
2005 Microchip Technology Incorporated. All Rights Reserved. Mechatronics Workshop-in-a-Box Slide 69

This slide shows the state of RA7 through RA0. Starting with RA7 the pins are at 5V, 0V, 0V, 0V, 0V, 5V, 5V, and 5V. As you can see PORTA is equal to a binary number: 10000111.

RA7

RA0

69

I/O Ports: TRISA Register

TRISA 0x85

RA7
2005 Microchip Technology Incorporated. All Rights Reserved. Mechatronics Workshop-in-a-Box

RA0
Slide 70

TRISA is an 8-bit register (memory location 0x85) that controls the direction of each pin in Port A. In other words, TRISA determines whether a pin is either an output or an input. A pin is an input if the corresponding bit in TRISA is a 1. A pin is an output if the corresponding bit in TRISA is a 0. This is easy to remember because 0 looks like O for output. 1 looks like I for input. If a pin is an output then you have control over the state of the pin by setting or clearing the corresponding bit in PORTA. If a pin is an input then you can only read the state of the pin in PORTA. Manipulating a input pin is not possible.

70

I/O Ports: TRISA Register

0 0 0 1 0 1 1 0

RA7
2005 Microchip Technology Incorporated. All Rights Reserved. Mechatronics Workshop-in-a-Box

RA0
Slide 71

This slide shows the TRISA register and the correlation to an input or output pin. If TRISA is set as show here which pins do you have control over?

71

I/O Ports: Port D


PORTD: 8-bit I/O port PORTD is actually data memory 0x08 TRISD: 8-bit direction control register TRISD is actually data memory 0x88

2005 Microchip Technology Incorporated. All Rights Reserved.

Mechatronics Workshop-in-a-Box

Slide 72

Weve talked about Port A. As you can see there are more Ports on the PIC16F917, according to the labels next to microcontroller on the PICDEM Mechatronics Board. PORT D is another 8-bit I/O port. PORTD is memory location 0x08. The direction control register is TRISD and it is data memory 0x88.

72

Hands-on with MPLAB IDE

MPLAB IDE

2005 Microchip Technology Incorporated. All Rights Reserved.

Mechatronics Workshop-in-a-Box

Slide 73

Lets do another hand-on. In this hands-on we will write code to make PORT D all outputs and turn on and off all the pins in this port. Well use the simulator and a watch window to check to see if our source code is actually doing what it should.

73

Code Round 3
Change your code to

movlw b00000000 movwf 0x08 movlw b11111111 movwf 0x08 goto 0


Quickbuild Change the Watch address to 8
2005 Microchip Technology Incorporated. All Rights Reserved. Mechatronics Workshop-in-a-Box Slide 74

Change the code in h1.asm to this. Dont forget the end directive at the end of the code. Choose Project -> Quickbuild Change the Watch address to 8 (Note the symbol name shown next to the address)

74

Stepping Through the Code


Do a Window Tile Horizontally Use F7 to Single-Step through the code

movlw movwf movlw movwf


goto 0
2005 Microchip Technology Incorporated. All Rights Reserved.

b00000000 0x08 b11111111 0x08


Slide 75

Mechatronics Workshop-in-a-Box

Tile the Windows horizontally by choosing Window -> Tile horizontally Single step through the code using F7. What should the code be doing? (Loading PORTD with 0 and then loading PORTD with 0xFF) What is the code doing? (PORTD never changes.) Why isnt the code doing what it is supposed to?

75

PORTD Direction Control


Add TRISD (0x88) to your Watch PORTD is all inputs! Set TRISD to all outputs (zeros)

2005 Microchip Technology Incorporated. All Rights Reserved.

Mechatronics Workshop-in-a-Box

Slide 76

Lets take a look at the Direction control register, TRISD. Add TRISD to your watch window. What is it. TRISD is all 1s. Remember a binary 1 means a pin in an input. PORTD is all inputs according to the TRISD register. We have to make TRISD all outputs (zeros). Lets do that in the code.

76

TRISD - Direction Control


Add this line to the top of your code

clrf 0x88 ; clear TRISD


Build, single-step Can you see TRISD being cleared?

2005 Microchip Technology Incorporated. All Rights Reserved.

Mechatronics Workshop-in-a-Box

Slide 77

Add the line of code to the top of you code. Any guesses as to what the clrf (clear file) command does? Our intention is to make all the 1s in TRISD all 0s. We could use the movlw command to move 0 into W and then the movwf to move W into TRISD. However, the clrf (clear file) register allows us to do this in one instruction rather than two. Build, single-step Is TRISD all zeros? (No.)

77

Why doesnt TRISD clear?


Lets revisit data memory

2005 Microchip Technology Incorporated. All Rights Reserved.

Mechatronics Workshop-in-a-Box

Slide 78

Why doesnt TRISD clear? TRANSTITION: The reason TRISD is not being cleared requires us to learn a little more about PIC microcontroller architecture.

78

Architecture: Overview

Program Memory

Data Memory

Special Features

I/O Ports

2005 Microchip Technology Incorporated. All Rights Reserved.

Mechatronics Workshop-in-a-Box

Slide 79

Lets look more closely at how instructions operate on data memory.

79

Accessing Data Memory

Data Memory

clrf 0x88

2005 Microchip Technology Incorporated. All Rights Reserved.

Mechatronics Workshop-in-a-Box

Slide 80

Again, our intention is to clear data memory location 0x88 or the TRISD register.

80

Architecture: Data Memory

Address

Data Memory

clrf 0x88

2005 Microchip Technology Incorporated. All Rights Reserved.

Mechatronics Workshop-in-a-Box

Slide 81

What youve probably figured out is that 0x88 is actually a data memory address. When we use clrf 0x88 we expect address 0x88 to be cleared.

81

Architecture: Data Memory


2 Data Memory

3<6:5>

Address

clrf b10001000

2005 Microchip Technology Incorporated. All Rights Reserved.

Mechatronics Workshop-in-a-Box

Slide 82

What I didnt tell you before is that you can only specify the first 7-bits of an address after an instruction. That why clearing 0x88 didnt change TRISD. 0x88 is shown here as a binary number. The bit in red is out of the range of the instruction to operate on. With 512 bytes of data memory, we need 9-bits of addressing. These two other bits are in register 3, bits 5 and 6.

82

Architecture: Data Memory


3,6 3,5

00

01

10

11

Bank 0 Bank 1 Bank 2 Bank 3 0-7F 80-FF 100-17F 180-1FF 00xxxxxxx 01xxxxxxx 10xxxxxxx 11xxxxxxx

2005 Microchip Technology Incorporated. All Rights Reserved.

Mechatronics Workshop-in-a-Box

Slide 83

This effectively splits the memory into 4 banks. An instruction will reference Bank0 when bits 5 and 6 of register 3 are zero. An instruction will reference Bank1 when 3,6 is 0 and 3,5 is 1. When 3,6 is a 1 and 3,5 is a 0 an instruction will reference Bank 2. Finally, when both bits are set, an instruction will address registers in Bank3.

83

Architecture: Data Memory

00

01
88

10

11

Bank 0 Bank 1 Bank 2 Bank 3 0-7F 80-FF 100-17F 180-1FF 00xxxxxxx 01xxxxxxx 10xxxxxxx 11xxxxxxx

2005 Microchip Technology Incorporated. All Rights Reserved.

Mechatronics Workshop-in-a-Box

Slide 84

TRISD, or data memory address 0x88, is clearly in Bank 1 as seen in this diagram.

84

Architecture: Bank 1 Select

00

01 bsf 3,5

Bank 0 Bank 1 0-7F 80-FF 00xxxxxxx 01xxxxxxx

2005 Microchip Technology Incorporated. All Rights Reserved.

Mechatronics Workshop-in-a-Box

Slide 85

Therefore, if we want an instruction to address TRISD we have to first set the 3,5 bit. We use the bsf or bit set file instruction to set a bit in a file register.

85

Architecture: TRISD

00

01
88

Bank 0 Bank 1 0-7F 80-FF 00xxxxxxx 01xxxxxxx

bsf 3,5 clrf 0x88

2005 Microchip Technology Incorporated. All Rights Reserved.

Mechatronics Workshop-in-a-Box

Slide 86

Once we are in bank1, we can clear TRISD. We can enter clrf 0x88.

86

Architecture: Bank 0 Select

00
8

01 bsf 3,5 clrf 0x88 ????

Bank 0 Bank 1 0-7F 80-FF 00xxxxxxx 01xxxxxxx

2005 Microchip Technology Incorporated. All Rights Reserved.

Mechatronics Workshop-in-a-Box

Slide 87

Once we are done setting up the TRISD register, we want to be able to manipulate PORTD, or address 8. What do we need to do to return to Bank0?

87

TRISD - Direction Control


Our final code

bsf 3,5 clrf 0x88 bcf 3,5 movlw b00000000 movwf 0x08 movlw b11111111 movwf 0x08 goto 3
2005 Microchip Technology Incorporated. All Rights Reserved. Mechatronics Workshop-in-a-Box Slide 88

The answer is, clear bit 3,5. This is done with the bcf instruction. Modify the your code as shown on this slide. Refer to the handout for comments about what each line of code is doing. Step through the code. Is TRISD being set appropriately? What is happening to PORTD?

88

Symbol Name and File Register Correlation


bsf 3,5 clrf 8 bcf 3,5 movlw 0 movwf 8 movlw 0xff movwf 8 goto 3
2005 Microchip Technology Incorporated. All Rights Reserved.

include <p16f917.inc> bsf STATUS,RP0 clrf TRISD bcf STATUS,RP0 Loop movlw 0 movwf PORTD movlw 0xff movwf PORTD goto Loop
Mechatronics Workshop-in-a-Box Slide 89

Remembering the address of every register would be hard to do. Fortunately, you can include a file with all the symbol names defined for a given part. This allows you to address addresses by name rather than number. Add include <p16f917.inc> to the top of the code. After the 3rd instruction add the label Loop. Change the goto 3 instruction to goto Loop. You may have made the connection that the microcontroller manipulates numbers. In order to make these numbers easier for a human to work with, specific addresses are given names that represent what that address is responsible for. Youll also notice by the changes to the code that register 3 is the STATUS register. Well learn more about some of the other bits in the STATUS register later. One important note regarding symbol names and labels They are case sensitive! The compiler will interpret PORTD and portd differently. The same goes for Loop and LOOP.

89

Cycle #3: What Did I Learn?


PORTx Registers TRISx Registers Banking STATUS register, bits RP0 & RP1 Symbol name and number correlation Four instructions One assembler directive
2005 Microchip Technology Incorporated. All Rights Reserved. Mechatronics Workshop-in-a-Box Slide 90

Review Cycle #3 PORTx PORTx Banking STATUS bits RP0 and RP1 Symbol name and number correlation 4 instructions: bsf, bcf, clrf, movlw One assembler directive: include

90

Agenda
Introduction to Microchip Mechatronics examples and benefits PIC Microcontroller Basics
- Hands-On Learning Cycles Cycle #4

Labs
- Simple I/O and Timer 0 - Reading an analog sensor, LCD module - Controlling the speed of a motor

Resources
2005 Microchip Technology Incorporated. All Rights Reserved. Mechatronics Workshop-in-a-Box Slide 91

Up until now, weve been working will the simulator. In cycle #4, we are actually going to make the PIC16F917 interact with the physical world.

91

Architecture: Overview

Program Memory

Data Memory

Special Features

I/O Ports

2005 Microchip Technology Incorporated. All Rights Reserved.

Mechatronics Workshop-in-a-Box

Slide 92

We will be doing this with the I/O ports that you were introduced to in cycle #4.

92

Introduction to the PICDEM Mechatronics Board

2005 Microchip Technology Incorporated. All Rights Reserved.

Mechatronics Workshop-in-a-Box

Slide 93

The PICDEM Mechatronics Boards that you purchased for this workshop will be the vehicle that we use to experiment with the PIC16F917. It will allow you to see the microcontroller working. In cycle #4 we will be using the PICDEM mechatronics board to observe firmware reading and manipulating the digital I/O pins. A few things you should know about the board are: We are going to power the board from a 9V, 0.75 supply The on-board regulator drops the voltage on the board to 5V What all this means is that, this board will not electrocute you! TRANSISION: First, we need to connect the microcontroller on the PICDEM Mechatronic board to some of the surrounding components.

93

Connect the Hardware

2005 Microchip Technology Incorporated. All Rights Reserved.

Mechatronics Workshop-in-a-Box

Slide 94

Lets configure the board for our next hands on. For cycle#4 we will set up one input. The input will be a tactile switch connected to RA4. PORTD will be all outputs. We are going to attach each pin in PORT D to an LED. This essentially gives us a visual binary representation of PORTD. The student handout contains the wiring diagram shown on this slide. Using Jumper wires connect: SW2 (J4) to RA4 (J13) D0 (J14) to RD7 (J10) D1 (J14) to RD6 (J10) D2 (J14) to RD5 (J10) D3 (J14) to RD4 (J10) D4 (J14) to RD3 (J10) D5 (J14) to RD2 (J10) D6 (J14) to RD1 (J13) D7 (J14) to RD2 (J13)

94

Connecting the ICD 2 and Power

J9

J11
ICD2

USB

2005 Microchip Technology Incorporated. All Rights Reserved.

Mechatronics Workshop-in-a-Box

Slide 95

Next, we need to connect the PICDEM Mechatronics Board to power and the MPLAB ICD 2 Connect the power supply to J9 Connect the ICD 2 to J11 Connect the USB cord to the ICD 2

95

Introduction to the MPLAB ICD 2


MPLAB ICD 2 is an In-circuit Debugger and Programmer Debug mode:
- Find out why your program isnt doing what you expect it to do - Look at the data memory - Step through the code - Set break points

Program mode:
- Program a device
2005 Microchip Technology Incorporated. All Rights Reserved. Mechatronics Workshop-in-a-Box Slide 96

What is the MPLAB ICD 2? The MPLAB ICD 2 is an in-circuit debugger. An in-circuit debugger allows you to: Debug the code by allowing you to stop the part and step through your code. While stepping the debugger uploads critical registers from the microcontroller and displays these registers in the MPLAB IDE. This allows you to see what the part is doing and find why it isnt working as suspected. In other words, the debugger does what the simulator did only it does it using actual hardware and the device. Program a device

96

Hands-on with MPLAB IDE

MPLAB IDE

2005 Microchip Technology Incorporated. All Rights Reserved.

Mechatronics Workshop-in-a-Box

Slide 97

Now we are going to finally make the PIC16F917 interact with the outside world.

97

Create a Project In MPLAB IDE

2005 Microchip Technology Incorporated. All Rights Reserved.

Mechatronics Workshop-in-a-Box

Slide 98

Lets first create and save a project in MPLAB IDE. The benefits of creating a project are: The project window gives you easy access to the file or files in you project You can link more than one file together at build time. Well look at this more later in the labs The advantage you will see now is that we can build at the touch of a button rather than choosing quickbuild Once in MPLAB IDE click on Project in the menu bar and select the Project Wizard. The project wizard helps you create a project very quickly.

98

Creating a Project Continued


Select the PIC16F917, click Next Choose the Microchip MPASM Toolsuite, click Next Create a project name of test Save in C:\, click Next Add h1.asm to the project, click Next Click Finish
2005 Microchip Technology Incorporated. All Rights Reserved. Mechatronics Workshop-in-a-Box Slide 99

Follow these steps to finish creating a project

99

Save Workspace

Save the Workspace as test in C:\

2005 Microchip Technology Incorporated. All Rights Reserved.

Mechatronics Workshop-in-a-Box

Slide 100

MPLAB IDE may automatically prompt you to save the workspace. If it doesnt, click on File -> Save Workspace As Next, find the c:\ and save the workspace as test. Benefits of a Workspace A workspace saves your MPLAB environment so that the next time you want to work on a specific project you can pick up right where you left off. Saves the configuration bits

100

Opening Source Files


The project window contains the source, include, and linker files Double-click on the file names to open (or focus on) the desired file Right-click on Source Files to add source files Remove files by rightclicking on them and choosing Remove
2005 Microchip Technology Incorporated. All Rights Reserved. Mechatronics Workshop-in-a-Box Slide 101

The project window now shows the name of the workspace, the project name, and the files included in the project. Use this window to add source, include and linker files. Opening a file in projects is as easy as double-clicking on a file name. Use the project window to add and delete files for a project. In our case, we only have one file. Later on, however, youll be working with projects with more than one source file.

101

ICD 2 Setup
Debugger - Select Tool - 1 MPLAB ICD-2 Debugger - Connect Configuration - Configuration Bits

2005 Microchip Technology Incorporated. All Rights Reserved.

Mechatronics Workshop-in-a-Box

Slide 102

Lets select the ICD 2 as our debugger in MPLAB. Select ICD 2 as debugging tool: Debugger -> Select Tool -> 1 MPLAB ICD-2 Connect to the ICD-2: Debugger -> Connect Setup Configuration bits: Configuration Configuration Bits Oscillator equal Watchdog Timer Power Up Timer INTOSC off on

(The rest can remain in the default state) Configuration bits do exactly what the name implies they configure the microcontroller. For the PIC16F917, there are 14 configuration bits. These bits set up the clock source for the microcontroller, turn on the watchdog timer, etc. The configuration bits can not be changed during runtime. In order words you have to reprogram the part to re-configure these bits.

102

Cycle #4: Write the Source Code


include bsf clrf bsf bcf Loop btfsc goto incf goto <p16f917.inc> STATUS,RP0 TRISD TRISA,4 STATUS,RP0 PORTA,4 Loop PORTD,f Loop
Mechatronics Workshop-in-a-Box Slide 103

2005 Microchip Technology Incorporated. All Rights Reserved.

Type in the source code shown

103

Building and Programming


In a project the build command is F10.
(Do this now!)

Once the source code is built it must be programmed into the PIC16F917 To program a device click on:

You must build and program after every change to your source code!
2005 Microchip Technology Incorporated. All Rights Reserved. Mechatronics Workshop-in-a-Box Slide 104

The build command in a project is Project -> Make, or the F10 key. Use F10 to build the project now. Use this method rather than Quickbuild when working with a project. We are now using the ICD 2 and not the simulator. This means we have to transfer the code to the PIC16F917 before running the device. Use the indicated icon to program the PIC16F917. Keep in mind that every time you make a change to your code you will have to build the source code and then program the PIC microcontroller before running.

104

Watching the Source Run


Create a Watch window Watch PORTD and PORTA Click the Animate button What happens when you press SW2?

2005 Microchip Technology Incorporated. All Rights Reserved.

Mechatronics Workshop-in-a-Box

Slide 105

Were almost there! Create a watch window that watches PORTD and PORTA Click the animate button Watch the program flow pointer in the h1.asm file. Press SW2. What happens to the program flow pointer. Look at PORTA in the watch window while pressing and releasing SW2. What happens to bit 4? (Other bits might change. These bits are floating and are electrostatically influenced by RA4. Use a jumper wire to connect the changing pin to Vss. The pin will no longer change.) With SW2 pressed look at PORTD in the Watch window. Look at the LEDs. See any correlation?

105

Cycle #4: What Did I Learn?


Set up the PICDEM Mechatronics Board Configured the MPLAB ICD 2 Created a Project Saved a Workspace Built a project Programmed the PIC16F917 Ran code using the MPLAB ICD 2
2005 Microchip Technology Incorporated. All Rights Reserved. Mechatronics Workshop-in-a-Box Slide 106

Review Cycle #4

106

Agenda
Introduction to Microchip Mechatronics examples and benefits PIC Microcontroller Basics
- Hands-On Learning Cycles

Labs
- Simple I/O and Timer 0 - Reading an analog sensor, LCD module - Controlling the speed of a motor

Resources
2005 Microchip Technology Incorporated. All Rights Reserved. Mechatronics Workshop-in-a-Box Slide 107

Now were going to start working on the labs.

107

Lab Introduction
Problem: Management wants you to design a cooling fan for an electronics bay in the new Mars Rover

2005 Microchip Technology Incorporated. All Rights Reserved.

Mechatronics Workshop-in-a-Box

Slide 108

All of our labs will focus on solving this problem: Management wants you to create a cooling fan for an electronics bay in the new Mars Rover. The labs will all focus on solving this problem. The labs will be very basic and then gradually get more and more complex

108

Agenda
Introduction to Microchip Mechatronics examples and benefits PIC Microcontroller Basics
- Hands-On Learning Cycles

Labs
- Simple I/O and Timer 0 - Reading an analog sensor, LCD module - Controlling the speed of a motor LAB 1

Resources
2005 Microchip Technology Incorporated. All Rights Reserved. Mechatronics Workshop-in-a-Box Slide 109

The purpose of Lab 1 is to use the knowledge youve just learned in PIC Microcontroller Basics to perform the specific task. You will be introduced to Timer 0 in this lab. Lets take a look at our design objectives for this Lab.

109

Lab 1: Design Objectives


Read the state of a thermal breaker Turn on the fan when the breaker trips When the breaker resets, wait 2 seconds, then turn off fan

Thermal Breaker
2005 Microchip Technology Incorporated. All Rights Reserved.

PIC16F917 Fan
Mechatronics Workshop-in-a-Box Slide 110

In Lab 1 we will be creating a very simple system. We will be using a PIC16F917 to read a thermal breaker output. When the thermal breaker trips we will turn on the fan. Now, in order to up the complexity of this system a little and make putting a PIC microcontroller in it worthwhile, management has mandated that when the breaker resets, the fan should cool for another two seconds before shutting down.

110

Lab 1: Hardware
We will use a tactile switch on the board to simulate the thermal breaker The Brushed DC motor will substitute for the fan For the PIC16F917 . . . . well well use that!
SW2

Tactile Switch

PIC16F917
Mechatronics Workshop-in-a-Box

Brushed DC motor
Slide 111

2005 Microchip Technology Incorporated. All Rights Reserved.

For the lab we will be using other components on the PICDEM Mechatronics Board to simulate our hardware requirements. SW2 is a tactile switch. The output from SW2 is normally high (meaning at 5V DC). When the button is pressed, its output becomes low (ground or 0 V). We will use SW2 high to simulate a breaker operating normally. SW2 low will simulate the breaker being tripped The substitution for the fan is the brushed DC motor on the PICDEM Mechatronics Board. This is relatively realistic substitution as if we put a fan blade on the motor it would cool! However, since we didnt want anybody to lose their fingers we didnt include a fan blade. The PIC16F917 will be taking the role of itself in this lab TRANSITION: Lets set up our hardware first.

111

Lab 1: Schematic
+5V +5V R1 RA4 SW2 RD7 MOSFET N2 Motor

PIC16F917 D0

2005 Microchip Technology Incorporated. All Rights Reserved.

Mechatronics Workshop-in-a-Box

Slide 112

Here is a simplified schematic of the system we need to create for this lab. The line tying Switch 2 to the microcontroller is tied to +5V via a pull-up resistor,R1. When SW2 is depressed the line is grounded. This changes the state of the input pin from a 1 to a 0. RD7 is our output. When RD7 is a logic 0, or at ground potential, the MOSFET will be open and the LED off. The motor will not run when the MOSFET is open. When RD7 is a logic 1, or at +5V, the MOSFET will close, causing the motor to turn on. A MOSFET is a solid-state switch that is open or closed based the input at its gate. For simplicity its shown in this schematic as a switch. D0 is a LED that weve also hooked up for this lab. If you get tired of the motor running on your desk you can connect just D0. D0 will give a visual representation of the drive control to the motor. The lines in red show the connections you will be making on the PICDEM Mechatronics board. Lets make those connections now.

112

Lab 1: Connection Diagram

RD7,D0 RD7,N2 RA4,SW2 Vdd,P1

2005 Microchip Technology Incorporated. All Rights Reserved.

Mechatronics Workshop-in-a-Box

Slide 113

Now we are going to hook up the board like I just described. First, connect a wire jumper between SW2 on J4 and RA4 on J13. J4 and J13 as well as other headers on the board have horizontal pins connected together. This is so that you can jumper from a peripheral device to the microcontroller and also from the peripheral device to a piece of test equipment or LED. Connect a wire jumper between VDD (J10) and P1 (J1). Connect a wire jumper between RD7 (J10) and D0 (J14). We will use the LED to visually check the state of RD7 Connect a wire jumper between RD7 (J10) and N2 (J1)

113

Lab 1: Connection Diagram

JP8: Center and Right using shunt

2005 Microchip Technology Incorporated. All Rights Reserved.

Mechatronics Workshop-in-a-Box

Slide 114

Inspect your board for 2 pin jumpers, or shunts. The only shunt on the board will be connecting +5 VDC to our output stage (JP8). Make sure the shunt is connecting the middle and right pin. Connect one lead of the brushed DC motor to the screw terminal labeled DRIVE 1 Connect the other lead of the brushed DC motor to the screw terminal label DRIVE 2

114

Timer 0
8-bit timer It continuously runs Overflow flag: INTCON,T0IF
Example: Timer 0
11111110 11111111 00000000
2005 Microchip Technology Incorporated. All Rights Reserved. Mechatronics Workshop-in-a-Box

INTCON,T0IF
0 0 1
Slide 115

In order to make the 2 second timer required for this lab you need to first learn about Timer 0. Timer 0 will facilitate in helping us easily create a 2 second timer. Timer 0 is and 8-bit timer. It continuously runs. When Timer overflows (goes from 255 to 0) the INTCON,T0IF flag is set. This flag remains set until you clear it in software. The example shows Timer 0 just before and after overflowing. Note that as Timer 0 transitions from 255 to 0 the Timer 0 overflow flag is set

115

Timer 0 Prescaler
Timer 0 normally counts at the rate instructions are executed Timer 0 can be scaled using a prescaler Timer 0 will count once every P instructions, where P is the prescaler Prescaler: OPTION_REG<2:0>

2005 Microchip Technology Incorporated. All Rights Reserved.

Mechatronics Workshop-in-a-Box

Slide 116

Timer 0 normally will count at the same rate as the microcontroller executes instructions. This can be changed by modifying the Timer 0 prescaler. The prescaler slows Timer 0 down. Timer 0 will count up one every P instructions, where P is the prescaler The prescaler is located in bits 0 to 2 of the OPTION register.

116

Timer 0 Hands-On
include Counter Loop btfss goto bcf incf goto end <p16f917.inc> equ 0x20 INTCON,T0IF Loop INTCON,T0IF Counter,f Loop
Mechatronics Workshop-in-a-Box Slide 117

Create in h1.asm in the test workspace

2005 Microchip Technology Incorporated. All Rights Reserved.

Lets see how Timer 0 works. 1. Change the code in h1.asm to this.

117

Set Animate Step Interval


Choose Debugger Select Tool MPLAB SIM Choose Debugger Settings Click on the Animation/Realtime Updates tab Change the Animate Step Time to 10 ms

10
2005 Microchip Technology Incorporated. All Rights Reserved. Mechatronics Workshop-in-a-Box Slide 118

We need to speed up the timer interval of the simulator animate function for this hands-on. Follow these steps to set the simulator animate time interval: 1. Choose Debugger > Select Tool > MPLAB SIM 2. Choose Debugger > Settings 3. Click on the Animation/Realtime Updates Tab 4. Change the Animate Step Time to 10 msecs.

118

Build and Watch


Build the project by pressing F10 Create a Watch Window Watch TMR0, OPTION_REG, and Counter Enter 0 in the value for OPTION_REG
(The prescaler is now 1:2, Timer 0 will count every 2 instructions)

Choose Debugger Animate


2005 Microchip Technology Incorporated. All Rights Reserved. Mechatronics Workshop-in-a-Box Slide 119

Were almost ready to see Timer 0 working Build your project by pressing F10. Now create a watch window. In symbol name enter TMR0, OPTION_REG, and Counter. Enter a value of zero for the OPTION_REG. The prescaler for TMR0 is now 1:2. This means TMR0 will increment every 2 instructions. Choose Debugger>>Animate.

119

Watch Window

Enter values between 0 and 7 in OPTION_REG


2005 Microchip Technology Incorporated. All Rights Reserved. Mechatronics Workshop-in-a-Box Slide 120

Your watch window should look like this. What happens to Counter when TMR0 goes from 255 to 0? Have the students enter values into OPTION_REG between 0 and 7. What happens to the speed that TMR0 increments?

120

Relationship between Timer 0 and Instruction Cycle time


OPTION_REG bits 0 - 2 0 1 2 3 4 5 6 7
2005 Microchip Technology Incorporated. All Rights Reserved.

Instructions per one Timer 0 count 2 4 8 16 32 64 128 256


Mechatronics Workshop-in-a-Box

Rollover (4MHz) 512 s 1.02 ms 2.05 ms 4.10 ms 8.20 ms 16.4 ms 32.8 ms 65.5 ms
Slide 121

You noticed that Timer 0 slows down when you increase the value in bits 0-2 of the OPTION_REG. Timer 0 without any prescaler would normally count at the same rate as the microcontroller executes instructions. The microcontroller defaults to the 4MHz internal clock. The instruction cycle frequency is of this or 1 MHz. This means one instruction is executed every 1us. With a prescaler of 1:2 Timer 0 will count once every 2 instructions, or 2 us. You can see by this chart that TMR0 will overflow every 512 us with a 1:2 prescaler. With the prescaler at its maximum, Timer 0 will overflow every 65.5ms. If you recall, our objective in this Lab is to create a 2 second delay between the time SW2 is released and the time we shut off the motor.

121

Relationship between Timer 0 and Instruction Cycle time


OPTION_REG bits 0 - 2 Instructions per one Timer 0 count 0 2 1 4 2 How many times must8 Timer 0 3 16 of 1:256 overflow with a prescaler 4 before 2 seconds has32 passed? 5 64 6 128 7 256
Mechatronics Workshop-in-a-Box

Rollover (4MHz) 512 s 1.02 ms 2.05 ms 4.10 ms 8.20 ms 16.4 ms 32.8 ms 65.5 ms
Slide 122

2005 Microchip Technology Incorporated. All Rights Reserved.

Key Question: If we set up Timer 0 so that it will overflow every 65.5ms, how many times will Timer 0 overflow in 2 seconds? (Answer is approximately 30.)

122

decfsz Instruction
clrf TMR0 movlw .30 movwf Counter Loop btfss INTCON,T0IF goto Loop bcf INTCON,T0IF decfsz Counter,f goto Loop end
2005 Microchip Technology Incorporated. All Rights Reserved.

Enter this code after: Counter equ 0x20

Mechatronics Workshop-in-a-Box

Slide 123

We need some way to detect when Timer 0 has overflowed 30 times. The decfsz instruction allows us to do this fairly easily. The decfsz instruction decrements a register. If the register is zero, then the next instruction is skipped. After the Counter equ 0x20 line, change your code to what is on this screen.

123

Setup the Simulator Processor Frequency Debugger Settings Click on the Osc/Trace Tab Set the Processor Frequency to 4 MHz

2005 Microchip Technology Incorporated. All Rights Reserved.

Mechatronics Workshop-in-a-Box

Slide 124

In order to see how accurate our 2 second timer is we have to set the simulator processor frequency to the default processor speed of the PIC16F917, or 4 MHz. Go To the simulator settings menu (Debugger > Settings) Click on the Osc/Trace Tab Set the Processor Frequency to 4 MHz.

124

The MPLAB Stopwatch


Debugger Stopwatch Build the Project Change the OPTION_REG value to 7 in the watch window Run the simulator

2005 Microchip Technology Incorporated. All Rights Reserved.

Mechatronics Workshop-in-a-Box

Slide 125

Now lets see how well our 2 second timer works. 1. Under Debugger select Stopwatch. 2. Build the project. 3. In the watch window change the OPTION_REG value to 0x07. This sets the prescaler to 1:256 and causes Timer 0 to overflow every 65.5 ms. 4. Run the simulator

125

The MPLAB Stopwatch

2005 Microchip Technology Incorporated. All Rights Reserved.

Mechatronics Workshop-in-a-Box

Slide 126

The stopwatch will stop on the end statement. What is the stopwatch time? (The time should be 1.99 seconds.) If you run the project again dont forget to hit reset and then change OPTION_REG to 0x07.

126

Timer 0 Review
Timer 0 is an ____ - bit Timer. The prescaler for Timer 0 is in the _______ register. Increasing the prescaler speeds up or slows down Timer 0? The ______ instruction is great for counting down the number of Timer 0 overflows.

2005 Microchip Technology Incorporated. All Rights Reserved.

Mechatronics Workshop-in-a-Box

Slide 127

Review Timer 0 with the students: Answers: 1. 8 2. OPTION_REG 3. Slows down 4. Decfsz

127

Lab 1: Design Objectives Review


Read the state of SW2 (Thermal Breaker) When SW2 is pressed turn on the brushed DC motor (Fan) When SW2 is released, wait 2 seconds, then turn off the motor

2005 Microchip Technology Incorporated. All Rights Reserved.

Mechatronics Workshop-in-a-Box

Slide 128

We now have all the tools we need to write the code for Lab 1. We can read an input, manipulate an output and use Timer 0 to generate a delay. Lets go over our design objectives again. Recall that we are using SW2 to simulate a thermal breaker. So first we have to read SW2. When SW2 is pressed, simulating the breaker tripping, we turn on the brushed DC motor (or fan.) When SW2 is released, simulating the breaker resetting, wait 2 seconds and turn the motor off.

128

Converting Design Objectives to Program States

Initialize State 1

State 2
2005 Microchip Technology Incorporated. All Rights Reserved. Mechatronics Workshop-in-a-Box

State 3
Slide 129

We can interpret these design objectives into program states. States are code segments that do a particular task. The program flow stays in a state until a certain condition is met. This slide shows a simple program with an Initialize routine and three states. Breaking your code into states allows you to structure your code in a easy to follow manner. Lets look at the program states for Lab 1 to illustrate this point.

129

Lab 1: Your Task


Initialize I/O and TMR0

Initialize State 1
Motor Off, Check for Button Pressed

State 2
2005 Microchip Technology Incorporated. All Rights Reserved. Mechatronics Workshop-in-a-Box

Motor On, Check for Button Not Pressed

Wait 2 State 3 Seconds

Slide 130

This slide illustrates the key code segments for Lab 1. First, the source code initializes the PIC microcontroller. This includes defining input and output pins, initializing variables, and setting up the prescaler for TMR0. Then the different operation states are implemented. In Lab 1 we have three states: State 1: The motor is off and the part is waiting for a button press State 2: A button press was received, turn on the motor, wait for button release State 3: The button has been released, wait for two seconds and return to State 1 The microcontroller will remain in each state until a certain condition is met and then migrate to the next state. What is the condition that must be met in order to move from State 1 to State 2? State 2 to State 3? State 3 to State 1? Breaking your application down into its various states and sub-states makes your code logical and easy to follow. Each of these states have at least one conditional statement. The code remains in a state until one of the conditions is met and then the program flow moves to another state. The states in this lab are fairly straight forward. Lets look at each of these states individually. 130

State 1: Wait for Button Press


Turn off Motor

PORTD,7 = 0

Is SW2 Pressed?

No

PORTA,4
Yes

State 2

2005 Microchip Technology Incorporated. All Rights Reserved.

Mechatronics Workshop-in-a-Box

Slide 131

In state 1 you turn off the motor and look for a button press. RD7 is the output pin controlling the motor. We turn this off. RA4 is the Switch input. If RA4 is low then the button has been pressed and move to state 2. If the button is high then continue looping in State 1. Key Question: What would be a good instruction to use when checking the state of RA4. (Answer: btfsc This instruction will skip the next instruction if RA4 is set.)

131

State 2: Wait for Button Release


Turn on Motor

PORTD,7 = 1

Is SW2 Released?

No

PORTA,4
Yes

State 3

2005 Microchip Technology Incorporated. All Rights Reserved.

Mechatronics Workshop-in-a-Box

Slide 132

State 2 does just the opposite of State 1. We turn the motor on and then wait for SW2 to be released. RA4 will be 1 when the switch is released. Key Question: What would be a good instruction to use for this. (Answer: btfss)

132

State 3: Two Second Delay


You just wrote this code!

2005 Microchip Technology Incorporated. All Rights Reserved.

Mechatronics Workshop-in-a-Box

Slide 133

You should all be familiar with state three as we just wrote the code for this.

133

Lab 1: Implement a Solution


Open the workspace in: C:\Mechatronics WIB\Lab1 Open Lab1.asm in the project folder All I/O ports and the OPTION_REG are initialized for you. Fill in the code for the three states under the corresponding labels. You must press SW5 to enable the drive circuit!
2005 Microchip Technology Incorporated. All Rights Reserved. Mechatronics Workshop-in-a-Box Slide 134

Now its time for you to use everything youve learned to implement the requirements of this Lab 1. The code has been started for you. Open the Lab1 project in the folder shown. Open Lab1.asm in the project folder. The initialization routine sets up the ports and the option register. There are three labels: State 1, State 2 and State 3. Fill in the code below these Labels with the functionality we just described. Make sure you enable the drive circuit on your board by pressing SW5 (near lower right corner of the board.) Go over the solution with the class once youve given them a chance to work on it. The solution is located in the Lab1 folder under the file Lab1solution.asm.

134

Lab 1: Review
New PIC16F917 features and registers
- Timer 0 (TMR0) - OPTION_REG

Tools
- Stopwatch - Simulator: animate interval, processor frequency

Instructions
- decfsz

Concepts
- Programming with states
2005 Microchip Technology Incorporated. All Rights Reserved. Mechatronics Workshop-in-a-Box Slide 135

Review Lab 1

135

Agenda
Introduction to Microchip Mechatronics examples and benefits PIC Microcontroller Basics
- Hands-On Learning Cycles

Labs
- Simple I/O and Timer 0 - Reading an analog sensor, LCD module - Controlling the speed of a motor LAB 2

Resources
2005 Microchip Technology Incorporated. All Rights Reserved. Mechatronics Workshop-in-a-Box Slide 136

In Lab 2 you will learn how to read an analog sensor with the analog-to-digital conversion module.

136

Lab 2: Design Objectives


Read an analog temperature sensor Turn on the fan when the temperature > 40oC Turn off the fan when the temperature <= 40oC Display the temperature

Temperature Sensor
2005 Microchip Technology Incorporated. All Rights Reserved.

PIC16F917 Fan
Mechatronics Workshop-in-a-Box Slide 137

Scenario: Management has come to us and is telling us that the thermal breaker is not a very good solution at it trips over a wide temperature range. Therefore they want to use a precision analog temperature sensor. Here are the new requirements: Read an analog temperature sensor If the temperature in the electronics cooling bay of the Mars Rover is over 40 degrees C then turn on the fan. When the temperature is equal to or below 40 degrees C turn off the fan Display the temperature on the LCD

137

Lab 2: Hardware
A potentiometer on the board will be used to produce the varied output voltage The Brushed DC motor will substitute for the fan The LCD will be used to display the analogto-digital Converter output
POT1

Potentiometer

LCD
Mechatronics Workshop-in-a-Box

Brushed DC motor
Slide 138

2005 Microchip Technology Incorporated. All Rights Reserved.

A potentiometer will be used to simulate the output on the analog temperature sensor. Were doing this because changing the temperature in the room is not an option. A potentiometer outputs an analog voltage level related to the position of the potentiometer. Again, the brushed dc motor will be used for the fan. We will be adding an LCD to this project as well. The LCD will allow you to see the digital interpretation of the analog voltage produced at the potentiometer output.

138

Lab 2: Schematic
+5V +5V Motor POT1 RA0 RD7 MOSFET N2

PIC16F917 D0

2005 Microchip Technology Incorporated. All Rights Reserved.

Mechatronics Workshop-in-a-Box

Slide 139

This is the schematic for Lab 2. Note that a Potentiometer POT1 (on the left side of the screen) is being used in place of SW2. The potentiometer connects to RA0 instead of RA4. You should recall, that the output of SW2 was at either ground potential or +5V. In other words it was a digital signal equivalent to 0 and 1 respectively. A potentiometer in the configuration shown here has an output that is variable between 0 and 5V. This means that the output of the potentiometer will be 2.5V if it is turned of its full range of motion; 1.25V if it is turned of its full range of motor; and so on and so forth. This is an analog output voltage the voltage is variable between 0 and 5V.

139

Lab 2: Connection Diagram

RA0,POT1

2005 Microchip Technology Incorporated. All Rights Reserved.

Mechatronics Workshop-in-a-Box

Slide 140

Set up the board for this lab. This board is configured the same as it was for Lab1 with one exception. Move the jumper wire between RA4 and SW2 to between RA0 and POT1 Remember, if the students would rather not have the motor turn on and off they can remove the jumper wire between RD7 and N2. LED0 (or D0) can be used to simulate the motor.

140

Analog-To-Digital Converter
Converts an analog voltage level into a binary number Resolution: How many different readings are possible
- 8-bit -> 28 -> 256 possible readings - 10-bit -> 210 -> 1024 possible readings

Example: 8-bit resolution over 5 volts:


Voltage resolution = 5V/256 = 19.5 mV per count
2005 Microchip Technology Incorporated. All Rights Reserved. Mechatronics Workshop-in-a-Box Slide 141

We will be using the analog to digital conversion module on the PIC16F917 to read this voltage and display the digital representation of that voltage on the LCD. What an analog-to-digital converter does is it measures an analog voltage, and then based on the resolution of the module converts that voltage into a number. On this slide you can see how many counts are possible for a 8-bit and 10-bit analog to digital module. The analog-to-digital conversion module on the PIC16F917 is a 10-bit module. For simplicity we will be ignoring the least significant 2 bits. In other words we will be using only the highest 8 bits. You can see on this slide that 256 counts are possible in 8-bit mode. Over 5 volts this is 19.5mV per count. In our application, this means that every 19.5mV that the POT1 output increases will be interpreted by the analog to digital converter as one increment.

141

ADC Registers
ANSEL Select analog input pins ADCON1 Select the conversion clock ADCON0 Select analog channel, turn the module on, do the conversion ADRESL Low-byte of conversion value ADRESH High-byte of conversion value
2005 Microchip Technology Incorporated. All Rights Reserved. Mechatronics Workshop-in-a-Box Slide 142

These are the registers associated with the Analog-to-Digital Conversion register. I just want you to be aware that there are several registers associated with this module. In this lab we will be using the default configuration for the analog to digital module therefore we only need to be concerned with the ADCON0 and ADRESH registers. Only ADRESH is needed for the conversion value because we will be using the highest 8 bits of the conversion value.

142

A/D Conversion Steps


1. Turn on the analog module 2. Set GO_DONE bit of ADCON0 3. Wait for GO_DONE bit to be cleared 4. Read A/D result in ADRESH

2005 Microchip Technology Incorporated. All Rights Reserved.

Mechatronics Workshop-in-a-Box

Slide 143

Once the ADC module is setup and turned on there are four basic steps that you need to follow to acquire an ADC reading. These are: 1. Turn the analog module on 2. Set the GO_DONE bit of ADCON0 3. Next, wait for the GO_DONE bit to clear. The microcontroller clears the GO_DONE flag when the a-to-d conversion is completed. Reading the ADC module before this flag is set will result in reading an older value. 4. Finally, read the ADC result in ADRESH.

143

ADC Hands-On
include <p16f917.inc> bsf ADCON0,ADON Create in h1.asm in LoopOuter the test workspace bsf ADCON0,GO_DONE LoopInner btfsc ADCON0,GO_DONE goto LoopInner movf ADRESH,w goto LoopOuter end
2005 Microchip Technology Incorporated. All Rights Reserved. Mechatronics Workshop-in-a-Box Slide 144

Lets look at the ADC module in action. Reopen the test project in the c:\ directory and enter this code into h1.asm

144

Looking at the ADC module


Select the MPLAB ICD 2 as the debugger Create a watch window Add ADRESH to the watch window Build the project Program the MPLAB ICD 2 Click animate What happens to ADRESH when you turn POT1?
2005 Microchip Technology Incorporated. All Rights Reserved. Mechatronics Workshop-in-a-Box Slide 145

1. Choose the ICD-2 as your debugger 2. Create a watch window with ADRESH 3. Click animate Questions to ask: What happens to the ADRESH value when you turn POT1? What voltage does a 0 reading correspond to? (GND) What voltage does a 255 reading correspond to? (Vdd or 5V)

145

ADC Module Review


The analog to digital module converts an ________ into a ________ . The ________ register is used to turn the module on and start an A-to-D conversion. The ________ register contains the high order bits of the ADC value. You must wait for the ________ bit to clear before reading the ADC value.

2005 Microchip Technology Incorporated. All Rights Reserved.

Mechatronics Workshop-in-a-Box

Slide 146

Review the ADC Module. Answers: 1. analog voltage, binary representation of the signal 2. ADCON0 3. ADRESH 4. G0_DONE

146

Displaying Values on the LCD


The LCD is driven directly from the LCD module on-board the PIC16F917 The LCD is a 3 digit display Pins that are connected to the LCD are indicated by a white box enclosing the pin designation LCD functions are provided in linkable files for your convenience
2005 Microchip Technology Incorporated. All Rights Reserved. Mechatronics Workshop-in-a-Box Slide 147

Reading the potentiometer was the first step in completing the design objectives for Lab 2. Recall that we also want to display the analog voltage on the LCD. The slide shows some pertinent information about the LCD on the PICDEM Mechatronics board The LCD is driven directly from the PIC16F917s LCD module. This is a very useful and cost-saving feature on the PIC16F917. The LCD used the board is a 3 digit display. This means in will display 3 digits ranging 0 to 9 and 1 digit that is either blank or a 1. If you look at the PICDEM Mechatronics board, you can see the pins that are connected to the LCD module on the board. Look for the segment and common pins with their designations enclosed in a white box. Because using the LCD module is somewhat complex, functions for displaying values on the LCD are included in linkable files for Lab 2. What are linkable files

147

Linking Files in a Project Linking is used because:


- It is convenient to break up lengthy code into more than one file - It helps make code more portable from one application to another - It helps make code easy for others to use

2005 Microchip Technology Incorporated. All Rights Reserved.

Mechatronics Workshop-in-a-Box

Slide 148

The functions for displaying values on the LCD are included in linkable files. Linking files is useful because it: 1. Breaks up the source code into smaller more readable segments 2. It makes code more portable from one application to another 3. It makes code easy for others to use. This is especially true when more than one person is working on source code. The code can be divided up by function and then linked together in the end

148

call Instruction
Loop call movlw movwf goto TurnOnRA4 bsf return
2005 Microchip Technology Incorporated. All Rights Reserved. Mechatronics Workshop-in-a-Box

TurnOnRA4 0x78 PORTD Loop

PORTA,4

Slide 149

We need to learn another instruction that will enable us to call the functions in the linked files the call instruction. The call instruction works similar to the goto instruction. In this code segment you can see that when we call TurnOnRA4 the program flow goes to the first instruction in the TurnOnRA4 instruction.

149

call Instruction
Loop call movlw movwf goto TurnOnRA4 bsf return
2005 Microchip Technology Incorporated. All Rights Reserved. Mechatronics Workshop-in-a-Box

TurnOnRA4 0x78 PORTD Loop

PORTA,4

Slide 150

The microcontroller keeps track of where it was executing code when the call instruction was executed. When the return instruction is encountered the program flow will return to the next instruction after the call statement. The call instruction is very powerful as it allows you to execute self-contained functions in your code.

150

DisplayHex and DisplayDecimal Functions


Example 1: movlw 0xFF call DisplayDecimal

Example 2: movlw 0xFF call DisplayHex

2005 Microchip Technology Incorporated. All Rights Reserved.

Mechatronics Workshop-in-a-Box

Slide 151

The purpose of the discussion on the call instruction and linking files was to familiarize you with the concepts necessary for talking about the DisplayHex and DisplayDecimal functions. In Lab2, these functions available to you through linked files. The main file for the project is . These functions display a value on the LCD. To use these functions, move the value you want displayed into the W register and call DisplayHex or DisplayDecimal. Lets use these function.

151

LCD Hands-on
File Open Workspace
- c:\Mechatronics WIB\Lab2\Lab2.mcw

The code from the last Hands-on is duplicated in the Lab2.asm file After the line: movf ADRESH, W Call one of the following: DisplayDecimal or DisplayHex Build and animate the code using the ICD 2
2005 Microchip Technology Incorporated. All Rights Reserved. Mechatronics Workshop-in-a-Box Slide 152

In this hands-on we are now going to display the A-to-D reading. First open Lab2.mcw. The code from the last hands-on is duplicated in Lab2.asm. Some code has been added in order to satisfy the linker. For this hands-on, add one line of code. After the movf ADRESH,w call DisplayDecimal or DisplayHex. The choice is yours. Build, program and animate the code.

Turn the potentiometer and look at the display. What does the LCD show?

152

Experimentation
Light Sensor
- Move the jumper wire from POT1 to LIGHT - Vary the light to the light sensor

Temperature Sensor
- Try moving the same wire to TEMP - Breath heavily on the temperature sensor
2005 Microchip Technology Incorporated. All Rights Reserved. Mechatronics Workshop-in-a-Box Slide 153

Just for fun: 1. Move the jumper wire from POT1 to LIGHT (one pin up). 2. Wave your hand over the light sensor located in the top left corner of the board. What happens to the value on the LCD? 3. Move the same jumper to TEMP (one more pin up). 4. Breath out deeply onto the temperature sensor located above the light sensor. What happens to the value on the LCD? 5. Move the jumper back to POT1 to continue with the lab

153

Comparing Two Numbers


Recall these design objectives:
- Turn the motor (fan) on when the result of the ADC (temperature) is greater than 40 - Turn off the motor when the result of the ADC is equal to or less than 40

This requires comparing two numbers Solution: Use the sublw instruction

2005 Microchip Technology Incorporated. All Rights Reserved.

Mechatronics Workshop-in-a-Box

Slide 154

We have learned how to read an analog sensor. We have learned how to display a value on the LCD. One objective remains: comparing sensor result with a temperature of 40 degrees C. For simplicity we are going to assume a Potentiometer reading of 40 is equal to 40 degrees C. Meeting this design criteria means that we have to compare two numbers. The easiest way to do this is with the sublw instruction.

154

sublw Instruction
Subtracts W from a literal and places the result in W Carry and Zero STATUS flags affected Example: (Setpoint Temp) movlw Temp sublw Setpoint Relation Setpoint > Temp Setpoint = Temp Setpoint < Temp
2005 Microchip Technology Incorporated. All Rights Reserved.

Result STATUS,Z STATUS,C + 0 Mechatronics Workshop-in-a-Box

0 1 0

1 1 0
Slide 155

The sublw instruction subtracts W for the operator and places the result in W. We have not talked before about STATUS flags. STATUS flags indicate to us certain things about the result of an operation. In the case of the sublw instruction the STATUS flags affected are the zero flag (STATUS,Z) and the carry flag (STATUS,C). The zero flag is set if the result of the operation is zero. The carry flag is set if the result is zero or positive. Lets take a look at an example

155

sublw Instruction
What is the result of the following operation? movlw sublw 4 5

2005 Microchip Technology Incorporated. All Rights Reserved.

Mechatronics Workshop-in-a-Box

Slide 156

Here we are moving 4 into W. We then subtract W from a literal, in this case 5. What is the result? The result is 5 4 or 1. This result is non-zero so the Zero flag is not set. The result is positive, so the carry flag is set. Ive included a screen shot of the status bar in MPLAB after performing this operation. You can see that all this information is shown on the status bar. After the operation: W is 0x01 The Zero flag is not set. This is indicated by a lower case z The Carry flag is set. This is indicated by an upper case C

156

Using sublw for Greater Than


Problem: You want to find out if the value in ADRESH is greater than 40. Solution:
1. Move the value in ADRESH to W 2. Subtract W from .40 3. Check the Carry flag
If clear, then the value is greater than 40 If set, then the value is less than or equal to 40
2005 Microchip Technology Incorporated. All Rights Reserved. Mechatronics Workshop-in-a-Box Slide 157

We are going to pretend that an ADC reading of 40 corresponds to 40 degrees C. Therefore, we will turn on the motor when the ADC reading is 40 or greater. We will turn off the motor when the ADC reading is 40 or less. To make this comparison, we need to subtract the value in the ADRESH register from 40. Here are the steps for doing that. 1. movf ADRESH,w 2. sublw .40 (Dont forget than the decimal point indicates a decimal number follows. If you do forget, then you will be specifying 0x40.) 3. btfss STATUS,C

If the Carry flag is set, well turn on the motor. If its clear well turn off the motor.

157

Lab 2 State Diagram


Read ADC

Display ADC Value

Turn on Motor

Compare ADC Value

Turn off Motor

2005 Microchip Technology Incorporated. All Rights Reserved.

Mechatronics Workshop-in-a-Box

Slide 158

Here is a state diagram for Lab 2. The first thing we want to do is read the ADC module. Then we will display the value using one of the two provided functions: DisplayDecimal or DisplayHex. Next, using the technique we just went over than incorporates the sublw command we will check to see if the ADC value is above 40. If it is above 40 then we will turn on the motor. If its below 40 then we will turn off the motor. Once this is done, the whole process will be repeated.

158

Lab 2 State Diagram


Read ADC

Display ADC Value

Turn on Motor

Compare ADC Value

Turn off Motor

2005 Microchip Technology Incorporated. All Rights Reserved.

Mechatronics Workshop-in-a-Box

Slide 159

Youve written code for the all of these states except for the compare state. All you need to do is the comparison on ADRESH using the addlw instruction and based on that comparison, turn the motor on or off. Remember RD7 is the pin that drives the motor on or off.

159

Lab 2: Implement a Solution


Add to your existing code for Lab2 Use sublw to test whether the ADC value is 40 or greater Check the STATUS,C flag If clear, turn on the motor If set, turn off the motor

2005 Microchip Technology Incorporated. All Rights Reserved.

Mechatronics Workshop-in-a-Box

Slide 160

Implement a solution. Youre almost there with the code you have. Use the commands youve learned to make the comparison. Go over the solution when everybody is done. The solution is in Lab2solution.asm in the Lab2 folder.

160

Lab 2 Review
New PIC16F917 Peripherals
- Analog to Digital Conversion Module - LCD Module

New Tools
- MPLAB Linker

New Instructions
- call and return - sublw

New Concepts
- Comparing two numbers
2005 Microchip Technology Incorporated. All Rights Reserved. Mechatronics Workshop-in-a-Box Slide 161

Review Lab 2

161

Agenda
Introduction to Microchip Mechatronics examples and benefits PIC Microcontroller Basics
- Hands-On Learning Cycles

Labs
- Simple I/O and Timer 0 - Reading an analog sensor, LCD module - Controlling the speed of a motor

LAB 3

Resources
2005 Microchip Technology Incorporated. All Rights Reserved. Mechatronics Workshop-in-a-Box Slide 162

In Lab 3 you will learn how pulse width modulation is used to vary the speed of a motor.

162

Lab 3: Design Objectives


Read an analog temperature sensor Vary the speed of the fan in proportion to the temperature reading

Temperature Sensor
2005 Microchip Technology Incorporated. All Rights Reserved.

PIC16F917 Fan
Mechatronics Workshop-in-a-Box Slide 163

Management has returned and said that they are concerned about the efficiency of the system. Theyve asked us to come up with a way to vary the speed of the fan based on the temperature. This will be less of a drain on the batteries.

163

Lab 3: Schematic
+5V +5V Motor POT1 RA0 RD2 MOSFET N2

PIC16F917 D0

2005 Microchip Technology Incorporated. All Rights Reserved.

Mechatronics Workshop-in-a-Box

Slide 164

This is the schematic for Lab 3. Note the only change is the pin driving the MOSFET. We moving from RD7 to RD2 because this pin is multiplexed with a module that will allow us to easily implement speed control.

164

Lab 3: Connection Diagram

RD2,D0 RD2,N2

2005 Microchip Technology Incorporated. All Rights Reserved.

Mechatronics Workshop-in-a-Box

Slide 165

All the pins are connected exactly as in the last lab only now N2 and D0 are connected to CCP2 (also RD2) instead of RD7. Make this change now.

165

Brushed DC Motor Speed Control


1000 Motor Speed (RPM) 180 0V
2005 Microchip Technology Incorporated. All Rights Reserved. Mechatronics Workshop-in-a-Box

5V

Average Voltage
Slide 166

The speed of a brushed dc motor is proportional to the average voltage applied to the leads of the motor. The only exception is at low speeds where the motor must overcome friction to start spinning. For the most part, however, speed and voltage are proportional. Because a microcontroller works in the digital realm we would like to find a way to use a digital signal to control the speed of such a motor. How can we vary the speed of a motor using a digital signal?

166

Pulse Width Modulation


Pulse Width

Period Duty Cycle = Pulse Width Period


Slide 167

2005 Microchip Technology Incorporated. All Rights Reserved.

Mechatronics Workshop-in-a-Box

The answer is a technique called Pulse Width Modulation. Pulse width modulation is a technique commonly used in controlling the speed of a motor. In pulse width modulation a modulating digital signal is created with a fixed period. Within that period, the length of time that the signal remains high, or pulse width, is varied. Duty cycle refers to the ratio of pulse width to period.

167

PWM and Average Voltage


VP A

A is the area

VAVG = Duty Cycle x VP VAVG A

2005 Microchip Technology Incorporated. All Rights Reserved.

Mechatronics Workshop-in-a-Box

Slide 168

The average voltage of the signal changes in proportion to the duty cycle (see formula). If you drive a motor with this signal (assuming the frequency is sufficiently high) the windings in the motor essentially see the average voltage of the signal. Therefore, if the peak voltage of this digital signal is 5 volts, then a 50% duty cycle would look like 2.5 volts to the motor. The letter A in the diagrams above represents the area under the pulse. A is the same for both diagrams. This is another way of looking at average voltage.

168

Frequency

Lower

20 Hz Audible Range

Higher

20 kHz

2005 Microchip Technology Incorporated. All Rights Reserved.

Mechatronics Workshop-in-a-Box

Slide 169

Frequency plays an important role in the signal driving a motor. The human ear can hear frequencies below about 20 kHz. Therefore if you drive a motor with a PWM signal below 20 kHz you will hear an audible (and annoying) whine when running the motor at low speeds. To eliminate this, we modulate the drive signal faster than 20 kHz.

169

PWM Hands-On

Experimenting with Duty Cycle

2005 Microchip Technology Incorporated. All Rights Reserved.

Mechatronics Workshop-in-a-Box

Slide 170

In this hands-on we will create a simple PWM signal and change the duty cycle.

170

PWM Hands-On
include bsf bcf bcf PWMLoop bsf nop nop . . bcf goto end <p16f917.inc> STATUS,RP0 Create in h1.asm in TRISD,2 the test workspace STATUS,RP0 PORTD,2 Copy these three lines and paste here 6 times

PORTD,2 PWMLoop
Mechatronics Workshop-in-a-Box Slide 171

2005 Microchip Technology Incorporated. All Rights Reserved.

Alright, lets create our first PWM signal. 1. Create a file with this code. Use the test workspace weve been using. 2. Under the label PWMLoop enter the three lines of code shown. 3. Copy these three lines six more times for a total of seven bsf PORT,2 statements followed by two nop statements. 4. Finish the code segment by clearing PORTD,2 and looping back to PWMLoop. Dont forget the end statement.

171

Simulating the PWM Loop


1. Choose MPLAB SIM 2. Build the project

3. Set a Breakpoint at goto PWMLOOP

2005 Microchip Technology Incorporated. All Rights Reserved.

Mechatronics Workshop-in-a-Box

Slide 172

Well use the simulator to see the PWM signal in action. 1. Choose Debugger -> Select Tool -> MPLAB SIM 2. Build the project 3. Set a breakpoint at the goto PWMLoop statement by double-clicking in the margin.

172

Set Up the Logic Analyzer


1. Choose View - Simulator Logic Analyzer 2. Select Add Signals 3. Choose RD2 in the available Signals Box and click Add => 4. Run the simulator (press F9) 5. Run again (press F9) 6. And again (press F9)
2005 Microchip Technology Incorporated. All Rights Reserved. Mechatronics Workshop-in-a-Box Slide 173

We can use the built-in simulator Logic Analyzer to see our PWM in action. Follow the steps shown.

173

Simulate using the Logic Analyzer

2005 Microchip Technology Incorporated. All Rights Reserved.

Mechatronics Workshop-in-a-Box

Slide 174

You should see a signal with a 7/8ths duty cycle in the Logic Analyzer window.

174

Change the Duty Cycle


Starting from the bottom change bsf instructions to bcf one at a time Build the project and simulate between changes
Do you see the change in duty cycle?

Remove the breakpoint Switch to the ICD 2 as the debugger Do the same experiment as above
How does the motor behave to bsf changes?
2005 Microchip Technology Incorporated. All Rights Reserved. Mechatronics Workshop-in-a-Box Slide 175

1. Change the bsf instructions to bcf instructions starting from the bottom of the code and working your way up. 2. Build the project and simulate between changes. Question: Do you see the change in duty cycle on the analyzer? 1. Next, change to the ICD 2. 2. Remove the breakpoint. 3. Do the same experimentation using running the motor. Question: How does the motor behave when you increase the duty cycle?

175

PWM Review
PWM stands for _______ _______ ______. PWM signals have a fixed _______. The duty cycle is the ratio between _______ and ________. The human ear can hear frequencies below ____ kHz. Which frequency is higher (right or left)?

2005 Microchip Technology Incorporated. All Rights Reserved.

Mechatronics Workshop-in-a-Box

Slide 176

Answers: 1. Pulse Width Modulation 2. Period 3. Pulse Width and period 4. 20 5. left

176

Source Code Generated PWM Drawbacks Processor intensive PWM Loop must be continually executed Little time to accomplish other tasks Possible Solutions: 1. Slow down the PWM 2. Decrease PWM resolution 3. Use MCU with PWM peripheral
2005 Microchip Technology Incorporated. All Rights Reserved. Mechatronics Workshop-in-a-Box Slide 177

The PWM signal we just created was very processor intensive. In other words, we would have a difficult time doing much else besides generating the PWM signal in that loop. If you wanted, for instance, to read a sensor, communicate with a PC, and a perform a variety of other tasks it would be very difficult (impossible depending how much other stuff) to return to the PWM generation routine in a timely manner. There are there possible solutions to this. The first is to slow down the PWM loop. As we discussed earlier this is ok to a certain point. However once the frequency falls below 18kHz the motor will make and annoying whine. The second is to decrease PWM resolution. In the signal we just created we had 8 bits of resolution. In other words we could have 8 different motor speeds. This is too little for most applications as it is so this is not a good solution. The best solution is to off-load the PWM generation to a dedicated hardware peripheral. Lets take a look at the peripheral on the PIC16F917 that allows us to do this.

177

Capture, Compare, PWM (CCP) Module


The CCP module is a hardware PWM signal generator Timer 2 is used to clock the PWM signal Up to 10-bits of resolution (1024 pulse width settings per period) At 8-bits of resolution the 8 MHz internal clock will output 31.2 kHz CCP2 is multiplexed with RD2
2005 Microchip Technology Incorporated. All Rights Reserved. Mechatronics Workshop-in-a-Box Slide 178

The CCP module is a hardware module that automatically generates a PWM signal. This module uses Timer 2 to generate a PWM signal. The signal can have up to 10 bits of resolution, or 1024 possible pulse witch settings per period.) If you recall our discussion about avoiding the audible frequency range, then youll understand why the next point is important. With 8 bits of resolution and utilizing the 8 MHz internal oscillator a frequency of 31.2 kHz is possible on by the CCP module. Finally, the reason we switched our output drive from RD7 to RD2 is that RD2 is multiplexed with the CCP2 module. If you look on the PICDEM Mechatronics board youll see the RD2 pin is labeled RD2/CCP2.

178

CCP2 Registers
CCP2CON Select PWM mode, 2 LSB of Duty Cycle CCPR2L 8 MSB of Duty Cycle PR2 Frequency select register T2CON Turn on Timer 2 TRISD Make CCP2 pin an output

2005 Microchip Technology Incorporated. All Rights Reserved.

Mechatronics Workshop-in-a-Box

Slide 179

These are the registers that are used to set up the PWM module. Again, I just want you to be aware that several registers are responsible for setting up the CCP2 module. In this lab all setup has be done for you. You need only be concerned with the CCPR2L register. This register contains the 8 most significant bits of the Duty Cycle.

179

Lab 3: Using the CCP


V

ADC
t

ADRESH

CCPR2L

2005 Microchip Technology Incorporated. All Rights Reserved.

Mechatronics Workshop-in-a-Box

Slide 180

Once the CCP is set up, changing the duty cycle of the PWM output is as simple as loading the duty cycle into the CCPR2L register. In this lab this task is as simple as moving the ADRESH value into CCPR2L. As you can see this is much easier than implementing Pulse width modulation in source code alone.

180

Lab 3 State Diagram

Read ADC

Display ADC Value

Set CCP2 Duty Cycle

2005 Microchip Technology Incorporated. All Rights Reserved.

Mechatronics Workshop-in-a-Box

Slide 181

This lab is actually easier than Lab 2. The first two states are exactly the same as the first two states of Lab 2. Instead of doing the comparison that you did in Lab 2, simply move the value in ADRESH into CCPR2L

181

Lab 3: Implement a Solution


Open the Lab3 workspace in: c:\Mechatronics WIB\Lab3 All I/O ports and modules (including the CCP) are initialized for you Copy the first two states in Lab 2
- Read ADC - Display ADC Value

Move result of the analog-to-digital conversion into CCPR2L


2005 Microchip Technology Incorporated. All Rights Reserved. Mechatronics Workshop-in-a-Box Slide 182

Now its time to finish Lab 3. The I/O ports, ADC module, and CCP2 module are all initialized for you. Simply copy the first two states you created in Lab 2. Add to this, code that copies ADRESH in CCPR2L. Go over the solution with the class once theyve working on it a while.

182

Motor Whine

Question: Why does the motor whine?

2005 Microchip Technology Incorporated. All Rights Reserved.

Mechatronics Workshop-in-a-Box

Slide 183

Once the students have written the code and have the motor running they may notice that the motor has an audible whine. Why is this? Answer: The CCP module is operating at 7 kHz. If you recall, this is below 20 kHz which means the human ear can hear the modulation of the motor windings.

183

QuietPWM Function
Generates a 31.2 kHz signal using the 8 MHz internal oscillator Has 8-bits of resolution How to use:
- Move duty cycle value in W - Call QuietPWM

2005 Microchip Technology Incorporated. All Rights Reserved.

Mechatronics Workshop-in-a-Box

Slide 184

The Fix: Increase the frequency of the PWM signal. Increasing the frequency makes loading the PWM duty cycle more complicated than moving the ADC result into CCPR2L. Ive provided an easy to use function that loads the duty cycle into the necessary registers when CCP2 is configured to generate a 31.2 kHz signal. Call the QuietPWM function instead of moving ADRESH into CCP2. (Move the value in ADRESH into W and call QuietPWM.) Do you notice any difference? If you created an appliance with a DC motor, which frequency to you think your customers would want you to use in your design?

184

Lab 3 Review
Introduction to Pulse Width Modulation
- Duty Cycle is linear to motor speed - When driving motors, modulating the PWM signal above 18 kHz is a good idea

Development Tools
- MPLAB Signal Analyzer

CCP Module
- Can generate an 8-bit 31.2 kHz PWM signal using the 8 MHz internal oscillator

2005 Microchip Technology Incorporated. All Rights Reserved.

Mechatronics Workshop-in-a-Box

Slide 185

Review Lab 3.

185

Agenda
Introduction to Microchip Mechatronics examples and benefits PIC Microcontroller Basics
- Hands-On Learning Cycles

Labs
- Simple I/O and Timer 0 - Reading an analog sensor, LCD module - Controlling the speed of a motor

Resources
2005 Microchip Technology Incorporated. All Rights Reserved. Mechatronics Workshop-in-a-Box Slide 186

That concludes that hands on portion of this presentation. You are now well equipped to start using PIC microcontrollers on your own! You wont be on your own, however, when you leave this class. Microchip has many resources available to you to assist you in application development.

186

Continue to learn with the Mechatronics Board . . .

2005 Microchip Technology Incorporated. All Rights Reserved.

Mechatronics Workshop-in-a-Box

Slide 187

First, the PICDEM Mechatronics Demonstration Board still has a lot more to teach you.

187

PICDEM Mechatronics Projects For Self-Study Learn to read an analog temperature sensor and light sensor How to create a real-time clock Brushed DC motor control Stepper motor control Using the LCD module on the PIC16F917 Using serial communication Other concepts: Back EMF, optical speed sensing, and current sensing
2005 Microchip Technology Incorporated. All Rights Reserved. Mechatronics Workshop-in-a-Box Slide 188

The self-study projects included with the board teach you about the topics listed on this slide. The knowledge you gain in this WIB is built upon in these self-study projects. I highly encourage you to load these projects after you leave this training. You will have a lot of fun learning with these projects.

188

Microchip Web Resources Electronic Product Selector Guide Design Centers www.microchip.com/mechatronics Step-by-step Tutorials Webinars Online presentations Application Notes, Technical Briefs, Articles Upcoming Training and Events Technical Support
2005 Microchip Technology Incorporated. All Rights Reserved. Mechatronics Workshop-in-a-Box Slide 189

Microchips website is a resource I highly encourage you to become familiar with. The following are some of the resources available on Microchips website: Electronic Product selector guide Design Centers (mention the mechatronics design center) Tutorials Technical Support information Webinars 20 minute mini-presentations on various topics Application notes and Technical Briefs Articles Upcoming Training and events

189

PICkit 2 Microcontroller Programmer


Programs all Flash PIC microcontrollers and dsPIC Digital Signal Controllers $34.95 USD PICkit 2 Flash Starter Kit Programmer bundled with small development board for $49.95 USD Compatible with the PICDEM Mechatronics Board

2005 Microchip Technology Incorporated. All Rights Reserved.

Mechatronics Workshop-in-a-Box

Slide 190

We used the ICD 2 in this workshop-in-a-box. The PICDEM Mechatronics board is also compatible with the PICkit 2 Microcontroller Programmer. This is a low-cost programmer that you can take with you anywhere.

190

MPLAB ICD 2
MPLAB ICD 2 Part # DV164007
- Includes 9V power supply, serial cable, USB cable, ICD interface cable, and MPLAB ICD 2

2005 Microchip Technology Incorporated. All Rights Reserved.

Mechatronics Workshop-in-a-Box

Slide 191

It is likely that you will want to continue developing and debugging code with the ICD 2. The recommended part number for the ICD 2 is DV164007. This kit includes the MPLAB ICD 2, the 9V power supply youve been using today, a serial cable, USB cable, and an ICD interface cable.

191

Third Party Tools


Third Party Tool Developers are our Partners
- Give them access to early samples/information - License Hardware Design to accommodate certain Markets

Preferred Programmer Vendor Top Compilers Choices


- Hi-Tech - IAR - CCS

Complete listing at: www.microchip.com/thirdparty


2005 Microchip Technology Incorporated. All Rights Reserved. Mechatronics Workshop-in-a-Box Slide 192

We recognize that we cannot supply all the tools everybody wants. There are many third party tools available that support Microchips products.

192

Summary
Designing a PIC microcontroller into a mechanical system is beneficial to you Youve see how easy it is to get started with Microchip and PIC microcontrollers You can now use Microchips low-cost tools to change, adapt and add features to a design You can now perform basic mechatronic tasks using a PIC microcontroller
2005 Microchip Technology Incorporated. All Rights Reserved. Mechatronics Workshop-in-a-Box Slide 193

Re-emphasize the general points that the students learned.

193

Thank You for Coming!

Microchip appreciates your feedback on the content of this presentation. Please tell us what you liked and didnt like about the presentation. Please send your comments to: mechatronicsWIB@microchip.com
2005 Microchip Technology Incorporated. All Rights Reserved. Mechatronics Workshop-in-a-Box Slide 194

Thank you for attending todays presentation.

194

Trademarks & Disclaimers


The Microchip name and logo, the Microchip logo, Accuron, dsPIC, KEELOQ, microID, MPLAB, PIC, PICmicro, PICSTART, PRO MATE, PowerSmart, rfPIC and SmartShunt are registered trademarks of Microchip Technology Incorporated in the U.S.A. and other countries. AmpLab, FilterLab, Migratable Memory, MXDEV, MXLAB, PICMASTER, SEEVAL, SmartSensor and The Embedded Control Solutions Company are registered trademarks of Microchip Technology Incorporated in the U.S.A. Analog-for-the-Digital Age, Application Maestro, dsPICDEM, dsPICDEM.net, dsPICworks, ECAN, ECONOMONITOR, FanSense, FlexROM, fuzzyLAB, In-Circuit Serial Programming, ICSP, ICEPIC, MPASM, MPLIB, MPLINK, MPSIM, PICkit, PICDEM, PICDEM.net, PICtail, PowerCal, PowerInfo, PowerMate, PowerTool, rfLAB, rfPICDEM, Select Mode, Smart Serial, SmartTel and Total Endurance are trademarks of Microchip Technology Incorporated in the U.S.A. and other countries. SQTP is a service mark of Microchip Technology Incorporated in the U.S.A. All other trademarks mentioned herein are property of their respective companies. Information contained in this publication regarding device applications and the like is provided only for your convenience and may be superseded by updates. It is your responsibility to ensure that your application meets with your specifications. MICROCHIP MAKES NO REPRESENTATIONS OR WARRANTIES OF ANY KIND WHETHER EXPRESS OR IMPLIED, WRITTEN OR ORAL, STATUTORY OR OTHERWISE, RELATED TO THE INFORMATION, INCLUDING BUT NOT LIMITED TO ITS CONDITION, QUALITY, PERFORMANCE, MERCHANTABILITY OR FITNESS FOR PURPOSE. Microchip disclaims all liability arising from this information and its use. Use of Microchips products as critical components in life support systems is not authorized except with express written approval by Microchip. No licenses are conveyed, implicitly or otherwise, under any Microchip intellectual property rights.

2005 Microchip Technology Incorporated. All Rights Reserved.

Mechatronics Workshop-in-a-Box

Slide 195

195

Das könnte Ihnen auch gefallen