You are on page 1of 126

UNIVERSITI TEKNOLOGI MALAYSIA

DECLARATION OF THESIS / UNDERGRADUATE PROJECT PAPER AND COPYRIGHT

Authors full name : AHMAD RIDWAN MUSHOFFA


Date of birth

: 5

Title

: MASTER/SLAVE CONTROLLER USING ENCRYPTED


SERIAL COMMUNICATION PROTOCOL

TH

NOVEMBER 1989

Academic Session:I 2011/2012


hereby declare that
I declare that this thesis is classified as :

I have read this thesis and in

my opinion this thesis is sufficient in terms of scope and quality


for the reward of the degree of

CONFIDENTIAL
(ContainsEngineering
confidential(Computer)
information under the Official Secret
Bachelor of Electrical
Act 1972)*

RESTRICTED

(Contains restricted information as specified by the


organization where research was done)*

OPEN ACCESS

I agree that my thesis to be published as online open access

I acknowledged that Universiti Teknologi Malaysia reserves the right as follows:


1. The thesis is the property of Universiti Teknologi Malaysia.
2. The Library of Universiti Teknologi Malaysia has the right to make copies for the purpose
of research only.
3. The Library has the right to make copies of the thesis for academic exchange.

Signature

________________________
Certified by :

Name of Supervisor

En. Zulfakar Aspar

SIGNATURE

Date

200707M10019

SIGNATURE OF SUPERVISOR

(NEW IC NO. /PASSPORT NO.)

Date : 5 JULY 2012

NOTES :

5TH July, 2012

EN. ZULFAKAR ASPAR


NAME OF SUPERVISOR

Date : 5 JULY 2012

If the thesis is CONFIDENTAL or RESTRICTED, please attach with the letter from
the organization with period and reasons for confidentiality or restriction.

I hereby declare that I have read this report and in


my opinion this report is sufficient in terms of scope and quality
for the award of the degree of
Bachelor of Electrical Engineering (Computer)

Signature

_______________________

Supervisors Name

En. Zulfakar bin Aspar

Date

5TH July, 2012

MASTER/SLAVE CONTROLLER USING ENCRYPTED


SERIAL COMMUNICATION PROTOCOL

AHMAD RIDWAN MUSHOFFA

A report submitted in partial fulfillment of the


requirements for the award of the degree of
Bachelor of Electrical Engineering (Computer)

Faculty of Electrical Engineering


Universiti Teknologi Malaysia

JULY 2012

ii

I declare that this thesis entitled Master/Slave Controller using Encrypted Serial
Communication Protocol is the result of my own research except as cited in the
references. The thesis has not been accepted for any degree and is not concurrently
submitted in candidature of any other degree.

Signature

....................................................

Name

AHMAD RIDWAN MUSHOFFA

Date

5TH July, 2012

iii

To my self, my beloved parents, family, and friends.

iv

ACKNOWLEDGEMENT

Bismillahirrahmanirrahim, in the name of Allah S.W.T. the Most Gracious


and Most Merciful, who always gives me the strength to withstand all drawback and
constraints toward completion of this project.

First of all, I would like to express my great gratitude to my parents and


family who always give their love, support, and stand by my side in any condition.
Without them I could not encounter any setbacks stand before me.

I would like to express my gratitude and sincere appreciation to my


supervisor, En. Zulfakar Aspar for his guidance, passion, encouragement, and advice
given to me throughout the process of this project. Without his support this project
would not have been realized.

Nevertheless, I also would like to express my gratitude to all my friends for


their support upon completion of this project.

ABSTRACT

Serial communication has been widely used to establish communication


between two or more devices. The high transfer data rate makes serial
communication a better consideration than other transmission media. Some standard
protocols also use serial communication as transmission media. Modbus RTU is a
standard protocol which implements serial communication as a basis of data
transmission and has been used for years which is industrial proven. The ability to
transmit continuous data stream over serial line without inter-character hesitations
and ensure data reliability make Modbus a superior and well-known communication
protocol. In addition, it allows communication between many devices connected to
the same network with error check mechanism using Cyclic Redundancy Check
(CRC) checksum to ensure the reliability of data. Moreover, the extensive use of
Modbus with the royalty-free, more efficient to deploy and maintain, and allow to
handle many devices lead Modbus as a topnotch standard protocol in industry field.
The project extends the regular design of Modbus RTU device by developing a
programmable Modbus device on AVR platform and enhances it with security in
data transmission.

vi

ABSTRAK

Komunikasi bersiri telah digunakan secara meluas untuk mewujudkan


komunikasi antara dua atau lebih peranti. Kadar data pemindahan tinggi membuat
komunikasi bersiri pertimbangan yang lebih baik daripada media penghantaran lain.
Beberapa protokol standard juga menggunakan komunikasi bersiri sebagai media
penghantaran. Modbus RTU adalah protokol standard yang melaksanakan
komunikasi bersiri sebagai asas penghantaran data dan telah digunakan selama
bertahun-tahun yang perindustrian terbukti. Keupayaan untuk menghantar aliran data
berterusan melalui talian bersiri tanpa antara aksara hesitations dan memastikan
kebolehpercayaan data membuat Modbus protokol komunikasi yang unggul dan
terkenal. Di samping itu, ia membolehkan komunikasi antara peranti banyak yang
disambungkan kepada rangkaian yang sama dengan mekanisme semak ralat
menggunakan Cyclic Redundancy Check (CRC) checksum untuk memastikan
kebolehpercayaan data. Selain itu, penggunaan meluas Modbus dengan bebas royalti,
lebih cekap untuk menggunakan dan menyenggara, dan membenarkan untuk
mengendalikan peranti banyak membawa Modbus sebagai protokol standard nombor
wahid dalam bidang industri. Projek memanjangkan reka bentuk tetap alat RTU
Modbus oleh membangunkan peranti Modbus yang yang diprogramkan pada
platform AVR dan meningkatkan dengan keselamatan dalam penghantaran data.

vii

TABLE OF CONTENT

CHAPTER

TITLE

PAGE

DECLARATION

ii

DEDICATION

iii

ACKNOWLEDGEMENTS

iv

ABSTRACT

ABSTRAK

vi

TABLE OF CONTENTS

vii

LIST OF TABLES

LIST OF FIGURES

xi

LIST OF ABBREVIATIONS

xiii

LIST OF SYMBOLS

xv

LIST OF APPENDICES

xvi

INTRODUCTION

1.1

Project Background

1.2

Problem Statement

1.3

Objectives of Project

1.4

Scope of Project

1.5

Project Schedule

LITERATURE REVIEW

2.1

2.2

Serial Communication
2.1.1

Synchronous Format

2.1.2

Asynchronous Format

Programmable Logic Controller (PLC)

viii
2.3

Modbus-RTU
2.3.1

10

2.4

Tiny Encryption Algorithm

12

2.5

Microcontroller

14

2.5.1

Atmel AVR ATmega324P

14

2.5.2

Pin Configuration

18

2.5.3

Block Diagram

19

2.6

Message Framing

RS-232 Interface

20

METHODOLOGY

22

3.1

Project Flow

22

3.2

Master/Slave Controller Device

25

3.3

Modbus-RTU Protocol

27

3.3.1

Slave Controller Process State

29

3.3.2

Transceiver State

30

3.3.3

Interrupt Service Routine

31

3.4

Secured Communication Protocol

32

3.5

Integrating Tiny Encryption Algorithm and Modbus

34

Protocol
3.6

36

DEVELOPMENT PROCESS

38

4.1

Tiny Encryption Algorithm Simulation

38

4.2

Modbus-RTU Development

41

4.3

Software Development Stage

48

4.3.1

AVR Studio 6

48

4.3.2

Modular Programming

49

4.4

Programming Interface

Hardware Programming

51

RESULTS AND DISCUSSION

54

5.1

Simulation Result

54

5.2

Experimental Result

56

ix
6

CONCLUSION AND RECOMMENDATIONS

61

6.1

Conclusion

61

6.2

Recommendations

62

REFERENCES

64

APPENDICES

66

LIST OF TABLES

TABLE NO.

TITLE

PAGE

5.1

Data Log Summary of Experiment 1

58

5.2

Data Log Summary of Experiment 2

59

5.3

Data Log Summary of Experiment 3

60

xi

LIST OF FIGURES

FIGURE NO.

TITLE

PAGE

1.1

Project Schedule for Semester 1

1.2

Project Schedule for Semester 2

2.1

Serial Transmission Data Frame

2.2

Synchronous Data Transmission Format

2.3

Asynchronous Data Transmission Format

2.4

PLC Structure Block Diagram

2.5

Ladder Logic Diagram

2.6

Modbus Communication Response

2.7

Modbus-RTU Network

10

2.8

Modbus-RTU Frame Format

11

2.9

Modbus Function Codes

11

2.10

TEA Block Diagram

12

2.11

TEA Feistel Cycle

13

2.12

ATmega324P I/O Pinout Diagram

18

2.13

ATmega324P Block Diagram

19

2.14

DB-9 Pinout Diagram

20

2.15

RS-232 Interface Connects two Devices

21

3.1

Project Flow Chart

23

3.2

AVR Wise-SDK Board

25

3.3

Wise-SDK Particular System Architecture

26

3.4

Slave Controller General State Cycle

27

3.5

State Status Dependencies

28

3.6

Process State Flowchart

29

xii
FIGURE NO.

TITLE

PAGE

3.7

Transceiver State Diagram

30

3.8

Interrupts on Software Development

31

3.9

Encryption on Modbus Frame

32

3.10

Secured Communication Flow

33

3.11

TEA Implementation Flowchart

34

3.12

Test and Verification Process Cycle

35

3.13

USBtiny Programming Process

36

3.14

USBtiny Device

36

3.15

RFI InTerm Windows GUI

37

4.1

Simulation Procedure

39

4.2

TEA Implementation Result on PIC18F4550

40

4.3

Process State Tree Diagram

41

4.4

Timer1-Compare Interrupt Routine

43

4.5

USART0-rx Interrupt Routine

45

4.6

USART0-UDRE Interrupt Routine

47

4.7

AVR Studio 6 Workplace Windows

48

4.8

Dependency Files Tree Diagram

50

4.9

WinAVR Functional Block Process

52

4.10

Hardware Programming Process

52

5.1

Tiny Encryption Algorithm Result

55

5.2

Modbus-RTU Frame Format

56

5.3

Plaintext Data Response

57

5.4

Encrypted Data Response

59

5.5

Incorrect Input Data Response

60

xiii

LIST OF ABBREVIATIONS

ADC

Analog-to-Digital Converter

AES

Advanced Encryption Standard

ALU

Arithmetic Logic Unit

CISC

Complex Instruction Set Computing

CMOS

Complementary Metal-Oxide Semiconductor

CPU

Central Processing Unit

CRC

Cyclic Redundancy Check

DES

Data Encryption Standard

EEPROM

Electrically Erasable Programmable Read-Only Memory

GCC

GNU Compiler Collection

GND

Ground

GUI

Graphical User Interface

I/O

Input-Output

IC

Integrated Circuit

ISP

In-System Programming

ISR

Interrupt Service Routine

IEEE

Institute of Electrical and Electronic Engineering

JTAG

Joint Test Action Group

LLD

Ladder Logic Diagram

LSB

Least Significant Bit

MIPS

Microprocessor without Interlock Pipeline Stages

MSB

Most Significant Bit

PC

Personal Computer

PDIP

Plastic Dual In-Line Package

PLC

Programmable Logic Controller

xiv
PWM

Pulse Width Modulation

RISC

Reduced Instruction Set Computing

RTC

Real-Time Clock

RTOS

Real Time Operating System

RTU

Remote Terminal Unit

SDK

Software Development Kit

SoC

System on Chip

SPI

Serial Peripheral Interface

SRAM

Static Random Access Memory

TEA

Tiny Encryption Algorithm

USART

Universal Synchronous/Asynchronous Receiver/Transmitter

USB

Universal Serial Bus

VCC

Voltage Input

XTAL

External Crystal

xv

LIST OF SYMBOLS

KB

Kilo Bytes

KHz

Kilohertz (frequency symbol)

mA

mili-Ampere

MHz

Megahertz (frequency symbol)

Voltage

xvi

LIST OF APPENDICES

APPENDIX

TITLE

Proposed Design of AVR-based Slave Controller


Device

PAGE

66

Source Code of Borland C for


Tiny Encryption Algorithm Simulation

73

Source Code of AVR Microcontroller ATmega324P

75

for Modbus-RTU and Tiny Encryption Algorithm

CHAPTER 1

INTRODUCTION

1.1.

Project Background

Remote terminal unit to centralize monitoring activity and interfacing distant


devices has been intensively used for automation and control system process. A
digital computer device (master) monitors digital and analog parameters and
transmits data to control machines or peripheral devices as well as receives its
response data. A master device (usually microprocessor) can be interfaced with the
peripheral

devices

(slave)

with

different

communication

media

(serial

communication or Ethernet). Its remote connectivity can support standard protocols


(Modbus, IEC, DNP3, etc.) between master and slave devices.

Serial communication takes a significant part in distant data transmission for


both short distance and long-haul communication and most computer networks as
well. Considering the aspect of cable cost, synchronization, and ease of use makes
serial communication is preferable rather than other transmissions. A serial
connection requires fewer interconnecting cables and hence occupies less space. In
serial connection, crosstalk is less of an issue, because there are fewer conductors
cables. Many ICs also have serial interfaces, so that they have fewer pins and
therefore less expensive. In many cases, serial is a better option because it is cheaper
to implement.

2
In this project, serial communication is used as a main data transmission to
connect master device with several slave devices using Modbus as standard
communication protocol. A different approach in developing master device using
microcontroller will also be introduced as a basis hardware platform.

1.2.

Problem Statement

Remote terminal unit transmission using well-known protocols (standard


protocols) becomes vulnerable due to its standardized and eminent data framing
structure. Security issue arises due to vulnerability hole which leads to security threat
and will result in transmission interception and data manipulation.

1.3.

Objective of Project

The main objective of the project is to develop a secured data transmission


over serial communication line and secured Master/Slave controller by implementing
Tiny Encryption Algorithm (TEA) as security protocol.

1.4.

Scope of Project

The scope of the project is to develop a secured serial communication using


Modbus-RTU protocol and a secured Master/Slave controller PLC-based system
using AVR microcontroller as device platform. The project includes hardware design
of the Master/Slave controller system and implementation of Tiny Encryption
Algorithm (TEA) on RS-232 as serial communication interface.

3
1.5.

Project Schedule

The first phase of project schedule is to comprehend fundamental theory of


