C Language Programming
#1

[attachment=13520]
C Language Programming for the 8051
C for Microcontrollers
Of higher level languages, C is the closest to assembly languages
bit manipulation instructions
pointers (indirect addressing)
Most microcontrollers have available C compilers
Writing in C simplifies code development for large projects.
Available C Compilers
Kiel – integrated with the IDE we have been using for labs.
Reads51 – available on web site (http://rigelcorpreads51.htm)
Freeware: SDCC - Small Device C Compiler (http://sdcc.sourceforge)
Other freeware versions …
Compilation Process (Keil)
Modular Programming
Like most high level languages, C is a modular programming language (but NOT an object oriented language)
Each task can be encapsulated as a function.
Entire program is encapsulated in “main” function.
Basic C Program Structure
Compiler directives and include files
Declarations of global variables and constants
Declaration of functions
Main function
Sub-functions
Interrupt service routines
Example: blinky.c
Back to C Basics
All C programs consists of:
Variables
Functions (one must be “main”)
Statements
To define the SFRs as variables:
#include <c8051F020.h>
Variables
All variables must be declared at top of program, before the first statement.
Declaration includes type and list of variables.
Example: void main (void) {
int var, tmp;
Types:
int (16-bits in our compiler)
char (8-bits)
short (16-bits)
long (32-bits)
sbit (1-bit)
others that we will discuss later
Variables
The following variable types can be signed or unsigned:
Statements
Assignment statement:
variable = constant or expression or variable
examples: upper = 60;
I = I + 5;
J = I;
Operators
Arithmetic: +, -, *, /
Relational comparisons: >, >=, <, <=
Equality comparisons: ==, !=
Logical operators: && (and), || (or)
Increment and decrement: ++, --
Example:
if (x != y) && (c == b)
Code:
{
    a=c + d*b;
    a++;
}

Example – Adder program (add 2 16-bit numbers)
$INCLUDE (C8051F020.inc)
XL equ 0x78
XH equ 0x79
YL equ 0x7A
YH equ 0x7B
cseg at 0
ljmp Main
cseg at 100h
; Disable watchdog timer
Main:
Code:
    mov 0xFF, #0DEh
             mov 0xFF, #0ADh
        mov a, XL
        add a, YL
        mov XL, a        mov a, XH
        addc a, YH
        mov XH, a
        nop
end
#include <c8051f020.h>    
void main (void) {
int x, y, z;   //16-bit variables
   // disable watchdog timer
   WDTCN = 0xde;
   WDTCN = 0xad;
   z = x + y;
}
adder.SRC
Bitwise Logic Instructions
AND
OR
XOR
left shift
right shift
1’s complement
Example – Logic in Assembly and C
Main:
mov WDTCN, #0DEh
mov WDTCN, #0ADh
xrl a, #0xF0 ; invert bits 7-4
orl a, #0x0C ; set bits 3-2
anl a, #0xFC ; reset bits 1-0
mov P0, a ; send to port0
void main
Code:
(void) {
char x;
WDTCN = 0xDE;
WDTCN = 0xAD;
x = x ^ 0xF0;
x = x | 0x0C;
x = x & 0xFC;
P0 = x;
}
Loop Statements - While
While loop:
while (condition) { statements }
while condition is true, execute statements
if there is only one statement, we can lose the {}
Example: while (1) ; // loop forever
Statements - For
For statement:
for (initialization; condition; increment) {statements}
initialization done before statement is executed
condition is tested, if true, execute statements
do increment step and go back and test condition again
repeat last two steps until condition is not true
Example: for loop
for (n = 0; n<1000; n++)
n++ means n = n + 1
Be careful with signed integers!
for (i=0; i < 33000; i++) LED = ~LED;
Why is this an infinite loop?
Loops: do - while
do
statements
while (expression);
Test made at the bottom of the loop
Decision – if statement
if (condition1)
{statements1}
else if (condition2)
{statements2
else
{statementsn}
Decision – switch statement
switch (expression) {
case const-expr: statements
case const-expr: statements
default: statements
}
Example: switch
switch (unibble) {
case 0x00 : return (0xC0);
case 0x01 : return (0xF9);
case 0x02 : return (0xA4);
case 0x03 : return (0xC0);
default : return (0xFF);
}
Revisit Toggle and Blink5
C Extensions: Additional Keywords
Accessing Specific Memory
C Access to 8051 Memory
C Extensions for 8051 (Cygnal)
New data types:
Example:
bit bit new_flag; //stored in 20-2F
sbit sbit LED = P1^6;
sfr sfr SP = 0x81; //stack pointer
sfr16 sfr16 DP = 0x82; // data pointer
$INCLUDE (c8051F020.h)
C Data Types With Extensions
Declaring Variables in Memory
Example: Accessing External Memory
Program defines two 256 element arrays in external memory
First array is filled with values that increase by 2 each location.
First array is copied to second array.
Similar to block move exercise done in assembly.
xdata_move.c
Interrupts – Original 8051
Other Interrupt Numbers
Revisit Timer Exercise
Blinking!
In-line Assembly
When it is more efficient, or easier, can insert assembly code in C programs.
#pragma asm
put your assembly code here
#pragma endasm
Compilation Process (Keil)
Example – Switch/LED Program
Interfacing with C
Example: Temperature Sensor program
Configures the external oscillator
Configures the ADC0 for temp. sensor
Configures Port1 so LED can be used
Configures Timer3 to synch the ADC0
Uses ADC0 ISR to take temperature samples and averages 256 of them and posts average to global variable
Main program compares average temp. to room temp. and lights LED if temp is warmer.
Temp_2.c
Revisit DAC0 Program
And “C” the difference!
Converting to Real Values
C makes it easier to implement equations
Example: Temperature conversion
For analog to digital conversion – assuming left justified:
The temperature sensor:
Temperature Conversion
C for the Equation
Make it REAL!
Temperature Conversion
Arrays in C
Useful for storing data
type arr_name[dimension]
char temp_array[256]
Array elements are stored in adjacent locations in memory.
Pointers in C
Pointers are variables that hold memory addresses.
Specified using * prefix.
int *pntr; // defines a pointer, pntr
pntr = &var; // assigns address of var to pntr
Pointers and Arrays
Array Example
Compiler Optimization Levels
Optimization level can be set by compiler control directive:
Examples (default is #pragma (8, speed)
#pragma ot (7)
#pragma ot (9, size)
#pragma ot (size) – reduce memory used at the expense of speed.
#pragma ot (speed) – reduce execution time at the expense of memory.
Compiler Optimization Levels
Example: 7-seg Decoder
Effect of Optimization Level on Code Size
Level 0 Optimization
Level 9 Optimization
Memory Models
Small - places all function variables and local data segments in the internal data memory (RAM) of the 8051 system. This allows very efficient access to data objects (direct and register modes). The address space of the SMALL memory model, however, is limited.
Large - all variables and local data segments of functions and procedures reside (as defined) in the external data memory of the 8051 system. Up to 64 KBytes of external data memory may be accessed. This,however, requires the long and therefore inefficient form of data access through the data pointer (DPTR).
Selected by compiler directives
Examples:
#pragma small
#pragma large
Example: LARGE
Example: SMALL
Initialization
When a C program is compiled, some code is created that runs BEFORE the main program.
This code clears RAM to zero and initializes your variables. Here is a segment of this code:
I/O Circuitry - Exercise
Port I/O - Output
Port I/O - Input
Port I/O Example
Keypad Interface
C for Large Projects
Use functions to make programs modular
Break project into separate files if the programs get too large
Use header (#include) files to hold definitions used by several programs
Keep main program short and easy to follow
Consider multi-tasking or multi-threaded implementations
Functions
The basis for modular structured programming in C.
return-type function-name(argument declarations)
{
declarations and statements
}
Example – no return value or arguments
Example – with arguments
void Timer3_Init (int counts) {
// Stop timer, clear TF3, use SYSCLK as timebase
TMR3CN = 0x02;
// Init reload value
TMR3RL = -counts;
// Set to reload immediately
TMR3 = 0xffff;
// Disable interrupts
EIE2 &= ~0x01;
// Start timer
TMR3CN |= 0x04;
}
Example – with return value
char ascii_conv (char num) {
return num + 30;
}
Header Files
Use to define global constants and variables
Multitasking and Multithreading
Multitasking: Perception of multiple tasks being executed simultaneously.
Usually a feature of an operating system and tasks are separate applications.
Embedded systems are usually dedicated to one application.
Multithreading: Perception of multiple tasks within a single application being executed.
Example: Cygnal IDE color codes while echoing characters you type.
Multitasking and Multithreading
Multi-tasking/threading Implementations

Cooperative multi-tasking – each application runs for a short time and then yields control to the next application.
Timer-based multi-tasking – on each timer interrupt, tasks are switched.
When switching between tasks, state of processor (internal registers, flags, etc) must be saved and previous state from last task restored. This is the “overhead” of multitasking. Also called “context switching”.
Multithreading with Interrupts
Real-Time Operating Systems (RTOS)
Usually a timer-based task switching system that can guarantee a certain response time.
Low level functions implement task switching.
High level functions create and terminate threads or tasks.
Each task might have its own software stack for storing processor state.
Reply

Important Note..!

If you are not satisfied with above reply ,..Please

ASK HERE

So that we will collect data for you and will made reply to the request....OR try below "QUICK REPLY" box to add a reply to this page
Popular Searches: lisp programming language seminar report, watermarker freeware, d programming language download, c programming language seminar, d programming language book, progect report on c programming language, variables**ne crime reporting asp net,

[-]
Quick Reply
Message
Type your reply to this message here.

Image Verification
Please enter the text contained within the image into the text box below it. This process is used to prevent automated spam bots.
Image Verification
(case insensitive)

Possibly Related Threads...
Thread Author Replies Views Last Post
  C# classes - CS 638 Web Programming computer girl 0 694 08-06-2012, 01:21 PM
Last Post: computer girl
  Finger Detection for Sign Language Recognition computer girl 0 1,381 08-06-2012, 10:35 AM
Last Post: computer girl
  Language Emulator smart paper boy 1 1,111 23-02-2012, 03:46 PM
Last Post: kotojuvenu
  An Adaptive Programming Model for Fault-Tolerant Distributed Computing electronics seminars 3 2,582 20-02-2012, 01:13 PM
Last Post: seminar paper
  Mac OS X Programming smart paper boy 0 1,042 06-08-2011, 03:18 PM
Last Post: smart paper boy
  Speech Synthesis Markup Language (SSML) smart paper boy 0 830 14-07-2011, 02:48 PM
Last Post: smart paper boy
  Object Oriented Programming: Its Origins and Importance in Computer Science smart paper boy 0 1,207 14-07-2011, 10:29 AM
Last Post: smart paper boy
  Query Language Modeling for Voice Search seminar class 0 847 23-04-2011, 03:11 PM
Last Post: seminar class
  An Implementation of A Spatial Query Language for Multiple Data Sources project topics 0 853 18-01-2011, 12:47 PM
Last Post: project topics
  Calculator Code: Programming Code for Use within a Scientific Calculator seminar surveyer 0 2,355 04-01-2011, 01:08 PM
Last Post: seminar surveyer

Forum Jump: