Professional Documents
Culture Documents
Revision History
Revision Date Description Author
Rev <nn.nn> + 1 <dd-mm-yyyy><Revision Description – Delete if not required> <Author>
Rev <nn.nn> <dd-mm-yyyy><Revision Description> <Author>
/* User definitions */
#define user_definition
/* Function prototypes */
/* Function declarations */
return_type function_name (parameter_list)
{
/* body of the function */
/* return expression */
}
/* Main program */
int main(void)
{
/* Body of main function */
6. Biến số và hằng số
6.1. Biến số - Variable
6.1.1. Kiểu biến - Variable Types
• Được khai báo cú pháp sau:
• [<storage modifier>] <type definition> <identifier>;
• [<lớp lưu trữ>] <định nghĩa kiểu dữ liệu> <tên biến>;
• Có thể khai báo dưới dạng mảng, tối đa 8 chiều.
• Phần tử đầu tiên lúc nào cũng được định vị trí bằng 0.
• Giá trị khởi tạo biến sẽ được xóa về 0 nếu không có giá trị khởi tạo cụ thể nào cho nó.
• Lưu trên RAM vì nội dung có thể thay đổi trong quá trình chạy.
Biến kiểu bit - Bit variable
• Các biến kiểu bit toàn cục (global bit variable) có thể nằm phân bổ trong các thanh ghi
GPIOR từ R2 Æ R14.
• Cú pháp: bit <identifier>
Ví dụ:
/* declaration and initialization for an ATtiny2313 chip
which has GPIOR0, GPIOR1 and GPIOR2 registers */
bit alfa=1; /* bit0 of GPIOR0 */
bit beta; /* bit1 of GPIOR0 */
void main(void)
{
if (alfa) beta=!beta;
/* ........ */
}
• Các biến kiểu bit cục bộ (local bit variable) có thể khai báo tối đa 8 biến và được phân bổ
trong thanh ghi R15.
Ví dụ:
void main(void)
{
bit alfa; /* bit 0 of R15 */
bit beta; /* bit 1 of R15 */
/* ........ */
}
tween = 12; // OK
globey = 47; // OK
main_loc = 12; // Error
}
/* Main program */
void main(void)
{
/* A local variable to main */
unsigned char main_loc;
/* And Initialization */
char b = 99;
main_loc = 1; // OK
globey = 20; // OK
tween = 30; // Error
/* Multidimensional array */
int multidim_array[2][3]={{1,2,3},{4,5,6}};
void main(void) {
/* local array declaration */
int local_array1[10];
a = 255;
b = (unsigned int)a + 100;
}
/* Main program */
void main()
{
/* Variable */
unsigned char x, y;
x = y + c;
/* “3” is stored in FLASH/ROM and can not be modified */
x = 3 + y;
/* Letter ‘B’ is stored in FLASH/ROM and can not be modified */
x = ‘B’;
/* String “Hello world!” stored in FLASH/ROM
and can not be modified */
printf(“Hello world!”);
/* Main loop */
while(1);
}
Ví dụ 2:
/ * this function displays a string located in SRAM */
void display_ram(char *s) {
/* ....... */
/* ....... */
void main(void) {
/* this will not work !!! */
/* because the function addresses the string as */
/* it is located in SRAM, but the string "Hello world" */
/* is constant and is placed in FLASH */
display_ram("Hello world");
Lưu ý:
Để hiển thị dấu nháy đơn (‘) hay dấu xổ ngược trong dạng printable, chúng phải đặt trong cặp
dấu nháy đơn và theo sau dấu xổ ngược.
‘\’’ represented for a single quote.
‘\\’ represented for a back slash.
Static
• Biến kiểu này mặc dù chỉ có thể được truy xuất từ hàm mà nó được khai báo trong đó
(không thể truy xuất từ các hàm khác), nhưng được compiler phân bổ trong vùng nhớ
toàn cục (global memory space).
• Biến này sẽ được khởi tạo giá trị một lần duy nhất khi hàm được gọi lần đầu tiên và giá
trị nó vẫn được lưu lại khi thoát khỏi hàm và gọi lại hàm đó vào lần tiếp theo.
static int value;
Ví dụ:
int alfa(void) {
/* declare and initialize the static variable */
static int n=1;
return n++;
}
void main(void) {
int i;
Register
• Tương tự như biến auto.
• Chỉ khác là được compiler phân bỏ trong thanh ghi thực sự của vi điều khiển để giảm tối
đa chu kỳ truy xuất dữ liệu từ các biến đó.
register char value;
Extern
• Nếu biến đó khai báo ở source file khác, trước khi tham chiếu tới biến cần phải khai báo
biến với kiểu extern.
extern int xyz;
Volatile
• Sử dụng để tránh compiler phân bổ biến đó vào vùng nhớ các thanh ghi của vi điều
khiển và lưu ý compiler rằng nội dung của biến có thể bị thay đổi khi chương trình kiểm
tra.
volatile int abc;
void main()
{
value = third_val; // value = 12
value = first_val; // value = 10
}
void main()
{
// All following lead to the same result
PORTA = 1;
PORTA = red_led_on;
leds = 1;
leds = red_led_on;
}
Ví dụ 1:
// Following is the same
x = x + 1;
// Or
x++; // Post-Increasement
// Or
++x; // Pre-Increasement
Ví dụ 2: Về Pre-Increasement và Post-Increasement
i = 1;
k = 2*i++; // at complettion, k = 2, i = 2.
i = 1;
k = 2*++i; // at completion, k = 4, i = 2.
Ví dụ:
unsigned char x = 5;
unsigned char y = 2;
9.4. If-else
if (expression)
{
statement;
} else if (exression)
{
statement;
} else
{
statement;
}
Hoặc
if (expression)
statement;
else if (exression)
statement;
else
statement;
* Xem thêm biểu thức chứa điều kiện.
* Tham khảo ví dụ P.23 Æ P.26
9.5. Switch/Case
switch (expression)
{
case const_1:
statement;
break;
case const_2:
statement;
break;
case const_3:
statement;
break;
default:
statement;
break;
}
* Tham khảo ví dụ P.27
10.1. Bố cục của hàm và tiền khai báo hàm – Prototyping and Function
Organization
// Declaration of global variables
int var1, var2, var3;
// Declaration of function
int function_1 (int x, int y)
{
// statement
}
void main(void)
{
float a, b, c;
a = 12.9;
b = 13.3;
c = cube(a,b); // assign c to return value of cube() function
while(1);
}
10.3. Đệ quy
// Calculate Factorials
// n! = n * (n – 1)
int fact(int n)
{
if (n == 0) return n;
else return (n * fact(n - 1));
}
b = *p; // b = a = 10 now
Ví dụ 2:
char *p;
char a;
char b = 20;
p1 = &i;
p2 = &p1;
p3 = &p2;
void main(void)
{
swap(&var1, &var2);
}
Ví dụ 2: Với hàm scanf
int x, y z;
scanf(“ %d %d %d”, &x, &y, &z);
void task_0(void)
{
printf("This is task 0 \n\r");
}
void task_1(void)
{
printf("This is task 1 \n\r");
}
task_ptr = task_0;
(*task_ptr)();
task_ptr = task_1;
(*task_ptr)();
while(1);
11.4. Mảng
Mảng là tập dữ liệu với kiểu được khai báo trước, sắp xếp theo thứ tự.
Khai báo mảng cũng tương tự như khai báo biến, hằng và số lượng phần tử trong mảng trong
dấu [] ngay sau tên mảng.
Ví dụ:
int digit[10];
char str[20];
char str2[]=”Testing…\n\r”;
Cách truy xuất giá trị của phần tử trong mảng: các phần tử trong mảng được định vị từ 0 Æ
lượng phần tử - 1.
Ví dụ 2:
char digit[10]={0, 1, 2, 3, 4, 5 ,6 , 7, 8, 9};
char b;
b = digit[0]; // b = 0
b = digit[5]; // b = 5
b = digit[9]; // b = 9
Truy xuất phần tử trong mảng với con trỏ: giá trị của mảng cũng chính là địa chỉ của phần tử
đầu tiên trong mảng.
Ví dụ 3:
char digit[10]={0, 1, 2, 3, 4, 5 ,6 , 7, 8, 9};
char *p;
p = digit;
// Or
p = &digit[0];
type member_n;
} structure_var_name;
// Access to member 1
structure_var_name.member_1;
Ví dụ 3:
struct DATE {
int month;
int day;
int year;
}
struct PART {
char part_name[20];
long int sku;
struct LOCATION bin;
} widget;
// Access to member
int x_location, y_location;
x_location = widget.bin.x;
y_location = widget.bin.y;
temp.sku = 0;
temp,bin.x = x;
temp.bin.y = y;
return temp;
}
int x;
int y;
}
struct PART {
char part_name[20];
long int sku;
struct LOCATION bin;
};
struct PART widget, *this_widget;
int pos;
item.next_item = &item2;
pos = item.next_item->position;
// The same as
pos = item2.postion;
Sử dụng trong LINKED-LISTS và QUICK-SORTS.
12.2. Union
Cách khai báo của union cũng tương tự như của structure
Ví dụ:
struct union_tag_name {
type member_1;
type member_2;
type member_3;
//...
type member_n;
} union_var_name;
Chỉ khác biệt ở chỗ cách phân bổ bộ nhớ, các thành phần trong union chia sẻ với nhau vùng
nhớ chung là vùng nhớ chứa thành phần có kích thước lớn nhất của union đó.
Ví dụ 2:
union SOME_TYPES {
char character;
int integer;
long int long_one;
} my_space;
while(1)
{
value.port_byte[0] = PINA;
value.port_byte[1] = PINB;
printf(“16-bit = %04x \n”, value.port_word);
}
}
14. Phương pháp lập trình thời gian thực – Realtime methods
14.1. Sử dụng ngắt – Using Interrupt
14.2. Thực thi thời gian thực – Realtime Executive
14.3. State Machines
Table Of Content
1. Cấu trúc chương trình C - C Program Structure............................................................................................................. 3
2. Kiểu dữ liệu - Data types................................................................................................................................................. 3
3. Ghi chú – Comment ........................................................................................................................................................ 4
4. Từ khóa - Reserved keyword.......................................................................................................................................... 4
5. Cách đặt tên - Identifier Naming ..................................................................................................................................... 4
6. Biến số và hằng số.......................................................................................................................................................... 5
6.1. Biến số - Variable .................................................................................................................................................... 5
6.1.1. Kiểu biến - Variable Types ................................................................................................................................ 5
6.1.2. Phạm vi của biến ............................................................................................................................................... 5
6.1.3. Ép kiểu cho biến - Type Casting ....................................................................................................................... 7
6.2. Hằng số - Constant ................................................................................................................................................. 7
6.3. Lớp lưu trữ - Storage Class .................................................................................................................................. 10
7. Liệt kê và Định nghĩa .................................................................................................................................................... 11
7.1. Liệt kê - Enumeration ............................................................................................................................................ 11
7.2. Định nghĩa - Definition........................................................................................................................................... 11
8. Các phép tính toán và biểu thức ................................................................................................................................... 12
8.1. Toán tử gán – Assignment Operator..................................................................................................................... 12
8.2. Toán tử số học – Arithmetic Operator................................................................................................................... 12
8.3. Toán tử với bit – Bitwise Operator ........................................................................................................................ 12
8.4. Toán tử quan hệ và logic – Logical and Relational Operator ............................................................................... 13
8.5. Toán tử gán kép – Compound Assignment Operator ........................................................................................... 14
8.6. Biểu thức chứa điều kiện – Conditional Expression ............................................................................................. 14
8.7. Độ ưu tiên của các toán tử - Operator Precedence.............................................................................................. 14
9. Các cấu trúc điều khiển – Control Statement ............................................................................................................... 14
9.1. While loop.............................................................................................................................................................. 14
9.2. Do/While loop ........................................................................................................................................................ 14
9.3. For loop ................................................................................................................................................................. 15
9.4. If-else..................................................................................................................................................................... 15
9.5. Switch/Case .......................................................................................................................................................... 15
9.6. Break, Continue và Goto....................................................................................................................................... 16
10. Hàm - Function.......................................................................................................................................................... 16
10.1. Bố cục của hàm và tiền khai báo hàm – Prototyping and Function Organization .......................................... 16
10.2. Hàm trả về giá trị - Functions return value ...................................................................................................... 17
10.3. Đệ quy ............................................................................................................................................................. 17
11. Con trỏ và mảng........................................................................................................................................................ 17
11.1. Con trỏ............................................................................................................................................................. 17
11.2. Hàm với tham số vào là con trỏ ...................................................................................................................... 18
Appendix