You are on page 1of 246

Lp Trnh H Thng Nhng

10 tun hc ngn ng c
Michael J. Pont
University of Leicester
Thng tin chi tit:
http://www.le.ac.uk/engineering/mjp9/
Bn quyn tc gi Michael J. Pont,
2002-2006

Ti liu ny c th c sao chp v phn phi t do,min l thng bo bn quyn trong


tt c cc bn sao.
Bn dch u tay khng th thiu nhng sai st. Rt mong nhn c s gp ca cc
bn.
Mi thc mc v bn dch xin vui lng gi ti :
doanhau198@gmail.com
tranthien.pro@gmail.com
Atienganh.blogspot.com

Atienganh.blogspot.com

No book no knowledge

Mc lc
CHNG 1: XIN CHOTH GII NHNG .............................................................................................................4
KHI QUT KIN THC : ....................................................................................................................................5
TI SAO DNG NGN NG C? ....................................................................................................................... - 7 THE 8051 MICROCONTROLLER...........................................................................................................................8
CU TRC SIU VNG LP .............................................................................................................................9
C (V VIT) CC CHN ................................................................................................................................ 12
CCH TO V S DNG BIN SBIT ................................................................................................................... 14
TO HM TR BNG PHN MM .................................................................................................................... 16
CHNG 2: C S THIT LP PHN CNG (RESETS, DAO DNG V PORT I/O) .................................................. 18
TNG QUAN : .................................................................................................................................................. 21
DAO NG PHN CNG ................................................................................................................................. 22
VN N NH ............................................................................................................................................. 24
RESET PHN CNG.......................................................................................................................................... 28
LED NHIU THANH L G? ................................................................................................................................ 36
IU KHIN LED N ...................................................................................................................................... 37
CHNG 3: C NT BM .................................................................................................................................. 38
S CN THIT CA IN TR KO ................................................................................................................... 47
V D:C NT BM (CODE C BN) ............................................................................................................. 51
V D: M NHNG CH CU ........................................................................................................................ 57
CHNG 4: THM CU TRC VO CODE CA BN.............................................................................................. 63
GII THIU ..................................................................................................................................................... 64
V D LP TRNH HNG I TNG VI C (O-O C ) ...................................................................................... 68
D LIU CC LOI BIN THNG THNG ....................................................................................................... 75
INTERRUPTS .................................................................................................................................................... 76
TM TT: TI SAO S DNG PROJECT HEADER(TIU D N)? ................................................................... 77
THE PORT HEADER (PORT.H) ........................................................................................................................... 78
CU TRC LI V D :HELLO WORLD . .......................................................................................................... 81
CHNG 5:THI GIAN THC .............................................................................................................................. 98
GII THIU ..................................................................................................................................................... 99
HAI THANH GHI B SUNG .............................................................................................................................. 104
V D: TO HM TR PHN CNG................................................................................................................. 109
S CN THIT CHO C CH TIMEOUT (THI GIAN TR) - V D ................................................................... 112
TO LOOP TIMEOUTS .................................................................................................................................... 113
V D: NT BM TIN CY HN ...................................................................................................................... 116
KT LUN ...................................................................................................................................................... 119
CHNG 6: TO RA MT H IU HNH NHNG ............................................................................................. 121
LI GII THIU.............................................................................................................................................. 122
CC NGT TIMER C BN (LI CA MT H IU HNH NHNG) ................................................................. 125
CHNG TRNH CON PHC NGT (ISR) ......................................................................................................... 126
TIMER T NG NP LI .............................................................................................................................. 127
GII THIU V SEOS ...................................................................................................................................... 128
TC V, HM V LP TRNH .......................................................................................................................... 134
TIT KIM NNG LNG............................................................................................................................... 138
V D: TIT TRNG SA................................................................................................................................. 141
KT LUN ...................................................................................................................................................... 155
CHNG 7: H THNG A TRNG THI V DY HM ...................................................................................... 157
LI GII THIU.............................................................................................................................................. 158
THI HNH MT H THNG A TRNG THI (NH THI GIAN)...................................................................... 160
V D: DY N GIAO THNG ....................................................................................................................... 161
V D: KHNG LONG MY ............................................................................................................................. 169
THI HNH MT H THNG A TRNG THI (U VO/NH THI(INPUT/TIMER)) ...................................... 175
V D: B IU CHNH CHO MT MY GIT .................................................................................................. 176

Atienganh.blogspot.com

No book no knowledge

CHNG 8: S DNG GIAO DIN NI TIP ....................................................................................................... 190


RS-232 L G? .............................................................................................................................................. 192
GIAO THC RS-232 C BN ........................................................................................................................... 193
TRUYN D LIU KHNG NG B V TC BAUD................................................................................... 194
RS-232 CC MC IN P ............................................................................................................................. 195
CU TRC PHN MM .................................................................................................................................. 196
S DNG U(S)ART TRN CHIP CHO KT NI RS-232 ....................................................................................... 198
CC THANH GHI PORT NI TIP ..................................................................................................................... 199
TO RA TC BAUD ................................................................................................................................... 200
V LNH PRINTF()? ........................................................................................................................................ 203
RS-232 V 8051: BAO GM C IM MNH V IM YU............................................................................. 204
KT LUN ...................................................................................................................................................... 216
CHNG 9: H THNG BO NG NGI XM PHM .................................................................................... 218
LI GII THIU.............................................................................................................................................. 219
S HOT NG CA H THNG .................................................................................................................... 220
KT LUN ...................................................................................................................................................... 238
CHNG 10: IU KHIN MT ROBOT DI CHUYN............................................................................................ 239
KHI QUT CHUNG ....................................................................................................................................... 240
ROBOT C TH LM G? ................................................................................................................................ 241
ROBOT CHUYN NG NH TH NO? ......................................................................................................... 243
IU CH RNG XUNG ............................................................................................................................. 244
PHN MM PWM.......................................................................................................................................... 245

Atienganh.blogspot.com

No book no knowledge

Chng 1: Xin choth gii Nhng

Atienganh.blogspot.com

No book no knowledge

Khi qut kin thc :


Chng m u ny s:
Cung cp khi qut v kha hc ny
Gii thiu VK 8051
Cu trc phn mm siu vng lp
M t cch s dng cc chn iu khin
Bn to ra hm tr nh th no? V ti sao bn cn n?
Khi qut v kha hc ny
Kha hc ny c lin quan n s thc hin ca phn mm (v mt lng nh phn cng)
cho vic xy dng h thng nhng s dng 1 VK.
Cc b vi x l c kim tra chi tit l h 8051 (Bao gm c thit b chun v
thit b nh).
Tt c lp trnh ngn ng C.
Kt thc kha hc
Kt thc kha hc, bn c th:
1. Thit k phn mm cho b x l nhng ng dng n, trn c s nh,tiu chun
cng nghip.
2. Thc hin thit k trn bng cch s dng ngn ng lp trnh bc cao, hin i
3. Bt u hiu cc vn v tin cy,an ton,lm th no thit k phn mm v
chng trnh quyt nh c th c mt tc ng tch cc hoc tiu cc ln mt phn
vng.

Atienganh.blogspot.com

No book no knowledge

Sch tham kho

Trong sut kha hc bn c th tham kho cun sch sau:


Embedded C
by Michael J. Pont (2002)
Addison-Wesley
[ISBN: 0-201-79523X]

Thng tin chi tit ti:


http://www.engg.le.ac.uk/books/Pont/ec51.htm

Atienganh.blogspot.com

No book no knowledge

Ti sao dng ngn ng C?


y l ngn ng mc gia, vi cc tnh nng ca bc cao: h tr cho cc chc
nng v cc modul, v cc tnh nng bc thp: truy cp vo phn cng thng qua con
tr
Hiu qu cao.
Ph bin v d hiu.
Thm ch nhng ngi pht trin my tnh bn ch s dng c Java v C++
cng d dng hiu c php C.
Tt, trnh bin dch c cho mi vi x l nhng, (8-bit to 32-bit or
more) .
Sch, cc kha o to, code v d v cc trang wed tho lun rng ri trn ton th gii.

Ni chung ngn ng C c th khng l mt ngn ng hon ho pht trin h thng


nhng, nhng n l mt s la chn tt (v khng chc c mt ngn ng hon ho
c to ra.:-d).
Cn bit nhng g?
Trong sut kha hc ny, n s gi nh rng bn c kinh nghim lp trnh.V d Java or C++.
Mi ngi u c nn tng v lp trnh ri th vic hc C qu tht n gin

Atienganh.blogspot.com

-7-

No book no knowledge

The 8051 microcontroller

Tnh nng in hnh ca 8051:


32 chn I/O
B nh trong (RAM) - 256 bytes.
Nng cp ln ti 64 kbytes of ROM (B nh flash)
3 timer/counter 16-bit
9 ch ngt (2 ngt ngoi) vi 2 mc u tin.
Ngun tiu th thp.

Cc loi khc trong h 8051 thch hp cho mi th t h thng t v hng khng


n iu khin TV.

Atienganh.blogspot.com

No book no knowledge

Cu trc siu vng lp

Vn :
Mi trng phn mm ti thiu bn cn to 1 chng trnh C l g?
Gii quyt:
void main(void)
{
/* chuan bi cho nhiem vu X */
X_Init();
while(1) /* vong lap mai mai */
{
X(); /* thuc hien nhiem vu X */
}
}

iu quan trng l: siu vng lp, hoc vng lp v cng l mt iu cn thit v chng ta
khng c h thng iu hnh quay tr v gia tr ban u, chng trnh ca chng ta s duy tr
vng lp cho n khi ngt ngun.

Atienganh.blogspot.com

No book no knowledge

u nhc im ca siu vng lp


u im chnh ca vng lp chnh l s n gin. iu ny gip chng ta d dng xy dng,
g li, kim tra v duy tr .
Vng lp c hiu qu cao: c ti nguyn phn cng ti thiu.
Vng lp c tnh di dng cao .(rt phong ph v a dng)
Nhc im:
Nu chng trnh ca bn yu cu tnh chnh xc cao (v d bn cn c d liu chnh
xc ti 2ms), th khung vng lp ny khng cung cp chnh xc hay s linh hot
theo yu cu.
Cc vng lp hot ng ch ngun y .(full power). iu ny c th l khng
cn tht tt c cc chng trnh, v c th nh hng ti h thng ngun tiu th.
[Chng ta s thy chng 6, ngi lp trnh s gii quyt vn ny.]

Atienganh.blogspot.com

10

No book no knowledge

V d: Trung tm iu khin nhit

void main(void)
{
/* Khoi tao he thong */
C_HEAT_Init();
while(1) /* vong lap mai mai */
{
/* tim kiem nhiet do nguoi dung cai dat thong qua dao dien nguoi
C_HEAT_Get_Required_Temperature();
/* tim kiem nhiet do phong hien tai ..thong qua sensor nhiet do */
C_HEAT_Get_Actual_Temperature();
/* dieu chinh bep lua theo yeu cau */
C_HEAT_Control_Boiler();
}
}

Atienganh.blogspot.com

11

No book no knowledge

dung*/

c (v vit) cc chn

Vn
Lm th no vit phn mm c v vit t cc chn ca 8VK?
Bi cnh:
8051 chun c 4 cng 8-bit.
Tt c cc chn u dung c c 2 chiu: input v out put.
SFRs cc chn
iu khin cc chn ca 8051 thng qua phn mm l c bit n nh l cc thanh ghi
c bit special function registers (SFRs).
V mt vt l, SFR l mt vng b nh trong RAM ni:
P0 ti a ch 0x80
P1 ti a ch 0x90
P2 ti a ch 0xA0
P3 ti a ch 0xB0
Ch : 0x l nh dng s dng thp lc phn xem cun Embedded C, Chapter 2.

Atienganh.blogspot.com

12

No book no knowledge

SFRs v cc chn
Mt SFR phn u mt tp tin cho h 8051 s so dng:
sfr P0
sfr P1
sfr P2
sfr P3

=
=
=
=

0x80;
0x90;
0xA0;
0xB0;

Khai bo cc bin SFR nh danh, chng ta c th vit ti cc port mt cch n gin.


V d, chng ta c th gi d liu ti Port 1 nh sau:
unsigned char Port_data;
Port_data = 0x0F;
P1 = Port_data;

/* viet 00001111 toi Port 1 */

Cng nh vy, chng ta c th c t Port 1 nh sau:


unsigned char Port_data;
P1 = 0xFF;
Port_data = P1;

/* thiet lap che do doc */


/* doc du lieu */

Atienganh.blogspot.com

13

No book no knowledge

Cch to v s dng bin sbit


vit ti 1 chn n ca vk (p1_1) Chng ta c th dng Keil C d dng bin dch
v kim sot li.

#define LED_PORT P3
#define LED_ON 0
#define LED_OFF 1
sbit Warning_led

= LED_PORT^0;

/* LED duoc ket noi toi pin

Warning_led = LED_ON;
... /* delay */
Warning_led = LED_OFF;
... /* delay */
Warning_led = LED_ON;
... /* etc */

Atienganh.blogspot.com

14

No book no knowledge

3.0

*/

V d: c v vit bytes

void main (void)


{
unsigned char Port1_value;
/* cai dat P1 de doc
P1 = 0xFF;

*/

while(1)
{
/* doc tu P1 */
Port1_value = P1;

/* sao chep gia tri toi P2


P2 = Port1_value;
}

Atienganh.blogspot.com

*/

15

No book no knowledge

To hm tr bng phn mm

Vn
Lm th no to hm tr m khng dng ti phn cng (timer):
Gii quyt
Loop_Delay()
{
unsigned int x,y;
for

(x=0; x

<=

65535; x++)

{
y++;
}

Longer_Loop_Delay()
{
unsigned int x, y, z;

for (x=0; x<=65535; x++)


{
for (y=0; y<=65535; y++);
{
z++;
}
}

S dng my phn tch kim tra hm tr

Atienganh.blogspot.com

16

No book no knowledge

u nhc im ca hm delays
To ra thi gian tr ngn.
Khng yu cu timer (ca phn cng)
Lm vic vi bt k VK no.
Nhc im:

thay i tn s, hoc thm ch thay i ti u ha trnh bin dch.

Chun b cho chng tip theo


Bn gi lp phn cng th nhng bi hc c. iu ny to cho bn c kh nng
tp trung vo kha cnh phn mm ca h thng nhng of embedded systems, m khng cn
quan tm n vn phn cng.
Trong chng tip theo chng ti s chun b to ra h thng th nghim u tin ca
bn trn phn cng thc t.

Vui lng c chng 1, 2, 3 trc khi c


chng tip theo

Atienganh.blogspot.com

17

No book no knowledge

Chng 2: C s thit lp phn cng (resets, dao dng v port I

Atienganh.blogspot.com

18

No book no knowledge

Nhc li: The 8051 microcontroller

Tnh nng in hnh ca 8051:


32 cng vo ra I/O.
B nh trong (RAM) - 256 bytes.
Nng ln 64 kbytes vi b nh ca ROM (usually flash)
3 Timer 16bit/ counter
9 ch ngt vi 2 ch ngt trong vi 2 ch u tin .
Low-power Idle and Power-down modes.

Cc loi khc ca h 8051 rt thch hp cho tt c mi th t h thng t v hng


khng n iu khin TV.

Atienganh.blogspot.com

19

No book no knowledge

Nhc li: Trung tm iu khin l si

void main(void)
{
/* khoi tao he thong
C_HEAT_Init();

*/

while(1) /* vong lap mai mai */


{
/* tim kiem nhiet do yeu cau thong qua giao
dien nguoi dung */
C_HEAT_Get_Required_Temperature();
/* Nhiet do phong hien nay la.(thong qua gao
dien nguoi dung */
C_HEAT_Get_Actual_Temperature();
/* dieu chinh bep ga theo yeu cau */
C_HEAT_Control_Boiler();
}
}

Atienganh.blogspot.com

20

No book no knowledge

Tng quan :
Chng ny s:
Gii thiu k thut m bn cn xy dng mt h thng nhng thc t u
tin ca bn (trn bo th).
Chnh xc, chng ta s xem xt:
Mch dao ng
Mch Reset
Mch LEDs

Atienganh.blogspot.com

21

No book no knowledge

Dao ng phn cng


Tt c my tnh k thut s u c iu khin bi hnh thc mch dao ng.
Mch ny l nhp tim ca h thng v rt quan trng h thng lm vic chnh
xc.
V d:
Nu dao ng b li h thng s ngng hot ng.
Nu dao ng khng u th bt k thi gian tnh ton no cng s b sai lch.
Thch anh dao ng

Thch anh c s dng rt ph bin to ra


cc mch dao ng.

to ra dao ng hu ht cc thnh phn


bao gm u nm trn chnh VK
Ngi s dng thit b ny thng cung cp
thch anh v hai t nh hon thnh mt b dao ng.

Atienganh.blogspot.com

22

No book no knowledge

Kt ni thch anh t
VDDK nh th no?

Trong trng hp khng c thng tin c th, gi tr ca t =30pF s thc hin


tt trong mi trng hp.

Atienganh.blogspot.com

23

No book no knowledge

Tn s dao ng v thi gian chu k my


Trong cc thnh vin h 8051 ban u, 1 chu k my c khong 12 dao dng.
Cc th h sau nh Infineon C515C, mt chu k my c khong 6 dao ng, trong cc thi b
gn y nh Dallas 89C420, ch 1 dao dng trong mi chu k my.
Kt qu l cc thnh vin th h sau hot ng cng tn s nhng thc hin
nhiu vic v nhanh hn.
Gi tn s cng thp cng tt
Many developers select an oscillator Nhiu nh pht trin chn mt tn s cng hng,
l gn hoc l gi tr cao nht c h tr bi thit b c bit.
iu ny c th l mt sai lm:
Many Nhiu chng trnh khng yu cu cao v hiu sut m mt loi 8051 hin
i c th cung cp.
Cc nhiu in t (EMI) s tng ln cng vi tn s dao ng.
Trong hu ht cc h 8051 hin i (CMOS-based), c mt mi quan h gn gi giwuax
tn s dao ng v mch ngun cung cp. Kt qu l, bng cch s dng tn s thp nht
cn thit c th s gim mc tiu th in nng: iu ny rt hu ch trong nhiu ng
dng.
Khi truy cp cc thit b ngoi vi tn s thp nh LCD,b nh ngoi , chng trnh v
phn cng thit k c th n gin ha- v chi ph cho cc thit b ngoi vi, nh b nh
cht c th c gim xung (nu chip hot ng chm hn).
Ni chung, bn nn hot ng tn s thp nht c th tng thch vi thc hin cc nhu
cu cho cc ng dng ca bn.
Vn n nh
Mt yu t quan trng trong vic la chn mt b dao ng cho h thng dao ng
ca bn vn n nh dao ng. Trong hu ht cc trng hp,b dao dng n nh
trong khong :20 ppm: 20 phn trn triu.(percent part million).

Thch anh tinh th tiu chun c nh gi trong khong t 10 100 ppm, v nh


vy c th t ti 5 50 Pht/nm.

Atienganh.blogspot.com

24

No book no knowledge

Ci thin s n nh ca tn s dao ng
Nu bn mun mt h thng iu khin nhng ni chung c thch anh gi thi gian
chnh xc, bn c th chn cch l gi thit b l nng hoc t lnh (ni c nhit
n nh) , v tinh chnh phn mm gi thi gian chnh xc.(tuy nhin iu ny
him khi thc t.
Temperature Compensated Crystal Oscillators (TCXOs) Nhit b dao ng
thch anh- l c sn , cung cp trong mt gi phn mm s fujng d dng- 1 thch anh
dao ng, mt mch in b li s thay i nhit .
TCXOs c gi khong $100.00 .
Mt thc t l xc nh nhit , tn s c trng cho s la chn thch anh ca
bn, v bao gm c thng tin chng trnh ca bn.
Gi ca mt cm bin nhit nh khong ~$2.00), Bn c th theo di nhit v
iu chnh thi gian theo yu cu.

Atienganh.blogspot.com

25

No book no knowledge

u nhc im
Thc anh dao ng l n nh,. Thng thng khong 20-100 ppm = 50
pht/nm
Phn ln cc thit k c s ca 8051 u da trn mch dao ng thch anh .
Thch anh c chi ph hp l cho vic ph bin tn s.

Cc thnh phn b sung ch yu cu 2 t nh (30pF)

Nhng:
ca tinh th ph
thuc vo tui.

Atienganh.blogspot.com

26

No book no knowledge

B cng hng gm
Khi qut u nhc im
R hn tinh th.
Mnh v vt l: t b tn thng bi rung ng thit b,hoc v thit b.
Nhiu cn hng cha c xy dng trong t in., v c th s dng m khng
cn bt k thit b ngoi vi no.
C nh, khong tinh th dao ng.
Nhng
S n nh tng i thp: ni chung khng thch hp s dng khi yu cu chnh
xc thi gian.
chnh xc thng khong 5000 ppm = 2500 pht/nm (ln ti 50
pht/tun).

Atienganh.blogspot.com

27

No book no knowledge

Reset phn cng


Qu trnh bt u khi ng ca VK l mt qu trnh khng bnh thng.
Cc phn cng nm bn di l phc tp v nh,
Nh sn xut xc nh, (reset routine)thi quen xc lp li phi c chy
t phn cng ny thnh trng thi thch hp trc khi n thc hin mt chng
trnh ca ngi dng. Vic reset mt mt khong thi gian v yu cu b dao
ng ca VK hot ng.
1 mch reset l cch n gin nht diu khin reset thng xuyn.

V d:

Atienganh.blogspot.com

28

No book no knowledge

Mch reset mnh m hn


V d: (dng ds1812)

Atienganh.blogspot.com

29

No book no knowledge

Ti DC (in 1 chiu)
Cc chn cng ca VK 8051 c th ci t gi tr 0V hoc 5V (hoc trong 3V,
0V hoc 3V)di s iu khin ca phn mm.
Mi cng thng thng xut ra tn hiu c dng ~10mA.
Tng dng in trn VK xut ra khong 70mA hoc nh hn.

Atienganh.blogspot.com

30

No book no knowledge

LEDs

Kt ni trc tip led n ti 1 chn VK .


Ngun in p, Vcc = 5V,
LED in p thun, V diode = 2V,
Yu cu dng in, Idiode = 15 mA (Lu rng cc thng tin v LED c ch r
trong datasheet).
Gi tr in tr cn thit R= 200.

Atienganh.blogspot.com

31

No book no knowledge

Dng in tr ko (Use of pull-up resistors)

thch nghi vi mch m kt ni vi chn vk khng c in tr ko ta cn phi mc thm


in tr ko bn ngoi.
Gi tr in tr ko thch hp vo khong 1K 10K.
iu ny p dng cho mi v d trong sch.
Lu :
iu ny thng xy ra Port 0 (xem chng 3 bit them chi tit).

Atienganh.blogspot.com

32

No book no knowledge

Lai mt ti in p thp m khng cn b m

Xem cun PATTERNS FOR TIME-TRIGGERED EMBEDDED SYSTEMS, p.115


(NAKED LOAD)

Atienganh.blogspot.com

33

No book no knowledge

Dng 1 IC m

Dng IC m CMOS.

Dng IC m TTL.
C th s dng IC m CMOS trong bt c mch m no ca bn. Tham kho thm ti
liu v mch logic s.
Xem cunPATTERNS FOR TIME-TRIGGERED EMBEDDED SYSTEMS, p.118 (IC
BUFFER)

Atienganh.blogspot.com

34

No book no knowledge

V d: m 3 LED vi IC 74HC04
V d ny ch dung mt IC 74HC04 m cho 3 LEDs. Nh tho lun trong cch gii
quyt m vi CMOS chng ti khng yu cu in tr ko ln vi cc b m HC
(CMOS).
Trong trng hp ny chng ta gi nh rng cc led c iu khin dng ~15mA
mi led trong tng 50mA ca b m.

Xem cun PATTERNS FOR TIME-TRIGGERED EMBEDDED SYSTEMS, p.123

Atienganh.blogspot.com

35

No book no knowledge

LED nhiu thanh l g?


Nhiu n led c sp xp nh mt on nhiu thanh hin th : s
hin th ca 7 thanh led to thnh led hin th 7 thanh
.

Hin th c b tr nh sau thng c gi l catot chung hoc anot chung.

Yu
cu
dng in qua mi led khong 2mA (led hin th nh) ti 60mA (Led hin th to,
100mm hoc hn).

Atienganh.blogspot.com

36

No book no knowledge

iu khin Led n

Trong trng hp ny yu cu c mch m hoc IC iu khin


VK v LED.

gia chn ca

V d, chng ta c th dng UDN2585A.


Mi knh trong b m ny c th cng mt lc dng in len ti 120 mA
(ln ti 25V): iu ny l cho mt mn hnh LED rt to.

Lu rng y l b m o ngc (ngun


in). Logic 0 s cho ra logic 1.
Chun b bi cho chng tip

Atienganh.blogspot.com

37

No book no knowledge

Chng 3: c nt bm

Atienganh.blogspot.com

38

No book no knowledge

Gii thiu
Cc h thng nhng thng s dng cc thit b chuyn mch ging nh mt phn
giao din ngi dng.
Quy lut chung ny p dng cho hu ht cc h thng iu khin t xa nh gara t,
v nhiu nht l h thng li xe t ng.
D h thng bn to nh th no, bn vn cn c 1 giao din chuyn i ng
tin cy.

Trong chng ny chng ta xem xt lm th no c tn hiu t nt bm c


kh ti h thng nhng.
Trc khi xem xt chnh cc cng tc, chng ta hy xem xt qu trnh c trng
thi t chn vk.

Atienganh.blogspot.com

39

No book no knowledge

Nhc li: Phng php c bn c tn hiu t chn vk.


Chng ta c th gi mt vi d liu vo Port 1 nh sau:
sfr P1 = 0x90;

/* Tap tin tieu de thong thuong */

P1 = 0x0F;

/* viet 00001111 toi Port 1 */

Trong 1 cng cch chnh xc, chng ta c th c t Port 1 nh sau :


unsigned char Port_data;
P1 = 0xFF;
Port_data = P1;

/* t Port 1 ch doc */
/* doc tu P1 */

V d: c v Vit tng bytes .

void main (void)


{
unsigned char Port1_value;
/* Phai thiet lap P1 de doc */
P1 = 0xFF;
while(1)
{
/* doc gia tri P1 */
Port1_value = P1;
/* chep gia tri toi P2 */
P2 = Port1_value;
}
}

Atienganh.blogspot.com

40

No book no knowledge

V d: c v vit bits (n gin)


/*-------------------------------------------------------------*Bits1.C (v1.00)
-*-------------------------------------------------------------*/
#include <Reg52.H>
sbit Switch_pin = P1^0;
sbit LED_pin = P1^1;
/* ... ...................................................................................................................................................................................... */
void main (void)
{
bit x;
/* thiet lap chuyen doi pin de doc */
Switch_pin = 1;
while(1)
{
x = Switch_pin;
LED_pin = x;
}
}

/* doc Pin 1.0 */


/* viet toi Pin 1.1 */

/*-------------------------------------------------------------*---- END OF FILE ---------------------------------------*-------------------------------------------------------------*/


Ngi lp trnh c khinh nghim v C nn lu dng ny:
sbit Switch_pin = P1^0;
sbit LED_pin = P1^1;
y chng ta truy cp c vo 2 chn cng P1 thng qua vic s dng 1
khai bo bin.

Atienganh.blogspot.com

41

No book no knowledge

V d: c v vit bits (phin bn chung)


S dng 6 php ton vi ton t bit:
Php ton
&
|
^
<<
>>
~

Atienganh.blogspot.com

M t
AND
OR
XOR
Dch bit sang tri
Dch bit sang phi
o trng thi

42

No book no knowledge

/* Chuong trinh may tinh - minh hoa viec dung toan tu bit */
#include <stdio.h>
void Display_Byte(const unsigned char);
/* ... ...................................................................................................................................................................................... */
int main()
{
unsigned char x = 0xFE;
unsigned int y = 0x0A0B;
printf("%-35s","x");
Display_Byte(x);
printf("%-35s","1s complement [~x]");
Display_Byte(~x);
printf("%-35s","Bitwise AND [x & 0x0f]");
Display_Byte(x & 0x0f);
printf("%-35s","Bitwise OR [x | 0x0f]"); Display_Byte(x
| 0x0f);
printf("%-35s","Bitwise XOR [x ^ 0x0f]");
Display_Byte(x ^ 0x0f);
printf("%-35s","Left shift, 1 place [x <<= 1] "); Display_Byte(x <<=
1);
x = 0xfe; /* quay tro lai x de * gia tri ban dau */
printf("%-35s","Right shift, 4 places [x >>= 4]"); Display_Byte(x >>=
4);
printf("\n\n");
printf("%-35s","Display MS byte of unsigned int y");
Display_Byte((unsigned char) (y >> 8));
printf("%-35s","Display LS byte of unsigned int y");
Display_Byte((unsigned char) (y & 0xFF));
return 0;
}

Atienganh.blogspot.com

43

No book no knowledge

/* --------------------------------------------------------------- */
void Display_Byte(const unsigned char CH)
{
unsigned char i, c = CH;
unsigned char Mask = 1 << 7;
for (i = 1; i <= 8; i++)
{
putchar(c & Mask ? '1' : '0'); c <<= 1;
}
putchar('\n');
}

x
1s complement [~x]
Bitwise AND [x & 0x0f]
Bitwise OR [x | 0x0f]
Bitwise XOR [x ^ 0x0f]
Left shift, 1 place [x <<= 1]
Right shift, 4 places [x >>= 4]

11111110
00000001
00001110
11111111
11110001
11111100
00001111

Display MS byte of unsigned int y


Display LS byte of unsigned int y

00001010
00001011

Atienganh.blogspot.com

44

No book no knowledge

/*-------------------------------------------------------------*doc va viet du lieu vao tung chan(pin) cua cac cong.


Luu y: 2 chan tren cung 1 port 1
-*-------------------------------------------------------------*/
#include <reg52.H>
void Write_Bit_P1(const unsigned char, const bit); bit
Read_Bit_P1(const unsigned char);
/* ... ...................................................................................................................................................................................... */
void main (void)
{
bit x;
while(1)
{
x = Read_Bit_P1(0);
Write_Bit_P1(1,x);
}
}

/* doc Port 1, Pin 0 */


/* viet to Port 1, Pin 1 */

/* --------------------------------------------------------------- */
void Write_Bit_P1(const unsigned char PIN, const bit VALUE)
{
unsigned char p = 0x01;
/* 00000001 */
/* Dich trai voi so thich hop */
p <<= PIN;
/* neu muon muc logic 1 out o pin nay */
if (VALUE == 1)
{
P1 |= p;
/* toan tu OR */
return;
}
/* neu muon muc logic 0 out o pin nay */
p = ~p;
/* dao bit */
P1 &= p; /* toan tu AND
*/
}
/* --------------------------------------------------------------- */
bit Read_Bit_P1(const unsigned char PIN)
{
unsigned char p = 0x01;
/* 00000001 */
45
Atienganh.blogspot.com

No book no knowledge

/* Dich trai */
p <<= PIN;
/* viet 1 bit vao pin (de cai dat che do doc) */
Write_Bit_P1(PIN, 1);
/* doc pin (AND) va tro ve gia tri */
return (P1 & p);
}
/*-------------------------------------------------------------*---- END OF FILE ---------------------------------------*-------------------------------------------------------------*/

Atienganh.blogspot.com

46

No book no knowledge

S cn thit ca in tr ko

Phn cng ny hot ng nh sau:


Khi nt bm c m, khng c s tc ng vo cc chn(pin ) ca cc port. Mt
in tr trong trn cng ko cc chn ca vk ln mc 1 (thng l 5V). Nn
chng ta c cc chn(pin) s thy gi tr l 1.
Khi nt bm c nhn, cc chn(pin) s v mc 0V. khi chng ta c cc chn
c gi tr 0.

Atienganh.blogspot.com

47

No book no knowledge

S cn thit ca in tr ko (P1,P2,P3)
Chng ta tm tt in tr ko chng 2.
C in tr ko:

Khng c in tr ko:

Atienganh.blogspot.com

48

No book no knowledge

S cn thit ca in tr ko ln(P0)

Atienganh.blogspot.com

49

No book no knowledge

X l vi nt bm ny ln
Trong thc t cc nt bm c kh thng ny ln (c ngha l ON ri OFF trong mt thi
gian rt ngn) sau khi nt bm ng hoc m. (y gi l rung c kh)

Mi ln nhy tng ng vi mt ln bm l i vi 1 nt bm l tng. V vy nu


khng thit k phn mm ph hp, iu n c th pht sinh mt vi vn , nht l:
Thay v c A t bn phm, chng ta c th c AAAAA.
m s ln cng tc c nhn l v cng kh khn.
Nu nt bm c nhn 1 ln v nh ngay sau , vic nhy phm din ra ging
nh ta li nhn nt bm ln na.
Vic to ra phn mm kim tra gi tr u vo l rt n gin:
1. Chng ta c th c cc chn ph hp.
2. Nu chng ta ngh rng nt bm c nhn, chng ta ch thm 20ms v sau c
li chn ln na.
3. Nu c ln 2 xc nhn c l 1 th ta gi nh rng nt bm c nhn..

Lu rng con s 20 ms ch ph hp cho mt s trng hp.

Atienganh.blogspot.com

50

No book no knowledge

V d:c nt bm (code c bn)


Code dc nt bm ny ch yu chng ta mun thc hin cc cng vic nh:
iu khin motor khi nt bm c nhn.
Chuyn i nh sang n khi nt bm c nhn.
Kch hot my bm khi nt bm c nhn.

Cc hot ng nay c th s dng cc cng tc in m khng cn dung n vk, tuy


nhin chng ta dng vk s thch hp cho iu khin nhiu cng tc phc tp . V d:
iu khin motor khi nt bm cc nhn.
iu kin: Khng phi bo m an ton ti ch, thay vo l ting r trong 2s.
Chuyn i nh sang n khi nt bm c nhn.
iu kin: tit kim in, br qua cc yu cu bt sng ban ngy.
Kch hot my bm khi nt bm c nhn
iu kin: Nu cc b cha nc ch yu l di 300lit, Khng bm: thay vo bt
u d tr bm v rt nc t cc b khn cp.

Atienganh.blogspot.com

51

No book no knowledge

/*-------------------------------------------------------------*Switch_read.C (v1.00)

Mot chuong trinh doc nut bam don gian cho 8051.
- doc (phong nhay phim) nut bam vao Pin 1^0
- neu nut bam duoc nhan thay thi doi Port 3 output
-*-------------------------------------------------------------*/
#include <Reg52.h>
/* Connect switch to this pin */
sbit Switch_pin = P1^0;
/* hien thi trang thai nut bam o port 3 */
#define Output_port P3
/* tro ai gia tri Switch_Get_Input() */
#define SWITCH_NOT_PRESSED (bit) 0
#define SWITCH_PRESSED (bit) 1
/* ham chuc nang */
void SWITCH_Init(void);
bit SWITCH_Get_Input(const unsigned char DEBOUNCE_PERIOD); void
DISPLAY_SWITCH_STATUS_Init(void);
void DISPLAY_SWITCH_STATUS_Update(const bit);
void DELAY_LOOP_Wait(const unsigned int DELAY_MS);

Atienganh.blogspot.com

52

No book no knowledge

/*---------------------------------------------------------------- */
void main(void)
{
bit Sw_state;
/* ham khoi tao */
SWITCH_Init();
DISPLAY_SWITCH_STATUS_Init();
while(1)
{
Sw_state = SWITCH_Get_Input(30);
DISPLAY_SWITCH_STATUS_Update(Sw_state);
}
}
/*-------------------------------------------------------------*SWITCH_Init()
Ham khoi tao cho swicth
-*-------------------------------------------------------------*/
void SWITCH_Init(void)
{
Switch_pin = 1; /* dung pin nay cho input */
}

Atienganh.blogspot.com

53

No book no knowledge

/*-------------------------------------------------------------*SWITCH_Get_Input()
Doc va phong chong nhay co khi nhu sau:
1. Neu nut bam khong nhan, tro ve SWITCH_NOT_PRESSED.
2. neu nut bam duoc nhan, cho ham DEBOUNCE_PERIOD (in ms).
Sau do:
a. Neu nut bam khong duoc nhan trong thoi gian dai, tro ve SWITCH_NOT_PRESSED.
b. neu nut bam van duoc nhan, tro ve SWITCH_PRESSED
xem Switch_Wait.H de biet thm chi tiet ve gia tri ham tre.
-*-------------------------------------------------------------*/
bit SWITCH_Get_Input(const unsigned char DEBOUNCE_PERIOD)
{
bit Return_value = SWITCH_NOT_PRESSED;
if (Switch_pin == 0)
{
/* nut bam duoc nhan */
/* phong chong nhay phim cho phim ... */
DELAY_LOOP_Wait(DEBOUNCE_PERIOD);
/* kiem tra nut nhan lan nua */
if (Switch_pin == 0)
{
Return_value = SWITCH_PRESSED;
}
}
/* ay gio qay tro ve gia tri nut nhan */
return Return_value;
}

Atienganh.blogspot.com

54

No book no knowledge

/*-------------------------------------------------------------*DISPLAY_SWITCH_STATUS_Init()
Ham khoi tao DISPLAY_SWITCH_STATUS.( Trang thai cua nut bam)
-*-------------------------------------------------------------*/
void DISPLAY_SWITCH_STATUS_Init(void)
{
Output_port = 0xF0;
}
/*-------------------------------------------------------------*DISPLAY_SWITCH_STATUS_Update()
Ham don gia hien thi du lieu (SWITCH_STATUS) tren led ket
noi voi cac pin (Output_Port)
-*-------------------------------------------------------------*/
void DISPLAY_SWITCH_STATUS_Update(const bit SWITCH_STATUS)
{
if (SWITCH_STATUS == SWITCH_PRESSED)
{
Output_port = 0x0F;
}
else
{
Output_port = 0xF0;
}
}

Atienganh.blogspot.com

55

No book no knowledge

/*-------------------------------------------------------------*DELAY_LOOP_Wait()
Thoi giant re la khac nhau voi cac tham so.
Tham so la, khoang thoi giant re trong 1ms, tren 12MHz 8051 (12 dao
dong trong 1 chu ki may).
Ban can phai dieu chinh choc ac ung dung cua ban!
-*-------------------------------------------------------------*/
void DELAY_LOOP_Wait(const unsigned int DELAY_MS)
{
unsigned int x, y;
for (x = 0; x <= DELAY_MS; x++)
{
for (y = 0; y <= 120; y++);
}
}

Atienganh.blogspot.com

56

No book no knowledge

V d: m nhng ch cu
Vi code n gin trong v d trc, vn c th xy ra bt c khi no mt nt
bm(cng tc) c nhn trong khong thi gian di hn thi gian tr.

y l mi quan tm ln, bi v trong nhiu trng hp, ngi s dng s nhn


trong it nht 500ms (hoc cho n khi h nhn c phn hi rng nt bm c
nhn). Kt qu l ngi dng g ch hello trn man hnh c th thy:
HHHHHHHHHeeeeeeeeellllllllllllllllooooooooooo.

Mt hu qu l cc m code ny khng thch hp cho ng dng m chng ta cn m s


ln cng tc c nhn .

Atienganh.blogspot.com

57

No book no knowledge

Nu chng ta th dung code ny cho v d trc, cm bin s khng cho chng ta m s


cu nhng thay vo l thi gian ch cu i qua sensor.

Atienganh.blogspot.com

58

No book no knowledge

/*-------------------------------------------------------------*mot chuong trinh dem cuu voi 8051...


-*-------------------------------------------------------------*/
#include <Reg52.h>
/* ket noi toi pin nay */
sbit Switch_pin = P1^0;
/* hien thi so dem o port nay */
#define Count_port P3
/* tro ve gia tri Switch_Get_Input() */
#define SWITCH_NOT_PRESSED (bit) 0
#define SWITCH_PRESSED (bit) 1
/* ham chuc nang */
void SWITCH_Init(void);
bit SWITCH_Get_Input(const unsigned char DEBOUNCE_PERIOD); void
DISPLAY_COUNT_Init(void);
void DISPLAY_COUNT_Update(const unsigned char);
void DELAY_LOOP_Wait(const unsigned int DELAY_MS);
/* ---------------------------------------------------------------- */
void main(void)
{
unsigned char Switch_presses = 0;
/* Init functions */
SWITCH_Init();
DISPLAY_COUNT_Init();
while(1)
{
if (SWITCH_Get_Input(30) == SWITCH_PRESSED)
{
Switch_presses++;
}
DISPLAY_COUNT_Update(Switch_presses);
}
}

Atienganh.blogspot.com

59

No book no knowledge

/*-------------------------------------------------------------*/
void SWITCH_Init(void)
{
Switch_pin = 1; /* dung pin nay cho input */
}
/*-------------------------------------------------------------*SWITCH_Get_Input()
Doc va chong nhay co khi nhu sau:
1. Neu nut bam khong nhan, tro ve SWITCH_NOT_PRESSED.
2. neu nut bam duoc nhan, cho ham DEBOUNCE_PERIOD (in ms).
Sau do:
a. Neu nut bam khong duoc nhan trong thoi gian dai, tro ve SWITCH_NOT_PRESSED.
b. neu nut bam van duoc nhan, tro ve SWITCH_PRESSED
xem Switch_Wait.H de biet thm chi tiet ve gia tri ham tre.
-*-------------------------------------------------------------*/
bit SWITCH_Get_Input(const unsigned char DEBOUNCE_PERIOD)
{
bit Return_value = SWITCH_NOT_PRESSED;
if (Switch_pin == 0)
{
/* nut bam duoc nhan */
/* chong nhay phim - just wait... */
DELAY_LOOP_Wait(DEBOUNCE_PERIOD);
/* kiem tra lai nut bam */
if (Switch_pin == 0)
{
/* doi den khi nut bam duoc nha ra. */
while (Switch_pin == 0);
Return_value = SWITCH_PRESSED;
}
}
/* cuoi cung quay tro ve gia tri ban dau */
return Return_value;
}

Atienganh.blogspot.com

60

No book no knowledge

/*-------------------------------------------------------------*DISPLAY_COUNT_Init()
Ham khoi tao hien thi gia tri dem DISPLAY COUNT .
-*-------------------------------------------------------------*/
void DISPLAY_COUNT_Init(void)
{
Count_port = 0x00;
}
/*-------------------------------------------------------------*DISPLAY_COUNT_Update()
Ham don gian de hien thi ra cac led (Count_Port)
-*-------------------------------------------------------------*/
void DISPLAY_COUNT_Update(const unsigned char COUNT)
{
Count_port = COUNT;
}
/*-------------------------------------------------------------*DELAY_LOOP_Wait()
Thoi giant re la khac nhau voi cac tham so.
Tham so la, khoang thoi giant re trong 1ms, tren 12MHz 8051 (12 dao
dong trong 1 chu ki may).
Ban can phai dieu chinh cho cac ung dung cua ban!
-*-------------------------------------------------------------*/
void DELAY_LOOP_Wait(const unsigned int DELAY_MS)
{
unsigned int x, y;
for (x = 0; x <= DELAY_MS; x++)
{
for (y = 0; y <= 120; y++);
}
}

Atienganh.blogspot.com

61

No book no knowledge

Kt lun
M code nt bm va trnh by v tho lun trong cc chng trc gip chng ta thc hin c 2
vic :
Thc hin mt hot ng khi nt bm c nhn.
Tr li s vic l ngi s dng nhn v sau nt bm v sau nh.
Trong c 2 trng hp chng ti minh ha lm th no chng rung(nhy) nt bm.
Chun b cho chng tip theo
Trong chng tip theo, chung ti chuyn s ch v phng php cc bn c th s dng
li m code cho cc ti tip theo.

Atienganh.blogspot.com

62

No book no knowledge

Chng 4: Thm cu trc vo code ca bn

Atienganh.blogspot.com

63

No book no knowledge

Gii thiu
Chng ta s lm 3 vic chnh trong chng ny:
1. Chng ta m t lm cch no p dng lp trnh hng i tng vi ngn ng
C.cho php to ra cc th vin m code bn d dng lp vo cc ti lp trnh
nhng khc.
2. Chng ta m t lm cch no to v s dng cc file header. Cc tp
tin nay gi gn trong kha cnh t kha ca mi trng phn cng, ging nh cc
loi vi x l c s dng, b dao ng tn s v s chu k yu cu thc hin mi
lnh. iu ny gip ta d dng ti cng c m ca vi x l khc.
3. Chng ta s m t lm cch no to v s dng mt file Port Header: tp
hp tt c chi tit ca cc cng truy cp t ton b h thng. Ging nh file
header, n c rt nhiu tnh nng quan trng.

Chng ta s s dng 3 phng php ny trong code v d cc chng sau.

Atienganh.blogspot.com

64

No book no knowledge

Lp trnh hng i tng vi C

Ngn ng chung

Ngn ng v d

Code my

First-Generation Language
(1GL)

Assembly
Language.

Second-Generation Languages
(2GLs)

COBOL,
FORTRAN

Third-Generation Languages
(3GLs)

C, Pascal, Ada 83

Fourth-Generation Languages
(4GLs)

C++, Java, Ada 95

Atienganh.blogspot.com

65

No book no knowledge

Graham ni1:
Cm t hng i tng(object-oriented) tr thnh gn nh
ng ngha vi s hin i, tt p v gi tr trong cng ngh thng tin.
Jalote ni:
Mt li th chnh ca vic s dng nh hng hng i tng l n lm
cho d dng sn xut v hiu thit k hn.

Ngn ng hng i tng khng c sn trong cc ng dng nh, bi v chi ph cho vic s
dng cc tnh nng trong ngn ng ny kh cao.

Graham, I. (1994) Object-Oriented Methods, (2nd Ed.) Addison-Wesley. Page


1.

Jalote, P. (1997) An Integrated Approach to Software Engineering, (2nd Ed.)


Springer-Verlag. Page 273.

Atienganh.blogspot.com

66

No book no knowledge

N c th to ra cc file-based-classes( file c s, cc lp) trong C m khng cn mt


b nh ng k..

Atienganh.blogspot.com

67

No book no knowledge

V d lp trnh hng i tng vi c (O-O C )


/*-------------------------------------------------------------*PC_IO.H (v1.00)

Xem PC_IO.C de biet them chi tiet


-*-------------------------------------------------------------*/
#ifndef _PC_IO_H
#define _PC_IO_H
/* ------ hang so cong khai ------------------------------------ */
/* Gia tri tro ve boi PC_LINK_Get_Char_From_Buffer neu khong co san trong bo
dem */
#define PC_LINK_IO_NO_CHAR 127
/* ------ Khai bao ham mau -------------------------- */
void PC_LINK_IO_Write_String_To_Buffer(const char* const); void
PC_LINK_IO_Write_Char_To_Buffer(const char);
char PC_LINK_IO_Get_Char_From_Buffer(void);
/* phai thuong xuyen goi cac ham nay... */
void PC_LINK_IO_Update(void);
#endif
/*-------------------------------------------------------------*---- END OF FILE ---------------------------------------*-------------------------------------------------------------*/

Atienganh.blogspot.com

68

No book no knowledge

/*-------------------------------------------------------------*PC_IO.C (v1.00)

[chua day du - - xem EC Chap 9 de hoan thien thu vien] -*------------------------------------------------------------*/


#include "Main.H"
#include "PC_IO.H"
/* ------ dinh nghia cac bien cong khai ------------------------- */
tByte In_read_index_G;
tByte In_waiting_index_G;

/* du lieu trong bo dem da duoc doc */


/* du lieu trong bo dem cho de doc */

tByte Out_written_index_G; /* du lieu trong bo dem da duoc viet */ tByte


Out_waiting_index_G; /* du lieu trong bo dem cho de viet */
/* ------ ham mau rieng ------------------------- */
static void PC_LINK_IO_Send_Char(const char);
/* ------ hang so rieng ----------------------------------- */
/* nhan bo dem length */
#define RECV_BUFFER_LENGTH 8
/* truyen bo dem length */
#define TRAN_BUFFER_LENGTH 50
#define XON 0x11
#define XOFF 0x13
/* ------ cac bien rieng ----------------------------------- */
static tByte Recv_buffer[RECV_BUFFER_LENGTH];
static tByte Tran_buffer[TRAN_BUFFER_LENGTH];
/*-------------------------------------------------------------*/
void PC_LINK_IO_Update(...)
{
}

Atienganh.blogspot.com

69

No book no knowledge

/*-------------------------------------------------------------*/
void PC_LINK_IO_Write_Char_To_Buffer(...)
{
}
/*-------------------------------------------------------------*/
void PC_LINK_IO_Write_String_To_Buffer(...)
{
}
/*-------------------------------------------------------------*/
char PC_LINK_IO_Get_Char_From_Buffer(...)
{
}
/*-------------------------------------------------------------*/
void PC_LINK_IO_Send_Char(...)
{
}

Atienganh.blogspot.com

70

No book no knowledge

The Project Header (Main.H)

Project Header (Main.H)


#include <AT89S53.H>
#define OSC_FREQ (11059200UL)
typedef unsigned char tByte;

Atienganh.blogspot.com

71

No book no knowledge

/*-------------------------------------------------------------*Main.H (v1.00)
-*-------------------------------------------------------------*/
#ifndef _MAIN_H
#define _MAIN_H
/*-------------------------------------------------------Chung ta can chinh sua doan nay cho moi project
-------------------------------------------------------- */
/* bao gom cac tap tin cua loai vi dieu khien thich hop */
#include <reg52.h>
/* tan so dao dong (in Hz) e.g. (11059200UL) */
#define OSC_FREQ (12000000UL)
/* so dao dong theo huong dan (12, etc)
12 - ho 8051 / 8052 va phan lon nhieu thiet bi khac nhau cua Philip.
4 - Dallas 320, 520 etc.
1 - Dallas 420, etc. */
#define OSC_PER_INST (12)
/* -------------------------------------------------------khong nen them cac phan duoi
-------------------------------------------------------- */
/* dinh ghia theo loai bien (xem Chap 5)
typedef unsigned char tByte;
typedef unsigned int tWord;
typedef unsigned long tLong;

*/

/* ham ngat (xem Chap 7)


*/
#define INTERRUPT_Timer_0_Overflow 1
#define INTERRUPT_Timer_1_Overflow 3
#define INTERRUPT_Timer_2_Overflow 5
#endif
/*-------------------------------------------------------------*---- END OF FILE ---------------------------------------*-------------------------------------------------------------*/

Atienganh.blogspot.com

72

No book no knowledge

Cc tiu thit b
/*---------------------------------------------------------REG515C.H
File tieu de Infineon C515C
Copyright (c) 1995-1999 Keil Elektronik GmbH All rights reserved.
----------------------------------------------------------------*/

/*
sfr

bo chuyen doi A/D


ADCON0 = 0xD8;

*/

/*
sfr

he thong ngat
IEN0
= 0xA8;

*/

/*
sfr
sfr
sfr
sfr
sfr
sfr
sfr
sfr

Ports
P0
P1
P2
P3
P4
P5
P6
P7

/*
sfr

Serial Channel
SCON
= 0x98;

*/

/*
sfr

Timer0 / Timer1
TCON
= 0x88;

*/

/*
sfr

CAP/COM Unit / Timer2 */


CCEN
= 0xC1;

*/
=
=
=
=
=
=
=
=

0x80;
0x90;
0xA0;
0xB0;
0xE8;
0xF8;
0xDB;
0xFA;

Atienganh.blogspot.com

73

No book no knowledge

Tn s dao ng v dao ng theo hng dn


/* tan so dao dong (in Hz) e.g. (11059200UL) */
#define OSC_FREQ (12000000UL)
/* so dao dong theo huong dan (12, etc)
12 - ho 8051 / 8052 va phan lon cac thiet bi khac cua philip.
4 - Dallas 320, 520 etc.
1 - Dallas 420, etc. */
#define OSC_PER_INST (12)

Chng ta gii thch lm th no s dng cc thng tin ny:


To tr (Embedded C, Chapter 6),
Kim sot thi gian trong ht thng (Chapter 7), and,
Kim sot tc (baud) truyn trong giao tip kiu serial (Chapter 9).

Atienganh.blogspot.com

74

No book no knowledge

D liu cc loi bin thng thng

typedef unsigned char tByte;


typedef unsigned int tWord;
typedef unsigned long tLong;
Trong C cc t kha typedef cho php chng ta cung cp b danh cho cc kiu d liu.
Nh vy, trong project ny chng ta nhn thy m nh th ny:
tWord Temperature;
thay v:
unsigned int Temperature;
L do chnh s dng typedef l dn gin ha v thc y vic s dng d liu khng
m.(unsigned)
8051 khng h tr m s v m code s hc ph l cn thit thao tc d liu :
iu ny lm gim tc chng trnh v lm tng kch thc chng trnh.
S dng ton t bit ch dung cho cc d liu kiu unsigned: dung bin kiu
typedef lm gim kh nng lp trnh v v tnh p dng ton t ny vo d liu
signed.

Cui cng, ging nh chng trnh my tnh, s dng t kha typedef l cch d dng
lp rp ti code ca bn s dng cc vi x l khc.

Atienganh.blogspot.com

75

No book no knowledge

Interrupts
Nh lu trong Embedded C Chapter 2, Ngt l mt thnh phn quan trng
trong cc h thng nhng.
Nhng dng sau trong tiu Project Header c tc dng lm cho bn d dng s
dng hm ngt trong cc d n ca bn.
#define INTERRUPT_Timer_0_Overflow 1
#define INTERRUPT_Timer_1_Overflow 3
#define INTERRUPT_Timer_2_Overflow 5
Chng ta s m t lm cch no dung hm ny d dng trong Embedded C, Ch. 7.

Atienganh.blogspot.com

76

No book no knowledge

Tm tt: ti sao s dng Project Header(tiu d n)?


Vic s dng PROJECT HEADER lm cho code ca bn tr nn hay hn, bi v bt c ai
s dng project ca bn u bit ni tm kim thng tin. Chng hn nh m hnh mu ca
VK v tn s dao ng i hi s thc hin ca phn mm.
Vic s dng 1 project header c th lm cho code ca bn d dng di ng, bng cch t
mt s d liu quan trng ph thuc vo VK mt ni: nu bn thay i b vi x l hoc
dao ng s dng sau - trong nhiu trng hp bn s ch cn thay i project
header(tiu d n)

PES I - 91

Atienganh.blogspot.com

77

No book no knowledge

The Port Header (Port.H)

Port Header (Port.H)


// chn 3.0 v 3.1 c s dng
// cng RS-232

// cng tc
sbit Sw_up = P1^2;
sbit

Sw_down = P1^3;
f

Atienganh.blogspot.com

78

No book no knowledge

Tp tin Port Header rt n gin chng ta hiu v p dng.


rng, V d, chng ta c 3 file C trong mt profect (A, B,
C) mi file yu cu truy cp ti 1 hoc nhiu hn 1 chn cu VK,
File A c th bao gm:
/* File A */
sbit Pin_A = P3^2;
File B c th bao gm:
/* File B */
#define Port_B = P0;
File C c th bao gm:
/* File C */
sbit Pin_C = P2^7;

Trong phin bn ca m code ny, tt c cc port i hi truy cp tri rng qua nhiu
file.
C rt nhiu thun li thu c bng cch tch hp tt c cc cng truy cp trong mt file
tiu port.h :
/* ----- Port.H ----- */
/* dinh nghia cong truy cap B */
#define Port_B = P0;
/* dinh nghia cong truy cap A */
sbit Pin_A = P3^2;
/* dinh nghia cong truy cap C */
sbit Pin_C = P2^7;

Atienganh.blogspot.com

79

No book no knowledge

/*-------------------------------------------------------------*Port.H (v1.01)

'Port Header' (xem Chap 5) cho projwct DATA_ACQ (xem Chap 9)


-*-------------------------------------------------------------*/
#ifndef _PORT_H
#define _PORT_H
#include "Main.H"
/* ------ Menu_A.C ----------------------------------------- */ /* su dung toan bo cong port 1
va 2 cho du lieu thu duoc */
#define Data_Port1 P1
#define Data_Port2 P2
/* ------ PC_IO.C ------------------------------------------ */ /* chan 3.0 va 3.1 dung giao tiep
RS-232 */
#endif
/*-------------------------------------------------------------*---- END OF FILE ---------------------------------------*-------------------------------------------------------------*/

PES I - 95
Atienganh.blogspot.com

80

No book no knowledge

Cu trc li v d :Hello World .


/*-------------------------------------------------------------*Main.H (v1.00)
-*-------------------------------------------------------------*/
#ifndef _MAIN_H
#define _MAIN_H
/*-------------------------------------------------------Ban can sua phan nay cho moi project khac nhau
-------------------------------------------------------- */
/* dat cac file tieu de thich hop cho vdk tai day */
#include <reg52.h>
/* tan so dao dong (Hz) e.g. (11059200UL) */
#define OSC_FREQ (12000000UL)
/* so dao dong trong huong dan (12, etc)
12 - hoc 8051 va phan lon cac vdk thuoc ho philip etc.
4 - Dallas 320, 520 etc.
1 - Dallas 420, etc. */
#define OSC_PER_INST (12)
/* -------------------------------------------------------khong nen sua phan khai bao sau
-------------------------------------------------------- */
/* kieu du lieu (xem Chap 5)
typedef unsigned char tByte;
typedef unsigned int tWord;
typedef unsigned long tLong;

*/

/* khai bao ham ngat (xem Chap 7)


*/
#define INTERRUPT_Timer_0_Overflow 1
#define INTERRUPT_Timer_1_Overflow 3
#define INTERRUPT_Timer_2_Overflow 5
#endif

Atienganh.blogspot.com

81

No book no knowledge

/*-------------------------------------------------------------*Port.H (v1.00)

'Port Header' for project HELLO2 (xem Chap 5)


-*-------------------------------------------------------------*/
#ifndef _PORT_H
#define _PORT_H
/* ------ LED_Flash.C ----------------------------------------- */
/* ket noi led toi chan nay, kem theo tro thich hop */
sbit LED_pin = P1^5;
#endif
/*-------------------------------------------------------------*---- END OF FILE ---------------------------------------*-------------------------------------------------------------*/

Atienganh.blogspot.com

82

No book no knowledge

/*-------------------------------------------------------------*Main.C (v1.00)

Chuong trinh test cho 8051 "Hello Embedded World".


-*-------------------------------------------------------------*/
#include "Main.H"
#include "Port.H"
#include "Delay_Loop.h"
#include "LED_Flash.h"
void main(void)
{
LED_FLASH_Init();
while(1)
{
/* Thay doi trang thai led (OFF to ON,) */
LED_FLASH_Change_State();
/* Tre khoang 1000 ms */
DELAY_LOOP_Wait(1000);
}
}
/*-------------------------------------------------------------*---- END OF FILE ---------------------------------------*-------------------------------------------------------------*/

Atienganh.blogspot.com

83

No book no knowledge

*-------------------------------------------------------------*LED_flash.H (v1.00)

- Xem LED_flash.C de biet them chi tiet.


-*-------------------------------------------------------------*/
#ifndef _LED_FLASH_H
#define _LED_FLASH_H
/* ------ ham chuc nang mau -------------------------- */
void LED_FLASH_Init(void);
void LED_FLASH_Change_State(void);
#endif
/*-------------------------------------------------------------*---- END OF FILE ---------------------------------------*-------------------------------------------------------------*/

Atienganh.blogspot.com

84

No book no knowledge

/*-------------------------------------------------------------*LED_flash.C (v1.00)

Kiem tra ham sang led don gian.


-*-------------------------------------------------------------*/
#include "Main.H"
#include "Port.H"
#include "LED_flash.H"
/* ------ dinh nghia bien rieng ------------------------ */
static bit LED_state_G;
/*-------------------------------------------------------------*LED_FLASH_Init()
Chuan bi thay doi trang thai led .
-*-------------------------------------------------------------*/
void LED_FLASH_Init(void)
{
LED_state_G = 0;
}

Atienganh.blogspot.com

85

No book no knowledge

/*-------------------------------------------------------------*LED_FLASH_Change_State()
Thay doi trang thai cua LED tren 1 chan out danh nghia cua vdk
-*-------------------------------------------------------------*/
void LED_FLASH_Change_State(void)
{
/* thay doi trang thai led tu OFF ON */
if (LED_state_G == 1)
{
LED_state_G = 0;
LED_pin = 0;
}
else
{
LED_state_G = 1;
LED_pin = 1;
}
}
/*-------------------------------------------------------------*---- END OF FILE ---------------------------------------*-------------------------------------------------------------*
/*-------------------------------------------------------------*Delay_Loop.H (v1.00)
- Xem Delay_Loop.C de biet them chi tiet.
-*-------------------------------------------------------------*/
#ifndef _DELAY_LOOP_H
#define _DELAY_LOOP_H
/* ------ ham mau chuc nang --------------------------- */
void DELAY_LOOP_Wait(const tWord DELAY_MS);
#endif
/*-------------------------------------------------------------*---- END OF FILE ---------------------------------------*-------------------------------------------------------------*/

Atienganh.blogspot.com

86

No book no knowledge

/*-------------------------------------------------------------*Delay_Loop.C (v1.00)

Tao tre phan mem don gian trong 1 vong lap.


-*-------------------------------------------------------------*/
#include "Main.H"
#include "Port.H"
#include "Delay_loop.h"
/*-------------------------------------------------------------*DELAY_LOOP_Wait()
Thoi giant re voi bien la thong so .
Thong so o day la thoi giant re ms tren 12MHz 8051 (12 osc cycles).
Ban can sua lai thoi gian cho dung chuong trinh cua ban
-*-------------------------------------------------------------*/
void DELAY_LOOP_Wait(const tWord DELAY_MS)
{
tWord x, y;
for (x = 0; x <= DELAY_MS; x++)
{
for (y = 0; y <= 120; y++);
}
}
/*-------------------------------------------------------------*---- END OF FILE ---------------------------------------*-------------------------------------------------------------*/

Atienganh.blogspot.com

87

No book no knowledge

V d: cu trc li v d m nhng ch d.
/*-------------------------------------------------------------*Main.H (v1.00)
-*-------------------------------------------------------------*/
#ifndef _MAIN_H
#define _MAIN_H
/*-------------------------------------------------------Ban can them phan nay ho moi project
-------------------------------------------------------- */
/* phai khai bao file tieu de header thich hop cho vdk o day */
#include <reg52.h>
/* tan so dao dong (in Hz) e.g. (11059200UL) */
#define OSC_FREQ (12000000UL)
/* so dao dong trong moi huong dan (12, etc)
12 - ho 8051 / 8052 va phan lon cac ic khac cua philip
4 - Dallas 320, 520 etc.
1 - Dallas 420, etc. */
#define OSC_PER_INST (12)
/* -------------------------------------------------------nen sua cac phan duoi day
-------------------------------------------------------- */
/* kieu du lieu
typedef unsigned char tByte;
typedef unsigned int tWord;
typedef unsigned long tLong;

*/

/* dinh nghia ham ngat


*/
#define INTERRUPT_Timer_0_Overflow 1
#define INTERRUPT_Timer_1_Overflow 3
#define INTERRUPT_Timer_2_Overflow 5
#endif

Atienganh.blogspot.com

88

No book no knowledge

/*-------------------------------------------------------------*Port.H (v1.00)

'Port Header' cho project GOATS2 (xem Chap 5)


-*-------------------------------------------------------------*/
#ifndef _PORT_H
#define _PORT_H
/* ------ Switch_Wait.C ------------------------------------------ */ /* ket noi toi pin nay */
sbit Switch_pin = P1^0;
/* ------ Display_count.C ---------------------------------------- */ /* ma nhi phan ra o port 3 */
#define Count_port P3
#endif
/*-------------------------------------------------------------*---- END OF FILE ---------------------------------------*-------------------------------------------------------------*/

Atienganh.blogspot.com

89

No book no knowledge

/*-------------------------------------------------------------*Main.C (v1.00)

Chuong trinh dem cho 8051.


-*-------------------------------------------------------------*/
#include "Main.H"
#include "Port.H"
#include "Switch_wait.H"
#include "Display_count.H"
/* ---------------------------------------------------------------- */
void main(void)
{
tByte Switch_presses = 0;
/* ham khoi tao*/
SWITCH_Init();
DISPLAY_COUNT_Init();
while(1)
{
if (SWITCH_Get_Input(30) == SWITCH_PRESSED)
{
Switch_presses++;
}
DISPLAY_COUNT_Update(Switch_presses);
}
}
/*-------------------------------------------------------------*---- END OF FILE ---------------------------------------*-------------------------------------------------------------*/

Atienganh.blogspot.com

90

No book no knowledge

/*-------------------------------------------------------------*Switch_wait.H (v1.00)

- Xem Switch_wait.C de biet them chi tiet


-*-------------------------------------------------------------*/
#ifndef _SWITCH_WAIT_H
#define _SWITCH_WAIT_H
/* ------ hang so chung ------------------------------------ */ /* quay tro ve gia tri
Switch_Get_Input() */
#define SWITCH_NOT_PRESSED (bit) 0
#define SWITCH_PRESSED (bit) 1
/* ------ ham mau chuc nang chung --------------------------- */
void SWITCH_Init(void);
bit SWITCH_Get_Input(const tByte DEBOUNCE_PERIOD);
#endif
/*-------------------------------------------------------------*---- END OF FILE ---------------------------------------*-------------------------------------------------------------*/

Atienganh.blogspot.com

91

No book no knowledge

/*-------------------------------------------------------------*Switch_Wait.C (v1.00)
Thu vien don gian cho phong chong rung phim.
luu y: khong thoi gin cua chuc nang nay a bien o muc cao!
-*-------------------------------------------------------------*/
#include "Main.H"
#include "Port.H"
#include "Switch_wait.h"
#include "Delay_loop.h"
/*-------------------------------------------------------------*SWITCH_Init()
Cai dat chuc nang cho thu vien nut bam.
-*-------------------------------------------------------------*/
void SWITCH_Init(void)
{
Switch_pin = 1; dung pin nay cho tin hieu vao */
}

Atienganh.blogspot.com

92

No book no knowledge

/*-------------------------------------------------------------*SWITCH_Get_Input()
Doc va chong rung phim co khi nhu sau:
1. neu nut bam chua duoc nhan quay tro ve SWITCH_NOT_PRESSED.
2. neu nut bam duoc nhan, cho ham chong rung phim
DEBOUNCE_PERIOD (in ms).
-*-------------------------------------------------------------*/
bit SWITCH_Get_Input(const tByte DEBOUNCE_PERIOD)
{
bit Return_value = SWITCH_NOT_PRESSED;
if (Switch_pin == 0)
{
/* nut bam duoc nhan */
/* chong rung phim..cho (wait) */
DELAY_LOOP_Wait(DEBOUNCE_PERIOD);
/* Kiem tra nut bam lan nua */
if (Switch_pin == 0)
{
/* Cho den khi nut bam nay len */
while (Switch_pin == 0);
Return_value = SWITCH_PRESSED;
}
}
/* cuoi cung quay tro ve gia tri ban dau */
return Return_value;
}
/*-------------------------------------------------------------*---- END OF FILE ---------------------------------------*-------------------------------------------------------------*/

Atienganh.blogspot.com

93

No book no knowledge

/*-------------------------------------------------------------*Display_count.H (v1.00)

- Xem Display_count.C de biet them chi tiet


-*-------------------------------------------------------------*/
#ifndef _DISPLAY_COUNT_H
#define _DISPLAY_COUNT_H
/* ------ Ham mau chuc nang-------------------------- */
void DISPLAY_COUNT_Init(void);
void DISPLAY_COUNT_Update(const tByte);
#endif
/*-------------------------------------------------------------*---- END OF FILE ---------------------------------------*-------------------------------------------------------------*/

Atienganh.blogspot.com

94

No book no knowledge

/*-------------------------------------------------------------*Display_count.C (v1.00)
-*-------------------------------------------------------------*/
#include "Main.H"
#include "Port.H"
#include "Display_Count.H"
/*-------------------------------------------------------------*DISPLAY_COUNT_Init()
Khoi tao thu vien ham hien thi.
-*-------------------------------------------------------------*/
void DISPLAY_COUNT_Init(void)
{
Count_port = 0x00;
}
/*-------------------------------------------------------------*DISPLAY_COUNT_Update()
Ham hien thi don gian gia tri dem tren led qua cac cong
-*-------------------------------------------------------------*/
void DISPLAY_COUNT_Update(const tByte COUNT)
{
Count_port = COUNT;
}
/*-------------------------------------------------------------*---- END OF FILE ---------------------------------------*-------------------------------------------------------------*/

Atienganh.blogspot.com

95

No book no knowledge

/*-------------------------------------------------------------*Delay_Loop.H (v1.00)

- Xem Delay_Loop.C de biet them chi tiet.


-*-------------------------------------------------------------*/
#ifndef _DELAY_LOOP_H
#define _DELAY_LOOP_H
/* ------ ham chuc nang chung --------------------------- */
void DELAY_LOOP_Wait(const tWord DELAY_MS);
#endif
/*-------------------------------------------------------------*---- END OF FILE ---------------------------------------*-------------------------------------------------------------*/

Atienganh.blogspot.com

96

No book no knowledge

/*-------------------------------------------------------------*Delay_Loop.C (v1.00)

Tao ham tre phan mem do gian.


-*-------------------------------------------------------------*/
#include "Main.H"
#include "Port.H"
#include "Delay_loop.h"
/*-------------------------------------------------------------*DELAY_LOOP_Wait()
Thoi giant re voi cac thong so.
Thong so tre la ms, tan so 12MHz voi 8051 (12 osc cycles).
Ban can sua laic ho dung voi chuong trinh cua ban!
-*-------------------------------------------------------------*/
void DELAY_LOOP_Wait(const tWord DELAY_MS)
{
tWord x, y;
for (x = 0; x <= DELAY_MS; x++)
{
for (y = 0; y <= 120; y++);
}
}
/*-------------------------------------------------------------*---- END OF FILE ---------------------------------------*-------------------------------------------------------------*/
Chun b cho chng tip theo

Vui lng c trc chng 5 trc khi


chng ta cng nghin cu

Atienganh.blogspot.com

97

No book no knowledge

Chng 5: Thi gian thc

Atienganh.blogspot.com

98

No book no knowledge

Gii thiu
Trong chuyn ny, chng ta bt u xem xt vn phc tp trong vic o chnh
xc thi gian.
Vn ny kh quan trng v nhiu h thng nhng phi tha mn rng buc thi gian
thc.

Atienganh.blogspot.com

99

No book no knowledge

bit SWITCH_Get_Input(const tByte DEBOUNCE_PERIOD)


{
tByte Return_value = SWITCH_NOT_PRESSED;
if (Switch_pin == 0)
{
/* nhan nut bam */
/* Chong rung phim - just wait... */
DELAY_LOOP_Wait(DEBOUNCE_PERIOD); /* POTENTIAL PROBLEM */
/* kiem tra nut bam lan nua */
if (Switch_pin == 0)
{
/* cho den khi nt bam duoc nha tay */
while (Switch_pin == 0);
Return_value = SWITCH_PRESSED;
}
}
/* cuoi cung tro ve gia tri nut bam */
return Return_value;
}

Vn u tin s chng rung phm.khng bit chc lc no nt bm c nhn. V hm


tr l thc hin bng phn mm c th khng chnh xc c thi gian.
Vn th 2 thm ch cn nghim trng hn, trong mt h thng vi cc c trng thi gian
thc: chng ta lm cho h thng ch i v thi hn cho s nh ra cu nt bm.
Chng ta s gii quyt vn ny trong chng ny.

Atienganh.blogspot.com

100

No book no knowledge

To tr phn cng
Tt c cc thnh vin h 8051 u c it nht 16 bit timer/counter( nh bit l timer
0 v timer1).
Timer ny c th s dng vi thi gian chnh xc.

/* Cau hinh Timer 0 nhu mot timer 16-bit


*/
TMOD &= 0xF0; /* Xoa tat ca bit T0 (T1 trai khong doi) */
TMOD |= 0x01; /* cai dat bt T0 (T1 trai khong doi)
ET0 = 0;

*/

/* khong cho phep ngat */

/* gia tri cho tre 50 ms */


TH0 = 0x3C;
/* Timer 0 gia tri dau (byte cao) */
TL0 = 0xB0;
/* Timer 0 gia tri dau ( Byte thap) */
TF0 = 0;
TR0 = 1;

/* xoa co tran */
/* bat dau Timer 0 */

while (TF0 == 0); /* choc ho den khi timer 0 tran (TF0 == 1) */


TR0 = 0;

/* dung Timer 0 */

By gi chng ta xem n hot ng th no

Atienganh.blogspot.com

101

No book no knowledge

Thanh ghi TCON SFR

Bit

7
(msb)

NAME

TF1

TF1

TR1

TF0

TR0

4
IE1

IT1

1
IE0

0
(lsb)
IT0

C trn Timer 1

Ci t bi c trn Timer 1.
(Xa bi phn cng nu vi x l ngt thng thng .)
TR1
bit iu khin Timer 1
Ci t/ xa bi phn mm Timer 1 ON or OFF.
TF0
C trn Timer 0
Xa bi phn cng trn c trnTimer 0
(Xa bi phn cng nu vi x l ngt thng thng.)
TR0 bit iu khin Timer 0
Ci t/ xa bi phn mm Timer 0 ON or OFF.

Lu rng c bo trn ca timer c th dung to ra hm ngt. Chng ti se khng s


dng hm ny trong m code tr phn cng.
v hiu ha hm ngt, ta c th dung lnh C :
ET0 = 0; /* khong cho phep ngat (Timer 0) */
ET1 = 0; /* khong cho phep ngat (Timer 1) */

Atienganh.blogspot.com

102

No book no knowledge

Thanh ghi TMOD SFR


Bit

NAME Gate

6
C/T

M1 M0 Gate

Timer 1

C/T

M1 M0

Timer 0

Mode 1 (M1 = 0; M0 = 1)
16-bit timer/counter ( np li ch bnh thng))
Mode 2 (M1 = 1; M0 = 0)
8-bit timer/counter (ch 8bit t np li))
GATE

Gating control

Khi ci t, timer/counter x is c hiu lc khi INT x mc cao v TRx


iu khin bit c ci t. Khi xa timer x c hiu lc bt c khi no bit iu
khin TRx c ci t (TRx =1)
C/T

Counter or timer chn bit

Ci t counter hot ng truy cp (u vo t chn Tx).


Xa timer hot ng truy cp (du vo t h thng ng h ni b)).

Atienganh.blogspot.com

103

No book no knowledge

Hai thanh ghi b sung


Trc khi chng ta xem xt phn cng ny to ra hm tr nh th no, chng ta cn nhn
thy rng c 2 thanh ghi b sung lin kt ti mi timer: Chng ta gi l TL0 and TH0,
and TL1 and TH1.

Atienganh.blogspot.com

104

No book no knowledge

V d: Generating a precise 50 ms delay


/*-------------------------------------------------------------*Hardware_Delay_50ms.C (v1.00)

Kiem tra co se tre phan cung.


-*-------------------------------------------------------------*/
#include <reg52.h>
sbit LED_pin = P1^5;
bit LED_state_G;
void LED_FLASH_Init(void);
void LED_FLASH_Change_State(void);
void DELAY_HARDWARE_One_Second(void);
void DELAY_HARDWARE_50ms(void);
/*... .................................................................................................................................... ...*/
void main(void)
{
LED_FLASH_Init();
while(1)
{
/* thay doi trang thai led (OFF to ON, or vice versa) */
LED_FLASH_Change_State();
/* Tre khoang 1000 ms */
DELAY_HARDWARE_One_Second();
}
}

Atienganh.blogspot.com

105

No book no knowledge

/*-------------------------------------------------------------*LED_FLASH_Init()
Chuan bi cho ham thay doi trang thai led- xem ben duoi
-*-------------------------------------------------------------*/
void LED_FLASH_Init(void)
{
LED_state_G = 0;
}
/*-------------------------------------------------------------*LED_FLASH_Change_State()
-*-------------------------------------------------------------*/
void LED_FLASH_Change_State(void)
{
/* doi trang thai ON-OFF */
if (LED_state_G == 1)
{
LED_state_G = 0;
LED_pin = 0;
}
else
{
LED_state_G = 1;
LED_pin = 1;
}
}

Atienganh.blogspot.com

106

No book no knowledge

/*-------------------------------------------------------------*DELAY_HARDWARE_One_Second()
Tre phan cung trong khoang 1000 ms.
*** Gia thiet 12MHz 8051 (12 osc cycles) ***
-*-------------------------------------------------------------*/
void DELAY_HARDWARE_One_Second(void)
{
unsigned char d;
/* goi ham DELAY_HARDWARE_50ms() 20 lan */
for (d = 0; d < 20; d++)
{
DELAY_HARDWARE_50ms();
}
}
/*-------------------------------------------------------------*DELAY_HARDWARE_50ms()
*** gia thiet 12MHz 8051 (12 osc cycles) ***
-*-------------------------------------------------------------*/
void DELAY_HARDWARE_50ms(void)
{
/* cau hinh Timer 0 nhu mot 16-bit timer
*/
TMOD &= 0xF0; /* xoa tat ca bit T0 (T1 trai khong doi) */
TMOD |= 0x01; /* cai dat bit yeu cau T0 (T1 trai khong doi)
ET0 = 0;

*/

/* cam ngat */

/* gia tri tre 50 ms delay */


TH0 = 0x3C;
/* Timer 0 gia tri ban dau ( Byte cao) */
TL0 = 0xB0;
/* Timer 0 gia tri ban dau ( Byte thap) */
TF0 = 0;
TR0 = 1;

/* xoa co tran */
/* bat dau timer 0 */

while (TF0 == 0); /* choc ho den khi Timer 0 tran (TF0 == 1) */


TR0 = 0;
}

/* dung Timer 0 */

Atienganh.blogspot.com

107

No book no knowledge

Trong trng hp ny chng ta gi thit tn s dao ng cho vk l 12 MHz

Chng ta yu cu tr 50s, v vy thi gian yu cu :


50 ms

1000000 = 50000 n v.

1000 ms
Timer trn khi b m tng n gi tr 65535.
Nh vy, gi tr u cn np tr 50 ms delay l:
65536 - 50000 = 15536 (decimal) = 0x3CB0

Atienganh.blogspot.com

108

No book no knowledge

V d: to hm tr phn cng
/*-------------------------------------------------------------*Main.C (v1.00)

Nhay led voi ham tre phan cung (T0).


-*-------------------------------------------------------------*/
#include "Main.H"
#include "Port.H"
#include "Delay_T0.h"
#include "LED_Flash.h"
void main(void)
{
LED_FLASH_Init();
while(1)
{
/* thay doi trang thai led (OFF to ON,) */
LED_FLASH_Change_State();
/* tre khoang 1000 ms */
DELAY_T0_Wait(1000);
}
}
/*-------------------------------------------------------------*---- END OF FILE ---------------------------------------*-------------------------------------------------------------*/

Atienganh.blogspot.com

109

No book no knowledge

.
#define PRELOAD01
(65536 - (tWord)(OSC_FREQ / (OSC_PER_INST * 1020)))
#define PRELOAD01H (PRELOAD01 / 256)
#define PRELOAD01L (PRELOAD01 % 256)
/*-------------------------------------------------------------*/
void DELAY_T0_Wait(const tWord N)
{
tWord ms;
/* cu hnh Timer 0 nh mt 16-bit timer
*/
TMOD &= 0xF0; /* xoa bit T0 (T1 left unchanged) */
TMOD |= 0x01; /* cai dat bit yeu cau T0 (T1 left unchanged)
ET0 = 0;

*/

/* cam ngat */

/* tre 1 ms moi vong lap


for (ms = 0; ms < N; ms++)
{
TH0 = PRELOAD01H;
TL0 = PRELOAD01L;
TF0 = 0;
TR0 = 1;

*/

/* xoa co tran */
/* bat dau timer 0 */

while (TF0 == 0); /* cho den khi timer 0 tran (TF0 == 1) */


TR0 = 0;
}

/* ngung Timer 0 */

Atienganh.blogspot.com

110

No book no knowledge

Atienganh.blogspot.com

111

No book no knowledge

S cn thit cho c ch timeout (thi gian tr) - V d


Philips 8Xc552 l mt thit b m rng 8051 vi mt s thit b ngoi vi on-chip trong
bao gm c ADC 8-knh 10-bi. Philips cung cp mt chng trnh ng dng (AN93017)
m t lm th no s dng tnh nng ny ca vk.
Chng trnh ny bao gm on m sau:
/* ch cho n khi ADC chuyn i xong (checking ADCI) */
while ((ADCON & ADCI) == 0);
M code nh vy c th khng ng tin cy, bi v c mt s trng hp m ng dng c
th b treo. iu ny xy ra v mt trong nhng l do sau :
Nu ADC khi to khng chnh xc, chng ta khng th chc chn rng mt
chuyn i c th c thc hin.
Nu ADC phi chu mt in p u vo qu nhiu, sau c th n s khng hot
ng.
Nu bin ADCON or ADCI khng khi to ng, Chng c th khng
hot ng theo yu cu.

V d ca Philips khng c nh sn xut code. Tht khng may, tuy nhin code ny
ph bin trong nhiu chng trnh nhng.

Hai gii php gii quyt vn : Loop timeouts v hardware timeouts.


(ngng tr dng vng lp v ngng tr phn cng)

Atienganh.blogspot.com

112

No book no knowledge

To loop timeouts
C s ca loop timeout:
tWord Timeout_loop = 0;

while (++Timeout_loop);

Original ADC code:


/* Doi cho den khi chuyen doi ket thuc (checking ADCI) */
while ((ADCON & ADCI) == 0);
Modified version, with a loop timeout:
tWord Timeout_loop = 0;
/* doi cho den khi chuyen doi ket thuc
(checking ADCI) vong thoi giant tre don gian */
while (((ADCON & ADCI) == 0) && (++Timeout_loop != 0));

Note that this alternative implementation is also useful:


while (((ADCON & ADCI) == 0) && (Timeout_loop != 0))
{
Timeout_loop++;
/* ngat su dung phan cung ao */
}

Atienganh.blogspot.com

113

No book no knowledge

/*-------------------------------------------------------------*TimeoutL.H (v1.00)

Thoi giant tre don gian voi cac thanh vien ho 8051
* nhung gia tri nay khong chinh xac ban phai lap vao he thong cua ban*
-*-------------------------------------------------------------*/
#ifndef _TIMEOUTL_H
#define _TIMEOUTL_H
/* ------ Public constants ------------------------------------ */
/* bien nay thay doi thoi gian lap
Gia tri nay co cac khoang thoi giant re tren 8051, 12 MHz, 12 Osc
/ cycle
*** phai chinh xac dung voi chuong trinh cua ban ***
*** thoi gian khac nhau voi cac thiet lap toi uu hoa trinh
bien dich *** */
/* tWord */
#define LOOP_TIMEOUT_INIT_001ms 65435
#define LOOP_TIMEOUT_INIT_010ms 64535
#define LOOP_TIMEOUT_INIT_500ms 14535
/* tLong */
#define LOOP_TIMEOUT_INIT_10000ms 4294795000UL
#endif
/*-------------------------------------------------------------*---- END OF FILE ---------------------------------------*-------------------------------------------------------------*/

Atienganh.blogspot.com

114

No book no knowledge

V d: kim tra loop timeouts


/*-------------------------------------------------------------*Main.C (v1.00)
-*-------------------------------------------------------------*/
#include <reg52.H>
#include "TimeoutL.H"
/* dinh nghia kieu bien (xem Chap 5) */
typedef unsigned char tByte;
typedef unsigned int tWord;
typedef unsigned long tLong;
/* khai bao ham */
void Test_Timeout(void);
/*-------------------------------------------------------------*/
void main(void)
{
while(1)
{
Test_Timeout();
}
}
/*-------------------------------------------------------------*/
void Test_Timeout(void)
{
tLong Timeout_loop = LOOP_TIMEOUT_INIT_10000ms;
/* ngung tre vong lap don gian... */
while (++Timeout_loop != 0);
}

Atienganh.blogspot.com

115

No book no knowledge

V d: nt bm tin cy hn
bit SWITCH_Get_Input(const tByte DEBOUNCE_PERIOD)
{
tByte Return_value = SWITCH_NOT_PRESSED;
tLong Timeout_loop = LOOP_TIMEOUT_INIT_10000ms;
if (Switch_pin == 0)
{
/* nut bam duoc nhan */
/* chong rung - chi can doi... */
DELAY_T0_Wait(DEBOUNCE_PERIOD);
/* khiem tra nut bam lan nua */
if (Switch_pin == 0)
{
/* doi cho den khi nut bam nay len
(voi vong lap thoi gian tre - 10 s) */
while ((Switch_pin == 0) && (++Timeout_loop != 0));
/* kiem tra vong lap thoi gian tre */
if (Timeout_loop == 0)
{
Return_value = SWITCH_NOT_PRESSED;
}
else
{
Return_value = SWITCH_PRESSED;
}
}
}
/* bay gio quay tro ve gia tri nut bam */
return Return_value;
}

Atienganh.blogspot.com

116

No book no knowledge

To hardware timeouts
/* cau hinh Timer 0 nhu mot 16-bit timer
*/
TMOD &= 0xF0; /* xoa bit T0 (T1 trai khong doi) */
TMOD |= 0x01; /* cai dat bit yeu cau T0 (T1 trai khong doi
ET0 = 0;

*/

/* cam ngat */

/* thoi giant tre don gian khoang 10ms */


TH0 = PRELOAD_10ms_H; /* Xem Timeout.H for PRELOAD de biet them */
TL0 = PRELOAD_10ms_L;
TF0 = 0; /* xoa co tran */
TR0 = 1; /* bat dau timer */
while (((ADCON & ADCI) == 0) && !TF0);

Atienganh.blogspot.com

117

No book no knowledge

/*-------------------------------------------------------------*TimeoutH.H (v1.00)
-*-------------------------------------------------------------*/
#ifndef _TIMEOUTH_H
#define _TIMEOUTH_H
/* ------ hang so chung ------------------------------------ */
/* gia tri Timer T_ su dung don giant hoi gian tre (phan cung ) */
- Timers 16-bit, che do nap lai binh thuong('one shot'). */
Luu y: Cac che do dinh thoi phai kiem tra bang tay cho hinh xac . */
/* dinh nghia ban dau Timer 0 / Timer 1 gia tri de tre 50us */
#define T_50micros (65536 - (tWord)((OSC_FREQ /
26000)/(OSC_PER_INST)))
#define T_50micros_H (T_50micros / 256)
#define T_50micros_L (T_50micros % 256)

/* dinh nghia ban dau Timer 0 / Timer 1 gia tri tre ~10 ms*/
#define T_10ms
(65536 - (tWord)(OSC_FREQ / (OSC_PER_INST * 100)))
#define T_10ms_H (T_10ms / 256)
#define T_10ms_L
(T_10ms % 256)
/* dinh nghia ban dau Timer 0 / Timer 1 gia tri tre ~15 ms */
#define T_15ms
(65536 - (tWord)(OSC_FREQ / (OSC_PER_INST * 67)))
#define T_15ms_H (T_15ms / 256)
#define T_15ms_L
(T_15ms % 256)
/* dinh nghia ban dau Timer 0 / Timer 1 gia tri tre ~20 ms */
#define T_20ms
(65536 - (tWord)(OSC_FREQ / (OSC_PER_INST * 50)))
#define T_20ms_H (T_20ms / 256)
#define T_20ms_L
(T_20ms % 256)
/* dinh nghia ban dau Timer 0 / Timer 1 gia tri tre ~50 ms */
#define T_50ms
(65536 - (tWord)(OSC_FREQ / (OSC_PER_INST * 20)))
#define T_50ms_H (T_50ms / 256)
#define T_50ms_L (T_50ms % 256)
#endif

Atienganh.blogspot.com