projects scope, objectives, and methodology on how to implement and accomplish
desired system to work according to specification as a final outcome. Gantt charts on
Figure 1.1 and Figure 1.2 show the detail of project timeline.

Thesis Preparation

12

Hardware Prototyping

Hardware Design Modification & Adjustment


TEA Implementation
Test & Verification
Modbus-RTU Development
Test & Verification
Secured Modbus Development
Test & Verification
Seminar

Supervisor Meeting
Literature Review

Task

October
8

March
6

Week
9
10

April

Figure 1.2 Project schedule for Semester 2

February

11

12

13

May
12

November
Week
9
10
11

Figure 1.1 Project schedule for Semester 1

Supervisor Meeting
Brief Project Idea
Literature Review
Design & Analysis Hardware Specification
Hardware Schematic Design
Hardware PCB Layout Design
Order Hardware Parts
Seminar
Report Preparation

Task

1
2
3
4
5
6
7
8
9
10
11

No

1
2
3
4
5
6
7
8
9

No

September

14

13

15

14

16

16

17

June

15

December

18

CHAPTER 2

LITERATURE REVIEW

2.1.

Serial Communication

Serial communication is the process of sending data from the transmitter or


driver one bit at a time in sequence order. In serial link, one signal required by all
serial links is a clock to control the flow of data. The transmitter and receiver use a
clock to decide when to send and read each bit.

Figure 2.1 Serial Transmission Data Frame

There are two types of serial-data transmission format, synchronous and


asynchronous data transmission.

6
2.1.1

Synchronous Format

In a synchronous transmission, all devices use a common clock generated by


one of the devices or an external source. The clock may have a fixed frequency or it
may toggle at irregular intervals. All transmitted bits are synchronized to the clock.
In other word, each transmitted bit is valid at a defined time after a clock transition
(rising or falling edge). The receiver uses the clock transition to decide when to tread
each incoming bit.

Figure 2.2 Synchronous Data Transmission Format

Synchronous formats use a variety of ways to signal the start and end of a
transmission, including Start and Stop bits. Synchronous interface is useful for short
links, with cables of 15 feet or less or even between components on a single circuit
board. For longer links, synchronous format is less practical due to the need of
transmitting the clock signal which requires extra line and subject to noise.

7
2.1.2

Asynchronous Format

In asynchronous transmission, the link does not include a clock line because
each end of the link provides its own clock. Each end must agree on the clocks
frequency and all of the clocks must match. Each transmitted byte includes a Start bit
to synchronize the clocks, and one or more Stop bit to signal the end of a transmitted
signal.

An asynchronous transmission may use any of several common formats. The


most common format is 8-N-1, where the transmitter sends each data byte as 1 Start
bit, followed by 8 data bits, beginning with bit 0 (the LSB), and ending with 1 Stop
bit.

Figure 2.3 Asynchronous Data Transmission Format

The N in 8-N-1 indicates that the transmissions do not use a parity bit. Parity
can be Even, Odd, Mark, or Space. With Even parity, the parity bit is set or cleared
so that the data bits plus the parity bit contain an even number of 1s. With Odd
parity, the bit is set or cleared so that these bits contain an odd number of 1s. Mark
and Space parity are forms of Sticky parity: with Mark parity, the parity bit is always
1, and with Space parity it is always 0.

8
2.2.

Programmable Logic Controller (PLC)

Programmable Logic Controller is a special-purpose digital computer based


on one or more microprocessor designed for use in the control of wide variety of
automation and control systems especially in industrial manufacturing machines.
PLC has four major components, microprocessor as the Central Processing Unit
(CPU), memory to store data and information of system software and user program,
input-output (I/O) modules, and power supply.

Figure 2.4 PLC Structure Block Diagram

The PLC is designed for multiple inputs and outputs interface, extended temperature
ranges, immunity to electrical noise, and resistance to vibration and impact. PLC is
also armored to withstand severe conditions such as dust, moisture, heat, and cold.
The feature of multiple I/O allows PLC to have extensive input/output arrangements
as well.

The PLC is programmed in a ladder logic programming; it uses a form of


Boolean algebra or digital gates to program the ladder logic diagram. Ladder logic is
a graphical programming language which represents a program based on the circuit
diagrams of relay logic hardware.

Figure 2.5 Ladder Logic Diagram

2.3.

Modbus-RTU

Modbus is a serial communication protocol derived from the master/slave


architecture. Modbus is a master-slave system, where the master communicates with
one or multiple slaves on different types of busses or network. A master device can
initiate communication to slave devices on Modbus network, while slave device only
can respond request data from the master, a master device on Modbus typically is a
PLC or PC.

Figure 2.6 Modbus Communication Response

Modbus-RTU (Remote Terminal Unit) means that the Modbus protocol is used on a
serial line with RS-232 port as the interface. The original Modbus-RTU scheme runs
over RS-232, however it is possible to adapt RS-485 to gain faster speed, longer
distance, and multi-drop network. It is possible to connect multi-master (usually only

10
2 master devices) on Modbus-RTU network, however the prior master should be
defined that only one master can initiate communication within the network.

Figure 2.7 Modbus-RTU Network

2.3.1. Message Framing

To initiate communication with slave devices, a master device sends a


message containing following data:

Device Address

Function Code

Data

Error Check

The device address can be defined in a number range of 0 to 247, address number 1
to 247 are addresses of specific slave device and address number 0 is for broadcast
messages which will be received by all slave devices. Hence, if the master sends data
to slave address 1 only relevant address will respond the request while the rest of
slave devices will remain on standby for further communication.

11

Figure 2.8 Modbus-RTU Frame Format

The function code defines the command that the slave device is to execute,
such as read data, accept data, and report status. Function codes are in a number
range of 1 to 255 where some function code have sub-function code and the function
is depend on device specification.

Figure 2.9 Modbus Function Codes


The data defines addresses in the devices memory map for reading functions.
It contains data values to be written into the devices memory or contains other
information needed to carry out the function requested.

The error check is a 16-bit numeric value representing the Cyclic


Redundancy Check (CRC). The CRC is generated by the master and checked by the
receiving devices. If the CRC values do not match, the receiving devices ask for a
retransmission of the message.

12
2.4.

Tiny Encryption Algorithm (TEA)

The Tiny Encryption Algorithm (TEA) is a cryptographic algorithm designed


by Wheeler and Needham in 1994. TEA is moderately robust cryptographic system
and it was designed to minimize memory usage while maximize processing speed.
Tiny Encryption Algorithm implies a symmetric block cipher which has simple
structure, fast, and most efficient cryptography algorithm. It operates on a 64-bits
block and has 128-bit key.

Figure 2.10 TEA Block Diagram

TEA is a Feistel type cipher structure which handles operations of orthogonal


algebraic groups. Its cryptographic algorithm consists of shifting, XOR, and ADDing
to provide nonlinearity and a dual shift within its routine process initiates all bits of
data and key to be mixed repeatedly. The Feistel routine reduces the code
implementation by halved of original size which is 64 rounds for TEA iteration
routine. TEA key schedule algorithm is 128-bit length and fragmented into four 32bit blocks.

13
Input: Plaintext

Output: Ciphertext
Figure 2.11 TEA Feistel Cycle

The input of plaintext/ciphertext is divided into two 32-bits value and then mixed
with key schedule and constant value which is

Furthermore,

each input vector text then will be processed through shifting, adding, and XOR as
shown on Figure 2.10. Adding operation will be commenced by using resulting data
through algebraic process from the respected input vector to generate ciphertext, the
routine iteration will be performed 32 times.

14
#include <stdint.h>
void encrypt (uint32_t* v, uint32_t* k) {
uint32_t v0=v[0], v1=v[1], sum=0, i;
uint32_t delta=0x9e3779b9;

/* set up */
/* a key schedule constant */

uint32_t k0=k[0], k1=k[1], k2=k[2], k3=k[3]; /* cache key */


for (i=0; i < 32; i++) {

/* basic cycle start */

sum += delta;
v0 += ((v1<<4) + k0) ^ (v1 + sum) ^ ((v1>>5) + k1);
v1 += ((v0<<4) + k2) ^ (v0 + sum) ^ ((v0>>5) + k3);
}

/* end cycle */

v[0]=v0; v[1]=v1;
}

void decrypt (uint32_t* v, uint32_t* k) {


uint32_t v0=v[0], v1=v[1], sum=0xC6EF3720, i; /* set up */
uint32_t delta=0x9e3779b9;

/* a key schedule constant */

uint32_t k0=k[0], k1=k[1], k2=k[2], k3=k[3]; /* cache key */


for (i=0; i<32; i++) {

/* basic cycle start */

v1 -= ((v0<<4) + k2) ^ (v0 + sum) ^ ((v0>>5) + k3);


v0 -= ((v1<<4) + k0) ^ (v1 + sum) ^ ((v1>>5) + k1);
sum -= delta;
}

/* end cycle */

v[0]=v0; v[1]=v1;}

Tiny Encryption Algorithm (TEA) appears to be highly resistant to


differential cryptanalysis and achieves complete diffusion where a one bit difference
in the plaintext will cause approximately 32-bit differences in the ciphertext [1]. Its
simplicity allows TEA to be easily implemented in various programming language.
The design efficiency exhibits outstanding runtime speed compared to other similar
block encryption algorithms. Moreover, its effectiveness provides adequate
encryption strength on par with more complicated and resource-intensive algorithm
such as DES or AES [18]. The TEA fundamental three elements of simplicity,
performance, and strength attain immense consideration to implement Tiny
Encryption Algorithm more extensively on embedded system design.

15
2.5.

Microcontroller

Microcontroller is a small scale computer on a single integrated circuit


comprising three fundamental elements of processor core, memory, and
programmable I/O peripherals. Microcontroller adopts Reduced Instruction Set
Computer (RISC) central processing unit (CPU) architecture which is designed to
perform simplified instructions. This simplicity enables faster execution of each
instruction which can provide higher system performance. In contrast to
microprocessor used in general purpose computer such as personal computer (PC),
microcontroller is designed for specific purpose solution as implemented for
embedded system applications. Originally, Microcontrollers were programmed using
assembly language, however nowadays various high-level programming languages
are compatible to program microcontroller. In addition, the most common language
to program microcontroller is using C language.

2.5.1. Atmel AVR ATmega324P

Atmel is a global industry leader in the design and manufacture of


microcontrollers and related embedded system solutions. The advanced Atmel
product of microcontroller and integrated circuit enables developers to develop
complete solutions from the low level deployment to the full range upscale system.
Atmel AVR integrated circuit, specifically 8-bit microcontroller, deliver a unique
combination of performance, power efficiency, and design flexibility. A wideranging Atmel AVR implementation is optimized to speed time to market and easily
adapt to updated system solutions composes its microcontroller products are based
on the industrys most code-efficient architecture for C and assembly programming.
Compare to microcontroller product from other corporation, Atmel delivers more
computing performance with better power efficiency. The extensive development
using AVR microcontroller makes it easy to reuse knowledge when improving
designers current system and expanding to a new more upscale design easily and
cost-effectively.

16

The advanced performance of Atmel ATmega family with low-cost product


gives prior concern to select ATmega324P as core process of the project. The
features of selected product is described as follow,

i.

ii.

Advanced RISC Architecture

131 Powerful Instructions Most Single-clock Cycle Execution

32 x 8 General Purpose Working Registers

Fully Static Operation

Up to 20 MIPS Throughput at 20 MHz

On-chip 2-cycle Multiplier

High Endurance Non-volatile Memory segments

32K Bytes of In-System Self-programmable Flash program memory

1K Bytes EEPROM

2K Bytes Internal SRAM

Write/Erase Cycles: 10,000 Flash/ 100,000 EEPROM

Data retention: 20 years at 85C/100 years at 25C

Optional Boot Code Section with Independent Lock Bits


In-System Programming by On-chip Boot Program
True Read-While-Write Operation

iii.

Programming Lock for Software Security

JTAG (IEEE std. 1149.1 Compliant) Interface

Boundary-scan Capabilities According to the JTAG Standard

Extensive On-chip Debug Support

Programming of Flash, EEPROM, Fuses, and Lock Bits through the


JTAG interface

iv.

Peripheral Features

Two 8-bit Timer/Counter with Separate Prescalers and Compare Modes

One 16-bit Timer/Counter with Separate Prescalers, Compare Mode, and


Capture Mode

17

Real Time Counter with Separate Oscillator

Six PWM Channels

8-channel, 10-bit ADC


Differential mode with selectable gain at 1x, 10x, or 200x

v.

Byte-oriented Two-wire Serial Interface

Two Programmable Serial USART

Master/Slave SPI Serial Interface

Programmable Watchdog Timer with Separate On-chip Oscillator

On-chip Analog Comparator

Interrupt and Wake-up on Pin Change

Special Microcontroller Features

Power-on Reset and Programmable Brown-out Detection

Internal Calibrated RC Oscillator

External and Internal Interrupt Sources

Six Sleep Modes: Idle, ADC Noise Reduction, Power-save, Power-down,


Standby and Extended Standby

vi.

I/O and Package

vii.

viii.

ix.

32 Programmable I/O Lines

Operating Voltages

1.8V 5.5V

2.7V 5.5V

Speed Grades

0 4 MHz @ 1.8V 5.5V, 0 10 MHz @ 2.7V 5.5V

0 10 MHz @2.7V, 0 20 MHz @ 4.5V- 5.5V

Power Consumption at 1 MHz, 1.8V, 25C

Active: 0.4 mA

Power-down Mode: 0.1 A

Power-save Mode: 0.6 A (Including 32 kHz RTC)

18
2.5.2. Pin Configurations

ATmega324P microcontroller has four general purpose I/O peripherals:


PORTA, PORTB, PORTC, and PORTD with total 40 pins for PDIP package. In
general, the general purpose I/O peripherals interface possess similar feature which
operate as an 8-bit bi-directional I/O port with internal pull-up resistors. Figure 2.11
shows the detail pinout diagram of ATmega324P as used in the project.

Figure 2.12 ATmega324P I/O Pinout Diagram

Moreover, each Port has different supplementary extended feature and alternate pin
configurations function, such Port A serves as analog inputs to the Analog-to-digital
Converter. Port B has alternate function as Serial Peripheral Interface (SPI) and I/O
analog comparator. Port C also serves the function of the JTAG interface along with
special function as timer oscillator and 2-wire serial interface. In addition, Port D has
USART interface, timer/counter, and external interrupt pins.

19
2.5.3. Block Diagram

The ATmega324P is a low-power CMOS 8-bit microcontroller based on the


AVR enhanced RISC architecture. By executing powerful instructions in a single
clock cycle, the ATmega324P achieves throughputs approaching 1 MIPS per MHz
allowing the system designer to optimize power consumption as opposed to
approaching speed.

