SlideShare a Scribd company logo
1 of 20
Download to read offline
EE216                                                             9 April 2008

Tutorial on C Compiler


           C Programming for PIC Microcontroller

Introduction:
          This tutorial will introduce you to using the C programming language for
          microcontroller applications. We will be using a freeware C compiler, called
          PICC Lite, supplied by a company called Hi-Tech. However, our code will
          still be written in MPLAB environment.

Part I: Using PICC Lite
   1. PICC Lite is a free version of Hi-Tech’s PICC compiler. It supports several but
      not all Microchip devices including the 16f84, 16F84A, 16F877, 16F877A, and
      the 12f675. There are some limitations, but nothing that will affect our coding.
      (Take a look at www.htsoft.com for more info.)

   2. To use the compiler and write our code in C, we will still be using MPLAB IDE.
      Open the MPLAB Integrated Development Environment
3. We will start a new project using the project wizard, just as in the past.
4) Specify the device you will be using, making sure it is one of the devices
   supported by PICC Lite Compiler.
5. This time, when you must select a tool-suite, choose Hi-Tech PICC Toolsuite
   from the drop down menu. Then set up the directories and project name. If the
   assembler, linker and compiler are not selected, browse to location
   C:PICCLiteBinPICL.exe.
6. Now create a Project and Directory just as you’ve done with the Assembly
   Language version.
7. Click “NEXT” brings up this window, but there is nothing to add.




Now select “Finish” in Summary window and verify project parameters

Go to File and selct NEW; open a window “untitled”.
8. Now create a new blank file and save it in your project directory with a “.c”
extension.
9. Then add this file to your project Source Files. By adding the “.c” extension,
      MPLAB automatically uses C syntax for editing in the IDE.

Right click on source file and select “Add Files” as shown in the following window.
Part 2: Setting up the Microcontroller Some Code
     1. Now, open the blank file you’ve created, cprog.c, and the first line of code to
         add to your blank page is:

     #include <pic.h>




        Navigate to the Hi-Tech directory and look at this include file. It basically sets
        up all the definitions for the particular chip you are using, similar to the
        16F877 inc file we used in assembly.
2. Next, we will add our main program body. Everything in PICC is just like
    ANSI C, so we have:

   void main (void)
   {
   }
3. Now, just like in our assembly programs, we must set up all of the registers
associated with our device - only in C, it is much easier!

To set up the configuration bits, just select the CONFIGURATION Pull-Down
Menu and set the configuration you want.
Also, if you want to change devices, simply go to the CONFIGURATION Pull-
Down Menu and select the device
4. To verify that the device you’ve selected is supported by the compiler, go to
the PROJECTS pull-down menu and select BUILD ALL. It should successfully
build the program as show in the slides below.
Part3: Some Code
Now, to enter some code and run a program, begin by selecting the 12F675
Device.

1. To set up the registers, simply set the name of the register equal to some value.
For example: GPIO = 4. Easy enough? The compiler takes care of all bank
switching, register size considerations, etc. Since our first program will (of
course) be a blinking light, let’s turn off the ADC, turn off the comparators, and
set TRISIO to all outputs. The following code takes care of that, and can be
placed right inside the main braces.

       TRISIO = 0;
       ANSEL = 120;
       CMCON = 7;
       ADCON0 = 140;

2. Now, let’s attach an LED to pin 2 (GPIO 5). If we want to turn this light on, we
    just set GPIO to 0b100000 or 0x20 in hex. In addition, we need some sort of
infinite program loop. An elegant way to do this is with a while(1) statement.
        Add the following to the main program code to make the light blink:

                           while(1)
                           {
                           GPIO = 0x20;
                           GPIO = 0x00;
                           }

     3. Now this will obviously switch the light on and off too quickly to see. Let’s add
         a delay! In C, there are many ways to do this, but we will do a quick and dirty
         one for now. Just add an empty for loop in between each change of state. The
         only problem you would anticipate is that the 8 bit registers we use for
         variables can only count to 255. In assembly, we got around this by nesting
         two loops together. In C, we can simply define our counter as something
         larger that 8 bits, say…. an UNSIGNED INT. This will let us count much
         higher and PICC will take care of the assembly code to do it. Add the
         following line to the main code (before our loop of course):

                    unsigned int index;

        Then, modify the While loop to look like this:

                           while(1)
                           {
                           GPIO = 0x20;
                           for(index = 0;index<10000;index++);
                           GPIO = 0x00;
                           for(index = 0;index<10000;index++);
                           }

        4. Before we can compile and test this code, we must set the configuration of
        the device. In assembly, we did this with some code at the beginning of the
        program. In C, we are going to do it using MPLAB. From the configure menu,
        select configuration bits. Set these up as you deem appropriate based on our
        last couple labs. Explain your choices. Now build your project and test it out.