118

No book no knowledge

Kt lun
Vic tr v thi gian ch xem xt trong chng ny s dng rt rng ri trong cc chng
trnh nhng.
Trong chng tip theo chng ta xem xt phn mm khc cu thnh nhiu chng trnh nhng: h
iu hnh..

Atienganh.blogspot.com

119

No book no knowledge

Chun b cho chng tip theo

Vui lng xem trc chng 6

Atienganh.blogspot.com

120

No book no knowledge

Chng 6: To ra mt h iu hnh nhng


Xc nh tc dng chy da vo dng xung

H thng tit trng sa

Atienganh.blogspot.com

121

No book no knowledge

Li gii thiu
void main(void)
{
/* chun b chy hm X */
X_Init();
while(1) /* 'mi mi' (Vng lp v tn) */
{
X(); /* chy hm X */
}
}
Mt gii hn ring ca kiu kin trc ny l rt kh thi hnh hm X() nhng khong thi
gian chnh xc: nh chng ta s thy , l mt mt hn ch ng k.

Atienganh.blogspot.com

122

No book no knowledge

Ch n mt lot cc yu cu c thu thp t mt dy cc d n nhng(trong kiu kin trc


khng c bit):
Tc hin ti ca vt chuyn ng phi c o nhng khong thi gian 0.5s.
Kt qu hin th phi c lp li 40 ln trong 1 giy.
Cc ci t mi phi c p dng trong mi khong thi gian 0.5 giy
S thay i v tn s thi gian phi c p dng 20 ln mi giy.
D liu dao ng phi c ly mu 1000 ln trong mt giy.
D liu min tn s phi c phn loi 20 ln mi giy.
Bn phm phi c qut trong mi 200ms.
Cc nt iu khin chnh phi kt ni vi tt c cc nt khc mt ln trn mt giy.
Cc ci t iu chnh mi phi c tnh ton mi 0.5 giy.
Cc cm bin phi c ly mu mt ln trong mt giy.

Trn thc t , rt nhiu h thng nhng s phi chp nhn kiu hm chu k ny.

Atienganh.blogspot.com

123

No book no knowledge

void main(void)
{
Init_System();
while(1) /* 'mi mi' (Vng lp v tn) */
{
X();
/* Gi hm ny (Tn ti 10 ms) */
Delay50ms(); /* Tr 50 ms */
}
}
iu ny s tt nu:
1. Nu chng ta bit chnh xc thi gian tn ti ca hm X()v
2. Khong thi gian ny khng bao gi bin thin.

Atienganh.blogspot.com

124

No book no knowledge

Cc ngt Timer c bn (Li ca mt h iu hnh nhng)


#define INTERRUPT_Timer_2_Overflow 5
...
void main(void)
{
Timer_2_Init();

/* Ci t Timer 2 */

EA = 1;

/* Cho php ton b cc ngt hot ng */

while(1);
}

/* vng lp v tn rng */

