chapter 11 - the c language

Post on 02-Jan-2016

23 Views

Category:

Documents

1 Downloads

Preview:

Click to see full reader

DESCRIPTION

Chapter 11 - The C Language. Dennis Ritchie (1940-2011). Dennis Ritchie, the software developer who brought the world the C programming language and Unix operating system, has died at the age of 70.  - PowerPoint PPT Presentation

TRANSCRIPT

Chapter 11 - The C Language

BYU CS/ECEn 124 Chapter 9 - Interrupts 2

Dennis Ritchie (1940-2011)

Dennis Ritchie, the software developer who brought the world the C programming language and Unix operating system, has died at the age of 70. 

Ritchie (known by the username "dmr") was part of a dynamic software development duo with Ken Thompson at Bell Labs,, which they joined in 1967 and 1966, respectively. Ritchie created the C programming language, which replaced the B programming language Thompson invented. 

Two years later in 1969, they created Unix, initially designed for minicomputers. Unix was initially written in 1969 in assembly language and later in C. Unix went on to become key software for critical computing infrastructure around the world. 

“UNIX is very simple, it just needs a genius to understand its simplicity.”

--Dennis Ritchie

BYU CS/ECEn 124 The C Language 3

Topics to Cover…

High Level Languages Compilers vs. Interpreters The C Language 1st C Program C Style C Preprocessor printf Function RBX430-1 Header Files 2nd C Program

BYU CS/ECEn 124 The C Language 4

Levels of Abstraction

Problems

Algorithms

Language

Machine (ISA) Architecture

Microarchitecture

Circuits

Devices Transistors

Logic gates, multiplexers, memory, etc.

MSP430 Architecture

Machine code

Assembly code

High Level Languages

BYU CS/ECEn 124 The C Language 5

High Level Languages

The closer a language is to your original specification, the easier the program is to write.

Many, many programming languages LISP - LISt Processing PROLOG - logic programming MATLAB - matrix and vector manipulations BASIC – interpreter for small computers APL – matrix and vectors FORTRAN – formula translation COBOL – business and accounting PASCAL – procedural Ada – DOD large systems Java – Internet C, C++ ….

High Level Languages

BYU CS/ECEn 124 The C Language 6

High Level Languages

Allow us to use symbolic names for values Programmer simply assigns each value a name Allow us to ignore many memory details, the compiler takes

care of … register usage variable allocation loads and stores from memory callee/caller protocol stack management for subroutine calls

Provide abstraction of underlying hardware Hide low level details (ISA) from programmer Uniform interface (not tied to ISA) to program Portable software (works on different ISAs) The compiler generates the machine code

High Level Languages

numberOfDays = 30;myCurrentPayPerHour = 10.75;switch_A = ON;

numberOfDays = 30;myCurrentPayPerHour = 10.75;switch_A = ON;

BYU CS/ECEn 124 The C Language 7

High Level Languages

Provide expressiveness Human-friendly orientation Express complex tasks with smaller amount of code English-like and human constructs

if-then-else… while… for...

Enhance code readability Can read like a novel… Readability.. is very important

life cycle costs are more importantthan initial programming costs

Easier to debug Easier to maintain

High Level Languages

if(isCloudy) get(umbrella);else get(sunglasses);

if(isCloudy) get(umbrella);else get(sunglasses);

main(){ readInput(); checkForErrors(); doCalculation(); writeOutput();}

main(){ readInput(); checkForErrors(); doCalculation(); writeOutput();}

BYU CS/ECEn 124 The C Language 8

High Level Languages

Provide safeguards against bugs Rules can lead to well-formed programs

structured programming (no GOTO statements) Compilers can generate checks

array bounds checking data type checking

Many languages provide explicit support for assertions something that should be true - if it isn’t, then error

High Level Languages

assert(accountBalance >= 0);assert(accountBalance >= 0);

High-level languages make complex programming simpler, while low-level languages tend to produce more efficient code

However, well-designed compilers frequently produce code comparable in efficiency to what most low-level programmers can produce by hand with better overall results

BYU CS/ECEn 124 The C Language 9