Part4: Exploiting C
        1. C makes programming the PIC incredibly easy, at the cost of some code
        efficiency. Let’s exploit some of the high-level functions and make our code
        more interested. First, we should make a delay routine that will delay by an
        amount specified. Add the following code before the main routine.

                    void delay(unsigned int amount)
                    {
unsigned int index;
                      for(index=0;index<amount;index++);
                      }

               This routine will count up to whatever number we pass to it. The variable
       index is local as is the variable amount declared in the function.
               Remove the variable index declared in main, and replace the for loops
       with calls to our delay function. Try two different values:

                              While(1)
                              {
                              GPIO = 0x20;
                              delay(10000);
                              GPIO = 0x00;
                              delay(30000);
                              }

       2. Now lets add the following subroutine to read a value from the ADC:

                      unsigned int adc_read(void)
                            {
                            unsigned int result;
                            GODONE = 1;
                            while(GODONE); // wait for conversion complete
                            result=(ADRESH << 8) + ADRESL;
                            return result;
                            }

This routine sets the GODONE bit high to start a conversion, and then waits for the PIC
to set it low indicating completion. Then we take ADRESH (the upper 8 bits of the result)
and put it into “result” while shifting it by 8. At the same time, we add the lower 8 bits
(ADRESL) to get out full 16 bit conversion. Then, result is returned to the caller.

To use this subroutine, be sure to change TRISIO to 0b010000 so that we have an input
pin on pin 3. Also, change ADCON0 to 141 so that the ADC is turned on.

       3. Let’s modify the main program to call adc_read and then delay accordingly. In
           C, this is quite simple. Since the function returns an unsigned int, we can just
           move it into the call to delay. (Add a multiplication by 4 to get a little more
           delay.)
                               While(1)
                               {
                               GPIO = 0x20;
                               delay(adc_read() * 4);
                               GPIO = 0x00;
                               delay(adc_read() * 4);
                               }
4. Attach a voltage divider POT, or a variable voltage source to pin 3. As the
           voltage input changes, the light will flash at different rates.

So now we have implemented the same function as in Lab #3 using C. How does using a
high-level language compare from the programming perspective? How about in
terms of efficiency (code size, reliability, etc.)? Compare the code in this lab to the
code from lab #3.

More Related Content

Viewers also liked

Projek rekabentuk
Projek rekabentukProjek rekabentuk
Projek rekabentukmkazree
 
Projek rekabentuk1
Projek rekabentuk1Projek rekabentuk1
Projek rekabentuk1mkazree
 
rekabentruk berbantu komputer Lab 4
rekabentruk berbantu komputer Lab 4rekabentruk berbantu komputer Lab 4
rekabentruk berbantu komputer Lab 4mkazree
 
Introduction to pic
Introduction to picIntroduction to pic
Introduction to picPRADEEP
 
19199406 embedded-c-tutorial-8051
19199406 embedded-c-tutorial-805119199406 embedded-c-tutorial-8051
19199406 embedded-c-tutorial-8051PRADEEP
 
Chapter 4 synchronous machine
Chapter 4 synchronous machineChapter 4 synchronous machine
Chapter 4 synchronous machinemkazree
 
Tutorial chapter 3 robotic
Tutorial chapter 3 roboticTutorial chapter 3 robotic
Tutorial chapter 3 roboticmkazree
 
Tutorial 2 amplitude modulation
Tutorial 2 amplitude  modulationTutorial 2 amplitude  modulation
Tutorial 2 amplitude modulationmkazree
 
120102011
120102011120102011
120102011mkazree
 
ADC Interfacing with pic Microcontrollert
ADC Interfacing with pic MicrocontrollertADC Interfacing with pic Microcontrollert
ADC Interfacing with pic Microcontrollertleapshare007
 
Tutorial chapter 2 robotic
Tutorial chapter 2 roboticTutorial chapter 2 robotic
Tutorial chapter 2 roboticmkazree
 
