SK40C + PIC16F887 - Cytron · robot . head to toe sk40c + 16f887 getting started contents...

64
SK40C + PIC16F887 STARTER KIT MANUAL BEGINNER GUIDE

Transcript of SK40C + PIC16F887 - Cytron · robot . head to toe sk40c + 16f887 getting started contents...

SK40C + PIC16F887

STARTER KIT MANUAL

BEGINNER GUIDE

ROBOT . HEAD to TOESK40C + 16F887 GETTING STARTED

SK40C + 16F887 STARTER KIT MANUAL

BEGINNER GUIDE

BY

Page 2

ROBOT . HEAD to TOESK40C + 16F887 GETTING STARTED

CONTENTSINTRODUCTIONCOMPONENT REQUIREDWHAT EXACTLY INSIDE SK40CGETTING STARTED

– MPLAB IDE & HITECH C PRO Installation

– CREATE PROJECT– PICKIT 2 SETUP– OPEN PROJECT– HARDWARE SETUP– I/O PORT

PROJECT 0– CONNECTION– CODE OVERVIEW

PROJECT 1– CONNECTION– ADDITIONAL INFORMATION– CODE OVERVIEW

PROJECT 2– CONNECTION– ADDITIONAL INFORMATION– CODE OVERVIEW

PROJECT 3– CONNECTION– ADDITIONAL INFORMATION– CODE OVERVIEW

PROJECT 4– CONNECTION– ADDITIONAL INFORMATION– CODE OVERVIEW

PROJECT 5– CONNECTION– ADDITIONAL INFORMATION– CODE OVERVIEW

PROJECT 6– CONNECTION– ADDITIONAL INFORMATION– CODE OVERVIEW

4568

8910111112131313171717182020202123232324262626273030313233333435

PROJECT 7– CONNECTION– ADDITIONAL INFORMATION– CODE OVERVIEW

PROJECT 8– CONNECTION– ADDITIONAL INFORMATION– CODE OVERVIEW

PROJECT 9– CONNECTION– ADDITIONAL INFORMATION– CODE OVERVIEW

PROJECT 10– CONNECTION– ADDITIONAL INFORMATION– CODE OVERVIEW

PROJECT 11– CONNECTION– ADDITIONAL INFORMATION– CODE OVERVIEW

PROJECT 12– CONNECTION– ADDITIONAL INFORMATION– CODE OVERVIEW

PROJECT 13– CONNECTION– ADDITIONAL INFORMATION– CODE OVERVIEW

PROJECT 14– CONNECTION– ADDITIONAL INFORMATION– CODE OVERVIEW

PROJECT 15– CONNECTION– ADDITIONAL INFORMATION– CODE OVERVIEW

393940404242424344444546474748495151515354545556575758596060616162626363

Page 3

ROBOT . HEAD to TOESK40C + 16F887 GETTING STARTED

INTRODUCTION

SK40C is another enhanced version of 40 pins PIC microcontroller start up kit. It is designed to offer an easy to start board for PIC MCU user. Users are able to utilize the function of PIC by directly plugging in the I/O components in whatever way that is convenient to user. With UIC00B connector on board, user can start developing projects and have fun with this kit right away. This kit comes WITHOUT PIC microcontroller to provide the freedom for user to choose PIC type.

In here , we are going to explain to you the method of using SK40C with PIC16F887 by interfacing with others common use electronic components such as sensor, LED, UART, PS2 controller and etc. There is total of 15 interesting project from Project_0 to Project_15 which have explain the method to use SK40C with PIC16F887 interfacing with electronic component.

This will help user on deeply and easily understanding the function of SK40C, microcontroller and also HI-TECH C programming.

SK40C board comes with basic element for user to begin project development. It offer plug and use features.

HOW TO USE ITThis starter kit manual are start off with a simple introduction of SK40C, software installation, electronic component needed and interfacing, hardware, some useful additional information and lastly the C code explanation . We will also describe separately the code and also the hardware connection in some detail and how it works.

WHAT YOU WILL NEED First, you will need access to internet and go to www.cytron.com.my to download the sample code of 15 interesting project and also any code libraries that is required in the projects.

Second, you will need to prepare the electronic component which will be use in the project such as LED, Ultrasonic sensor, UC00A and etc. Then you also need a well lit table or other surface to lay down all your components and this will be next to your computer for enable you to easily upload the code into the SK40C. Always beware that you are working with electricity (although is low voltage) but safety is a MUST to avoid damages on yourself and components Besides that, also of some benefit, although not essential, may be a pair of wire cutters, a pair of long nosed pliers and a wire stripper for making a jumper wires.

Lastly, the most important thing is the willingness to learn. Coming project are design as a simple way to help you get involve to the microcontroller electronics and nothing is too hard to learn.

Page 4

ROBOT . HEAD to TOESK40C + 16F887 GETTING STARTED

COMPONENT REQUIRED

SK40C PIC16F887 UIC00B LEDS

RESISTOR BREADBOARD16x2 PARALLEL LCD

POTENTIALMETER

LM35 TEMPRETURE SENSOR ULTRASONIS RANGE FINDER EZ1

PIEZO BUZZERIR DISTANCE SENSOR

LDR MD10C 7 SEGMENT CD4511 7SEGMENT DECODER

USB TO UART CONVERTER RELAY JUMPER WIRES DC POWER SUPPLY

SKPS CONTROLLER STARTER KIT 1N5817 SCHOTTKY DIODE SONY PS2 CONTROLLER

BB-PSJ ANALOG JOYSTICK BREAKOUT BOARD

Page 5

ROBOT . HEAD to TOESK40C + 16F887 GETTING STARTED

WHAT EXACTLY INSIDE SK40CBOARD OVERVIEWSK40C, another enhanced version after SK40B which can support for 40 pins PIC such as PIC16F and PIC18F family. This board comes with basic element that mostly use by hobbyist and experts. This kit is design to offer:

• Industrial grade PCB • Every board is being fully tested before shipped to customer • Compact, powerful, flexible and robust start-up platform • Suitable for hobbyists and experts • Save development and soldering time • No extra components required for the PIC to function • All 33 I/O pins are nicely labeled to avoid miss-connection by users • Connector for UIC00A (low cost USB ICSP PIC Programmer) - simple and fast method to load program • Fully compatible with SK40B • No more frustrated work plugging PIC out and back for re-programming • Perfectly fit for 40 pins 16F and PIC18F PIC • With UIC00A, program can be loaded in less than 5 seconds • More convenient to use and it is smaller than SK40B. • Maximum current is 0.5A. • Dimension: 85mm x 55mm

SK40C come with additional features: • 2 x Programmable switch • 2 x LED indicator • Turn pin for crystal. User may use others crystal provided. • LCD display (optional) • UART communication

• USB on board. •And all the necessities to eliminate users difficulty in using PIC.

LABEL FUNCTION LABEL FUNCTION

A DC Power Adapter Socket I Programmable Push Button

B USB Connector J Reset Button

C Toggle Switch for Power Supply

K LCD Contrast

D Power Indicator LED L JP8 for LCD Backlight

E Connector for UIC00B Programmer

M JP9 for USB

F LED Indicator N 40 pin IC Socket for PIC MCU

G Header Pin and Turn Pin O Turn Pin for Crystal

H UART Connector P LCD Display

A – DC power adapter socket for user to plug in DC adapter. The input voltage should be range 7 – 15V.

B – USB connector for communication between devices and a host controller. This function only valid for certain model of PIC microcontroller. Please refer to SK40C User Manual. The power LED will light ON when USB cable is connected.

C – Toggle switch to ON/OFF the power supply from DC adapter.

D – Power indicator LED for on board. It will light ON

Page 6

ROBOT . HEAD to TOESK40C + 16F887 GETTING STARTED

as long as the input power is correctly connected.E – 2x5 box header for UIC00A & UIC00B, USB ISCP Programmer.

F – 2 LEDs (connected to RB6 and RB7) as active High output for PIC MCU. These LEDs are controllable from PIC MCU.

G – Consist of several line of header pin and turn pin. Header pin provide connector for user to solder SK40C to prototype board and use the I/O of PIC MCU. It is fully compatible between SK40B. Turn pin offer simple way to check voltage with multi-meter probe. 40 pins of PIC MCU excerpt OSC ( connected to crystal) are extended out to there pin. There is an extra pin on top of MCLR which is labeled as Vin, is connected to the input power.

H – Reserved for UART communication. Tx and Rx pin of SK40C are connected to RC6 and RC7 respectively. Ensure PIC use have the correct UART pin (RC6 and RC7).

I – 2x Push Button connected to RB0 and RB1 of PIC MCU. This is extra input button for user. It can be programmed as input switch.

J – Push button with the function of reset for PIC MCU.

K – 5K of trimmer to set LCD contrast.

L – JP8 is provided for LCD backlight. LCD Display will have backlight if this pin is shorted.

M – JP9 is provided for USB. Connect this pin is user use USB port.

N – 40 pin IC socket for user to plug in any 40 pin PIC MCU(8Bit). It can be either 16F or 18F PIC. Of course the IC package should be PDIP. Please ensure the first pin is at the top side. Inside IC socket, there some electronic component, it include a 20MHz Crystal.

O – Turn pins is provided for crystal. 20MHz is default crystal provided in SK40C. However, the 20MHz crystal; can be removed and replace with other crystal. Just remove crystal and put other crystal on turn pin without soldering.