Figure 2.13 ATmega324P Block Diagram

The AVR core of ATmega324P combines a rich instruction set with 32 general
purpose working registers. All the 32 registers are directly connected to the
Arithmetic Logic Unit (ALU), allowing two independent registers to be accessed in
one single instruction executed in one clock cycle. The resulting architecture is more
code efficient while achieving throughputs up to ten times faster than conventional
CISC microcontrollers.

20
2.6.

RS-232 Interface

RS-232 is a standard communication interface based on serial transmission


protocol. RS-232 stands for Recommendation Standard number 232. It is generally
used to establish communication between two devices through peer-to-peer
connection method to perform data exchange. In data transmission RS-232 can
handle communication with an effective distance limit of 15 to 100 meter, depending
on the bit rate and cable type. Commonly, RS-232 is used in computer serial port for
connecting personal computer (PC) to modems, printer, data storage, and other
peripheral devices using a DB-9 connector as RS-232 standard. However, nowadays
the requirements to use serial port are lessen than previous era yet serial port is still
introduced especially on PC.

A DB-9 has 9 pin connectors where each pin has different purpose. Figure
2.13 shows DB-9 pinout connection as generally used for serial communication
standard RS-232. Pin number 2 (receive data), 3 (transmit data) and 5 (ground) are
the most frequent used in establishing communication protocol through RS-232
interface. It is the most fundamental connection to perform transmission and
reception data as described on Figure 2.14

Figure 2.14 DB-9 Pinout Diagram

21
There are specifically nine pins connectors on DB-9 serial port, however on
the practical implementation not all pins are used through serial communication line.
For the data exchange of reception and transmission only three pins out of nine
connections are required. The other pins are specifically for particular development
purpose of serial communication interface. A model to describe usage of RS-232
Interface is introduced on Figure 2.15.

RS-232 Interface

PC

2
3
5

3
2

PLC

Figure 2.15 RS-232 Interface Connects two Devices

The abovementioned figure shows a connection using RS-232 interface to


establish communication between PC and PLC. On this configuration, the usage of
three pins of DB-9 serial port is described. The above configuration shows a
crossover connection on pin 2 and 3 from PC to PLC. As mentioned earlier, pin 2
functions as receiving data and pin 3 functions as transmitting data port. In this case,
when PC transmits data to PLC through pin 3, the PLC receives data sent in pin 2.
Then, as a response PLC sends back the data from pin 3 to pin 2 of PC. This
establishes communication between two devices over RS-232 interface.

22

CHAPTER 3

METHODOLOGY

3.1.

Project Flow
The projects development planning process adopts divide & conquer method

which is breaking down a problem into two segments sub-process of the related type.
The solutions of the sub-processes are then combined to give a proposed solution of
the project. In general, the projects process flow consists of five phases which is
shown on Figure 3.1. Master/slave controller design is the first phase of project
which subsequently develop master/slave controller device. Divide & conquer
method starts at phase two where the work is divided into two sub-processes,
Modbus development and TEA implementation. Third phase is test & verification for
both sub-processes which is performed concurrently and independently. The outcome
from both solutions of Phase 2 and Phase 3 then are combined as a proposed
solution is the fourth phase of the project. The final phase or fifth phase is test &
verification of proposed solution to check whether the output of solution
accomplishes projects objectives.

23

Master/Slave Controller Design

Propose AVR Based Platform


Controller Device

Use Existing AVR Based


SDK Device

Master/Slave Controller Device

Modbus RTU
Development

TEA Implementation

Test & Verification

Test & Verification

Secured Modbus

Test & Verification

Figure 3.1 Project Flow Chart

The first phase is hardware design for master/slave controller device. The
main objective of this phase is to design master/slave controller PLC based system
using AVR microcontroller as hardware platform. This phase comprises two subprocesses, primary task and secondary task. The primary task is to propose an AVR
based platform controller device while secondary task is to use existing AVR based
software development kit which has serial communication feature to run-through
Modbus-RTU protocol. The primary process of this phase requires adequate
understanding of circuitry design and implementation before fabricating the design to
manufacturer. In the event of insufficient time to fabricate proposed design,
secondary task works as alternative plan to overcome unavailability of proposed
device and use existing AVR based SDK instead. The device outcome of this phase,
whether accomplishing primary or secondary procedure, is used as a baseline
platform for further phases.

24
Second phase is Modbus-RTU and Tiny Encryption Algorithm (TEA)
development and implementation by using controller device as the product of first
phase. From this point onward, the process is fragmented into two different tasks,
first task is Modbus-RTU development and second task is TEA implementation. The
Modbus-RTU and TEA implementation are constructed in concurrent work such that
Modbus protocol is applied on the hardware controller and TEA is developed on
simulation software environment.

Third phase is test and verification for both Modbus and TEA
implementation. Since the development process is handled in different workplace
framework, test and verification is performed in different environment as well. For
Modbus development, test and verification is executed in microcontroller and
monitor the data transmission from PC through serial interface. The data send and
received by microcontroller is analyzed to ensure its correctness. Meanwhile, TEA
implementation is monitored on output data run-through program compiled on
Borland C through command line interface. Debugging process then is done in
advanced for any incorrect output result.

Fourth phase is the proposed system, a secured Modbus communication


protocol which is constructed by integrating Tiny Encryption Algorithm in the data
transmission process within Modbus protocol. The idea is simply implement TEA
routine, which has been tested and verified previously, in microcontroller. Certain
adjustment is performed for TEA routine to be functioned well with Modbus
transmission routine.

Finally, the fifth phase is test and verification for secured Modbus
communication to ensure the encryption and decryption process generates correct
data according to algorithm and desired outcome.

25

3.2.

Master/Slave Controller Device

The outcome of Phase 1 decides the flow of project to proceed with


secondary task which is use existing AVR SDK board. The complementary device
which works as controller device is Wise AVR MiCE SDK board. Wise board is a
compact device and provides significant I/O peripheral devices. The device is
installed with AVR ATmega324P which is one of high-end microcontroller in its
family and provides various features. In conjunction with supplementary components
such as RTCC, EEPROM, JTAG, serial interface, and USB interface, Wise-SDK
offers the ability to develop upscale embedded system solution. Therefore, equipped
with numerous features and fast processing speed, the board is considerably suitable
for the development process of this project. Figure 3.2 shows physical design of
Wise-SDK board.

Figure 3.2 AVR Wise-SDK Board

26
In addition, Wise-SDK has unique system architecture which differs from
other microcontroller software development kit board. Some I/O peripheral devices
are connected to the same data bus. The usage of sharing bus saves pin connection
thus maximizes provision of features and I/O peripheral devices. As shown on Figure
3.2, standard programmable I/O peripheral devices cover LEDs, DIP switch, push
button, and 7-segment display.

Furthermore, software development of this project does not comprise all


features and I/O devices in Wise-SDK board. The programmable peripheral devices
used in this are LEDs and 7-segment display as indicator of main routine of the
project and RS-232 interface for data transmission.

The Wise-SDK system

architecture shows on Figure 3.3 with related peripheral devices used in this project.
As shown on the architecture diagram, the LEDs and four 7-segment displays, which
is connected to latches, are connected to same port.

PA3

Latch 0

PA4

Latch 1

PA5

Latch 2

RS-232

PD0 (RX)
PD1 (TX)

Wisepath SDK Board

PORT B

PORT B

PORTB

8 LEDs

Figure 3.3 Wise-SDK Particular System Architecture

PA6

Latch 3

27
3.3.

Modbus-RTU Protocol

Transmission protocol of this project applies standard communication using


Modbus-Remote Terminal Unit (RTU) protocol over serial line. The development
planning of Modbus protocol in this project is prior to the implementation in slave
controller device. In the other hand, Modbus routine will be preceding in receiving
state and responds if requested by master device. Main routine of slave controller
device will employ polling method to scan any changes in defined process
continuously. While waiting for the input request, the slave device will remain in idle
state and set transceiver precedence in receiving state. In accordance of any
communication reception occurred, slave device will analyze input data received and
advances to the next state according to defined process decision. Figure 3.4 shows
general state routine of slave controller device.

Start

Initialization

Idle
No
Event?

Yes

Process

Figure 3.4 Slave Controller General State Cycle

As shown on the abovementioned figure, the process starts with device initialization.
This state executes initialization module on software part in slave device. After
setting up the device, next process is Idle state where slave device will continuously
remain in the respective state up until communication event occurred.

28
In order the slave device to decide current and upcoming process status, the
routine program is designed to be dependence to each other. This design appears to
be more effective due to less decision statement on the program. The whole Process
State depends on the Transceiver State while Interrupt Service Routine (ISR) triggers
Transceiver State. Figure 3.5 shows state dependencies diagram of the slave
controller device. It is shown on the direction of arrow that Transceiver State triggers
Process State and then Transceiver State is driven by ISR.

ISR

Transceiver State

Process State

Figure 3.5 State Status Dependencies

29
3.3.1

Slave Controller Process State

Comprehensively, the Process State comprises of four sub-process states


which are Idle State, Frame Received, Execute, and Frame Sent. Each sub-process
state performs different task. Figure 3.6 shows the flowchart of four sub-process
states in accordance of reception transmission to decide which processes to be
performed thereafter. As the process has been executed, program flow will return to
the main routine.

Process State

Process?

Frame
Received

Idle

Execute

Frame Sent

Return

Figure 3.6 Process State Flowchart

In addition, Idle process is the default state of slave device which is


fundamentally the main routine. Principally the Process State is always in Idle state
until the condition to other state is fulfilled. Frame Received process is the condition
when slave device receives incoming transmission. Execute state processes the
received request which slave device is required to handle. In this state, slave device
automatically prepare respond message to be transmitted to master after Execute
state. Frame Sent is essentially a feedback report to the slave device and user through
I/O interface indicates that slave device received incoming data transmission and
responds as request condition.

30
3.3.2

Transceiver State

The transceiver state represents serial interface module on slave device. It is


divided into two distinct states in which represent transmission task performed on
slave device, either it is on Receiver State or Transmitter State. As the slave device
operates prior to be receiving data transmission, the transceiver state will be set at
Receiver State as higher precedence than Transmitter State. Figure 3.7 shows
transceiver division where each state has three sub-states for Receiver State and two
sub-states for Transmitter State respectively.

Receiver State

RX_Init

RX_Idle

Transmitter State

RX_Receive

TX_Idle

TX_Transmit

Figure 3.7 Transceiver State Diagram

Receiver State indicates reception transmission into slave device which is


represented in three process stages, RX_Init, RX_Idle, or RX_Receive. Refer to
Figure 3.4, RX_Init receiver status when it is firstly set in Initialization state.
RX_Idle is the Receiver State in Idle process of general slave device cycle. At this
state, receiver in serial interface is enabled while transmitter is disabled until data is
received by slave device. In accordance to receiving data, Receiver State changes its
status to RX_Receive indicates that data is received over serial transmission line.

The Transmitter State includes two transmitter process stages, TX_Idle and
TX_transmit. It depends on the status of Receiver State. The transmitter only
activated after data is completely received by slave device. In other words,
Transmitter State is activated as a response of reception status. Since it has lesser
precedence than Receiver State, Transmitter State is always in idle state.

31
3.3.3

Interrupt Service Routine

Interrupt is exceptionally essential in Modbus development process. It


controls directly to the flow of main routine in the programming structure. Moreover,
without implementing interrupt the coding development may have grown larger and
inefficient. ISR suspends main routine polling loop process and respective interrupt
request (IRQ). There are three interrupts service routine will be used which is
provided by ATmega324P, Timer1_CompA, USART0_RX, and USART0_UDRE as
shown on Figure 3.8.

TIMER1_COMPA

ISR

USART0_RX

USART0_UDRE

Figure 3.8 Interrupts on Software Development

According to the interrupt vector precedence table of ATmega324P,


Timer1_CompA has the highest precedence among other interrupts implemented in
the project followed by USART0_RX and USART0_UDRE. However, in the
behavior of slave device which prior to remain at reception state as the highest
precedence, the USART0_RX will be often called and timer to drive Timer1
interrupt will be activated thereafter. USART0_RX interrupt is called after slave
device received data from serial interface. In software development the
Timer1_CompA is designed to be called when certain conditions are met within
USART0_RX routine. USART0_UDRE is driven when data register of serial
interface is empty. In other words, if receiver of serial interface is disabled it clears
its data register. In that condition, USART0_UDRE is driven and transmit data
through serial line interface. This interrupt is used by slave device in order to
transmit data as the reply of incoming request data.

32
3.4.

Secured Communication Protocol

A secured communication protocol is proposed by implementing Tiny


Encryption Algorithm within Modbus frame. TEA implementation should not change
the original Modbus frame format. The encryption procedure is essentially performed
in most effortless approach thus not changing data arrangement of Modbus frame.
The implementation also must be able to rebuild encrypted data to acquire original
plaintext message and construct it in the right particular frame position. Figure 3.9
shows the proposed secured Modbus-RTU communication protocol where Tiny
Encryption Algorithm is performed to encrypt Function, Data, and CRC Check of
Modbus frame.

Encrypted

Figure 3.9 Encryption on Modbus Frame

The new content of secured Modbus frame appears to be seamlessly safe and
effective to protect communication transmission from unauthorized access. In the
case of unauthorized party intercepted communication transmission, the message
data is encrypted with 128-bit length key and it is not easily to be cracked. This
proposed secured communication design must be implemented on both host and
target device in order to establish data exchange. If Tiny Encryption Algorithm is
implemented on one-sided device, other remote devices could not recognize content
of Modbus protocol when received packet data. Once Tiny Encryption Algorithm is
embedded on host and remote devices, a secured communication between two or
more devices is established. Figure 3.10 shows the proposed design of secured
Modbus-RTU over serial line communication flow. However, the secured
communication flow is achieved only while both host and remote device share
identical Tiny Encryption Algorithm cipherkey.

33
Master
Address

Slave

Encrypt

Error Check

Send Request

Identify Address

Begin Transmission

Pointed
Address?

Idle

Yes
Address

Decrypt

No

Ignored

Error Check

Process Information
Function

Function

Address

Data

Decrypt

Data

Respond

Error Check

Reply Request

Address

Encrypt

Error Check

Figure 3.10 Secured Communication Flow

The abovementioned figure demonstrates a new breed of secured