8-bit PIC Microcontrollers
8-bit PIC Microcontrollers8-bit PIC Microcontrollers
8-bit PIC MicrocontrollersPremier Farnell
 
Unit 3 tables and data structures
Unit 3 tables and data structuresUnit 3 tables and data structures
Unit 3 tables and data structuresPRADEEP
 
The Electronic Hobby Kit
The Electronic Hobby KitThe Electronic Hobby Kit
The Electronic Hobby Kitmkazree
 
Foster-seely and Ratio Detector (Discriminator )
Foster-seely and Ratio Detector (Discriminator )Foster-seely and Ratio Detector (Discriminator )
Foster-seely and Ratio Detector (Discriminator )mkazree
 
Interfacing keypad
Interfacing keypadInterfacing keypad
Interfacing keypadPRADEEP
 
CMOS Topic 7 -_design_methodology
CMOS Topic 7 -_design_methodologyCMOS Topic 7 -_design_methodology
CMOS Topic 7 -_design_methodologyIkhwan_Fakrudin
 

Viewers also liked (19)

Projek rekabentuk
Projek rekabentukProjek rekabentuk
Projek rekabentuk
 
Projek rekabentuk1
Projek rekabentuk1Projek rekabentuk1
Projek rekabentuk1
 
rekabentruk berbantu komputer Lab 4
rekabentruk berbantu komputer Lab 4rekabentruk berbantu komputer Lab 4
rekabentruk berbantu komputer Lab 4
 
Introduction to pic
Introduction to picIntroduction to pic
Introduction to pic
 
19199406 embedded-c-tutorial-8051
19199406 embedded-c-tutorial-805119199406 embedded-c-tutorial-8051
19199406 embedded-c-tutorial-8051
 
Mp lab
Mp labMp lab
Mp lab
 
16f877
16f87716f877
16f877
 
Chapter 4 synchronous machine
Chapter 4 synchronous machineChapter 4 synchronous machine
Chapter 4 synchronous machine
 
Tutorial chapter 3 robotic
Tutorial chapter 3 roboticTutorial chapter 3 robotic
Tutorial chapter 3 robotic
 
Tutorial 2 amplitude modulation
Tutorial 2 amplitude  modulationTutorial 2 amplitude  modulation
Tutorial 2 amplitude modulation
 
120102011
120102011120102011
120102011
 
ADC Interfacing with pic Microcontrollert
ADC Interfacing with pic MicrocontrollertADC Interfacing with pic Microcontrollert
ADC Interfacing with pic Microcontrollert
 
Tutorial chapter 2 robotic
Tutorial chapter 2 roboticTutorial chapter 2 robotic
Tutorial chapter 2 robotic
 
8-bit PIC Microcontrollers
8-bit PIC Microcontrollers8-bit PIC Microcontrollers
8-bit PIC Microcontrollers
 
Unit 3 tables and data structures
Unit 3 tables and data structuresUnit 3 tables and data structures
Unit 3 tables and data structures
 
The Electronic Hobby Kit
The Electronic Hobby KitThe Electronic Hobby Kit
The Electronic Hobby Kit
 
Foster-seely and Ratio Detector (Discriminator )
Foster-seely and Ratio Detector (Discriminator )Foster-seely and Ratio Detector (Discriminator )
Foster-seely and Ratio Detector (Discriminator )
 
Interfacing keypad
Interfacing keypadInterfacing keypad
Interfacing keypad
 
CMOS Topic 7 -_design_methodology
CMOS Topic 7 -_design_methodologyCMOS Topic 7 -_design_methodology
CMOS Topic 7 -_design_methodology
 

More from PRADEEP

Unit 2 software partitioning
Unit 2 software partitioningUnit 2 software partitioning
Unit 2 software partitioningPRADEEP
 
Unit 1 introduction
Unit 1 introductionUnit 1 introduction
Unit 1 introductionPRADEEP
 
Unit 5 multi-board system
Unit 5 multi-board systemUnit 5 multi-board system
Unit 5 multi-board systemPRADEEP
 
13986149 c-pgming-for-embedded-systems
13986149 c-pgming-for-embedded-systems13986149 c-pgming-for-embedded-systems
13986149 c-pgming-for-embedded-systemsPRADEEP
 
22323006 embedded-c-tutorial-8051
22323006 embedded-c-tutorial-805122323006 embedded-c-tutorial-8051
22323006 embedded-c-tutorial-8051PRADEEP
 