P – Reserved for 2 x 16 LCD Display. User may solder 2 x 16 LCD display at this space if want to use it

2 X 16 Parallel LCD Display Connection Pin (Label P)PIN NAME PIN FUNCTION CONNECTION

1 GND Ground GND

2 VDD Positive Supply for LCD 5V

3 CON Brightness Adjust Connected to Preset to Adjust Brightness

4 RB4 Select Register, Selector Instruction or Data Register

Pin RS of LCD

5 GND Ground GND

6 RB5 Start Data Read or Write Pin E of LCD

7 RD0 LCD Data Bus Pin Pin D0 of LCD

8 RD1 LCD Data Bus Pin Pin D1 of LCD

9 RD2 LCD Data Bus Pin Pin D2 of LCD

10 RD3 LCD Data Bus Pin Pin D3 of LCD

11 RD4 LCD Data Bus Pin Pin D4 of LCD

12 RD5 LCD Data Bus Pin Pin D5 of LCD

13 RD6 LCD Data Bus Pin Pin D6 of LCD

14 RD7 LCD Data Bus Pin Pin D7 of LCD

15 VDD Backlight Positive input VDD

16 B/L Backlight Negative Input Connected to JP8

Turn Pin For Crystal (Label O)PIN NAME PIN FUNCTION CONNECTION

RA6 OSC2 Crystal Turn Pin (JP7)

RA7 OSC1 Crystal Turn Pin (JP7)

Push Button Pin (Label I)PIN NAME PIN FUNCTION CONNECTION

RB0 SW1 Digital Input “SW1” Switch

RB1 SW2 Digital Input “SW2” Switch

UART PIN (Label H)PIN NAME PINFUNCTION CONNECTION

RC6 TX Transmit Data TX Pin of UART

RC7 RX Receive Data RX Pin of UART

Page 7

ROBOT . HEAD to TOESK40C + 16F887 GETTING STARTED

GETTING STARTEDIn this SK40C tutorial, we are going to use MPLAB with HI-TECH C compiler to compile and program to the PIC16F887. MPLAB can be supported to Window, MAC OS and LINUX. In here we are presume that you are using Window. Download the MPLAB IDE from download page.

MPLAB IDE & HITECH C InstallationPlease install MPLAB IDE and HI-TECH PICC Lite according to the following steps.

1. Please double click on the Setup to install MPLAB V8.70.

2. The Install Shield Wizard will pop out.

3. After all the directions shown in the welcome note (as in following diagram) is done, please click Next> for next step.

4. Please select I accept the terms of the license agreement if it is not selected in the diagram below, and click Next> after this.

5. Please select Complete for the setup type to install all program features, and click Next> to next step.

6. In the Choose Destination Location , user is recommended to use the default destination folder, which is C:\Program Files\Microchip\ or user is also free to select the other destination folder by using the Browse… button to browse to the desired destination folder. After that, click Next> for next step.

7. Please select I accept the terms of the license agreement if it is not selected in the diagram below, and click Next> after this.

8. Please select I accept the terms of the

Page 8

ROBOT . HEAD to TOESK40C + 16F887 GETTING STARTED

license agreement again for the window shown below, and click Next> after this.

9. Please click Next> for the diagram below.

10. Please wait for awhile for the installation process shown in diagram below.

11. A window for Question will pop out, please click YES to proceed with installation of HI-TECH C.

12. Please click Next to Install HI-TECH C

13. Please select I accept the terms of the license agreement if it is not selected in the diagram below, and click Next to Install HI-TECH C.

14. Please click Next> to proceed.

15. Please select Add to environment path if it is not selected in the diagram below, and click Next to proceed.

16. Please wait for the installation process to be completed.

17. Please click Finish after successfully installed the HI-TECH C.

18. The installation of MPLAB V8.70a is completed. Please click Finish to exit. User may need to restart the computer just after the installation or restart later.

CREATE PROJECTAfter finished install the MPLAB IDE, we are going to show you how to create a project using it. There is just a few simple step to follow on how to create it. Please follow the step below:

1. Go to to MENU BAR and click Project > Project Wizard.

Page 9

ROBOT . HEAD to TOESK40C + 16F887 GETTING STARTED

2. Click Next> . On the Device menu, choose PIC16F887 because we are going to use this PIC MCU for coming project.

3. Choose HI-TECH Universal Toolsuite in Active Toolsuite. A HI-TECH ANSI C Compiler will show up in the Toolsuite Content.

4. After that, choose a destination where the project you create to be save as. And also the project name. After that, click NEXT>.

5. In step 4, there are no existing file to be added so we can skip this step by just click NEXT>. After that, a project are created with the project name you added earlier.

PICKIT 2 SETUPIn here, we want our compiler to automatically send the .HEX file into our PIC MCU after compiler. There will be just only 4 step to do it. Please follow the instruction below:

1. Go to MENU BAR. Programmer> Select Programmer> PICkit 2.

2. Again, go to Programmer> Setting.

3. For UIC00B, please tick the box below.

Page 10

ROBOT . HEAD to TOESK40C + 16F887 GETTING STARTED

OPEN PROJECTThere are only few simple step to open an project. 1st Open the project file. Then, double-click the project file with MPLAB logo. Example like figure below.

C LANGUAGE KEYWORDBelow are the keyword using in standard ANSI C language.

auto break

bit case

char const

continue define

default do

double else

enum extern

float for

goto if

int long

register return

short signed

sizeof static

struct swtich

typedef union

unsigned void

volatile while

HARDWARE SETUP

To make the SK40C function, put the PIC16F887 into the IC Socket that have been provided. Make sure the PIC MCU is correctly installed in the SK40C board. The PIN 1 is just next to the little half moon shape or circle.

Next, connect the A-type USB to the computer using like picture below.

Page 11

ROBOT . HEAD to TOESK40C + 16F887 GETTING STARTED

After that, plug in the USB(mini) to the UIC00B. The power supply indication green LED will ON.

Lastly, connect one side of programming cable to box header of UIC00B and the other side to box header of SK40C(Target device) to be program.

I/O PORTI/O of microcontroller can be access through few method such as breadboard, extend jumper wire like picture below.

Extend I/O to another board using jumper wire.

Plug the I/O of the Sk40C into breadboard. Then, access I/O pin through breadboard.

Page 12

ROBOT . HEAD to TOESK40C + 16F887 GETTING STARTED

PROJECT 0My 1st PIC PROJECT, LOAD A SIMPLE LED BLINK

In this project, we are going to do a simple LEDs blinking using the LEDs on SK40C. In here, we are using both of the LEDs and blink it like a police car.Besides on learning electronic parts, you will also learn about some coding in C using HI-TECH C in MPLAB. COMPONENT NEEDED

LEDs ON SK40C

CONNECTIONFor this project, the LEDs was already connected to the pins RB6(PORTB.6) and RB7(PORTB.7). So, you may only have to configure the I/O pins as an output in programming part. To program the PIC16F887, connect the UIC00B to the ICSP Programmer. Make sure the power connection is correct and ON for SK40C. Open MPLAB and include the Project_0.c and click to compile and build .HEX file. After “Build Successful”, the PICKit2 should automatically run and program the .HEX file into PIC16F887. Finally, the LED1 and LED2 will be blink like the police car.

CODE OVERVIEWConfiguration for PIC16F887Figure below shows the Configuration for PIC16F887. The code above can be found at the Configuration bits (CONFIG1) in PIC16F887 data sheet.

HS External Crystal in High Speed

WDTDIS Watchdog Timer Disable

PWRTEN Power Up Timer Enable

BORDIS Brown Out Reset Disable

MCLREN MCLR Function Enabled

LVPDIS Low Voltage Programming Disable

Page 13

ROBOT . HEAD to TOESK40C + 16F887 GETTING STARTED

system.h

#define _XTAL_FREQ 20000000Besides that, same step by #define the crystal frequency(_XTAL_FREQ) according to your external crystal frequency using. In here, the default external crystal frequency using are 20000000 (20MHz).

#define SW1 RB0In here, we have already define the switch on SK40C board as RB0. User are no need to define again in the main coding.

#define LED1 RB6In figure above, using the code #define, we can replace the RB6 and RB7 as LED1 and LED2. By doing this, we can easily remember and the I/O port we are using.

#define LCD_E RB5#define LCD_RS RB4#define LCD DATA PORTDBesides that, user are not required again to define the LCD pin for SK40C. User only required to include the system.h file. Further detail on LCD please refer to Project_2.

#define TX RC6

#define RX RC7User are not required again to define the serial comunication (UART) pin for SK40C. User only required to include the system.h file. Further detail on UART please refer to Project_13.

void delay_ms(unsigned int ui_value);Function prototype is the declaration of a function that omits the function body but does specify the function's name, arity, argument types and return type. The symbol “ ; ” should put at the end of this line.

MAIN PROGRAM

void main (void)In figure above is the main program. 1st we have to type “void main(void)” at the 1st line to tell the micro-controller that this is the starting point of the program. Here, void main, tell the compiler the name of the functin which is main and it don't return any data(void).

PORTA = 0;Clear the PORT to prevent from the data latch on the PIC MCU.

TRISA = 0b00000000;is the Tri-STATE Register that declare the I/O ports as

Page 14

ROBOT . HEAD to TOESK40C + 16F887 GETTING STARTED

an INPUT or OUTPUT by (1=INPUT) and (0=OUTPUT). E.g. TRISB = 0b00001111 is to set the PORTB<7:4> to OUTPUT and PORT<3:0> as INPUT.

