1 / 44

EEE305 Microcontroller Systems

Teaching resources on Blackboard Copies on www.eej.ulst.ac.uk My office 5B18, telephone 028 90 366364 My email IJ.McCrum@ulster.ac.uk. EEE305 Microcontroller Systems. Computers: hardware and Software. Understanding what computers, micro-controllers and microprocessors can do

efrem
Télécharger la présentation

EEE305 Microcontroller Systems

An Image/Link below is provided (as is) to download presentation Download Policy: Content on the Website is provided to you AS IS for your information and personal use and may not be sold / licensed / shared on other websites without getting consent from its author. Content is provided to you AS IS for your information and personal use only. Download presentation by click this link. While downloading, if for some reason you are not able to download a presentation, the publisher may have deleted the file from their server. During download, if you can't get a presentation, the file might be deleted by the publisher.

E N D

Presentation Transcript


  1. Teaching resources on Blackboard Copies on www.eej.ulst.ac.uk My office 5B18, telephone 028 90 366364 My email IJ.McCrum@ulster.ac.uk EEE305 Microcontroller Systems

  2. Computers: hardware and Software • Understanding what computers, micro-controllers and microprocessors can do • What the hardware of these systems are like • What the software (firmware) of these systems is like • How to make the software • How to make the hardware

  3. Software • How to average 10 numbers? • Get the first number • Add the second number to it • Add the next number to it • Continue until you have added 10 numbers • Divide the total by 10.

  4. Start Clear TOTAL and Clear COUNT Get INPUT Add input to TOTAL Add 1 to COUNT Is Total =10 ? NO Divide TOTAL by 10 Present the ANSWER Stop Programming • How to average 10 numbers? • Get the first number • Add the second number to it • Add the next number to the sum • Continue until you have added 10 numbers • Divide the total by 10. Note the slight difference in the methods. The computer is good at repetitive stuff so it is good to make the first step the same as all The other steps, so the first number is not treated differently to Subsequent numbers.

  5. Start Clear TOTAL and Clear COUNT Get NUMBER Add NUMBER to TOTAL Add 1 to COUNT Is Total =10 ? NO Divide TOTAL by 10 Present the ANSWER Stop /******* comments can be made in two ways ***/ #include <stdio.h> // we use scanf and printf void main(void) { // two slashes produce a comment int number; // used for input int total=0; // used for running total int count=0; /* number of numbers input */ float answer; // compiler must know the type // of ALL variables in a program do{ scanf(“%d”,&number); complicated way to I/p total=total+number; // '='sign means “will become equal to” count =count+1; // or use count++ }while(count<10); answer = total/10; // better to use /count! printf(“\nThe answer is %f “,answer); }//--end of main –//

  6. Printf and Scanf – standard I/o library routines – not in the C language but supplied in libraries with each compiler The quoted strings passed to printfcan contain three things Ordinary text, escaped characters and format placeholders. The backslash followed by a character or characters e.g\n This is known as an escape sequence, and in this case it causes the printffunction to take a newline after the line of text has been printed. The other new device is the %f This is called a place holderand is used to indicate where the value of a particular variable should be printed. The fact that an f is used indicates that the variable is expected to be a floating point number. The values to be printed, or names of the variables to be printed, follow the string in a comma-separated list as shown.

  7. Escape sequences

  8. Format Placeholders

  9. Microcontroller • e.g a PIC microcontroller from Microchip • Many versions! (check out their website) • Our boards have 16F877A – 40 pin chip • 5 ports - Port A has 6 bits, B,C,D are 8 bit and E is 3 • Each pin can be input or output (just about) • Outputs are roughly 0V or 5V, up to 25mA (typically 3-4 volts) • Has timers built in – can work off system clock • Has an 10 bit ADC – Analogue to Digital convertor on PORTA, but you can choose to use it or ordinary i/o • Has serial input and output on RC6 and RC7. • Has chip interfacing capabilies on other PORTC lines IIC or SPI protocols.

  10. Hardware of PIC supported by Software • There are 4 or 5 C compilers for the PIC; made by CCS inc, or the HiTecCorporation • HiTec C provides special keywords to manipulate hardware features as well as a C library of useful functions. It was recently bought over by microchip and they have rebadged the compilers as the C8, C16 and C32 products. • The Standard C language has only 35 keywords and three or four basic data types. • Although it also has standard libraries – to calculate cosine for example or provide input and output through a keyboard and screen(console) - or a serial interface to a keyboard and screen.

  11. HiTec C (c.f www.htsoft.com)or now www.microchip.com

  12. Start Get TEMPERATURE YES Is it greater than 25? NO YES NO Is it greater than 25? Switch Heater ON Switch Heater ON Delay_milli_seconds(10) Another program • Get the temperature • If it is too high (>25) • Switch heater on • If it is too low (<22) • Switch heater off • Wait a bit • Do it again

  13. Start Get TEMPERATURE YES Is it greater than 25? NO YES NO Is it greater than 22? Switch Heater ON Switch Heater ON Delay_milli_seconds(10) #include <htc.h> #define _XTAL_FREQ 20000000 // line above needed to make __delay calls work __CONFIG(WDTDIS & PWRTDIS & BORDIS & UNPROTECT); //line above needed to set “fuses” in a PIC void main (void) { unsigned short int temperature; PORTC = 0x00; // TRISC = 0xFF; // set PORTC to be I/p PORTB = 0x00; TRISB = 0xFE; do { Temperature = PORTC; // assuming PORTC wired up if(temperature > 25) { RB0=1; //predefined in Hitec C } // PORTB bit 0 else { if(temperature < 22) { RB0=0; } } __delay_ms(10); //supplied library }while(1); }//-- end of main – never reached!--//

  14. Embedded C vs Ordinary C • Embedded C (running in a single chip microcomputer) • has few bits of input and a few bits of output as a minimum • Perhaps uses timers and special built in peripherals such as an ADC, serial port, I2C, SPI, USB, PWM outputs. • Might not use “console i/o” (after debugging) and does not have access to an OS. • Ordinary C runs on a full computer • has access to a disk drive and operating system resources • has access to a sophisticated screen for output and a keyboard and mouse for input. • May use “text console” or access the operating system resources – the windowing system and the various OS library calls to move about a window. • Interacts with a user in the normal way

  15. Learning C • Simple language of 35 Keywords • Simple structure, can be a single file containing a collection of functions, it will have a single function (named main()) and this might call other functions. • A function is a section of code that does a single simple thing; it has a defined entry point – a start, a defined list of incoming data to work on and a mechanism to send its results somewhere. (unless it is a beep() function)

  16. The C language • As well as functions you write there are library functions. You can also “include” other files that contain other functions. • Good to partition or split big problems into a number of small functions. Top down design… • As well as “WHAT NEEDS DONE” you also need to think about “WHAT DATA IS BEING MANIPULATED” • (If you focus on this then you have become Object Orientated) – There is a version of C that is suitable for OOPs programming – C++ Algorithms + Data Structures = Programs

  17. Why Use C? • C is a powerful and flexible language. • C is a popular language preferred by professional programmers. As a result, a • wide variety of C compilers and helpful accessories are available. • C is a portable language. Portable means that a C program written for one computer • system (an IBM PC, for example) can be compiled and run on another system • (a DEC VAX system, perhaps) with little or no modification • C is a language of few words, containing only a handful of terms, called keywords, • which serve as the base on which the language’s functionality is built. • C is modular. C code can (and should) be written in routines called functions. • These functions can be reused in other applications or programs. By passing pieces • of information to the functions, you can create useful, reusable code.

  18. Making Programs • Several tool paths exist; • Edit a file, give it a .c extension, e.gtest.c • Compile it, this creates test.obj • Link to any previously created .obj files • Link it to the standard library (to “bring in” printf.obj) • This creates test.exe • Run test.exe.

  19. Making Programs • In practice it is common to use an IDE to automate these steps and also manage the source files. • An IDE will have an editor window, a project navigation window, a function list window and a single button/command to create and run test.exe. • Visual C++ can create C based console programs, the IDE has a “make” command [F9] • And a run in a window command. • In practice you should add a line to pause the program so you can read the screen before the window exits. • In the embedded world, microchip provide MPLAB, with similar capabilities, and also a device programmer/downloader.

  20. Your First C Program C is case sensitive, C treats all “white space” the same (spaces, tabs, newlines) unless inside double quotes. Most C statements end in a semicolon. Line 1 tells the compiler where to find out about functions that you use and didn’t write yourself (printf) Line 2 is the start of a block of code – known as a function. This function is called main, it is passed nothing and returns a number Line 3 tells the compiler to allocate a bit of space for a “variable” that will be a whole number and will be referred to as i . Line 4 calls the special library function called printf. The documentation for printf describes what is passed to it, what it does and what if anything it returns to the caller. Line 5 scans the keyboard and awaits input Line 6 sends the number zero back to whoever called main, in this case it is the OS. Line 7 finishes the body of the main function. Most “blocks” of code have start and end curly brackets • #include <stdio.h> • intmain(void) { • inti; • printf(“Hello, World!\n”); • scanf(“%d”,&i); • return 0; • }

  21. Exercises: start up visual Studio, start a project of type C++ and windows CONSOLE based. Note: Variables declared outside a function are known and accessible anywhere in the file. Variables declared inside a function are only visible, known and accessible inside the function. Although you can pass a variables value to a function by calling it from within your own function (that is how printf knows the value to print) It is even possible to pass a reference to a variable, rather than its value, this is how scanf works • Enter and compile the following program. What does this program do? • #include <stdio.h> • intradius, area; • intmain( void ) { • printf( “Enter radius (i.e. 10): “ ); • scanf( “%d”, &radius ); • area = (int) (3.14159 * radius * radius); • printf( “\n\nArea = %d\n”, area ); • return 0; • } • Enter and compile the following program. What does this program do? • #include <stdio.h> • intx, y; • intmain( void ){ • for ( x = 0; x < 10; x++, printf( “\n” ) ) • for( y = 0; y < 10; y++ ) • printf( “X” ); • return 0; • }

  22. Exercises: programs with bugs! • BUG BUSTER: The following program has a problem. Enter it in your editor and • compile it. Which lines generate error messages? • #include <stdio.h> • intmain( void ); • { • printf( “Keep looking!” ); • printf( “You\’ll find it!\n” ); • return 0; • } • BUG BUSTER: The following program has a problem. Enter it in your editor and • compile it. Which lines generate problems? • #include <stdio.h> • intmain( void ) • { • printf( “This is a program with a “ ); • do_it( “problem!”); • return 0; • }

  23. Draw a flowchart , then write a program • Find the average of ten numbers • Input your coursework and exam marks for your semester one subjects and print out your semester average. • NB; %f is used for floating point in printf’s format specifier strings. • There are clues in the earlier slides.

  24. Variables in C • A variable is a named data storage location in your computer’s memory. By using a variable’s name in your program, you are, in effect, referring to the data stored there. • Variable names can contain a-z, A-Z, digits and the underscore, the first character must not be a number or one of the C keywords. • Variable names should be meaningful – self documenting code. • The computer works out where to store each variable, what address to place it and what size (how many bytes to allocate to store the variable contents. • We must give the compiler clues as to how many bytes – the type of data to be stored in each variable

  25. Variable sizes in bytes for a typical PC compiler, NB embedded compilers often are differerent!!!

  26. Although compilers differ; what is always true To give a compiler information about a variable you must “declare” your intentions // to declare a variable, give a type then the variable name (and a semicolon) inti; /* often worth adding a comment here!... i is used as a loop counter … */ char ch; Also, you can have multiple declarations within a statement but it makes commenting harder. inti,j,k; Also you can initialise a variable when you declare it. int total=0; float sum=0.0; // note how you can specify a floating point constant.

  27. Numbers, characters and strings • Numbers can be whole numbers or floating point numbers of different sizes; signed or unsigned. For example 42, or 42.0. We can also use HEX numeric constants by using a 0x prefix so 0x42 is actually 66 in decimal (4*16+2) • Programs often deal with text. There is only limited support for this in the actual C language, though there are many string functions available, you must #include <string.h> to access them • The data type char is used to hold a single character – actually it just holds an 8 bit number. • The compiler will convert a single character to its 8 bit numeric value – by using SINGLE quotes. Thus if i is declared as a char, you can say i = ’a’; and i ends up with the value 65. • The character set is known as the ASCII character set. • A string does not exist in C, we use arrays instead. An array is a collection of data objects of the same type and given a single collective name. Thus an array of characters is considered a string and there are a dozen library functions written to use an array of characters, with the VERY IMPORTANT CONVENTION that an extra byte is out at the end of the array that contains zero.

  28. The ASCII character set; in binary the symbol ‘A’ is 100 0001 or 0x41 or 65 in decimal

  29. Text strings • Whilst it is true no string variables exist in C, null terminated char arrays are treated as strings by the functions in the string library. • Also the compiler will convert string constants to a null terminated char array in memory; this uses the DOUBLE QUOTES to tell the compiler what to do. • You have already seen this in the parameters passed to printf (and scanf) • Thus printf(“This is a string”); will work • You cannot assign text to a string or add strings together in C – without using specially written string functions strcpy() and strcat()

  30. Declaring arrays and strings • //C uses square brackets with arrays. To declare • intmydata[6]; // the compiler sets aside room for 6 ints • char me[6]; // 6 bytes, 5 for chars and one for the zero terminator • // To declare and initialise, the compiler helps a bit here • intmydata[] = {1,2,99,42,55,77}; // you can keep the [6] if you want • char me[] = “james”; // the compiler stores 6 bytes ‘j’,’a’,’m’,’e’,’s’,’\0’ • To use an array element as a single data value, use the square brackets and an index number. x = mydata[2]; makes x=99 • NOTE indexing starts at zero mydata[0], mydata[1] then mydata[2] – the third element of the array

  31. Assignment = a simple statement • You have seen simple assignments; in C these use the assignment operator, the equal sign. • In the assignment statement values move from the righthand side to the lefthand side of the equal sign. • Thus x=10; causes 10 to move into the variable x. • In C we use the double equal combination for an equality test, no data moves! • If(x==10)printf(“nothing moved”); • Be careful you see the difference between the assignment operator and the equality test

  32. The IF statement (two versions – the single staement and the block of startement version) • If (conditional test is true)do this-only if it was true; • … always do this… • If (conditional test is true){ • do this-only if it was true; • do that-only if it was true; • } • … now do this (always) • I recommend you always put brackets in – even in the single statement version – at least when you start C it reduces errors • If (conditional test is true){do this-only if it was true;} • … always do this…

  33. If statements • If (conditional test is true)do this-only if it was true; • … always do this… • e.g, actual C • If(count==10)average=sum/count;

  34. If(count==10) { average=sum/count; printf(“average of %d numbers is %f\n”, count, average); } // There is a lot going on here, note the use of two format specifiers and one // escape character in the printf function parameter list. • The other conditional tests are • != • < • > • <= • >=

  35. If – else statements • If(count<10){ // Note NO semicolon • sum=sum+mydata[count]; // If and if-else are compound • count=count+1; // statements. Only simple • }else{ // statements end in • printf(“average is %f\n”,sum/count); // semicolons • return 0; • } • // program defensively – keep your logic flow simple, easy to understand • You can also have nested if and multiple elses – too awkward…

  36. The following code sets a variable c equal to the greater of two variables a and b, or 0 if a and b are equal. • if(a > b){ • c = a; • } • else if(b > a){ • c = b; • } • else{ • c = 0; • } • Too error prone, find a way to express your code more simply. • (switch-case statements)

  37. The Conditional Expression • You do not often need this, I usually look up the syntax if I am going to use it, it can give you concise code. • A conditional expression is a way to set values conditionally in a more shorthand fashion than If Else. The syntax is: • (/* logical expression goes here */) ? (/* if nonzero (true) */) : (/* if 0 (false) */) • The logical expression is evaluated. If it is nonzero (true), the overall conditional expression evaluates to the expression placed between the ? and :, otherwise, it evaluates to the expression after • the : • Therefore, the above example (changing its function slightly such that c is set to b when a and b are equal) becomes: • c = (a > b) ? a : b; • So c = a if the test is true or c = b if the test is false

  38. The Switch Case statement The SwitchCase construct takes a variable, usually an int, placed after switch, and compares it to the value following the case keyword, the value can be a char constant ‘x’ If the variable is equal to the value specified after case, the construct "activates", or begins executing the code after the case statement. Once the construct has "activated", there will be no further evaluation of cases. SwitchCase is syntactically "weird" in that no braces are required for code associated with a case. Very important: Typically, the last statement for each case is a break statement. This causes program execution to jump to the statement following the closing bracket of the switch statement, which is what one would normally want to happen. However if the break statement is omitted, program execution continues with the first line of the next case, if any. This is called a fallthrough. • switch (grade) • { • case 1: • printf("A\n"); • break; • case 2: • printf("B\n"); • break; • case 3: • printf("C\n"); • break; • case ‘q’: • case ‘Q’: • printf("D\n"); • break; • default: • printf("F\n"); • break; • }

  39. Loops: there are 3 of these; the FOR loop, the WHILE loop and the DO loop int a=1; do{ printf("a is %d \n",a); a = a*2; }while(a<100); // note semicolon! // loop is done once or more times // again break can be used to exit // to the statement below the loop // prematurely and continue can // be used to jump back up to the // do (start of loop) • int a=1; • while(a<100) { • printf("a is %d \n",a); • a = a*2; • } • // loop is done zero or • // more times. • // Note no semicolons • // the keywords break • // and continue can be • // used inside while • // loops

  40. The for loop is handiest when we know how many times around a loop we want, e.g to execute a loop 100 times. However you can use it in a variety of ways. • int ix; • for(ix = 1; ix <= 100; ix = ix +1){ // or use ix++ to save typing. • printf("%d ", ix); • } • // the three parts of the FOR loop, initialisation executed once on • // entering the loop the test, done at the TOP of the loop at • // the first } and the loop end statement, the increment done at the • // END of the loop, at the last } • // note that ix++ is shorthand for ix=ix+1, you can also use -- as a // decrement operator. These can be prepended or appended • // to the variable. i++ or ++i. This sometimes matters. E.g • i = 5; • x = i++; // now x is 5 and I is 6

  41. Functions • Things to know; • How to declare them e.gfloat sqr(double); or one you have seen • int main(void); // this declaration is in stdio.h! done for us! • // note the semicolon is vital here – to let the compiler see which is //the declaration and which is the body of the function • How to use them – pass them data and get results • x = sqr(y); // pass it a number, the VALUE of y • z = sqr(16); • p = sqr(4*y + x); // pass it a number, the value of the expression • How to write them. Note NO SEMICOLON below • float sqr(double dd){ //dd is not a local variable that takes the • return(dd*dd); // value of the incoming number • }

  42. Directives; not really part of the compiler – the file is preprocessed before being compiled • #include <string.h> // angle brackets = system • #include part1.c // no brackets = user folder • Note no semicolons!, the files are just inserted • #define PI 3.1428 // a simple text subsitution • Convention is to use UPPER CASE. (used a lot) • #ifndef GOTLCD • #define “putch(“ “putch(LCD,” • #endif • So if GOTLCD has been previously #defined • Then a text substitution will be carried out • #pragma Some none standard feature that your compiler allows • A different compiler will ignore a #pragma line if it doesn’t understand it.

  43. Summary • You have seen. • Basic data types • Arrays and strings • simple statements such as assignment expression • Conditional expression • Compound statements; if, while, do, for, switch,case, break, continue • Function usage • Preprocessor directives • Still to see; • casts, • accessing memory, (pointers) • passing variable references into functions instead of values. • Some more library functions, strings and files. • Read the 129 page “C_Programming__WikiBook.pdf” for next week

More Related