14157565 embedded-programming
14157565 embedded-programming14157565 embedded-programming
14157565 embedded-programmingPRADEEP
 
Rtos 3 & 4
Rtos 3 & 4Rtos 3 & 4
Rtos 3 & 4PRADEEP
 
Interrupts
InterruptsInterrupts
InterruptsPRADEEP
 
Chapter 3
Chapter 3Chapter 3
Chapter 3PRADEEP
 
Leadership lessons-from-obama-
Leadership lessons-from-obama-Leadership lessons-from-obama-
Leadership lessons-from-obama-PRADEEP
 
Programming timers
Programming timersProgramming timers
Programming timersPRADEEP
 
Interfacing stepper motor
Interfacing stepper motorInterfacing stepper motor
Interfacing stepper motorPRADEEP
 
Interfacing rs232
Interfacing rs232Interfacing rs232
Interfacing rs232PRADEEP
 
Interfacing adc
Interfacing adcInterfacing adc
Interfacing adcPRADEEP
 
EMBEDDED SYSTEMS 6
EMBEDDED SYSTEMS 6EMBEDDED SYSTEMS 6
EMBEDDED SYSTEMS 6PRADEEP
 
EMBEDDED SYSTEMS 5
EMBEDDED SYSTEMS 5EMBEDDED SYSTEMS 5
EMBEDDED SYSTEMS 5PRADEEP
 
EMBEDDED SYSTEMS 2&3
EMBEDDED SYSTEMS 2&3EMBEDDED SYSTEMS 2&3
EMBEDDED SYSTEMS 2&3PRADEEP
 
EMBEDDED SYSTEMS 4&5
EMBEDDED SYSTEMS 4&5EMBEDDED SYSTEMS 4&5
EMBEDDED SYSTEMS 4&5PRADEEP
 
EMBEDDED SYSTEMS 1
EMBEDDED SYSTEMS 1EMBEDDED SYSTEMS 1
EMBEDDED SYSTEMS 1PRADEEP
 

More from PRADEEP (20)

Unit 2 software partitioning
Unit 2 software partitioningUnit 2 software partitioning
Unit 2 software partitioning
 
Unit 1 introduction
Unit 1 introductionUnit 1 introduction
Unit 1 introduction
 
Unit 5 multi-board system
Unit 5 multi-board systemUnit 5 multi-board system
Unit 5 multi-board system
 
13986149 c-pgming-for-embedded-systems
13986149 c-pgming-for-embedded-systems13986149 c-pgming-for-embedded-systems
13986149 c-pgming-for-embedded-systems
 
22323006 embedded-c-tutorial-8051
22323006 embedded-c-tutorial-805122323006 embedded-c-tutorial-8051
22323006 embedded-c-tutorial-8051
 
14157565 embedded-programming
14157565 embedded-programming14157565 embedded-programming
14157565 embedded-programming
 
Rtos 3 & 4
Rtos 3 & 4Rtos 3 & 4
Rtos 3 & 4
 
Interrupts
InterruptsInterrupts
Interrupts
 
Chapter 3
Chapter 3Chapter 3
Chapter 3
 
Leadership lessons-from-obama-
Leadership lessons-from-obama-Leadership lessons-from-obama-
Leadership lessons-from-obama-
 
Programming timers
Programming timersProgramming timers
Programming timers
 
Interfacing stepper motor
Interfacing stepper motorInterfacing stepper motor
Interfacing stepper motor
 
Interfacing rs232
Interfacing rs232Interfacing rs232
Interfacing rs232
 
Interfacing adc
Interfacing adcInterfacing adc
Interfacing adc
 
EMBEDDED SYSTEMS 6
EMBEDDED SYSTEMS 6EMBEDDED SYSTEMS 6
EMBEDDED SYSTEMS 6
 
EMBEDDED SYSTEMS 5
EMBEDDED SYSTEMS 5EMBEDDED SYSTEMS 5
EMBEDDED SYSTEMS 5
 
EMBEDDED SYSTEMS 2&3
EMBEDDED SYSTEMS 2&3EMBEDDED SYSTEMS 2&3
EMBEDDED SYSTEMS 2&3
 
EMBEDDED SYSTEMS 4&5
EMBEDDED SYSTEMS 4&5EMBEDDED SYSTEMS 4&5
EMBEDDED SYSTEMS 4&5
 
Timers
TimersTimers
Timers
 