LED1 = 0;Then, we make the LED1 off by giving it a 0 at initial state as show above. So as the LED2 too. To make it on, just change the 0 to 1.

while(1)To make the program loop forever, we use while(1) function. while construct consists of a block of code and a condition. The condition is evaluated, and if the condition is true, the code within the block is executed. In here, we put (1) to indicated that the condition is true.

delay_ms(100);is a function call is an expression containing a simple type name and a parenthesized argument list. The argument list can contain any number of expression separated by commas. It can also be empty. In here, we put the arguments list as 100 which is 100ms.

Comment line //In the code, we can found the // on the right hand side of the code. The // is simply a comment in the code and is ignore by the compiler. Any code that behind the // is ignore by compiler and is just simply there for you, or everyone to reads the code.

Comments are essential in the code to help you to better understanding on what going on and how the code works. Comments can be put after the command as in the next line of the program.

On the other hand, you can also put comments into the block statement by using /* and */. E.g.:

/* All the code within the slash and asterisks will be ignore by compiler */

void delay_ms(unsigned int ui_value)is an function that will be call and perform in the main function. “void delay_ms”, here we are telling the compiler that out function is name delay_ms and it don't return any data (void).

(unsigned int ui_value)is the parameter use to insert value depending to our requirement. “int” mean integer which the minimum allow range are between -32767 to +32767(2 Bytes). “unsigned int” mean that the data we can insert is between 0 to 65535. There are many data type that we can assign and use that act as the temporary space for micro-controller to store the data.

while(ui_value-- > 0)in this condition, if the ui_value is subtract by one at the time and check if the ui_value is't still greater then 0. The code within the while loop will be running for many times until the ui_value is less then 0.

__delay_ms(1);This is the macro from HI-TECH complier which will generate 1ms delay base on value of _XTAL_FREQ.

Page 15

ROBOT . HEAD to TOESK40C + 16F887 GETTING STARTED

PROJECT 1LED BLINKING: LED CHASER

In project 1, you are about to experience how to program a LED chaser which can be increase the running speed by just a single button pushing. While releasing it, the running speed will slowly back to normal. In here, we are going to use total of 6 LEDs and will connected with a current limiting resistor before plug into the I/O port.

COMPONENT NEEDED

6x 1K RESISTOR

BREADBAORD

JUMPER WIRES

LEDs x6

CONNECTIONRefer to the figure below and connect the anode (+ve) of all LEDs to 1K Resistor and end of resistor is connected to the VDD (Power Supply). On the other hand, the cathode(-ve) of all LEDs are directly

connected to the PORTA.0 until PORTA.5. Besides that, we are going to use the switch 1 (SW1) on SK40C as our running speed controller.

The 1K Resistor are function to limit the current going through it to the safe value. So that it can protect the LEDs from burn out.

ADDITIONAL INFORMATIONLIGHT EMITTING DIODE

Page 16

ROBOT . HEAD to TOESK40C + 16F887 GETTING STARTED

There are few method to determine the anode and cathode side of the LED such as :

1. The flat spot on the lens/case of the LED is cathode.

2. The short lead (or leg) is cathode.3. The flag symbol inside the lens is cathode.

For further information about LED, please refer to this webpage.

RESISTOR COLOUR CODE

Above are the example of resistor with the colour code example. For more detail, refer to this webpage.

BREADBOARD OVERVIEW

Figure above have shows that the connection of half of the breadboard. The RED and BLACK colour line are usually been connect to power supply (VDD) and ground (GND). They are connected all the way from the beginning to the end but they did not connect to each other.

Besides that, the orange colour line are the part that we usually use to place the electronic component. They are connected in a straight line. There is a gap in the middle of the breadboard which are not connected to anything. This allow you to put integrated circuit across the gap and have each pin of the chip go to the different set of holes and therefore a different rial.

CODE OVERVIEW

static unsigned int time = 1000;As we can see that there is a static in front of the unsigned int. Static is a keyword which are commonly use in C programming to represent some value. Besides that, the value in static can be modified or replace. In here, we default the time

Page 17

ROBOT . HEAD to TOESK40C + 16F887 GETTING STARTED

value as 1000ms. For further information, please refer this wedpage.

LED1 = 0;Our main program are start with a while loop so that it can stay running non-stop. Refer to the connection circuit, the LEDs are connected to VDD at anode while the cathode is connected to the PORTB. So it means that to ON the LEDs, we need to give it a LOW bit (0). To OFF the LEDs, just simply give a HIGH bit (1) to LED1.

delay_ms(delay_period());To control the running speed, we have give a value to delay_ms loop by scanning through the delay_period(). The delay_period() loop will give a value to delay_ms on how many millisecond should the be delayed.

if (time > 150)As we declare on the start that time is set to 1000ms at the beginning. In this if loop, we check that is it true that the time is greater (>) than 150ms. if is true, then do the following code, if not then out of this loop.

if (SW1 == 0)If switch 1 is press, then do the subtraction of the time. if not then go to do the addition of the time.time = time – 100;In this case, it means that the default time 1000 is subtract by 100ms at each time the compiler come back to this subroutine.

If (time < 50){time = 100}

In this case, the time is check again whether the time is lesser (<) then 50ms. If it does, then change the time to 100ms. This is to prevent that the delay are too little and running speed too fast until we can't seen.

return time;As we have discuss before this, the value of static unsigned int time can be change or modified. In this code, after the time is been substrate or addition, it will return and change the value of time to become a new value. time = time + 100;

{if (time > 1000) time = 1000;}

If the switch 1 is not press, the time will be increase by 100ms at the time. Besides that, after increase, it will be check again whether the time is greater then 1000ms. If it does, then limit it to 1000ms.

References:1. http://en.wikipedia.org/wiki/Light-

emitting_diode

2. http://www.elexp.com/t_resist.htm

Page 18

ROBOT . HEAD to TOESK40C + 16F887 GETTING STARTED

PROJECT 2“Hello World” WITH PARALLEL LCD

For project 2, we will show you how to interface the SK40C board will parallel 16x2 LCD display. The connection are simple and the coding are easy to learn. We are going to display the “Hello World” on the LCD display by just adding a library that has been done for you.

COMPONENT NEEDED

16x2 LCD DISPLAY

CONNECTIONSK40C have offer a extra connecter for user to directly plug in the LCD display. This have save the user a lot of time from soldering the LCD display. The data pin of the LCD are connected to the PORTD while the RS of LCD are connected to RB4 and E of LCD are connected to RB5.Please refer to LCD datasheet1, LCD datasheet2 and SK40C user manual for further information.

ADDITIONAL INFORMATIONLIQUID CRYSTAL DISPLAYBefore start program the LCD, we have to know the function of each pin on the LCD display to avoid wrong connection.

Page 19

ROBOT . HEAD to TOESK40C + 16F887 GETTING STARTED

RS – LOW (0), data bytes transfer are treated as command.HIGH (1), character can be transfer to and from module.

R/W – LOW(0), write command or character data to the module.HIGH(1), read character data or status information from its registers.

E – HIGH(1) to LOW(0), writing to display.LOW(0) to HIGH(1), reading from display.

D0 to D7 – Eight data bus line.

There are numbers of cool experiment inside the LCD datasheet which have teach us how to entering the text, addressing, shifting the display, character entry mode, user-defined graphic, 4-bits data transfer.

LCD BACKLIGHT CONTROL

To make your LCD look cool, we can ON the backlight of the LCD by just put or solder a mini jumper to short LCD B/L.

LCD CONTRAST CONTROL

There is a potential meter who is purposely added for user to adjust the different contrast of LCD. Turn left or right to adjust the contrast level.

CODE OVERVIEW

Figure above have show that we have included an lcd.h and system.h file inside our main program. The reason we are doing this is to separated our code in different file and for easily to relocated back by user if got any error. To refer back the LCD program, all we need is double-click the lcd.c and it will show up.

What's inside “lcd.c” & “lcd.h” ?Inside lcd.c, we have already defined all the code that needed to control the LCD such as the coding in figure below:

As for lcd.h is an header file. These files allow programmers to separate certain elements of a program's source code into reusable files. Header files commonly contain forward declarations of classes, subroutines, variables, and other identifiers. Programmers who wish to declare standardized identifiers in more than one source file can place such identifiers in a single header file, which other code can then include whenever the header contents are required.

Page 20

Put Jumper to short LCD B/L

Adjust the potential meter for different contrast of LCD

ROBOT . HEAD to TOESK40C + 16F887 GETTING STARTED

system.h

In system.h, we use to give a name to a port using. Besides from defining the crystal frequency, in here, we have also define the PORT that required to use by LCD which is RB4, RB5 & PORTD.

lcd_initialize();Before start to send any data to LCD, the LCD should be initialize 1st. The initialization process are such as, clear LCD display, cursor home, cursor on/off, display/cursor shift and function set.

lcd_home();To make sure that the cursor is back to home. We need to send a command for it which is in binary 00000010.

lcd_putstr(“Hello World”)Send a string to LCD data bus to display it on the screen. The symbol “” is mean what the word or text inside are in ASCII format. The compiler will automatically convert it to binary and send to the required port. Finally the texts Hello World will be display on the screen.

References: http://www.cytron.com.my/usr_attachment/SK40C_Users_Manual.pdf

Page 21

ROBOT . HEAD to TOESK40C + 16F887 GETTING STARTED

