You are on page 1of 3

H v tn: Phm Minh Thin Thnh

MSSV: 21303683

CU TRC MT CHNG TRNH VIT TRN NGN NG CCS


1. Phn khai bo tin x l:
a. u tin l phn khai bo file header: #include <tn chip dng.h>
V d: # include <16f877a.h>
Vic khai bo ny thc cht l chp c file 16f877a.h vo chng trnh ny.
Ni dung ca file .h ny l s nh ngha tt c cc tn cng nh nh ngha cc hng s
c dng trong cc hm chc nng ca CCS.
b. Khai bo cu hnh: #fuses HS,NOLVP,NOWDT
Vi iu khin PIC c th hot ng nhiu ch khc nhau, cng nh cch cu hnh
phn cng ca n cng c nhiu ch . Mi ch nh vy c khai bo v dng s
nh hng n hot ng ca cc khi chc nng, cng nh cc chn ca vi iu khin.
V vy, i vi mi ng dng, ta phi khai bo cu hnh cho ph hp.
c. Khai bo tn s thch anh dng cho ng dng: # USE Delay(clock=tn s thch anh)
Tc ny phi ph hp vi thch anh ta dng trong mch.
Lu l chng ta ch dng c hm to thi gian tr delay_ms(), delay_us() sau khi c
khai bo ny trong chng trnh.
d. S dng cc chc nng c bit:
Khi s dng bt c khi chc nng c bit no trong vi iu khin PIC ta phi dng ch
th tin x l #USE khai bo.
Cc khi chc nng c bit l RS232, PWM, SPI, I2C ..vv.
2. Phn khai bo bin ton cc:
Sau phn khai bo tin x l l phn khai bo bin ton cc nu c.
Bin ton cc l bin c s dng trong ton b chng trnh, c chng trnh chnh v
chng trnh con. iu ny khc vi bin cc b l bin c khai bo trong cc chng
trnh con, hm con, chng trnh chnh, cc bin ny ch c to ra v s dng trong
chnh mi chng trnh khai bo n.
Mt s dng khai bo bin dng trong CCS:
Khai bo bin:
Int1,short: dng logic 1,0
Int,Int8,byte: dng s nguyn 8 bit, nu khai bo dng s nguyn 8 bit c du thm signed
Int16,long: dng s nguyn 16 bit
Int32: dng s nguyn 32 bit
Char: dng k t 8 bit
Float: dng s thc 32 bit

V d: int8 a; // Khai bo a l bin s nguyn 8 bit


Khai bo hng s:
V d: int8 const a=231;
Khai bo mng hng s:
V d: int const a[5]= {1, 23, 3, 4, 5}
3. Phn khai bo, nh ngha cc chng trnh con:
Chng trnh con l chng trnh s c gi t chng trnh chnh hoc chng trnh
con khc.
Chng trnh con phi c khai bo v nh ngha trong mt file chng trnh ng dng.
Phn khai bo phi t trc chng trnh chnh (trong file).
Phn nh ngha c th nh ngha ngay trong khai bo hoc c t bt k ni no sau
phn khai bo bin ton cc nu c.
Ngoi cc chng trnh con bnh thng ra, cn c chng trnh con phc v ngt c
t sau khai bo tin x l: # int_tn ngt.
4. Phn chng trnh chnh:
Bt u bng:
void main() {
}
Mt chng trnh trong CCS, vi iu khin s chy t chng trnh chnh bt u t dng lnh
u tin sau void main().
Cc chng trnh con ch c gi ti cc li gi chng trnh con trong chng trnh chnh
hoc t cc chng trnh con khc. Chng trnh con phc v ngt ch c chy khi c ngt xy
ra, v ngt c cho php.
Trong chng trnh chnh thng c cc cu trc nh:
-

Cu trc IF:
If (biu thc)
{
Lnh1;
Else lnh2;
}

Cu trc lp While:
While (biu thc)
{
Cc lnh;

}
-

Cu trc lp FOR:
For (biu thc 1, biu thc 2, biu thc 3)
{
Cc lnh;
}

Cu trc la chn SWITCH:


SWITCH (bin)
{
Case gi tr 1: lnh 1;
Break;
Case gi tr 2: lnh 2;
Break;

Case gi tr n: lnh n
Break;
[default: lnh n+1; break;]
}