EMBEDDED SYSTEMS 1
EMBEDDED SYSTEMS 1EMBEDDED SYSTEMS 1
EMBEDDED SYSTEMS 1
 

Recently uploaded

Connect Wave/ connectwave Pitch Deck Presentation
Connect Wave/ connectwave Pitch Deck PresentationConnect Wave/ connectwave Pitch Deck Presentation
Connect Wave/ connectwave Pitch Deck PresentationSlibray Presentation
 
"Debugging python applications inside k8s environment", Andrii Soldatenko
"Debugging python applications inside k8s environment", Andrii Soldatenko"Debugging python applications inside k8s environment", Andrii Soldatenko
"Debugging python applications inside k8s environment", Andrii SoldatenkoFwdays
 
SIP trunking in Janus @ Kamailio World 2024
SIP trunking in Janus @ Kamailio World 2024SIP trunking in Janus @ Kamailio World 2024
SIP trunking in Janus @ Kamailio World 2024Lorenzo Miniero
 
Install Stable Diffusion in windows machine
Install Stable Diffusion in windows machineInstall Stable Diffusion in windows machine
Install Stable Diffusion in windows machinePadma Pradeep
 
"LLMs for Python Engineers: Advanced Data Analysis and Semantic Kernel",Oleks...
"LLMs for Python Engineers: Advanced Data Analysis and Semantic Kernel",Oleks..."LLMs for Python Engineers: Advanced Data Analysis and Semantic Kernel",Oleks...
"LLMs for Python Engineers: Advanced Data Analysis and Semantic Kernel",Oleks...Fwdays
 
DevoxxFR 2024 Reproducible Builds with Apache Maven
DevoxxFR 2024 Reproducible Builds with Apache MavenDevoxxFR 2024 Reproducible Builds with Apache Maven
DevoxxFR 2024 Reproducible Builds with Apache MavenHervé Boutemy
 
WordPress Websites for Engineers: Elevate Your Brand
WordPress Websites for Engineers: Elevate Your BrandWordPress Websites for Engineers: Elevate Your Brand
WordPress Websites for Engineers: Elevate Your Brandgvaughan
 
Anypoint Exchange: It’s Not Just a Repo!
Anypoint Exchange: It’s Not Just a Repo!Anypoint Exchange: It’s Not Just a Repo!
Anypoint Exchange: It’s Not Just a Repo!Manik S Magar
 
Bun (KitWorks Team Study 노별마루 발표 2024.4.22)
Bun (KitWorks Team Study 노별마루 발표 2024.4.22)Bun (KitWorks Team Study 노별마루 발표 2024.4.22)
Bun (KitWorks Team Study 노별마루 발표 2024.4.22)Wonjun Hwang
 
Ensuring Technical Readiness For Copilot in Microsoft 365
Ensuring Technical Readiness For Copilot in Microsoft 365Ensuring Technical Readiness For Copilot in Microsoft 365
Ensuring Technical Readiness For Copilot in Microsoft 3652toLead Limited
 
Unraveling Multimodality with Large Language Models.pdf
Unraveling Multimodality with Large Language Models.pdfUnraveling Multimodality with Large Language Models.pdf
Unraveling Multimodality with Large Language Models.pdfAlex Barbosa Coqueiro
 
CloudStudio User manual (basic edition):
CloudStudio User manual (basic edition):CloudStudio User manual (basic edition):
CloudStudio User manual (basic edition):comworks
 
Nell’iperspazio con Rocket: il Framework Web di Rust!
Nell’iperspazio con Rocket: il Framework Web di Rust!Nell’iperspazio con Rocket: il Framework Web di Rust!
Nell’iperspazio con Rocket: il Framework Web di Rust!Commit University
 
"Federated learning: out of reach no matter how close",Oleksandr Lapshyn
"Federated learning: out of reach no matter how close",Oleksandr Lapshyn"Federated learning: out of reach no matter how close",Oleksandr Lapshyn
"Federated learning: out of reach no matter how close",Oleksandr LapshynFwdays
 
Beyond Boundaries: Leveraging No-Code Solutions for Industry Innovation
Beyond Boundaries: Leveraging No-Code Solutions for Industry InnovationBeyond Boundaries: Leveraging No-Code Solutions for Industry Innovation
Beyond Boundaries: Leveraging No-Code Solutions for Industry InnovationSafe Software
 