PROJECT 3DIGITAL INPUT: PUSH BUTTON

For this project, we will discover how to manage a digital input signal. As we know that digital signal is either HIGH (1) and LOW (0) only. But for different integrated circuit such as PIC MCU, we need to define at the beginning of the code that the port using are either input or output and also declaration for digital or analog signal send and received.

COMPONENT NEEDED

PUSH BUTTON & LEDS ON SK40C

PUSH BUTTON

BREADBOARD

JUMPER WIRES

1K Resistor

CONNECTIONThere is no need to connect extra push button to SK40C board because inside SK40C, there is already have 2 push button on board which is purposely prepared for user to use it. These push button are already connected to RB0 and RB1 while external push button are connected to RB2. So all we need to do is just declare there 3 port as INPUT. As for the output, we use the on board LEDs to show us that we have push the push button. The LEDs are connect to RB6 and RB7. To use the LEDs, we need to declare it as an OUTPUT.

ADDITIONAL INFORMATIONBesides on using the push button on SK40C, we can use others component to replace it such as limit switch, keypad and etc. Referring to the figure below, input signal read at HIGH are between 3.5V to 5V

Page 22

ROBOT . HEAD to TOESK40C + 16F887 GETTING STARTED

and while LOW are read between 1.5V to 0V. For output of the external device are giving the digital value of HIGH at between 4.95V to 5V and LOW at between 0.05V to 0V. As long as the logic input and output voltage are within this level, the PIC MCU can read it without any conversion. For more information, please refer to this webpage.

On the other hand, by adding an additional switch to the PIC16F887, the switch have to be pull-up due to the some port are not have this pull-up function and it may effect out coding if we are reading the push button I/O. Besides on pull-up resistor, there are also an pull-down resistor such as showing in picture below.

In this project, we are using one additional push button so it may need to be pull-up like the picture showing. For more information about pull up resistor. Please refer to this webpage.

CODE OVERVIEWPORTA = 0;To prevent the data latch, we clear PORTA so that it won't affect Tri-State Register (TRIS).

TRISB = 0b00000111;Push buttons is connected to RB0 to RB2. To make in as an input, we have set HIGH(1) to TRISB.0, TRISB.1 and TRISB.2. The rest are declare as an output port.

ANSEL = 0;ANSEL is an analog select high register for PORTA. LOW(0) the register will make it DIGITAL I/O while HIGH(1) it will make it an ANALOG I/O.

ANSELH = 0;ANSELH is an analog select high register for PORTB. LOW(0) the register will make it DIGITAL I/O while HIGH(1) it will make it an ANALOG I/O.

Page 23

ROBOT . HEAD to TOESK40C + 16F887 GETTING STARTED

while (SW1 == 0)Check whether the switch 1 is LOW(0). If it does then do the following code which is blink the LED1 and loop forever. The symbol == is usually use to represent the signal in digital. While = is usually use to represent the signal in analog.

References:1. http://en.wikipedia.org/wiki/Pull-up_resistor

2. http://www.seattlerobotics.org/encoder/mar 97/basics.html

Page 24

ROBOT . HEAD to TOESK40C + 16F887 GETTING STARTED

PROJECT 4ANALOG SENSOR: POTENTIALMETER & BB-PSJ

In this part, we are going to discuss about how to write the Analog to Digital Converter code which has become the most popular question among the students. We are going to use PIC16F887 with have contain of 10-bits binary result and a potential-meter to adjust the voltage different and display it in the LCD display.

COMPONENT NEEDED

16 x 2 LCD Display

POTENTIALMETER(5K)

BB-PSJAnalog Joystick Breakout

Board

BREADBOARD

JUMPER WIRES

CONNECTIONThe connection for the potential-meter are very easy. Just connect one end to VDD and the other end to GND while the middle pin is connected to RA0. By referring to the PIC16F887, there are total 14 analog pins that we can choose. In here we use RA0 as out ADC input pin. For thumb joystick, connect VDD as 5V and GND. X-A connected to RA1, Y-A connected to RA5 and SW connected to RA2.

ADDITIONAL INFORMATIONADC enable the microcontroller to recognize, not only whether a pin is driven to logic zero or one (0 or +5V), but to precisely measure its voltage and convert it into a numerical value, i.e. digital format. The whole procedure takes place in the A/D converter module which has the following features:

1. The converter generates a 10-bit binary result using the method of successive approximation and

Page 25

ROBOT . HEAD to TOESK40C + 16F887 GETTING STARTED

stores the conversion results into the ADC registers (ADRESL and ADRESH).2. There are 14 separate analog inputs.

3. The A/D converter allows conversion of an analog input signal to a 10-bit binary representation of that signal.

4. By selecting voltage references Vref- and Vref+, the minimal resolution or quality of conversion may be adjusted to various needs.

For detail information, please refer to the PIC16F887 datasheet and also this webpage.

CODE OVERVIEWADC CONFIGURATION

ADCS1 = 1;ADCS0 = 0;ADCS is the A/D Conversion Clock select bits. In here we have selected the conversion clock as Fosc/32. Which the Fosc using are 20MHz.

ANS0 = 1;

Refer to the PORTA Analog select register. We already configure the RA0 which is ANS0 as an analog I/O. While the rest of PORTA pins as an digital I/O.

ADFM = 1;ADFM is the conversion result format select bit. In here, we give a value 1 to configure it as an Right Justified. While if the value 0 is given, the format are in Left justified.

VCFG1 = 0;VCFG0 = 0;VCFG is the voltage reference bit. Which if VCFG1 is 0, the GND pin will be configure as an VSS pin. On the other hand, VCFG0 is 0, is mean that the voltage supply pin is configure as VDD.ADON = 0;ADON is the ADC enable bit. If the ADON is 0, the ADC is OFF. While if the ADON is 1, the ADC is ON.

Page 26

ROBOT . HEAD to TOESK40C + 16F887 GETTING STARTED

ADC READ

unsigned int pot = 0;Initialize and make the “pot” as a 0 value at the every time the code jump into this subroutine.

__delay_ms(1);The purpose of the 1ms delay in here is to wait the holding capacitor in ADC module to fully charge.

GODONE = 1;After the A/D Conversion started, set this register and wait it to become LOW(0) which mean that it's has done the conversion.

pot = (unsigned int) ADRESH << 8;After done conversion, the value of ADRESH memory of ADRESH is change to 2 Bytes and shifted LEFT by 8.E.g.: ADRESH = 0000 0011 (unsigned int)ADRESH = 0000 0000 0000 0011 (unsigned int)ADRESH = 0000 0011 0000 0000 (<< 8)

pot = pot + ADRESL;After the value ADRESH is shifted. The value are keep in pot. After that, the value in pot will be added with ADRESL.E.g: pot = 11 0000 0000 ADRESL = 1111 1111

Final pot result = 11 1111 1111 (10 bits)

LCD & ADC INITIALISE

Before the main code is start running, we initialize the LCD and also the ADC.

MAIN PROGRAM CASE 1 : POTENTIALMETER

CHS2 = 0;CHS1 = 0;CHS0 = 0;Analog channel select bit which is use to select the analog port we are using. In this case we are using the RA0. By referring to the datasheet, RA0 is on the CHS<2:0> = 000;.

for(i=0 ; i<10 ; i++) {adc_value = adc_value + ui_adc_read();}

In this case, the value of ADC have been taken and add together for 10 times.

Page 27

ROBOT . HEAD to TOESK40C + 16F887 GETTING STARTED

adc_value = adc_value/10;After the adc_value is been added by 10 times. It must be divided by 10 to get the average value. The purpose of this is to get more accurate value.

lcd_bcd(4,adc_value);Convert the ADC output value in BCD and display it in LCD. In here, we have limit it to display maximum 4 digit only. volt_value = (adc_value*50)/102.4;To display the voltage of the analog. We have to convert the digital value in the output of the ADC by applying the formula. E.g. : If adc_value is 1022 (decimal)

1022*50 = 51100.51100/102.4 = 499(volt_value)499 / 100 = 4(1st digit)499%100 = 99, 99/10 = 9(2nd digit)499%10 = 9(3th digit)

CASE 2 : JOYSTICK

Display the joystick X-axis adc value which is from 0 to 1022.

Display the joystick Y-axis adc value which is from 0 to 1022.

Check if the push button on joystick is press. If press then display (“0”). If not press then display (“1”).

References:http://www.mikroe.com/eng/chapters/view/8/chapter-7-analog-modules/

Page 28

ROBOT . HEAD to TOESK40C + 16F887 GETTING STARTED

PROJECT 5ANALOG SENSOR: TEMPERATURE USING LM35

Nowadays, there are many type of temperature sensor is come with different output form and also the temperature range such as thermocouple, thermistor, infrared, RTD. In here, we pick LM35 as our temperature sensor due to it have a linear output and also suitable for normal use like weather temperature measuring.

COMPONENT NEEDED

16 x 2 LCD Display

LM35 TEMPRETURE SENSOR

BREADBOARD

JUMPER WIRES

CONNECTIONThe connection for the LM35 are very easy. Just connect one end to VDD (RED wire)(4V to 20V) and the other end to GND(BLACK wire) while the middle pin (YELLOW wire) is connected to RA0. By referring to the PIC16F887, there are total 14 analog pins that we can choose. In here we use RA0 as out ADC input pin.

Page 29

ROBOT . HEAD to TOESK40C + 16F887 GETTING STARTED