Execution Models

Interpreted Interpreted languages are read and then executed directly, with

no compilation stage. A program called an interpreter reads the program line by line

and executes the lines as they are read. Compiled

Compiled languages are transformed into an executable form before running. There are two types of compilation:

Machine code generation Intermediate representations

Translated A language may be translated into a low-level programming

language for which native code compilers are already widely available. The C programming language is a common target for such translators.

Execution Models

BYU CS/ECEn 124 The C Language 10

Compilers vs Interpreters

temp=v[i];v[i]=v[i+1];v[i+1]=temp;

High-levellanguagestatements

Co

mp

iler

MOV.B 0x0001(SP),R14MOV.W SP,R15INCD.W R15ADD.W R15,R14MOV.B @R14,0x0000(SP)MOV.B 0x0001(SP),R14INC.W R14

Assembly

Ass

emb

ler

415E 0001410F532F5F0E4EE1 0000415E 0001531E

Objectcode

Ap

plic

ati

on

= Executable = Data Path

temp=v[i];v[i]=v[i+1];v[i+1]=temp;

Sourcecode

Inte

rpre

ter

Compilers vs Interpreters

BYU CS/ECEn 124 The C Language 11

Compilation

Compilers convert high-level code to machine code compile once, execute many times resulting machine code is optimized may include intermediate step (assembly) slower translation, but higher performance when executed

If the compiled program can run on a computer whose CPU is different from the one on which the compiler runs, the compiler is known as a cross-compiler.

A program that translates from a low level language to a higher level one is a de-compiler.

Is an assembler considered a compiler? assemblers do convert higher level code to machine code,

but… they are usually in a class by themselves

Compilers

BYU CS/ECEn 124 The C Language 12

The C Programming Language

Developed between 1969 and 1973 by Dennis Ritchie at Bell Labs.

C first developed for use in writing compilers and operating systems (UNIX).

A low-level high-level language Many variants of C 1989, the American National Standards Institute standardized C

(ANSI C, most commonly used C) “The C Programming Language” by Kernighan and Ritchie is the

C “Bible” (Also called the “White Book”.) C is one of the most popular programming languages of

all time – very few computer architectures exist for which there is no C.

C is predecessor to most of today’s procedural languages such as C++ and Java.

The C Language

BYU CS/ECEn 124 The C Language 13

The C Programming Language

Developed between 1969 and 1973 by Dennis Ritchie at Bell Labs.

C first developed for use in writing compilers and operating systems (UNIX).

A low-level high-level language Many variants of C 1989, the American National Standards Institute standardized C

(ANSI C, most commonly used C) “The C Programming Language” by Kernighan and Ritchie is the

C “Bible” (Also called the “White Book”.) C is one of the most popular programming languages of

all time – very few computer architectures exist for which there is no C.

The C Language

More Comments About C

BYU CS/ECEn 124 The C Language 14

“C is a terse and unforgiving abstraction of silicon.” Although C was designed for implementing system

software, C remains without rival in programming embedded systems.

Learning C imparts a deep understanding of the dominant von Neumann architecture in a way that no other language can.

C is the predecessor to most of today’s procedural languages such as C++ and Java.

Since poor C programming plays in the prevalence of the buffer overflow security vulnerabilities, it is critical that programmers learn how to program C properly.

The C Language

BYU CS/ECEn 124 The C Language 15

Compiling a C ProgramThe C Language

Object Code

Assembler Code

C/C++ Code

Machine Code

BYU CS/ECEn 124 The C Language 16

Compiling a C ProgramC Source Code

C Preprocessor

Library & ObjectFiles

ExecutableImage

C Compiler

The C Language

Preprocessedsource code

Source CodeAnalysis

1st Pass

SymbolTable

CodeGeneration

2nd Pass

Linker

Object module

BYU CS/ECEn 124 The C Language 17

A First Program

//************************************// blinky.c: Software Toggle P1.0//************************************#include "msp430x22x4.h"