Vertex AI Gemini Prompt Engineering Tips
Vertex AI Gemini Prompt Engineering TipsVertex AI Gemini Prompt Engineering Tips
Vertex AI Gemini Prompt Engineering TipsMiki Katsuragi
 
The Future of Software Development - Devin AI Innovative Approach.pdf
The Future of Software Development - Devin AI Innovative Approach.pdfThe Future of Software Development - Devin AI Innovative Approach.pdf
The Future of Software Development - Devin AI Innovative Approach.pdfSeasiaInfotech2
 
My Hashitalk Indonesia April 2024 Presentation
My Hashitalk Indonesia April 2024 PresentationMy Hashitalk Indonesia April 2024 Presentation
My Hashitalk Indonesia April 2024 PresentationRidwan Fadjar
 
Tampa BSides - Chef's Tour of Microsoft Security Adoption Framework (SAF)
Tampa BSides - Chef's Tour of Microsoft Security Adoption Framework (SAF)Tampa BSides - Chef's Tour of Microsoft Security Adoption Framework (SAF)
Tampa BSides - Chef's Tour of Microsoft Security Adoption Framework (SAF)Mark Simos
 

Recently uploaded (20)

Connect Wave/ connectwave Pitch Deck Presentation
Connect Wave/ connectwave Pitch Deck PresentationConnect Wave/ connectwave Pitch Deck Presentation
Connect Wave/ connectwave Pitch Deck Presentation
 
"Debugging python applications inside k8s environment", Andrii Soldatenko
"Debugging python applications inside k8s environment", Andrii Soldatenko"Debugging python applications inside k8s environment", Andrii Soldatenko
"Debugging python applications inside k8s environment", Andrii Soldatenko
 
SIP trunking in Janus @ Kamailio World 2024
SIP trunking in Janus @ Kamailio World 2024SIP trunking in Janus @ Kamailio World 2024
SIP trunking in Janus @ Kamailio World 2024
 
Install Stable Diffusion in windows machine
Install Stable Diffusion in windows machineInstall Stable Diffusion in windows machine
Install Stable Diffusion in windows machine
 
"LLMs for Python Engineers: Advanced Data Analysis and Semantic Kernel",Oleks...
"LLMs for Python Engineers: Advanced Data Analysis and Semantic Kernel",Oleks..."LLMs for Python Engineers: Advanced Data Analysis and Semantic Kernel",Oleks...
"LLMs for Python Engineers: Advanced Data Analysis and Semantic Kernel",Oleks...
 
DevoxxFR 2024 Reproducible Builds with Apache Maven
DevoxxFR 2024 Reproducible Builds with Apache MavenDevoxxFR 2024 Reproducible Builds with Apache Maven
DevoxxFR 2024 Reproducible Builds with Apache Maven
 
WordPress Websites for Engineers: Elevate Your Brand
WordPress Websites for Engineers: Elevate Your BrandWordPress Websites for Engineers: Elevate Your Brand
WordPress Websites for Engineers: Elevate Your Brand
 
Anypoint Exchange: It’s Not Just a Repo!
Anypoint Exchange: It’s Not Just a Repo!Anypoint Exchange: It’s Not Just a Repo!
Anypoint Exchange: It’s Not Just a Repo!
 
Bun (KitWorks Team Study 노별마루 발표 2024.4.22)
Bun (KitWorks Team Study 노별마루 발표 2024.4.22)Bun (KitWorks Team Study 노별마루 발표 2024.4.22)
Bun (KitWorks Team Study 노별마루 발표 2024.4.22)
 
Ensuring Technical Readiness For Copilot in Microsoft 365
Ensuring Technical Readiness For Copilot in Microsoft 365Ensuring Technical Readiness For Copilot in Microsoft 365
Ensuring Technical Readiness For Copilot in Microsoft 365
 
E-Vehicle_Hacking_by_Parul Sharma_null_owasp.pptx
E-Vehicle_Hacking_by_Parul Sharma_null_owasp.pptxE-Vehicle_Hacking_by_Parul Sharma_null_owasp.pptx
E-Vehicle_Hacking_by_Parul Sharma_null_owasp.pptx
 
Unraveling Multimodality with Large Language Models.pdf
Unraveling Multimodality with Large Language Models.pdfUnraveling Multimodality with Large Language Models.pdf
Unraveling Multimodality with Large Language Models.pdf
 