ADDITIONAL INFORMATIONThe LM35 series are precision integrated-circuit temperature sensors, whose output voltage is linearly proportional to the Celsius (Centigrade) temperature. The LM35 does not require any external calibration or trimming to provide typical accuracies of ±1⁄4˚C at room temperature and ±3⁄4˚C over a full −55 to +150˚C temperature range. Low cost is assured by trimming and calibration at the wafer level. The LM35’s low output impedance, linear output, and precise inherent calibration makeinterfacing to readout or control circuitry especially easy. It can be used with single power supplies, or with plus and minus supplies. As it draws only 60 µA from its supply, it has very low self-heating, less than 0.1˚C in still air. The LM35 is rated to operate over a −55˚ to +150˚C temperature range.

Features~ Calibrated directly in ° Celsius (Centigrade)~ Linear + 10.0 mV/°C scale factor~ 0.5°C accuracy guaranteeable (at +25°C)~ Rated for full −55° to +150°C range~ Suitable for remote applications~ Low cost due to wafer-level trimming~ Operates from 4 to 30 volts~ Less than 60 μA current drain~ Low self-heating, 0.08°C in still air~ Nonlinearity only ±1⁄4°C typical~ Low impedance output, 0.1 W for 1 mA load.

Page 30

ROBOT . HEAD to TOESK40C + 16F887 GETTING STARTED

CODE OVERVIEW

celsuis=adc_value/2; LM35 have already designed to give an exact value of temperature in Celsius. By referring to the graph, the ADC output are only need to divide by 2 to get the result in Celsius.

kelvin = ((celsius*100)+27315)/100; Kelvin formula are (Celsius + 273.15). But for microcontroller, it will not read the result after the DOT. E.g. : if result is kelvin = 300.15, the mcrocontroller will only read 300 only and will ignore .15. In order to get the result after the DOT, we times the result in 100 so that we can get the result after the DOT.

fehrenheit = ((celsius*18)/10)+32; Fahrenheit formula are ([celsuis*1.8]+32). In the coding, the formula have been times will 10 times to get the exact result.

reaumur = (celsuis*8)/10; Reaumur formula are (celsius*0.8). Same as the previous technic, in order to let microcontroller to get the more accurate result, we times it with 10 to get the result after the DOT.

References: http://www.national.com/ds/LM/LM35.pdf

Page 31

ROBOT . HEAD to TOESK40C + 16F887 GETTING STARTED

PROJECT 6ANALOG SENSOR: RANGE USING ULTRASONIC

RANGE FINDER

There are many sensor to measure a range such as using Ultrasonic, Infrared and more. In here, we are going to experience how to measure a range using Maxbotic Maxsonar-EZ1 ultrasonic range finder which it will give the output value in inch.

COMPONENT NEEDED

16 x 2 LCD Display

MAXSONAR-EZ1

NPN TRANSISTOR 2N2222

BREADBOARD

JUMPER WIRES

1K RESISTOR 4.7K RESISTOR

CONNECTIONMaxsonar-EZ1 ultrasonic sensor are operate in +5V and draw on 2mA of current. For this sensor, it have 3 modes of output which is UART, analog and pwm. UARTMaxsonar-EZ1 will send the output if in ASCII format. For this sensor, the output are in RS232 format which mean that the HIGH(1) bit are at 0V while the LOW(0) bit are 5V. We need to connect the TX of sensor connect to NPN while RX of sensor to TX of microcontroller just like figure below.

Page 32

ROBOT . HEAD to TOESK40C + 16F887 GETTING STARTED

Analog Connect the analog output of the ultrasonic sensor to the RA0 of microcontroller.

PWMConnect this pin to the RB2 of microcontroller.

ADDITIONAL INFORMATIONMaxsonar-EZ1The Maxsonar-EZ1 sensor offer a very short to long range detection which is from 0-inches to 254-inches plus with a very low power consumption. It has provided sonar range information from 6-inches out to 254-inches with 1-inches resolution. Object from 0-inches to 6-inches are range as 6-inches. It has 3 modes selection for the output range which is:

~ Serial, 0V – 5V, 9600 Baud~ Analog, 10mV/inch~ Pulse Width, 147us/inch

For detail information, please refer the Maxsonar-EZ1 datasheet .

EUART of PIC16F887The Enhanced Universal Synchronous Asynchronous Receiver Transmitter (EUSART) module is a serial I/O communication peripheral. It is also known as Serial Communications Interface (SCI). It contains all clock generators, shift registers and data buffers necessary to perform an input or output serial data transfer independently of the device program execution. As its name states, apart from the usage of clock for synchronization, this module can also establish asynchronous connection, which makes it irreplaceable in some applications.

EUSART Asynchronous Mode

EUSART Asynchronous Transmitter

Page 33

ROBOT . HEAD to TOESK40C + 16F887 GETTING STARTED

EUSART Asynchronous Receiver

CODE OVERVIEWGLOBAL VARIABLE

unsigned int T0=0, T=0, TH=0;unsigned char data[6] = {0};In this global variable, we have already declare that To, T, TH are 0. Same as data[0] to data[6] are 0.

INTERRUPT ISR

static void interrupt isr(void)For every interrupt subroutine, void interrupt isr(void) MUST be added in the program. In here, we extra added a static is because we need to return the result of the program that executed in the interrupt

subroutine back to the main program. On the other hand, there was 2 interrupt that have been set in main program which is timer 0 and also PORTB change interrupt.

If (T0IF){T0IF = 0;To +=0x100;}

Check if the timer 0 is interrupt . If interrupt flog is HIGH(1), the timer 0 is interrupt. Clear the timer flag to LOW(0) and add the increase To and make it 16-bit.

If (RBIF){RBIF = 0;

if (PWM_IN){TMR0 = 0;To = 0;}

else TH = TMR0 + To;}

If PORTB interrupt-on-change flag is set, we reset the flag bit by giving a value 0 to RBIF. After that we check whether if the input from PWM is in HIGH(1) or LOW(0). If HIGH(1), reset timer and To to 0. if LOW(0), the TMR0 value is added with To value. INTERRUPT ON CHANGE

Page 34

ROBOT . HEAD to TOESK40C + 16F887 GETTING STARTED

IOCB<7:0> = 00000100For enabled interrupt-on-change pins, the present value is compared with the old value latched on the last read of PORTB to determine which bits have changed or mismatched the old value. The ‘mismatch’ outputs of the last read are OR’d together to set the PORTB. Change Interrupt flag bit (RBIF) in the INTCON register. In here, we make the PORTB.2 as interrupt on change. Please refer PIC16F887 for detail.

RBIE = 1;PORTB Change Interrupt Enable Bit. HIGH(1) to enable while LOW(0) to disable. If detected the change on PORTB.2.

TIMER 0 CONFIGURATION

T0CS = 0;TMR0 Clock Source Select Bit. We choose LOW(0) for selecting the Internal instruction cycle clock. Let's say our default used crystal is 20MHz. The clock cycle is 20MHz/4 = 5MHz.

PSA = 0;Prescaler Assignment Bit. We choose LOW(0) to assign the precaler to the timer 0 module.

PS<2:0> = 111;Choose the TMR0 prescaler rate to 256.

T0IE = 1;Timer 0 Interrupt enable bit. HIGH(1) to ON the timer 0 interrupt.

TMR0 = 0;Timer 0 module register from 0x00 to 0xFF. The timer 0 will start counting from the value given until the next 0x00 and trigger the overflow flag.

GIE = 1;PEIE = 1;GIE,Global Interrupt Enable Bit. HIGH(1) to enable all unmasked interrupt. LOW(0) disable all interrupt.

PEIE,Peripheral Interrupt Enable Bit. HIGH(1) to enable all unmasked peripheral interrupt. LOW(0) to disable all peripheral interrupt.

EUSART CONFIGURATION

BRG16 = 0;BRG16, 16-bit Baud Rate Generator bit. HIGH(1) to set it to 16 bit baud rate generator. LOW(1) to 8-bit baud rate generator.SYNC = 0;EUSART Mode Select bit. HIGH(1) to synchronous mode. LOW(0) to asynchronous mode.

TX9 =0;RX9 = 0;8-Bits transmit enable bit and 8-Bits reception.

BRGH = 1;High Baud rate select bit are set to High Speed.

Page 35

ROBOT . HEAD to TOESK40C + 16F887 GETTING STARTED

SPBRG = 129;SPBRG is in decimal value which is use to select the baud rate of 9600 with condition of SYNC = 0, BRGH = 1, BRG16 = 0, Fosc = 20MHz. Please refer PIC16F887 datasheet for detail.

SPEN = 1;SPEN is serial port enable bit which will configure RX/DT and TX/CK pins as serial port pins.

CREN = 1;Continuously receive the data enable bit.

TXEN = 1;Transmit enable to send data out through serial communication port TX pin.dummy = RCREG;Store the data in the dummy to clear the buffer of RCREG.

MAIN PROGRAMCASE 1 : ANALOG READING

In analog reading, by including the adc.c & adc.h module, the adc result will be save in adc_value after been added by 10 times and divided by 10 to get the average result. By referring to the Maxsonar-EZ1 datasheet. The output are 10mV/Inch and the maximum range are given 2.55V. By applying formula:

adc_value = 2.55/5*1024 = 522(decimal)522 / 256-inch = ~2

CASE 2 : PWM READING

range_pwm = TH;We have already declare that TH is the timer value of the PWM reading. The TH value are insert to range_pwm.