communication flow based on Modbus-RTU protocol over serial communication
line. The transmission starts on Master device in sending request data to slave device.
Before data is transmitted, encryption process is performed to generate encrypted
Modbus frame. Subsequently, once encryption process is completed data is
transmitted through serial line to slave device. Since address data on frame format is
not encrypted, slave device still could recognize target address without performing
decryption process thus saves process cycle. In accordance of correct corresponding
address of target device, next process is acquiring information by decrypting received
message. Once original message data is successfully obtained, slave device executes
corresponding request assignment and then prepare for replying request data. In
advance, before sending reply request to master device encryption process is
performed over. Moreover, this procedure process is performed recursively on both
master and slave device. Consequently, every single packet data sent through serial
line from master to slave device or vice versa is an encrypted message data. In the
other hand, the message data is not easily manipulated while unauthorized party
successfully intercepts data transmission in the communication line.

34
3.5.

Integrating Tiny Encryption Algorithm and Modbus Protocol

The integration of Tiny Encryption Algorithm and Modbus protocol method


includes implementation on both deployment stages. Tiny Encryption Algorithm and
Modbus protocol integration process generally described on Figure 3.11. It is shown
on the flowchart that only TEA implementation is stated for both on PC and
microcontroller where Modbus-RTU implementation is not stated. As described on
previous segment, the Modbus development is performed directly in microcontroller.
In addition, Tiny Encryption Algorithm runs-through two different implementation
platforms, on windows and microcontroller. Therefore, implementation of TEA on
microcontroller is the actual process of integrating Tiny Encryption Algorithm and
Modbus protocol.

Firstly, Tiny Encryption Algorithm routine should be initially tested and


verified before advancing on the microcontroller deployment. The implementation of
TEA takes place on PC software simulation environment and then followed by test
and verification. Afterwards, integration process is allowed to commence. The next
stage is TEA implementation on microcontroller which is the integrating process of
TEA and Modbus routine. Finally, after Tiny Encryption Algorithm and Modbus
protocol has been integrated test and verification for integrated system is compulsory
needed to perform.
Start

TEA Implementation
on PC

Test & Verification

TEA Implementation
on Microcontroller

Test & Verification

End

Figure 3.11 TEA Implementation Flowchart

35
More detail of elaborated process steps from Figure 3.11 is described on
Figure 3.12. As explained earlier, Tiny Encryption Algorithm implementation is
performed at the first place specifically on Borland C for this project. The source
code composed on Borland C then is simulated to check for error. If error exists on
constructed source code, the process goes through debugging stage of software
development to fix bugs and errors. Debugging process is recursively performed
while the source code still has errors. Once errors have been fixed, the output result
from simulation is tested and verified. In addition, if output result is incorrect
debugging process is repeated up until simulation output generates correct result.
Moreover, as outcome of implementation on PC has been tested and verified the
process advances to TEA integration process on microcontroller. The steps on
integration process are identical with implementation on PC. It comprises of error
check, debugging process, and test & verification of output result for correct data
output.

Start

TEA Implementation
On Borland C

Debugging

Error?

TEA Implementation
On Microcontroller

Debugging

Error?

Output Result

Output Result

Test & Verification

Test & Verification

Correct?

Correct?

Tested & Verified

End

Figure 3.12 Test and Verification Process Cycle

36
3.6.

Programming Interface

Programming interface is the method to load program code compiled by


compiler to hardware. The terms hardware means in general definition, thus not only
microcontroller chip needs programming interface but all programmable hardware
requires one. There are approximately seven methods of current programming
interfaces to program AVR microcontroller chips. On the other hand, this project will
use one through seven methods of programming interfaces. The In-System
Programming (ISP) will be introduced as the main programming interface to
ATmega324P microcontroller chip as used in this project.

In-System Programming is programming method which is functionally


performed through Serial Peripheral Interface (SPI). The programmer device or so
called programmer adapter as well, requires six pins connection linked to AVR chip.
In addition, among seven methods of programming interface, there are numerous
programmer adapter devices for ISP technique as well. The programmer device will
be used in this project is USBtiny programmer. Programming process of ISP method
using USBtiny is shown on Figure 3.13. USBtiny will load .hex file generated by
compiler and then load it to AVR device. In other words, USBtiny functions as
intermediary tools to program AVR microcontroller from compiler used on PC.
Figure 3.14 shows the actual USBtiny device which will be used to program AVR
chip on this project.
Compiler

.hex File

USBtiny

AVR

Figure 3.13 USBtiny Programming Process

Figure 3.14 USBtiny Device

37
3.7.

Terminal Emulator

Terminal emulator functions to capture data transmission flowing through


communication interface between two devices or more. In addition, terminal
emulator also functions as intermediary program to send and receive data from host
to remote device. It allows user to transmit data through terminal emulator and
receives data on it as well. A terminal emulator program presented in graphical user
interface is called terminal window.

Generally, terminal emulator is used to analyze data transmission from PC to


remote host. Terminal emulator captures data exchange within communication
interface and emulates graphical representation presented on terminal window.
HyperTerminal is the most common terminal emulator on windows platform. It is
one of the most terminal emulator program used based on windows environment.
However, this project will introduce RFI InTerm as terminal emulator program.
Figure 3.15 shows graphical representation of RFI InTerm with example of data
captured on its terminal windows indicated within colored rectangular box.

Figure 3.15 RFI InTerm Windows GUI

CHAPTER 4

DEVELOPMENT PROCESS

4.1

Tiny Encryption Algorithm Simulation


The first step of projects development process before implementing the Tiny

Encryption Algorithm is simulation on windows platform. This is one of the essential


processes before advancing to further development stage. The simulation process is
required to ensure consistency of implemented TEA routine to generate valid
encryption and decryption data. Simulation process comprises Tiny Encryption
Algorithm coding construction on Borland C compiler. Its simplicity and ease of use
make Borland C a suitable tool to test and verify TEA implementation. The
simulation stage consists of Test and Verification processes. Testing process is to
ensure the TEA coding implemented compiled successfully without any errors and
function as desired specification. Furthermore, verification process is to confirm
whether the output generated from compiling process is valid and consistent. In
addition of verification process, a cross reference with other related work needs to be
performed to double check output result is valid. Figure 4.1 shows simulation
procedure for TEA simulation stage.

39

Start

Set Input Plaintext

Set Cipherkey

Debugging

Encrypt

Output Ciphertext

Cross Reference
0
Valid?
1
Input Ciphertext

Decrypt

Output Plaintext
0
Compare with
Original Plaintext

Valid?
1
End

Figure 4.1 Simulation Procedure

40
To perform a cross reference check, the simulation stage referred to previous
related project executed by using same encryption algorithm. Moreover, to validate
the output result of simulation process input plaintext and cipher text have to be
exactly match with referred project. The reference of output result is cited from the
project entitled The Implementation of Tiny Encryption Algorithm (TEA) on
PIC18F4550 Microcontroller. The referred project implemented same encryption
technique which is Tiny Encryption Algorithm. Even though the implementation
platform is different, the essential point here is to compare whether TEA result from
simulation generates equal ciphertext with identical input text and cipherkey as to
refer project. Figure 4.2 shows the referred project output result of TEA
implementation on PIC microcontroller.

Figure 4.2 TEA Implementation Result on PIC18F4550 [14]

Therefore, the objective of TEA simulation stage is to ensure output result


compiled with Borland C generates same exact result as abovementioned figure with
identical input plaintext and cipherkey. Once the encryption process generates
similar ciphertext, next validation process is to perform decryption routine whether
the TEA implemented obtains original input plaintext. Conclusively, if TEA
implemented on Borland C output result conforms to the cross reference, the project
advances to next development stage.

41
4.2

Modbus-RTU Development

In Modbus development, slave device process state performs main function


of Modbus protocol. Function called within the tree process needs to be handled well
managed. Within the process tree diagram, two process states perform significant
flow of Modbus protocol, the other two processes perform as indicator status to slave
device. The Idle state performs no operation and Frame Sent states change current
states status back to Idle. Figure 4.12 shows detail execution processes within
Process State as explained in previous chapter.

Idle

Frame Received

Execute

Frame Sent

Get Modbus
frame

Get function code

Process = Idle

Check target
address

Compatible?

True?

No

Yes

Process = Execute

No

Yes
Call respective
function code

Write exception
code

Exception?

Yes

Process = Idle

No

Call transmit
function

Return

Figure 4.3 Process State Tree Diagram

Exception data
frame

42

In the other hand, Frame Received and Execute state perform more detail
operations. Slave devices state changes when data reception is occurred in serial
communication interface. It is triggered by interrupt corresponding to USART0_RX
interrupt. The data received from serial interface then stored into buffer array on
slave device. Once the state is changed to Frame Received, the program will get
Modbus frame previously stored in buffer and check target address within the packet
message. If the target address is correct to corresponding slave device, the process
state then is changed to Execute and return to the main routine otherwise back to Idle
state.

On the next polling cycle, since the process state is changed to Execute thus
slave device will call functions within Execute state tree. In this process, the Modbus
function protocol will be performed. Initially, slave device will get function code
from data buffer and then analyze whether requested function is implemented or
compatible on slave controller device. In accordance of function availability, slave
device will call respective function code on the Modbus protocol routine. On the
other hand, if the requested function code is not compatible slave device will write
exception code. Exception code is a Modbus protocol code where the requested
function code is not compatible or not available on respective slave device. Next
process is checking whether exception code is exist on slave device routine status.
Slave device then will prepare for data transmission over serial interface to reply
request message from master device. At this point, regardless the status of exception
code on Modbus program, slave device will transmit both conditions whether
exception code is exist or not. This condition is shown on decision making process
within Execute tree functions. Moreover, the difference between true or false status
of exception code is the content within Modbus frame. In accordance of false
exception status slave device will send function code and respected data function
code otherwise data transmitted is exception code response.

43
Furthermore, the interrupt service routines which affects directly to the flow
of process state will be introduced from this point onward. The first interrupt which
is set as highest precedence is USART0_RX. This interrupt is driven by the time
receiver in serial interface received data transmission. While main routine performs
polling cycle, the moment data is received by serial interface current main routine
process is suspended and USART0_RX interrupt is called.

USART0_RX

Set TX_Idle

Get data received

Check receiver
status

RX_Init?

No

RX_Idle?

No

RX_Receive?

Yes

Yes

Index = 0

Index++

Store data received

Store data received

Set RX_Receive
Yes
Enable timer

Return

Figure 4.4 USART0-rx Interrupt Routine

44
The first process of this interrupt is setting the transmitter status to idle. As
explained earlier based on Figure 4.3, once data is received by serial interface slave
device store it to buffer. Next process is to get data received from data buffer.
Afterwards, the program checks receiver current status. The checking is essential for
slave device to remain within interrupt function where incoming data is still
transmitted to construct one Modbus frame package. There are three decision
condition regarding receiver status. First is RX_Init, at this state interrupt program
will perform no operation and return to the main routine. Second state is RX_Idle,
this state is when receiver is waiting for data reception through serial interface line, if
this condition is true interrupt program will set data index to 0 to prepare receiving
incoming message and stored it to data buffer. After data is received, it is directly
stored to data buffer and then set receiver state to RX_Receive for the next cycle,
before exiting the routine timer is enabled to count time interval between receiving
packet data. The third condition is when receiver in RX_Receive, at this condition in
accordance of triggered interrupt the program will increment current data index by
one and stored data received in the respective buffer position and the process returns
back to the main routine. In addition, by the time program leaves interrupt routine,
the timer still counting up until reaches defined value. At this time, once the timer
reached it maximum threshold value Timer1_CompA interrupt will be driven.

The second interrupt service routine implemented is Timer1_CompA.


Timer1_CompA interrupt basically function as stopwatch to count time process on
particular process state. Timer feature on ATmega324P offers accurate calculation of
timing counter. The Timer1_CompA will start counting and compare counted value
with designated value on channel A of timer hardware architecture. Once timing
counter reaches value set in channel A, overflow occurred then Timer1_CompA is
driven. Figure 4.4 shows function routines within Timer1_CompA interrupt handler.

45

TIMER1_COMPA

Check receiver
status

RX_Init?

Yes

Process = Idle

No

RX_Receive?

Yes

Process = Frame Received

No

Disable timer

Set RX_Idle

Return

Figure 4.5 Timer1-Compare Interrupt Routine

By the time corresponding interrupt is called, the system program checks the
receiver status. Slave device then analyze current receiver state and process next
function according to its condition. The abovementioned figure shows a setting to
Idle process state when receiver at initialization state otherwise slave device
advances to analyze next condition. Afterwards, the program checks whether receiver
in RX_Receive state, if the state is true the program will change current process state
to Frame Received otherwise the process moves to next instruction. Subsequently,
the timer will be disabled and set receiver status to idle then return to the main
routine indicates that interrupt routine is completely executed.

46
The third and last interrupt implemented on slave device is USART0_UDRE.
This interrupt implicitly functions to transmit data as a response event in accordance
of request data from master. USART0_UDRE interrupt is driven by the time serial
interface data register is empty. In the other hand, if the receiver of serial interface is
disabled it will flush data held within USART Data Register (UDRE) and then
corresponding

interrupt

is

driven.

Figure

4.6

shows

detail

process

of

USART0_UDRE routine.

The USART0_UDRE process starts with setting receiver to idle state.


Afterwards, the program checks transmitter status whether it is in idle or transmit
state. Furthermore, if transmitter is in TX_Idle state the interrupt program will enable
the receiver which is set to idle state. On the other hand, the condition of
TX_Transmit is true interrupt programs executes next instruction to check Modbus
transmission buffer index. In other word, slave device prepares to transmit data by
the time transmitter in TX_Transmit state. As shown on Figure 4.6 in the
TX_Transmit decision tree, the program acquires data from buffer as the condition of
Index is not 0. The Index data variable introduced in this program represents the
length of data to be transmitted. Afterwards, next process is sending data from buffer
according to its index position represented on buffer value and increases buffer value
while decreasing Index value. This process is performed repeatedly over until the
Index value is 0 which means all data has been successfully transmitted. In advance,
once data transmission is completed interrupt program changes current process status
to Frame Sent while then enables receiver and set transmitter to idle state. Once the
interrupt routine is commenced, flow program returns back to the main routine.

47

USART0_UDRE

Set RX_Idle

Check transmitter
status

Yes

TX_Idle

No

Enable receiver

TX_Transmit?

Yes

Check Send
Buffer Index

Index = 0?

Yes

No

Get data from buffer

Process = Frame Sent

Send data

Enable receiver

Buffer++
Index--

Set TX_Idle

Return

Figure 4.6 USART0-UDRE Interrupt Routine

No

48
4.3

Software Development Stage

4.3.1

AVR Studio 6

AVR Studio 6 is the latest integrated development environment (IDE) for