void Timer_2_Init(void)
{
/* Timer 2 l mt Timer 16 bit , c th t ng np li khi b trn gi tr
Code ny (Ph hp vi 8051/52) gi s h thng dao ng vi tn s 12Mhz.Nh vy
Timer 2 c phn gii l 1.000 s
Np li gi tr FC18 (hex) = 64536 (Thp phn)
Timer (16-bit) s trn khi ti gi tr 65536 (Thp phn)
V vy,vi nhng ci t sau, timer s trn sau mi khong thi gian 1 ms */
T2CON = 0x04;
/* Np gi tr thanh ghi T2CON */
TH2
=
RCAP2H =
TL2
=
RCAP2L =

0xFC;
0xFC;
0x18;
0x18;

/*
/*
/*
/*

Load
Load
Load
Load

T2
T2
T2
T2

high */
reload capt. reg. high byte */
low byte */
reload capt. reg. low byte */

/* Ngt timer 2 c cho php, v ISR s c gi n bt c khi no Timer ny trn


xem bn di. */
ET2 = 1;
/* Bt u chy Timer 2 */
TR2 = 1;
}
void X(void) interrupt INTERRUPT_Timer_2_Overflow
{
/* ISR ny s c gi sau mi khong thi gian 1ms */
/* t nhng code cn thit y */
}

Atienganh.blogspot.com

125

No book no knowledge

Chng trnh con phc ngt (ISR)


Ngt c to ra bi vic ngt ca Timer 2 , gi ISR nh sau:
/* --------------------------------------------------------------- */
void X(void) interrupt INTERRUPT_Timer_2_Overflow
{
/* ISR ny s c gi sau mi khong thi gian 1ms */
/* t nhng code cn thit y */
}
Mi lin lc gia hm ny v s trn ca Timer c to ra bng cch s dng t kha Keil
interrupt:
void X(void) interrupt INTERRUPT_Timer_2_Overflow
cng vi #define sau ch dn:
#define INTERRUPT_Timer_2_Overflow 5

a ch
0x00

Ngt
Reset h thng

S hiu IE
-

Ngt ngoi 0

0x03

Trn Timer 0

0x0B

Ngt ngoi 1

0x13

Trn Timer 1

0x1B

Port ni tip

0x23

Trn Timer 2

0x2B

Atienganh.blogspot.com

126

No book no knowledge

Timer t ng np li
/* Np trc cc gi tr tr 50ms */
TH0 = 0x3C;
/* Timer 0: Gi tr khi to ( Byte cao) */
TL0 = 0xB0;
/* Timer 0: Gi tr khi to (Byte thp) */
TF0 = 0;
TR0 = 1;

/* Xa c trn */
/* Bt u timer 0 */

while (TF0 == 0); /* Lp n khi Timer o trn (TF0 == 1) */


TR0 = 0;

/* dng Timer 0 */

i vi h iu hnh, chng ta c thm cc yu cu nh sau:


chng ta yu cu mt chui cc ngt nhng khong thi gian chnh xc nh trc.
Chng ta mun to ra cc ngt ny m khng without to ra cc ti ng k trn CPU.

Timer 2 ph hp vi nhng yu cu chnh xc.


Trong trng hp ny, timer 2c np li bng vic s dng ni dung ca thanh ghi thu
thp(ch rng tn ca cc thanh ghi ny c mt cht thay i nh ty vo hng sn xut):
RCAP2H = 0xFC;
RCAP2L = 0x18;

/* Np vo gi tr np li byte cao */
/* Np vo gi tr np li byte thp*/

Kh nng t ng np li m bo rng timer ny s gi nguyn cc gi tr yu cu nhng


khong thi gian chnh xc 1ms,vi rt t phn mm c to m khng c bt k s can thip
no t pha ngi dng.

Atienganh.blogspot.com

127

No book no knowledge

Gii thiu v sEOS

void main(void)
{
Init_System();
while(1) /* Vng lp v tn */
{
X();
/* Gi hm ny (Duy tr trong 10ms) */
Delay_50ms(); /*Tr 50 ms */
}
}

Trong trng hp ny:


Chng ta s dng mt vng lp v tn v hm tr
Chng ta gi hm X() sau mi khong thi gian xp x 60ms

Chng ta s cng xem mt cch lm tt hn cch ny

Atienganh.blogspot.com

128

No book no knowledge

Gii thiu v sEOS


Xem cun Embedded C, Chng 7
/*--------------------------------------------------------*Main.c (v1.00)
--------------------------------------------------Minh ha cho sEOS chy mt tc v gi .
-*--------------------------------------------------------*/
#include "Main.H"
#include "Port.H"
#include "Simple_EOS.H"
#include "X.H"
/* ----------------------------------------------------- */
void main(void)
{
/* Chun b cho mt tc v gi */
X_Init();
/* Ci t EOS n gin (khong thi gian tick 60 ms) */
sEOS_Init_Timer2(60);
while(1) /* Vng lp v tn */
{
/* a ra ch ngh tit kim nng lng */
sEOS_Go_To_Sleep();
}
}
/*--------------------------------------------------------*---- KT THC FILE ----------------------------------*--------------------------------------------------------*/

Atienganh.blogspot.com

129

No book no knowledge

/*--------------------------------------------------------*Simple_EOS.C (v1.00)
--------------------------------------------------File chnh cho h iu hnh n gin (Simple Embedded Operating System: sEOS).
Phin bn chng thc vi tc v gi X().
-*--------------------------------------------------------*/
#include "Main.H"
#include "Simple_EOS.H"
/* Header cho tc v gi
#include "X.H"

*/

/*--------------------------------------------------------*sEOS_ISR()
Gi ra mt cch nh k bi vic trn Timer 2:
Xem hm sEOS_Init_Timer2() cho cc nh thi chi tit.
-*--------------------------------------------------------*/
sEOS_ISR() interrupt INTERRUPT_Timer_2_Overflow
{
/* Phi t reset c T2 */
TF2 = 0;
/*===== M ngi dng Bt u ============================= */
/* Gi tc v gi y */
X();
/*===== M ngi dng Ht =============================== */
}

Atienganh.blogspot.com

130

No book no knowledge

/*--------------------------------------------------------*sEOS_Init_Timer2()
-*--------------------------------------------------------*/
void sEOS_Init_Timer2(const tByte TICK_MS)
{
tLong Inc;
tWord Reload_16;
tByte Reload_08H, Reload_08L;
/* Timer 2 l mt Timer 16 bit, t ng np li khi b trn */
T2CON = 0x04;
/* Np gi tr thanh ghi T2CON */
/* Lng gia tng timer yu cu (Ln nht 65536) */
Inc = ((tLong)TICK_MS * (OSC_FREQ/1000)) /
(tLong)OSC_PER_INST;
/* 16-bit np li gi tr */
Reload_16 = (tWord) (65536UL - Inc);
/* 8-bit np li gi tr (cao & thp) */
Reload_08H = (tByte)(Reload_16 / 256);
Reload_08L = (tByte)(Reload_16 % 256);
/* c s dng kim tra s nh thi (trong m hnh) */
/*P2 = Reload_08H; */
/*P3 = Reload_08L; */
TH2
=
RCAP2H =
TL2
=
RCAP2L =

Reload_08H;
Reload_08H;
Reload_08L;
Reload_08L;

/*
/*
/*
/*

Np
Np
Np
Np

T2
T2
T2
T2

Byte cao */
Gi tr np li(cao) */
byte thap */
gi tr np li(thp) */

/* ngt Timer 2 c cho php, v ISR s b gi bt c khi no timer trn. */


ET2 = 1;
/* bt u chy timer 2 */
TR2 = 1;
EA = 1;
}

/* cho php ngt ton b */

Atienganh.blogspot.com

131

No book no knowledge

/*--------------------------------------------------------*sEOS_Go_To_Sleep()
h iu hnh ny a vo ch nghgia cc xung nhp tit kim nng lng. xung
nhp tip theo s tr li ch bnh thng cho b x l
-*--------------------------------------------------------*/
void sEOS_Go_To_Sleep(void)
{
PCON |= 0x01;
/* ch ngh (h 8051) */
}
/*--------------------------------------------------------*---- KT THC FILE ----------------------------------*--------------------------------------------------------*/

Atienganh.blogspot.com

132

No book no knowledge

/*--------------------------------------------------------*X.C (v1.00)
--------------------------------------------------Tc v gi gii thiu v sEOS.
-*--------------------------------------------------------*/
#include "X.H"
/*--------------------------------------------------------*X_Init()
Hm bt u.
-*--------------------------------------------------------*/
void X_Init(void)
{
/* tc v gi bt u... */
}
/*--------------------------------------------------------*X()
Tc v gi c gi t vic ngt.
-*--------------------------------------------------------*/
void X(void)
{
/* tc v gi... */
}
/*--------------------------------------------------------*---- KT THC FILE ----------------------------------*--------------------------------------------------------*/

Atienganh.blogspot.com

133

No book no knowledge

Tc v, hm v lp trnh
Khi cp n cc h thng nhng, bn s thng xuyn nghe thy cm tthit k nhim
v, nhim v chu k v
h x l a nhim.

Trong trng hp ny, thut ng tc v lun c s dng ch mt hm m hm c


thc thi trong mt chu k chun.

Trong trng hp ca sEOS, cc tc v s c thc thi bng cch s dng cc hm c gi


t dch v ngt ca timer.

Atienganh.blogspot.com

134

No book no knowledge

Ci t khong thi gian tick


