Administration Realtime systems D0003E Lecture 1: Introduction to real-time systems & bare metal programming in C Examiner / lecturer: Fredrik Bengtsson <bson@ltu.se> Lab instructor: Hassan Derhamy Assistant lab instructors: Erik Hellström, David Eng Course homepage: www.sm.luth.se/csee/courses/d0003e check often for news! Literature Lectures Alan Burns & Andy Wellings: Real-time Systems and Programming Languages Available at Begis, Adlibris, Bokus, Amazon, Also need: some additional book for C 16 in total may be subject to change slightly Lecture notes/slides will be available on the web (Last year s slides accessible via course homepage, expect some reorganization for this year!) updated as we go along Written examination: date: 2015-03-23 Text book coverage Lab assignments Core parts (3:rd edition) Chapters 6 (except 6.5), 7, 8, 9, 10.6, 11.7, 12, 13 (except 13.12), 15 (except 15.9), 17 Parts covered lightly (3:rd edition) Chapters 1, 2, 3, 4, 15.9, 18 Core parts (4:th edition) Chapters 2 (except 2.5), 4, 5, 6, 7, 8, 9, 10, 11 (ej 11.10), 7.1, 7.2 Parts covered lightly (4:th edition) Chapters 1, 14.1, 14.7, 16 Regarding sections on specific languages: C/POSIX parts should be fully understood For other languages, only key concepts need to be recognized when reading examples 5 assignments in total one optional Lab: A1503-A1506 (check your access cards) Work in teams of two (self-organized) 15 lab occations scheduled not enogh have to work on your own outside scheduled hours Lab instructor present at selected hours First lab is scheduled next week be there 1
Assignment deadlines Lab examination There is a deadline for each assignment (see web) Talk to your lab instructor if you are in need of a deadline extension The assignments are compulsory you are required to pass them all to pass the laborative part of the course Passed assignments cannot be claimed as credit if the course is taken another year To pass an assignment a team must produce a correct and comprehensible solution produce a report that describes the design and answers any questions asked in the assignment email the report in time (in pdf, including links to full source ) to keero@sm.luth.se Be prepared for further oral examination (randomized) Note: by submitting a report each team member accepts full responsibility for the team s solution Lab examination Cheating vs. co-operation To pass an assignment a team must produce a correct and comprehensible solution Present the solution for one of the lab supervisors Be prepared to answer questions abou the solution You are encouraged to work together with other groups on a conceptual level, as long as you declare which people you have been working with However, stealing or copying is equivalent to cheating, and will be reported to the diciplinary board Severe failure at an oral examination will be interpreted as an indication of cheating It is the responsibility of a team to ensure that each member is prepared to defend their full solution Word of advice Course goals Read the course homepage and the course material Spend considerable time in the lab Ask questions! The workload of this course is admittedly high, but the skills you are about to develop will be your reward! Above all, the basic message of the course is: To give competence in the development of real-time systems in high level programming languages To discuss various models of synchronization and communication between concurrent processes in such systems To study the characteristics of real-time systems and their constructions Realtime programming is fun! - for real, it is! 2
Three central concepts Concurrency Concurrency programs are built using several concurrent threads of execution Reactivity external input is reacted to rather than requested Realtime the timing of reactions is as important their functional behavior The world is concurrent several computers running in parallel is a concurrent system The physical processesproducing input to computers are inherently concurrent Multiple inputs could be handled by multiple computers but cost considerations suggest mapping multiple tasks onto fewer computers (resource sharing) When tasks are not indpendent but cooperating, things start getting interesting this is what concurrent programming is about, and something we will study in depth Reactivity Realtime Who is the active party below? Who calls who? the user demanding a result by clicking on the screen the programrequesting the next mouse click by means of an OS call The active view: the environment (user) acts because the program demands it (traditional programming) The reactive view: the program acts because the environment ( user ) demands it (embedded systems) We will study this problem, as well as reactive programming in general Someone asks about the current outdoor temperature. Which response is better? A correct reading of 20 C delivered 12 hours later An false reading of 10 C delivered immediately In a realtime system, a late reponse is just as bad as a wrong one In this course we will introduce methods and models for controlling the timing behavior of programs, in addition to their functionality Lab environment Buy your own lab equipment? For program development: standard PC Programming target: the AVR Butterfly a small 8/16 bit microprocessor with a 6 character LCD display various hardware ports 1 kb of RAM (+ program memory) no operating system! Programs will be downloaded before execution Will use C together with our own concurrency kernel Easy to lab at home buy you own card make a serial-cable (to connect it to the computer) you have to by a cable and solder it yourself we can help you Cards available from http://www.digikey.se/ search for "avr butterfly" There is a programmer too (much better than serial cable) AVRISP mkii You can download AVR Studio from www.atmel.com Of course, we have the equipment in the lab which you can borrow and take home during the course! 3
Overview Programming in C Start looking at C the language used in this course the preprocessor pointers programming model () some I/O C is the precursor to C++ and Java Dates back to the early 70 s (Kernighan & Ritchie) Developed hand-in-hand with Unix Primary goal was a flexible, machine-independent, assembly language for operating systems implementation Compared to most modern languges, C is very low-level and extremely unsafe Still C remains the natural choice for tasks with a certain hardware-oriented flavor, like, for example, the implementation of realtime systems C versus Java Functions and variables Many similarities, especially in syntax Major difference: C has no objects Instead C has records (structs), and a very general (and unsafe) support for pointers Other differences C has no garbage collection C has no concurrency support C has no exceptions All functions are declared on the top-level (remember there are no objects) A variable is either global (initialized to all-zero bitpatterns), or local to a function (as in Java) Local variable-declarations must precede all other statements in a block int a; int fname(int x, char y) { int z = x+y+a; During compilation, a C program is first processed in a pass that does plain textual manipulation of the source, without any regard to the C semantics. Common use: Defining constants Defining functions that expand inline Example #define SIZE 28 #define init(v) x=v; y=v; z=v The C preprocessor init(size); ==> x=28; y=28; z=28; C has no notion of a module, instead the file is the basic program unit To refer to and data in another file, one uses the preprocessor to include a header file with stub declarations of the external entities Example: #include myfile.h ------------------------ might expand to extern int myvar; char myfunc(float f); To include standard header files one writes #include <stdio.h> Include files 4
Include files Structures (records) /* myfile.h */ int myfunction(void); /* myfile.c */ int myfunction(void) { return 3; /* main.c */ #include "myfile.h int main(void) { printf("%i", myfunction()); Include file similar to an interface in java to some extent at least include file declares functions to be used elsewhere include file has a corresponding c-file functions implemented A struct in C is reminiscent of an interface in Java struct S { int y: ; struct S a = {1,2; a.x a.y Note the keyword struct that must accompany S A typedef declaration can help: typedef struct S T; T a = {1,2; typedef struct directly Pointers Typedef a struct directly when decloaring the struct: typedef struct { int y: T; T a = {1,2; a.x a.y Pointer in C reference to memory address Declaration int pointer int *p; Usage use * to dereference pointer example: *p=52; p denotes the pointer itself not the int it is pointing to Pointers Pointers Reference use &-operator to create pointer from value example int i=2; int *p; p=&i; p is now a pointer to i The closest to a new operator in C: T *p = (T *)malloc(sizeof(t)); *p (*p).x p->x Note that the C equivalent to Java s obj.x is (*obj).x (*obj).x is equivalent to obj->x In contrast to Java, a pointer p must be deallocated explicitly: free(p) Beware of the dangling pointer problem free(p); p->x. However, malloc and free are actually OS/library calls, and will play a diminsihedrole in this course 5
Call-by-reference C allows the address of any variable to be used as a pointer: struct S a = {1, 2; struct S *p = &a; Primarily used to implement call-by-reference: int v; f(&v); void f(int *x) { *x = 8; Here, x becomes a pointer to the original argument. Again, beware of dangling pointers! Pointer operations summary reference (get pointer to something): &variable variable is a normal variable, we get a pointer to it dereference (get what a pointer points to): *variable variable is a pointer, we get the value it points to dereference AND struct field: variable->fieldname same as (*variable).fieldname Arrays Type casts In Java: int[] a = new int[100]; In C: int a[100]; C notably treats array identifiers as pointers: int *b = a; *a = b[0]; It actually goes further (pointer arithmetic): a[3] = *(b+3); [Caution!] Strings are just arrays of characters: char buf[256] = "abcd" String are terminated by the '\0' character Syntactically identical to Java, type casts in C just mean "compiler, please look away!". No checks at runtime! only change compilers interpretation of value struct S a = {1,2; char *p = (char *)&a; Exception: float <-> int does conversions actually converts the value The type (void *) is commonly used to denote the unknown type Bit-level programming Hexadecimal representation of integers and bit-level operations work just like in Java Will be more emphasized in this course than what is the case generally For preparation: recapitulate the semantics of operations &,, ~, ^, <<, and >>; and make sure the difference to logical operators &&,, and! is clear. x = w = 0 6
; ; Stack frame (aktiverinspost) ; ; Stack pointer Program counter ; int z = 23; ; int z = 23; w = 77; Locals of c z = 23 Locals of c z = 23 w = 77 7
; int z = 23; w = 77; return z+1; y = 24 ; b () { int y; int z = 23; w = 77; return z+1; Locals of c z = 23 w = 77 w = 77 Standard I/O w = 77 ; int z; w = 77; return z+1; To write to the standard output stream: printf("result is %d\n", r); putchar( q ); To read from the standard input stream: char c = getchar(); gets(buf); To access a non-standard stream: FILE *f = fopen("myfile.txt", "r"); char c = getc(f); fprintf(f, "Result is %d\n", r); To write to the standard error stream: fprintf(stderr, "Result is %d\n", r); More on printf() However The first argument to printf() is a string where certain characters have special meaning: %d format the int found as extra argument %x as %d, but use hexadecimal format %f format a float %c insert a char found as extra argument %s insert a string found as extra argument %% insert a single % Many more options, see library manual Several format chars consume extra arguments Note that printf takes a variable number of arguments (a gross hack even by C standards!) All I/O operations in the C standard libraries are built upon the assumption of an underlying operating system (Unix-like) Our target platform has no OS, so we ll have to replace printf and friends with something else Still, the standard I/O library is very handy when experimenting with C on the development system Note also that these standard libraries are completely different from those in Java 8
stdint.h As for the rest Very convenient size of int in C is compiler-dependent also exists: short int, long int In stdint.h: uint8_t: unsigned 8-bit integer uint16_t, uint32_t, uint64_t: 16, 32, 64-bits int8_t: signes 8-bit int16_t, int32_t, int64_t more types available Expressions, loops, switches very similar to Java [No built-in type boolean in C] available from stdbool.h For fuller coverage, read the tutorials referenced on the course homepage Best of all, study examples, and try modifying them bit-by-bit Or ask your lab instructor! Next lecture will deal with accessing hardware in C 9