developing and debugging microcontroller based applications system. This latest
framework tools support two Atmel microcontroller architecture, ARM and AVR
processor. AVR Studio 6 supports over 300 Atmel AVR and ARM microcontroller
devices. The integrated compiler and environment allow programmer to develop
program written in C/C++ or assembly language easily. The project used AVR
Studio 6 as simulator and compiler on the software development process. Figure 4.7
shows the Graphical User Interface (GUI) of AVR Studio 6.

Figure 4.7 AVR Studio 6 Workplace Windows

Moreover, AVR Studio 6 is an open source program which is free of charge


and comes along with large library. AVR Studio 6 also offers advanced development
features such as integrated editor with visual assist, full debug views, and full chip
simulation which gives a better consideration to streamline design process rather than
using other development tools.

49
4.3.2

Modular Programming

In designing a system program, software development process of a project


may have outgrown the scope of a single file implementation due to complexity and
functions applied. At this point, the usage of single file program for development
process will decrease work efficiency and effectiveness. The computer will require
more memory resources just to open project file. It also prolong debugging process
due to massive structure of line coding which will end up in unresolved problem
when tracking down for a single line code. Prior to the further software development
process with large number of line coding, a modular programming is compulsory
needed in order to increase work efficiency, effectiveness, and reduce error.

Modular programming is a software design technique which increases the


extent of developing program into separate interchangeable modules by breaking
down program function or subroutine into modules. The main idea basically to
identify common routines and group them into one file or called as a module. The
modules are interchangeable which mean that functions within associated module are
able to be called from other modules. The programming process of this project was
designed by implementing modular programming on C language. Software design
and prototyping was started by fragmenting a single project file into several .c file
modules. Furthermore, subroutines or functions were composed in different modules
regarding its function similarity and named the modules according its general
operation. Figure 4.8 shows the hierarchical structure of projects file which is
fragmented into several modules (.c files) and header files (.h files). It is shown on
diagram that Main.c which is encircled with red line is the main routine of program
and other modules are named based on its general functions implementation, such as
Modbus.c contains function for Modbus protocol, Tea.c is the Tiny Encryption
Algorithm routine, Deviceinit.c for hardware initialization, etc.

50

Rtufunccoils.c

Deviceinit.c

Devicetimer.c

Deviceport.h

Main.h

Modbus.h

Deviceserial.c

Main.c

Modbus.c

Tea.h

Rtucrc.h

Avrwise.h

Tea.c

Rtucrc.c

Avrwise.c

Figure 4.8 Dependency Files Tree Diagram

Moreover, as software development process is modularized and separated in


two distinct files which are the modules (.c) and header files (.h), it is important to
comprehend to avoid composing statement within header files. Header file allows
programmer to separate certain elements of programs source code into reusable file
which is commonly contain declarations and definitions of variables, subroutines,
and identifiers. Writing code statement in header file will result a multiple definition
error, specifically subroutine function, such that the compiler will generate object file
for each .c and .h files where it contain copies of function from .c and .h files. Thus,
fundamentally all declaration and definition of identifier of function prototype are
composed within header file. Furthermore, to circumvent a large header file
containing all declarations and definitions, the header file is breaking up into separate
files according to each C module. The header files contain function prototype for the
respective modules such as shown on Figure 4.8, Main.h, Modbus.h, Tea.h, Rtucrc.h,
and Avrwise.h. In advanced, to reduce repetitive statement and file size, several
global definition of header files are created where on Figure 4.8 shows Deviceport.h,
Main.h, and Modbus.h function as global definition header files as well.

51
Parting code files not only organize software development process into
structured and well managed project but also construct effective and efficient work.
Most compilers work on one file at a time, thus any changes on one line coding will
result the compiler has to recompile the whole linen of code. On the other hand, if the
file is fragmented into several files, any changes on line coding in one file will only
require the respective file to be compiled while rest of the files will not need
compiling. Thus, it speeds up compilation process. Splitting source code along
logical lines also makes it easier for the programmer to find variable, function,
declaration, and other definitions. It also reduces amount of code needed to read in
order to find specific line coding which increases file organization. Moreover,
creating several modules facilitate code reuse within the project file. While the
source code is split up into sections which operate essentially independent of each
other, it allows the code to be reused which saving time or rewriting over. Hence,
splitting source code into several files will give significant advantages in software
development process.

4.4

Hardware Programming

Hardware programming stage is flashing the compiled software source code


into the microcontroller device. As compilation on software development process
using AVR Studio 6 generates .hex file, next step is download the .hex file using
programming interface to the device. AVR Studio 6 offers powerful feature and ease
of use for the software development stage however on the other hand it requires
programmer device from Atmel in order to integrate AVR Studio 6 with programmer
device. This is the constraint of using AVR Studio 6 on the software development.
Furthermore, to overcome the current drawback an alternative is proposed by using
third party programmer device which is USBtiny and WinAVR as a tool to integrate
USBtiny through windows platform. Figure 4.9 shows general process of
programming AVR microcontroller using USBtiny device and WinAVR.

52

Compiler

.hex File

WinAVR

USBtiny

AVR

Figure 4.9 WinAVR Functional Block Process

WinAVR is an executable suite and open source software development tools


for Atmel AVR RISC microcontroller hosted on Windows platform. WinAVR
functions as compiler and programming interface as well. The first step is to install
WinAVR on windows platform. Once WinAVR is installed on hosted machine
windows system has integrated it with command prompt. At this point, to program
hardware device using USBtiny is running WinAVR through command line interface
on windows. Figure 4.10 shows process of programming hardware device through
command prompt using WinAVR.

Figure 4.10 Hardware Programming Process

53
To perform hardware programming, first of all run command prompt on
windows. Next step is change the directory where .hex file is located. The above
figured used ls instruction on command prompt to display files within directory on
list view. It is noticed within the black rectangle that .hex file is inside the target
directory. The next instruction line is to run WinAVR by using avrdude instruction
as within purple rectangle box followed by programmer device. In this case the
project used USBtiny as programmer device and ATmega324P as microcontroller
device, the instruction is within red rectangle. Lastly, flash instruction along with
.hex file target as within brown box. Afterwards, once WinAVR has successfully
connected with programmer device, as in this project, the rest of operation will be
handled by USBtiny. Detail descriptions are listed on Figure 4.10 after WinAVR is
executed.

The first operation is initialization to verify device signature and flash


memory of target microcontroller device. After target device is verified, the next step
is erasing device chip and reading .hex file. The processing speed of writing .hex file
into microcontroller device depends on the size of .hex, the larger file size the longer
writing process needed. Moreover, even though the writing .hex has done WinAVR
performs data verification of written .hex file from microcontroller device to ensure
its consistency.

CHAPTER 5

RESULT AND DISCUSSION

5.1

Simulation Result

The simulation process of the project was done using Borland C compiler to
test and verify whether Tiny Encryption Algorithm routine is correctly implemented.
The expected outcome of simulation result is a correct ciphertext as the product of
encryption process and then acquires same input plaintext in the decryption process.
Additionally, the point of interest in the simulation is whether the generated
ciphertext is correct with associated cipherkey even though decryption process
obtains original input plaintext. A cross reference was performed with other related
project using similar input plaintext and cipherkey.

After run-through simulation procedure, debugging, and cross reference


process, the TEA routine implemented on Borland C generates valid output result
data. The implemented TEA algorithm has succesfully performed encryption process
which generated discrete data in contrast with original input plaintext. Moreover,
result of decyption process also obtained original input palintext. Figure 5.1 shows
result of TEA routine on command line interface compiled by Borland C.

(a)

(b)

Figure 5.1 TEA Simulation Result (a) Cipherkey = 0x112233 44556677 8899AABB
CCDDEEFF (b) Cipherkey = 0x1F54EC0A B8EA73C9 ACRD561F A3C96E0F

The above mentioned figure shows two distinct results of TEA operation
performed with different cipherkey. Resulting output of segment (a) shown on Figure
5.1 was the first simulation process as the cross reference performed to ensure correct
output result. The outcome of cross reference in simulation process indicated that the
constructed TEA routine on Borland C is valid and verified.

Moreover, additional simulation was performed to ensure consistency of


encryption process by replacing previous cipherkey with a new one while maintain
earlier input plaintext. On the segment (b) of Figure 5.1 shows that the encrypted text
differs from the output generated on segment (a) with same input plaintext. These
results confirm the non-linearity of TEA routine implemented with different
ciphertext even though using same input plaintext. Moreover, the successful
performance of simulation process is that both two simulation results indicated
approved decryption process to obtain original input plaintext.

5.2

Experimental Result

The experimental process of the project was performed using Wise-SDK


board as slave controller device with ATmega324P installed on the board as core
processor. The main objective of experimental result that slave device responds
request data from PC in Modbus-RTU protocol. The protocol comprises incoming
data transmission sent by the PC and outgoing data transmission replied by the slave
device. Moreover, the expected outcome also includes the ability of slave device to
transmit and received encrypted data transmission. In observing data transmission
flowing through PC from slave device and vice versa terminal emulator is highly
required unless message data is unable to be captured. Terminal emulator used in this
project is RFI Interm.
According to the projects plan previously on Methodology parts, the first
experiment in modbus development tree is test and verification of Modbus-RTU
protocol. Theoritically, the expected outcome of first experimental phase is the slave
device responds based on Modbus-RTU message framming. Modbus-RTU frame
format is re-introduced as shown on Figure 5.2 for further analysis.

Figure 5.2 Modbus-RTU Frame Format

The first phase experimental result captured by terminal emulator showed that
the slave device sent message frame based on Modbus-RTU format. Figure 5.3
shows data transmission from PC to slave device and its respond back to PC. Before
commencing data transmission, slave device address is set to 0x31 and source code
of modbus transmission is set to reply received address. When receives incoming
data from master device, slave device analyzes the first segment of message data
whether it is sent to corresponding slave device. In other words, when slave device
received a message which is sent to address other than 0x31, as configured earlier,
the slave device will not respond to the request. As can be observed on the captured
transmission, the first line of data transmission sent address data of 0x32, 0x33, 0x34,
0x35, 0x36, and x37, which is indicated within red rectangular shape, to the slave
device where no responses sent by slave device.

Figure 5.3 Plaintext Data Response

Furthermore, the next transmission line captured that slave device respond to
the request data form PC recognizing address data was sent for address 0x31 which is
correct corresponding slave device. As a response, the receiving message from PC
indicated several data segment of modbus message protocol. Table 5.1 shows
summary of data transmission captured on terminal emulator. In addition, all
numbers listed on further tables are represented in hexadecimal numeric system

Table 5.1 Data Log Summary of Experiment 1


Reception
No

Transmission

Address

Function

Data

CRC
Lo

Hi

32; 33; 34; 35; 36; 37

N/A

N/A

N/A

N/A

N/A

31

31

00

80

E1

F0

31, 31, 31

31

00

80

40

41

31, 32, 31

31

00

80

E1

F0

According to the data log summary table, transmission column shows distinct
separator from transmisision line 1 with the rest of data log. The data separated with
semicolon indicates the data was sent one-by-one, meaning that it was a single data
transmission from PC to slave device. On the other hand, line transmission 3 and 4
separated by comma indicates continous data transmission from one packet to
another. In other word, transmission line 3 and 4 sent three packet based on modbusRTU data frame format to slave device. As a response for transmission line 2 through
line 3, slave device sent error message to the request data. It is shown from function
column on reception segment that the data sent was 0x00 which indicates incorrect
function request sent by the PC. In response of incorrect function code, slave device
sent exception response code indicates that error received request on data column.

Second experiment comprises integrating Tiny Encryption Algorithm routin


in Modbus RTU protocol on slave device. The second experiment also used similar
packet transmission from first experiment as well to observe the difference when
implementing Tiny Encryption Algorithm within Modbus frame. Resulting reception
response on host PC showed significant contrast message regarding data sent from
slave device with encrypted packet data. In this experiment, Tiny Encryption
Algorithm routine implemented was the encryption process only. Hence, slave device
still recognize address data sent from PC since it did not go to decryption process
which will generate different address data received on slave device. Figure 5.4 shows
encrypted response of slave device to the request tranmission from host PC.

Figure 5.4 Encrypted Data Response

From the abovementioned figure it can be observed the different encrypted


response along with its input data on slave device. The first line transmission as
shown on captured data that slave device did not respond to the incorrect
corresponding address. Meanwhile, slave device did respond to the rest of
transmission line in distinct encrypted message. More detail captured data
transmission log is listed on Table 5.2 for second experiment.

Table 5.2 Data Log Summary of Experiment 2


Reception
No

Transmission

Address

Function

Data

CRC
Lo

Hi

32; 33; 34; 35; 36; 37

N/A

N/A

N/A

N/A

N/A

31

97

E9

80

E1

F0

31, 31, 31

7D

8B

69

81

1E

31, 32, 31

03

13

0B

81

F7

Separator in transmission column still refers to previous table where


semicolon indicates single packet data transmission while numbers separated by
comma denotes several packet data on Modbus frame format. The resulting data
summary on above table shows significant non-linearity compared to first experiment
. It can be well observed the difference among transmission line 2 through line 4 that
encrypted data generated different ciphertext message based on its input plaintext.

The third experiment was conducted to test decryption process of Tiny


Encryption Algorithm implemented on slave device. Identical to previous
experiments, the transmitted message used similar message data.

However, as

transmitted from host PC the slaved device performed decryption process for
receiving data. The result of decryption process modified received data by slave
device. As shown on Figure 5.5, slave device did not respond to host PC even though
correct corresponding request address was sent. The received data was modified thus
it was no longer represent corresponding slave device address. Therefore, it was
considered as different target address and slave device ignored the request. Table 5.3
shows detail summary of data transmission captured by emulator. It can be
concluded that transmission process was failed. To overcome this problem, correct
encryption routine should be performed on host PC.

Figure 5.5 Incorrect Input Data Response

Table 5.3 Data Log Summary of Experiment 3


Reception
No

Transmission

Address

Function

Data

CRC
Lo

Hi

32; 33; 34; 35; 36; 37

N/A

N/A

N/A

N/A

N/A

31

N/A

N/A

N/A

N/A

N/A

31, 31, 31

N/A

N/A

N/A

N/A

N/A

31, 32, 31

N/A

N/A

N/A

N/A

N/A

CHAPTER 6

CONCLUSION AND RECOMMENDATIONS

6.1

Conclusion

The main objectives of this project consist of two software development


parts, Tiny Encryption Algorithm and Modbus-RTU protocol. The final outcome of
software implementation stage is a secured communication protocol by integrating
Tiny Encryption Algorithm and Modbus-RTU protocol on AVR-based device
platform. As a result a secured communication protocol on AVR-based device
platform has successfully constructed and functionally worked.