void main(void){ int i = 0; WDTCTL = WDTPW + WDTHOLD; // stop watchdog P4DIR |= 0x40; // P4.6 output for (;;) // loop { P4OUT ^= 0x40; // toggle P4.6 while (--i); // delay }}

Tells compiler to use all the definitions found in the msp430x22x4.h library. A .h file is called a header file and contains definitions and declarations.

All programs must have a main() routine. This one takes no arguments (parameters).

Set P4.6 as output

Loop forever

Toggle P4.6Delay 65,536

1st C Program

Stop WD w/Password

BYU CS/ECEn 124 The C Language 18

Comments

Use lots of comments

/* This is a comment */ // This is a single line comment

Comment each procedure telling:/*----------------------------------* * ProcedureName – what it does * * Parameters: * * Param1 – what param1 is * * Param2 – what param2 is * * Returns: * * What is returned, if anything * *----------------------------------*/

Use lots of white space (blank lines)

C Style

BYU CS/ECEn 124 The C Language 19

Indenting Style

Each new scope is indented 2 spaces from previous Put { on end of previous line, or start of next line Line matching } up below

Style is something of a personal matter.

Everyone has their own opinions…

What is presented here is similar to that in common use and a good place to start...

if(a < b) { b = a; a = 0; } else { a = b; b = 0; }

if(a < b) { b = a; a = 0; } else { a = b; b = 0; }

Style 1 if(a < b) { b = a; a = 0; } else { a = b; b = 0; }

if(a < b) { b = a; a = 0; } else { a = b; b = 0; }

Style 2

C Style

BYU CS/ECEn 124 The C Language 20

More On Indenting Style

For very long clauses, you may want to add a comment to show what the brace is for:

if(a < b){

/* Lots of code here... */

} // end if(a < b)else{

/* Lots of code here... */

} // end else

if(a < b){

/* Lots of code here... */

} // end if(a < b)else{

/* Lots of code here... */

} // end else

C Style

BYU CS/ECEn 124 The C Language 21

The C Preprocessor

#define symbol code The preprocessor replaces symbol with code everywhere it appears in the

program below#define NUMBER_OF_MONKEYS 259#define MAX_LENGTH 80#define PI 3.14159

#include filename.h The preprocessor replaces the #include directive itself with the contents of

header file filename.h#include <stdio.h> /* a system header file */#include "myheader.h" /* a user header file */

Macros Pass arguments

#define add(x,y) x+y#define concatenate(x,y) x##y

C Preprocessor

C Header Files

BYU CS/ECEn 124 The C Language 23

RBX430-1 System Functions

RBX430-1.h and RBX430-1.c

uint8 RBX430_init(enum _430clock clock); // init boardvoid ERROR2(int error); // fatal error

Setting system clock

RBX430-1 Header Files

#include "msp430x22x4.h"

enum _430clock {_16MHZ, _12MHZ, _8MHZ, _1MHZ};#define myClock _8MHZ#define SMCLK 8000000 // SMCLK = ~8 mhz