range_pwm = (range_pwm*100)/288; ~ each value = 256*4/20mhz = 51.2us ~ 1 inch = 147us ~ 147us/51.2us = 2.88

CASE 3 : UART READING

Maxsonar-EZ1 in UART mode are directly given an ASCII value to the microcontroller which start with an “R”, then follow by 3 value of range such as 255-inch in “2”, “5”, “5” and then lastly is the carriage return which is totally of 5 data to be received.

If (RCREG == 'R') data[k=0] = RCREG;

Page 36

ROBOT . HEAD to TOESK40C + 16F887 GETTING STARTED

Check if the RCREG are ASCII value 'R'. if yes then save the data at data[0] by reset the k = 0.if (data[0] == 'R') data[k++] = RCREG;After make sure the data[0] is 'R'. Then next step is to save the next RCREG value in data[1], data[2], data[3] by increasing k by 1 at the time.

send_lcd_data(1,data[1]);By referring to LCD library, by sending a 1 will toggle ON the RS of the LCD which is read as an character for LCD. Then send the ASCII data that given by the Maxsonar-EZ1 to the LCD.

CASE SWITCHING

while (SW1 == 0 );Check if switch 1 is still holding. If yes then keep looping until switch 1 is release.

If (++mode > 3){mode = 1;}

Check if mode is increase until 3 or more. If yes then reset back to mode 1.

References:http://www.mikroe.com/eng/chapters/view/7/chapter-6-serial-communication-modules/

Page 37

ROBOT . HEAD to TOESK40C + 16F887 GETTING STARTED

PROJECT 7ANALOG SENSOR: RANGE USING ANALOG

DISTANCE SENSOR

Analog distance sensor which have a function that same as the Ultrasonic sensor which is use to measure range. But for this sensor, the output value are in centimeter(cm) and also the output are only given an analog value. To get the result, an mathematics formula are required to apply into our C-code for calculation.

COMPONENT NEEDED

16 x 2 LCD Display

ANALOG DISTANCE SENSOR

SN - GP2Y0A21

BREADBAORD

JUMPER WIRES

CONNECTIONAnalog Distance Sensor Analog distance sensor have 3 pin which is VDD, GND and Vout.

1 – Vout 2 – GND 3 – VCC (5V)*User must refer to analog distance sensor datasheet before connect power to sensor. Cable's color are not standard.

By referring to the figure below, the YELLOW colour wire are connected to RA0, RED wire are VDD and BLACK wire are GND.

Page 38

ROBOT . HEAD to TOESK40C + 16F887 GETTING STARTED

ADDITIONAL INFORMATION

Referring to the chart above are the output voltage(V) versus distances(cm) of the analog distance sensor. By plotting the output voltage versus inverse number distance (1/cm), we can get the linear relation such as in figure below.

The linear equation is y = 20.99x + 0.19, where y is voltage output and x invert distance. Notice that the trusted output voltage are about 0.4 to 2.8 V.

CODE OVERVIEW

Vout = (adc_value*500000)/1024;After take the ADC output value for 100 times. The adc_value are time with 500000 and divided by 1024 to eliminate the DOT and get the bigger value. Besides that, we also get the value after the DOT.

E.g : adc_value = 1022,~ if using adc_value*5/1024, Vout = 4

~ if using adc_value* 500000/1024 Vout = 499023

Page 39

ROBOT . HEAD to TOESK40C + 16F887 GETTING STARTED

if ((Vout > 43945) && (Vout < 279785))Check if Vout are between 0.4V to 2.8V. If the value is more then less then 0.4 and more then 2.8 are not valid and LCD will display “OUT OF RANGE”. See example below to get the Vout.E.g-1 : If using Vout = adc_value*5/1024 Vout = 2.8V 2.8V*1024 / 5 = 573. (convert to Decimal) 573*5 / 1024 = 2 (Convert to Volt)E.g-2 : If using Vout = adc_value*500000/1024 Vout = 2.8V 2.8V*1024 / 5 = 573. (convert to Decimal) 573*500000/1024 = 279785. (Convert to Volt)

range_an = (Vout – 19000)/2099;Refer example below on how to get the range in centimeter(cm).E.g-1 : if Vout = 279785 279785 – 19000 = 260785 260785 / 2099 = 124 1000 / 124 = 8

References: http://mcu-programming.blogspot.com/2006/09/distance-measurement-sensor.html

Page 40

ROBOT . HEAD to TOESK40C + 16F887 GETTING STARTED

PROJECT 8PIEZO BUZZER: MELODY – BIRTHDAY SONG

Piezo buzzer, generally use as a sensor and actuator which are use to measure force, pressure , tools for positioning object and etc. As for this project, we are going to use it to generate a melody by applying PWM frequency to it.

COMPONENT NEEDED

PIEZO BUZZER

CONNECTIONFor piezo buzzer, connect any of the wire to ground(GND) and the other wire to RC1.

ADDITIONAL INFORMATIONINSIDE OF PIEZO BUZZER

HOW PIEZO BUZZER WORKS

RECOMMENDED OPERATING CIRCUIT

Page 41

ROBOT . HEAD to TOESK40C + 16F887 GETTING STARTED

CODE OVERVIEWsystem.h

#define A4 78In system.h, we firstly declare each delay period value according to the musical tone chart.

MAIN PROGRAM

unsigned int birthday[]Assign an array for birthday[] so that it can increase 1 at the time by just simply give bithday[] a number.E.g: birthday [4], the delay period are N which is 132.

unsigned int delay_pariod[]Assign the delay period for each tone. The delay_period much be within 0 to 65535.

PR2 = (birthday[wait]/2);Assign timer 2 value (PR2) with the delay period over 2 to generate the PWM period.

tone_out(birthday[wait],delay_period[wait]*20000);Call tone_out subroutine and also assign the birthday[wait] value and delay_period times with 20000.

E.g: delay_period for C4_1 = (1) * 20000 = 20000

while(delay-- > 0)Loop forever if the 30000 is decrease by 1 at the time is still greater then 0.

pwm_set_duty_cycle(tone);Set the duty cycle of the PWM with birthday[] value.

References:1. http://www.tdk.co.jp/tefe02/ef532_ps.pdf 2. http://www.buzzer-

speaker.com/manufacturer/introduction%20of%20piezo%20buzzer.htm

Page 42

ROBOT . HEAD to TOESK40C + 16F887 GETTING STARTED

PROJECT 9ANALOG SENSOR: LIGHT DETECTION USING LDR

A photoresistor or light dependent resistor (LDR) is a resistor whose resistance decreases with increasing incident light intensity. It can also be referred to as a photoconductor. In here, we going to do a simple connection of LDR and display the ADC and Voltage value on LCD.

COMPONENT NEEDED

16 x 2 LCD Display

LIGHT DEPENDENT RESISTOR

1K RESISTOR

BREADBOARD

JUMPER WIRES

CONNECTION

There are 2 way of constructing the voltage divider which is LDR on top or LDR on bottom.

LDR ON TOPRefer to the figure below, there are total 3 wires using. RED wire connect between LDR and VDD. Black wire connect between resistor and GND. Lastly, YELLOW wire are connect between RA0 and between LCD and resistor. Please refer this webpage for further detail.

Page 43

ROBOT . HEAD to TOESK40C + 16F887 GETTING STARTED

LDR ON BOTTOMRefer to the figure below, there are total 3 wires using. BLACK wire connect between LDR and VDD. RED wire connect between resistor and GND. Lastly, YELLOW wire are connect between RA0 and between LCD and resistor. Please refer this webpage for further detail.

ADDITIONAL INFORMATION

MEASURING RESISTANCE OF LDRTo measure the LDR resistance, just probe directly +ve to one side of LDR and -ve to the other side of LDR.

LDR VOUT MEASUREMENT

In this case, we give the Vin as 5V and resistor are 1K.

E.g-1: LDR on Top, Rtop = 10K Vout = 1K x 5V

1K + 10K = 0.45V

E.g-2: LDR on bottom, Rbottom= 10K Vout = 10K x 5V

10K + 1K = 4.54V

Page 44

ROBOT . HEAD to TOESK40C + 16F887 GETTING STARTED

CODE OVERVIEW

for (i=0 ; i<10 ; i++){adc_value = adc_value + ui_adc_read();}

Read and store the ourput value of ADC for 10 times.

adc_value = adc_value/10;Divide the adc_value by 10 times to get the average result.

volt_value = (adc_value*50)/102.4;Same as project_4, to display the output in voltage, we need to recalculate the adc_value given and times with 50 and divided by 102.4.

References:1. http://www.technologystudent.com/elec1/ld

r1.htm 2. http://www.doctronics.co.uk/ldr_sensors.ht

m

Page 45

ROBOT . HEAD to TOESK40C + 16F887 GETTING STARTED

PROJECT 10DRIVING DC BRUSH MOTOR WITH MD10C

MD10C is an enhanced version of the MD10B which is designed to drive high current brushed DC motor up to 10A continuously. It offers several enhancements over the MD10B such as support for both locked-antiphase and sign-magnitude PWM signal as well as using full solid state components which result in faster response time and eliminate the wear and tear of the mechanical relay.

COMPONENT NEEDED

16 x 2 LCD Display

MD10C

DC MOTORSPG10

JUMPER WIRES