According to the result and analysis, the Modbus protocol implemented on


microcontroller device functioned well regarding its format frame. The slave device
responded to the request for address data correctly. Integration of Tiny Encryption
Algorithm and Modbus-RTU protocol has been successfully running. The secured
communication flow has been established as designed as well.

In the other hand, the resulting outcome of the project still does not reach a
complete system of Modbus protocol. Some improvements need to be performed to
fix current drawbacks of the proposed system. The function handler of Modbus-RTU
protocol and integration system with Tiny Encryption Algorithm are required to
improve

62
6.2

Recommendations

The resulting performance as the outcome of this project demonstrated the


functional segment only. It is too impulsive to state that the proposed system design
has excellent overall performance. Further research and experimental studies are
essentially required in enhancing and analyze possible method to streamline current
system design. Supplementary system analysis on the device timing performance is
necessary as well in order to outline that system bottleneck does not exist in the
proposed design.

Moreover, continual improvement and enhancement are highly important in


order to devise stable and upscale system design. More thorough analysis should be
performed by comparing the proposed design performance with other platform
device. Further detail analysis on system performance and benchmarking with
microprocessor and System-on-Chip (SoC) based designed is substantially essential
to develop better system design.

In advance, integration with other device platform is necessary as well. It


measures the capability of a system to uphold its performance while integrating with
different platform device. The concrete solution is to integrate the proposed system
on a complete PLC and RTOS (Real Time Operating System) based system. Detail
analysis can be well acquired while testing it with complete and full-range upscale
systems such as described.

63

REFERENCES

1.

Andem, W. R. (2003). A Cryptanalysis of the Tiny Encryption Algorithm.


Tuscaloosa: University of Alabama.

2.

Atmel Corporation (2008). In-System Programming. United States.

3.

Atmel Corporation (2010). AVR Hardware Design Consideration. United


States.

4.

Axelson, J. (1998). Serial Port Complete: Programming and Circuits for RS232 and RS-485 Links and Networks. Madison, W. I.: Lakeview Research.

5.

Axelson, J. (1999). Designing RS-485 Circuits. Circuit Cellar. 107(6).

6.

Cui, B. and Xu. G. (2009). Design and Realization of an Intelligent Data


Acquisition and Display System Based on AT89C52 and Modbus. IEEE
Journal.

7.

Heo, J. and Hong, C. S. A Security Mechanism for Automation Control in


PLC-based Networks. IEEE Journal.

8.

Israsena, P. Securing Ubiquitous and Low-Cost RFID Using Tiny Encryption


Algorithm. IEEE Journal.

9.

Liao, G. Y., Chen, Y. J., Lu, W. C., and Cheng, T. C. (2008). Toward
Authenticating the Master in the Modbus Protocol. IEEE Journal.

64

10.

Marchant, V. (2007). Using MODBUS for Process Control and Automation.


United States: Moore Industries Inc.

11.

Modbus Organization (2006). MODBUS Over Serial Line: Specification and


Implementation Guide. Massachusetts: Modbus Organization Inc.

12.

Modbus Organization (2006). MODBUS Messaging Implementation Guide.


Massachusetts: Modbus Organization Inc.

13.

Modbus

Organization

(2006).

MODBUS

Application

Protocol.

Massachusetts: Modbus Organization Inc.

14.

Permadi, E. (2005). The Implementation of Tiny Encryption Algorithm (TEA)


on PIC18F4550 Microcontroller. Indonesia: President University.

15.

Rehg, J. A. and Sartori, G. J. (2007). Programmable Logic Controllers.


Upper Saddle River, N. J.: Prentice Hall.

16.

Senthil, K. S. and Manjupriya. M. (2011). Microcontroller Based


Cyptosystem With Key Generation Unit. IEEE Journal.

17.

Wheeler, D. J. and Needham, R. M. (1994). Tiny Encryption Algorithm.


United Kingdom: Cambridge University.

18.

Williams, D. (2008). The Tiny Encryption Algorithm (TEA). United States:


Colombus State University

65

APPENDIX A

Proposed Design of AVR-based Slave Controller Device

66

67

68

69

70

71

72

APPENDIX B

Source Code of Borland C for Tiny Encryption Algorithm Simulation

B.1

TEA.C

/* Name : Ahmad Ridwan Mushoffa


Project: Tiny Encryption Algorithm*/

#include <conio.h>
#include <stdio.h>

void encipher(unsigned long *const v,unsigned long *const w,const unsigned long
*const k)
{
register unsigned long

y=v[0],z=v[1],sum=0,delta=0x9E3779B9,
a=k[0],b=k[1],c=k[2],d=k[3],n=32;

while(n-->0){
sum += delta;
y += (z << 4)+a ^ z+sum ^ (z >> 5)+b;
z += (y << 4)+c ^ y+sum ^ (y >> 5)+d;
}
w[0]=y; w[1]=z;
}

73
void decipher(unsigned long *const v, unsigned long *const w, const unsigned long
*const k){
register unsigned long

y=w[0],z=w[1],sum=0xC6EF3720,delta=0x9E3779B9,

a=k[0],b=k[1],c=k[2],d=k[3],n=32;

while(n-->0){
z -= ((y << 4)+c) ^ (y+sum) ^ ((y >> 5)+d);
y -= ((z << 4)+a) ^ (z+sum) ^ ((z >> 5)+b);
sum -= delta;
}
w[0]=y; w[1]=z;
}

