EmbeddedSystemsAndLabsForARM-V1 2 PDF
EmbeddedSystemsAndLabsForARM-V1 2 PDF
EmbeddedSystemsAndLabsForARM-V1 2 PDF
To Readers
<<Embedded System Application Development and Labs>> Textbook is compounded with the
Embest ARM Development System that was developed by Embst Inc. at Shenzhen, China. Any reader
who is interested in using the Embest development tools for ARM can contact Embest Inc. The
following is the Embest contact information:
<<Embedded System Development and Applications>> Textbook and <<Embedded System Application
Development and Labs>> Textbook are compounded with teaching demo modules separately. If you are
interested in any of these demo modules please contact Embest Inc.
2
Embedded Systems Development and Labs; The English Edition
This book is a Lab manual and is part of the “Embedded System Development and Application” course series.
This Lab manual is based on the Embest ARM Labs System development platform hardware, which uses an
ARM processor as its core. The Lab manual is a complete teaching and training tool for developing Embedded
Systems. The book contains 22 Labs that include: Labs for the embedded software development fundamentals;
Labs for basic interfaces; Labs for human-machine interface; Labs for communication and audio interfaces;
Labs for uC/OS-II embedded real-time operating system porting and application; etc. This book offers many
examples for the embedded system learners. The Labs form an embedded system teaching or training tool and
are introduced in a gradual manner from simple to complex applications that are close related to the engineering
world. This book is accompanied by a free CD that contains the Embest IDE Pro Education Version software
produced by Embest Inc.
This book can be used as a Lab teaching material for embedded and real-time embedded systems at
undergraduate or graduate level with majors in Commuter Science, Computer Engineering, Electrical
Engineering; or for professional engineers.
3
Embedded Systems Development and Labs; The English Edition
About the Editor of the English Version of the Embedded System Development and Labs
Radu Muresan is the editor of the English version of the “Embedded System Development and
Labs” book offered first in Chinese by Embest as an accompaniment book to their ARM
development platform. Radu Muresan has a PhD in Electrical and Computer Engineering from the
University of Waterloo Canada and is currently an assistant professor at the University of Guelph
Canada. He is currently teaching the Real-Time Systems Design course in the School of
Engineering using the “Embedded System Development and Labs” book and the Embest
development platform and tools.
4
Embedded Systems Development and Labs; The English Edition
FOREWORD
5
Embedded Systems Development and Labs; The English Edition
software development in the last few years; another is the SoC. RTOS can be run in a dependable, effaceable
and affordable way. Most of the RTOS are expensive. As a result, some open sourced RTOS such as uc/OS-II,
ucLinux are being chosen by many users. These open sourced RTOS are also suitable as teaching tools. The
RTOS functionality and principles are relatively complex. Anyone who is interested in the RTOS research or
development, please refer to related books in the field.
Embedded systems based on embedded processor are characterized by small size, lightweight, low cost and
high performance. The largely used 32-bit microprocessors are ARM from ARM Ltd, Alpha from Compaq,
PA-RISE from HP, Power-PC from IBM, MIPS from MIPS Technologies Inc., SPARC from Sun etc.
ARM processors have merits of high performance, low power consumption, low cost, etc. ARM processors are
the most widely used microprocessors amongst the 32 bit and 64 bit microprocessors.
In the early 90s, the semiconductor industry formed a production chain that combined the design industry,
manufacture industry, packaging and testing industry. Some real semiconductor companies were greatly
developed and some fabless (chipless) companies also emerged. The Advanced RISC Machines (ARM), is the
most successful company based on the fabless chipless mode. ARM doesn’t produce or sale chips but provides
high performance IP cores that are being sold to authorized semiconductor companies.
Let’s look back to the development history of ARM technologies. At the time when ARM7 system architecture
(system architecture v3) was just been accepted and applied, the embedded microprocessor market was
overwhelmingly occupied by 8-bit and 16-bit microprocessors. However these microprocessors can’t meet the
requirements of developing high-end applications such as mobile phones, modems, etc. These high-end
products needed the 32-bit microprocessors processing power and higher programming code density than the
16-bit CISC processors. In order to meet these requirements, a T variety of ARM architecture was developed.
This T variety is called 16-bit Thumb Instruction Set. Thumb technology is one of the best characteristics of
ARM technology. The ARM7TDMIT (system architecture v4T) is the first microprocessor that supports Thumb
instruction set. ARM7TDMIT’s work mode can be switched to the Thumb working state. The 32-bit processor
can be run with 16-bit Thumb instruction set. So, thumb is a bridge between the 16-bit older system and the
32-bit new system. ARM architecture provided higher performance processor solutions to the users who were
looking for higher performance processors. These features greatly increased the embedded development as well
as ARM technology. The 16-bit microprocessors were not developed as people expected. The reason was
complicated. Maybe one of the reasons was that the 32-bit ARM processors provided higher performance and
lower price than the 16-bit processors and enabled the high-end embedded applications to jump to the new
32-bit generation.
Many semiconductor companies have accepted the ARM processor production development. There are more
than 100 IT companies that are currently using the ARM processors. Among them 19 of the 20 largest
semiconductor companies are developing chips based on the ARM architecture. These semiconductor
companies include TI, Philips, Intel etc. The excellent processor performance and the punctual marketing
enabled ARM to get tremendous resources. These resources greatly accelerated many kinds of system chips
developed for different applications. ARM has already established its lead position in the embedded
technologies and the ARM technologies are being widely used. ARM has gained great success in the field of
high performance embedded applications and the number one position in 32-bit embedded applications in the
world. In 2002, ARM processors occupied 79.5% of 32-bits and 64-bit microprocessor market in the world.
There were 20 billion ARM cores used by 2002. Nowadays, ARM processors are almost in everybody’s pocket
6
Embedded Systems Development and Labs; The English Edition
because almost all of the mobile phones, PDAs are developed based on ARM cores. As a result, in order to keep
up with the modern embedded technologies, people need to study the embedded development technologies that
are based on 32-bit ARM processors and also need to study its development environment and platform
technologies.
If integrated circuit and related technologies are the drivers of PC development that have increased the IT
technologies in the last twenty years, we could say that, besides the PC technologies, the portable, mobile and
Internet related embedded Internet information processing devices will be the main drivers that will enable a
Post-PC time becomes true in the next few decades. Currently the embedded Internet is merely limited to some
applications such as mobile business, intelligent electronic home devices, control and intelligent devices etc.
With the development of related technologies, embedded technology will be developed more and more at an
unimaginable speed with more complex applications. The area of embedded applications will be expanded and
the embedded systems and applications will be more valuable to the society.
Currently the Wintel (Microsoft an Intel federation established at early 90s) has dominated the computer
industry. With the development of information technology and network technology, the embedded technology
will make this monopoly not exist in the Post-PC time. Embedded System will be the main portion of non-PC
devices.
7
Embedded Systems Development and Labs; The English Edition
In order to coordinate with the course teaching and Lab teaching, we developed Multimedia Demo Modules for
the <<Embedded System Development and Applications>> and << Embedded System Application
Development and Labs>> courses. As a start point, we will continually change or add new course textbooks, lab
textbooks or multimedia demo modules based on real practical teaching techniques and the evolution of related
technologies.
This set of textbook combined with class teaching and lab teaching, provides a solution for students to master
embedded system development technologies based on ARM. The tools used in the ARM embedded application
development include the Integrated Development Environment (IDE), the Embedded Real-Time Operating
System, the evaluation board, the JTAG emulator, and other auxiliary tools. Generally, an Integrated
Development Environment (IDE) with its basic functions is the only nedded tool for embedded system
development. Others tools are optional.
The major IDEs used in the world include: SDT and ADS from ARM, Multi2000from GreenHill, Embest IDE
for ARM from Embest Inc, etc. The emulators used are Muti-ICE from ARM and ARM JTAG Emulater from
Embest Inc.
SDT and ADS is the IDE produced by ARM Ltd in its early state (discontinued). The S3C series chips from
SAMSUNG are the most widely used ARM based microprocessors. Embest Inc has developed the Embest
ARM Development board based on the S3C44B0 chip. This development board has memory, I/O, digital LCD
display, touch screen, keyboard, IIS, Ethernet interface, USB interface IIC interface, advanced extension
including IDE hard disk, CF card, flash disk etc. The Embest software and hardware tools are complete, reliable
8
Embedded Systems Development and Labs; The English Edition
and easy to use. These qualities are most needed in an university environment and made us use these tools for
our embedded based courses.
NOTE that other microprocessor and interfacing courses and textbooks can provide the basic
background for using the Embest development system.
9
Embedded Systems Development and Labs; The English Edition
Due to the fact that the translation draft was sort of word by word translation there are still English and technical
errors throughout the book. I have issued this version so the students can perform the required labs for my
Real-Time System Design course. I am still working on editing and updating the book and I hope to produce a
better version soon. Also, I am planning to produce an Embedded Real-Time system design text book that can
accompany this lab manual. However, I believe that this lab book is an excellent tool for teaching embedded
systems based on the ARM architecture. I have used other IDEs and I can say that the Embest engineers have
developed an excellent product. I want to congratulate the Embest engineers for putting together this product.
10
Embedded Systems Development and Labs; The English Edition
PREFACE
Theory teaching and Lab teaching are two important parts of the modern advanced education. Lab course is an
important part in the teaching process. This book is the Lab manual of the Embedded System Development
Course Series that provides teachers and students with complete embedded system training tools based on the
ARM architectures. In this Lab manual, we focus mainly on developing complete embedded applications using
the Embest development system. The applications provide the software and hardware details of the designs. We
integrated complex embedded system application sample modules, porting of embedded operating systems, etc.
Using this manual the students can learn not only the basics of the embedded system development, but also can
learn how to develop complex interface modules that apply to real world applications.
The following outlines the content of the chapters:
Chapter One: An overview of embedded system development, embedded system IDE, ARM embedded
development system, embedded study, etc.
Chapter Two: Embest embedded IDE for ARM, Embest ARM development system and Embest JTAG
emulator.
Chapter Three: Basic Labs of embedded software development based on ARM including: ARM basic
instruction set, Thumb instruction set, assembly programming, ARM processor mode switching, embedded C
programming, C and assembly language mix programming, overview of programming. (This chapter provides
the basic knowledge of embedded software development, basic programming skills, usage of IDE)
Chapter Four: Labs that target basic peripheral interfacing in embedded systems. The chapter includes
applications using memory, I/O interface, interrupts, serial communication, real-time clock and simple digital
LED interface.
(These Labs teach the student the basic principles of peripheral interfacing in embedded systems)
Chapter Five: Complex applications that introduce the human-machine interfacing. This chapter includes a
Lab using the LCD display, a Lab using the keyboard control, a Lab using the touch screen control.
(These Labs are more complex, difficult and closer to the real engineering applications. These labs require good
skills in using the Embest development system)
Chapter Six: Complex labs for developing applications using communication interfacing and IIS voice
interfacing. This chapter includes a Lab of IIC serial communication bus, a Lab of Ethernet communication and
a Lab of IIS voice bus interface communication.
(Chapters 4, 5, and 6 can prepare the students to develop applications using various interfaces and device
development that target real world applications.)
Chapter Seven: Introduces the uC/OS-II real-time operating system, porting and real-time application
development based on the Embest tools.
(Through the Labs of this chapter, the students will learn how to port uC/OS-II to the ARM processor and how
to build simple real-time applications based on the uC/OS-II kernel. They will learn the porting steps of the
uC/OS-II kernel to the ARM7 microprocessor, the boot flow of the uc/OS-II, the task management, the
inter-task communication, the synchronization and the memory management under uc/OS-II kernel.)
11
Embedded Systems Development and Labs; The English Edition
The CD attached to this book is IDE Pro, a free educational version of the IDE software that Embest Inc
provides to the readers of this book. The readers can install this software and edit, compile and debug the sample
programs on a software target emulator. After this software is installed, the readers can find the basic Lab
sample software of Chapter 3 of this manual in the “\EmbestIDE\Examples\S3CEV40” directory. To run the rest
of the sample programs of the manual the readers need to purchase the full version of the Embest IDE, the
Embest development board and ICE emulator. The students should also study the embedded Lab development
system course that introduces computer interfacing, computer application software development, computer
operatimg systems, applied electronic technology, network communication, etc.
This lab manual can be used as a reference book for embedded system development based on ARM. There are
many real-time operating systems (RTOS) for embedded applications based on 32b-bit systems (RTOS such as
VxWorks, Windows CE, Palm, uClinux, uC/OS, etc). We have selected the uC/OS since this kernel is fully
documented and is an excellent tool for learning to develop real-time embedded applications.
This manual together with the Embest development system can be used in teaching undergraduate and graduate
courses in embedded systems design.
12
Embedded Systems Development and Labs; The English Edition
13
Embedded Systems Development and Labs; The English Edition
14
Embedded Systems Development and Labs; The English Edition
15
Embedded Systems Development and Labs; The English Edition
16
Embedded Systems Development and Labs; The English Edition
17
Embedded Systems Development and Labs; The English Edition
18
Embedded Systems Development and Labs; The English Edition
19
Embedded Systems Development and Labs; The English Edition
Serial port, network port and USB port are also the communication channels of ICE. ICE can emulate high
speed ARM processor. ICE is expensive and normally used in hardware development. It is seldom used in
software development.
1.2.2 Software Emulator
Software Emulator can partly emulates the target hardware. It is normally an instruction set emulator. Software
emulator can only be used as a primary debug tool because its function is limited and can’t completely emulate
the real hardware.
1.2.3 Evaluation Board
The evaluation board is also called a development board. It is useful for the developers. Experienced engineers
can also make their own development board. A good development board has complete documentation, hardware
and software implementations, schematic, sample programs, source code, etc for development references.
1.2.4 Embedded Operation System
Embedded real time operation system (RTOS) provides memory management, task management and resource
management, etc. RTOS can save a lot of troubles in complicated applications. But if the application is not
complicated, embedded systems can run without real time operation systems.
20
Embedded Systems Development and Labs; The English Edition
21
Embedded Systems Development and Labs; The English Edition
22
Embedded Systems Development and Labs; The English Edition
23
Embedded Systems Development and Labs; The English Edition
24
Embedded Systems Development and Labs; The English Edition
25
Embedded Systems Development and Labs; The English Edition
26
Embedded Systems Development and Labs; The English Edition
27
Embedded Systems Development and Labs; The English Edition
29
Embedded Systems Development and Labs; The English Edition
28
Embedded Systems Development and Labs; The English Edition
30
Embedded Systems Development and Labs; The English Edition
31
Embedded Systems Development and Labs; The English Edition
The following are the basic features of the S3CEV40 development board:
● Power supply: 5V power supply or USB power supply via PC, LED power status display, 500mA fuse.
● 1M x 16 bit Flash
● 4 x 1M x 16 bit SDRAM
● 4Kbit IIC bus serial EEPROM
● 2 serial ports: one is a simple interface port, another is a full interface port that can be connected to the
RS232 MODEM
● Reset switch
● Two interrupt buttons, two LEDs
● IDE hard disk interface
● LCD and TSP touch screen interfaces
32
Embedded Systems Development and Labs; The English Edition
33
Embedded Systems Development and Labs; The English Edition
34
Embedded Systems Development and Labs; The English Edition
Select “Next” to follow the installation steps. Type of Setup will show below in Figure 2-8.
After the installation, the system will prompt you to reboot the computer. After the computer is rebooted, an
icon of Embest IDE will be displayed on the desktop. Double click on this icon to run Embest IDE. When the
Embest IDE is first time started, the software will prompts to a registration dialog box as shown in Figure 2-9.
After you fill correctly the user information, click on the “Generate Key.dat” button. The software will generate
a key.dat file in the License subdirectory. Send the key.dat file to [email protected] via email. The user
35
Embedded Systems Development and Labs; The English Edition
will receive a License.dat file in 24 hours. Copy the License.dat file to the License subdirectory. Restart the IDE,
and the Embest IDE will work properly.
36
Embedded Systems Development and Labs; The English Edition
37
Embedded Systems Development and Labs; The English Edition
2. Memory System
The Lab system has one 1Mx16 Flash chip (SST39VF160) and a 4Mx16 SDRAM chip (HY57V65160B). The
flash chip interconnection diagram is shown in Figure 2-13. The pin nGCS0 of 44B0X microprocessor chip is
connected to the pin nCE of SST39VF160 flash chip. Because the flash chip is 16 bit, the address bus A1-A20
of 44B0X CPU is connected to the A0-A19 of the SST39VF160 flash chip. The memory space address of the
Flash is 0x000000-0x00200000.
The SDRAM circuit interconnection diagram is shown at Figure 2-14. The SDRAM has four banks. Each bank
has 1Mx16 bit. The address of the bank is decided by pin BA1 and BA0: 00 selects Bank0, 01 selects bank1, 10
selects Bank2, and 11 selects Bank3. The row address pulse RAS and the column address pulse CAS are used in
addressing each banks. The Lab system provides jumpers for the users to upgrade the capability of SDRAM up
to 4x2M x16 bit. The upgrade method is done by connecting the pin BA0, BA1 of SDRAM chip to the pins A21,
A22, A23 of CPU chip. The SDRAM will be the chip selected by a specified chip selection signal nSCS0 of the
CPU. The SDRAM memory space is 0x0C000000-0x0C8000000.
38
Embedded Systems Development and Labs; The English Edition
A(20..1) A(19..0)
D(15..0) DQ(15..0)
nGCS0 nCE
nOE nOE
nWE nWE
44B0X SST39VF160
FLASH
A(12..1) A(11..0)
D(15..0) D(15..0)
nSRAS nRAS
nSCAS nCAS
nSCS0 nCS
nOE nWE
DQM0 LDQM
DQM1 UDQM
A21 R1
A22 BA0
R2
44B0X R4 SDRAM
UNLOAD
4. Serial Interface
The serial interface of the circuit is shown in Figure 2-15. The Lab system provides two serial ports (DB9). One
is the main port UART1 that is used to communicate with the PC or the MODEM. Because the S3C44B0X
doesn’t provides the I/O modem interface signals DCD, DTR, DSR, RIC, the MCU general purpose I/O must be
used. The other serial interface is UART0 that has two wires RxD and TxD for simple data
receiving/transmitting. The UART1 port uses MAX3243E for voltage conversion. The UART0 uses
MAX3221E for voltage conversion.
39
Embedded Systems Development and Labs; The English Edition
GPE2 ROUT 3
RIN
D(7..0) D(7..0)
D- 2
A1 A0 USBPORT
D+ 3
nOE RE
44B0X USBN9603
nWE WE
X3 C1
nRESET 24MHz
RESET XOUT
EXINT0 INTR R1
C2
CS1
CS XIN
40
Embedded Systems Development and Labs; The English Edition
RTL8019AS a full duplex Ethernet controller that can be hot swapped. The followings are the features of this
Ethernet controller chip:
● Meet the standard of Ethernet II and IEEE802.3.
● Full duplexes send and receive at 10Mb/s.
● Internal 16KB SRAM for send/receive buffering. This buffer can reduce the speed requirements of the main
CPU.
● Support 8/16-bit data bus, 8 interrupt lines, and 16 I/O base address selections.
● Support UTP, AVI and BNC auto detection, support auto polar modification for the 10BaseT network
architecture.
● Four LED programmable output
● 100 pin PQFP package that minimized the size of the PCB board.
D(15..0) SD(15..0)
RTL8019AS has three work modes. If 93C46 is not used in the embedded application, the cost could be reduced
and the wiring. Thus the jumper work mode is normally used. The I/O address of the network card is decided by
IOS3, IOS2, IOS1 and IOS0. There are two RAMs that are integrated in the RTL8019. One is a 16KB from
0x4000 to 0x7FFF and another is a 32 bit from 0x0000 to 0x001F. The RAM is a paged memory with one page
of 256-bit. Generally the page 0 is called PROM for storing the networks card address that will be read when the
network card is reset. This Lab system doesn’t use 93C46, so the PROM is not used. In this case, the software
must specify a network address and write it to MAR0-MAR5. The 16KB RAM is used for receive/transmit
buffering where 0x4C00-0x7FFF is used as a receive buffer and 0x4000-0x4BFF is used as a send buffer.
7. IIS Interface
IIS is an audio bus interface. It is a standard interface that is used by SONY, Philips, etc. The IIS interface circuit
diagram is presented in Figure 2-18. The S3C44B0x’s IIS interface is connected to the Philips’ UDA1341TS
Digital audio CODEC. A MICROPHONE output channel and a SPEAKER phone input channel is available on
this chip. UDA1341 can convert the analog dimensional sound stereo to digital signal and convert digital signal
to analog signal. For the digital signal, this chip provides DSP functions for digital audio signal processing. In
applications, this chip can be used at MDs, CDs, Notebook computers, PCs, Digital Cameras, etc. The
41
Embedded Systems Development and Labs; The English Edition
S3C44B0X’s IIS port can be connected to the pin BCK, WS, DATAI, DATAO and SYSCLK of UDA1341TS.
The pins L3DATA, L3MODE and L3CLOOCK are the L3 bus of the UDA1341TX. This bus is used at
microprocessor input mode. The pins are microprocessor data line, microprocessor mode line and
microprocessor clock line. Microprocessor can configure the digital audio process parameter and system control
parameter via this bus interface. But S3C44B0X doesn’t have connections to this bus interface. This bus
interface could be extended via I/O port.
IISLRC WS VOUT
SPEAK
VOUT
IISD DAT
IISD DATA
IISCL BC
PA L3DAT VINL
Micropho
DQM L3MO VINR
DQM L3CLOCK
CODE SYSCL
44B0 UDA1341
Figure 2-18 IIS Interface Circuit Diagram
8. 8 segments LED
The lab system has an 8 segments LED shown in Figure 2-19. The low level signal lights the LED. The CPU
data bus DATA (0-7) drives the LED through 74LC573 driver. Its chip select signal is select by CPU’s nGCS1
and CS6, which is generated by the CODEC from 3 address wires (A20, A19, A18). The low data wires of CPU
determine the contents of the 8 segments LED.
Q0
D(7..0) D(7..0) Q1 DPY
Q2 a
Q3 f b
g
Q4
G Q5 e c
44B0X d
Q6
dp
Q7
CS6 1 2
A 74LCX573
42
Embedded Systems Development and Labs; The English Edition
ports (PF6, PF5, NXDACK0, NXDREQ0) are connected to ALE, CLE, R/B and CE port of K9F2080 separately.
The user can treat the solid-state hard disk and the USB port together as a U-disc. The user can also store his
program and data on the solid-state hard disk. The solid-state hard disk practical application includes:
● Stores the gathered data on the solid-state hard disk and upload these data to PC through USB for backup
and analysis purposes.
● Save certain system parameters in the solid-state hard disk, and make real-time revision when the system is
running. Protect data when electricity drops.
● When system source code quantity is extremely large, and unable to run in 2M FLASH memory, the system
source code can be stored in the solid-state hard disk. When the system is powered, a start up code in the
FLASH memory can load the code in the SDRAM. This function is extremely useful when running big
operation system applications.
D(7..0) I/O(7..0)
NXDACK0 R/B\
NXDREQ0 CE
PF6 ALE
PF5 CLE
nWE
WE
OR
CS2 RE
nOE
OR
44B0X K9F2808
43
Embedded Systems Development and Labs; The English Edition
small (about several hundred ohms), a low level is gained at EXINT2, which generates an interrupt signal to the
MCU. The MCU causes Q2, Q4 to be opened and Q1, Q3 to be closed through controlling I/O ports. AIN1 reads
X-axis coordinates, then closes Q2, Q4, and causes Q1, Q3 to pass. AIN0 reads Y-axis coordinates. When the
system reaches the coordinate value, Q4, Q2, Q3 are closed, Q1 is opened and the system returns to its original
state and waits for the next touch. TSP occupies 44B0X external interrup-EXINT2, as well as 4 general I/O port
(PE4-PE7).
VDD
Q3
PE5
VDD
AIN1
PE4 TSPX+
Q4
EXINT2 PE7
Q1
R TSPX-
PE6
Q2
VDD
44
Embedded Systems Development and Labs; The English Edition
R200
10K R201 R202 R203 U100
U101
14 7 10K 10K 10K 74HC541
VCC GND
L3 12 13 11 10 GND
6Y 6A Y8 GND
L2 10 11 12 9 A4
5Y 5A Y7 A8
L1 8 9 13 8 A3
4Y 4A Y6 A7
L0 6 5 14 7 A2 D7
3Y 3A Y5 A6 1N4148
4 3 D3 15 6 A1 L3
2Y 2A Y4 A5
2 1 D2 16 5 D8
1Y 1A R205 Y3 A4 1N4148
D1 17 4 L2
10K Y2 A3
74HC17 R204 D0 18 3
Y1 A2 L1 D9 4*4KEYBOARD
10K NGCS3 19 2 1N4148
G2 A1
20 1 GND
VDD33 VCC G1 L0 1
2
U13B D10 3
1N4148 4
74HC08 74HC08
7
U13C 4 5
10 6 6
EXINT18 5 7
9 8
13 CON7
14
11
U13D 12
VDD33
74HC08
VDD33
JTAG20
VDD33
2 1 VDD33
4 3
TDI TDI
6 5
TMS TMS
8 7
TCK TCK
10 9
GND
12 11
TDO TDO
14 13
nRESET nRESET
16 15
18 17
GND
20 19 R52 R53 R54 R55
10K 10K 10K 10K
VDD33
Figure 2-23 JTAG Interface Circuit Diagram
45
Embedded Systems Development and Labs; The English Edition
development board is powered by the power supply. D3 is the power-indicating lamp, which lights if the board
is powered. Moreover, the Ethernet port also has 4 status indicating lamps, which are: D5 for connection; D6 for
data receiving; D13 for data transmitting; D14 for auto-testing passed.
15. User Testing Area
The development board has a solder point matrix area for the users to do testing or circuit extension during the
process of using the Lab system or software development.
NGCS0 FLASH
NGCS6/NSCS0 SDRAM
0 0 0 CS1 USB
0 1 0 CS3
0 1 1 CS4 IDE
1 0 0 CS5
1 0 1 CS6 8-SEG
1 1 0 CS7 ETHERNET
1 1 1 CS8 LCD
46
Embedded Systems Development and Labs; The English Edition
2. I/O Ports
The I/O port A-G pin definitions are listed in Table 2-3 to Table 2-9.
47
Embedded Systems Development and Labs; The English Edition
48
Embedded Systems Development and Labs; The English Edition
49
Embedded Systems Development and Labs; The English Edition
50
Embedded Systems Development and Labs; The English Edition
51
Embedded Systems Development and Labs; The English Edition
(2) Provides dialogs for microprocessor/debug device selection and settings, configuration of debug information,
compiler/assembly/linker settings, etc.
(3) Provides Build menu and tool buttons and output build information the Build page in Output Window
(Figure 2-27).
2. Create a Project
A workspace consists of one or multiple projects. The steps of creating a project are the followings:
(1) Select File New Workspace, IDE will prompt a dialog for creating a new project. The dialog box is shown
in Figure 2-28.
(2) Fill in the project name, use the default directory or select another directory for saving the project.
(3) Click OK. A new project will be created. A new workspace with the same name as the project’s name will
also be created. Also for an existing workspace new projects can be added by right clicking the workspace name
in the Project Management Window.
52
Embedded Systems Development and Labs; The English Edition
53
Embedded Systems Development and Labs; The English Edition
Figure 2-30 Color Icon and Right Click to Select Active Project
2. Emulator Settings
54
Embedded Systems Development and Labs; The English Edition
Select Project Settings… The IDE will open a new dialog box. Select the “Remote” page shown in
Figure 2-32.
Figure 2-33 Embest Power ICE for ARM Emulator Download Speed Support
55
Embedded Systems Development and Labs; The English Edition
3. Debugging Settings
The debug related settings are shown in Figure 2-34. There are the following three options:
1) General
● Download file: Symbol file name and its directory. Symbol file includes debug information. Normally
symbol file is an elf format file or a coff format file.
● Action after connected: There are three ways for selection:
None -- No actions after the IDE connected to target.
Auto download – After the IDE is connected to the target, the file will be automatically
downloaded to the board.
Command script -- After the IDE is connected to the target, a script file will be executed first.
2) Download Settings
Download settings page is shown in Figure 2-35.
● Download file: Symbol file name and its directory. Symbol file includes debug information. Normally the
symbol file is an elf format file or a binary file. When download as an elf file the system will automatically
convert it into a binary file.
● Download verification: Automatically compare the downloaded file if it is the same as the original file.
● Download address: The downloaded file will be stored from this address.
● Execute program from:
Don’t care – After download the system’s PC (program counter) will not change.
Download address – After download the system will execute from this address.
56
Embedded Systems Development and Labs; The English Edition
Program entry point -- After download, the system will set the PC to the program entry point.
● Execute until: The last symbol the system will execute after the download.
57
Embedded Systems Development and Labs; The English Edition
4. Directory Settings
If users want to trace driver function library and programs in function library, select this item. Shown in
Figure 2-37.
58
Embedded Systems Development and Labs; The English Edition
5. Compiler Settings
The compiler settings are shown in Figure 2-38. All of the settings in this page will be displayed in the
“Compile Options” edit window. The users can manually edit the Compile Options but need to follow the
GNU rules.
a) Compiler General Settings
The compiler general setting is shown in Figure 2-38.
● Include Directory – header files directory.
● Object files location – the directory of object files.
● Preprocessor Definitions – Define the pre-compile micros.
59
Embedded Systems Development and Labs; The English Edition
60
Embedded Systems Development and Labs; The English Edition
61
Embedded Systems Development and Labs; The English Edition
6. Assembler Settings
The assembler settings is shown in Figure 2-43. All the settings in this page will be displayed in the
“Assemble Options” window. The users can manually edit the “Assemble Options” but need to follow the
GNU rules.
a) Assembler General Settings
The assembler general settings are shown in Figure 2-43.
● Include Directory – header files directory.
● Object files location – the directory of object files.
● Predefinitions – Define the pre-compile macros.
62
Embedded Systems Development and Labs; The English Edition
63
Embedded Systems Development and Labs; The English Edition
64
Embedded Systems Development and Labs; The English Edition
7. Linker Settings
The linker settings are shown in Figure 2-47. All the settings in this page will be displayed in the “Link
Options” edit window. The users can manually edit the Link Options but need to follow the GNU rules.
a) Linker General Settings
The linker general setting is shown in Figure 2-47.
● Executable file – generate executable file.
● Library – generate library file.
● Linker script file – select this item only when executable output file is selected.
● Output file name – could be elf or lib file.
65
Embedded Systems Development and Labs; The English Edition
66
Embedded Systems Development and Labs; The English Edition
67
Embedded Systems Development and Labs; The English Edition
68
Embedded Systems Development and Labs; The English Edition
If a break point is set at a non-executable line, the break point is not valid. The non-valid break point is shown in
Figure 2-54.
When the program is executed, it will stop at the first break point as shown in Figure 2-55.
The user can select Debug Breakpoints… item, and a dialog box will list all the break points as shown in
Figure 2-56.
69
Embedded Systems Development and Labs; The English Edition
The user can click the “Modify” button to modify break point information as shown in Figure 2-57.
In this dialog, user can click the “Advanced” button to add condition information as shown in Figure 2-58.
70
Embedded Systems Development and Labs; The English Edition
2. Disassembly Window
The disassembly window is shown in Figure 2-59. Break points can be set in disassembly window.
71
Embedded Systems Development and Labs; The English Edition
3. Register Window
Register Windows is shown in Figure 2-60. It is used to display and modify the values of the registers of the
target microprocessor and peripheral devices.
Click on a register name, the name and the value of the register will be displayed at the top of the window. The
user can modify the register value here as shown in Figure 2-61.
72
Embedded Systems Development and Labs; The English Edition
4. Memory Window
The memory Window is used to display and modify the content of memory. The display will be started from the
address indicated by the user. The Memory Window is shown in Figure 2-63.
The user can modify the address from the pull down menu at the top of the Memory Window. The pull down
menu can record 10 start addresses as shown in Figure 2-64.
73
Embedded Systems Development and Labs; The English Edition
6. Variable Window
Select View Debug Window Variables and the Variable Window will be open. The Variable Window is used
to display the values of global or local variables as shown in Figure 2-66.
74
Embedded Systems Development and Labs; The English Edition
Double click on any function in the function list. The IDE will go to the source code of this function as shown in
Figure 2-68.
75
Embedded Systems Development and Labs; The English Edition
76
Embedded Systems Development and Labs; The English Edition
● Supports most of flash products such as ATMEL AM29 series, Intel 28 series and SST 29/39/49 series, etc.
● Supports flash empty checking, erasing, programming, verifying files, protecting, upload operations, etc.
● All the flash operation can be located to specific sectors.
● Support 8-bit, 16-bit, 32-bit flash visit width.
● Support one chip, two chips and four chips programming. As a result the program file doesn’t need to be
separated.
2. Other Characters of Flash Programmer
● The programming configuration data can be saved.
● Can read registers before program and test the target.
● Can specify the individual sectors.
● Simple and direct microprocessor register configuration interface.
77
Embedded Systems Development and Labs; The English Edition
78
Embedded Systems Development and Labs; The English Edition
which version is being referred to, you use names of the form: R13_<mode>, R14_<mode>. Where <mode> is
the appropriate one of usr, svc (for Supervisor mode), abt, und, irq and fiq. Register R13 is normally used as a
stack pointer and is also know as the SP. In the ARM instruction set, this is by convention only, as there are no
defined instructions or other functionality which use R13 in a special-case manner. However, there are such
instructions in the Thumb instruction set.
Each exception mode has its own banked version of R13, which should normally be initialized to point to a
stack dedicated to that exception mode. On entry, the exception handler typically stores to this stack the values
of other registers to be used. By reloading these values into the registers when it returns, the exception handler
can ensure that it does not corrupt the state of the program that was being executed when the exception
occurred.
Register R14 (also, known as the Link Register or LR) has two special functions in the architecture:
• In each mode, the mode’s own version of R14 is used to hold the subroutine return address. When a
subroutine call is performed by a BL or BLX instruction, R14 is set to the subroutine return address.
The subroutine return is performed by copying R14 back to the program counter.
• When an exception occurs, the appropriate exception mode’s version of R14 is set to the exception
return address (offset by a small constant for some exceptions). The exception return is performed in a
similar way to a subroutine return, but using slightly different instructions to ensure full restoration of
the state of the program that was being executed when the exception occurred.
Register R14 can be treated as a general-purpose register at all other times.
C) Register R15 holds the Program Counter (PC). It can often be used in place of the general-purpose registers
R0 to R14, and is therefore considered one of the general-purpose registers. However, there are also many
instruction-specific restrictions or special cased about its use. These are noted in the individual instruction
descriptions. Usually, the instruction is UNPREDICTABLE if R15 is used in a manner that breaks these
restrictions.
2. Memory Format
The ARM architecture uses a single, flat address space. Byte addresses are treated as unsigned numbers,
running from 0 to 232 - 1. The address space is regarded as consisting of 230 32-bit words, each of whose
address is word-aligned, which means that the address is divisible by 4. The word whose word-aligned
address is A consists of the four bytes with addresses A, A+1, A+2, and A+3. In ARM architecture version
4 and above, the address space is also regarded as consisting of 231 16-bit halfwords, each of whose
address is halfword-aligned.
• In a little-endian memory system: a byte or halfword at a word-aligned address is the least significant
byte or halfword within the word at that address; a byte at a halfword-aligned address is the least
significant byte within the halfword at that address.
• In a big-endian memory system: a byte or halfword at a word-aligned address is the most significant
byte or halfword within the word at that address; a byte at a halfword-aligned address is the most
significant byte within the halfword at that address.
79
Embedded Systems Development and Labs; The English Edition
rules should be following when programming. For the usage of as, gcc and ld, please refer to the electronic
document ProgRef.chm of the Embest IDE. Following presents some basic knowledge:
● The program entry point is “_start”. The default start address of text segment is 0x8000;
● “as” is often used as a pseudo operator.
1) . equ
.equ can be used to define a symbol such as a variable, a value based on a register, a label in the program, etc.
Syntax Format:
.equ symbol, expr
expr can be an address value of a register, a 32-bit address variable or a 32-bit variable.
symbol can be a character name of expr defined by .equ.
Example:
.equ Version, “0.1”
3) .text
The .text pseudo operator tells the compiler to put the compiled code to start from .text of the code
section or subsection.
Syntax Format:
.text {subsection}
Example:
.text
4) .end
.end is the end notation of the assembly file. The code after this notation will not be processed.
Syntax Format:
.end
3.1.5 Lab 1 Operation Steps
1. Lab A
(1) Create a New Project:
Run the Embest IDE and select File->New Workspace menu item. A new dialog window will pop up. Input the
contents shown in Figure 3-1.
80
Embedded Systems Development and Labs; The English Edition
Click OK button and a new project will be created. A new workspace will also be created using the same name
with the project. In the work space window, the new workspace and project will be opened by the IDE.
Note: In order to add a new project to the workspace right click on the “Workspace ‘name’: n project(s)” that
appears in the left window after a workspace ‘name’ is created. Normally, n represents the total number of
projects that are currently in the workspace. In order to build your new project you have to activate the project.
(2) Create a Source File:
Select File New and a new editor window without a specific title will appear. The input cursor will be at the
first line of the window. Input the sample source code asm_a.s. After the edition of the source file is finished
save the file as asm_a.s in the project directory.
(3) Add a Source File to the Project. First click project source then do the followings:
Select Project Add To Project->Files or right click the project name in the project window. A file selection
dialog will appear. Select the file asm_a.s that has just been created.
(4) Basic Settings:
Select Project Settings… or press Alt+F7. The project settings dialog will open. Select the “Processor” page
shown in Figure 3-2. Set the target board processor as arm7.
81
Embedded Systems Development and Labs; The English Edition
82
Embedded Systems Development and Labs; The English Edition
Select “Debug” page to set the debug module shown in Figure 3-5.
Notice: The setting of symbol file should be the same as the download file. The user can copy the system default
output file setting from the “Linker” page; the download address of the Lab 1 is 0x8000 that is the start address
of the text segment used by GNU as assembler. Because the “Assembler” and “Linker” page doesn’t need
setting, the default values are used. So the start address of text segment is started from 0x8000.
(7) Select Debug Remote Connect. Select Debug Download. Open the “Register” window by clicking the
Register window in the tool bar.
(8) Open the “Memory” window; watch the content in the address 0x8000-0x801F and the content in the
address 0xFF0-0xFFF.
(9) Single step to execute the program and watch and record the values in the memory.
(10) Watch the program run and study the related technical details. Get a good understanding of the usage of the
ARM instructions.
(11) After understanding and mastering the Lab A, do the exercises at the end of the Lab 1.
83
Embedded Systems Development and Labs; The English Edition
3. Lab B
(1) Right click the mouse on the Workspace in the project management window and select “Add New Project to
Workspace…”
(2) Refer to Lab A, build project sam_b.
(3) Refer to Lab A, finish the object code generation and debugging.
(4) After understanding and mastering the Lab A, do the exercises at the end of the Lab 1.
3.1.6 Sample Programs of Lab 1
1. Lab A Sample Program
84
Embedded Systems Development and Labs; The English Edition
Executing the above program step your register window and memory window will show how the values of the
registers and memory locations change when each instruction execute. For example, stepping through the above
program the following figures show the content of the windows:
85
Embedded Systems Development and Labs; The English Edition
Sep-by-step execution
86
Embedded Systems Development and Labs; The English Edition
3.1.7 Exercises
(1) Write a program to write the values 1-8 into R4-R11. Every time when you write this value, save the content
of R4-R11 to SP. The initial value of SP should be 0x800. At the end, use the LDMFD instruction to clear
R4-R11 to 0.
(2) Modify the value of x, y in this Lab and watch the results in the debug windows.
87
Embedded Systems Development and Labs; The English Edition
88
Embedded Systems Development and Labs; The English Edition
3) Other Bits
Other bits in the program status registers are reserved for future expansion. In general, programmers must take
care to write code in such a way that these bits are never modified. Failure to do this might result in code which
has unexpected side-effects on future versions of the architecture.
Syntax Format:
LDR <Rd>, =<expression>
Where “expression” is a 32 bit variable that needs to be read; “Rd” is the target register.
Example:
LDR r1,=0xff
LDR r0,=0xfff00000
(2) ADR
89
Embedded Systems Development and Labs; The English Edition
ADR can read a value into a register from an address stored in the PC or other general register. The assembler
will replace the ADR with a suitable instruction, ADD or SUB.
Syntax Format:
ADR <register><label>
“register” is the target register. “label” is an expression based on a PC address or a register.
Example:
Label1:
MVO r0,#25
ADR r2,label1
(3) .ltorg
.ltorg is used to generate a word aligned address for the following segment of code (generally is .text segment).
Syntax Format:
.ltorg
2. Lab B
(1) Reter to 3.1 ARM Instruction Lab 1 and sample programs, add new project to the current work apace.
(2) Refer to the steps in Lab A, finish the object code generation and debugging.
(3) After understanding and mastering the Lab B, do the exercises at the end of the Lab 2.
90
Embedded Systems Development and Labs; The English Edition
91
Embedded Systems Development and Labs; The English Edition
3.2.7 Exercises
(1) Open the boot file in the Example directory (C:\EmbestIDE\Examples\Samsung\S3CEV40). Watch the
programming of reset exception, the usage and functions of .ltorg.
(2) Build a project and write your own assembly program. Use the LDR, STR, LDMIA and STMIA to write data
to a section of consequent memory and watch the results.
92
Embedded Systems Development and Labs; The English Edition
ARM cores start up, after reset, executing ARM instructions. The normal way they switch to execute Thumb
instructions is by executing a Branch and Exchange instruction (BX, BLX). The format of the instructions is BX
| BLX Rm. The branch target is specified in the Rm register. Bit[0] of Rm is copied into the T bit in the CPSR
and bits[31:1] are moved into the PC:
a) If Rm[0] is 1, the processor switches to execute Thumb instructions and begins executing at the address
in Rm aligned to a half-word boundary by clearing the bottom bit.
b) If Rm[0] is 0, the processor continues executing ARM instructions and begins executing at the address
in Rm aligned to a word boundary by clearing Rm[1].
Other instructions which change from ARM to Thumb code include exception returns, either using a special
form of data processing instruction or a special form of load multiple register instruction. Both of these
instructions are generally used to return to whatever instruction stream was being executed before the exception
was entered and are not intended for deliberate switch to Thumb mode. Like BX, these instructions change the
program counter and therefore flush the instruction pipeline.
Note: The state switching between Thumb and ARM doesn’t change the processor modes and contents of the
registers.
ARM processor can be switched between the two working states.
93
Embedded Systems Development and Labs; The English Edition
Syntax Format:
.code [16|32]
2) .thumb
as same as .code 16.
3) .arm
94
Embedded Systems Development and Labs; The English Edition
4) .align
Alignment method: Add filling bits to make the current address meet the alignment.
Syntax Format:
.align {alignment}{,fill}{,max}
alignment: the alignment method, possibly 2 xxx, default is 4.
fill: contents of filling, default is 0.
max: maximum number of filling bits. If the number of filling bits exceeds the max, the alignment will not
process.
Example:
.align
stop:
B stop
doadd:
ADD r0, r0, r1 /* Subroutine code */
MOV pc, lr /* Return from subroutine. */
95
Embedded Systems Development and Labs; The English Edition
_start:
.arm /* Subsequent instructions are ARM header */
MOV sp, #0x400 /* set up user_mode stack pointer (r13) */
ADR r0, Tstart + 1 /* Processor starts in ARM state, */
BX r0 /* so small ARM code header used */
/* to call Thumb main program. */
.thumb /* Subsequent instructions are Thumb. */
Tstart:
LDR r0, =src /* r0 = pointer to source block */
LDR r1, =dst /* r1 = pointer to destination block */
MOV r2, #num /* r2 = number of words to copy */
blockcopy:
LSR r3,r2, #2 /* number of four word multiples */
BEQ copywords /* less than four words to move? */
copywords:
MOV r3, #3 /* bottom two bits represent number... */
AND r2, r3 /* ...of odd words left to copy */
BEQ stop /* No words left to copy ? */
wordcopy:
LDMIA r0!, {r3} /* a word from the source */
STMIA r1!, {r3} /* store a word to the destination */
SUB r2, #1 /* decrement the counter */
BNE wordcopy /* ... copy more */
96
Embedded Systems Development and Labs; The English Edition
stop:
B stop
.align
src:
.long 1,2,3,4,5,6,7,8,1,2,3,4,5,6,7,8,1,2,3,4
dst:
.long 0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0
.end
3.3.7 Exercises
Write a program; switch the state processor from ARM state to Thumb state. In ARM state, put the value
0x12345678 to R2; in Thumb state, put the value 0x87654321 to R2. Watch and record the value of CPSR and
SPSR. Analyze each of the flag bits.
97
Embedded Systems Development and Labs; The English Edition
they allow a fully protected operating system to be built. Most ARMs are used in embedded systems where such
protection is inappropriate, but the privileged modes can still be used to give a weaker level of protection that is
useful for trapping errant software.
The mode can be changed through software. Interrupts and exceptions can also change the mode of the
processor. When the processor is working in the user mode, the executing program can’t use some of the system
resources that are protected. In the privileged modes, the system resources can be freely used and the modes can
be changed as well. 5 of these modes are called exception modes:
FIQ (Fast Interrupt reQuest);
IRQ (Interrupt ReQuest);
Management (Supervisor);
Abort (Abort);
Undefined (undefined);
When a specific exception happens, the processor enters the related mode. Each mode has its own additional
registers to avoid the user mode to enter in some unstable state when the exception happens.
The supervisor mode is only available for the higher versions of ARM system architecture. The processor can’t
enter this mode by any exceptions. The supervisor mode has the same registers as the user mode. It is not limited
as the user mode because it is an authorized mode. It is used by the operation system task when the operation
system needs to use the system’s resources without using the same registers that the exception mode used. The
task states will be stable when the additional registers are not used when exceptions happen.
2. Program Status Register
98
Embedded Systems Development and Labs; The English Edition
The program status register CPSR and SPAR in 3.2.4 includes condition code flags, interrupt disable bit, current
processor mode bits, etc. Each exception mode has a Saved Program Status Registers (SPSR). When exceptions
happen, SPSR is used to save the status of CPSR.
The format of CPSR and SPSR is as following:
99
Embedded Systems Development and Labs; The English Edition
3) Other Bits
The other bits of status register are reserved for extension in the future.
100
Embedded Systems Development and Labs; The English Edition
9) Combined with the contents of the Lab and related technology materials, watch the program run. Get a deeper
101
Embedded Systems Development and Labs; The English Edition
SWI_Handler:
mov pc, lr
Reset_Handler:
102
Embedded Systems Development and Labs; The English Edition
MOV R8, #9
MOV R9, #10
MOV R10, #11
MOV R11, #12
MOV R12, #13
MOV R13, #14
MOV R14, #15
103
Embedded Systems Development and Labs; The English Edition
B Reset_Handler
.end
3.4.7 Exercises
Refer to the example of this Lab, change the system mode to user mode; compile and debug the program; watch
the result of the program execution.
Prompt: You can’t switch the mode directly from user mode to system mode. Use SWI instruction to switch to
supervisor mode first.
104
Embedded Systems Development and Labs; The English Edition
the comment. Every command that can be used in the debug window can also be used in the command script file
including the executing command SCRIPT. For the debug commands and detailed contents, please refer to
“Debug Command List” in the user guide document UserGuide.chm found on the CD that accompanies the
EmbestIDE ARM development system.
The commands in the script will be executed automatically in a sequential order.
Parameter: none
option: none
example: Go
105
Embedded Systems Development and Labs; The English Edition
parameter: none
option: none
example: refresh
option: none
parameter: none
option: none
example: reset
parameter: none
option: none
example: stop
106
Embedded Systems Development and Labs; The English Edition
107
Embedded Systems Development and Labs; The English Edition
3.5.7 Exercises
Write an assembly program. Use B or BL instruction to jump to the main () function of the C language program.
Use the ev40boot.cs as command script file. Watch the memory settings by executing this command script file.
108
Embedded Systems Development and Labs; The English Edition
● Understand the boot process of ARM7. Learn how to write simple C language programs and assembly
language boot program.
● Master the linker commands.
● Learn how to specify a code entry address and entry point.
● Learn the usage of Memory/Register/Watch/Variable windows.
Multiple exceptions can arise at the same time. As a result, a priority order in which the exceptions are handled
is defined:
High Priorities
1—Reset (highest priority)
2— Data abort
3—FIQ
4—IRQ
5—Prefetch Abort
6— SWI, undefined instruction (including absent coprocessor); this is the lowest priority
These are mutually exclusive instruction encodings and therefore cannot occur simultaneously. Reset starts the
109
Embedded Systems Development and Labs; The English Edition
processor from a known state and renders all other pending exceptions irrelevant. The most complex scenario is
where a FIQ, an IRQ and a third exception (which is not Reset) happen simultaneously. FIQ has higher priority
than IRQ and also masks it out, so the IRQ will be ignored until the FIQ handler explicitly enables IRQ or
returns to the user code. If the third exception is a data abort, the processor will enter the data abort handler and
then immediately enter the FIQ handler, since data abort entry does not mask FIQs out. The data abort is
remembered in the return path and will be processed when the FIQ handler returns. If the third exception is not a
data abort, the FIQ will be entered immediately. When the FIQ and IRQ have both completed, the program
returns to the instruction which generated the third exception, and in all the remaining cases the exception will
recur and be handled accordingly.
From the above, the reset entry is the start point of all the programs. So the first executed line of the program
will be executed at 0x00000000. Generally, the following code is used:
Reset_Handler:
LDR sp, =0x00002000
…
2. Linker Script
The Linker Script controls all the linking process. The Linker Script is written using the so called link command
language. The main functions of the linker scripts control how to place the programs to the output file and
control how to locate the output file in the memory. If needed, the linker script can implement other functions.
Most of the linker script files are simple. The simplest linker file has only one command line called SECTIONS.
The SECTION command controls the memory distribution of the output file (code).
SECTION command is powerful. For example, consider a program that consists of consists of code, initialized
data and un-initialized data are placed in “.text”, “.data” and “.bss” sections. The code of these sections needs to
be placed at addresses 0x10000 and 0x8000000, respectively. A simple linker script that performs the above
110
Embedded Systems Development and Labs; The English Edition
tasks is:
SECTIONS
{
. = 0x1000;
.text : { *(.text) }
. =0x8000000
.data : { *(.data) }
.bss : { *(.bss) }
}
The starts with the key word SECTIONS. Next is the body of the command encompassed by “{“ and “}”.
Within the command The first line inside the SECTIONS command sets the value of the special symbol “.”
which is the location counter. If you do not specify the address of an output section in some other way (other
ways are described later), the address is set from the current value of the location counter. The location counter
is then incremented by the size of the output section. At the start of the SECTIONS command, the location
counter has the value 0.
The second line defines an output section “.text”. The colon “:” is required syntax that may be ignored for now.
Within the brackets after the output section name, you list the names of the input section that should be placed
into this output section. The “*” is a wildcard which matches any file name. The expression *(.text) means
all .text input sections of all input files. Since the location counter is 0x10000 when the output section .text is
defined, the linker will set the address of the .text section in the output file to be 0x10000.
The remaining lines define the .data and .bss section in the output file. The linker will place the .data output
section at address 0x8000000. After the linker places the .data output section, the value of the location counter
will be 0x8000000 plus the size of the .data output section. The effect is that the linker will place the .bss output
section immediately after the .data output section in memory.
The linker will ensure that each output section has the required alignment, by increasing the location counter if
necessary. In this example, the specified addresses for the .text and .data section will probably satisfy any
alignment constraints, but the linker may have to create a small gap between the .data and .bss sections.
3. Embedded Assembly Code
The GCC support most of the basic assembly code. The following example shows how the assembly code can
be embedded in a C program. An assembly language notation will be inserted to the output stream when the
compiler meets this statement.
Example: A basic embedded assembly code.
111
Embedded Systems Development and Labs; The English Edition
Because the concept of initialization file in introduced, the entry file init.o should be specified as shown in
Figure 3-12. Please note that the init.o code must be downloaded at address 0x0. The other programs of the
project will be automatically downloaded to consecutive address locations. The init.s program initializes the SP
register (VERY IMPORTANT !!!) and jumps to the _main () function of the C program.
4) Refer to the former Labs and compile the project. Set the Linker page options as explained in Chapter 2. Also,
Figures 3-12a to 3-12d show the correct settings for this project. Build the c2 project. Set the debug options.
5) Download the program, open the Memory/Register/Watch/Variable windows, single step execute the
program and analyze the results. In the Watch window, input the variable I that need to be watched. Specially
watch and record the changes of the variable I.
6) Combined with the contents of the Lab and related technology materials, watch the program run. Get a deeper
understanding of the usage of the registers in different modes.
7) After understanding and mastering the lab, finish the Lab exercises.
112
Embedded Systems Development and Labs; The English Edition
113
Embedded Systems Development and Labs; The English Edition
Figure 3-12b. General options for compiler and linker settings. (Note: set the compiler options and do the
compile command before you set the linker options. The Linker script file is set to be ldscript)
Figure 3-12c. Image Entry Option and Code Generation Options for the Linker page. (Note: the init.o is the
select entry file. The c2.o file will be loaded at the end of the init.o code)
Figure 3-12d. The Debug page option settings. (Note: the download address is set to 0x0 since the init.o starts at
114
Embedded Systems Development and Labs; The English Edition
//------------------------------------------------------------------------------------------------
//Function Name: delay
//------------------------------------------------------------------------------------------------
void delay(void) //delay
{
int i;
for(i=0;i<=10;i++)
{
_nop_();
}
}
void delay10(void)
115
Embedded Systems Development and Labs; The English Edition
{
int i;
for(i=0;i<=10;i++)
{
delay();
}
}
//*----------------------------------------------------------------------------
//* Function Name : _start
//* Input Parameters : none
//* Output Parameters : none
//*----------------------------------------------------------------------------
__main()
{
int i=5;
for(;;)
{
delay10();
}
}
3. init.s source code
# *******************************************************
# * NAME : 44BINIT.S *
# * Version : 10.April.2000 *
# * Description: *
# * C start up codes *
# * Configure memory, Initialize ISR ,stacks *
# * Initialize C-variables *
# * Fill zeros into zero-initialized C-variables *
# *******************************************************
# Program Entry
#.arm
.global _start
.text
_start:
# --- Setup interrupt / exception vectors
B Reset_Handler
Undefined_Handler:
B Undefined_Handler
116
Embedded Systems Development and Labs; The English Edition
SWI_Handler:
B SWI_Handler
Prefetch_Handler:
B Prefetch_Handler
Abort_Handler:
B Abort_Handler
NOP /* Reserved vector */
IRQ_Handler:
B IRQ_Handler
FIQ_Handler:
B FIQ_Handler
Reset_Handler:
LDR sp, =0x00002000
#------------------------------------------------------------------------------
#- Branch on C code Main function (with interworking)
#----------------------------------------------------
#- Branch must be performed by an interworking call as either an ARM or Thumb
#- main C function must be supported. This makes the code not position-
#- independant. A Branch with link would generate errors
#------------------------------------------------------------------------------
.extern __main
.end
SECTIONS
117
Embedded Systems Development and Labs; The English Edition
{
. = 0x0;
.text : { *(.text) }
.data : { *(.data) }
.rodata : { *(.rodata) }
.bss : { *(.bss) }
}
3.6.7 Exercises
(1) Improve the exercise “ARM Assembly Instruction Lab 1” in 3.1. Define globe and local variables in the C
file. Use the linker script file in compiling and linking. Use the Disassemble all in the Tools menu to generate
objdump file. Watch the storage of code and variables in the target output file.
(2) In the above C language files, add embedded assembly language code. Implement read/write memory using
assembly code. Primarily master the usage of embedded assembly code.
118
Embedded Systems Development and Labs; The English Edition
119
Embedded Systems Development and Labs; The English Edition
120
Embedded Systems Development and Labs; The English Edition
int main()
{
int i;
int nTemp;
unsigned int random[10];
for( i = 0; i < 10; i++ )
{
nTemp = randomnumber();
random[i] = nTemp;
}
return( 0 );
}
# *******************************************************
# * NAME: 44BINIT.S *
# * Version: 10.April.2000 *
# * Description: *
# * C start up codes *
# * Configure memory, Initialize ISR ,stacks *
# * Initialize C-variables *
# * Fill zeros into zero-initialized C-variables *
# *******************************************************
# Program Entry Point, ARM assembly
#.arm
.global _start
.text
121
Embedded Systems Development and Labs; The English Edition
_start:
# --- Setup interrupt / exception vectors
B Reset_Handler
Undefined_Handler:
B Undefined_Handler
SWI_Handler:
B SWI_Handler
Prefetch_Handler:
B Prefetch_Handler
Abort_Handler:
B Abort_Handler
NOP /* Reserved vector */
IRQ_Handler:
B IRQ_Handler
FIQ_Handler:
B FIQ_Handler
Reset_Handler:
LDR sp, =0x00002000
#------------------------------------------------------------------------------
#- Branch on C code Main function (with interworking)
#----------------------------------------------------
#- Branch must be performed by an interworking call as either an ARM or Thumb
#- main C function must be supported. This makes the code not position-
#- independant. A Branch with link would generate errors
#------------------------------------------------------------------------------
.extern main
122
Embedded Systems Development and Labs; The English Edition
.global __gccmain
__gccmain:
mov pc, lr
.end
seedpointer:
.LONG seed
.DATA
.GLOBAL seed
seed:
.LONG 0x55555555
123
Embedded Systems Development and Labs; The English Edition
.LONG 0x55555555
# END
3.7.7 Exercises
Refer to the “sample source code” of Lab A in 3.3.6, improve the exercise program “C language program Lab2”
in 3.6. Use embedded assembly language to implement R1_R2=R0. Save the result in R0. When you debugging,
open the Register window, watch the changes R0, R1, R2 and SP registers before and after the embedded
assembly program run. Watch the content changes in ATPCS mapping registers.
124
Embedded Systems Development and Labs; The English Edition
Edit Windows; use the Disassembly Window to watch the execution of the program; use the Register Window
to watch the operation of the program and the status of the CPU; use Watch or Variable Windows to watch
variables of the program; use the Operation Console to execute special commands. With the additional right
click menu items, users can implement or find any part of the program, modify any errors during development
time or run time.
125
Embedded Systems Development and Labs; The English Edition
126
Embedded Systems Development and Labs; The English Edition
127
Embedded Systems Development and Labs; The English Edition
Figure 3-18 Select Setting the Output Format of the Target Code of C Programs
Figure 3-19 Select Setting the Output Format of the Target Code of Assembly Programs
4) Use elf2bin to convert the elf file into bin file. Compare the source code and objdump file in the IDE and get
a better understanding of the linking location of the source code.
128
Embedded Systems Development and Labs; The English Edition
5) Single step execute the ARM and Thumb mutual call disassembled programs, analyze the status changing
process of ARM core.
6) After understanding and mastering the lab, finish the Lab exercises.
2. entry.s
.equ count, 20
.global Thumb_function
.text
#.arm
mov r0, #count
mov r1, #0
mov r2, #0
mov r3, #0
mov r4, #0
mov r5, #0
mov r6, #0
loop0:
add r1, r1, #1
129
Embedded Systems Development and Labs; The English Edition
# thumb
.thumb
Thumb_Entry:
mov r0, #count
mov r1, #0
mov r2, #0
mov r3, #0
mov r4, #0
mov r5, #0
mov r6, #0
loop1:
add r1, #1
add r2, #1
add r3, #1
add r4, #1
add r5, #1
add r6, #1
sub r0, #1
bne loop1
bl Thumb_function
.end
3. random.s
130
Embedded Systems Development and Labs; The English Edition
.GLOBAL randomnumber
randomnumber:
# on exit:
# a1 = low 32-bits of pseudo-random number
# a2 = high bit (if you want to know it)
LDR ip, seedpointer
LDMIA ip, {a1, a2}
TST a2, a2, LSR#1 /* to bit into carry */
MOVS a3, a1, RRX /* 33-bit rotate right */
ADC a2, a2, a2 /* carry into LSB of a2 */
EOR a3, a3, a1, LSL#12 /* (involved!) */
EOR a1, a3, a3, LSR#20 /* (similarly involved!)*/
STMIA ip, {a1, a2}
MOV pc, lr
seedpointer:
.LONG seed
.global __gccmain
__gccmain:
mov pc, lr
.DATA
.GLOBAL seed
seed:
.LONG 0x55555555
.LONG 0x55555555
# END
4. thumb.c
extern void arm_function(void);
char arm[22];
char thumb[22];
131
Embedded Systems Development and Labs; The English Edition
{
int i, j, k;
k = 0;
for(i=0; i<time; i++)
{
for(j=0; j<1000; j++)
k++;
}
}
int Thumb_function(void)
{
int i;
char * p = "Hello from Thumb World";
arm_function();
delay(10);
for(i=0; i<22; i++)
thumb[i] = (*p++);
while(1);
}
3.8.7 Exercises
(1) Read 44binit.s boot file, try to understand every line of this program.
(2) Write an assembly program and a C Language program to implement transferring parameters from a C
mathematic function to an assembly mathematical function and return the result from the C function. Name the
new project as “smath”. Add the 44init.s to the project. Refer to the project settings in the basic Labs. Use the
ldscript linker script file in the “common” directory. After the compiling and linking, use the Embest tools to
disassemble all and elf2bin to convert and analyze the output file. Connect the software emulator and download
file at 0x0C000000 to start the debugging, tracing and program execution.
132
Embedded Systems Development and Labs; The English Edition
133
Embedded Systems Development and Labs; The English Edition
134
Embedded Systems Development and Labs; The English Edition
The format of Bus Width & Wait Control Register (BWSCON) is shown in Figure 4-2.
135
Embedded Systems Development and Labs; The English Edition
136
Embedded Systems Development and Labs; The English Edition
For the detailed definition of the above registers, please refer to S3C44B0X specification.
The 13 control registers are located at consequent memory addresses starting from 0x01C80000. As a result, the
instruction “stmia r0, {r1-r13}” writes the configuration data to the corresponding registers. The Embest
S3CEV40 memory (SROM/DRAM/SDRAM) address pin connection are shown in Table 4-9.
137
Embedded Systems Development and Labs; The English Edition
138
Embedded Systems Development and Labs; The English Edition
2. Circuit Design
The memory system of the development board includes a 1M×16bit Flash (SST39VF160) and a 4M×16bit
SDRAM (HY57V65160B). As shown in Figure 4-3, the Flash chip is enabled by the nGCS0 signal. The Flash
address space is from 0x00000000 ~ 0x00200000. As a result, the processor’s address bits A0-A19 are used.
Figure 4-4 presents the SDRAM connection diagram. The SDRAM memory is divided into 4 equal memory
banks of 1Mx16 bits. The BANK’s address is determined by BA1, BA0 pins (00 corresponds to BANK0, 01
corresponds to BANK1, 10 corresponds to BANK2, 11 corresponds to BANK3). Each bank uses the row
address pulse to select RAS and the column address pulse to select CAS to carry on the addressing. This
development board also has Jumpers that allow for memory update to 4×2M×16bit. For 8M SDRAM, R1 and
R3 are 0 ohms and R2 and R4 are empty. Namely, BA0, BA1 are connected separately to A21 and A22; both
10 10
row and column address wire width are A1~A11. As a result, the address space is 4×2 ×2 , (from 0x0C000000
~ 0x0C3FFFFF). For 16M SDRAM, R2 and R4 are 0 ohms and R1 and R3 are empty. Namely, BA0, BA1 are
connected to A22, A23, respectively; both row and column address wire width are A1~A12. The address space
11 11
is 4×2 ×2 , from 0x0C000000 ~ 0x0C7FFFFF. The SDRAM chip is selected by MCU through the chip select
signal nSCS0 and its address space is from 0x0C000000 ~ 0x0C8000000.
139
Embedded Systems Development and Labs; The English Edition
140
Embedded Systems Development and Labs; The English Edition
Have the 44init.s window active and compile the file by clicking on the Build >> Compile 44init.s. After this
build the project and reconnect and download the code to the board. Make sure that the ..\common\ev40boot.cs
file is present in the debug window of the project settings.
4) Open Memory1 window, key in the address 0x0C010000. Open Memory2 window, key in the address
0x0C010200.
5) Open Rwrams.s, set a break point at the line “LDR r2, =0x0C010000”. Open Rwarmc.c, set a break point at
the line “*ptr=0xAA55AA55;”.
6) Execute the program. The program will stop at the line “LDR r2, =0x0C010000”. Watch the date content in
the Memory1 window. Single step execute the program and watch the changes in Memory 1 window. According
to the program, master the method of visiting memory using assembly language.
7) When the program stops at the line “*ptr=0xAA55AA55;”, watch the content in the Memory2 window.
Single step execute the program and watch the changes in Memory2 window. According to the program, master
the method of visiting memory using C language.
8) After understanding and mastering the lab, finish the Lab exercises.
LDR r2,=RWBase
LDRH r3,[r2] /*// Read by half Word.*/
ADD r3,r3,#1
STRH r3,[r2],#2 /*// Write by half Word.*/
STRH r3,[r2]
LDR r2,=RWBase
LDRB r3,[r2] /*// Read by half Byte.*/
LDRB r3,=0xDD
STRB r3,[r2],#1 /*// Write by half Byte.*/
LDRB r3,=0xBB
STRB r3,[r2],#1
141
Embedded Systems Development and Labs; The English Edition
LDRB r3,=0x22
STRB r3,[r2],#1
LDRB r3,=0x11
STRB r3,[r2]
mov pc,lr /* The LR register may be not valid for the mode changes. */
char i;
unsigned char tmpb;
unsigned short tmph;
unsigned long tmpw;
*ptr = 0xAA55AA55;
142
Embedded Systems Development and Labs; The English Edition
Test_MEM();
Uart_Printf("\n Press any key to exit Memory Test.\n");
Uart_Getch();
void Test_MEM(void)
{
int i,step;
volatile char input_char;
Uart_Printf(
"\n ================= Memory Read/Write Access Test. ================= \n");
143
Embedded Systems Development and Labs; The English Edition
Uart_Printf("\n << CACHE >> Test. Y/y to continue,any key skip it.\n");
input_char = Uart_Getch();
if(input_char == 'Y' || input_char == 'y')
Test_CACHE();
}
144
Embedded Systems Development and Labs; The English Edition
4.1.7 Exercises
Write a program to read and write a consequent RAM memory space using assembly and C language.
145
Embedded Systems Development and Labs; The English Edition
Table 4-12 to Table 4-18 show the pin definitions of each port.
146
Embedded Systems Development and Labs; The English Edition
147
Embedded Systems Development and Labs; The English Edition
LED1
23 R95
NGCS4
24 R96
NGCS5
S3C44B0X LED2
47
VDD33
148
Embedded Systems Development and Labs; The English Edition
149
Embedded Systems Development and Labs; The English Edition
/***************************************************************************
* name: leds_on
* func: all leds on
* para: none
* ret: none
* modify:
* comment:
***************************************************************************/
void leds_on()
{
Led_Display(0x3);
150
Embedded Systems Development and Labs; The English Edition
/**************************************************************************
* name: leds_off
* func: all leds off
* para: none
* ret: none
* modify:
* comment:
*****************************************************************************/
void leds_off()
{
Led_Display(0x0);
}
/****************************************************************************
* name: led1_on
* func: led 1 on
* para: none
* ret: none
* modify:
* comment:
*****************************************************************************/
void led1_on()
{
led_state = led_state | 0x1;
Led_Display(led_state);
}
/*****************************************************************************
* name: led1_off
* func: led 1 off
* para: none
* ret: none
* modify:
* comment:
****************************************************************************/
void led1_off()
{
led_state = led_state & 0xfe;
Led_Display(led_state);
151
Embedded Systems Development and Labs; The English Edition
/*****************************************************************************
* name: led2_on
* func: led 2 on
* para: none
* ret: none
* modify:
* comment:
******************************************************************************/
void led2_on()
{
led_state = led_state | 0x2;
Led_Display(led_state);
}
/*****************************************************************************
* name: led2_off
* func: led 2 off
* para: none
* ret: none
* modify:
* comment:
******************************************************************************/
void led2_off()
{
led_state = led_state & 0xfd;
Led_Display(led_state);
}
152
Embedded Systems Development and Labs; The English Edition
{
led_state = LedStatus;
if((LedStatus&0x01)==0x01)
rPDATB=rPDATB&0x5ff;
else
rPDATB=rPDATB|0x200;
if((LedStatus&0x02)==0x02)
rPDATB=rPDATB&0x3ff;
else
rPDATB=rPDATB|0x400;
}
#endif
4.2.7 Exercises
Write a program to implement LED1 and LED2 display 00-11 in a loop.
153
Embedded Systems Development and Labs; The English Edition
154
Embedded Systems Development and Labs; The English Edition
2. Interrupt Sources
Among 30 interrupt sources, 26 sources are provided for the interrupt controller. Four external interrupt
(EINT4/5/6/7) requests are ORed to provide a single interrupt source to the interrupt controller, and two UART
error interrupts (UERROR0/1) use the ORed configuration.
NOTE: EINT4/5/6/7 share the same interrupt request line. Therefore, the ISR (interrupt service routine) will
discriminate these four interrupt sources by reading the EXTINPHD[3:0] register. EXTINPND[3:0] must be
cleared by writing a 1 in the ISR after the corresponding ISR has been completed.
Table 4-19
155
Embedded Systems Development and Labs; The English Edition
The interrupt controller generates the machine code for branching to the vector address of each interrupt source.
For example, if EINT0 is IRQ, the interrupt controller must generate the branch instruction which branches to
0x20 instead of 0x18. As a result, the interrupt controller generates the machine code, 0xea000000.
The user program code must locate the branch instruction, which branches to the corresponding ISR (interrupt
service routine) at each vector address. The machine code, branch instruction, at the corresponding vector
address is calculated as follows:
Branch Instruction machine code for vectored interrupt mode = 0xea000000 +((<destination address> - <vector
address> - 0x8)>>2)
Note: A relative address must be calculated for the branch instruction.
For example, if Timer 0 interrupt is to be processed in vector interrupt mode, the branch instruction, which
jumps to the ISR, is located at 0x00000060. The ISR start address is 0x10000. The following 32bit machine
code is written at 0x00000060. The machine code at 0x00000060 is:
156
Embedded Systems Development and Labs; The English Edition
The assembler usually generates the machine code automatically and therefore the machine code does not have
to be calculated as above.
ENTRY
b ResetHandler ; 0x00
b HandlerUndef ; 0x04
b HandlerSWI ; 0x08
b HandlerPabort ; 0x0c
b HandlerDabort ; 0x10
b . ; 0x14
b HandlerIRQ ; 0x18
b HandlerFIQ ; 0x1c
ldr pc,=HandlerEINT0 ; 0x20
ldr pc,=HandlerEINT1
ldr pc,=HandlerEINT2
ldr pc,=HandlerEINT3
ldr pc,=HandlerEINT4567
ldr pc,=HandlerTICK ; 0x34
b.
b.
ldr pc,=HandlerZDMA0 ; 0x40
ldr pc,=HandlerZDMA1
ldr pc,=HandlerBDMA0
ldr pc,=HandlerBDMA1
ldr pc,=HandlerWDT
ldr pc,=HandlerUERR01 ; 0x54
b.
b.
ldr pc,=HandlerTIMER0 ; 0x60
ldr pc,=HandlerTIMER1
ldr pc,=HandlerTIMER2
ldr pc,=HandlerTIMER3
ldr pc,=HandlerTIMER4
ldr pc,=HandlerTIMER5 ; 0x74
157
Embedded Systems Development and Labs; The English Edition
b.
b.
ldr pc,=HandlerURXD0 ; 0x80
ldr pc,=HandlerURXD1
ldr pc,=HandlerIIC
ldr pc,=HandlerSIO
ldr pc,=HandlerUTXD0
ldr pc,=HandlerUTXD1 ; 0x94
b.
b.
ldr pc,=HandlerRTC ; 0xa0
b.
b.
b.
b.
b.
b.
ldr pc,=HandlerADC ; 0xb4
NOTE: FIQ interrupt mode does not support vectored interrupt mode.
158
Embedded Systems Development and Labs; The English Edition
interrupt request is generated, the corresponding interrupt bit in INTPND will be set to 1. The interrupt service
routine must then clear the pending condition by writing '1' to the corresponding bit of I_ISPC/F_ISPC. When
several interrupt sources generate requests simultaneously, the INTPND will indicate all interrupt sources that
have generated an interrupt request. Even if the interrupt source is masked by INTMSK, the corresponding
pending bit can be set to 1.
If the INTMSK is changed in ISR (interrupt service routine) and the vectored interrupt is used, an INTMSK bit
cannot mask an interrupt event, which had been latched in INTPND before the INTMSK bit was set. To
eliminate this problem, clear the corresponding pending bit (INTPND) after changing INTMSK.
159
Embedded Systems Development and Labs; The English Edition
NOTE: In FIQ mode, there is no service pending register like I_ISPR, users must check INTPND register.
The priority-generating block consists of five units, 1 master unit and 4 slave units. Each slave
priority-generating unit manages six interrupt sources. The master priority-generating unit manages 4 slave
units and 2 interrupt sources. Each slave unit has 4 programmable priority source (sGn) and 2 fixed priority
sources (kn). The priority among the 4 sources in each slave unit is determined by the I_PSLV register. The
other 2 fixed priorities have the lowest priority among the 6 sources. The master priority-generating unit
determines the priority between 4 slave units and 2 interrupt sources using the I_PMST register. The 2 interrupt
sources, INT_RTC and INT_ADC, have the lowest priority among the 26 interrupt sources. If several interrupts
are requested at the same time, the I_ISPR register shows only the requested interrupt source with the highest
priority.
160
Embedded Systems Development and Labs; The English Edition
6. Circuit Description
As shown in Figure 4-6, the external interrupts EXINT6 and EXINT7 are used in this Lab. The button SB2 and
SB3 generate interrupts. When the buttons are pressed, EXINT6 and EXINT7 are connected to the ground and a
0V signal is present at these pins. This will initiate an interrupt request. After the CPU accepts the requests, the
corresponded ISRs are executed to implement LED1 and LED2 display. From the presentation of the interrupt
functionality, the EXINT6 and EXINT7 are using the same interrupt controller. As a result, the CPU will only
accept one interrupt request at one time. In another word, when SB2 is pressed, the CPU will not process the
EXINT7 interrupt routine that was generated by pressing SB7 until the EXINT6 interrupt routine is processed.
Please note this functionality in the operation of the Lab.
The 8-SEG LED display circuit is not given here. If needed, please refer to the “8-SEG LED Display Lab”
presented in Section 4.6.
LED1
23 R95
NGCS4
24 R96
NGCS5
LED2
VDD33 47
S3C44B0X
R111 SB2
EXINT6 1 3
2 4
R112 SB3
EXINT7 1 3
2 4
GND
161
Embedded Systems Development and Labs; The English Edition
4) Set a break point at the entry point of Eint4567Isr.c as shown in Figure 4-8. Execute the program; press SB2
or SB3, the program will stop at the break point. Double click the INTPND and I_ISPR; the register window
will be open. Watch the value changes in these registers. Watch the value change at bit21 before and after the
program executed.
5) Cancel all of the above break points. Set a break point at main() function shown in Figure 4-9. Execute the
program. When the program will stop at the break point, watch the value changes at bit21 of these two registers
again. Through these operations, understand the functions of INTPND and I_ISPR register in the interrupt
processing.
162
Embedded Systems Development and Labs; The English Edition
6) Cancel all the above break points. Execute the program, press SB2 or SB3. Watch the changes of LED1,
LED2 and 8-SEG LED on the target board.
7) After understanding and leaning the Lab, do the exercises at the end of the Lab.
ENTRY:
b ResetHandler /* for debug */
b HandlerUndef /* handlerUndef */
b HandlerSWI /* SWI interrupt handler*/
b HandlerPabort /* handlerPAbort */
b HandlerDabort /* handlerDAbort */
b. /* handlerReserved */
b HandlerIRQ
b HandlerFIQ
2. Interrupt Initialization
/*********************************************************************
* name: init_Eint
* func:
* para: none
* ret: none
163
Embedded Systems Development and Labs; The English Edition
* modify:
* comment:
**********************************************************************/
void init_Eint(void)
{
/* enable interrupt */
rI_ISPC = 0x3ffffff;
rEXTINTPND = 0xf; // clear EXTINTPND reg
rINTMOD = 0x0;
rINTCON = 0x1;
rINTMSK = ~(BIT_GLOBAL|BIT_EINT1|BIT_EINT4567);
/* PORT G */
rPCONG = 0xffff; // EINT7~0
rPUPG = 0x0; // pull up enable
rEXTINT = rEXTINT|0x22220020; // EINT1¡¢EINT4567 falling edge mode
rI_ISPC |= (BIT_EINT1|BIT_EINT4567);
rEXTINTPND = 0xf; // clear EXTINTPND reg
}
164
Embedded Systems Development and Labs; The English Edition
which_int = rEXTINTPND;
rEXTINTPND = 0xf; //clear EXTINTPND reg.
rI_ISPC |= BIT_EINT4567; //clear pending_bit
}
4.3.6 Exercises
(1) Get familiar with the S3C44B0X timer controller, the related registers and the principle of timer interrupt.
(2) Write a program and make usage of timer interrupt to implement LED1 and LED2 flashing every 1s.
UART Operation
165
Embedded Systems Development and Labs; The English Edition
The following sections describe the UART operations that include data transmission, data reception, interrupt
generation, baud-rate generation, loop back mode, infra-red mode, and auto flow control.
Data Transmission
The data frame for transmission is programmable. It consists of a start bit, 5 to 8 data bits, an optional parity bit
and 1 to 2 stop bits, which can be specified by the line control register (UCONn). The transmitter can also
produce the break condition. The break condition forces the serial output to logic 0 state for a duration longer
than one frame transmission time. This block transmit break signal after the present transmission word transmits
perfectly. After the break signal transmit, continuously transmit data into the Tx FIFO (Tx holding register in
the case of Non-FIFO mode).
Data Reception
Like the transmission, the data frame for reception is also programmable. It consists of a start bit, 5 to 8 data bits,
an optional parity bit and 1 to 2 stop bits in the line control register (UCONn). The receiver can detect overrun
error, parity error, frame error and break condition, each of which can set an error flag.
● The overrun error indicates that new data has overwritten the old data before the old data has been read.
● The parity error indicates that the receiver has detected an unexpected parity condition.
● The frame error indicates that the received data does not have a valid stop bit.
● The break condition indicates that the RxDn input is held in the logic 0 state for a duration longer than one
frame transmission time.
Receive time-out condition occurs when it does not receive data during the 3 word time and the Rx FIFO is not
empty in the FIFO mode.
Baud-Rate Generation
The baud rate divisor register (UBRDIVn) controls the baud rate. The serial Tx/Rx clock rate (baud rate) is
calculated as follows:
The divisor should be from 1 to (216-1). For example, if the baud-rate is 115200 bps and MCLK is 40 MHz,
UBRDIVn is:
166
Embedded Systems Development and Labs; The English Edition
Loop-back Mode
The S3C44BOX UART provides a test mode referred to as the loopback mode, to aid in isolating faults in the
communication link. In this mode, the transmitted data is immediately received. This feature allows the
processor to verify the internal transmit and to receive the data path of each SIO channel. This mode can be
selected by setting the loopback-bit in the UART control register (UCONn).
Break Condition
The break condition is defined as a continuous low level signal for more than one frame transmission time on
the transmit data output.
The divisor should be from 1 to (216-1). For example, if the baud-rate is 115200 bps and MCLK is 40 MHz,
UBRDIVn is:
167
Embedded Systems Development and Labs; The English Edition
= (int)(21.7+0.5) -1
= 22 -1 = 21
#ifdef __BIG_ENDIAN
#define rUTXH0 (*(volatile unsigned char *)0x1d00023)
#define rUTXH1 (*(volatile unsigned char *)0x1d04023)
#define rURXH0 (*(volatile unsigned char *)0x1d00027)
#define rURXH1 (*(volatile unsigned char *)0x1d04027)
#define WrUTXH0(ch) (*(volatile unsigned char *)(0x1d00023))=(unsigned char)(ch)
#define WrUTXH1(ch) (*(volatile unsigned char *)(0x1d04023))=(unsigned char)(ch)
#define RdURXH0() (*(volatile unsigned char *)(0x1d00027))
#define RdURXH1() (*(volatile unsigned char *)(0x1d04027))
#define UTXH0 (0x1d00020+3) //byte_access address by BDMA
#define UTXH1 (0x1d04020+3)
#define URXH0 (0x1d00024+3)
#define URXH1 (0x1d04024+3)
168
Embedded Systems Development and Labs; The English Edition
The following 3 functions are the main functions that used in this Lab including UART initialization and
character receive/send program. Read tem carefully and understand every line of the program. These functions
can be found at \commom\44lib.c.
169
Embedded Systems Development and Labs; The English Edition
if(whichUart==0)
{
while(!(rUTRSTAT0 & 0x1)); //Receive data read
return RdURXH0();
}
else
{
while(!(rUTRSTAT1 & 0x1)); //Receive data ready
return rURXH1;
}
}
170
Embedded Systems Development and Labs; The English Edition
2. RS232 Interface
In the schematic of S3CEV40, the serial port circuit is shown as Figure 4-10. The development board provides
two serial ports DB9. The UART1 is the main serial port that can be connected to PC or MODEM. Because
44B0X didn’t provide standard I/O signals such as DCD, DTE, DSR, RIC, etc. the general I/O port signals are
used. UART0 has only 2 lines RXD and TXD that can be used only for simple data transmitting and receiving.
The full UART1 connects to MAX3243E voltage converter. The simple UART0 connects to MAX3221 voltage
converter.
GPE2 ROUT 3
RIN
171
Embedded Systems Development and Labs; The English Edition
/*********************************************************************
* name: main
* func: c code entry
* para: none
* ret: none
* modify:
* comment:
*******************************************************************/
void Main(void)
{
char input_char; /* user input char */
int i;
char *pt_str = str;
/* printf interface */
Uart_Printf("\n");
Uart_Printf(str_send);
/* get user input */
172
Embedded Systems Development and Labs; The English Edition
Delay(500);
//* Terminal handler
while(1)
{
*pt_str = Uart_Getch();
Uart_SendByte(*pt_str);
if (*pt_str == 0x0D)
{
if (pt_str != str)
{
//* Send str_send
Uart_SendByte(CR[0]);
//* Send received string
pt_str = str;
while (*pt_str != 0x0D)
{
Uart_SendByte(*pt_str);
pt_str++;
}
pt_str = str;
}
Uart_SendByte(CR[0]);
Uart_Printf(str_send);
}
else
pt_str++;
}
}
173
Embedded Systems Development and Labs; The English Edition
char Uart_GetKey(void)
{
if(whichUart==0)
{
if(rUTRSTAT0 & 0x1) //Receive data ready
return RdURXH0();
else
return 0;
}
else
{
if(rUTRSTAT1 & 0x1) //Receive data ready
return rURXH1;
else
return 0;
}
}
174
Embedded Systems Development and Labs; The English Edition
Uart_SendByte('\n');
}
int Uart_GetIntNum(void)
{
char str[30];
char *string=str;
int base=10;
int minus=0;
int lastIndex;
int result=0;
int i;
Uart_GetString(string);
if(string[0]=='-')
{
minus=1;
string++;
}
lastIndex=strlen(string)-1;
if( string[lastIndex]=='h' || string[lastIndex]=='H' )
{
base=16;
string[lastIndex]=0;
lastIndex--;
}
if(base==10)
{
result=atoi(string);
result=minus ? (-1*result):result;
}
else
175
Embedded Systems Development and Labs; The English Edition
{
for(i=0;i<=lastIndex;i++)
{
if(isalpha(string[i]))
{
if(isupper(string[i]))
result=(result<<4)+string[i]-'A'+10;
else
result=(result<<4)+string[i]-'a'+10;
}
else
{
result=(result<<4)+string[i]-'0';
}
}
result=minus ? (-1*result):result;
}
return result;
}
Exercises
(1) Write a program that displays the characters received from serial port on the LCD.
(2) Based on the sample program in this Lab, add an error detection function.
176
Embedded Systems Development and Labs; The English Edition
The following are the features of the RTC (Real Time Clock) unit:
● BCD number: second, minute, hour, date, day, month, year
● Leap year generator
● Alarm function: alarm interrupt or wake-up from power down mode.
● Year 2000 problem is removed.
● Independent power pin (VDDRTC)
● Supports millisecond tick time interrupt for RTOS kernel time tick.
● Round reset function
1) Read/Write Registers
177
Embedded Systems Development and Labs; The English Edition
Bit 0 of the RTCCON register must be set in order to read and write the register in RTC block. To display the
sec., min., hour, date, month, and year, the CPU should read the data in BCDSEC, BCDMIN, BCDHOUR,
BCDDAY, BCDDATE, BCDMON, and BCDYEAR registers, respectively, in the RTC block. However, a one
second deviation may exist because multiple registers are read. For example, suppose that the user reads the
registers from BCDYEAR to BCDMIN, and the result is is 1959(Year), 12(Month), 31(Date), 23(Hour) and
59(Minute). If the user reads the BCDSEC register and the result is a value from 1 to 59(Second), there is no
problem, but, if the result is 0 sec., the year, month, date, hour, and minute may be changed to 1960(Year),
1(Month), 1(Date), 0(Hour) and 0(Minute) because of the one second deviation that was mentioned. In this case
(when BCDSEC is zero), the user should re-read from BCDYEAR to BCDSEC.
2) Backup Battery Operation
The RTC logic can be driven by the backup battery, which supplies the power through the RTCVDD pin into
RTC block, even if the system’s power is off. When the system is off, the interfaces of the CPU and RTC logic
are blocked, and the backup battery only drives the oscillator circuit and the BCD counters in order to minimize
power dissipation.
3) Alarm Function
The RTC generates an alarm signal at a specified time in the power down mode or normal operation mode. In
normal operation mode, the alarm interrupt (ALMINT) is activated. In the power down mode the power
management wakeup (PMWKUP) signal is activated as well as the ALMINT. The RTC alarm register,
RTCALM, determines the alarm enable/disable and the condition of the alarm time setting.
4) Tick Time Interrupt
The RTC tick time is used for interrupt request. The TICNT register has an interrupt enable bit and the count
value for the interrupt. The count value reaches '0' when the tick time interrupt occurs. Then the period of
interrupt is as follow:
This RTC time tick may be used for RTOS (real time operating system) as kernel time tick. If the RTC is used to
generate the time ticks, the time related function of RTOS would always be synchronized in real time.
5) Round Reset Function
The round reset function can be performed by the RTC round reset register, RTCRST. The round boundary (30,
40, or 50 sec) of the second carry generation can be selected, and the second value is rounded to zero in the
round reset. For example, when the current time is 23:37:47 and the round boundary is selected to 40 sec, the
round reset changes the current time to 23:38:00.
NOTE 1: All RTC registers have to be accessed by the byte unit using the STRB, LDRB instructions or char
type pointer.
NOTE 2: For a complete description of the registers bits please check the “S3C44BOX User’s Manual”.
178
Embedded Systems Development and Labs; The English Edition
VDD33
EXTAL1
CRYSTAL D9
32.768k
XTAL1 X2 1N4148
R72
10K
VDDRTC
BAT1 C54
C47 C46 104
15P 15P
GND BATTERY GND
2. Software Design
1) Timer Settings
The timer setting program implements functions such as detecting timer work status, verifying the setup data.
For detailed implementations, please refer to Section 4.5.7 “Timer Setting Control Program” and to the
“S3C44BOX User’s Manual”.
2) Time Display
The time parameters are transferred through the serial port 0 to the hyper terminal. The display content includes
year, month, day, hour, minute, second. The parameters are transferred as BCD code. The users can use the
serial port communication program (refer to Section 4.4 “Serial Port Communication Lab”) to transfer the time
parameters.
The following presents the C code of the RTC display control program:
void Display_Rtc(void)
{
Read_Rtc();
Uart_Printf(" Current Time is %02x-%02x-%02x %s",year,month,day,date[weekday]);
Uart_Printf(" %02x:%02x:%02x\r",hour,min,sec);
}
void Read_Rtc(void)
{
//Uart_Printf("This test should be excuted once RTC test(Alarm) for RTC initialization\n");
rRTCCON = 0x01; // R/W enable, 1/32768, Normal(merge), No reset
while(1)
{
179
Embedded Systems Development and Labs; The English Edition
if(rBCDYEAR == 0x99)
year = 0x1999;
else
year = 0x2000 + rBCDYEAR;
month=rBCDMON;
day=rBCDDAY;
weekday=rBCDDATE;
hour=rBCDHOUR;
min=rBCDMIN;
sec=rBCDSEC;
if(sec!=0)
break;
}
rRTCCON = 0x0; // R/W disable(for power consumption), 1/32768, Normal(merge), No reset
}
180
Embedded Systems Development and Labs; The English Edition
int Test_Rtc_Alarm(void);
void Rtc_Init(void);
void Read_Rtc(void);
void Display_Rtc(void);
void Test_Rtc_Tick(void);
yn = Uart_Getch();
if((yn == 0x4E)|(yn == 0x6E)|(yn == 0x59)|(yn == 0x79)) Uart_SendByte(yn);
if((yn == 0x0d)|(yn == 0x59)|(yn == 0x79))
{
RTC_alr = Test_Rtc_Alarm();
Display_Rtc();
}
else break;
181
Embedded Systems Development and Labs; The English Edition
if (RTC_alr) break;
}
*/
RTC_alr = Test_Rtc_Alarm();
Display_Rtc();
return RTC_alr;
}
char USE_RTC(void)
{
char yn,tmp,i,N09=1;
char num0 = 0x30;//"0";
char num9 = 0x39;//"9";
char schar[] ={0,'-',' ',':'};
char sDATE[12];//xxxx-xx-xx x
char sTIME[8];//xx:xx:xx
if(check_RTC())
{
Uart_Printf("\n RTC Working now. To set time(Y/N)? ");
yn = Uart_Getch();
if((yn == 0x4E)|(yn == 0x6E)|(yn == 0x59)|(yn == 0x79)) Uart_SendByte(yn);
if((yn == 0x0d)|(yn == 0x59)|(yn == 0x79)) //want to set time?
{
///////////////////////////////////////////////////////////////////////////////////
do{
Uart_Printf("\nCurrent day is (%04x,%02x,%02x, %s). To set day(yy-mm-dd w): "\
,year,month,day,date[weekday]);
Uart_GetString(sDATE);
if(sDATE[0] == 0x32)
{
if((sDATE[4] == schar[1] )&(sDATE[7] == schar[1] )&(sDATE[10] == schar[2] ))
{
if((sDATE[11] >0)|(sDATE[11] <8))
{
i=0; N09 = 0;
while(i<12)
{
if((i !=4)|(i !=7)|(i !=10))
{
if((sDATE[i] < num0 )&(sDATE[i] > num9))
182
Embedded Systems Development and Labs; The English Edition
{ N09 = 1;
break; }
}
i++;
}
if(N09 == 0)
break;//all right
} // if date 1 - 7
} // if "-" or " "
} // if 32 (21th century)
N09 = 1;
Uart_Printf("\n Wrong value!! To set again(Y/N)? ");
yn = Uart_Getch(); //want to set DATE again?
if((yn == 0x4E)|(yn == 0x6E)|(yn == 0x59)|(yn == 0x79)) Uart_SendByte(yn);
}while((yn == 0x0d)|(yn == 0x59)|(yn == 0x79));
if(N09 ==0)
{
rRTCCON = 0x01; // R/W enable, 1/32768, Normal(merge), No reset
rBCDYEAR = ((sDATE[2]<<4)|0x0f)&(sDATE[3]|0xf0);//->syear;
rBCDMON = ((sDATE[5]<<4)|0x0f)&(sDATE[6]|0xf0);//->smonth;
rBCDDAY = ((sDATE[8]<<4)|0x0f)&(sDATE[9]|0xf0);//->sday;
tmp = ((sDATE[11]&0x0f)+1);
if(tmp ==8) rBCDDATE = 1;// SUN:1 MON:2 TUE:3 WED:4 THU:5 FRI:6 SAT:7
else rBCDDATE = tmp;
rRTCCON = 0x00; // R/W disable
}else Uart_Printf("\n\n Use Current DATE Settings.\n");
///////////////////////////////////////////////////////////////////////////////////
do{
Uart_Printf("\nCurrent time is (%02x:%02x:%02x). To set time(hh:mm:ss): "\
,hour,min,sec);
Uart_GetString(sTIME);
183
Embedded Systems Development and Labs; The English Edition
break; }
}
i++;
}
if(N09 == 0)
{
tmp = ((sTIME[0]<<4)|0x0f)&(sTIME[1]|0xf0);
if((tmp >0)&(tmp <0x24))
{
sTIME[2] = tmp;//->shour;
tmp = ((sTIME[3]<<4)|0x0f)&(sTIME[4]|0xf0);
if(tmp <=0x59)
{
sTIME[5] = tmp;//->smin;
tmp = ((sTIME[6]<<4)|0x0f)&(sTIME[7]|0xf0);
if(tmp <=0x59)
break;//all right
} //if min < 59
} //if 0 < hour < 24
} //if num 0-9
}
N09 = 1;
Uart_Printf("\n Wrong value!! To set again(Y/N)? ");
yn = Uart_Getch(); //want to set Time again?
if((yn == 0x4E)|(yn == 0x6E)|(yn == 0x59)|(yn == 0x79)) Uart_SendByte(yn);
}while((yn == 0x0d)|(yn == 0x59)|(yn == 0x79));
if(N09 ==0)
{
rRTCCON = 0x01; // R/W enable, 1/32768, Normal(merge), No reset
rBCDHOUR = sTIME[2]; //->shour;
rBCDMIN = sTIME[5]; //->smin;
rBCDSEC = ((sTIME[6]<<4)|0x0f)&(sTIME[7]|0xf0); //->ssec;
rRTCCON = 0x00; // R/W disable
}else Uart_Printf("\n\n Use Current TIME Settings.\n");
}else{
Uart_Printf("\n Use Current Settings...\n");
return 1;
} /* end if want to set? */
}else{
Uart_Printf("\n Please check RTC or maybe it's Wrong. \n");
184
Embedded Systems Development and Labs; The English Edition
return 0;
} /* end if(check_RTC) */
}
4.5.8 Exercises
Write a program detecting RTC clock (alarm) function.
185
Embedded Systems Development and Labs; The English Edition
2
a
3
b
4 DPY
c
5 a
d
7
dp f g b
8
e
9 e c
f
10 d
g
1 dp
VCC
6
VCC
186
Embedded Systems Development and Labs; The English Edition
Static Display: When the 8 SEG LED displays a character, the control signals remain the same.
Dynamic Display: When the 8 SEG LED displays a character, the control signals are alternately changing. The
control signal is valid in a period of time (1 ms). Because of the human’s eyes vision, the display of LEDs
appears stable.
2. Principles of Circuits
In the circuit of S3CEV40, common anode type of 8-SEG is used. The control signals for each segment are
controlled by lower 8 bits of S3C44B0 data bus through 74LS573 flip-latch. The resisters R1-R8 can modify the
brightness of the LED. The chip selection for the 74LS573 flip-latch is shown in Figure 4-15.
The flip-latch chip select signal CS6 is generated by S3C44B0 nGCS1 and A18, A19, A20. Shown in Figure
4-16. When nGCS1, A18, A20 are high, and A19 is low, the CS6 is valid. At this time the contents in the lower 8
bits of data bus will be displayed at the 8-SEG LED.
VDD33
R7
U2 U1
74LS573 470E R5 8-LED
GND
1 20 470E
OE VCC 2
D0 2 19 R8 a
D0 Q0 3
D1 3 18 b
D1 Q1 470E 4 DPY
D2 4 17 R6 c
D2 Q2 5 a
D3 5 16 d
D3 Q3 470E 7
D4 6 15 R4 dp f g b
D4 Q4 8
D5 7 14 e
D5 Q5 470E 9 e c
D6 8 13 R2 f
D6 Q6 10 d
D7 9 12 g
D7 Q7 470E 1 dp
10
GND 11 R3 VCC
GND G 6
VCC
470E R1
470E
U8C VDD33
6 5 CS6
74HC14
U7
74LV138
A18 1 16
A0 VDD VDD33
A19 2 15 CS1
R35 A20 A1 Y0
22E 3 14 CS2
A2 Y1
nGCS1 4 13 CS3
S3 Y2
5 12 CS4
S2 Y3
6 11 CS5
VDD33 S1 Y4
CS8 7 10 CS6
R32 Y7 Y5
10K GND8 9 CS7
VSS Y6
187
Embedded Systems Development and Labs; The English Edition
The start address and end address of the S3C44B0 storage area 1 is fixed. The address range of storage area 1 is
0x02000000-0x2FFFFFF. When the microprocessor accesses this area, the nGCS1 is valid. Compound with
A18, A19, A20, CS6 will be valid when the microprocessor accesses the address 0x02140000-0x0217FFFF. In
the program, the 8SEG LED is displayed by sending data to the address 0x02140000.
188
Embedded Systems Development and Labs; The English Edition
SEGMENT_E | SEGMENT_G)
#define DIGIT_7 (SEGMENT_A | SEGMENT_B | SEGMENT_C)
#define DIGIT_6 (SEGMENT_A | SEGMENT_C | SEGMENT_D | SEGMENT_F | SEGMENT_E |
SEGMENT_G)
#define DIGIT_5 (SEGMENT_A | SEGMENT_C | SEGMENT_D | SEGMENT_F | SEGMENT_G)
#define DIGIT_4 (SEGMENT_B | SEGMENT_C | SEGMENT_F | SEGMENT_G)
#define DIGIT_3 (SEGMENT_A | SEGMENT_B | SEGMENT_C | SEGMENT_D | SEGMENT_F)
#define DIGIT_2 (SEGMENT_A | SEGMENT_B | SEGMENT_D | SEGMENT_E | SEGMENT_F)
#define DIGIT_1 (SEGMENT_B | SEGMENT_C)
#define DIGIT_0 (SEGMENT_A | SEGMENT_B | SEGMENT_C | SEGMENT_D | SEGMENT_E |
SEGMENT_G)
/********************************************************************
* name: Digit_Led_Test
* func: 8-segment digit LED test function
*********************************************************************/
void Digit_Led_Test(void)
{
int i;
/* display all digit from 0 to F */
for( i=0; i<16; i++ )
{
Digit_Led_Symbol(i);
Delay(4000);
}
}
4.6.7 Exercises
Write a program that displays each segment of the 8-SEG LED alternatively.
189
Embedded Systems Development and Labs; The English Edition
190
Embedded Systems Development and Labs; The English Edition
The main parameters of LCD are size, differentiate, dot width and color mode, etc. The mian parameters of
S3C40 development board LCD panel (LRH9J515XA STN/BW) are shown in Table 5-1.
The size parameters are shown in Figure 5-1. The outlook is shown is Figure 5-2.
Figure 5-1 Size Parameters (The unit of the numbers are mm)
191
Embedded Systems Development and Labs; The English Edition
2. S3C44B0X LCD Controller (See the “S3C44BOX User’s Manual” for a complete description)
S3C44B0X integrated LCD controller supports 4-bit Single Scan Display, 4-bit Dual Scan Display and 8-bit
Single Scan Display. The on-chip RAM is used as display buffer and supports screen scrolling. DMA (direct
memory access) is used in data transfer for minimum delay. Programming according to the hardware could
enable the on-chip LCD controller to support many kinds of LCD panels. The LCD controller within the
3C44B0X is used to transfer the video data and to generate the necessary control signals. The LCD controller
block diagram is shown in Figure 5-3.
192
Embedded Systems Development and Labs; The English Edition
DISMOD[6:5] 00 01 10 11
(1) 4-bit Single Scan – the LCD controller scan line is started from the left-top corner of the LCD panel. The
displayed data is VD[3:0]. The correspondence between the VD bits and the RGB color digits is shown in
Figure 5-5.
193
Embedded Systems Development and Labs; The English Edition
(3) 8-bit Single Scan – the LCD controller scan line is started from the left-top corner of the LCD panel. The
displayed data is VD[7:0]. The correspondence between the VD bits and the RGB color digits is shown in
Figure 5-7.
194
Embedded Systems Development and Labs; The English Edition
195
Embedded Systems Development and Labs; The English Edition
196
Embedded Systems Development and Labs; The English Edition
The following description is just a simple introduction to these registers. For detailed usage information, please
refer to the S3C44B0X User’s Manual.
The VFRAME and VLINE pulse generation is controlled by the configurations of the HOZVAL field and the
LINEVAL field in the LCDCON2 register. This is shown below:
In color mode:
Horizontal display size = 3 * Number of Horizontal Pixel
LINEVAL = (Vertical display size) -1: In case of single scan display type
LINEVAL = (Vertical display size / 2) -1: In case of dual scan display type
VCLK(Hz)=MCLK/(CLKVAL x 2)
The frame rate is given by the VFRAM signal frequency. The frame rate is closely related to the field of WLH
(VLINE pulse width), WHLY (the delay width of VCLK after VLINE pulse), HOZVAL, VLINEBLANK, and
LINEVAL in LCDCON1 and LCDCON2 registers as well as VCLK and MCLK. Most LCD drivers need their
own adequate frame rate. The frame rate is calculated as follows:
197
Embedded Systems Development and Labs; The English Edition
Data frame start address = 0xC300000, offset dot numbers=2048 (512 half words)
198
Embedded Systems Development and Labs; The English Edition
(2) LCD Panel: 320 x 240, 16 gray scale, dual scan mode
LINEVAL = 120 –1 = 0x77;
PAGEWIDTH = 320 x 4/16 = 0x50;
OFFSIZE = 512 = 0x200;
LCDBANK = 0xc300000 >> 22 = 0x30;
LCDBASEU = 0x100000 >> 1 = 0x8000;
LCDBASEL = 0x8000 + (0x50 + 0x200) x (0x77 + 1) = 0xa91580;
2) Pin Description
The pin description of LCD panel is shown in Table 5-6.
199
Embedded Systems Development and Labs; The English Edition
200
Embedded Systems Development and Labs; The English Edition
D1
L1
47uH
MBR0540 C8
U1 22u
1 8
nSHDN VCC R8
2 7 C7
FOL LX C6 680K
3 6
C5 REF GND 0.1u
4 5 150P
FB ISET
0.1u MAX629
R9 R10
100K
39K
C1 C2 C3 C4
14
1
8
U2A
VEE U2B U2C U2D
4 11 LM324 LM324 LM324
LM324
3
10
12
13
R3 R4 R5 R6 R7
VEE
15K 15K 180K 15K 15K
2. Software Design
The Lab implementation includes 3 parts: display rectangles, characters and bit maps.
1) A Thought on Design
The basic principle of LCD display is pixel control. The pixel storage and transfer determines the effect
obtained on the display. As a result, the graphics can be displayed by controlling the pixels. Storing the pixels in
some order can display characters such as ASCII characters, language characters, etc.
Embest ARM development system for pixel control functions are the following:
/**************************************************************************
* S3CEV40 LCD pixel display micro definition
* LCD LCD_PutPixel(x, y, c) – Send the pixel to the virtual buffer
* LCD_Active_PutPixel(x, y, c) – Send the pixel to the display buffer (directly drive LCD)
/**************************************************************************
#define LCD_PutPixel(x, y, c) \
(*(INT32U *)(LCD_VIRTUAL_BUFFER+ (y) * SCR_XSIZE / 2 + ( (x)) / 8 * 4)) = \
(*(INT32U *)(LCD_VIRTUAL_BUFFER+ (y) * SCR_XSIZE / 2 + ( (x)) / 8 * 4)) & \
(~(0xf0000000 >> ((( (x))%8)*4))) |((c) << (7 - ( (x))%8) * 4)
#define LCD_Active_PutPixel(x, y, c) \
(*(INT32U *)(LCD_ACTIVE_BUFFER + (y) * SCR_XSIZE / 2 + (319 - (x)) / 8 * 4)) = \
(*(INT32U *)(LCD_ACTIVE_BUFFER + (y) * SCR_XSIZE / 2 + (319 - (x)) / 8 * 4)) & \
(~(0xf0000000 >> (((319 - (x))%8)*4))) |((c) << (7 - (319 - (x))%8) * 4)
201
Embedded Systems Development and Labs; The English Edition
2) Rectangle Display
The rectangle consists of two horizon lines and two vertical lines. Drawing a rectangle on the LCD is
accomplished by calling the line draw function. The line draw function is alternately calling the pixel control
function.
3) Character Display
Characters can be displayed using many fonts. The font size is W x H or H x W such as 8 x 8, 8 x 16, 16 x 16, 16
x 24, 24 x 24, etc. The users can make use of different character libraries for displaying different fonts. For
example, the Lab system uses the 8 x 16 font to display ASCII characters. In order to display an ASCII character
first we have to access the look up predefined character table. This table, used for storing characters, is called
ASCII library.
The function call for the ASCII library is:
Const INIT8U g_auc_Ascii8x16[]={ //ASCII table}
The storage of ASCII table is an array that uses the value of ASCII character as its index. The relationship
between the width/height and the library will be extracted during the process of the pixel-controlled drawing.
The ASCII library consists of 256 ANSI ASCII characters. For detailed information, please refer to the sample
programs of the Lab project.
The Embest ARM development system provides the following functions that can be used for bit map display:
Const INT8U ucMouseMap[] = {//Bit Map File Data}
Bit map display (please refer to the sample program) function is the following:
Void BitmapView(INT16U x, INT16U y, STRU_BITMAP Stru_Bitmap);
Bit map action (please refer to the sample program) functions are the following:
Void BitmapPush(INT16U x, INT16U y, STRU_BITMAP Stru_Bitmap);
Void BitmapPop(INT16U x, INT16U y, STRU_BITMAP Stru_Bitmap);
202
Embedded Systems Development and Labs; The English Edition
/* screen size */
#define MLCD_320_240 (3)
#define LCD_TYPE MLCD_320_240
#define SCR_XSIZE (320)
#define SCR_YSIZE (240)
#define LCD_XSIZE (320)
203
Embedded Systems Development and Labs; The English Edition
/* Micro definition*/
#define MODE_GREY16 (16)
#define CLKVAL_GREY16 (12)
#define HOZVAL (LCD_XSIZE/4-1)
#define LINEVAL (LCD_YSIZE -1)
#define MVAL (13)
/* LCD buffer */
#define ARRAY_SIZE_GREY16 (SCR_XSIZE/2*SCR_YSIZE)
#define LCD_BUF_SIZE (SCR_XSIZE*SCR_YSIZE/2)
#define LCD_ACTIVE_BUFFER (0xc300000)
#define LCD_VIRTUAL_BUFFER (0xc300000 + LCD_BUF_SIZE)
/***********************************************************************
* name: Lcd_Init()
* func: Initialize LCD Controller
* para: none
* ret: none
* modify:
* comment:
*********************************************************************/
void Lcd_Init(void)
{
rDITHMODE=0x1223a;
rDP1_2 =0x5a5a;
rDP4_7 =0x366cd9b;
rDP3_5 =0xda5a7;
rDP2_3 =0xad7;
rDP5_7 =0xfeda5b7;
rDP3_4 =0xebd7;
rDP4_5 =0xebfd7;
rDP6_7 =0x7efdfbf;
rLCDCON1=(0)|(1<<5)|(MVAL_USED<<7)|(0x0<<8)|(0x0<<10)|(CLKVAL_GREY16<<12);
rLCDCON2=(LINEVAL)|(HOZVAL<<10)|(10<<21);
rLCDSADDR1= (0x2<<27) | ( ((LCD_ACTIVE_BUFFER>>22)<<21 ) |
M5D(LCD_ACTIVE_BUFFER>>1));
rLCDSADDR2= M5D(((LCD_ACTIVE_BUFFER+(SCR_XSIZE*LCD_YSIZE/2))>>1)) |
(MVAL<<21);
204
Embedded Systems Development and Labs; The English Edition
2. Control Functions
1) Clear Screen Functions
/*****************************************************************
* name: Lcd_Active_Clr()
* func: clear virtual screen
* para: none
* ret: none
* modify:
* comment:
********************************************************************/
void Lcd_Clr(void)
{
INT32U i;
INT32U *pDisp = (INT32U *)LCD_VIRTUAL_BUFFER;
/********************************************************************
* name: Lcd_Active_Clr()
* func: clear LCD screen
* para: none
* ret: none
* modify:
* comment:
******************************************************************/
void Lcd_Active_Clr(void)
{
INT32U i;
INT32U *pDisp = (INT32U *)LCD_ACTIVE_BUFFER;
205
Embedded Systems Development and Labs; The English Edition
/*********************************************************************
* name: Lcd_Draw_VLine()
206
Embedded Systems Development and Labs; The English Edition
207
Embedded Systems Development and Labs; The English Edition
INT32U i, j;
INT8U ucColor;
ucZdma0Done=1;
//#define LCD_VIRTUAL_BUFFER (0xc400000)
//#define LCD_ACTIVE_BUFFER (LCD_VIRTUAL_BUFFER+(SCR_XSIZE*SCR_YSIZE/2))
//DMA ON
//#define LCD_ACTIVE_BUFFER LCD_VIRTUAL_BUFFER
//DMA OFF
//#define LCD_BUF_SIZE (SCR_XSIZE*SCR_YSIZE/2)
//So the Lcd Buffer Low area is from LCD_VIRTUAL_BUFFER to
(LCD_ACTIVE_BUFFER+(SCR_XSIZE*SCR_YSIZE/2))
rNCACHBE1=(((unsigned)(LCD_ACTIVE_BUFFER)>>12)
<<16 )|((unsigned)(LCD_VIRTUAL_BUFFER)>>12);
rZDISRC0=(DW<<30)|(1<<28)|LCD_VIRTUAL_BUFFER; // inc
208
Embedded Systems Development and Labs; The English Edition
Delay(500);
//while(ucZdma0Done); //wait for DMA finish
}
5.1.8 Exercises
Refer to the sample program; display the 4 x 4 keyboard values on the LCD panel.
209
Embedded Systems Development and Labs; The English Edition
read the keyboard status on the data bus through different addresses and determine which key is pressed.
● Scanning: Send low voltage to one horizontal line and high level to the other horizontal lines. If any vertical
line is low, the key that sits at the intersection of the selected row and column is pressed.
● Inversion: Send low voltage to the horizontal lines and read the vertical lines. If any vertical line is low, it
indicates one key is pressed on that column. Then send low voltage to the vertical lines and read the
horizontal lines. If any horizontal line is low, it indicates one key is pressed on that row. The intersection of
the identified row and column will give the position of the key.
210
Embedded Systems Development and Labs; The English Edition
R48
10K R51 R54 R55 U10
U11
14 7 10K10K 10K 74HC541
VCCGND
L3 12 13 11 10 GND
6Y 6A Y8 GND
L2 10 11 12 9 A4
5Y 5A Y7 A8
L1 8 9 13 8 A3
4Y 4A Y6 A7
L0 6 5 14 7 A2 D11
3Y 3A Y5 A6 1N4148
4 3 D3 15 6 A1 L3
2Y 2A Y4 A5
2 1 D2 16 5 D10
1Y 1A Y3 A4 1N4148
R56 D1 17 4 L2
Y2 A3
74HC17 R58 10K D0 18 Y1 A2
3
2 L1 D8 J7
10K 19
NGCS3 G2 A1 1N4148
20 1GND 1
VDD33 VCC G1 L0
2
U9B D7 3
1N4148 4
74HC08 74HC08
7
U9C 4 5
10 6 6
EXINT1 8 5 7
9 8
13
14
11 KEYBOARD
U9D 12
VDD33
74HC08
VDD33
3) Circuit Functionality
As shown in Figure5-13, the keyboard connection electric circuit, a 4×4 matrix keyboard port is expanded on
the board. This keyboard supports the interrupt mode and the scanning mode. 4 data wires represent the rows
and 4 address wires represent the columns. Row wires are connected with pull-up resistors to maintain high
level. These row signals are used to generate the EXINT1 MCU’s interrupt signal through a 74HC08 AND gate.
The column wires are connected with pull-down resistors to maintain low level. When some key is pressed
down, the row wires are pulled to low level, which causes EXINT1 input to become low and activate the MCU
interrupt system. After the interrupt is recognized, the pressed key can be found by scanning the rows and
columns of the keyboard then the corresponding key is processed. Chip 74HC541 is selected through the chip
select signal nGCS3. This guarantees that MCU reads the row wire’s information only when the keyboard is
used. For example, if the key that connects pin1 and pin5 of J7 is pressed, the interrupt routine will read data
using the following addresses (x means 0 or 1):
• Xxx11101, A1 is logic low. Analyze whether the button on L0 line is pressed. Because the fourth pin
on J7 is in the off status, and high logic on A4 causes that the first pin is disconnected with the fifth
pin of J7, output of data bus from U10 is still 0xF
• Xxx11011, A2 is low logic. Analyze whether the buttons on L1 line are pressed. Because the third pin
of J7 is in the off status, and high logic on A4 causes that the first pin is disconnected with the fifth pin
of J7, output of data bus from U10 is still 0xF.
• Xxx10111, A3 is low logic. Analyze whether the buttons on L2 line are pressed. Because the second
211
Embedded Systems Development and Labs; The English Edition
pin of J7 is in the off status, and high logic on A4 causes that the first pin is disconnected with the fifth
pin of J7, output of data bus from U10 is still 0xF.
• Xxx01111, A4 is low logic. Analyze whether the buttons on L3 line are pressed. Because the first pin
is connected with the fifth pin of J7, and low logic on A4 causes that input of data bus pass through
the loop from U11 to U10, the output of data bus D0 is pulled down by U10 and becomes 0xE. The
interrupt service routine (ISR) can analyze whether the button SB16 is pressed according to the rules.
The addresses and the data for the 16 keys are shown in Table 5-7.
212
Embedded Systems Development and Labs; The English Edition
VDD33
R7
U2 U1
74LS573 470E R5 8-LED
GND
1 20 470E
OE VCC 2
D0 2 19 R8 a
D0 Q0 3
D1 3 18 b
D1 Q1 470E 4 DPY
D2 4 17 R6 c
D2 Q2 5 a
D3 5 16 d
D3 Q3 470E 7
D4 6 15 R4 dp f g b
D4 Q4 8
D5 7 14 e
D5 Q5 470E 9 e c
D6 8 13 R2 f
D6 Q6 10 d
D7 9 12 g
D7 Q7 470E 1 dp
10
GND 11 R3 VCC
GND G 6
VCC
470E R1
470E
U8C VDD33
6 5 CS6
74HC14
Interrupt
Start Routine
Ax low?
Keyboard Data
Initialization Recognition
Read Ax+1
Interrupt
Pressed?
Routine Display
Key Value
Wait
Exit Interrupt
213
Embedded Systems Development and Labs; The English Edition
2. Keyboard Inicialization
/***********************************************************************
* name: init_keyboard
* func: init keyboard interrupt
* para: none
* ret: none
* modify:
* comment:
**********************************************************************/
void init_keyboard()
{
/* enable interrupt */
rINTMOD = 0x0;
rINTCON = 0x1;
214
Embedded Systems Development and Labs; The English Edition
pISR_EINT1 = (int)KeyboardInt;
pISR_EINT4567 = (int)Eint4567Isr;
/* PORT G */
rPCONG = 0xffff; // EINT7~0
rPUPG = 0x0; // pull up enable
rEXTINT = rEXTINT|0x20; // EINT1 falling edge mode
3. Interrupt Routine
/*******************************************************************
* name: KeyboardInt
* func: keyboard interrupt handler function
* para: none
* ret: none
* modify:
* comment:
*********************************************************************/
void KeyboardInt(void)
{
int value;
rI_ISPC = BIT_EINT1; // clear pending bit
value = key_read();
if(value > -1)
{
Digit_Led_Symbol(value);
Uart_Printf("Key is:%x \r",value);
}
8-SEG LED is used in the LAB. For the related programs, please refer to Section 4.6 “8-SEG LED Display
Lab”.
int Seg[] = { SEGMENT_A, SEGMENT_B, SEGMENT_C, SEGMENT_D, SEGMENT_E, SEGMENT_F,
SEGMENT_G, SEGMENT_P};
/*********************************************************************
* name: Digit_Led_Segment
215
Embedded Systems Development and Labs; The English Edition
216
Embedded Systems Development and Labs; The English Edition
return value;
}
/* read line 2 */
temp = *(keyboard_base+0xfb);
/* not 0xF mean key down */
if(( temp & KEY_VALUE_MASK) != KEY_VALUE_MASK)
{
if( (temp&0x1) == 0 )
value = 7;
else if( (temp&0x2) == 0 )
value = 6;
else if( (temp&0x4) == 0 )
value = 5;
else if( (temp&0x8) == 0 )
value = 4;
return value;
}
/* read line 3 */
temp = *(keyboard_base+0xf7);
/* not 0xF mean key down */
if(( temp & KEY_VALUE_MASK) != KEY_VALUE_MASK)
{
if( (temp&0x1) == 0 )
value = 0xb;
else if( (temp&0x2) == 0 )
value = 0xa;
else if( (temp&0x4) == 0 )
value = 9;
else if( (temp&0x8) == 0 )
value = 8;
return value;
}
/* read line 4 */
temp = *(keyboard_base+0xef);
/* not 0xF mean key down */
if(( temp & KEY_VALUE_MASK) != KEY_VALUE_MASK)
{
if( (temp&0x1) == 0 )
217
Embedded Systems Development and Labs; The English Edition
value = 0xf;
else if( (temp&0x2) == 0 )
value = 0xe;
else if( (temp&0x4) == 0 )
value = 0xd;
else if( (temp&0x8) == 0 )
value = 0xc;
return value;
}
return -1;
}
5.2.8 Exercises
Write a program that can detect and process two keys pressed at the same time.
A 4-wire resistive touch panel is used by the Embest S3CEV40 Development system. The resolution of the
touch panel is 320 x 240 dots. The touch panel system consists of three parts that are the touch panel, the control
circuit and the AD converter circuit.
218
Embedded Systems Development and Labs; The English Edition
Since 44B0X chip did not provide this function, a general I/O port can be used for configuration. The TSP
includes two surface resistances, namely, X axial surface resistance and Y axial surface resistance. Therefore
TSP has 4 terminals. Its equivalent circuitry when the screen is pressed is shown in Figure 5-19. When the
system is in the sleep mode (panel not touched) Q4, Q2 and Q3 are closed and Q1 is opened. When the screen is
touched, X axial surface resistance and Y axial surface resistance is opened at the touching point. Since the
resistance value is very small (about several hundred ohms) a low level signal is generated at EXINT2, which
results into interrupt; MCU causes Q2, Q4 to be opened and Q1, Q3 to be closed by controlling the I/O port.
S3C44B0X A/D converter channel AIN1 reads X axis coordinates, then closes Q2, Q4, and causes Q1, Q3 to
pass. S3C44B0X A/D converter channel AIN0 reads Y-axis coordinates. When the system reaches the
coordinate value, Q4, Q2, Q3 are closed and Q1 is opened. The system returns to original state, waiting for the
next touch. TSP occupies 44B0X external interrupt-EXINT2, as well as 4 general I/O ports (PE4 ~ PE7).
VDD
Q3
PE5
VDD
AIN1
PE4 TSPX+
Q4
EXINT2 PE7
Q1
R TSPX-
PE6
Q2
VDD
219
Embedded Systems Development and Labs; The English Edition
1) Register Group
The integrated ADC has the following three registers: ADC control register (ADCCON), ADC Prescaler
Register (ADCPSR) and ADC Data Register (ADCDAT).
(1) ADC control register (ADCCON)
220
Embedded Systems Development and Labs; The English Edition
66 MHz / 2(20+1) / 16(at least 16 cycle by 10-bit operation) = 98.2 KHz = 10.2 us
NOTE: Because this A/D converter has no sample-and-hold circuit, the analog input frequency should not
exceed 100Hz for accurate conversion although the maximum conversion rate is 100KSPS.
221
Embedded Systems Development and Labs; The English Edition
PE0 R33 9 8 J5
22E LCD&TSP
U8D
PD7
74HC14 1
PD6
CS8 R34 11 10 2
PD5
22E 3
U8E PD4
4
74HC14 PD3
R49 5
22E PD2
6
3
AIN0 PD1
R43 7
R45 PD0
Q4 4.7K GND 8
GNDGND
SD
MOSFET-P 3.3K 9
PE4 1 C32 EXINT2 PC7
G 10
3.3nF PC6
R44 11
PC5
2
100K 12
PC4
13
VDD25 14
15
PE5 TSPX+
16
3
Q3 GND TSPY+
MOSFET-P 17
Q2 TSPX-
C29 18
TSPY-
SD
R52 R40 3.3nF MOSFET-N 19
AIN1 1
G VDD33 20
120E 3.3K
GND
2
PE6 Q1
PE7 MOSFET-N
2. Software Design
The touch screen related software includes the serial port data transfer program, the LCD display program, the
touch screen calibration and interrupt service routine, and other auxiliary programs. For the serial port data
transfer program, please refer to the “Serial Port Communication Lab”. For the LCD display program, please
refer to the “LCD Display and Control Lab”. The touch screen calibration of this Lab uses two dots diagonal
calibration. The flow diagram of touch screen control program is shown in Figure 5-26.
222
Embedded Systems Development and Labs; The English Edition
Interrupt
Start Routine
N
X, Y Range
Calibrated Open Q2, Q4
Environment
Initialization
Y AIN1 ADC
Coordinates
LCD Getting X, Y
Calculation
Initialization
Open Q1, Q3
Y Interrupt
Pressed?
Routine
AIN0 ADC
N Coordinates
Calculation
Wait
223
Embedded Systems Development and Labs; The English Edition
The information gives the current valid coordinate range. These are factory default values. The user can select
Y/y to calibrate the TSP again. Otherwise use the default value.
When ‘calibrating the TSP’ is selected, any two points of the diagonal should be pressed using a finger or a
small stick. The hyper terminal will show the coordinate values that the user inputted and will decide if they are
valid. The touch screen program will output the new coordinate values. The user can accept them or calibrate
the screen coordinates again.
After the coordinates are calibrated, the user can press on the touch panel in the valid range. The hyper terminal
will output the coordinate values:
5) After understanding and mastering the lab, finish the Lab exercises.
224
Embedded Systems Development and Labs; The English Edition
Port_Init();
RIISPC = 0xffffffff;
Uart_Init()(0,115200);
char oneTouch;
unsigned int Vx;
unsigned int Vy;
unsigned int Xmax;
unsigned int Ymax;
unsigned int Xmin;
unsigned int Ymin;
225
Embedded Systems Development and Labs; The English Edition
rDP3_4 =0xebd7;
rDP4_5 =0xebfd7;
rDP6_7 =0x7efdfbf;
rLCDCON1=(0)|(1<<5)|(MVAL_USED<<7)|(0x0<<8)|(0x0<<10)|(CLKVAL_GREY16<<12);
rLCDCON2=(LINEVAL)|(HOZVAL<<10)|(10<<21);
rLCDSADDR1= (0x2<<27) | ( ((LCD_ACTIVE_BUFFER>>22)<<21 ) |
M5D(LCD_ACTIVE_BUFFER>>1));
rLCDSADDR2= M5D(((LCD_ACTIVE_BUFFER+(SCR_XSIZE*LCD_YSIZE/2))>>1)) |
(MVAL<<21);
rLCDSADDR3= (LCD_XSIZE/4) | ( ((SCR_XSIZE-LCD_XSIZE)/4)<<9 );
// enable,4B_SNGL_SCAN,WDLY=8clk,WLH=8clk,
rLCDCON1=(1)|(1<<5)|(MVAL_USED<<7)|(0x3<<8)|(0x3<<10)|(CLKVAL_GREY16<<12);
rBLUELUT=0xfa40;
//Enable LCD Logic and EL back-light.
rPDATE=rPDATE&0xae;
}
226
Embedded Systems Development and Labs; The English Edition
// <X-Position Read>
// TSPX(GPE4_Q4(+)) TSPY(GPE5_Q3(-)) TSMY(GPE6_Q2(+)) TSMX(GPE7_Q1(-))
// 0 1 1 0
rPDATE=0x68;
rADCCON=0x1<<2; // AIN1
227
Embedded Systems Development and Labs; The English Edition
Pt[i] = (0x3ff&rADCDAT);
}
// read X-position average value
Pt[5] = (Pt[0]+Pt[1]+Pt[2]+Pt[3]+Pt[4])/5;
tmp = Pt[5];
// <Y-Position Read>
// TSPX(GPE4_Q4(-)) TSPY(GPE5_Q3(+)) TSMY(GPE6_Q2(-)) TSMX(GPE7_Q1(+))
// 1 0 0 1
rPDATE=0x98;
rADCCON=0x0<<2; // AIN0
if(!(CheckTSP|(tmp < Xmin)|(tmp > Xmax)|(Pt[5] < Ymin)|(Pt[5] > Ymax))) // Is valid value?
{
tmp = 320*(tmp - Xmin)/(Xmax - Xmin); // X - position
Uart_Printf("X-Posion[AIN1] is %04d ", tmp);
if(CheckTSP)
/*----------- check to ensure Xmax Ymax Xmin Ymin ------------*/
DesignREC(tmp,Pt[5]);
228
Embedded Systems Development and Labs; The English Edition
5.3.8 Exercises
Refer to the LCD Display Lab and write a program that accepts 4 points pressed on the touch panel and display
the rectangle using the 4 coordinate values.
229
Embedded Systems Development and Labs; The English Edition
230
Embedded Systems Development and Labs; The English Edition
231
Embedded Systems Development and Labs; The English Edition
launched to write all the data from the buffer into the EPROM array. Writing to buffer is called page writing.
The capability of the buffer is called ‘page write byte’. The page write byte of AT24C04 is 8. It occupies the
lowest three bits of the address line. When the amount of data is not exceeding the page write byte, the write
operation to EPROM is the same as the write operation to SRAM. When the amount of data is exceeding the
page write byte, another write operation to EPROM will be initiated after a 5-10ms wait time.
2) Device Address (DADDR)
The AT24C04 device address is 1010.
3) AT24CXX Data Operation Format
In order to write or read the EPROM memory, both the device address (DADDR) and the read/write page
address (PADDR) should be given. These two addresses form the operation address (OPADDR) as following:
1010 A2 A1 –R/W
In the Embest ARM Development system, pins A2A1A0 are 000 and the system can access all pages of the
AT24C04 (4k). The format of the read/write data operation to an address (ADDR=1010 A2 A1 –R/W) is as
following:
(1) Write Format
The time sequence diagram for writing one byte to the address ADDR_W is shown in Figure 6-3. The write
format is:
The time sequence diagram for writing n bytes to the address ADDR_W is shown in Figure 6-4. The write
format is:
START_C OPADDR_W ACK ADDR_W ACK data1 ACK data1 ACK … datan ACK STOP_C
232
Embedded Systems Development and Labs; The English Edition
The time sequence diagram for reading 1 byte from the address ADDR_W from the same page is shown in
Figure 6-6. The read format is:
In reading 1 bytes operation, besides the read address ADDR_R, the operation address OPADD_R is also
needed. As a result, before the 1 byte of data is read, a one byte writing operation is needed. Notice that there is
no ACK after the read operation.
233
Embedded Systems Development and Labs; The English Edition
devices that are connected to the IIC-bus. The SDA and SCL lines are bi-directional. A High-to-Low transition
on SDA can initiate a Start condition. A Low-to-High transition on SDA can initiate a Stop condition while SCL
remains steady at High Level. The S3C44B0X IIC-bus interface has four operation modes:
— Master transmitter mode
— Master receiver mode
— Slave transmitter mode
— Slave receiver mode
In the Master Transmitter Mode, the microprocessor communicates to the serial devices via IIC bus using the
following registers:
(1) MULTI-MASTER IIC-BUS CONTROL REGISTER (IICCON)
234
Embedded Systems Development and Labs; The English Edition
235
Embedded Systems Development and Labs; The English Edition
Same page multi bytes write operation R/W=0 OPADDR:device and page
address (higher 7bit)
236
Embedded Systems Development and Labs; The English Edition
START_C P&R ACK Addr ACK P&R ACK DATA(nByte) ACK STOP_C
Start
IICDS Tx finished
End
237
Embedded Systems Development and Labs; The English Edition
2. Circuit Design
In the Embest S3CEV40, the S3C44B0X on-chip IIC controller is the master and the AT24C04 EEPROM is the
slave. The circuit design is shown in Figure 6-9.
U18
AT24LC04
1 8
A0 VDD VDD33
2 7
A1 WP
3 6 IICSCL
A2 SCL
4 5 IICSDA
GND SDA GND
GND
(5) After understanding and mastering the lab, finish the Lab exercises.
238
Embedded Systems Development and Labs; The English Edition
/* enbale TX/RX */
rIICSTAT=0x10;
2. Interrupt Declaration
/* enable interrupt */
pISR_IIC=(unsigned)IicInt;
3. Interrupt Routine
/***********************************************************************
* name: IicInt
* func: IIC interrupt handler
* para: none
* ret: none
* modify:
* comment:
*********************************************************************/
void IicInt(void)
{
rI_ISPC=BIT_IIC;
iGetACK = 1;
}
239
Embedded Systems Development and Labs; The English Edition
/* send address */
rIICDS = addr;
rIICCON = 0xaf; // resumes IIC operation.
/* send data */
rIICDS = data;
rIICCON = 0xaf; // resumes IIC operation.
/* end send */
rIICSTAT = 0xd0; // stop Master Tx condition
rIICCON = 0xaf; // resumes IIC operation.
DelayMs(5); // wait until stop condtion is in effect.
}
240
Embedded Systems Development and Labs; The English Edition
iGetACK = 0;
/* send address */
rIICDS = addr;
rIICCON = 0xaf; // resumes IIC operation.
/* get data */
recv_byte = rIICDS;
rIICCON = 0x2f;
DelayMs(1); // delay
241
Embedded Systems Development and Labs; The English Edition
/* get data */
recv_byte = rIICDS;
/* end receive */
rIICSTAT = 0x90; // stop Master Rx condition
rIICCON = 0xaf; // resumes IIC operation.
DelayMs(5); // wait until stop condition is in effect.
6.1.8 Exercises
Write a program to write words such as date, etc. and read them out through serial port or LCD panel.
242
Embedded Systems Development and Labs; The English Edition
Ethernet Li
3) Work Principles
The transportation method in Ethernet is Media Access Control technology that is also called Carrier Sense
Multiple Access / Collision Detection (CSMA/CD). The following are the descriptions of this technology:
● Carrier Sense: When your computer is trying to send information to another computer on the networks,
your computer should first monitor if there are information currently transferring on the network or if the
channel id idle.
● Channel Busy: If the channel is busy, then wait until the network channel is idle.
● Channel Idle: If the channel is idle, then transmit the message. Because the whole network is being shared
the same communication bus, all the network station can receive your message, but only the network station
you selected can receive your message.
● Collision Detection: When a network station is transmitting message, it needs to monitor the network
channels, detects if other network station are transmitting messages on the network. If yes, the messages
sent from two stations will be in collision that cause the message be damaged.
● Busy Stop: If there is network collision on the network, the transmission should stop immediately and a
“collision” signal should be sent to the network to let other stations know the collision has happen.
● Multiple Access: If the network station encountered collisions and stop transmission, it should wait for a
while and return to the first step, start the carrier sensing and transmission, until the data is successfully
transmitted.
All the network stations are transmitting messages through the above 6 steps.
Because at the same time, there is only one network station transmitting messages and other stations can only
receive or wait, the collision chances are increase when more network station added to the network. The
network stations will alternately follow the process monitor transmit stop transmit wait retransmit…
243
Embedded Systems Development and Labs; The English Edition
● Preamble consists of alternative 0 and 1 that informs network stations to get ready. The IEEE802.3
preamble is 7 bytes followed by one byte of SOF. The Preamble includes the SOF, so its total length is 8
bytes.
● Start of Frame (SOF) is one byte ended with two consequent 1. This byte stands for the start of the frame.
● Destination and Source Addresses means the addresses of the sending workstation and receiving
workstation. The destination address is a single address or a broadcast address.
● Data (Ethernet) will be transferred to higher protocols after the data has been processed in the physical
layer and the logic link layer. The minimum length of data is 46 bytes.
● Data (802.3) will be filled to 64 bytes if the length of data is not more than 64 bytes.
● Frame Check Sequence (FCS) consists of a 4-byte CRC that is generated by the sending device. The
receiving device will recalculate the CRC and compare is with the received CRC in order to make sure that
data has been transferred correctly.
244
Embedded Systems Development and Labs; The English Edition
RTL8019 consists of the following interfaces: remote DMA, local DMA, MAC (media access control) logic,
data CODEC, and others.
The remote DMA interface is an ISA bus that the processor write/read data to/from the RAM inside the
RTL8019. Microprocessor deals with remote DMA interface only. The local DMA interface is an
interconnection channel between RTL8019AS and network cable.
Bellow the MAC (media access control) logic completes the function:
• when the processor transmits data to the network, the processor transmits first a frame of data to the
transmit buffer via the remote DMA channel;
• then the processor sends a transmit command; when the RTL8019AS finishes the current frame
transmission, it starts to transmit the next frame;
• the RTL8019As receives the data the MAC comparison. After the CRC verification, the data is
transferred to buffer via FIFO;
• when the frame is full, the RTL8019As will inform the microprocessor through the interrupt or the
register flag bit.
FIFO receive/send 16 bytes data is used as a tampon buffer to reduce the DMA request frequency. The RTL8019
has two internal RAM blocks. One is 16Kb and occupies the address space 0x4000-0x7FFF. The other is 32Kb
and occupies the address space 0x0000-0x001F. The RAM is divided into pages of 256 bytes. Generally the first
12 pages (0x4000-0x4BFF) are used as the transmission buffer. The following 52 pages (0x4C00-0x7FFF) are
used as the receiver buffer. The page 0 is only 32 bytes (0x0000-0x001F) and is the PROM page. The PROM
page is used for storing the Ethernet physical address. In order to read/write data packages, the DMA mode is
needed to read/write the data to the 16 Kb RAM in the RTL8019AS. The RTL8019 has 32-bit input/output
addresses. The address offset is 0x00-0x1F where x00-0x0F are 16 register addresses. These registers hold the
pages addresses. They are PAGE0, PAGE1, PAGE2 and PAGE3. The bit PS1 and bit PS2 of CR (Command
Register) determines which page will be visited. But only the first 3 pages are compatible with NE2000. Page 3
is RTL8019 self defined page and is not compatible with other NE2000 chips (such as DM9008). The remote
DMA address is 0x10-0x17 and is used as remote DMA port. The reset port is 0x18-0x1F (8 addresses) that is
used to reset RTL8019AS. The application diagram of ATL8019As is shown in Figure 6-12.
245
Embedded Systems Development and Labs; The English Edition
Ethernet.c is the driver program of the RTL8019AS chip. The following describes briefly its functions:
● NicInit() 8019 initialization. The initialization steps are: (1) configure the chip to the jumper mode,
half-duplex. (2) Configure the receive/send buffer. Two buffers are used for sending data. Each buffer
occupies 6 pages (256 bytes) of internal RAM and it can transmit a maximum of 1536 bytes of Ethernet
data package. Another buffer is used for receiving data and consists of 20 pages (256 bytes/page) of internal
RAM block. (3) Set MAC address and broadcast address. MAC address is determined by mac_addr array.
(4) Configure the chip only receive the data package that match to the local MAC address (also can be
configured as receiving all packages or broadcast packages). Enable received interrupt. Enable CRC. (5)
Start the chip for receiving/sending data.
● NicClose() Close 8019AS data receive/send functions.
● NicReset() Reset 8019AS chip.
● NicOutput() Data package output. Fill the data package with a header of Ethernet data package. Set the
target MAC address according to the parameter. Write the content of Ethernet package to the send buffer.
Start DMA send function. This chip will automatically finish the sending.
● EtherInput() Data package input. Check the data receive flag register. If there is data in the buffer, then
receive the header of the package from the receive buffer. If the content of the header is correct, then
according to the data length in the header, read the content of data from the package and transfer it to the
higher layer interface. Make the pointer to the current receive buffer to the last page of the buffer.
2. IP Network Protocols
TCP/IP protocol is a group of protocols including TCP (Transmission Control Protocol) and IP (Internet
Protocol), UDP (User Datagram Protocol), ICMP (Internet Control Message Protocol) etc.
TCP/IP was first time introduced in 1973 by two researchers at Stanford University. At that time the US ARPA
(Advanced Research Project Agency) planed to implement interconnections between different networks. ARPA
aided the research and development of inter-network connections. In 1977-1979, the TCP/IP architecture and
standard was developed and is almost the same as the current TCP/IP architecture. Around 1980s, the US
DARPA started to port all the machines to the TCP/IP network. From 1985, NSF (National Scientific
246
Embedded Systems Development and Labs; The English Edition
Foundation) started to support TCP/IP research and gradually played an important role. NFS aided the
establishment of the global Internet network. and used TCP/IP as its communication protocol.
1) Architecture
TCP/IP is a four layers protocol. Every layer is independent and has its own specific function. The TCP/IP layer
structure is shown in Figure 6-13.
Application Layer(Layer 4)
Transmission Layer(Layer 3)
Internet Layer(Layer 2)
Network Interface Layer(Layer 1)
247
Embedded Systems Development and Labs; The English Edition
the route of the remote host from the route table in the local host (like we dial 114). If a route is found, the IP
will use this route to transfer data; if no route is found, the data package will be sent to a default gateway of the
source host (this gate way is also called a router).
The current IP protocol includes the IPv4 version and the v6 version. IPv4 is currently being widely used; IPv6
is the basic protocol that will be used in the next generation of high speed Internet.
The header of IP protocol is shown in Figure 6-14.
0 4 8 16 32
-----------------------------------------------------------------------
|Version |Header Length |Service Type| Total Length |
----------------------------------------------------------------------
| Identification |Flags|Fragment Offset|
-----------------------------------------------------------------------
| Time to Live | Protocol | Header Checksum |
-----------------------------------------------------------------------
| Source IP Address |
-----------------------------------------------------------------------
| Destination IP Address |
-----------------------------------------------------------------------
| Options |
==================================== ===
| Data |
-----------------------------------------------------------------------
Figure 6-14 IPv4 Data Package Format
struct ip_header
248
Embedded Systems Development and Labs; The English Edition
};
ip_hl: IP Header length. Based on 4 bytes unit. The length of IP header is fixed as 20 bytes. If there are no
options included, this value is 5.
ip_off: Fragment Offset. Used with the above IP for reunite fragments.
ip_ttl: Time to live. Minus 1 when passing a route, throw away the data package until this value becomes 0.
ip_p: Protocol. The higher layer protocols that create this package. TCP or UDP,for example.
The IP address is actually a method used to unite the network physical addresses with the higher layer software
via Internet Layer. This method uses uniform address format via a uniform management. Different hosts within
the Ethernet have different addresses. In IPv4, each host IP address is 32 bits that consists of 4 bytes. In order to
conveniently read the address by the users, decimal with dot separation format is used. For example,
211.154.134.93 is the IP address of Embedded Development Network Website. Each IP address has two parts.
The network section describes the type of different scale networks. The host section describes the address of the
249
Embedded Systems Development and Labs; The English Edition
host in the network. According to the size of the network scale, the IP address can be divided into five classes A,
B C, D, E and F. Among these classes, A, B and C are used as the main address types. D class address is used as
multi transmission address for multicasting. E class address is used as an extended optional address.
(2) TCP Protocol
If an IP package has a packaged TCP package, the IP layer will transmit this package to the higher TCP layer.
The TCP will sort the packages and do error checking. A virtual circuit connection will also be established. TCP
package has a series number and an acknowledgment. The received package will be sorted by the series number.
The damaged package will be re-transmitted.
The TCP sends its package to the higher layer programs such as Telnet service program or client programs.
Application programs will alternatively send the message back to the TCP layer. The TCP layer will send the
message down to the lower IP layer, device driver and physical media and at last to the end receiver. The format
of the TCP protocol data package header is shown in Figure 6-15.
0 4 8 10 16 24 32
-----------------------------------------------------------
| Source Port | Destination Port |
-----------------------------------------------------------
| Series number |
-----------------------------------------------------------
| Acknowledgment Number |
-----------------------------------------------------------
| | |U|A|P|S|F| |
| HL | Reserved |R|C|S|Y|I| Window |
| | |G|K|H|N|N| |
-----------------------------------------------------------
| Checksum | Emergency Pointer |
-----------------------------------------------------------
| Options | Fills |
-----------------------------------------------------------
Figure 6-15 TCP Protocol Data Package Header Format
For detail information about the TCP protocol, please refer to the related documentations. A TCP session is
established by a three times handshake initialization. The purpose of three times handshake initialization is to
synchronize the data transmission, inform other hosts about the data quantity it can be received at one time and
establish the virtual connection. The simplified process of three times handshake initialization is as following:
(1) Initialize the host and send a session request.
(2) The receiver host replies by sending a data segment with the following items: synchronization flag, the
250
Embedded Systems Development and Labs; The English Edition
series number of the data that will be sent, acknowledgment with the next series number of next data segment
that will be received.
(3) Request the host to send another data segment with acknowledges series number and acknowledge number.
UDP is at the same layer as the TCP protocol. UDP do not perform data package series, error checking or
retransmission. As a result, UDP is not used to virtual circuit services or connection oriented services. UDP is
mainly used by those polling-answer services, NFS for example. These services require less information
exchanging than FTP or Telnet. UDP services include NTP (Network Time Protocol) and DNS (DNS also use
TCP). The header of UDP package is shown at Figure 6-16.
0 16 32
---------------------------------------------------------------
| UDP Source Port | UDP Target Port |
---------------------------------------------------------------
| UDP Datagram Length | UDP Datagram Checksum |
---------------------------------------------------------------
Figure 6-16 UDP Protocol Data Package Header Format
2. If the target address of the target host mapping cannot be found, the ARP protocol will broadcast the
251
Embedded Systems Development and Labs; The English Edition
source host IP address and hardware address. All hosts in the network will receive this request via
multicasting and process the request.
3. Every host in the network receives the muticast request and searches for the corresponding IP address.
4. When the target host finds that the IP address broadcasted is the same as its own IP address, the target
host will send an ARP reply to inform its hardware address to the source host. The target host also
updates its ARP buffer with the source host IP address and hardware address. The source host will
establish a communication after receives the reply.
For more detailed information about ARP, please refer to related RFC documentation.
(6) TFTP Protocol
TFTP is a simple protocol for transferring files. It is based on the UDP protocol. It supports user receive/send
files from/to a remote host computer. This protocol is suitable only for small files. It doesn’t have same
functions as the FTP protocol. It can only receive or write files from/to the host server computer. It can’t list file
directory, no verification, it only transfers 8 bit type data.
Because TFTP uses UDP and UDP uses IP, and IP can communicate using other methods, a TFTP data package
includes the following segments: local header, IP header, data package header, TFTP header, and the TFTP data.
The TFTP doesn’t specify any data in the IP header but it uses UDP source and target address and length. The
TID used in TFTP is a port number that must be within 0-65535 range.
The initial connection needs to send WRQ (Write Remote Request) or RRQ (Read Remote Request) and receive
an acknowledgment message, a definite data package or the first data block. Normally an acknowledgment
package includes a package number. Every data package has its block number. The block number start from 0
and the numbers are continuous. The WRQ is a special package and its block number is 0. If the receiver
receives a wrong package, the received package will be rejected. When a connection is created, the two
communicating parts will randomly select a TID. Because the selection is random, the chance of the same TID
is very small. Each package has two IDs, one is for the sender, and the other is for the receiver. In the first
request, the package will be sent to port 69 of the receiver host. When the receiver host sends an
acknowledgment, it will use a selected TID as the source TID and use the TID in the former package as its target
TID. These two IDs will be used in the entire process of communication.
After the connection is created, the first data package with series number 1 will be sent from the host. Later on,
the two hosts must guarantee to communicate with the specified TIDs. If the source ID is not the same as the
specified ID, the data package will be thrown away as a message that is being sent to a wrong address.
For more detailed information about TFTP, please refer to related RFC documentation.
252
Embedded Systems Development and Labs; The English Edition
Server End
Create a server-end socket
Client End
Listen to the connection
Create a client-end socket
requests from clients
The most commonly used Socket interface functions are the following:
253
Embedded Systems Development and Labs; The English Edition
#include <stdio.h>
#include <stdlib.h>
#include <errno.h>
#include <string.h>
#include <sys/types.h>
#include <netinet/in.h>
#include <sys/socket.h>
#include <sys/wait.h>
void main()
{
int sockfd;
struct sockaddr_in my_addr; /* my address information */
struct sockaddr_in their_addr; /* connector's address information */
254
Embedded Systems Development and Labs; The English Edition
{
perror("socket");
exit(1);
}
my_addr.sin_family = AF_INET; /* host byte order */
my_addr.sin_port = htons(MYPORT); /* short, network byte order */
my_addr.sin_addr.s_addr = INADDR_ANY; /* auto-fill with my IP */
bzero(&(my_addr.sin_zero),; /* zero the rest of the struct */
{
perror("bind");
exit(1);
}
addr_len = sizeof(struct sockaddr);
if ( (numbytes=recvfrom(sockfd, buf, MAXBUFLEN, 0, \
(struct sockaddr *)&their_addr, &addr_len)) == -1 )
{
perror("recvfrom");
exit(1);
}
printf("got packet from %s\n",inet_ntoa(their_addr.sin_addr));
printf("packet is %d bytes long\n",numbytes);
buf[numbytes] = '\0';
printf("packet contains \"%s\"\n",buf);
close(sockfd);
}
255
Embedded Systems Development and Labs; The English Edition
(4) Connect the Embest Emulator to the target board. Open the TFTP_Test.ews project file in the TFTP_Test
sub directory in the sample directory. After compiling and linking, connect to the target board and download the
program.
(5) Run the TFTPDown.exe on PC, input the target board address 192.192.192.7. Input the address 0x30000 at
the Flash Start Address. Select the file that needs to be downloaded (bin, elf, etc. maximum 1M). Click the
Download button. The program will download the file into the flash of the target board using the TFTP protocol.
Success or error message will be prompted at the dialog box.
(6) Stop the target board run the Embest IDE. Open the Memory window and display the content from address
0x30000. Check if the data in flash is consistent with the downloaded file.
(7) After understanding the functionality of the lab, finish the Lab exercises.
Sample Programs
void Tftp_Test()
256
Embedded Systems Development and Labs; The English Edition
{
char* pData;
unsigned long write_addr;
char input_string[64];
char tmp_ip[4] = {0,0,0,0};
int tmp,len,i,j,num=0;
int b10 =0; int b100 =0; int flag=0;
if(num != 3) flag = 1;
else
{
num = i - 2; j =0;
for( i = num; i >= 0; i--)
{
if(input_string[i] != '.' )
{
if((input_string[i] < '0' | input_string[i] > '9')) flag = 1;
else
{
257
Embedded Systems Development and Labs; The English Edition
b10 = 1;
if(tmp < 256) tmp_ip[j] += tmp; else local_ip = 0x4dc0c0c0;
}
if(!flag)
{
Uart_Printf("\nManual Set local ip %d.%d.%d.%d\n",
tmp_ip[3],tmp_ip[2],tmp_ip[1],tmp_ip[0]
);
local_ip = ((tmp_ip[0]<<24))+((tmp_ip[1]<<16))\
+((tmp_ip[2]<<8))+tmp_ip[3];
}else
Uart_Printf("\nIP address error (xxx.xxx.xxx.xxx)!\n");
}// yes
else if(i == 'D' || i == 'd') {
local_ip = 0xc800a8c0; // config local ip 192.168.0.200
for( ; ; )
{
if( Uart_GetKey() )
return;
write_addr = (pData[0])+(pData[1]<<8)+(pData[2]<<16)+(pData[3]<<24);
pData = pData + sizeof(long);
258
Embedded Systems Development and Labs; The English Edition
259
Embedded Systems Development and Labs; The English Edition
PCM (Pulse Code Modulation) is used for sampling the voice signal and coding each sample. ITU-T 64kb/s
standard G.711 is based on the PCM method. The sample frequency is 8khz. Each sample is coded with
nonlinear u law or A law. The speed is 64 kb/s.
The CD voice using PCM coding, the sample frequency is 44khz, every sample uses 16-bit coding.
The PCM voice file used in Windows is a wav format file t.wav that uses 44.100 kHz sample frequency, 16 bit
code dimensional sound stereo.
Other coding methods include ADPCM (Adaptive Differential Pulse Code Modulation), LPC (Linear Predictive
Coding) and LD-CELP (Low Delay – Code Excited Linear Prediction) etc.
The current trend of coding format includes MP3 (MPEG Audio Layer 3), WMA (Windows Media Audio) and
RA (Real Audio). Some features of these coding formats is that they are used on the network, support playing
while reading, etc.
2. IIS Voice Interface
IIS is a serial bus design technology developed by SONY, Philips, etc. It is an interface standard for voice
processing technology and devices such as CD, digital voice processors, etc. IIS separates the clock signal from
the voice signal in order to avoid the clock jitter.
IIS processes only voice data. Other data (such as control signals) are transferred separately. IIS bus has only 3
serial lines that are: time multiplexing Serial Data (SD) line, Word Selection (WS) line, and Continuous Serial
Clock (CSK) line.
The IIS system interconnection diagram is shown in Figure 6-18.
260
Embedded Systems Development and Labs; The English Edition
WSD signal line indicates what channel (left or right) will be used for data transfer. SD signal line enables the
voice data transmission from the MSB (most significant bit) to the LSB (low significant bit). The MSB will
always be transferred in the first clock period after the WS signal is toggled. If the data length does not match,
the receiver or sender will automatically intercept or fill the data. For more information, please refer to the IIS
specification presented in the ScC44BOX User’s Manual.
3. Circuit Design
1) S3C44B0 IIS
(1) Signal Lines
The IIS bus has five lines:
● Serial data input (IISDI): The SD signal line of the IIS bus. Input.
● Serial data output (IISDO): The SD signal line of the IIS bus. Output.
● Left/right channel select (IISLRCK): The WS signal line of the IIS bus. Sampling clock.
● Serial bit clock (IISCLK): The SCK signal line of the IIS bus.
● CODECLK is generally 256 (256fs) or 384 (384fs) times the sample frequency (fs). CLDELEK is obtained
from the main CPU clock frequency. The CPU timer registers can be configured through programming. The
value for the frequency division can be from 0 to 16.The relationship of CODECLK and sample frequency
is shown is Table 6-1. It needs to correctly select the IISLRCK and CODEECLK.
(2) Registers
There are three registers related to IIS:
● IIS Control Register IISCON. IISCON can access the FIFO ready flag, enable or disable transmit DMA
service, enable IISLRCK, IIS prescaler and IIS interface.
● IIS Mode Register IISMOD. IISMOD can select master-slave mode, send-receive mode, active level, serial
data bit per channel, select CODECLK and IISRCK.
● IIS Prescaler Register IISPSR.
261
Embedded Systems Development and Labs; The English Edition
register IISFIF. In DMA mode, the DMA controller completely controls the data transfer to/from FIFO. The
DMA controller automatically sends/receives data according to the status of the FIFO.
2) UDA1341TS Chip
The UDA1341TS is a voice CODEC made by Philips. UDA1341TS can convert analog dimensional stereo
sound into digital signal and vise versa. It can process the analog signal using PGA (Programmable Gain Access)
and AGC (Automatic Gain Control) functions. For digital signals, this chip also provides special DSP functions.
UDA1341TS is widely used in MDs, CDs, Notebooks, PCs and Camcoders.
The UDA1341TS provides two groups of voice signal input lines, one group of signal output lines, one group of
IIS bus interface lines, and one group of L3 bus lines.
The IIS bus interface lines include clock line BCK, word selection line WS, data input line DATAI, data output
line DATAO and voice system clock SYSCLK.
The L3 bus lines includes microprocessor interface data line L3DATA, microprocessor interface mode line
L3MODE, microprocessor interface clock line L3CLOCK. The microprocessor can configure the UDA1341TS
voice processing parameters and system control parameters through the L3 bus. However, the S3C44B0X has
no L3bus and the general I/O ports must be used to connect to the UDA1341TS L3 bus. For the L3 bus time
sequence and control methods, please refer to UDA1341TS_datasheet.
3) Circuit Interconnection
The IIS interface circuit is shown in Figure 6-20.
IISLRC WS VOUT
SPEAK
VOUT
IISD DAT
IISD DATA
IISCL BC
PA L3DAT VINL
Micropho
DQM L3MO VINR
DQM L3CLOCK
CODE SYSCL
44B0 UDA1341
Figure 6-20 IIS Interface Circuit
262
Embedded Systems Development and Labs; The English Edition
/*********************************************************************
* name: IISInit
* func: Initialize IIS circuit
* para: none
263
Embedded Systems Development and Labs; The English Edition
* ret: none
* modify:
* comment:
********************************************************************/
void IISInit(void)
{
rPCONE = (rPCONE&0xffff)+(2<<16); // Set I/O port PE8 output CODECLK signal
iDMADone = 0;
/* initialize philips UDA1341 chip */
Init1341(PLAY);
}
/********************************************************************
* name: Init1341
* func: Init philips 1341 chip
* para: none
* ret: none
* modify:
* comment:
******************************************************************/
void Init1341(char mode)
{
/* Port Initialize */
rPCONA = 0x1ff; // set PA9 as output and connect to L3D
rPCONB = 0x7CF; // set PG5:L3M connect to PG4:L3C
rPDATB = L3M|L3C; // L3M=H(start condition),L3C=H(start condition)
/* L3 Interface */
_WrL3Addr(0x14+2); // status (000101xx+10)
#ifdef FS441KHZ
_WrL3Data(0x60,0); // 0,1,10,000,0 reset,256fs,no DCfilter,iis
#else
_WrL3Data(0x40,0); // 0,1,00,000,0 reset,512fs,no DCfilter,iis
#endif
264
Embedded Systems Development and Labs; The English Edition
/*******************************************************************
* name: _WrL3Addr
* func: write control data address to 1341 through L3-interface
* para: data -- control data address
* ret: none
* modify:
* comment:
********************************************************************/
void _WrL3Addr(U8 data)
{
U32 vPdata = 0x0; // L3D=L
U32 vPdatb = 0x0; // L3M=L(in address mode)/L3C=L
S32 i,j;
265
Embedded Systems Development and Labs; The English Edition
/*********************************************************************
* name: _WrL3Data
* func: write control data to 1341 through L3-interface
* para: data -- control data
* halt -- halt operate
* ret: none
* modify:
* comment:
******************************************************************/
void _WrL3Data(U8 data,int halt)
{
U32 vPdata = 0x0; // L3D=L
U32 vPdatb = 0x0; // L3M/L3C=L
S32 i,j;
266
Embedded Systems Development and Labs; The English Edition
if(halt)
{
rPDATB = L3C; // L3C=H(while tstp, L3 interface halt condition)
for( j=0; j<4; j++ ) // tstp(L3) > 190ns
;
}
rPDATB = L3C|L3M; // L3M=H(in data transfer mode)
for( j=0; j<4; j++ ) // tsu(L3)D > 190ns
;
267
Embedded Systems Development and Labs; The English Edition
6.3.6 Exercises
(1) Write a program that implements the function of adjusting the voice volume via button.
(2) Write a program that implements the recording function.
268
Embedded Systems Development and Labs; The English Edition
Application Software
269
Embedded Systems Development and Labs; The English Edition
The difference between these two functions is that the place for storing the variable temp is different. In the first
function, “temp” is a global variable. In the second function, “temp” is a local variable. As a result, the upper
function is not reentrant function. The lower function is a reentrant function.
2) Use C Language to Enable/Disable Interrupts
This can be done through the CPSR register within the ARM processor. The CPSR register has a global
interrupt disable bit. Controlling this bit can enable/disable interrupts.
3) Microprocessor Supports Interrupts and Supports Timer Interrupts (Ticks)
All of the ARM processor cores support interrupts and they can generate timer interrupts.
4) Microprocessor Provide Hardware Support for Stack Control
270
Embedded Systems Development and Labs; The English Edition
For the 8-bit microprocessors that have only 10 address lines, the chip can only access a maximum of 1Kb
memory. For these processors it is difficult to port the uC/OS-II kernel.
5) Microprocessor has Stack Pointer and Other Instructions for Reading Registers and Store the
Contents of Register to Memory or Stack.
The ARM processor has STMFD instruction for pushing the content of registers to stack, LDMFD instruction
for pulling the register contents back from stack..
271
Embedded Systems Development and Labs; The English Edition
(4) OSTickISR() function is a time tick function generated by the timer interrupt. OSTickISR() is responsible
for saving the microprocessor registers and recovering the registers when the task switching is finished.
3) Porting OS_CPU_C.C File
The third step of porting the uC/OS-II kernel is to port the OS_CPU_C.C file. There are 6 functions in this file
that need to be ported.
OSTaskStkInit()
OSTaskCreateHook()
OSTaskDelHook()
OSTaskSwHook()
OSTaskStatHook()
OSTaskTickHook()
The last 5 functions are called hook functions and are used mainly for extending the functions of uC/OS-II. Note
that these functions don’t have to contain code.
The only function that really needs to be ported is the OSTTaskStkInit(). This function is called when the task is
created. This function is responsible for initializing the stack architecture for tasks. This function can be in the
same form for porting to most of the ARM processors.
Please refer to the following sample programs.
272
Embedded Systems Development and Labs; The English Edition
# OSPrioCur = OSPrioHighRdy
LDR r4, addr_OSPrioCur
LDR r5, addr_OSPrioHighRdy
LDRB r6, [r5]
STRB r6, [r4]
# OSTCBCur = OSTCBHighRdy
STR r6, [r4] @ set new current task TCB address
#;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
#Change Supervisor mode
#!!!r12 register don't preserved. (r12 that PC of task)
273
Embedded Systems Development and Labs; The English Edition
#;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
#Now Supervisor mode
#;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
STR r12, [sp, #-8] @ saved r12
LDR r12, SAVED_LR @LDR r12, [pc, #SAVED_LR-.-8]
STMFD sp!, {r12} @ r12 that PC of task
SUB sp, sp, #4 @ inclease stack point
LDMIA sp!, {r12} @ restore r12
STMFD sp!, {lr} @ save lr
STMFD sp!, {r0-r12} @ save register file and ret address
MRS r4, CPSR
STMFD sp!, {r4} @ save current PSR
MRS r4, SPSR @ YYY+
STMFD sp!, {r4} @ YYY+ save SPSR
# OSPrioCur = OSPrioHighRdy
LDR r4, addr_OSPrioCur
LDR r5, addr_OSPrioHighRdy
LDRB r6, [r5]
STRB r6, [r4]
# OSTCBCur = OSTCBHighRdy
STR r6, [r4] @ set new current task TCB address
274
Embedded Systems Development and Labs; The English Edition
Exercises
(1) Expand the function of uC/OS-II. Add time calculation of task switching.
(2) Trace OsTickISR() function. Watch the task switching process in timer pacing.
275
Embedded Systems Development and Labs; The English Edition
(3) Describes boot task. Transfer the address of task function, task stack and task priority.
(4) The boot process is done by function main(). This function includes hardware initialization before running
tasks, operation system initialization, start timer interrupt, boot tasks, etc.
276
Embedded Systems Development and Labs; The English Edition
277
Embedded Systems Development and Labs; The English Edition
OSSemPost(UART_sem);
OSTimeDly(180);
}
}
}
void Task3 (void *Id)
{
char *Msg;
int i=0;
/* print task's id */
OSSemPend(UART_sem, 0, &err);
uHALr_printf(" Task%c Called.\n", *(char *)Id);
OSSemPost(UART_sem);
while(1)
{
OSTimeDly(900);
OSSemPend(UART_sem, 0, &err);
EV40_rtc_Disp();
OSSemPost(UART_sem);
}
}
278
Embedded Systems Development and Labs; The English Edition
279
Embedded Systems Development and Labs; The English Edition
7.2.6 Exercises
Improve the program by implementing inter-task communication and synchronization such that every time
when the 8-SEG LED displays a character the serial port also outputs the same character.
280
Embedded Systems Development and Labs; The English Edition
when the state is changed from CLEAR to COUNT, the msCntr is cleared to restart the millisecond
counter in the time update taks. When the CLEAR mode is entered, the display must be cleared one
time at the transition so it is done by this task. Notice that the buffer must be written to twice to clear
old buffer contents.
(5) DispTimeTsk(). This display task displays the current elapsed time by waiting for a value to be written
to the display ring buffer. It then uses BufRead() to copy the time value stored in the ring buffer into a
local display buffer. By using the ring buffer technique, the other tasks will not be blocked to wait for
the display.
main.c file
//Task definition
/* allocate memory for tasks' stacks */
#define STACKSIZE 128
/* Global Variable */
unsigned int Stack1[STACKSIZE];
unsigned int Stack2[STACKSIZE];
unsigned int Stack3[STACKSIZE];
unsigned int Stack4[STACKSIZE];
unsigned int StackMain[STACKSIZE];
281
Embedded Systems Development and Labs; The English Edition
OSSemPend(UART_sem, 0, &err);
uHALr_printf(" Task%c Called.\n", *(char *)Id);
OSSemPost(UART_sem);
while(1)
{
led1_on();
led2_off();
OSTimeDly(800);
led1_off();
led2_on();
OSTimeDly(800);
}
}
/* print task's id */
OSSemPend(UART_sem, 0, &err);
uHALr_printf(" Task%c Called.\n", *(char *)Id);
OSSemPost(UART_sem);
while(1)
{
for(i=0; i<16; i++)
{
OSSemPend(UART_sem, 0, &err);
NowTime=OSTimeGet(); //»ñȡʱ¼ä
//uHALr_printf("Run Times at:%d\r", NowTime);
OSSemPost(UART_sem);
OSTimeDly(180);
}
}
}
void Task3 (void *Id)
{
char *Msg;
int i=0;
/* print task's id */
OSSemPend(UART_sem, 0, &err);
282
Embedded Systems Development and Labs; The English Edition
OSSemPend(UART_sem, 0, &err);
EV40_rtc_Disp();
OSSemPost(UART_sem);
}
}
/* print task's id */
OSSemPend(UART_sem, 0, &err);
uHALr_printf(" Task%c Called.\n\n", *(char *)Id);
OSSemPost(UART_sem);
while(1)
{
value = key_read();
// display in 8-segment LED
if(value > -1)
{
Digit_Led_Symbol(value);
OSTimeDly(90);
}
OSTimeDly(90);
}
}
283
Embedded Systems Development and Labs; The English Edition
/*
* create the first Semaphore in the pipeline with 1
* to get the task started.
*/
UART_sem = OSSemCreate(1);
/*
* create the tasks in uC/OS and assign decreasing
* priority to them
*/
OSTaskCreate(Task1, (void *)&Id1, &Stack1[STACKSIZE - 1], 2);
OSTaskCreate(Task2, (void *)&Id2, &Stack2[STACKSIZE - 1], 3);
OSTaskCreate(Task3, (void *)&Id3, &Stack3[STACKSIZE - 1], 4);
OSTaskCreate(Task4, (void *)&Id4, &Stack4[STACKSIZE - 1], 5);
ARMTargetStart();
// Delete current task
OSTaskDel(OS_PRIO_SELF);
/* needed by uC/OS */
OSInit();
OSTimeSet(0);
284
Embedded Systems Development and Labs; The English Edition
Using the examples presented so far in this chapter implement an intruder alarm application using the uC/OS-II
kernel. The following describes the intruder alarm application.
An intruder alarm system receives information about the state of the monitored building from a number of
sensors located at every possible entrance and exit. Sensors function basically as switches, indicating whether a
given sensor has detected an intruder or not. The alarm is located inside the building. It is set (armed) and reset
(disarmed) from inside the building. A digital code of fixed length is required for both setting and resetting the
alarm. One of the entrances, which also functions as an exit, is nominated as the entrance and the exit after the
alarm has been set.
Timing information is crucial for proper functioning of an intruder alarm. When the alarm is initially set, a
specific time delay is allowed for the user to leave the building through the nominated exit. When the alarm is
set, the use of any of the entrances other than the nominated one for re-entry activates the alarm instantly or, at
most, within a matter of a few seconds. The sensors monitoring the entrance nominated for re-entry and the
route to the alarm control point do not activate the alarm until a set time has elapsed. This set time allows the
user to enter the building and disarm the alarm by entering the correct digital code. If this is not done
successfully, the alarm is activated at the end of the set time.
The alarm system has a siren and a strobe and these are located outside the building. If an intruder is detected or
the alarm is not disarmed by the person entering the building through the nominated entrance during the
required time, the siren begins to sound and the strobe begins to flash immediately, as mentioned above. In this
event, the siren continues to sound for a specified time, usually for a few minutes, and then stops, but the strobe
continues to flash. The alarm can be reset by the user only by entering the correct code. If the alarm has already
been triggered, this would turn the alarm off. The correct code is the most up to date code entered when arming
the system.
When entering the code for disarming the alarm, the user is allowed a maximum period to complete the task. If
the user fails to complete this within the given time, the system discards the partial entry and awaits for the next
attempt. The user is allowed as many attempts as possible to enter the correct code within the allocated time. If
the alarm has already been set off, after this period it cannot be reset except by an appointed independent
authority.
Some reasonable limiting values for the timing parameters involved are:
a. Time allowed for setting the alarm and leaving the building – 30 seconds
b. Time between detecting an intruder and triggering the alarm off – 5 seconds
c. Time allowed for re-entry through the nominated entrance and start resetting the alarm – 2 minutes
d. Duration for resetting the alarm after re-entry – 1 minute
e. Maximum duration for entering the code at each attempt – 20 seconds
f. Duration of the siren sound – 5 minutes
285
Embedded Systems Development and Labs; The English Edition
NOTE: In this application you can use the keypad in order to simulate the entrance and exit switches; the 8-SEG
LED or the LCD to perform the flashing; the earphone to simulate the siren sound.
286
Embedded Systems Development and Labs; The English Edition
Reference Documentations
287