Trong hm main(), chng ta c th thy rng khong thi gian tick ca h thng c t ng
ha mc ln:
/* Ci t EOS n gin (khong thi gian tick 60 ms) */
sEOS_Init_Timer2(60);
Trong v d ny, mt khong thi gian 60ms c s dng: iu ny c ngha l ISR (hm cp
nht) li ca sEOS s c gi ra sau mi 60ms:
/*--------------------------------------------------------*sEOS_ISR()
Gi ra nh k khi Timer 2 trn:
Xem hm sEOS_Init_Timer2() cho nh thi chi tit.
-*--------------------------------------------------------*/
sEOS_ISR() interrupt INTERRUPT_Timer_2_Overflow
{

Atienganh.blogspot.com

135

No book no knowledge

T ng iu khin thi gian t c bng cch b tin x l C, v cc thng tin bao gm


header file
(Main.H):
/* Xung nhp / tn s cng hng (Hz) v d 11059200 */
#define OSC_FREQ (12000000UL)
/* S lng dao ng trn mt chng trnh (12, v.v) */
...
#define OSC_PER_INST (12)
Thng tin ny c s dng tip theo tnh ton Timer yu cu c
np li gi tr trong Simple_EOS.C nh sau:
/* lng gia tng Timer yu cu (ln nht l 65536) */
Inc = ((tLong)TICK_MS * (OSC_FREQ/1000)) / (tLong)OSC_PER_INST;
/* 16-bit np li gi tr */
Reload_16 = (tWord) (65536UL - Inc);
/* 8-bit np li gi tr (cao & thp) */
Reload_08H = (tByte)(Reload_16 / 256);
Reload_08L = (tByte)(Reload_16 % 256);

TH2
=
RCAP2H =
TL2
=
RCAP2L =

Reload_08H;
Reload_08H;
Reload_08L;
Reload_08L;

Atienganh.blogspot.com

/*
/*
/*
/*

Np
Np
Np
Np

T2 Byte cao */
T2 (gi tr cn np li(byte cao)) */
T2 Byte thp */
T2 (gi tr cn np li(byte thp)) */

136

No book no knowledge

Nu s dng b dao ng 12MHz, th c th nh thi chnh xc trong khong xp x t 1 ms


n 60 ms .
Nu s dng nhng tn s khc (v d 11.0592 MHz), th nh thi
chnh xc ch thu c trong mt s khong gii hn.
Nu bn pht trin mt ng dng yu cu nh thi chnh xc, bn phi t kim tra kt qu
nh thi.
/* s dng kim tra s nh thi mt cch khng t ng (trong m phng) */
P2 = Reload_08H;
P3 = Reload_08L;

Atienganh.blogspot.com

137

No book no knowledge

Tit kim nng lng


S dng sEOS, chng ta c th gim bt lng tiu th ca ng dng bng cch s dng ch
ng khi b x l thc thi xong ngt IRS.
iu ny t c bng cch s dng hm sEOS_Go_To_Sleep():
/*--------------------------------------------------------*sEOS_Go_To_Sleep()
H iu hnh ny a vo 'ch ngh' gia cc xung nhp tit kim nng lng.xung
nhp tip theo s tr li ch bnh thng cho h thng.
-*--------------------------------------------------------*/
void sEOS_Go_To_Sleep(void)
{
PCON |= 0x01;
/* nhp vo ch ngh (h 8051) */
}
Ch rng b x l s t ng tr li ch bnh thng khi Timer tip theo ngt (sinh ra mt
ngt).

Linh kin
Atmel 89S53

Atienganh.blogspot.com

Bnh
thng
11 mA

138

Ngh
2 mA

Power Down
60 A

No book no knowledge

S dng sEOS trong d n ca chnh bn


Khi s dng sEOS trong cc ng dng ca chnh bn, bn s cn n c bn sao ca cc file
Simple_EOS.C v Simple_EOS.H trong d n ca bn: file .C s cn c chnh sa cho ph
hp vi yu cu ca bn trong phn minh ha di y:
sEOS_ISR() interrupt INTERRUPT_Timer_2_Overflow
{
/* phi t reset c nh T2 */
TF2 = 0;
/*===== USER CODE - Begin ============================= */
/* thm hm ca bn (TASK) y... */
/*===== USER CODE - End =============================== */
}

Atienganh.blogspot.com

139

No book no knowledge

Phng php ny c linh hot khng?


S c mt ca mt Timer trn chip, c s dng to ra ngt bng cch ny khng c
ngha l ch gii hn cho h 8051.: hu nh tt c cc b x l dng cho cc h thng nhng
u c cc Timer, c th c s dng theo mt kiu cch rt ging cc miu t y.

V d, cc b Timer tng t cng c trn cc vi iu khin 8-bit khc (H vi iu khin


PIC,h vi iu khin ca Motorola
HC08), v cng c trn cc thit b 16-bit khc (v d nh h Infineon
C167) v c trn cc b x l 32-bit (v d nh h ARM,h Motorola MPC500).

Atienganh.blogspot.com

140

No book no knowledge

V d: Tit trng sa

Atienganh.blogspot.com

141

No book no knowledge

/*-------------------------------------------------------------*Port.H (v1.00)
-------------------------------------------------------File tiu Port cho v d v h thng tit trng sa
(Embedded C Chng 7)
-*-------------------------------------------------------------*/
/* ------ Pulse_Count.C ---------------------------------- */
/* kt ni u vo xung vi chn ny-c hm bng phn mm */
sbit Sw_pin = P3^0;
/* kt ni bo ng vi chn ny (ci v nu xung di mc cho php) */
sbit Alarm_pin = P3^7;
/* ------ Bargraph.C -------------------------------------- */
/* Bargraph hin th ln cc chn ny (8 chn ni ny c th c phn b theo cc cch
khc nhau, nu b yu cu). */
sbit Pin0 = P1^0;
sbit Pin1 = P1^1;
sbit Pin2 = P1^2;
sbit Pin3 = P1^3;
sbit Pin4 = P1^4;
sbit Pin5 = P1^5;
sbit Pin6 = P1^6;
sbit Pin7 = P1^7;
/*-------------------------------------------------------------*---- END OF FILE ---------------------------------------*-------------------------------------------------------------*/

Atienganh.blogspot.com

142

No book no knowledge

/*-------------------------------------------------------------*Main.c (v1.00)
-------------------------------------------------------V d v h thng tit trng sa.
-*-------------------------------------------------------------*/
#include
#include
#include
#include

"Main.H"
"Port.H"
"Simple_EOS.H"
"Bargraph.H"

#include "Pulse_Count.H"
/* --------------------------------------------------------------- */
void main(void)
{
PULSE_COUNT_Init();
BARGRAPH_Init();
/* ci t simple EOS (khong thi gian tick 30ms) */
sEOS_Init_Timer2(30);
while(1) /* vng lp v tn */
{
/* a vo ch ngh tit kim nng lng */
sEOS_Go_To_Sleep();
}
}
/*-------------------------------------------------------------*---- END OF FILE ---------------------------------------*-------------------------------------------------------------*/

Atienganh.blogspot.com

143

No book no knowledge

/*-------------------------------------------------------------*Simple_EOS.C (v1.00)
-------------------------------------------------------File chnh cho h iu hnh nhng n gin(sEOS) s dng 8051.
-- phin bn ny kim tra tc dng chy ca sa.
-*-------------------------------------------------------------*/
#include "Main.H"
#include "Simple_EOS.H"
#include "Pulse_count.H"
/*-------------------------------------------------------------*sEOS_ISR()
c gi ra mt cch nh k bi vic trn timer 2:
Xem hm sEOS_Init_Timer2() bit chi tit nh thi.
-*-------------------------------------------------------------*/
sEOS_ISR() interrupt INTERRUPT_Timer_2_Overflow
{
/* phai tu reset c nh T2 */
TF2 = 0;
/*===== USER CODE - Begin ================================== */
/* Gi hm cp nht y */
PULSE_COUNT_Update();
/*===== USER CODE - End ==================================== */
}

Atienganh.blogspot.com

144

No book no knowledge

/*-------------------------------------------------------------*sEOS_Init_Timer2()
...
-*-------------------------------------------------------------*/
void sEOS_Init_Timer2(const tByte TICK_MS)
{
tLong Inc;
tWord Reload_16;
tByte Reload_08H, Reload_08L;
/* Timer 2 l mt Timer 16 bit,t ng np li gi tr khi b trn */
T2CON = 0x04;
/* np thanh ghi iu khin T2 */
/* ln yu cu(ln nht l 65536) */
Inc = ((tLong)TICK_MS * (OSC_FREQ/1000)) / (tLong)OSC_PER_INST;
/* gi tr 16 bit np li */
Reload_16 = (tWord) (65536UL - Inc);
/* gi tr 8 bit np li (cao & thp) */
Reload_08H = (tByte)(Reload_16 / 256);
Reload_08L = (tByte)(Reload_16 % 256);
/* c s dng t kim tra nh thi (trong m phng) */
/*P2 = Reload_08H; */
/*P3 = Reload_08L; */
TH2
=
RCAP2H =
TL2
=
RCAP2L =

Reload_08H;
Reload_08H;
Reload_08L;
Reload_08L;

/*
/*
/*
/*

Load
Load
Load
Load

T2
T2
T2
T2

high byte */
reload capt. reg. high byte */
low byte */
reload capt. reg. low byte */

/* ngt Timer 2 c cho php, ISR s b gi bt c khi no Timer trn. */


ET2 = 1;
/* bt u chy timer 2*/
TR2 = 1;
EA = 1;
}

/* cho phep toan bo cac ngat */

Atienganh.blogspot.com

145

No book no knowledge

/*-------------------------------------------------------------*sEOS_Go_To_Sleep()
h iu hnh s a vo 'ch ngh' gia cc tick ng h
tit kim nng lng. tick ng h tip theo s tr li trng thi
bnh thng cho b x l.
-*-------------------------------------------------------------*/
void sEOS_Go_To_Sleep(void)
{
PCON |= 0x01;
/* a vo ch ngh (h 8051) */
}
/*-------------------------------------------------------------*---- END OF FILE ---------------------------------------*-------------------------------------------------------------*/

Atienganh.blogspot.com

146

No book no knowledge

/*-------------------------------------------------------------*Pulse_Count.C (v1.00)
-------------------------------------------------------m xung t mt thit b ngt c kh hay thit b tng t.
___
___
-*-------------------------------------------------------------*/
#include "Main.H"
#include "Port.H"
#include "Bargraph.H"
#include "Pulse_Count.H"
/* ------ Private function prototypes ------------------------- */
void PULSE_COUNT_Check_Below_Threshold(const tByte);
/* ------ khai bo bin dng chung ------------------------ */
/* d liu c hin th */
extern tBargraph Data_G;
/* ------ nh ngha bin dng chung -------------------------- */
/* ch set sau khi sn xung c pht hin */
bit Falling_edge_G;
/* ------ nh ngha bin ring ------------------------- */
/* lin tc kim tra tn hiu xung */
/* (ch : khng th c mt dy cc bit...) */
static bit Test4, Test3, Test2, Test1, Test0;
static tByte Total_G = 0;
static tWord Calls_G = 0;
/* ------ hng s ring ----------------------------------- */
/* cho php thay i mc logic m phn cng khng thay i */
#define HI_LEVEL (0)
#define LO_LEVEL (1)

Atienganh.blogspot.com

147

No book no knowledge

/*-------------------------------------------------------------*PULSE_COUNT_Init()
Hm khi ng cho th vin thit b ngt.
-*-------------------------------------------------------------*/
void PULSE_COUNT_Init(void)
{
Sw_pin = 1; /* s dng chn ny cho u vo */
/* cc du hiu */
Test4 = LO_LEVEL;
Test3 = LO_LEVEL;
Test2 = LO_LEVEL;
Test1 = LO_LEVEL;
Test0 = LO_LEVEL;
}
/*-------------------------------------------------------------*PULSE_COUNT_Check_Below_Threshold()
Kim tra xem b m xung c thp hn gi tr ngng khng.
Nu ng, h thng bo ng s ku.
-*-------------------------------------------------------------*/
void PULSE_COUNT_Check_Below_Threshold(const tByte THRESHOLD)
{
if (Data_G < THRESHOLD)
{
Alarm_pin = 0;
}
else
{
Alarm_pin = 1;
}
}

Atienganh.blogspot.com

148

No book no knowledge

/*-------------------------------------------------------------*PULSE_COUNT_Update()
y l hm ngt chnh.
N ln c gi sau mi 30ms
( cho php thi gian hm c trng l 20ms).
-*-------------------------------------------------------------*/
void PULSE_COUNT_Update(void)
{
/* xa c timer */
TF2 = 0;
/* trn cc kt qu kim nh */
Test4 = Test3;
Test3 = Test2;
Test2 = Test1;
Test1 = Test0;
/* thu thp cc kt qu mi nht */
Test0 = Sw_pin;
/* kt qu
Test4 ==
Test3 ==
Test1 ==
Test0 ==

yu cu:
HI_LEVEL
HI_LEVEL
LO_LEVEL
LO_LEVEL */

if ((Test4 == HI_LEVEL) &&


(Test3 == HI_LEVEL) &&
(Test1 == LO_LEVEL) &&
(Test0 == LO_LEVEL))
{
/* sn xung c pht hin */
Falling_edge_G = 1;
}
else
{
/* mc nh */
Falling_edge_G = 0;
}

Atienganh.blogspot.com

149

No book no knowledge

/* tnh trung bnh 45 ln gi tc v


- s m ln nht trn mt chu k ny l 9 xung
if (++Calls_G < 45) */
/* 450 c s dng y mang mc ch kim tra (trong m phng)
[Bi v c mt gii hntc nn bn c th m phng bng tay
...] */
if (++Calls_G < 450)
{
Total_G += (int) Falling_edge_G;
}
else
{
/* cp nht hin th */
Data_G = Total_G; /* ln nht l 9 */
Total_G = 0;
Calls_G = 0;
PULSE_COUNT_Check_Below_Threshold(3);
BARGRAPH_Update();
}
}
/*-------------------------------------------------------------*---- END OF FILE ---------------------------------------*-------------------------------------------------------------*/

Atienganh.blogspot.com

150

No book no knowledge

/*-------------------------------------------------------------*Bargraph.h (v1.00)
-------------------------------------------------------- xem Bargraph.c bit thm chi tit.
-*-------------------------------------------------------------*/
#include "Main.h"
/* ------ khai bo kiu d liu chung ----------------------- */
typedef tByte tBargraph;
/* ------ khai bo hm nguyn mu -------------------------- */
void BARGRAPH_Init(void);
void BARGRAPH_Update(void);
/* ------ khai bo hng s ------------------------------------ */
#define BARGRAPH_MAX (9)
#define BARGRAPH_MIN (0)
/*-------------------------------------------------------------*---- END OF FILE ---------------------------------------*-------------------------------------------------------------*/

Atienganh.blogspot.com

151

No book no knowledge

/*-------------------------------------------------------------*Bargraph.c (v1.00)
-------------------------------------------------------Th vin bargraph n gin.
-*-------------------------------------------------------------*/
#include "Main.h"
#include "Port.h"
#include "Bargraph.h"
/* ------ khai bo bin chung ------------------------ */
/* d liu c hin th */
tBargraph Data_G;
/* ------ cc hng ring ----------------------------------- */
#define BARGRAPH_ON (1)
#define BARGRAPH_OFF (0)
/* ------ cc bin ring ----------------------------------- */
/* cc bin lu tr ngng ny c s dng cp nht hin th */
static tBargraph M9_1_G;
static tBargraph M9_2_G;
static tBargraph M9_3_G;
static tBargraph M9_4_G;
static tBargraph M9_5_G;
static tBargraph M9_6_G;
static tBargraph M9_7_G;
static tBargraph M9_8_G;

Atienganh.blogspot.com

152

No book no knowledge

*-------------------------------------------------------------*BARGRAPH_Init()
Chun b cho hin th bargraph.
-*-------------------------------------------------------------*/
void BARGRAPH_Init(void)
{
Pin0 = BARGRAPH_OFF;
Pin1 = BARGRAPH_OFF;
Pin2 = BARGRAPH_OFF;
Pin3 = BARGRAPH_OFF;
Pin4 = BARGRAPH_OFF;
Pin5 = BARGRAPH_OFF;
Pin6 = BARGRAPH_OFF;
Pin7 = BARGRAPH_OFF;
/* s dng mt t l tuyn tnh hin th d liu
Nh rng: *9* trng thi u ra c th thc hin
- lm tt c cc php ton mt ln */
M9_1_G = (BARGRAPH_MAX - BARGRAPH_MIN) / 9;
M9_2_G = M9_1_G * 2;
M9_3_G = M9_1_G * 3;
M9_4_G = M9_1_G * 4;
M9_5_G = M9_1_G * 5;
M9_6_G = M9_1_G * 6;
M9_7_G = M9_1_G * 7;
M9_8_G = M9_1_G * 8;
}

Atienganh.blogspot.com

153

No book no knowledge

/*-------------------------------------------------------------*BARGRAPH_Update()
Cp nht hin th bargraph.
-*-------------------------------------------------------------*/
void BARGRAPH_Update(void)
{
tBargraph Data = Data_G - BARGRAPH_MIN;
Pin0
Pin1
Pin2
Pin3
Pin4
Pin5
Pin6
Pin7
}

=
=
=
=
=
=
=
=

((Data
((Data
((Data
((Data
((Data
((Data
((Data
((Data

>=
>=
>=
>=
>=
>=
>=
>=

M9_1_G)
M9_2_G)
M9_3_G)
M9_4_G)
M9_5_G)
M9_6_G)
M9_7_G)
M9_8_G)

==
==
==
==
==
==
==
==

BARGRAPH_ON);
BARGRAPH_ON);
BARGRAPH_ON);
BARGRAPH_ON);
BARGRAPH_ON);
BARGRAPH_ON);
BARGRAPH_ON);
BARGRAPH_ON);

/*-------------------------------------------------------------*---- END OF FILE ---------------------------------------*-------------------------------------------------------------*/

Atienganh.blogspot.com

154

No book no knowledge

Kt lun
H iu hnh n gin (sEOS) c gii thiu trong chuyn ny p t mt ti x l rt
nh, nhng d sao cng rt mm do v hu ch.

Bn cht n gin ca sEOS cng cung cp cc li ch khc.iu c ngha l ngi pht


trin c th t mnh nhanh chng cho mt h iu hnh trn mt con vi iu khin.
iu ny cng c ngha rng ngi k s c th nhanh chng thch nghi cc yu cu ca ca
cc ng dng c bit.

C l tc dng khng mong mun nht ca kiu h iu hnh n gin l


khng ging vi mt h iu hnh thi gian thc truyn thng t n tr
thnh mt phn ca h thng, hn l to ra mt on m ring bit.

Atienganh.blogspot.com

155

No book no knowledge

Chun b cho chuyn tip theo

Xin c Chng 8
Trc khi bt u chuyn ny

Atienganh.blogspot.com

156

No book no knowledge

Chng 7: H thng a trng thi v dy hm

Ng

Thc dy

Lm vic

Gm g

Atienganh.blogspot.com

157

No book no knowledge

Li gii thiu
C hai loi h thng a trng thi:
a trng thi (c nh thi)
Trong h thng ny, s chuyn tip gia cc trng thi ch ph thuc vo hnh trnh ca thi
gian.
V d nh, h thng s b u trng thi A,thc thi nhiu ln hm FunctionA(), trong 10s.
Sau chuyn sang trng thi B, thc thi hm FunctionB() trong 5s.Sau chuyn n trng
thi A va kt thc qu trnh.
Mt h thng iu khin n giao thng l mt v d nh vy.
a trng thi (nhn tn hiu vo & nh thi)
l mt kiu h thng kh ph bin, s chuyn trng thi (v ch ca tng trng
thi)ca h thng s c qut nh bi c thi gian v cc u vo ca h thng.
V d, h thng ch chuyn t trng thi A sang trng thi B nu mt u vo no nhn
c mt tn hiu trong khong thi gian X giy.
H thng t ng li tho lun u chuyn c th minh ha cho vn ny, cng c th
v d nh h thng iu khin cho mt my git, hay mt h thng cnh bo ngi l xm
nhp.

Atienganh.blogspot.com

158

No book no knowledge

trn vn, chng ta s tip tc cp thm cc kh nng:


a trng thi (c u vo)
l mt kiu h thng tng i him gp, y s chuyn trng thi (v ch ca tng
trng thi) ch c quyt nh bi cc u vo ca h thng.
V d,h thng ch chuyn t trng thi A sang trng thi B nu c tn hiu u vo.n s vn
trng thi A nu cha c tn hiu vo.
Mt h thng nh th khng c khi nim v thi gian, v v th khng c cch no tm
ngng hoc tng t nh th. Chng ta s khng cp n cc h thng nh th trong kha
hc ny.

Trong chuyn ny, chng ta s tnh ton xem lm cch no cc kiu kin trc a trng thi
(Thi gian)v cc kiu kin trc a trng thi (u vo / Thi gian) c th thi hnh trong C.

Atienganh.blogspot.com

159

No book no knowledge

Thi hnh mt h thng a trng thi (nh thi gian)


Chng ta c th miu cc kiu kin trc a trng thi,iu khin thi gian nh sau:
H thng s hot ng hai (hoc hn 2 trng thi).
Mi trng thi c th km theo mt hay nhiu hn li gi hm.
S chuyn giao gia cc trng thi s c iu khin bng hnh trnh thi gian.
S chuyn giao gia cc trng thi cng c th gm nhiu li gi hm.

Ch rng, theo th t gim dn nhim v duy tr xy ra tip theo, trng thi h thng khng
nn c tn ty , nhng nn ni c th phn nh trng thi ca mt vt cht c quan st bi
ngi s dng hoc chnh nh pht trin.
Cng xin ch rng trng thi h thng s thng xuyn c biu hin bi cu lnh switch
trong h iu hnh ISR.

Atienganh.blogspot.com

160

No book no knowledge

V d: dy n giao thng

Thi gian

vng
xanh

Ch :
Kiu iu khin ny thuc chu u!

Atienganh.blogspot.com

161

No book no knowledge

Trong trng hp ny, cc trng thi khc nhau rt d dng nhn ra:

-vng
xanh
vng

Trong m ny, chng ta s biu din cc trng thi nh sau:


/* cc trng thi c th c ca h thng */
typedef enum {RED, RED_AND_AMBER, GREEN, AMBER} eLight_State;
chng ta s lu tr cc khong thi gian trong mi trng thi nh sau:
/* (tnh theo giy) */
#define RED_DURATION 20
#define RED_AND_AMBER_DURATION 5
#define GREEN_DURATION 30
#define AMBER_DURATION 5

Atienganh.blogspot.com

162

No book no knowledge

Trong trng hp n gin, chng ta khng cn cc li gi hm (hoc gia) cc trng thi ca


h thng: cc ch yu cu s c thi hnh trc tip thng qua iu khin cc chn ( cui h
thng).
V d:
case RED:
{
Red_light = ON;
Amber_light = OFF;
Green_light = OFF;
...

Atienganh.blogspot.com

163

No book no knowledge

/*-------------------------------------------------------------*Main.c (v1.00)
-------------------------------------------------------V d v n giao thng.
-*-------------------------------------------------------------*/
#include "Main.H"
#include "Port.H"
#include "Simple_EOS.H"
#include "T_Lights.H"
/* --------------------------------------------------------------- */
void main(void)
{
/* chuan bi chay day den giao thong */
TRAFFIC_LIGHTS_Init(RED);
/* ci t simple EOS (tick 50 ms) */
sEOS_Init_Timer2(50);
while(1) /* vng lp v tn */
{
/* cho vo ch ngh tit kim nng lng */
sEOS_Go_To_Sleep();
}
}
/*-------------------------------------------------------------*---- END OF FILE ---------------------------------------*-------------------------------------------------------------*/

Atienganh.blogspot.com

164

No book no knowledge

/*-------------------------------------------------------------*T_Lights.H (v1.00)
-------------------------------------------------------- xem T_Lights.C bit thm chi tit.
-*-------------------------------------------------------------*/
#ifndef _T_LIGHTS_H
#define _T_LIGHTS_H
/* ------ khai bo d liu chung ----------------------- */
/* cc trng thi c th c ca h thng */
typedef enum {RED, RED_AND_AMBER, GREEN, AMBER} eLight_State;
/* ------ cc hm nguyn mu chung -------------------------- */
void TRAFFIC_LIGHTS_Init(const eLight_State);
void TRAFFIC_LIGHTS_Update(void);
#endif
/*-------------------------------------------------------------*---- END OF FILE ---------------------------------------*-------------------------------------------------------------*/

Atienganh.blogspot.com

165

No book no knowledge

/*-------------------------------------------------------------*T_lights.C (v1.00)
-*-------------------------------------------------------------*/
#include "Main.H"
#include "Port.H"
#include "T_lights.H"
/* ------ hng s ring ----------------------------------- */
/* d dng thay i gi tr logic y */
#define ON 0
#define OFF 1
/* cc thi gian trong mi (4) trng thi sng ca h thng
(thi gian c tnh bng giy) */
#define RED_DURATION 20
#define RED_AND_AMBER_DURATION 5
#define GREEN_DURATION 30
#define AMBER_DURATION 5
/* ------ cc bin ring ----------------------------------- */
/* trng thi ca h thng */
static eLight_State Light_state_G;
/* thi gian trong cc trng thi */
static tLong Time_in_state;
/* c s dng bi sEOS */
static tByte Call_count_G = 0;
/*-------------------------------------------------------------*TRAFFIC_LIGHTS_Init()
Chun b cho cc hot ng ca n giao thng.
-*-------------------------------------------------------------*/
void TRAFFIC_LIGHTS_Init(const eLight_State START_STATE)
{
Light_state_G = START_STATE;
/* la chn trng thi u */
}

Atienganh.blogspot.com

166

No book no knowledge

/*-------------------------------------------------------------*TRAFFIC_LIGHTS_Update()
Phi c gi mt ln/mt giy.
-*-------------------------------------------------------------*/
void TRAFFIC_LIGHTS_Update(void)
{
switch (Light_state_G)
{
case RED:
{
Red_light = ON;
Amber_light = OFF;
Green_light = OFF;
if (++Time_in_state == RED_DURATION)
{
Light_state_G = RED_AND_AMBER;
Time_in_state = 0;
}
break;
}
case RED_AND_AMBER:
{
Red_light = ON;
Amber_light = ON;
Green_light = OFF;
if (++Time_in_state == RED_AND_AMBER_DURATION)
{
Light_state_G = GREEN;
Time_in_state = 0;
}
break;
}

Atienganh.blogspot.com

167

No book no knowledge

case GREEN:
{
Red_light = OFF;
Amber_light = OFF;
Green_light = ON;
if (++Time_in_state == GREEN_DURATION)
{
Light_state_G = AMBER;
Time_in_state = 0;
}
break;
}
case AMBER:
{
Red_light = OFF;
Amber_light = ON;
Green_light = OFF;
if (++Time_in_state == AMBER_DURATION)
{
Light_state_G = RED;
Time_in_state = 0;
}
break;
}
}
}
/*-------------------------------------------------------------*---- END OF FILE ---------------------------------------*-------------------------------------------------------------*/

Atienganh.blogspot.com

168

No book no knowledge

V d: khng long my

Sleeping

Attacking

Waking

Growling

Atienganh.blogspot.com

169

No book no knowledge

Cc trng thi h thng


Ng:
Khng long bt ng ,nhng hin nhin l vn th. Cc ting ngy pht ra khng u hay
nhng chuyn ng nh trong thi gian ny s thm phn th v cho khn gi.
Thc dy:
Khng long s bt u thc gic,m mt bt u h m , v bt u th mnh hn.
Gm g:
Mt t nhin m v khng long s pht ra ting gm ln. tip theo l mt s chuyn ng v
tip tc gm.
Tn cng:
Cc chuyn ng nhanh ngu nhin hng v pha khn gi, gy ra cc ting ng (you
should be able to hear this from the next floor in
the museum).

typedef enum {SLEEPING, WAKING, GROWLING, ATTACKING} eDinosaur_State;


/* thi gian ca cc trng thi c th c */
/* (thi gian tnh bng giy) */
#define SLEEPING_DURATION 255
#define WAKING_DURATION 60
#define GROWLING_DURATION 40
#define ATTACKING_DURATION 120

Atienganh.blogspot.com

170

No book no knowledge

/*-------------------------------------------------------------*Dinosaur.C (v1.00)
-------------------------------------------------------Trnh din kin trc a trng thi (Timed):
H thng iu khin khng long.
-*-------------------------------------------------------------*/
#include "Main.h"
#include "Port.h"
#include "Dinosaur.h"
/* ------ khai bo bin ring ---------------------- */
/* cc trng thi c th c ca h thng */
typedef
enum {SLEEPING, WAKING, GROWLING, ATTACKING} eDinosaur_State;
/* ------ hm nguyn mu ring ------------------------- */
void DINOSAUR_Perform_Sleep_Movements(void);
void DINOSAUR_Perform_Waking_Movements(void);
void DINOSAUR_Growl(void);
void DINOSAUR_Perform_Attack_Movements(void);
/* ------ cc hng s ring ----------------------------------- */
/* thi gian trong mi trng thi
(thi gian tnh bng giy) */
#define SLEEPING_DURATION 255
#define WAKING_DURATION 60
#define GROWLING_DURATION 40
#define ATTACKING_DURATION 120
/* ------ bin ring----------------------------------- */
/* trng thi hin ti ca h thng */
static eDinosaur_State Dinosaur_state_G;
/* thi gian trong trng thi */
static tByte Time_in_state_G;
/* c s dng bi sEOS */
static tByte Call_count_G = 0;

Atienganh.blogspot.com

171

No book no knowledge

/*-------------------------------------------------------------*DINOSAUR_Init()
-*-------------------------------------------------------------*/
void DINOSAUR_Init(void)
{
/* trng thi ban u */
Dinosaur_state_G = SLEEPING;
}
/*-------------------------------------------------------------*DINOSAUR_Update()
Phi c ghi theo lch trnh 1 ln/giy (t sEOS ISR).
-*-------------------------------------------------------------*/
void DINOSAUR_Update(void)
{
switch (Dinosaur_state_G)
{
case SLEEPING:
{
/* gi hm c lien quan */
DINOSAUR_Perform_Sleep_Movements();
if (++Time_in_state_G == SLEEPING_DURATION)
{
Dinosaur_state_G = WAKING;
Time_in_state_G = 0;
}
break;
}
case WAKING:
{
DINOSAUR_Perform_Waking_Movements();
if (++Time_in_state_G == WAKING_DURATION)
{
Dinosaur_state_G = GROWLING;
Time_in_state_G = 0;
}
break;
}

Atienganh.blogspot.com

172

No book no knowledge

case GROWLING:
{
/* gi hm c lin quan */
DINOSAUR_Growl();
if (++Time_in_state_G == GROWLING_DURATION)
{
Dinosaur_state_G = ATTACKING;
Time_in_state_G = 0;
}
break;
}
case ATTACKING:
{
/* gi hm c lin quan */
DINOSAUR_Perform_Attack_Movements();
if (++Time_in_state_G == ATTACKING_DURATION)
{
Dinosaur_state_G = SLEEPING;
Time_in_state_G = 0;
}
break;
}
}
}

Atienganh.blogspot.com

173

No book no knowledge

/*-------------------------------------------------------------*/
void DINOSAUR_Perform_Sleep_Movements(void)
{
/* chi la gioi thieu... */
P1 = (tByte) Dinosaur_state_G;
P2 = Time_in_state_G;
}
/*-------------------------------------------------------------*/
void DINOSAUR_Perform_Waking_Movements(void)
{
/* ch l gii thiu... */
P1 = (tByte) Dinosaur_state_G;
P2 = Time_in_state_G;
}
/*-------------------------------------------------------------*/
void DINOSAUR_Growl(void)
{
/* ch l gii thiu... */
P1 = (tByte) Dinosaur_state_G;
P2 = Time_in_state_G;
}
/*-------------------------------------------------------------*/
void DINOSAUR_Perform_Attack_Movements(void)
{
/* ch l gii thiu... */
P1 = (tByte) Dinosaur_state_G;
P2 = Time_in_state_G;
}
/*-------------------------------------------------------------*---- END OF FILE ---------------------------------------*-------------------------------------------------------------*/

Atienganh.blogspot.com

174

No book no knowledge

Thi hnh mt h thng a trng thi (u vo/nh thi(Input/Timer))


H thng s hot ng 2 hay nhiu trng thi.
Mi trng thi c th c mt hay nhiu hn li gi hm.
S thay i gia cc trng thi c th c iu khin bi hnh trnh thi gian, bi u vo h
thng, hoc bi c hai yu t trn.
S thay i gia cc trng thi cng c th cha nhiu li gi hm.

Atienganh.blogspot.com

175

No book no knowledge

Thi hnh trng thi ngh


Hy xem xt cc yu cu ca h thng di y(khng chnh thng):
Bm s chy trong 10 giy.Nu trong khong thi gian ny, khng c cht lng chy ra khi
b cha th bm s ng li v c ting cnh bomc nc thp.nu c cht lng, bm s
chy thm 45s na hoc s chy n khi no cm bin mc nc cao c kch hot
(whichever is first).
Sau khi ca trc c m, mt khu s c nhp vo bng iu khin trong vng 30 giy
nu khng s c ting bo ng.
Tn hiu ng kha s c pht ra, nu sau 50ms khng c s chuyn ng ca van th kt
lun l van b hng.H thng s bo ng cho ngi dng nhp vo ch bng tay.
Gp kiu yu cu ny,chng ta c th lm hai vic:
Gi li thng s thi gian trong mi trng thi;
Nu thi gian vt qu sai s cho php th chng ta s chuyn sang mt trng thi khc.

V d: b iu chnh cho mt my git

Van nc
START
B lm nng
Phm chn
Motor
Cm bin hi nc
LED
Cm bin nhit
Kha ca
Ca lm sch

Atienganh.blogspot.com

176

No book no knowledge

Di y l cc miu t ngn gn cc hot ng mong mun ca h thng:


1. Ngi dng chn mt ch git (v d len, Cotton) trn phm chn.
2. Ngi dng bm nt Start.
3. Kha ca kha.
4. Van nc m, cho php chy vo khu vc git.
5. Nu chng trnh bao gm c lm sch th m ca lm sch.khi lm sch xong, ca lm sch
c ng li.
6. Khi mc nc y c pht hin th van nc ng li.
7. Nu chng trnh git bao gm ch nc m,th b lm nng nc c bt . khi nc t
ti nhit chnh xc th tt b lm nng nc.
8. M t ca my c bt quay trng(ni git).sau motor s tri qua mt chui cc
chuyn ng,bao gm c tin v li( cc cp tc khc nhau) git qun o. (cc chuyn
ng chnh xc ca motor c qut nh bi ngi s dng chn ch nh th no) .
cui qu tnh git, motor s dng.
9. Bm c bt x nc, khi ch git(drum) chy ra ht th bm tt

Atienganh.blogspot.com

177

No book no knowledge

Kiu kin trc Input / Timed m chng ta tho lun y khng chi duy
nht cho hng trng(white goods) (v d nh my git).
V d, mt dy cc s kin c s dng nng bnh (landing-gear) trong my bay ch
hng s c iu khin mt cch tng t.Trong trng hp ny, cc kim tra quan trng (v
d WoW - Weight
on Wheels) s c s dng xc nh xem l my bay ang di t hay trn tri:cc
kim tra ny s hon thnh trc khi cng vic bt u.

Hi tip t cc ca khc nhau v cc cm bin bnh


s dng m bo rng tng bc ca hot ng chnh xc.

Atienganh.blogspot.com

178

No book no knowledge

/*-------------------------------------------------------------*Washer.C (v1.01)
-------------------------------------------------------Kt cu a trng thi cho b iu khin my git.
-*-------------------------------------------------------------*/
#include "Main.H"
#include "Port.H"
#include "Washer.H"
/* ------ khai bo d liu ring ---------------------- */
/* cc trng thi c th */
typedef enum {INIT, START, FILL_DRUM, HEAT_WATER,
WASH_01, WASH_02, ERROR} eSystem_state;
/* ------ cc hm nguyn mu ring ------------------------- */
tByte
bit
bit
bit

WASHER_Read_Selector_Dial(void);
WASHER_Read_Start_Switch(void);
WASHER_Read_Water_Level(void);
WASHER_Read_Water_Temperature(void);

void
void
void
void
void
void

WASHER_Control_Detergent_Hatch(bit);
WASHER_Control_Door_Lock(bit);
WASHER_Control_Motor(bit);
WASHER_Control_Pump(bit);
WASHER_Control_Water_Heater(bit);
WASHER_Control_Water_Valve(bit);

/* ------ hng s ring ----------------------------------- */


#define OFF 0
#define ON 1
#define MAX_FILL_DURATION (tLong) 1000
#define MAX_WATER_HEAT_DURATION (tLong) 1000
#define WASH_01_DURATION 30000

Atienganh.blogspot.com

179

No book no knowledge

/* ------ cc bin ring ----------------------------------- */


static eSystem_state System_state_G;
static tWord Time_in_state_G;
static tByte Program_G;
/* 10 chng trnh khc nhau c tr gip
Mi loi c th (hoc khng)dng lm sch */
static tByte Detergent_G[10] = {1,1,1,0,0,1,0,1,1,0};
/* mi loi c th (hoc khng)dng lm nng nc */
static tByte Hot_Water_G[10] = {1,1,1,0,0,1,0,1,1,0};
/* --------------------------------------------------------------- */
void WASHER_Init(void)
{
System_state_G = INIT;
}

Atienganh.blogspot.com

180

No book no knowledge

/* --------------------------------------------------------------- */
void WASHER_Update(void)
{
/* gi ra ln/1 giy */
switch (System_state_G)
{
case INIT:
{
/* ch gii thiu */
Debug_port = (tByte) System_state_G;
/* ci t trng thi u */
/* Motor tt */
WASHER_Control_Motor(OFF);
/* bm tt */
WASHER_Control_Pump(OFF);
/* my si tt */
WASHER_Control_Water_Heater(OFF);
/* van c ng */
WASHER_Control_Water_Valve(OFF);
/* ch (v hn nh) n khi nt START c bm */
if (WASHER_Read_Start_Switch() != 1)
{
return;
}
/* bt u bm nt
-> c t bn phm chn */
Program_G = WASHER_Read_Selector_Dial();
/* thay i trng thi */
System_state_G = START;
break;
}

Atienganh.blogspot.com

181

No book no knowledge

case START:
{
/* ch m phng */
Debug_port = (tByte) System_state_G;
/* ng ca */
WASHER_Control_Door_Lock(ON);
/* bt u cho y drum */
WASHER_Control_Water_Valve(ON);
/* tung ra ch lm sch (nu bnh thng) */
if (Detergent_G[Program_G] == 1)
{
WASHER_Control_Detergent_Hatch(ON);
}
/* sn sng ti trng thi tip theo */
System_state_G = FILL_DRUM;
Time_in_state_G = 0;
break;
}

Atienganh.blogspot.com

182

No book no knowledge

case FILL_DRUM:
{
/* ch c tnh cht gii thiu */
Debug_port = (tByte) System_state_G;
/* li trng thi ny n khi drum y
CH : thi gian ngh bao gm c y */
if (++Time_in_state_G >= MAX_FILL_DURATION)
{
/* s lm y drum... */
System_state_G = ERROR;
}
/* kim tra mc nc*/
if (WASHER_Read_Water_Level() == 1)
{
/* Drum y */
/* chng trnh c yu cu lm nng nc khng? */
if (Hot_Water_G[Program_G] == 1)
{
WASHER_Control_Water_Heater(ON);
/* sn sng chuyn trng thi */
System_state_G = HEAT_WATER;
Time_in_state_G = 0;
}
else
{
/* ch s dng nc lnh */
/* sn sng ti trng thi tip theo */
System_state_G = WASH_01;
Time_in_state_G = 0;
}
}
break;
}

Atienganh.blogspot.com

183

No book no knowledge

case HEAT_WATER:
{
/* ch gii thiu */
Debug_port = (tByte) System_state_G;
/* gi nguyn trng thi n khi nc nng
CH : thi gian ngh bao gm c y */
if (++Time_in_state_G >= MAX_WATER_HEAT_DURATION)
{
/* nc s c lm m... */
System_state_G = ERROR;
}
/* kim tran nhit ca nc */
if (WASHER_Read_Water_Temperature() == 1)
{
/* nc mc nhit yu cu */
/* sn sng ti trng thi tip theo */
System_state_G = WASH_01;
Time_in_state_G = 0;
}
break;
}

Atienganh.blogspot.com

184

No book no knowledge

case WASH_01:
{
/* ch minh ha */
Debug_port = (tByte) System_state_G;
/* tt c chng trnh git u cha WASH_01
Drum c quay chm m bo qun o c t hon ton */
WASHER_Control_Motor(ON);
if (++Time_in_state_G >= WASH_01_DURATION)
{
System_state_G = WASH_02;
Time_in_state_G = 0;
}
break;
}
/* cc bc git cn li b b qua y ... */
case WASH_02:
{
/* ch minh ha */
Debug_port = (tByte) System_state_G;
break;
}
case ERROR:
{
/* ch minh ha */
Debug_port = (tByte) System_state_G;
break;
}
}
}

Atienganh.blogspot.com

185

No book no knowledge

/* --------------------------------------------------------------- */
tByte WASHER_Read_Selector_Dial(void)
{
/* code ca ngi s dng y */
return 0;
}
/* --------------------------------------------------------------- */
bit WASHER_Read_Start_Switch(void)
{
/* n gin gii thiu ... */
if (Start_pin == 0)
{
/* nt bt u bm */
return 1;
}
else
{
return 0;
}
}
/* --------------------------------------------------------------- */
bit WASHER_Read_Water_Level(void)
{
/* User code here... */
return 1;
}
/* --------------------------------------------------------------- */
bit WASHER_Read_Water_Temperature(void)
{
/* code ca ngi s dng y... */
return 1;
}
/* --------------------------------------------------------------- */
void WASHER_Control_Detergent_Hatch(bit State)
{
bit Tmp = State;
/* code ca ngi s dng y... */
}

Atienganh.blogspot.com

186

No book no knowledge

Kt lun
Chuyn ny tho lun s thi hnh ca cc h thng a trng thi (timed v input/timed), c
s dng kt ni vi mt h iu hnh, chuyn ny c trnh by trong cun Embedded
C
Chng 7, cc kiu kin trc mm do ny s c s dng rng ri trong cc h thng nhng.

Atienganh.blogspot.com

187

No book no knowledge

Chun b cho chuyn tip theo

Xin c Chng 9
Trc khi bt u chuyn tip theo

Atienganh.blogspot.com

188

No book no knowledge

Atienganh.blogspot.com

189

No book no knowledge

Chng 8: S dng giao din ni tip

Atienganh.blogspot.com

190

No book no knowledge

Gii thiu tng qut v chuyn


Chuyn ny s:
Tho lun v kt ni d liu chunDRS-232
Xem xt vic s dng RS-232 truyn d liu(v nhn d liu )t cc my tnh(v cc thit
b tng t) nh th no.

iu ny hu ch:
Trong cc ng dng thu nhn d liu.
Trong cc ng dng iu khin(gi n b iu khin cc tham s).
Cho s chnh l ni chung.

Atienganh.blogspot.com

191

No book no knowledge

RS-232 l g?
Nm 1997, hip hi cng nghip vin thng(Telecommunications Industry Association) chnh
thc tung ra th trng mt giao thc truyn thng ni tip vi tn TIA-232 phin bn F, tr
nn ni ting hn RS-232 (xut hin ln u tin vo nhng nm 1960 vi tn Recommended
Standard). Cc chun tng t (V.28) cng c cng b bi International
Telecommunications Union (ITU) v bi CCITT (The Consultative
Committee International Telegraph and Telephone).
Chun RS-232 bao gm cc kha cnh sau:
Giao thc ny c s dng cho vic truyn d liu.
in p c s dng trn cc ng truyn tn hiu.
Cc u ni c s dng kt ni cc thit b vi nhau.

Ni chung,chun ny c s dng nhiu v rng ri, tc truyn d liu nm trong khong t


115 n 330 kbits /s (115 / 330 k
baud). Khong cch truyn d liu l 15 m hoc hn.
Ch rng RS-232 l mt chun kt ni cng mc (peer-to-peer).

Atienganh.blogspot.com

192

No book no knowledge

Giao thc RS-232 c bn


RS-232 l mt giao thc hng k t. l, gi mt khi 8-bit d liu. truyn pht mt byte
d liu trn kt ni RS-232 ,thng thng chng ta m ha thng tin nh sau:
Gi mt bit Start.
Gi d liu (8 bits).
Gi mt bit Stop (hay nhiu hn).

Ch : UART s chu trch nhim v nhng chi tit ny!

Atienganh.blogspot.com

193

No book no knowledge

Truyn d liu khng ng b v tc baud


RS-232 s dng mt giao thc khng ng b.
Cui ca c hai kt ni u c mt ng h ni,
chy cng mt tc . D liu (trong trng hp ca RS-232,
bit Start) sau c s dng ng b cc ng h (nu cn thit) m d liu c
truyn thnh cng.

RS-232 thng hot mt gii(gii hn) tc baud.


Tiu biu l: 75, 110, 300, 1200, 2400, 4800, 9600,
14400, 19200, 28800, 33600, 56000, 115000 v
330000 (him khi).
9600 l la chn rt an ton v n c h tr rt rng ri.

Atienganh.blogspot.com

194

No book no knowledge

RS-232 cc mc in p
Cc mc ngng c s dng nhn l +3 V v -3 V and the lines are inverted.
i p ln nht cho php l +/- 15V.

Ch rng cc mc in p ny khng th kt ni trc tip vi cc chn ca vi iu khin(vi


kiu giao din phn cng s c yu cu).
V d, Max232 v Max233 c s dng rt ph bin v rng ri cc dng chip iu khin.

S dng Max 233( nh RS-232) truyn nhn.

Atienganh.blogspot.com

195

No book no knowledge

Cu trc phn mm
Gi s chng ta mun truyn d liu ti mt my PC vi tc baud tiu chun l
9600(ngha l 9600 bit trn mt giy). Truyn tng byte d liu, tnh c bit start v bit stop l
10 bit thng tin (gi s rng mt bit stop n c s dng). Theo mt kt qu th mi byte
truyn i mt xp x 1ms.

V du: Gi s chng ta mun gi thng tin sau ti PC:


Current core temperature is 36.678 degrees
th vic gi 42 k t ny s mt hn 40 ms hon thnh .iu ny thng thng l mt
khong thi gian di, khng th chp nhn.

Cch r rng gii quyt vn ny l tng tc baud. Tuy nhin cch ny rt t khi c
s dng (v n khng thc s gii quyt c vn trn).

Mt cch gii qut tt hn l ghi tt d liu trn mt vng m ca vi iu


Khin.Ni dung ca vng m ny sau s c gi ti vi iu khin
(lun l mt bit mt ln) s dng mt tc v u n, nh k.

Atienganh.blogspot.com

196

No book no knowledge

Tng quan
Tt c k t c ghi ngay lp tc c ghi
vo b m

Current cor e temperature


is 36. 678 degrees

(hot ng rt nhanh)

B m(buffer)

Trnh lp lch s gi mt
k t ti PC sau mi 10 ms
(v d)

Atienganh.blogspot.com

197

No book no knowledge

S dng U(S)ART trn chip cho kt ni RS-232


UART l song cng hon ton,ngha l n c th truyn v nhn ng thi mt lc.
N cng c th m lc thu, ngha l n c th thu v gi mt byte trong khi byte th hai
c nhn

Port ni tip c th thc hin 4 ch (mt ch ng b v ba


ch khng ng b).

Trc tin chng ta xt ch 1.


Trong ch ny, 10 bit c truyn i(thng qua chn TxD) hay nhn
(thng qua chn RxD): mt bit start (0), 8 data bits v mt bit stop (1).

Atienganh.blogspot.com

198

No book no knowledge

Cc thanh ghi port ni tip


B iu khin port ni tip v b ghi trng thi cha trong thanh ghi SCON. Thanh ghi ny cha
cc bit chn ch ( v cc bit ngt,
TI v RI: khng c s dng y).
SBUF l mt thanh ghi m truyn nhn cng ni tip.
Ghi ln SBUF np thanh ghi truyn nhn v bt u truyn nhn.
SBUF = 0x0D;

/* Output CR */

c SBUF bng cch truy cp vo thanh ghi nhn ring r:.


/* doc du lieu tu UART
Data = SBUF;

Atienganh.blogspot.com

*/

199

No book no knowledge

To ra tc baud
Chng ta ch yu cp cch s dng port ni tip ch .
Trong ch ny, tc baud c xc nh tc trn ca timer 1
hay Timer 2.
Chng ta s tp trung vo Timer mt sinh ra tc baud.

Tc baud c sinh ra bi tc trn ca Timer 1 v gi tr ca


SMOD nh sau:

Trong :
SMOD

L tc bit baud kp trn thanh ghi PCON

Frequency oscillator L tn s dao ng


Instructionscycle
TH1

L s lng quy trnh my trn vng lp (v d: 12,6)


l gi tr np li cho Timer 1

Ch rng timer ny ch 8 bit t ng np li gi tr v s to thnh ngt nn c v


hiu.

Atienganh.blogspot.com

200

No book no knowledge

Ti sao li s dng thch anh 11.0592 MHz?


Rt quan trng khi hiu rng khng th to ra cc tc baud chun
(v d: 9600) s dng Timer 1 (hay Timer 2),tr phi bn s dng b
dao ng thch anh 11.0592 .

Ghi nh: l mt giao thc khng ng b, v da vo s hot ng


chnh xc trn c hai kt ni ang lm vic vi cng tc baud. Trn
thc t, bn c th lm vic vi mt t baud khc nhau cui c hai
kt ti 5%, nhng khng c ln hn.
Mc d sai s, nhng lun lun l nguyn tc tt c c
tc baud xp x gi tr chun bi v, trong phm vi ny, c th
c nhng bin i gia cc b dao ng trong PC v h thng nhng.

Cng ch rng,s dng cc dng dao ng thch anh


(hn thit b cng hng bng gm) l rt cn thit khi kt ni vi cc
ng dn ni tip , khng ng b (nh RS-232, RS-485, hay CAN):
b dao ng gm khng n nh cho mc ch ny.

Atienganh.blogspot.com

201

No book no knowledge

Phn mm trn PC

Nu my tnh ca bn ang chy h iu hnh Windows (95, 98, NT, 2000),th mt la chn n
gin m hiu qu l ng dngHyperterminal.

Atienganh.blogspot.com

202

No book no knowledge

V lnh printf()?
Thng thng, chng ti khuyn co khng nn s dng hm th vin chun
printf(), v:
Hm ny gi d liu ngay lp tc ti UART. Theo mt kt qu, thi gian truyn
nhn qu lu dn n s dng khng an ton (trong mt ng dng lp trnh c tnh
cht hp tc), v
hu ht s thi hnh ca hm printf() khng lin quan cht ch vi thi gian ngh, v
vy vic s dng hm ny c th dn n treo nu c li xy ra.

Atienganh.blogspot.com

203

No book no knowledge

RS-232 v 8051: Bao gm c im mnh v im yu


S h tr RS-232 l mt phn ca 8051: cc ng dng da vo RS-232
rt linh ng.
RS-232 rt thng gp: mi PC u c mt hoc nhiu hn cng kt ni
RS-232.
D liu c th truyn xa n 30 m (100 ft) (i vi cc chip truyn nhn hin i).
Bi v c phn cng h tr nn RS-232 c mc t ti thp.
NHNG:
RS-232 l mt giao thc bnh ng (v d: khng ging vi RS-485): bn
Ch c th kt ni trc tip (ng thi) mt vi iu khin vi mt PC.
RS-232 c rt t (hoc khng c) phn kim tra li cc mc phn cng
(khng ging vi CAN): nu bn mun chc chn rng d liu nhn my tnh l hp
l th bn cn tin hnh kim tra bng phn mm.
V d: Hin th thi gian trn mt my tnh

Atienganh.blogspot.com

204

No book no knowledge

/*-------------------------------------------------------------*Main.c (v1.00)
-------------------------------------------------------RS-232 (thi gian tri qua) v d - sEOS.
-*-------------------------------------------------------------*/
#include "Main.H"
#include "Port.H"
#include "Simple_EOS.H"
#include "PC_O_T1.h"
#include "Elap_232.h"
/* --------------------------------------------------------------- */
void main(void)
{
/* ci t tc baud l 9600 */
PC_LINK_O_Init_T1(9600);
/* chun b cho h thng o thi gian chy */
Elapsed_Time_RS232_Init();
/* ci t simple EOS (tick 5ms) */
sEOS_Init_Timer2(5);
while(1) /* vng lp v tn */
{
sEOS_Go_To_Sleep();
/* a vo ch ngh tit kim nng lng */
}
}
/*-------------------------------------------------------------*---- END OF FILE ---------------------------------------*-------------------------------------------------------------*/

Atienganh.blogspot.com

205

No book no knowledge

/*-------------------------------------------------------------*Elap_232.C (v1.00)
-------------------------------------------------------Hm th vin n gin cho vic theo di thi gian tri qua
Phin bn gii thiu dng hin th thi gian trn mn hnh my
tnh qua kt ni RS232.
-*-------------------------------------------------------------*/
#include "Main.h"
#include "Elap_232.h"
#include "PC_O.h"
/* ------ nh ngha cc bin chung ------------------------- */
tByte Hou_G;
tByte Min_G;
tByte Sec_G;
/* ------ khi bo cc bin chung ------------------------ */
/* xem Char_Map.c */
extern const char code CHAR_MAP_G[10];
/*-------------------------------------------------------------*Elapsed_Time_RS232_Init()
Hm khi u cho th vin hin th thi gian trn my tnh qua kt ni RS-232.
-*-------------------------------------------------------------*/
void Elapsed_Time_RS232_Init(void)
{
Hou_G = 0;
Min_G = 0;
Sec_G = 0;
}

Atienganh.blogspot.com

206

No book no knowledge

/*-------------------------------------------------------------*/
void Elapsed_Time_RS232_Update(void)
{
char Time_Str[30] = "\rElapsed time:

";

if (++Sec_G == 60)
{
Sec_G = 0;
if (++Min_G == 60)
{
Min_G = 0;
if (++Hou_G == 24)
{
Hou_G = 0;
}
}
}
Time_Str[15] = CHAR_MAP_G[Hou_G / 10];
Time_Str[16] = CHAR_MAP_G[Hou_G % 10];
Time_Str[18] = CHAR_MAP_G[Min_G / 10];
Time_Str[19] = CHAR_MAP_G[Min_G % 10];
Time_Str[21] = CHAR_MAP_G[Sec_G / 10];
Time_Str[22] = CHAR_MAP_G[Sec_G % 10];
/* chng ta s dng d liu "giy" bt hoc tt du hai chm
(gia gi v pht) */
if ((Sec_G % 2) == 0)
{
Time_Str[17] = ':';
Time_Str[20] = ':';
}
else
{
Time_Str[17] = ' ';
Time_Str[20] = ' ';
}
PC_LINK_O_Write_String_To_Buffer(Time_Str);
}

Atienganh.blogspot.com

207

No book no knowledge

/*-------------------------------------------------------------*PC_LINK_O_Init_T1()
Phin bn ny s dng T1 to ra tc baud.
S dng phn cng UART ca 8051
-*-------------------------------------------------------------*/
void PC_LINK_O_Init_T1(const tWord BAUD_RATE)
{
PCON &= 0x7F; /* Set bit SMOD v khng (khng nhn i cc tc baud) */
/* B nhn v hiu d liu 8-bit
, 1 bit start, 1 stop bit stop, baud thay i */
SCON = 0x42;
TMOD |= 0x20;

/* T1 ch 2, 8-bit t np li gi tr */

TH1 = (256 - (tByte)((((tLong)OSC_FREQ / 100) * 3125)


/ ((tLong) BAUD_RATE * OSC_PER_INST * 1000)));
TL1 = TH1;
TR1 = 1;
/* chy Timer */
TI = 1;
/* gi k t u tin (m hnh) */
/* ci t cc b m c v ghi d liu */
Out_written_index_G = 0;
Out_waiting_index_G = 0;
/* khng cho php ngt hot ng */
ES = 0;
}

Atienganh.blogspot.com

208

No book no knowledge

/*-------------------------------------------------------------*/
void PC_LINK_O_Update(void)
{
/* ni v cc byte truyn nhn y.
C d liu no sn sng gi cha? */
if (Out_written_index_G < Out_waiting_index_G)
{
PC_LINK_O_Send_Char(Tran_buffer[Out_written_index_G]);
Out_written_index_G++;
}
else
{
/* khng c d liu gi reset ch s m */
Out_waiting_index_G = 0;
Out_written_index_G = 0;
}
}
/*-------------------------------------------------------------*/
void PC_LINK_O_Write_String_To_Buffer(const char* const STR_PTR)
{
tByte i = 0;
while (STR_PTR[i] != '\0')
{
PC_LINK_O_Write_Char_To_Buffer(STR_PTR[i]);
i++;
}
}

Atienganh.blogspot.com

209

No book no knowledge

/*-------------------------------------------------------------*/
void PC_LINK_O_Write_Char_To_Buffer(const char CHARACTER)
{
/* ghi d liu ln b m ch khi no c ch trng
(khng c li bo co trong th vin n gin ny...) */
if (Out_waiting_index_G < TRAN_BUFFER_LENGTH)
{
Tran_buffer[Out_waiting_index_G] = CHARACTER;
Out_waiting_index_G++;
}
}
/*-------------------------------------------------------------*/
void PC_LINK_O_Send_Char(const char CHARACTER)
{
tLong Timeout1 = 0;
if (CHARACTER == '\n')
{
Timeout1 = 0;
while ((++Timeout1) && (TI == 0));
if (Timeout1 == 0)
{
/* UART khng c p ng li
Khng c li bo co trong th vin n gin ny... */
return;
}
TI = 0;
SBUF = 0x0d;
}

/* u ra CR

*/

Timeout1 = 0;
while ((++Timeout1) && (TI == 0));
if (Timeout1 == 0)
{
/* UART did not respond - error
No error reporting in this simple library... */
return;
}
TI = 0;
SBUF = CHARACTER;
}

Atienganh.blogspot.com

210

No book no knowledge

sEOS_ISR() interrupt INTERRUPT_Timer_2_Overflow


{
TF2 = 0;
/* t reset c nh T2

*/

/*===== USER CODE - Begin ================================== */


/* gi hm cp nht mi 5ms */
PC_LINK_O_Update();
/* ISR ny b gi sau mi 5 ms
- nhu cu cp nht thi gian sau mi giy */
if (++Call_count_G == 200)
{
/* cp nht thi gian */
Call_count_G = 0;
/* gi hm cp nht */
Elapsed_Time_RS232_Update();
}
/*===== USER CODE - End ==================================== */
}

Atienganh.blogspot.com

211

No book no knowledge

V d: s thu nhn tn hiu


Trong on ny,chng ti s a ra mt v d v h thng thu nhn tn
hiu n gin vi cu trc serial-menu .
trong trng hp ny, s dng menu, ngi dng cn xc nh r trng thi ca cc chn u
Port 1 hay Port 2:

Atienganh.blogspot.com

212

No book no knowledge

void MENU_Command_Processor(void)
{
char Ch;
if (First_time_only_G == 0)
{
First_time_only_G = 1;
MENU_Show_Menu();
}
/* kim tra cc u vo ca ngi dng */
PC_LINK_IO_Update();
Ch = PC_LINK_IO_Get_Char_From_Buffer();
if (Ch != PC_LINK_IO_NO_CHAR)
{
MENU_Perform_Task(Ch);
MENU_Show_Menu();
}
}
void MENU_Show_Menu(void)
{
PC_LINK_IO_Write_String_To_Buffer("Menu:\n");
PC_LINK_IO_Write_String_To_Buffer("a - Read P1\n");
PC_LINK_IO_Write_String_To_Buffer("b - Read P2\n\n");
PC_LINK_IO_Write_String_To_Buffer("? : ");
}

Atienganh.blogspot.com

213

No book no knowledge

void MENU_Perform_Task(char c)
{
PC_LINK_IO_Write_Char_To_Buffer(c);
/* phn hi menu la chn */
PC_LINK_IO_Write_Char_To_Buffer('\n');
/* chy tc v */
switch (c)
{
case 'a':
case 'A':
{
Get_Data_From_Port1();
break;
}
case 'b':
case 'B':
{
Get_Data_From_Port2();
break;
}
}
}
void Get_Data_From_Port1(void)
{
tByte Port1 = Data_Port1;
char String[11] = "\nP1 = XXX\n\n";
String[6] = CHAR_MAP_G[Port1 / 100];
String[7] = CHAR_MAP_G[(Port1 / 10) % 10];
String[8] = CHAR_MAP_G[Port1 % 10];
PC_LINK_IO_Write_String_To_Buffer(String);
}
void Get_Data_From_Port2(void)
{
tByte Port2 = Data_Port2;
char String[11] = "\nP2 = XXX\n\n";
String[6] = CHAR_MAP_G[Port2 / 100];
String[7] = CHAR_MAP_G[(Port2 / 10) % 10];
String[8] = CHAR_MAP_G[Port2 % 10];
PC_LINK_IO_Write_String_To_Buffer(String);
}

Atienganh.blogspot.com

214

No book no knowledge

sEOS_ISR() interrupt INTERRUPT_Timer_2_Overflow


{
TF2 = 0;
/*
phi t reset c T2

*/

/*===== USER CODE - Begin ================================== */


/* gi MENU_lnh_ca b iu khin mi 5ms */
MENU_Command_Processor();
/*===== USER CODE - End ==================================== */
}

Atienganh.blogspot.com

215

No book no knowledge

Kt lun
Trong chuyn ny, chng ta minh ha cch s dng giao din ni tip
trn vi iu khin 8051.
Trong chuyn tip, chng ta s s dng nghin cu trng hp
minh ha cc k thut tho lun y c s dng trong cc ng
dng thc t nh th no.

Atienganh.blogspot.com

216

No book no knowledge

Chun b cho chuyn tip theo

Xin c Chng 10
Trc khi bt u chuyn tip theo

Atienganh.blogspot.com

217

No book no knowledge

Chng 9: H thng bo ng ngi xm phm

Atienganh.blogspot.com

218

No book no knowledge

Li gii thiu

Atienganh.blogspot.com

219

No book no knowledge

S hot ng ca h thng
Khi bt u kch hot, h thng trng thi khng bo v (Disarmed).
Trong trng thi ny, cc cm bin b b qua. Bo ng khng ku.
H thng trng thi ny n khi ngi dng nhp vo mt khu ng qua bn phm(trong h
thng chng thc ca chng ta mt khu l 1234). Khi mt mt khu ng c nhp
vo,h thng cho vo trng
thi trang b (Arming) .
Trong trng thi Arming, h thng i trong 60 s, cho php ngi dng ra khi khu vc
ny trc khi qu trnh kim sot bt u. sau 60s,
h thng a vo trng thi c trang b(armed).
Trong trng thi Armed, tnh trng ca cc cm bin ca h thng
s c kim sot. Nu mt cm bin ca s c tn hiu th h thng s a ra trng thi c
ngi t nhp. Nu cm bin ca c tn hiu th h thng a vo trng thi ngui gin
(disarming). Hot ng ca bn phm cng c kim sot: nu mt mt khu ng c
nh vo, h thng s a vo trng thikhng bo v state.
Trong trng thi ngui gin, chng ta gi s rng ca c m bi ngi no , c th l
mt ngi s dng c y quyn.
H thng s trng thi ny ti 60 giy, sau , theo mc nh, n s a vo trng thi c
ngi xm nhp . nu trong chu k 60s, ngi s dng nhp vo mt khu ng, h thng s
a vo trng thi khng bo v.
Trong trng thi c ngi xm nhp , chung bo ng s ku. H thng bo ng s ku (v
hn nh) ti khi mt khu ng c nhp vo.

Atienganh.blogspot.com

220

No book no knowledge

Cc thnh phn phn mm kha c s dng trong


v d ny
chng ta s dng nhng thnh phn phn mm sau:
Phn mm iu khin cc chn ngoi ( kch hot chung),
c gii thiu trong cun Embedded C Chng 3.
c cng tc, ( tho lun trong Embedded C Chng 4)
truy cp vo cc u vo t cc cm bin ca v ca s. Ch rng, trong v d n gin
ny(vi mc ch minh ha) khng c hm cng
tc no c thc hin. Thnh phn ny c th c thm vo (nu c yu cu) m khng
h kh khn.
H thng nhng, sEOS, c gii thiu trong cun
Embedded C Chng 7.
Mt th vin bn phm , cn c trn mt dy cc cng tc.
Ch rng, n gin khi s dng th vin bn phm trong phn
m phng ny, chng ta gi s ch c 8 phm bm trong chng trnh
v d (0 - 7). H thng ny chc chn c th s dng t nht 10 phm
bm: vic thm vo cc phm bm rt d dng nu c yu cu.
Th vin RS-232 (t Embedded C Chng 9) c s dng
minh ha cho s hot ng ca chng trnh. Th vin ny c th khng cn thit trong h
thng cui (nhng c th hu ch khi dng tr gip bo dng h thng).

Atienganh.blogspot.com

221

No book no knowledge

Chy chng trnh

Atienganh.blogspot.com

222

No book no knowledge

Phn mm
/*-------------------------------------------------------------*Port.H (v1.00)
-------------------------------------------------------'Port Header' (xem chuong 5)d n INTRUDER (xem chuong 10)
-*-------------------------------------------------------------*/
/* ------ Keypad.C ------------------------------------------- */
#define KEYPAD_PORT P2
sbit
sbit
sbit
sbit
sbit
sbit
sbit
sbit

K0
K1
K2
K3
K4
K5
K6
K7

=
=
=
=
=
=
=
=

KEYPAD_PORT^0;
KEYPAD_PORT^1;
KEYPAD_PORT^2;
KEYPAD_PORT^3;
KEYPAD_PORT^4;
KEYPAD_PORT^5;
KEYPAD_PORT^6;
KEYPAD_PORT^7;

/* ------ Intruder.C --------------------------------------- */


sbit Sensor_pin = P1^0;
sbit Sounder_pin = P1^7;
/* ------ Lnk_O.C ------------------------------------------ */
/* Chn 3.0 v 3.1 c s dng cho giao din kt ni RS-232 */
/*-------------------------------------------------------------*---- END OF FILE ---------------------------------------*-------------------------------------------------------------*/

Atienganh.blogspot.com

223

No book no knowledge

/*-------------------------------------------------------------*Main.c (v1.00)
-------------------------------------------------------H thng bo ng n gin.
-*-------------------------------------------------------------*/
#include "Main.H"
#include "Port.H"
#include "Simple_EOS.H"
#include "PC_O_T1.h"
#include "Keypad.h"
#include "Intruder.h"
/* ............................................................... */
void main(void)
{
/* cai dat toc do baud la 9600 */
PC_LINK_O_Init_T1(9600);
/* chuan bi cho ban phim */
KEYPAD_Init();
/* chuan bi cho bao dong xam nhap */
INTRUDER_Init();
/* cai simple EOS (tick 5ms) */
sEOS_Init_Timer2(5);
while(1) /* vong lap vo tan */
{
sEOS_Go_To_Sleep();
/* dua vao che do nghi de tiet kiem nang luong */
}
}
/*-------------------------------------------------------------*---- END OF FILE ---------------------------------------*-------------------------------------------------------------*/

Atienganh.blogspot.com

224

No book no knowledge

/*-------------------------------------------------------------*Intruder.C (v1.00)
-*-------------------------------------------------------------*/
...
/* ------ khai bao du lieu chung ---------------------- */
/* cac trang thai co kha nang cua he thong */
typedef enum {DISARMED, ARMING, ARMED, DISARMING, INTRUDER}
eSystem_state;
/* ------ ham nguyen mau rieng ------------------------- */
bit
bit
bit
void

INTRUDER_Get_Password_G(void);
INTRUDER_Check_Window_Sensors(void);
INTRUDER_Check_Door_Sensor(void);
INTRUDER_Sound_Alarm(void);

...
/* --------------------------------------------------------------- */
void INTRUDER_Init(void)
{
/* cai dat trang thai dau cua he thong (DISARMED) */
System_state_G = DISARMED;
/* Set 'thoi gian trong trang thaive 0 */
State_call_count_G = 0;
/* xoa bo dem ban phim */
KEYPAD_Clear_Buffer();
/* Set co 'trang thai moi' */
New_state_G = 1;
/* Set hai chan cam bien de doc che do */
Window_sensor_pin = 1;
Sounder_pin = 1;
}

Atienganh.blogspot.com

225

No book no knowledge

void INTRUDER_Update(void)
{
/* gia tang thoi gian */
if (State_call_count_G < 65534)
{
State_call_count_G++;
}
/* goi ra sau moi 50 ms */
switch (System_state_G)
{
case DISARMED:
{
if (New_state_G)
{
PC_LINK_O_Write_String_To_Buffer("\nDisarmed");
New_state_G = 0;
}
/* chac chan rang canh bao da tat */
Sounder_pin = 1;
/* ch mt khu ng ... */
if (INTRUDER_Get_Password_G() == 1)
{
System_state_G = ARMING;
New_state_G = 1;
State_call_count_G = 0;
break;
}
break;
}

Atienganh.blogspot.com

226

No book no knowledge

case ARMING:
{
if (New_state_G)
{
PC_LINK_O_Write_String_To_Buffer("\nArming...");
New_state_G = 0;
}
/* doi o day 60 giay (gia su khoang tick la 50 ms) */
if (++State_call_count_G > 1200)
{
System_state_G = ARMED;
New_state_G = 1;
State_call_count_G = 0;
break;
}
break;
}

Atienganh.blogspot.com

227

No book no knowledge

case ARMED:
{
if (New_state_G)
{
PC_LINK_O_Write_String_To_Buffer("\nArmed");
New_state_G = 0;
}
/* dau tien, kiem tra cam bien cua so */
if (INTRUDER_Check_Window_Sensors() == 1)
{
/* mot nguoi la duoc phat hien */
System_state_G = INTRUDER;
New_state_G = 1;
State_call_count_G = 0;
break;
}
/* tiep theo,kiem tra cac cam bien cua */
if (INTRUDER_Check_Door_Sensor() == 1)
{
/* co the la nguoi su dung duoc uy quen toi trang thai 'Disarming' */
System_state_G = DISARMING;
New_state_G = 1;
State_call_count_G = 0;
break;
}
/* cuoi cung, kiem tra mat khau dung */
if (INTRUDER_Get_Password_G() == 1)
{
System_state_G = DISARMED;
New_state_G = 1;
State_call_count_G = 0;
break;
}
break;
}

Atienganh.blogspot.com

228

No book no knowledge

case DISARMING:
{
if (New_state_G)
{
PC_LINK_O_Write_String_To_Buffer("\nDisarming...");
New_state_G = 0;
}
/* doi o day 60s (gia su khoang thoi gian tick la 50 ms)
De cho phep nguoi su dung nhap mat khau dung
- sau do neu het thoi gian thi co tieng bao dong. */
if (++State_call_count_G > 1200)
{
System_state_G = INTRUDER;
New_state_G = 1;
State_call_count_G = 0;
break;
}
/* van phai kiem tra cac cam bien cua so */
if (INTRUDER_Check_Window_Sensors() == 1)
{
/* mot nguoi la duoc phat hien */
System_state_G = INTRUDER;
New_state_G = 1;
State_call_count_G = 0;
break;
}
/* cuoi cung, kiem tra mat khau dung hay chua */
if (INTRUDER_Get_Password_G() == 1)
{
System_state_G = DISARMED;
New_state_G = 1;
State_call_count_G = 0;
break;
}
break;
}

Atienganh.blogspot.com

229

No book no knowledge

case INTRUDER:
{
if (New_state_G)
{
PC_LINK_O_Write_String_To_Buffer("\n** INTRUDER! **");
New_state_G = 0;
}
/* co tieng bao dong! */
INTRUDER_Sound_Alarm();
/* giu nguyen tieng bao dong den khi mat khau dung duoc nhap
vao */
if (INTRUDER_Get_Password_G() == 1)
{
System_state_G = DISARMED;
New_state_G = 1;
State_call_count_G = 0;
}
break;
}
}
}

Atienganh.blogspot.com

230

No book no knowledge

bit INTRUDER_Get_Password_G(void)
{
signed char Key;
tByte Password_G_count = 0;
tByte i;
/* cap nhat bo dem ban phim */
KEYPAD_Update();
/* co du lieu moi o bo dem ban phim khong? */
if (KEYPAD_Get_Data_From_Buffer(&Key) == 0)
{
/* khong co du lieu moi mat khau sai */
return 0;
}
/* neu chung ta o do, mot phim se duoc bam*/
/* mat bao lau ke tu khi phim cuoi cung duoc bam?
Phai bam trong 50s (gia su khoang thoi gian tick la 50 ms ) */
if (State_call_count_G > 1000)
{
/* them 5s tinh t khi phim cuoi cung duoc bam
- khoi dong lai xu ly dau vao */
State_call_count_G = 0;
Position_G = 0;
}
if (Position_G == 0)
{
PC_LINK_O_Write_Char_To_Buffer('\n');
}
PC_LINK_O_Write_Char_To_Buffer(Key);
Input_G[Position_G] = Key;

Atienganh.blogspot.com

231

No book no knowledge

/* co phai mat khau co 4 so? */


if ((++Position_G) == 4)
{
Position_G = 0;
Password_G_count = 0;
/* kiem tra mat khau */
for (i = 0; i < 4; i++)
{
if (Input_G[i] == Password_G[i])
{
Password_G_count++;
}
}
}
if (Password_G_count == 4)
{
/* mat khau dung */
return 1;
}
else
{
/* mat khau sai */
return 0;
}
}

Atienganh.blogspot.com

232

No book no knowledge

bit INTRUDER_Check_Window_Sensors(void)
{
/* chi mot cam bien cua so o day
- nang cap de dang. */
if (Window_sensor_pin == 0)
{
/* nguoi la duoc phat hien... */
PC_LINK_O_Write_String_To_Buffer("\nWindow damaged");
return 1;
}
/* mac dinh */
return 0;
}
/* --------------------------------------------------------------- */
bit INTRUDER_Check_Door_Sensor(void)
{
/* cam bien cua don (truy cap hanh trinh) */
if (Door_sensor_pin == 0)
{
/* co ai do mo cua... */
PC_LINK_O_Write_String_To_Buffer("\nDoor open");
return 1;
}
/* mac dinh */
return 0;
}
/* --------------------------------------------------------------- */
void INTRUDER_Sound_Alarm(void)
{
if (Alarm_bit)
{
/* canh bao noi voi cac chan nay */
Sounder_pin = 0;
Alarm_bit = 0;
}
else
{
Sounder_pin = 1;
Alarm_bit = 1;
}
}

Atienganh.blogspot.com

233

No book no knowledge

void KEYPAD_Update(void)
{
char Key;
/* quet ban phim o day... */
if (KEYPAD_Scan(&Key) == 0)
{
/* khong co du lieu ban phim quay lai */
return;
}
/* muon tim ra chi so 0, neu du lieu cu khong duoc doc
(simple ~circular buffer). */
if (KEYPAD_in_waiting_index == KEYPAD_in_read_index)
{
KEYPAD_in_waiting_index = 0;
KEYPAD_in_read_index = 0;
}
/* nap du lieu ban phim vao bo dem */
KEYPAD_recv_buffer[KEYPAD_in_waiting_index] = Key;
if (KEYPAD_in_waiting_index < KEYPAD_RECV_BUFFER_LENGTH)
{
/* tang ma khong lam tran bo dem */
KEYPAD_in_waiting_index++;
}
}
bit KEYPAD_Get_Data_From_Buffer(char* const pKey)
{
/* neu co du lieu moi o bo dem */
if (KEYPAD_in_read_index < KEYPAD_in_waiting_index)
{
*pKey = KEYPAD_recv_buffer[KEYPAD_in_read_index];
KEYPAD_in_read_index++;
return 1;
}
return 0;
}

Atienganh.blogspot.com

234

No book no knowledge

bit KEYPAD_Scan(char* const pKey)


{
char Key = KEYPAD_NO_NEW_DATA;
if
if
if
if
if
if
if
if

(K0
(K1
(K2
(K3
(K4
(K5
(K6
(K7

==
==
==
==
==
==
==
==

0)
0)
0)
0)
0)
0)
0)
0)

{
{
{
{
{
{
{
{

Key
Key
Key
Key
Key
Key
Key
Key

=
=
=
=
=
=
=
=

'0';
'1';
'2';
'3';
'4';
'5';
'6';
'7';

}
}
}
}
}
}
}
}

if (Key == KEYPAD_NO_NEW_DATA)
{
/*khong co phim nao duoc bam */
Old_key_G = KEYPAD_NO_NEW_DATA;
Last_valid_key_G = KEYPAD_NO_NEW_DATA;
return 0;
}

/* khong co du lieu moi */

/* mot phim duoc bam: debounce boi hai lan kiem tra */
if (Key == Old_key_G)
{
/*mot phim bam dung duoc phat hien */
/* phai la mot phim bam moi khong tu dong nap lai */
if (Key != Last_valid_key_G)
{
/* phim moi! */
*pKey = Key;
Last_valid_key_G = Key;
return 1;
}
}
/* khong co du lieu moi */
Old_key_G = Key;
return 0;
}

Atienganh.blogspot.com

235

No book no knowledge

sEOS_ISR() interrupt INTERRUPT_Timer_2_Overflow


{
TF2 = 0;
/* tu reset co T2

*/

/*===== USER CODE - Begin ================================== */


/* goi ham cap nhat RS-232 moi 5ms */
PC_LINK_O_Update();
/* ISR nay duoc goi sau moi 5 ms
- chi muon cap nhat xem co nguoi la khong sau moi 50 ms. */
if (++Call_count_G == 10)
{
/* thoi gian de cap nhat canh bao co ke dot nhap */
Call_count_G = 0;
/* goi ham cap nhat intruder */
INTRUDER_Update();
}
/*===== USER CODE - End ==================================== */
}

Atienganh.blogspot.com

236

No book no knowledge

Nng cp v chnh sa h thng

Lm th no bn thm mt bn phm thc ?


(xem cun Patterns for Time-Triggered Embedded Systems, chng. 20)
Bn s thm mt mn hnh hin th LCD nh th no ?
(xem cun Patterns for Time-Triggered Embedded Systems, Chng. 22)
Bn s thm cc nt (node) nh th no ?
(xem cun Patterns for Time-Triggered Embedded Systems, Phn F)

Atienganh.blogspot.com

237

No book no knowledge

Kt lun
Trng hp nghin cu ny minh ha hu ht cc chc nng ca ngn
ng nhng C (nh c tho lun trong cc chuyn trc ca kha hc ny ).
Chng ta s xem xt trng hp nghin cu cui cng trong chuyn
tip theo.

Atienganh.blogspot.com

238

No book no knowledge

Chng 10: iu khin mt robot di chuyn

Atienganh.blogspot.com

239

No book no knowledge

Khi qut chung


Trong phn ny, chng ta s tho lun vic thit k mt phn mm
iu khin mt con robot di ng nh.

Robot ny l Mr Line
N c sn xut bi Microrobot NA
http://www.microrobotna.com

Atienganh.blogspot.com

240

No book no knowledge

Robot c th lm g?
Robot c cc cm bin hng ngoi v thit b pht, cho php n pht hin ra vch en trn nn
trng v bm theo vch en .

http://www.microrobotna.com

Atienganh.blogspot.com

241

No book no knowledge

B no ca robot
Mr Line c iu khin bi mt vi iu khin h 8051 ( AT89C2051).
Chng ta s s dng mt vi iu khin c chn tng thch l
AT89C4051.

http://www.microrobotna.com

Atienganh.blogspot.com

242

No book no knowledge

Robot chuyn ng nh th no?


Mr Line c hai motor: bng vic iu khin tc t i ca hai motor
ny chng ta c th iu chnh tc v hng ca con robot khi n
di chuyn.

http://www.microrobotna.com

Atienganh.blogspot.com

243

No book no knowledge

iu ch rng xung

Time
Ch lm vic(%) =

x
x y

100

chu k = x + y, (trong x v y c tnh bng giy).


Tn s =

1
x y

,.

Ch :in p trung bnh c tnh bng ch lm vic nhn vi


in p ti.
Xem cun: Patterns for Time-Triggered Embedded Systems, Chng 33

Atienganh.blogspot.com

244

No book no knowledge

Phn mm PWM

PWM_PERIOD_G
PWM_G
PWM_position_G
if (PWM_position_G < PWM_G)
{
PWM_pin = PWM_ON;
}
else
{
PWM_pin = PWM_OFF;
}

Xem cun: Patterns for Time-Triggered Embedded Systems, Chng 33

Atienganh.blogspot.com

245

No book no knowledge

bit thm v robot


Xem ti:
http://www.le.ac.uk/engineering/mjp9/robot.htm
Kt thc
That brings us to the end of this course!
Bn dch u tay khng th thiu nhng sai st. Rt mong nhn c s gp ca cc
bn.
Mi thc mc v bn dch xin vui lng gi ti :
doanhau198@gmail.com
tranthien.pro@gmail.com
Atienganh.blogspot.com

Atienganh.blogspot.com

246

No book no knowledge