int main(){
unsigned long v[] = {0x01234567, 0x89abcdef};
unsigned long key[] = {0x00112233, 0x44556677, 0x8899aabb, 0xccddeeff};
unsigned long res[2];

printf("\n Author : Ahmad Ridwan Mushoffa\n");


printf(" Project: Tiny Encryption Algorithm on Borland C\n\n");

printf("\n ************ Tiny Encryption Algorithm ************\n\n");


printf(" Plaintext: 0x%X%X\n\n", v[0], v[1]);
printf(" Cipherkey:\n k[0]: 0x%X, k[1]: 0x%X, k[2]: 0x%X, k[3]: 0x%X\n",
key[0], key[1], key[2], key[3]);

printf("\n Encription Process: \n");


encipher(v, res, key);
printf(" Ciphertext: 0x%X%X\n\n", res[0], res[1]);
printf(" Decription Process: \n");
decipher(v, res, key);
printf(" Plaintext: 0x%X%X\n", res[0], res[1]);
getch();
return 0;

74

APPENDIX C

Source Code of AVR Microcontroller ATmega324P for Modbus-RTU and


Tiny Encryption Algorithm

C.1

Main.h

#ifndef MAIN_H_
#define MAIN_H_

#define F_CPU 20000000UL


#include <avr/io.h>
#include <avr/interrupt.h>
#include <util/delay.h>
#include <avr/eeprom.h>
#include <stdio.h>
#include <stdint.h>
#include <math.h>
void Port_Init(void);
void UART_Init(void);
void Timer_Init(void);
void Device_Init(void);

#endif MAIN_H_

75
C.2

Main.c

/* ----------------------- Dependency includes -----------------------------------------------*/


#include "main.h"
#include "deviceport.h"

/* ----------------------- Modbus includes ----------------------------------------------------*/


#include "modbus.h"

/* ----------------------- Static variables ------------------------------------------------------*/


static uint16_t usPollCycles;

/* ----------------------- Interrupt Sub-routine -----------------------------------------------*/


ISR(USART0_RX_vect)
{
vRTUReceiveBuffer();
PORTB ^= (1<<6);
_delay_ms(100);
PORTB ^= (1<<6);
}

ISR(USART0_UDRE_vect)
{
vRTUTransmitBuffer();
PORTB ^= (1<<5);
_delay_ms(100);
PORTB ^= (1<<5);
}

76
ISR(TIMER1_COMPA_vect)
{
_delay_ms(100);
PORTB ^= (1<<7);

vTimerT35Expired();
}

/* ----------------------- Main Program -------------------------------------------------------*/


int main(void)
{
Device_Init();
vRTU_INIT(0x31);
//vRTUEnable();

uint8_t BufferTest;

while(1)
{
//TODO:: Please write your application code
vRTUPoll();
//usPollCycles++;
}
}

77
C.3

Modbus.h

#ifndef MODBUS_H_
#define MODBUS_H_
#include <stdint.h>

/*******************************************************************/
/* ----------------------- MODBUS TYPE DEFINITIONS --------------------------------*/
/*******************************************************************/
/* ----------------------- RTU Exception Codes ---------------------------------------------*/
typedef enum
{
RTU_EX_NONE = 0x00,
RTU_EX_ILLEGAL_FUNCTION = 0x01,
RTU_EX_ILLEGAL_DATA_ADDRESS = 0x02,
RTU_EX_ILLEGAL_DATA_VALUE = 0x03,
RTU_EX_SLAVE_DEVICE_FAILURE = 0x04,
} eRTUException;

/*******************************************************************/
/* ----------------------- MODBUS FRAME -------------------------------------------------*/
/*******************************************************************/
/* ----------------------- Defines ---------------------------------------------------------------*/
#define MASTER_ADDRESS

// Minimum size of a Modbus RTU frame.


#define RTU_SER_PDU_SIZE_MIN

// Maximum size of a Modbus RTU frame.


#define RTU_SER_PDU_SIZE_MAX

256

// Function Code
#define RTU_PDU_SIZE_MIN

// Maximum size of a PDU.


#define RTU_PDU_SIZE_MAX

253

78
#define RTU_SER_PDU_SIZE_CRC

/* ------------- Offset -------------*/


// Offset of target address in Modbus RTU Frame.
#define RTU_SER_ADDRESS_OFF

// Offset for response data in PDU.


#define RTU_SER_PDU_DATA_OFF

#define RTU_SER_PDU_SIZE_ADDR

// Offset of function code in PDU.


#define RTU_PDU_FUNC_OFF

// Offset of data code in PDU.


#define RTU_PDU_DATA_OFF

/* ----------------------- Macros ---------------------------------------------------------------*/


#define TEA_ENABLE 0
#define TEA_DISABLE 0

/*******************************************************************/
/* ----------------------- MODBUS PROTOTYPE ------------------------------------------*/
/*******************************************************************/
/* ----------------------- Defines -----------------------------------------*/
#define RTU_READ_COILS

#define RTU_READ_DI

#define RTU_READ_HOLD_REG

#define RTU_READ_IR

#define RTU_WRITE_COIL

#define RTU_WRITE_REG

#define RTU_READ_EXCEPTION

#define RTU_EXCEPTION

0x80

79
/* Modbus PDU
RTU_REQ_PDU(uint8_t ucFuncCode, uint8_t
ucDataFrame[RTU_PDU_SIZE_MAX] );
RTU_RSP_PDU(uint8_t ucFuncCode, uint8_t
ucDataFrame[RTU_PDU_SIZE_MAX]);*/
/* ----------------------- Modbus Initialization -----------------------------------------------*/
void vRTU_INIT(uint8_t ucSlaveAddress);
//void vRTUEnable(void);
void vRTUPoll(void);

/* ----------------------- Modbus functions ---------------------------------------------------*/


eRTUException eRTUReadCoil(uint8_t *pucDataFrame, uint16_t *pusDataLength);
eRTUException eRTUWriteCoil(uint8_t *pucDataFrame, uint16_t
*pusDataLength);

/* ----------------------- Serial port functions ------------------------------------------------*/


void vRTUSerialPort(uint8_t RXEnable, uint8_t TXEnable);
void vRTUGetChar(uint8_t *pucData);
void vRTUPutChar(uint8_t ucData);
void vRTUReceive(uint8_t *pucAddress, uint8_t **pucDataFrame, uint16_t
*pusDataLength);
void vRTUTransmit(uint8_t ucSlaveAddress, const uint8_t *pucDataFrame, uint16_t
usDataLength);
void vRTUReceiveBuffer(void);
void vRTUTransmitBuffer(void);

/* ----------------------- Timer functions -----------------------------------------------------*/


void vTimerInit(void);
void vTimerEnable(void);
void vTimerDisable(void);
void vTimerT35Expired(void);
void TestTransmit(void);

#endif /* MODBUS_H_ */

80
C.4

Modbus.c

/* ----------------------- Dependency includes -----------------------------------------------*/


//#include <util/delay.h>
#include "main.h"
#include "deviceport.h"
#include "avrwise.h"

/* ----------------------- Modbus includes ----------------------------------------------------*/


#include "modbus.h"

/* ----------------------- Type definitions -----------------------------------------------------*/


typedef enum
{
RX_INIT,

/* Receiver is in initial state.

*/

RX_IDLE,

/* Receiver is in idle state.

*/

RX_RECEIVE

/* Receiver is reception state.

*/

} eRTUReceiveState;

typedef enum
{
TX_IDLE,

/* Transmitter is in idle state.

TX_TRANSMIT

/* Transmitter is in transmission state. */

} eRTUSendState;

typedef enum
{
RTU_IDLE,
RTU_FRAME_RECEIVED,
RTU_PROCESSING,
RTU_FRAME_SENT
}eRTUProcess;

*/

81
/* ----------------------- Static variables ------------------------------------------------------*/
static volatile eRTUReceiveState

eReceiveState;

static volatile eRTUSendState

eSendState;

volatile uint8_t

ucRTUBuffer[RTU_SER_PDU_SIZE_MAX];

static volatile uint16_t

gusRcvBufferIndex;

static volatile uint8_t

*pucSendBuffer;

static volatile uint16_t

gusSendBufferIndex;

static eRTUProcess

eProcess;

static uint8_t

ucRTUSlaveAddress;

static uint32_t

TEAKey[] = {0x00112233, 0x44556677,


0x8899aabb, 0xccddeeff};

/* ----------------------- Functions Implementation -----------------------------------------*/


void vRTU_INIT(uint8_t ucSlaveAddress)
{
/* Set initial transmitter & receiver status */
eReceiveState = RX_INIT;
eSendState = TX_IDLE;
/* Initialize slave's address */
ucRTUSlaveAddress = ucSlaveAddress;
cli();
/* Initialize timer */
vTimerInit();
/* Enable serial port */
vRTUSerialPort(ENABLE, DISABLE);
/* Enable timer */
vTimerEnable();

sei();
}

82

void vRTUReceiveBuffer()
{
uint8_t ucBuffer;
/* Set transmitter to Idle Mode */
eSendState = TX_IDLE;
/* Get data received from USART */
vRTUGetChar(&ucBuffer);

switch(eReceiveState)
{
case RX_INIT:
vTimerEnable();
break;

case RX_IDLE:
/* Initialize buffer index value */
gusRcvBufferIndex = 0;
/* Received first character */
ucRTUBuffer[gusRcvBufferIndex] = ucBuffer;
/* Set next state to receiving process */
eReceiveState = RX_RECEIVE;
/* Enable t3.5 char timer */
vTimerEnable();
break;

case RX_RECEIVE:
/* Receiving data stream */
ucRTUBuffer[gusRcvBufferIndex++] = ucBuffer;

vTimerEnable();
break;
}
}

83
void vRTUReceive(uint8_t *pucAddress, uint8_t **pucDataFrame, uint16_t
*pusDataLength)
{
cli();
volatile uint32_t

TEABuffer[3];

uint16_t

usCRCBuf;

uint8_t

Buffer=24;

uint8_t

Counter;

int8_t

index;

/* CRC Check */
usCRCBuf = usRTUCRC(*ucRTUBuffer, gusRcvBufferIndex);

/* Decryption Process starts here*/


Counter = 0;
while(Counter < pusDataLength)
{
TEABuffer[0] |= ucRTUBuffer[Counter];
TEABuffer[0] = (TEABuffer[0]<<8);
Counter++;
PORTB ^= (1<<7);
_delay_ms(50);
}

Decryptor(TEABuffer[0], TEAKey);
Counter = pusDataLength;
Buffer = 0;
index = -1;

84
while(Counter > -1)
{
ucRTUBuffer[index++] = (uint8_t)((TEABuffer[0]>>Buffer)& 0x000000FF);
Buffer += 8;
Counter--;
PORTB ^= (1<<6);
_delay_ms(50);
}
//if((gusRcvBufferIndex >= 2) && (usCRCBuf == 0))
//{
/* Get address value within serial PDU */
*pucAddress = ucRTUBuffer[RTU_SER_ADDRESS_OFF];

/* Point to data frame within PDU */


*pucDataFrame = (uint8_t*) &ucRTUBuffer[RTU_SER_PDU_DATA_OFF];

/* Get data frame length */


*pusDataLength = (uint16_t) (gusRcvBufferIndex-RTU_SER_PDU_DATA_OFFRTU_SER_PDU_SIZE_CRC);
//}

sei();
}

85
void vRTUTransmitBuffer(void)
{
/* Set receiver to idle state */
eReceiveState = RX_IDLE;
switch(eSendState)
{
case TX_IDLE:
/* Enable reception */
vRTUSerialPort(ENABLE, DISABLE);
break;

case TX_TRANSMIT:
if(gusSendBufferIndex != 0)
{
/* Send character over serial line*/
vRTUPutChar(*pucSendBuffer);
/* Point to next data in buffer */
pucSendBuffer++;
/* Estimate current data length */
gusSendBufferIndex--;
}
else
{
/* Update current process */
eProcess = RTU_FRAME_SENT;
/* Enable reception in serial port */
vRTUSerialPort(ENABLE, DISABLE);
/* Set transmitter to idle state */
eSendState = TX_IDLE;
}
break;
}
}

86
void vRTUTransmit(uint8_t ucSlaveAddress, const uint8_t *pucDataFrame, uint16_t
usDataLength)
{
uint32_t TEABuffer[3];
uint16_t usCRC;
uint8_t Buffer=0;
int8_t Counter;
int8_t index;

TEABuffer[0] = 0x00000000;
TEABuffer[1] = 0x00000000;
cli();

if(eReceiveState == RX_IDLE)
{
pucSendBuffer = (uint8_t *)pucDataFrame-1;
gusSendBufferIndex = 1;

/* Store slave address value in buffer*/


pucSendBuffer[RTU_SER_ADDRESS_OFF] = ucSlaveAddress;
gusSendBufferIndex += usDataLength;

/* Calculate CRC value */


usCRC = usRTUCRC((uint8_t*)pucSendBuffer, gusSendBufferIndex);
ucRTUBuffer[gusSendBufferIndex++] = (uint8_t)(usCRC & 0xFF);
ucRTUBuffer[gusSendBufferIndex++] = (uint8_t)(usCRC >> 8);

/* Set transmitter to transmit state */


eSendState = TX_TRANSMIT;
/* Enable transmission in serial port */
vRTUSerialPort(DISABLE, ENABLE);
}

Counter = 0;

87
while(Counter < usDataLength)
{
TEABuffer[0] |= ucRTUBuffer[Counter];
TEABuffer[0] = (TEABuffer[0]<<8);
Counter++;
PORTB ^= (1<<7);
_delay_ms(50);
}

Encryptor(TEABuffer, TEAKey);
index = -1;
Buffer = 0;
Counter = usDataLength;

while(Counter > -1)


{
ucRTUBuffer[index++] = (uint8_t)((TEABuffer[0]>>Buffer)& 0x000000FF);
Buffer += 8;
Counter--;
PORTB ^= (1<<6);
_delay_ms(50);
}

/*ucRTUBuffer[0] = ((TEABuffer[0] >> 0) & 0x000000FF);


ucRTUBuffer[1] = ((TEABuffer[0] >> 8) & 0x000000FF);
ucRTUBuffer[2] = ((TEABuffer[0] >> 16) & 0x000000FF);
ucRTUBuffer[3] = ((TEABuffer[0] >> 24) & 0x000000FF);*/
sei();
}

88
void vTimerT35Expired()
{
/* Check current receiver's state */
switch(eReceiveState)
{
case RX_INIT:
/* Set event process to idle after initialization */
eProcess = RTU_IDLE;
break;

case RX_RECEIVE:
/* Report when whole frame is completely received */
eProcess = RTU_FRAME_RECEIVED;
break;

default:
break;
}
vTimerDisable();
eReceiveState = RX_IDLE;
}

void vRTUPoll()
{
static uint8_t

ucSlaveAddress;

static uint8_t

ucFunctionCode;

static uint8_t

*pucDataBuffer;

static uint16_t

usLengthBuffer;

static

eRTUException

eException;

89
switch (eProcess)
{
case RTU_IDLE:
PORTB ^= (1<<0);
_delay_ms(100);
//eReceiveState = RX_IDLE;

//vTimerEnable();
break;

case RTU_FRAME_RECEIVED:
PORTB ^= (1<<1);

/* Get data frame received from buffer */


vRTUReceive(&ucSlaveAddress, &pucDataBuffer, &usLengthBuffer);

/* Check validity of target address */


if(ucSlaveAddress == ucRTUSlaveAddress)
{
/* If valid process data, else ignore */
eProcess = RTU_PROCESSING;
}
else
{
eProcess = RTU_IDLE;
}
_delay_ms(100);
PORTB ^= (1<<1);
break;

case RTU_PROCESSING:
/* Get function code from data buffer */
ucFunctionCode = pucDataBuffer[RTU_PDU_FUNC_OFF];

90
/* Check function code */
switch(ucFunctionCode)
{
//case RTU_READ_COILS:
case 0x31:
eException = eRTUReadCoil(pucDataBuffer, usLengthBuffer);
break;

case RTU_WRITE_COIL:
//eException = eRTUWriteCoil();
break;

default:
/* If function is not supported send exception code */
eException = RTU_EX_ILLEGAL_FUNCTION;
break;
}

if(eException == RTU_EX_NONE)
{
vRTUTransmit(ucSlaveAddress, pucDataBuffer, usLengthBuffer);
}
else
{
/* Prepare exception code data frame */
PORTB ^= (1<<2);
usLengthBuffer = 0;
pucDataBuffer[usLengthBuffer++] = ucFunctionCode;
pucDataBuffer[usLengthBuffer++] = (ucFunctionCode + RTU_EXCEPTION);
vRTUTransmit(ucSlaveAddress, pucDataBuffer, usLengthBuffer);
}
_delay_ms(100);
PORTB ^= (1<<2);
break;

91

case RTU_FRAME_SENT:
/* Do nothing when transmit is completed */
eProcess = RTU_IDLE;
break;
}
}

C.5

Avrwise.h

#ifndef AVRWISE_H
#define AVRWISE_H
#include <stdint.h>

#define sbi(port, pin) port|=(1<<pin)


#define cbi(port, pin) port&=~(1<<pin)
#define TOGB(port, pin) port^=(1<<pin)
void toBCD(uint8_t val);
void Set7Seg(uint8_t val, uint8_t row);
void Clr7Seg(uint8_t row);
void ClrAll7Seg(void);
void On7Seg(uint8_t row);
uint8_t ReadDIP(void);
uint8_t ReadPB(void);
void Init_Board(void);
#endif

92
C.6

Avrwise.c

#include "main.h"
#include "avrwise.h"

uint8_t Dec7Seg[10]={0xC0,0xF9,0xA4,0xB0,0x99,0x92,0x82,0xF8,0x80,0x90};
uint8_t
Hex7Seg[16]={0xC0,0xF9,0xA4,0xB0,0x99,0x92,0x82,0xF8,0x80,0x90,0x88,0x83,
0xC6,0xA1,0x86,0x8E};
uint8_t n[3];

void toBCD(uint8_t val){


n[3] = val/1000;
val -= (n[3]*1000);
n[2] = val/100;
val -= (n[2]*100);
n[1] = val/10;
n[0] = val%10;
}

void Set7Seg(uint8_t val, uint8_t row)


{
DDRB = 0xFF; // Set direction to output

sbi(PORTA,(row+3));
PORTB = val;
cbi(PORTA,(row+3));

93
void Clr7Seg(uint8_t row)
{
DDRB = 0xFF; // Set direction to output

sbi(PORTA,(row+3));
PORTB = 0xFF;
cbi(PORTA,(row+3));
}

void ClrAll7Seg()
{
DDRB = 0xFF;
PORTA = 0x78;
PORTB = 0xFF;
PORTA = 0;
}

void On7Seg(uint8_t row)


{
DDRB = 0xFF; // Set direction to output

sbi(PORTA,(row+3));
PORTB = 0;
cbi(PORTA,(row+3));
}

void Idle7Seg()
{
DDRB = 0xFF;
sbi(PORTA,3);

94
uint8_t ReadDIP()
{
uint8_t buffer;

DDRB = 0; // Set direction to input


cbi(PORTD,6); //Turn on Buffer0
_delay_ms(1); //Wait for buffer to become ready
buffer = PINB;
sbi(PORTD,6); //Turn off Buffer0
DDRB = 0xFF;
return (buffer);
}

uint8_t ReadPB()
{
uint8_t buffer, adder, rShift;

rShift = 0;
adder = 0;
DDRB = 0;

// Set direction to input

cbi(PORTD,7);

//Turn on Buffer1

_delay_ms(1);

//Wait for buffer to become ready

buffer = PINB;
sbi(PORTD,7);

//Turn off Buffer1

buffer &= 0x3F;

//Encoder only gives 6-bit results. The upper 2 bits is

random, so mask it.


DDRB = 0xFF;
if((buffer >= 0) && (buffer <= 8)){
adder = 1;
rShift = 0;
}

95
else if ((buffer > 8) && (buffer != 0xFF)){
adder = 6;
rShift = 3;
}

buffer = ((~buffer>>rShift) & 0x07) + adder;

return (buffer);
}

void Init_Board()
{

DDRA = 0x78;
PORTA = 0;

DDRB = 0xFF;
PORTB = 0;

DDRD |= (1<<7) | (1<<6) | (0<<5) | (0<<4);


PORTD = 0;
}

96
C.7

Rtucrc.h

#ifndef RTUCRC_H_
#define RTUCRC_H_

#include <stdint.h>
uint16_t usRTUCRC(uint8_t *pucDataFrame, uint16_t usDataLength);

#endif RTUCRC_H_

C.8

Rtucrc.c

#include "rtucrc.h"

static const uint8_t aucCRCHi[] = {


0x00, 0xC1, 0x81, 0x40, 0x01, 0xC0, 0x80, 0x41, 0x01, 0xC0, 0x80, 0x41,
0x00, 0xC1, 0x81, 0x40, 0x01, 0xC0, 0x80, 0x41, 0x00, 0xC1, 0x81, 0x40,
0x00, 0xC1, 0x81, 0x40, 0x01, 0xC0, 0x80, 0x41, 0x01, 0xC0, 0x80, 0x41,
0x00, 0xC1, 0x81, 0x40, 0x00, 0xC1, 0x81, 0x40, 0x01, 0xC0, 0x80, 0x41,
0x00, 0xC1, 0x81, 0x40, 0x01, 0xC0, 0x80, 0x41, 0x01, 0xC0, 0x80, 0x41,
0x00, 0xC1, 0x81, 0x40, 0x01, 0xC0, 0x80, 0x41, 0x00, 0xC1, 0x81, 0x40,
0x00, 0xC1, 0x81, 0x40, 0x01, 0xC0, 0x80, 0x41, 0x00, 0xC1, 0x81, 0x40,
0x01, 0xC0, 0x80, 0x41, 0x01, 0xC0, 0x80, 0x41, 0x00, 0xC1, 0x81, 0x40,
0x00, 0xC1, 0x81, 0x40, 0x01, 0xC0, 0x80, 0x41, 0x01, 0xC0, 0x80, 0x41,
0x00, 0xC1, 0x81, 0x40, 0x01, 0xC0, 0x80, 0x41, 0x00, 0xC1, 0x81, 0x40,
0x00, 0xC1, 0x81, 0x40, 0x01, 0xC0, 0x80, 0x41, 0x01, 0xC0, 0x80, 0x41,
0x00, 0xC1, 0x81, 0x40, 0x00, 0xC1, 0x81, 0x40, 0x01, 0xC0, 0x80, 0x41,
0x00, 0xC1, 0x81, 0x40, 0x01, 0xC0, 0x80, 0x41, 0x01, 0xC0, 0x80, 0x41,
0x00, 0xC1, 0x81, 0x40, 0x00, 0xC1, 0x81, 0x40, 0x01, 0xC0, 0x80, 0x41,
0x01, 0xC0, 0x80, 0x41, 0x00, 0xC1, 0x81, 0x40, 0x01, 0xC0, 0x80, 0x41,
0x00, 0xC1, 0x81, 0x40, 0x00, 0xC1, 0x81, 0x40, 0x01, 0xC0, 0x80, 0x41,

97
0x00, 0xC1, 0x81, 0x40, 0x01, 0xC0, 0x80, 0x41, 0x01, 0xC0, 0x80, 0x41,
0x00, 0xC1, 0x81, 0x40, 0x01, 0xC0, 0x80, 0x41, 0x00, 0xC1, 0x81, 0x40,
0x00, 0xC1, 0x81, 0x40, 0x01, 0xC0, 0x80, 0x41, 0x01, 0xC0, 0x80, 0x41,
0x00, 0xC1, 0x81, 0x40, 0x00, 0xC1, 0x81, 0x40, 0x01, 0xC0, 0x80, 0x41,
0x00, 0xC1, 0x81, 0x40, 0x01, 0xC0, 0x80, 0x41, 0x01, 0xC0, 0x80, 0x41,
0x00, 0xC1, 0x81, 0x40
};

static const uint8_t aucCRCLo[] = {


0x00, 0xC0, 0xC1, 0x01, 0xC3, 0x03, 0x02, 0xC2, 0xC6, 0x06, 0x07,
0xC7, 0x05, 0xC5, 0xC4, 0x04, 0xCC, 0x0C, 0x0D, 0xCD, 0x0F, 0xCF,
0xCE, 0x0E, 0x0A, 0xCA, 0xCB, 0x0B, 0xC9, 0x09, 0x08, 0xC8, 0xD8,
0x18, 0x19, 0xD9, 0x1B, 0xDB, 0xDA, 0x1A, 0x1E, 0xDE, 0xDF, 0x1F,
0xDD, 0x1D, 0x1C, 0xDC, 0x14, 0xD4, 0xD5, 0x15, 0xD7, 0x17, 0x16,
0xD6, 0xD2, 0x12, 0x13, 0xD3, 0x11, 0xD1, 0xD0, 0x10, 0xF0, 0x30,
0x31, 0xF1, 0x33, 0xF3, 0xF2, 0x32, 0x36, 0xF6, 0xF7, 0x37, 0xF5, 0x35,
0x34, 0xF4, 0x3C, 0xFC, 0xFD, 0x3D, 0xFF, 0x3F, 0x3E, 0xFE, 0xFA,
0x3A, 0x3B, 0xFB, 0x39, 0xF9, 0xF8, 0x38, 0x28, 0xE8, 0xE9, 0x29,
0xEB, 0x2B, 0x2A, 0xEA, 0xEE, 0x2E, 0x2F, 0xEF, 0x2D, 0xED, 0xEC,
0x2C, 0xE4, 0x24, 0x25, 0xE5, 0x27, 0xE7, 0xE6, 0x26, 0x22, 0xE2,
0xE3, 0x23, 0xE1, 0x21, 0x20, 0xE0, 0xA0, 0x60, 0x61, 0xA1, 0x63,
0xA3, 0xA2, 0x62, 0x66, 0xA6, 0xA7, 0x67, 0xA5, 0x65, 0x64, 0xA4,
0x6C, 0xAC, 0xAD, 0x6D, 0xAF, 0x6F, 0x6E, 0xAE, 0xAA, 0x6A, 0x6B,
0xAB, 0x69, 0xA9, 0xA8, 0x68, 0x78, 0xB8, 0xB9, 0x79, 0xBB, 0x7B,
0x7A, 0xBA, 0xBE, 0x7E, 0x7F, 0xBF, 0x7D, 0xBD, 0xBC, 0x7C, 0xB4,
0x74, 0x75, 0xB5, 0x77, 0xB7, 0xB6, 0x76, 0x72, 0xB2, 0xB3, 0x73,
0xB1, 0x71, 0x70, 0xB0, 0x50, 0x90, 0x91, 0x51, 0x93, 0x53, 0x52, 0x92,
0x96, 0x56, 0x57, 0x97, 0x55, 0x95, 0x94, 0x54, 0x9C, 0x5C, 0x5D,
0x9D, 0x5F, 0x9F, 0x9E, 0x5E, 0x5A, 0x9A, 0x9B, 0x5B, 0x99, 0x59,
0x58, 0x98, 0x88, 0x48, 0x49, 0x89, 0x4B, 0x8B, 0x8A, 0x4A, 0x4E,
0x8E, 0x8F, 0x4F, 0x8D, 0x4D, 0x4C, 0x8C, 0x44, 0x84, 0x85, 0x45,
0x87, 0x47, 0x46, 0x86, 0x82, 0x42, 0x43, 0x83, 0x41, 0x81, 0x80, 0x40
};

98
uint16_t usRTUCRC(uint8_t *pucDataFrame, uint16_t usDataLength)
{
uint8_t ucCRCHi = 0xFF;
uint8_t ucCRCLo = 0xFF;
int8_t iIndex;

while(usDataLength--)
{
iIndex = ucCRCLo ^ *pucDataFrame++;
ucCRCLo = (uint8_t)(ucCRCHi ^ aucCRCHi[iIndex]);
ucCRCHi = aucCRCLo[iIndex];
}
return (uint16_t)((ucCRCHi << 8) | ucCRCLo);
}

C.9

TEA.h

#ifndef TEA_H_
#define TEA_H_
#include <stdint.h>
void Encryptor(uint32_t *const ulPlaintext, /*uint32_t *const ulCiphertext,*/
uint32_t *const Cipherkey);
void Decryptor(/*uint32_t *const ulCiphertext,*/ uint32_t *const ulPlaintext,
uint32_t *const Cipherkey);
#endif TEA_H_

99
C.10

TEA.c

/* ----------------------- Dependency includes -----------------------------------------------*/


#include "tea.h"

void Encryptor(uint32_t *const ulPlaintext, /*uint32_t *const ulCiphertext,*/


uint32_t *const Cipherkey)
{
register uint32_t

MSB = 0, LSB = 0, sum, delta, a = 0, b = 0, c = 0 ,d = 0, n = 32;

MSB = ulPlaintext[0];
LSB = ulPlaintext[1];
sum = 0;
delta = 0x9E3779B9;
a = Cipherkey[0], b = Cipherkey[1], c = Cipherkey[2], d = Cipherkey[3];

while(n-->0)
{
sum += delta;
MSB += (LSB << 4)+a ^ (LSB+sum) ^ (LSB >> 5)+b;
LSB += (MSB << 4)+c ^ (MSB+sum) ^ (MSB >> 5)+d;
}

ulPlaintext[0] = MSB; ulPlaintext[1] = LSB;


}

void Decryptor(/*uint32_t *const ulCiphertext,*/ uint32_t *const ulPlaintext,


uint32_t *const Cipherkey)
{
register uint32_t

MSB = ulPlaintext[0], LSB = ulPlaintext[1],


sum = 0xC6EF3720, delta = 0x9E3779B9,
a = Cipherkey[0], b = Cipherkey[1], c = Cipherkey[2],
d = Cipherkey[3], n = 32;

100
while(n-->0)
{
LSB -= ((MSB << 4)+c) ^ (MSB+sum) ^ ((MSB >> 5)+d);
MSB -= ((LSB << 4)+a) ^ (LSB+sum) ^ ((LSB >> 5)+b);
sum -= delta;
}

ulPlaintext[0] = MSB; ulPlaintext[1] = LSB;


}

C.11

Deviceport.h

#ifndef DEVICEPORT_H_
#define DEVICEPORT_H_

/* ----------------------- AVR Platform includes --------------------------------------------*/


#include <avr/io.h>
#include <avr/interrupt.h>
/* ----------------------- Defines ---------------------------------------------------------------*/
#define ENABLE
#define DISABLE

1
0

/* ----------------------- AVR ATmega324p platform specifics ---------------------------*/


#define UDR

UDR0

#define RXEN

(1<<RXEN0)

#define TXEN

(1<<TXEN0)

#define RXCIE

(1<<RXCIE0)

#define TXCIE

(1<<TXCIE0)

#define UDRIE

(1<<UDRIE0)

#define UDRE

(1<<UDRE0)

#endif DEVICEPORT_H_

101
C.12

Deviceinit.c

/* ----------------------- Dependency includes -----------------------------------------------*/


#include "main.h"
#include "avrwise.h"
#include "deviceport.h"

/* ----------------------- Functions Implementation -----------------------------------------*/


void Port_Init(void)
{
DDRA = 0x78;
PORTA = 0;
DDRB = 0xFF;
PORTB = 0x00;
DDRC = 0xD1;
PORTC = 0;
DDRD |= (1<<7)|(1<<6);
sbi(PORTD,6);
sbi(PORTD,7);
}

void UART_Init(void)
{

// USART0 initialization
// Communication Parameters: 8 Data, 1 Stop, No Parity
// USART0 Receiver: On Transmitter: On
// USART0 Mode: Asynchronous
// USART0 Baud Rate: 9600
UCSR0A=0x00;
UCSR0B = 0;
UCSR0B |= (RXCIE)|(UDRIE)|(RXEN)|(TXEN);
UCSR0C =0x06;
UBRR0H=0x00;
UBRR0L=0x81;

102
void Device_Init(void)
{
cli();
Port_Init();
UART_Init();
MCUCR = 0;
sei();
}

C.13

Deviceserial.c

/* ----------------------- Dependency includes -----------------------------------------------*/


#include "main.h"
#include "deviceport.h"
//#include "avrwise.h"

/* ----------------------- Modbus includes ----------------------------------------------------*/


#include "modbus.h"

/* ----------------------- Functions Implementation -----------------------------------------*/


void vRTUSerialPort(uint8_t RXEnable, uint8_t TXEnable)
{
if(RXEnable == 1)
{
UCSR0B |= RXEN|RXCIE;
}
else
{
UCSR0B &= ~(RXEN|RXCIE);
//UCSR0B |= (0<<RXEN)|(0<<RXCIE);//RXEN|RXCIE;
}

103
if(TXEnable == 1)
{
UCSR0B |= TXEN|UDRIE;
}
else
{
UCSR0B &= ~(UDRIE);
}
}

/* Function to receive data from serial port*/


void vRTUGetChar(uint8_t *pucData)
{
*pucData = UDR;
}

/* Function to transmit data to serial port */


void vRTUPutChar(uint8_t ucData)
{
UDR = ucData;
}

104
C.14

Devicetimer.c

/* ----------------------- AVR Platform includes --------------------------------------------*/


#include <avr/io.h>
#include <avr/interrupt.h>
#include <stdint.h>

/* ----------------------- Dependency includes -----------------------------------------------*/


#include "main.h"

/* ----------------------- Modbus includes ----------------------------------------------------*/


#include "modbus.h"

/* ----------------------- Defines ---------------------------------------------------------------*/


#define TIMER_DELAY

// In second

#define TIMER_MS

1000

#define TIMER_PRESCALER

1024UL

#define TIMER_CLOCK

(F_CPU/TIMER_PRESCALER)

/* ----------------------- Static variables ------------------------------------------------------*/


static uint16_t usTimerCount;

/* ----------------------- Functions Implementation -----------------------------------------*/


void vTimerInit()
{

usTimerCount = (TIMER_CLOCK*TIMER_DELAY/TIMER_MS)-1;
TCCR1A = 0x00;
TCCR1B = 0x00;
TCCR1C = 0x00;
TIFR1 |= (0<<OCF1A);
TIMSK1 = (0<<OCIE1A);
}

105
void vTimerEnable()
{
TCNT1 = 0x0000;

/* Enable timer compare interrupt */


TIMSK1 = (1<<OCIE1A);

/* Initialize OCR timer value*/


OCR1A = usTimerCount;

/* Enable CTC Mode*/


/* Set timer prescaler to 1024 */
TCCR1B |= (1<<WGM12)|(1<<CS12)|(1<<CS10);
}

void vTimerDisable()
{
/* Clear flag timer compare interrupt */
TIFR1 |= (0<<OCF1A);

/* Disable CTC mode */


TCCR1B |= (0<<WGM12)|(0<<CS12)|(0<<CS10);

/* Disable timer compare interrupt */


TIMSK1 = (0<<OCIE1A);
}

106
C.15

Rtufunccoils.c

/* ----------------------- AVR Platform includes --------------------------------------------*/


#include <stdint.h>
#include "deviceport.h"

/* ----------------------- Modbus includes ----------------------------------------------------*/


#include "modbus.h"

/* ----------------------- Defines ---------------------------------------------------------------*/


#define RTU_PDU_FREAD_ADDR_OFF

RTU_SER_PDU_DATA_OFF

#define RTU_PDU_FREAD_COIL_OFF

RTU_SER_PDU_DATA_OFF+2

#define RTU_PDU_FREAD_SIZE

#define RTU_PDU_FREAD_COIL_MAX

0xFF

#define RTU_PDU_FWRITE_ADDR_OFF

RTU_SER_PDU_DATA_OFF

#define RTU_PDU_FWRITE_VAL_OFF

RTU_SER_PDU_DATA_OFF+2

#define RTU_PDU_FWRITE_SIZE

/* ----------------------- Static variables ------------------------------------------------------*/


static volatile uint8_t

ucCoilAddress[6];

/* ----------------------- Functions Implementation -----------------------------------------*/


eRTUException eRTUReadCoil(uint8_t *pucDataFrame, uint16_t *pusDataLength)
{
uint16_t

usRegisterAddress;

uint16_t

usCoilIndex;

uint8_t

ucData;

uint8_t

*pucFrameBuffer;

eRTUException

eXStatus = RTU_EX_NONE;

107
if(*pusDataLength == (RTU_PDU_FREAD_SIZE + RTU_PDU_SIZE_MIN))
{
/* Get target address */
usRegisterAddress =
(uint16_t)(pucDataFrame[RTU_PDU_FREAD_ADDR_OFF]<<8);
usRegisterAddress |=
(uint16_t)pucDataFrame[RTU_PDU_FREAD_ADDR_OFF+1];
usRegisterAddress++;

usCoilIndex =
(uint16_t)(pucDataFrame[RTU_PDU_FREAD_COIL_OFF]<<8);
usCoilIndex |=
(uint16_t)(pucDataFrame[RTU_PDU_FREAD_COIL_OFF+1]);

if((usCoilIndex >= 1) && (usCoilIndex <= 8))


{
/* Set current PDU data pointer buffer to the beginning. */
pucFrameBuffer = &pucDataFrame[RTU_PDU_FUNC_OFF];
*pusDataLength += RTU_PDU_FUNC_OFF;

/* Get function code within PDU. */


*pucFrameBuffer++ = RTU_READ_COILS;
*pusDataLength += 1;

/* Get function data within PDU */


*pucFrameBuffer++ = ucData;
*pusDataLength += 1;

/* Check register address block*/


if((usRegisterAddress >= 1001) && (usRegisterAddress <= 1007))
{

}
}

108
}
else
{
/* Set exception status for invalid data */
eXStatus = RTU_EX_ILLEGAL_DATA_VALUE;
}
return eXStatus;
}

/*eRTUException eRTUWriteCoil(uint8_t *pucDataFrame, uint16_t


*pusDataLength)
{
uint16_t

usRegisterAddress;

uint8_t

ucBuffer[2];

//conditional branch if required


usRegisterAddress =
(pucDataFrame[RTU_PDU_FWRITE_ADDR_OFF] << 8);
usRegisterAddress |=
pucDataFrame[RTU_PDU_FWRITE_ADDR_OFF+1];
usRegisterAddress++;
} */

You might also like