CONNECTIONThis latest MD10C have offer for both Sign-Magnitude PWM and Locked-Antiphase PWM mode. The only difference between these 2 mode connection are Sign-Magnitude PWM use 2 control signal while Locked-Antiphase PWM use only 1 control signal. Please refer MD10C datasheet.

SIGN-MAGNITUDE PWMFor sign-magnitude PWM operation, 2 control signals are used to control the speed and direction of the motor. PWM is feed to the RC1 pin to control the speed while DIR pin is used to control the direction of the motor. Please refer figure and table below for Sign-Magnitude PWM connection.

MD10C PIN NAME PIC16F887

POWER + VDD (+5V)

POWER - GND

MOTOR A MOTOR +

MOTOR B MOTOR -

VIN VDD (+12V)

DIR RA0

PWM RC1

GND GND

Page 46

ROBOT . HEAD to TOESK40C + 16F887 GETTING STARTED

LOCKED-ANTIPHASE PWMFor Locked-Antiphase PWM operation, only 1 control signal is needed to control the speed and direction of the motor. PWM pin is connected to logic high while the DIR pin is being feed with the PWM signal. When the PWM signal has 50% duty cycle, the motor stops running. If the PWM has less than 50% duty cycle, the motor will turn CW (or CCW depending on the connection). If the PWM signal has more than 50% duty cycle, motor will turn CCW (or CW depending on the connection). Please refer figure and table below for Locked-Antiphase PWM connection.

MD10C PIN NAME PIC16F887

POWER + VDD (+5V)

POWER - GND

MOTOR A MOTOR +

MOTOR B MOTOR -

VIN VDD (+12V)

DIR RC1

PWM RA0

GND GND

ADDITIONAL INFORMATIONMD10C – ENCHANCED 10A DC MOTOR DRIVERThe MD10C has been designed with the capabilities and features of:• Bi-directional control for 1 brushed DC motor.• Support motor voltage ranges from 3V to 25V.• Maximum current up to 10A continuous and 15A peak (10 second).• 3.3V and 5V logic level input.• Solid state components provide faster response time and eliminate the wear and tearof mechanical relay.• Fully NMOS H-Bridge for better efficiency and no heat sink is required.• Speed control PWM frequency up to 10KHz.• Support both locked-antiphase and sign-magnitude PWM operation.• Dimension:75mm x 43mm

Page 47

ROBOT . HEAD to TOESK40C + 16F887 GETTING STARTED

SPECIFICATION AND LIMITATION

JUMPER – BOARD SUPPLY SELECTOR

PWR : Board is powered by motor power input. Only select this when motor power input is > 14V.

VIN : Board is powered by VIN. 12V must be supplied to the VIN pin and motor power input can be 3V to 25V.

SPG10 - METAL GEARMOTORThere are 3 types of metal gear motor which come with the difference gear ratio, stall torque and free run RPM. Please refer to SPG10 datasheet for detail.

CODE OVERVIEWMAIN PROGRAM

sign_magnitude_pwm();Call and execute “sign_magnitude_pwm” subroutine.

pwm_set_duty_cycle(0);Set PWM duty cycle to 0.

SIGN-MAGNITUDE PWM MODE

DIR = 1;Set the motor spinning direction. HIGH(1) to CW, LOW(0) to CCW.(Depend on motor connection) for (speed = 350;speed<1024;speed++)Increase the speed by 1 at the time which started

Page 48

ROBOT . HEAD to TOESK40C + 16F887 GETTING STARTED

from 350 until 1024.

pwm_set_duty_cycle(speed);Send the speed to the pwm duty cycle to generate the PWM.

LOCKED-ANTIPHASE PWM Mode

for (speed=1024;speed>0;speed--)Decrease the speed by 1 at the time started from 1024 until 0.

SWITCH 1 PRESS CHECK

Check if switch 1 is press by continuously loop for 200 times.

PWM INITIALIZE

PR2 = 0xFF;Send the timer 2 value(PR2) as 0xFF.

T2CKPS1 = 0;T2CKPS1 = 1;Set timer 2 prescaler to 1:4.

TMR2ON = 1;HIGH(1) to Timer 2 ON, LOW(0) to Timer 2 OFF

CCP2M3 = 1;CCP2M2 = 1;CCP2M1 = 0;CCP2M0 = 0;Configure the CCP2 module as PWM mode.

CCPR2L = 0x00;Initialize the PWM duty cycle at 0 at the start time.

PWM DUTY CYCLE

CCP2CON<5:4>These bits are the two LSB of the PWM duty cycle. CCPR2L = ui_duty_cycle >> 2;These are the 8 MSB of the PWM duty cycle.

Page 49

ROBOT . HEAD to TOESK40C + 16F887 GETTING STARTED

PROJECT 117 SEGMENT DISPLAY WITH DIRECT I/O

Nowadays, 7 segment has become the most popular display unit on market because it is cheap, easy to program and small. On market, we can found that there was 2 types of 7 segment which is common anode and common cathode. In this project, we are going to use 7 segment with common cathode and directly interface to microcontroller.

COMPONENT NEEDED

7 SEGMENT DISPLAY x2(COMMON CATHODE)

BREADBOARD

1K RESISTOR x2

JUMPER WIRES

CONNECTIONFrom figure below, we can see that the 1st 7 segment are connected to PORTC.0 to PORTC.6, while 2nd 7 segment are connected to PORTD.0 to PORTD.6. Both of the 1K resistor are connected to ground(GND).

ADDITIONAL INFORMATION7 segment have separated to 2 types which is common cathode and common anode which show in figure below.

Page 50

ROBOT . HEAD to TOESK40C + 16F887 GETTING STARTED

COMMON CATHODECommon cathode means that all the ground (GND) are all connected together. To ON the LED inside, we have to give a signal HIGH(1) or +5V to the input port of 7 segment.

COMMON ANODECommon anode means that all the voltage in (VCC) are connected together. To turn ON the LED inside, a signal LOW(0) or 0V are required to the 7 segment input port.

1K RESISTORBy refering to the circuit. We have connected 1K resistor to each 7 segment to limit the current flowing through it so that it may prevent the 7 segment from spoil.

7 SEGMENT INPUT TO PIC MCURC7/RD7

RC6/RD6

RC5/RD5

RC4/RD4

RC3/RD3

RC2/RD2

RC1/RD1

RC0/RD0

dp G F E D C B A

0 0 1 1 1 1 1 1 '0'

0 0 0 0 0 1 1 0 '1'

0 1 0 1 1 0 1 1 '2'

0 1 0 0 1 1 1 1 '3'

0 1 1 0 0 1 1 0 '4'

0 1 1 0 1 1 0 1 '5'

0 1 1 1 1 1 0 1 '6'

0 0 0 0 0 1 1 1 '7'

0 1 1 1 1 1 1 1 '8'

0 1 1 0 0 1 1 1 '9'

Page 51

ROBOT . HEAD to TOESK40C + 16F887 GETTING STARTED

CODE OVERVIEWMAIN PROGRAM

unsigned int dis1[]For this part, we use ARRAY to continuously display the 7 segment character from 0 to 9 and also from 9 to 0.

SEG1_dis = dis1[num];7 segment 1 will continuously display the number from dis1[] once the num are increase 1 at the time.

system.h

#define dis_1 0b00000110In system.h, we have already declare the output display of 7 segment.

#define SEG1_dis PORTCIn here, we have selected the output port that the data will be send through.

References:1. http://en.wikipedia.org/wiki/Seven-

segment_display

2. http://www.see.ed.ac.uk/~gaa/DigilabNotes /Digilab/Components/node7.html

Page 52

ROBOT . HEAD to TOESK40C + 16F887 GETTING STARTED

PROJECT 127 SEGMENT DISPLAY WITH CD4511 ENCODER

Besides on directly connected 7 segment with direct I/O port from microcontroller, we can also use the CD4511 (7 segment encoder) to help on decreasing the microcontroller I/O port and only required to send the binary data.

COMPONENT NEEDED

7 SEGMENT DISPLAY x2(Common Cathode)

BREADBOARD

1K RESISTOR x2

CD4511 7 SEGMENT ENCODER

JUMPER WIRES

CONNECTIONReferring to the figure below, RED and BLACK wire are VDD and GND and are share to both CD4511 encoder. Besides that, the LT, BI, LE pin from CD4511 are share to the same port of PIC MCU which is PORTB.0 , PORTB.1 and PORTB.2. Lastly, the LEFT CD4511 binary input (A,B,C,D) are connected to PORTC.0 until PORTC.3. While RIGHT CD4511 binary input (A,B,C,D) are connected to PORTD.0 until PORTD.3.

FROM CD4511 TO 7 SEGMENT & PIC16F887CD4511 7 SEGMENT PIC16F887

PINS PORTC PORTD

PIN1 B - PORTC.1 PORTD.1

PIN2 C - PORTC.2 PORTD.2

PIN3 LT - PORTB.0 PORTB.0

PIN4 BI - PORTB.1 PORTB.1

PIN5 LE - PORTB.2 PORTB.2

PIN6 D - PORTC.3 PORTD.3

PIN7 A - PORTC.0 PORTD.0

PIN8 VSS - GND

PIN9 e e - -

PIN10 d d - -

PIN11 c c - -

PIN12 b b - -

PIN13 a a - -

PIN14 g g - -

PIN15 f f - -

PIN16 VDD - VDD(+5V)

Page 53

ROBOT . HEAD to TOESK40C + 16F887 GETTING STARTED

ADDITIONAL INFORMATIONCD4511 7-SEGMENT ENCODER