void main(void){ RBX430_init(myClock); // init board ERROR2(5);}

Peripheral I/O in C

BYU CS/ECEn 124 The C Language 25

Switches on Port 1C Peripheral I/O

MS

P4

30F

22

74

BYU CS/ECEn 124 The C Language 26

Speaker on P4.5 (TB2)

MS

P4

30F

22

74

C Peripheral I/O

BYU CS/ECEn 124 The C Language 27

LEDs on Ports 3 & 4

MS

P4

30F

22

74

C Peripheral I/O

Stream I/O in C

BYU CS/ECEn 124 The C Language 29

C I/O

I/O facilities are not part of the C language itself Nonetheless, programs that do not interact with their environment

are useless Most digital I/O handled directly by C program

#include "msp430x22x4.h" SPR’s, Ports, A/D, transponder, switches, LED’s, etc

The ANSI standard defines a set of I/O library functions for portability

Programs that confine their system interactions to facilities provided by the standard library can be moved from one system to another without change.

The properties of the C I/O library functions are specified in header files

<stdio.h> (C standard library) “RBX430-1.h", “RBX430_lcd.h"

C Stream I/O

BYU CS/ECEn 124 The C Language 30

I/O Data Streams

All C character based I/O is performed on streams. In standard C there are 3 streams automatically opened

upon program execution: stdin is the input stream stdout is the output stream stderr stream for error messages

The printf function outputs formatted values to the stdout stream

printf( "format string...", parameters... );

The format string contains two object types: Ordinary characters that are copied to the output stream Conversion specifications which cause conversion and printing

of the next argument in the argument list.

C Stream I/O

BYU CS/ECEn 124 The C Language 31

Output in C

printf( format_string, parameters )

printf("Hello World");printf("%d plus %d is %d", x, y, x+y);printf("In hex it is %x", x+y);printf("Hello, I am %s. ", myname);printf("In ascii, 65 is %c. ", 65);

Output:Hello world

5 plus 6 is 11In hex it is bHello, I am Bambi.In ascii, 65 is A.

String literal

DecimalInteger

HexInteger

StringCharacterNewline

C Stream I/O

BYU CS/ECEn 124 The C Language 32

LCD on Ports 2,3, & 4

MS

P43

0F

227

4

C Stream I/O

BYU CS/ECEn 124 The C Language 33

RBX430_lcd.h Prototypes uint8 lcd_init(void); void lcd_clear(uint8 value); void lcd_backlight(uint8 backlight); void lcd_volume(uint8 volume); uint16 lcd_display(int16 mode); uint8 lcd_cursor(uint16 x, uint16 y); void lcd_printf(const char* fmt, ...); uint8 lcd_image(const uint8* image, uint16 x, uint16 y); uint8 lcd_blank(uint16 x, uint16 y, uint16 w, uint16 h); uint8 lcd_point(uint16 x, uint16 y, uint8 flag); void lcd_circle(uint16 x, uint16 y, uint16 r, uint8 pen); void lcd_square(uint16 x, uint16 y, uint16 s, uint8 pen); void lcd_rectangle(uint16 x0, uint16 y0, uint16 x1, uint16

y1, uint8 pen);

C Stream I/O

BYU CS/ECEn 124 The C Language 34

LCD – 160 x 160 x 5 PixelsY

(0-1

59)

Hello World!

// 5 x 8 pixel Characterslcd_cursor(40, 60);lcd_printf("Hello World!");

X (0-159)

C Stream I/O

BYU CS/ECEn 124 The C Language 35

Quiz 11.1 Pair up

Person “A” explain C I/O to Person “B” Person “B” explain (using different terms) C I/O to Person “A”

Write a C program to Initialize the RBX430-1 board to 8 mHz Initialize the lcd Write the word “Success” in the middle of the display

#include "msp430x22x4.h"#include "eZ430X.h"#include "lcd.h"

int main(void){ WDTCTL = WDTPW + WDTHOLD; // Stop WDT RBX430_init(_8MHZ); // init board lcd_init(); // init the lcd

lcd_cursor(80, 80); // position to middle of display lcd_printf("Success");}

BYU CS/ECEn 124 The C Language 36

// File: f_to_c.c// Date: 02/15/2010// Author: Joe Coder// Description: Output a table of Fahrenheit and Celsius temperatures.

#include "msp430x22x4.h"#include "eZ430X.h"#include "lcd.h"

#define LOW 0 // Starting temperature#define HIGH 100 // Ending temperature#define STEP 10 // increment

int main(void){ int fahrenheit; // Temperature in fahrenheit float celsius; // Temperature in celsius

WDTCTL = WDTPW + WDTHOLD; // Stop WDT eZ430X_init(_1MHZ); // init board lcd_init();

// Loop through all the temperatures, printing the table for(fahrenheit = LOW; fahrenheit <= HIGH; fahrenheit += STEP) { celsius = (fahrenheit - 32) / 1.8; lcd_printf("\nf=%d, c=%.1f", fahrenheit, celsius); }}

Use #define’s for magic numbers

A Second Program

1 digit to the right of the decimal point.

#include the lcd functions

Use meaningful names for variables

2nd C Program

Quiet the dog and init the system, lcd

BYU CS/ECEn 124 The C Language 37

top related