CloudStudio User manual (basic edition):
CloudStudio User manual (basic edition):CloudStudio User manual (basic edition):
CloudStudio User manual (basic edition):
 
Nell’iperspazio con Rocket: il Framework Web di Rust!
Nell’iperspazio con Rocket: il Framework Web di Rust!Nell’iperspazio con Rocket: il Framework Web di Rust!
Nell’iperspazio con Rocket: il Framework Web di Rust!
 
"Federated learning: out of reach no matter how close",Oleksandr Lapshyn
"Federated learning: out of reach no matter how close",Oleksandr Lapshyn"Federated learning: out of reach no matter how close",Oleksandr Lapshyn
"Federated learning: out of reach no matter how close",Oleksandr Lapshyn
 
Beyond Boundaries: Leveraging No-Code Solutions for Industry Innovation
Beyond Boundaries: Leveraging No-Code Solutions for Industry InnovationBeyond Boundaries: Leveraging No-Code Solutions for Industry Innovation
Beyond Boundaries: Leveraging No-Code Solutions for Industry Innovation
 
Vertex AI Gemini Prompt Engineering Tips
Vertex AI Gemini Prompt Engineering TipsVertex AI Gemini Prompt Engineering Tips
Vertex AI Gemini Prompt Engineering Tips
 
The Future of Software Development - Devin AI Innovative Approach.pdf
The Future of Software Development - Devin AI Innovative Approach.pdfThe Future of Software Development - Devin AI Innovative Approach.pdf
The Future of Software Development - Devin AI Innovative Approach.pdf
 
My Hashitalk Indonesia April 2024 Presentation
My Hashitalk Indonesia April 2024 PresentationMy Hashitalk Indonesia April 2024 Presentation
My Hashitalk Indonesia April 2024 Presentation
 
Tampa BSides - Chef's Tour of Microsoft Security Adoption Framework (SAF)
Tampa BSides - Chef's Tour of Microsoft Security Adoption Framework (SAF)Tampa BSides - Chef's Tour of Microsoft Security Adoption Framework (SAF)
Tampa BSides - Chef's Tour of Microsoft Security Adoption Framework (SAF)
 