Figure above is the CD4511 7 segment encoder which use to encode the binary input given and convert it into 7 segment number. This Integrated circuit input are required the BCD code and it will display the number from 0 – 9 in 7 segment.

TRUTH TABLE

X = Don't Care

*Depends upon the BCD code applied during the 0 to 1

transition of LE. Above are the truth table for CD4511 encoder to convert the input BCD to output of 7-segment number.

CODE OVERVIEWsystem.h

#define dis_1 0b00000001Declare the BCD number that will send to the CD4511 encoder. E.g: 0b00000001 are number “1” in 7 segment.

Page 54

ROBOT . HEAD to TOESK40C + 16F887 GETTING STARTED

#define LE RB2#define BI RB1#define LT RB0In here, we have initially declare the I/O port that use to control the CD4511 such as lamp test(LT), blanking (BI), latch enable(LE) and store a BCD code.

MAIN PROGRAM

LT = 0;Referring to the truth table, HIGH(1) the LT will stop the lamp test while LOW(0) the LT will on the lamp test.

LE = 0;HIGH(1) to ON the latch enable and may store a BCD code. LOW(0) will OFF latch enable and will not store a BCD code.

BI = 1;HIGH(1) will OFF the blanking and LOW(0) will ON the blanking.

References:http://www.play.com.br/datasheet/CD4511.pdf

Page 55

ROBOT . HEAD to TOESK40C + 16F887 GETTING STARTED

PROJECT 13UART TO COMPUTER

Universal Asynchronous Receive/Transmit (UART) has becoming a popular item on sending and receiving data in the fast way. In here, we are going to experience on how to use UC00A to communicate with our computer/PC and SK40C.

COMPONENT NEEDED

16 x 2 LCD DISPLAY

USB TO UART CONVERTER

HYPERTERMINAL INSTALL

JUMPER WIRES

CONNECTIONTo interface between UC00A and SK40C required only 4 wires connection which is power supply (VDD), ground(GND), transmit(TX) and receive (RX). For serial communication, the transmit and receive for UC00A and SK40C have to be connected in duplex. Please refer figure below and UC00A datasheet.

Page 56

ROBOT . HEAD to TOESK40C + 16F887 GETTING STARTED

ADDITONAL INFORMATION

Wires in PIN1 and PIN2 are switch for the second connecter.

HYPERTERMINAL INSTALLATIONHyperTerminal for WINDOW VISTA & 7 please download from this webpage. For WINDOW XP please refer to UC00A datasheet.

STEPS:1. Open hypertrm.exe. Next, LOCATION

INFORMATION will pop up like figure below. Then, click CANCEL until you see the CONNECTION DESCRIPTION.

2. Enter a project name then click OK.

3. Choose the suitable COM port by referring to the DEVICE MANAGER.

4. Setting up the COM PROPERTIES Like figure below.

Page 57

ROBOT . HEAD to TOESK40C + 16F887 GETTING STARTED

5. Go to FILE > PROPERTIES > SETTING > ASCII SETUP and tick like figure below. After that, the HyperTerminal is ready to go.

CODE OVERVIEW

uart_putstr(“Ready To Receive & Transmit!!”)Send a string of ASCII through UC00A and display on HyperTerminal to tell the computer that SK40C is ready.

Page 58

ROBOT . HEAD to TOESK40C + 16F887 GETTING STARTED

for(i=0 ; i<32 ; i++){if (i == 15) lcd_2ndline();else if (i == 31) lcd_home();}

This loop is to count and make sure that the word are display on LCD. This is to make sure that every word display can seen which is for 1st line LCD address are from 0x00 until 0x0F and for 2nd line LCD address are from 0x40 until 0x4F. If “i” counted 15, it automatically shift the cursor to 0x40 and when “i” counted 31, it back to 0x00.

uc_uart_receive();Receive the data from computer.

data = RCREG;Store the bytes of data receive in “data”.

send_lcd_data(1,data);Send the data received to LCD which sending the 1 to telling the LCD that the data is a character. The data received from the computer are in ASCII, so there was no need any conversion.

Page 59

ROBOT . HEAD to TOESK40C + 16F887 GETTING STARTED

PROJECT 14INTERFACE WITH RELAY

Relay have become a common use electronic component which operate as an switching device by simply apply voltage to ON and OFF it. For this project, we will discover a simple relay connected with an LED to show what is the basic function and connection.

COMPONENT NEEDED

RELAY

LED x2

1K RESISTOR x2

NPN TRANSISTOR2N2222

1N5817 SCHOTTKY DIODE

BREADBAORD

JUMPER WIRES

CONNECTIONNormally relay will have 4 pin which is normally open(NO), normally close(NC), common and 2 control pin to ON/OFF the magnetic coil. By referring to the figure below, RED wires are VDD which connected to LEDs anode. BLACK wires are GND are connected to common and NPN Emitter pin.. ORANGE and WHITE wire connected to both cathode of LED through 1K resistor. The YELLOW wire are connected to RA0 and NPN Base pin. For protection of the microcontroller, we added a schottky diode as an protection diode.

Page 60

ROBOT . HEAD to TOESK40C + 16F887 GETTING STARTED

ADDITIONAL INFORMATIONRelay have almost the same function as a switch but the difference are that relay can be toggle by simple giving an electricity. Please refer this webpage for detail.

CODE OVERVIEW

#define Relay1 RA0In system.h, we have defined the Relay1 I/O PORT as RA0.

If (SW1 == 0) Relay1 = 1;Check if switch 1 is trigger ON. If switch 1 is HIGH(1), then go out of this loop. If switch 1 is LOW(0), trigger ON Relay 1.

else Relays = 0;If switch 1 is HIGH(1), Relay1 =0.

References:http://www.kpsec.freeuk.com/components/relay.htm

Page 61

ROBOT . HEAD to TOESK40C + 16F887 GETTING STARTED

PROJECT 15INTERFACE WITH SKPS

Play Station 2 (PS2) controller is relatively easy to obtain from any game store and it offers good human manual input for control system. More and more developers are looking into applying existing PS2 controller to control particular system. In here, we going to explore on how to interface PS2 controller with SK40C through SKPS controller starter kit.

COMPONENT NEEDED

16 x 2 LCD DISPLAY

SKPS CONTROLLER STARTER KIT

SONY PS2 CONTROLLER

JUMPER WIRES

CONNECTIONConnection between SKPS and SK40C are only required 4 wires which is power in(VDD), ground(GND), transmit(TX), receive(RX). RED wire are VDD which connected from VDD of SK40C to 5V of SKPS. BLACK wire are GND which is connected from GND of SK40C to GND of SKPS. GREEN wire are transmit(TX) from SK40C to receive(RX) of SKPS. YELLOW wire are receive(RX) from SK40C connected to transmit(TX) of SKPS. Please refer SKPS user manual for detail.

Page 62

ROBOT . HEAD to TOESK40C + 16F887 GETTING STARTED

ADDITIONAL INFORMATIONThe major problem of PS2 Controller is to achieve this is the socket for PS2 and the protocol to communicate with it. PS2 socket is very unique and difficult to obtain. Besides, protocol to obtain the status (digital and analog) of each button and analog stick on PS2 controller create headache to developer. Thus, using SKPS starter kit, it offers a compact yet reliable PS2 Controller Converter for user. SKPS’s power and UART pin is compatible with SKKCA and SKXBee. A host is needed to communicate with SKPS through UART. It offers a standard connector for Sony PS2 controller to plug-in.

Features

• Stable 5V powered, low current consumption, less than 150mA.

• 1 standard PS2 controller socket.• Communicate with host microcontroller

through 5V TTL UART.• Simple inquiry command and button status

feedback for host to process.• Vibrator motor is controllable.• Wired or wireless PS2 controller is fully

compatible.• PS2 Controller will only operate in analog

mode.• A small LED as indicator for communication

between SKPS and PS2 controller.

CODE OVERVIEWSKPSunsigned char uc_skps(unsigned char uc_data)Receive uc_data from main program to requrest and check the I/O port of the PS2 controller. After that, return the result back to main program.

uart_transmit(uc_data);Send out the uc_data to SKPS to check or request the status of PS2 controller using serial communication (UART).

return uc_uart_receive();Send back the result received from SKPS to main program.

void skps_vibrate(unsigned char uc_motor, unsigned char uc_value)Send signal to PS2 controller to vibrate the motor inside. uc_motor is to select motor_1 or motor_2. uc_value is to select the motor speed. For motor_1, the speed are already fix while for motor_2, we can control the motor speed.

MAIN PROGRAM

uc_skps(no); Request the data output from PS2 by sending the request signal to SKPS and it will check the requested push button of PS2 whether it is been pressed.

case_num = no;Select the case needed. If SKPS have detected the push button of PS2 is pressed, case_num will select

Page 63

ROBOT . HEAD to TOESK40C + 16F887 GETTING STARTED

the case number same as the data sent then display on LCD for that which button we have pressed. display(); Select display() subroutine.

no = 0;Reset the no back to 0

Check the LEFT joystick if it is press by OR all the LEFT joystick to see if there is an output value. If is pressed, select case 16, then loop forever and store data in data[ ] then display the data[ ] value on LCD and ON motor_2. If not then clear LCD and stop the motor_2 vibrate.

Select the case by referring to the case_num and display the button pressed on LCD screen.

References:http://www.cytron.com.my/usr_attachment/SKPS%20User%20Manual.pdf

Page 64