18666800 c-programming-for-pic-microcontroller

  • 1. EE216 9 April 2008 Tutorial on C Compiler C Programming for PIC Microcontroller Introduction: This tutorial will introduce you to using the C programming language for microcontroller applications. We will be using a freeware C compiler, called PICC Lite, supplied by a company called Hi-Tech. However, our code will still be written in MPLAB environment. Part I: Using PICC Lite 1. PICC Lite is a free version of Hi-Tech’s PICC compiler. It supports several but not all Microchip devices including the 16f84, 16F84A, 16F877, 16F877A, and the 12f675. There are some limitations, but nothing that will affect our coding. (Take a look at www.htsoft.com for more info.) 2. To use the compiler and write our code in C, we will still be using MPLAB IDE. Open the MPLAB Integrated Development Environment
  • 2. 3. We will start a new project using the project wizard, just as in the past.
  • 3. 4) Specify the device you will be using, making sure it is one of the devices supported by PICC Lite Compiler.
  • 4. 5. This time, when you must select a tool-suite, choose Hi-Tech PICC Toolsuite from the drop down menu. Then set up the directories and project name. If the assembler, linker and compiler are not selected, browse to location C:PICCLiteBinPICL.exe.
  • 5. 6. Now create a Project and Directory just as you’ve done with the Assembly Language version.
  • 6. 7. Click “NEXT” brings up this window, but there is nothing to add. Now select “Finish” in Summary window and verify project parameters Go to File and selct NEW; open a window “untitled”.
  • 7. 8. Now create a new blank file and save it in your project directory with a “.c” extension.
  • 8. 9. Then add this file to your project Source Files. By adding the “.c” extension, MPLAB automatically uses C syntax for editing in the IDE. Right click on source file and select “Add Files” as shown in the following window.
  • 9.
  • 10.
  • 11. Part 2: Setting up the Microcontroller Some Code 1. Now, open the blank file you’ve created, cprog.c, and the first line of code to add to your blank page is: #include <pic.h> Navigate to the Hi-Tech directory and look at this include file. It basically sets up all the definitions for the particular chip you are using, similar to the 16F877 inc file we used in assembly.
  • 12. 2. Next, we will add our main program body. Everything in PICC is just like ANSI C, so we have: void main (void) { }
  • 13. 3. Now, just like in our assembly programs, we must set up all of the registers associated with our device - only in C, it is much easier! To set up the configuration bits, just select the CONFIGURATION Pull-Down Menu and set the configuration you want.
  • 14. Also, if you want to change devices, simply go to the CONFIGURATION Pull- Down Menu and select the device
  • 15.
  • 16. 4. To verify that the device you’ve selected is supported by the compiler, go to the PROJECTS pull-down menu and select BUILD ALL. It should successfully build the program as show in the slides below.
  • 17. Part3: Some Code Now, to enter some code and run a program, begin by selecting the 12F675 Device. 1. To set up the registers, simply set the name of the register equal to some value. For example: GPIO = 4. Easy enough? The compiler takes care of all bank switching, register size considerations, etc. Since our first program will (of course) be a blinking light, let’s turn off the ADC, turn off the comparators, and set TRISIO to all outputs. The following code takes care of that, and can be placed right inside the main braces. TRISIO = 0; ANSEL = 120; CMCON = 7; ADCON0 = 140; 2. Now, let’s attach an LED to pin 2 (GPIO 5). If we want to turn this light on, we just set GPIO to 0b100000 or 0x20 in hex. In addition, we need some sort of
  • 18. infinite program loop. An elegant way to do this is with a while(1) statement. Add the following to the main program code to make the light blink: while(1) { GPIO = 0x20; GPIO = 0x00; } 3. Now this will obviously switch the light on and off too quickly to see. Let’s add a delay! In C, there are many ways to do this, but we will do a quick and dirty one for now. Just add an empty for loop in between each change of state. The only problem you would anticipate is that the 8 bit registers we use for variables can only count to 255. In assembly, we got around this by nesting two loops together. In C, we can simply define our counter as something larger that 8 bits, say…. an UNSIGNED INT. This will let us count much higher and PICC will take care of the assembly code to do it. Add the following line to the main code (before our loop of course): unsigned int index; Then, modify the While loop to look like this: while(1) { GPIO = 0x20; for(index = 0;index<10000;index++); GPIO = 0x00; for(index = 0;index<10000;index++); } 4. Before we can compile and test this code, we must set the configuration of the device. In assembly, we did this with some code at the beginning of the program. In C, we are going to do it using MPLAB. From the configure menu, select configuration bits. Set these up as you deem appropriate based on our last couple labs. Explain your choices. Now build your project and test it out. Part4: Exploiting C 1. C makes programming the PIC incredibly easy, at the cost of some code efficiency. Let’s exploit some of the high-level functions and make our code more interested. First, we should make a delay routine that will delay by an amount specified. Add the following code before the main routine. void delay(unsigned int amount) {
  • 19. unsigned int index; for(index=0;index<amount;index++); } This routine will count up to whatever number we pass to it. The variable index is local as is the variable amount declared in the function. Remove the variable index declared in main, and replace the for loops with calls to our delay function. Try two different values: While(1) { GPIO = 0x20; delay(10000); GPIO = 0x00; delay(30000); } 2. Now lets add the following subroutine to read a value from the ADC: unsigned int adc_read(void) { unsigned int result; GODONE = 1; while(GODONE); // wait for conversion complete result=(ADRESH << 8) + ADRESL; return result; } This routine sets the GODONE bit high to start a conversion, and then waits for the PIC to set it low indicating completion. Then we take ADRESH (the upper 8 bits of the result) and put it into “result” while shifting it by 8. At the same time, we add the lower 8 bits (ADRESL) to get out full 16 bit conversion. Then, result is returned to the caller. To use this subroutine, be sure to change TRISIO to 0b010000 so that we have an input pin on pin 3. Also, change ADCON0 to 141 so that the ADC is turned on. 3. Let’s modify the main program to call adc_read and then delay accordingly. In C, this is quite simple. Since the function returns an unsigned int, we can just move it into the call to delay. (Add a multiplication by 4 to get a little more delay.) While(1) { GPIO = 0x20; delay(adc_read() * 4); GPIO = 0x00; delay(adc_read() * 4); }
  • 20. 4. Attach a voltage divider POT, or a variable voltage source to pin 3. As the voltage input changes, the light will flash at different rates. So now we have implemented the same function as in Lab #3 using C. How does using a high-level language compare from the programming perspective? How about in terms of efficiency (code size, reliability, etc.)? Compare the code in this lab to the code from lab #3.