You are on page 1of 40

M2M Assignment Report

Pranav Tankkar

Student No.: 220134178

NCL - MSc ES - IoT

October 2022
Abstract
Machine-to-machine (M2M) communication is a rapidly growing
field with a wide range of applications in industrial automation,
smart cities, and the Internet of Things (IoT). M2M
communication allows devices to communicate with each other
directly, without the need for human intervention. This report
provides an overview of M2M communication for motor PID
control over a wired network. Motor PID controllers are widely
used in industrial automation applications to control the speed and
torque of motors. M2M communication can be used to create
closed-loop control systems in which the controller monitors the
performance of the motor and makes adjustments in real time to
ensure that it is operating at the desired speed and torque. This
report also discusses how to configure the network for
multihoming, firewall configuration, and route setup between
different LANs. This is necessary to ensure that the motor PID
controller and other devices on the network can communicate with
each other.
Contents
Chapter 1.....................................................................................................................................................4
Introduction....................................................................................................................................................4
1.1 Aims and Objectives....................................................................................................................4
Aims 4
Objectives.......................................................................................................................................5
1.2 The OSI Reference Model and M2M Identification............................................................................5
M2M Identification in OSI Model:..................................................................................................7
1.3 Hardware and Software Information....................................................................................8
Hardware.........................................................................................................................................8
Software..........................................................................................................................................8
Chapter 2.....................................................................................................................................................9
Course Work Part-1.................................................................................................................................9
2.1 Network Design Specification................................................................................................9
2.2 IP Configuration........................................................................................................................10
2.3 Multihoming...............................................................................................................................11
2.4 Configuration of Devices.......................................................................................................12
2.5 Testing the Latency..................................................................................................................14
2.6 Configuring the Wifi................................................................................................................15
2.7 Password-less SSH sessions...........................................................................................................17
2.8 Throughput, TCPdump and SSH Pipeline......................................................................................19
Chapter 3...................................................................................................................................................22
Course Work Part-2............................................................................................................................22
3.1 Design of the M2M communication framework............................................................................22
3.2 DC Motor........................................................................................................................................22
3.3 Specifications.............................................................................................................................23
3.3.1 Objectives and Components of a Closed Loop Control System.......................................23
3.4 Control System Analysis........................................................................................................25
3.4.1 Software Process Controller Block...................................................................................25
3.4.2 Step Response Measurements...........................................................................................25
3.5 Rig Components.............................................................................................................................26
3.6 Ensuring System Stability..........................................................................................................26
3.7 Essential Libraries.......................................................................................................................26
3.8 GPIO Configuration....................................................................................................................27
3.9 Interrupts and Significance of the Encoder C Program.........................................................27
3.10 Encoder Algorithm......................................................................................................................27
3.11 Controller Algorithm...................................................................................................................28
3.12 Proportional, Integral, and Derivative Responses..................................................................28
3.13 The Significance of the Controller/Regulator C Program.....................................................28
3.14 Experiment 1................................................................................................................................28
3.15 Experiment 2................................................................................................................................29
Chapter 4...................................................................................................................................................31
Conclusion.....................................................................................................................................................31
References..................................................................................................................................................32
Appendices................................................................................................................................................32

3
Chapter 1
Introduction
The introduction serves as a fundamental section providing a
context for the subsequent discussions. In this chapter, we delve
into the expansive realm of the Internet of Things (IoT) with a
specific focus on machine-to-machine (M2M) communication
over wired networks. The Internet of Things (IoT) is a
transformative technological paradigm that has gained remarkable
traction in recent years. It encompasses a vast ecosystem of
interconnected devices, enabling them to communicate, collect,
and exchange data, leading to intelligent decision-making and
automation. IoT applications are ubiquitous, ranging from smart
homes and wearable devices to industrial automation and
healthcare systems. At the heart of IoT lies machine-to-machine
(M2M) communication, a pivotal aspect that drives the seamless
flow of data between devices.

Figure 1: M2M DeviceHive Architecture

1.1 Aims and Objectives

Aims
 The initial aim of the experiment is to establish network
connections among the computer hardware (Raspberry Pis)
across various LANs. This involves setting up IP routing
between these devices and to the internet, as well as
configuring them with IPv4 addresses. The objective is to
select the gateways for efficient packet transmission
between different LANs.

 The second phase of the experiment entails linking a DC


4
motor to any of the Raspberry Pis via a local area network
(LAN) and allowing precise control over its rotational
speed. This involves creating software components like an
encoder program to measure speed, a controller program to
set the target speed, and capturing step responses to
evaluate and fine-tune the control system. The objective is
to achieve stability and accuracy in motor speed control for
practical applications.

Objectives
 Configure hosts and define LANs with provided IP
addresses for effective communication.

 Ensure proper gateway setup for seamless connectivity


within and between LANs.

 Utilize tcpdump to analyze packet headers, focusing on


key fields and network performance.

 Measure latency and throughput for optimized intra and


inter-LAN connections.

 Generate and distribute SSH keys to facilitate secure,


password-less SSH sessions.

 Conduct experiments to forward data pipelines through


SSH, streamlining data transfer.

 Develop essential software components: Encoder program,


Controller program, and Step response capture tool.

 Configure the encoder program for optimal sample rate


and frequency measurement.

 Set the controller program to achieve a targeted rotational


speed of 2Hz for the motor.

 Capture and analyze motor speed responses to evaluate


system stability and performance.

1.2 The OSI Reference Model and M2M Identification


To comprehend M2M communication effectively, it's essential to
understand the OSI (Open Systems Interconnection) reference model.
The OSI model provides a conceptual framework that categorizes
5
network communication into seven distinct layers, each with its specific
functionalities and responsibilities. These layers, from the physical layer
to the application layer, collectively form the foundation for device
communication within IoT and M2M systems.

 Physical layer: Data transmission across the network medium is


handled by the physical layer. The physical layer of M2M
systems can use a range of media, such as wired networks
(Ethernet, power line, etc.). ) and wireless networks (such as Wi-
Fi and cellular). ( ).

 Data Link layer: This layer is in charge of encoding data into


packets and identifying and fixing data errors. Data link layer
protocols like 6LoWPAN and ZigBee, which are intended for
low-power and low-latency communication, are frequently used
in M2M systems.

 Network layer: Packets are routed to their destination by the


network layer. The network layer in M2M systems is frequently
used to implement routing protocols, like RPL and 6LoWPAN,
that are intended for low-power, low-latency networks.

 Transport layer: Ensuring dependable end-to-end communication


between apps is the responsibility of the transport layer.
Transport layer protocols like UDP-Lite and CoAP, which are
intended for low-power and low-latency communication, are
frequently used in M2M systems.

 Session layer: In order to manage sessions between applications,


the session layer is in charge. Session layer protocols like DTLS
and CoAP, which are intended for low-power and low-latency
networks, are frequently used in M2M systems.

 Presentation layer: The presentation layer is in charge of


converting data into a format that the application can
comprehend. Presentation layer protocols in M2M systems are
typically low-level.

6
Figure 2: OSI Model

M2M Identification in OSI Model:


In the context of M2M technology, the first four layers (Physical, Data
Link, Network, and Transport) are typically considered as the foundation
of the Internet, forming the underlying infrastructure for M2M systems.
These layers handle data transmission, framing, routing, and reliable
communication.

M2M Registration (Layer 5 - Session):

M2M devices register themselves at the session layer, establishing


connections within the M2M framework. This layer manages and
coordinates the sessions, exchanges, and dialogues between the M2M
applications.

API for Communication (Layer 6 - Presentation):

The presentation layer in the OSI model provides the API necessary for
devices, clients, and administrators to communicate with the M2M
framework. It acts as an intermediary for transforming data into a format
that the application layer can utilize.

System Level Characteristics (Layer 7 - Application):

At the application layer, the M2M system defines its topology, protocols,
and languages. It is unaware of the method of communication (whether
7
it's the Internet or OSI layers 1-4) and the method of registration of the
"things" (Layer 5). The application layer uses the OSI 6 API for
communication within the M2M system.

Understanding how M2M integrates into the OSI reference model allows
for a clear grasp of the system's structure and the interactions that occur
at various levels, aiding in effective design and implementation of M2M
networks. Understanding these layers is crucial for delving into the
intricacies of M2M communication within IoT, as each layer plays a
vital role in ensuring seamless communication between devices.

1.3 Hardware and Software Information

Hardware
As a network host device (RigPi Device), a Raspberry Pi computer is
used. Using multihoming, it functions both as a host and a gateway
on the network. When connected to one of the network's RigPi
devices, a DC motor performs the role of an IoT device. To power
and manage the DC motor, a Driver Board is utilized.

Software
The RigPi hardware runs a Linux-based operating system. C is a
programming language used to create computer programs. Making
and editing "C" programs requires the use of an nano editor. ssh,
ping, netstat, nslookup, route, iptables, and ifconfig are among the
numerous network Linux commands used. Plotting graphs using
output data requires the use of GNUPlot.

8
Chapter 2
Course Work Part-1
2.1Network Design Specification
All these Raspberry Pi devices operate on the Linux operating
system. Raspberry Pi A, known as Manager Pi 1 A, acts as the
Master Pi, while the other three devices (pi1b, pi2a, pi2b) are
collectively referred to as My Rig or RigPi. The next objective is
to configure these RigPi devices to be part of three LAN
networks: LAN 1, LAN 2, and LAN 3.

Figure 3: The LAN architecture

We have four Raspberry Pi devices identified by hostnames:

 Manager Pi 1 A: Hostname - pi1a


 My Rig B: Hostname - pi1b
 My Rig C: Hostname - pi2a
 My Rig D: Hostname - pi2b

9
2.2IP Configuration

Figure 3: IP Packet Structure

The appropriate IP addresses for the relevant devices are first


specified in the /etc/network/interfaces file. This file contains
definitions for two interfaces, designated as eth0 and eth0:0 and
each linked to a particular IP configuration.

Hostname entries are then added to the /etc/hosts file, ensuring


efficient resolution of local hostnames. The /etc/resolv.conf file
also receives an entry with domain information required for
network configuration.

The /etc/network/interfaces file is modified to include the


pertinent IP addresses for the eth0 and eth0:0 interfaces for
configuring RigPi-A's IP address. A visual representation of these
configurations can be found in the Interfaces File (Figure 4).

The 'ifconfig' command is then used to verify the changes made


(Figure 5) and shows that the defined IP addresses have been
successfully implemented. In conclusion, all Raspberry Pi devices
connected to this network are set up using a Linux-based
operating system and a structured method for configuring network
interfaces. By doing this, the devices within the defined network
environment are guaranteed to communicate and operate
effectively.

Device IP assignments within the LANs are as follows:

 ManagerPi A (pi1a):
LAN 1: 192.168.27.1

 MyRig B (pi1b):
10
LAN 1: 192.168.27.2
LAN 2: 192.168.124.4

 MyRig C (pi2a):
LAN 2: 192.168.124.3
LAN 3: 192.168.116.2

 MyRig D (pi2b):
LAN 3: 192.168.116.1

The network is structured with three LANs connecting the


devices:

1. LAN 1:
 Connects ManagerPi A (pi1a) with IP 192.168.27.1
 Connects MyRig B (pi1b) with IP 192.168.27.2
 Subnet: 192.168.27.0

2. LAN 2:
 Connects MyRig B (pi1b) with IP 192.168.27.1
 Connects MyRig C (pi2a) with IP 192.168.124.4
 Subnet: 192.168.124.0

3. LAN 3:
 Connects MyRig C (pi2a) with IP 192.168.124.4
 Connects MyRig D (pi2b) with IP 192.168.116.2
 Subnet: 192.168.116.0

This network configuration allows for communication and


interaction between the devices based on their respective
hostnames and assigned IP addresses within their respective
LANs.

2.3Multihoming
The allocation of RigPi devices to their respective LANs, each
given a different IPv4 Class C address, as shown above. The
network computers are set up as multihoming devices, which is
highlighted by the specific IPv4 Class C range at which these
addresses are set. Surprisingly, this configuration is carried out on

11
a single network interface card, demonstrating the efficient use of
IPv4 Class C addresses for efficient networking between the
devices.

Figure 6: Multihoming of RigPi B

2.4Configuration of Devices
Interconnecting all devices within a network is essential for
seamless communication and efficient data exchange. In the
described network scenario involving ManagerPi A (pi1a), MyRig
B (pi1b), MyRig C (pi2a), and MyRig D (pi2b) with their
respective LANs and IP addresses, establishing internetworking
involves configuring routing tables and firewall rules to enable
communication between these devices across different LANs.

Configure Firewall Rules with iptables:

ManagerPi A (pi1a):

sudo iptables -v -A FORWARD -s 192.168.27.0/24 -d


192.168.124.0/24 -j ACCEPT: This rule allows traffic to flow
from the 192.168.27.0/24 subnet to the 192.168.124.0/24 subnet.

sudo iptables -v -A FORWARD -s 192.168.27.0/24 -d


192.168.116.0/24 -j ACCEPT: Similarly, this rule allows traffic
from 192.168.27.0/24 to 192.168.116.0/24.
12
MyRig B (pi1b):

sudo iptables -v -A FORWARD -s 192.168.116.0/24 -d


192.168.124.0/24 -j ACCEPT: This rule allows traffic to flow
from the 192.168.116.0/24 subnet to the 192.168.124.0/24 subnet.

sudo iptables -v -A FORWARD -s 192.168.116.0/24 -d


192.168.27.0/24 -j ACCEPT: Similarly, this rule allows traffic
from the 192.168.116.0/24 subnet to the 192.168.27.0/24 subnet.

MyRig C (pi2a):

sudo iptables -v -A FORWARD -s 192.168.124.0/24 -d


192.168.27.0/24 -j ACCEPT: This rule allows traffic to flow from
the 192.168.124.0/24 subnet to the 192.168.27.0/24 subnet.

MyRig D (pi2b):

sudo iptables -v -A FORWARD -s 192.168.116.0/24 -d


192.168.124.0/24 -j ACCEPT: This rule allows traffic to flow
from the 192.168.116.0/24 subnet to the 192.168.124.0/24 subnet.

sudo iptables -v -A FORWARD -s 192.168.116.0/24 -d


192.168.27.0/24 -j ACCEPT: Similarly, this rule allows traffic
from the 192.168.116.0/24 subnet to the 192.168.27.0/24 subnet.

Set Up Routing Rules:

ManagerPi A (pi1a):

sudo route add -net 192.168.124.0 netmask 255.255.255.0 gw


192.168.27.2: This sets up a route to the 192.168.124.0/24 subnet
via the gateway at 192.168.27.2 (machine B).

sudo route add -net 192.168.116.0 netmask 255.255.255.0 gw


192.168.27.2: Similarly, a route is set up for the 192.168.116.0/24
subnet via the same gateway.

MyRig B (pi1b):

sudo route add -net 192.168.116.0 netmask 255.255.255.0 gw


192.168.124.4: This sets up a route to the 192.168.116.0/24 subnet
via the gateway at 192.168.124.4 (machine C).

MyRig C (pi2a):

13
sudo route add -net 192.168.27.0 netmask 255.255.255.0 gw
192.168.124.3: This sets up a route to the 192.168.27.0/24 subnet
via the gateway at 192.168.124.3 (machine B).

MyRig D (pi2b):

sudo route add -net 192.168.124.0 netmask 255.255.255.0 gw


192.168.116.1: This sets up a route to the 192.168.124.0/24 subnet
via the gateway at 192.168.116.1 (machine C).

sudo route add -net 192.168.27.0 netmask 255.255.255.0 gw


192.168.116.1: Similarly, a route is set up for the 192.168.27.0/24
subnet via the same gateway.

Figure: Routes Configured

The configuration of all RigPi devices involves enabling IP


forwarding, configuring network interfaces, defining firewall
rules, and establishing routing rules. The "route -n" command
displays the current routing table, allowing us to verify the route
table of the individual RigPi devices.

2.5Testing the Latency


Pinging is a basic network diagnostic tool that checks connectivity
and measures data travel time. It works by sending an ICMP echo
request packet to a target device. If the device is reachable, it
responds with an echo reply, confirming a successful network
connection. This tool is essential for diagnosing and resolving
network issues.

Pinging Devices from A:


 Pinging B from A: ping 192.168.124.3 (A to B)
14
 Pinging C from A: ping 192.168.124.4 (A to C)
 Pinging D from A: ping 192.168.116.2 (A to D)

Pinging Devices from B:


 Pinging A from B: ping 192.168.27.1 (B to A)
 Pinging C from B: ping 192.168.124.4 (B to C)
 Pinging D from B: ping 192.168.116.2 (B to D)

Pinging Devices from C:


 Pinging A from C: ping 192.168.27.1 (C to A)
 Pinging B from C: ping 192.168.27.2 (C to B)
 Pinging D from C: ping 192.168.116.2 (C to D)

Pinging Devices from D:


 Pinging A from D: ping 192.168.27.1 (D to A)
 Pinging B from D: ping 192.168.27.2 (D to B)
 Pinging C from D: ping 192.168.124.4 (D to C)

Traceroute from A to D:

Running traceroute 192.168.116.2 from A to D will provide a


hop-by-hop trace of the route taken by packets from A to D. It will
show the intermediate routers or gateways, and the number of
hops it takes for a packet to reach D from A. This traceroute
command can help identify any routing issues or delays in the
network.

Figure 8: Latency Calculation

2.6Configuring the Wifi

15
The following instructions were followed to configure of Wi-Fi
and network settings on ManagerPi A (pi1a):

1. Configuration of `/etc/network/interfaces`:

This initial step involves editing the `/etc/network/interfaces` file


on device A. Within this file, several key configurations are
specified. Notably, the loopback interface and the Ethernet (eth0)
interface are configured with a static IP address. It is important to
note that the gateway entry for eth0 is commented out, thus
preserving the default gateway setting.

2. Password Hash Generation:

The subsequent procedure entails the generation of a hash for the


WiFi password. This hash is created using a specific command
provided and is to be used for WiFi network authentication. The
resulting hash, such as '965d3595101640dbaa4bcf5987bf954,' will
serve as a credential for connecting to the WiFi network.

3. Configuration of `/etc/wpa_supplicant/wpa_supplicant.conf`:

In this step, the `/etc/wpa_supplicant/wpa_supplicant.conf` file on


device A is modified to encompass essential WiFi settings. These
settings include the Service Set Identifier (SSID), EAP
(Extensible Authentication Protocol) authentication method
(TTLS), identity, and the password hash, as generated in the
preceding step. This file plays a pivotal role in securing the WiFi
connection.

16
Figure: wpa_supplicant.conf file

4. Adjustment of `/etc/sysctl.conf`:

The subsequent action involves making modifications to the


`/etc/sysctl.conf` file. The primary objective here is to disable
IPv6 networking since IPv4 is being utilized. Several directives
are included to deactivate IPv6 for various network interfaces.
This ensures that the network stack operates exclusively in the
IPv4 domain.

5. Network Restart:

After amending the `/etc/sysctl.conf` file, it is recommended to


restart the network configuration. The command
`/etc/init.d/networking restart` is employed for this purpose. This
step helps implement the changes made to the network settings.

6. Network Connectivity Testing: Pinging Google Server (from


A):

To validate network connectivity, the 'ping' command is executed


towards a prominent Google DNS server with the IP address
'8.8.8.8.' This operation tests the ability of device A to
communicate with external internet resources.

7. Network Connectivity Testing: Pinging Newcastle University


Website (from A):

17
As a further assessment of network functionality, the 'ping'
command is employed to ping the Newcastle University website
with the hostname 'www.ncl.ac.uk.' This assesses the device's
capacity to access specific web resources on the network.

2.7Password-less SSH sessions

Figure: SSH Protocol

The below provided instructions detail the process of SSH key


generation and sharing among devices A, B, C, and D, as well as
making configuration changes for internet access. Here's a
summary of these actions:

SSH Key Generation and Sharing:

Figure: SSH Key Generation

1. Shared Public Key from A:

Navigate to the `.ssh/` folder: `cd .ssh/`

List files in the folder: `ls a`

18
Generate an SSH key pair: `ssh-keygen`
 Copy the public key from A to B:
`ssh-copy-id group-a@192.168.27.2`
 Copy the public key from A to C:
`ssh-copy-id group-a@192.168.124.4`
 Copy the public key from A to D:
`ssh-copy-id group-a@192.168.116.2`

2. Repeat for B, C, and D:

Generate an SSH key pair for B, C, and D.

Copy the respective public keys to A, C, and D (each device to the


other two devices).

Changing dhcpcd.conf File on B, C, and D:

 Edit dhcpcd.conf:

For devices B, C, and D, make changes in the


`/etc/dhcpcd.conf` file to enable internet access through
device A. The specific changes are not detailed here but
are likely related to routing and gateway configurations.

Changing DNS Server in B, C, and D:

 Edit resolv.conf:

On devices B, C, and D, modify the `/etc/resolv.conf` file


to specify DNS servers for WiFi functionality.

Add DNS server addresses to the file, e.g., `nameserver 8.8.8.8`


and `nameserver 1.1.1.1`.

2.8Throughput, TCPdump and SSH Pipeline


In order to find the throughput between to devices. The pi device
which receives the data stream must be configured as a listening
device. In order to achieve this, we must type the following
command.
Step 1: Install Netcat (nc) on Devices A, B, C, and D for
Throughput:
Run the following command on each device to install Netcat:

sudo apt install netcat

19
Figure: Throughput

Step 2: Install TCPdump on Devices A, B, C, and D:


Use the following command on each device to install TCPdump, a
network packet analysis tool:
sudo aptget install tcpdump

20
Figure: TCPdump

Step 3: Setting up an SSH Pipeline between Devices A and B:

Figure: SSH Pipeline

On Device A:

1. Create a named pipe (FIFO) called `fifoA` using the command:


mkfifo ~/fifoA

2. Create another named pipe called `fifoB` with the command:

21
mkfifo ~/fifoB

3. Use the `cat` command to establish an SSH connection from


Device A to Device B and create a pipeline for data transfer:
cat ~/fifoA | ssh group-a@192.168.27.2 'cat > ~/fifoB'

4. In a different terminal on Device A (`A terminal2`), write the


message "hi I am A" to `fifoA` using the following command:
echo "hi I am A" > ~/fifoA

5. To read the data sent from Device A, run the following


command in a terminal on Device B:
cat ~/fifoB

6. Create another named pipe called `fifo2A` on Device A:


mkfifo ~/fifo2A

7. Simultaneously send data to `fifoA` and save it to `fifo2A` with


the following command:
echo "hi I am A" > ~/fifoA | tee ~/fifo2A

22
Chapter 3
Course Work Part-2
Part 2 of the practical coursework entails the design and
implementation of a closed-loop control system. It consists of two
experiments, each highlighting different aspects of control system
architecture. Experiment 1 emphasizes simplicity and stability by
connecting the control system to a Rig Pi. It involves fine-tuning
PID coefficients and sample rates to achieve system stability. In
Experiment 2, network complexity is introduced, leading to
increased latency and decreased stability. This experiment
requires rewiring the system, employing secure shell connections,
and testing different PID coefficients and sample rates. Both
experiments involve measuring the step response, plotting motor
speed over time in response to a Heaviside step function.
Proficiency in C programming is essential, particularly in
handling data formats and utilizing C libraries for hardware
control. Careful consideration of PID coefficients and sample rates
is crucial to achieving system stability in these experiments.

3.1 Design of the M2M communication framework

Through the connection of a DC motor to a networked host/device


(Raspberry Pi), this experiment showcases an M2M device
communication framework. The use of the host's IP address for
remote DC motor control is covered later in the report. This M2M
setup uses IPv4 Class C addresses and TCP/IP. Designing the
communication framework requires a thorough understanding of
the operation of the DC motor.

3.2 DC Motor

23
Figure: DC motor Connected to Raspberry Pi

Two crucial parts make up a DC motor: the encoder attached to


the shaft and the DC motor shaft. The encoder's job is to record
and calculate how many rotations the shaft makes. The rotational
frequency information is then used as feedback for a piece of
software, allowing for precise control of the speed of the DC
motor shaft. Image The encoder component's internal architecture
consists of a disk with 500 cut slots in it. These slots allow light
from an LED to be directed onto photodiodes on the other side.
Signal pulses are produced by the photodiodes when they detect
an LED flash. Notably, 500 pulses, or a frequency of 500Hz, are
produced for every full rotation of the disk wheel.

The DC motor is linked to the RigPi-B host via an RS-232 serial


connection using a control board. To adjust the motor's rotational
speed, specific directives are sent to the serial port from the RigPi-
B server. Additionally, the encoder component of the DC motor is
attached to the RigPi-B host's GPIO pins, specifically GPIO-9 and
GPIO-10.

For the purpose of regulating the DC motor's speed via the RigPi-
B host, a particular command is employed:

echo 770 1\\ > /dev/serial0

It's important to note that when the value in this command is set to
737, it acts as a reference point equivalent to bringing the motor to
a standstill. When the value surpasses 737, the motor's shaft
initiates clockwise rotation, as demonstrated by this command:
24
echo 800 1\\ > /dev/serial0

Conversely, if the provided value is less than 737, the motor's


shaft commences an anti-clockwise rotation, as indicated by this
command:

echo 600 1\\ > /dev/serial0

These commands are central to the precise control of the DC


motor's speed through the RigPi-B host, facilitating both
clockwise and anti-clockwise rotations as needed for specific
applications.

3.3 Specifications

3.3.1 Objectives and Components of a Closed Loop


Control System

The main objective of this project is to design a closed-loop


control system for an electric motor, and it involves several
critical software components.

Encoder Program: The encoder program is responsible for data


collection. It enables the selection of an appropriate sampling rate,
data format, and method for measuring frequency. The collected
data is then outputted to the standard output stream (stdout) for
further processing.

Controller Program: The controller program's primary function is


to manage the motor's speed. It sets a specific target rotational
speed of 2Hz, and the controller's role is to ensure the motor
operates at this desired speed.

Step Response Capture: This component is essential for


understanding how the system behaves. It entails capturing and
plotting the motor's speed over time in response to a Heaviside
step function, which represents a sudden change in control input.

Stability Testing: The project includes various tests to assess


system stability. It evaluates performance under different
scenarios. First, it examines stability when the encoder and
controller are on the same device. Then, it extends this evaluation
to scenarios where they are on different devices within the same
LAN. Lastly, it explores the implications of operating on separate
LANs. These tests offer insights into how network communication
25
affects control system performance.

Figure 10: Control System Architecture

3.4 Control System Analysis

3.4.1 Software Process Controller Block


The software process controller in this block is responsible for regulating
the rotational speed of the DC motor shaft. It achieves this by collecting
feedback input from the encoder block. This forms a closed-loop control
system operating at 2Hz. To calculate and generate the desired setpoint
value, a PID (Proportional, Integral, and Differential) algorithm is
employed. After this computation, the RigPi B host or computer is
utilized to execute the controller program. To drive the DC motor, the
PID data output must be configured through the serial port on the host.

Hardware Rig Block: The output of this block is the rotation of the shaft,
which is realized through a DC motor. The key parameter here is the
rotational frequency of the shaft.

Software Process Encoder: This component is responsible for measuring


the output data from the hardware rig. The signal data is acquired from
the GPIO (General Purpose Input Output) pins 9 and 10 on the RigPi B
computer using the encoder software program. The collected data is then
26
compared to the desired value. Any resulting error is processed through
the PID controller, which adjusts the motor's speed to either accelerate or
decelerate, depending on the polarity of the error.

3.4.2 Step Response Measurements


First, a modification is made to the controller program, replacing the
constant 2Hz with a variable. This change eliminates the constant and
involves adding a small piece of code.

The encoder is used to record the output data, with the encoder's output
connected to the controller's input through a pipeline. The "tee" utility, a
standard tool in the Linux system, is used to create a copy of the standard
output and save it to a file.

To gain insights from the data and tune the PID coefficients, "Gnuplot"
software is employed to plot the step response data over time. To plot the
data stored in a file, the "gnuplot" tool is initiated, and the data can be
visualized using the command "plot samples.dat with lines." The
"samples.dat" file contains data with one data point per line.

3.5 Rig Components


Figure 13 illustrates the components that make up the rig. The rig
includes a DC motor linked to both an encoder and a regulator.
This coursework is segmented into two distinct experiments.
These experiments revolve around assessing stability, either
within the same device or across different LANs.

Figure 13: Rig Components

27
3.6 Ensuring System Stability
Upon the system's deployment, it is imperative to conduct a
thorough assessment of its stability. If any indications of
instability emerge, it becomes necessary to finetune the
coefficients of the PID controller. A reduction in the gain
mitigates oscillations, thereby enhancing system stability, albeit at
the potential cost of a diminished system response rate.

3.7 Essential Libraries


To underpin the program's functionality, a suite of essential
libraries is incorporated:

#include <stdio.h> // Facilitating functions like printf() and


fflush()

#include <unistd.h> // Enabling functions like usleep(), lseek(),


and read()

#include <stdlib.h> // Supporting functions such as system()

#include <poll.h> // For effective event polling

#include <fcntl.h> // Facilitating file operations, including file


opening

#include <pthread.h> // Enabling threadrelated operations such as


mutexes

#include <time.h> // Supporting timerelated functions

3.8 GPIO Configuration


This segment expounds upon the configuration of General-
Purpose Input/Output (GPIO) pins for the encoder. The provided
code serves as an illustrative example of executing a shell script
within a C program. GPIO pins 9 and 10 are set up for the purpose
of capturing data from the encoder, with pin 9 designated for
managing interrupt responses and pin 10 used to discern the
direction of shaft rotation.

3.9 Interrupts and Significance of the Encoder C


Program
28
These sections offer comprehensive insights into the handling of
interrupts generated by the encoder and the pivotal role played by
the encoder program. The code showcases the utility of the "poll"
function for awaiting interrupts. The process of managing
interrupts entails the essential steps of clearing the read buffer and
extracting data from GPIO pins. These procedures are
indispensable for achieving precise frequency measurements.

3.10 Encoder Algorithm


A meticulous account of the intricate execution of two concurrent
threads. These threads play a pivotal role in the functionality of
the encoder system. One thread is entrusted with the crucial task
of handling interrupts, ensuring that the system responds promptly
to external stimuli. The other thread is dedicated to the precise
tallying of frequencies, providing invaluable data for the control
system's operation. To maintain the integrity and reliability of this
dual-thread operation, the deployment of mutexes is of paramount
importance. These mutexes serve as sentinels, orchestrating
synchronized access to shared resources. This synchronized
collaboration between the threads is vital to the smooth and
efficient operation of the encoder system, ultimately ensuring the
accuracy of the data captured.

3.11 Controller Algorithm


The controller's algorithm is a well-orchestrated symphony of
coefficients, with a primary focus on two fundamental ones:

Kp (Proportional coefficient) and Ki (Integral coefficient).

The Kp value plays a pivotal role in determining the proportional


response, while the Ki coefficient is responsible for shaping the
integral response. These coefficients are not arbitrary; they are
carefully selected and fine-tuned to orchestrate the behavior of the
control system with precision and accuracy. This section serves as
a guide to understanding how these coefficients influence the
controller dynamics, leading to a stable and responsive control
system.

3.12 Proportional, Integral, and Derivative


Responses
29
These sections delve into the functionalities of the proportional,
integral, and derivative components inherent to the controller. A
comprehensive understanding of their respective roles in
influencing the behaviour of the control system is proffered.

3.13 The Significance of the Controller/Regulator


C Program
This segment underscores the profound significance of the
controller program. It expounds on the program's role in the
computation of errors, the seamless integration of proportional
and integral control, and the dynamic adjustments to input that are
indispensable for sustaining system stability and accuracy.

3.14 Experiment 1

Figure 17: Control System Connected to Rig B

Within this section, the first experiment is expounded upon. It


entails the connection of the control system to the same RigPi

30
device. RigPi B is chosen primarily for its operational
convenience, as it obviates the introduction of additional latency
stemming from network interactions. The consolidation of both
encoder and controller within the same device yields a robust step
response function.

Figure 18: Encoder Readings

In this configuration, marked by stability, the PID coefficients are


as follows: Kp = 0.85, Ki = 0.8, and the sample rate is set at
SAMPLE_RATE_MS ms for a standalone machine. Additionally,
the total number of interrupts per rotation is set to
TOTAL_INTERRUPTS_PER_ROTATION, and the rotation
direction GPIO is designated as GPIO 10.

Figure 19: Step Response

In this less stable configuration, characterized by instability, the


PID coefficients remain the same (Kp = 0.85, Ki = 0.8), but the
sample rate is reduced to SAMPLE_RATE_MS ms. This
modification translates into reduced system stability, in
consonance with the principle that lower sample time can

31
engender diminished system stability.
3.15 Experiment 2

Figure 17: Control System Connected to Rig B, Encoder to Rig D

The segment casts light on the second experiment, which


introduces a layer of network complexity, thereby elevating
latency and exerting a discernible impact on system stability. The
encoder is disengaged from the current machine and subsequently
linked to an alternative one, necessitating the utilization of a
sequence of secure shell connections to enable access. The
resultant step response differs appreciably.

32
Figure 21: Encoder Readings

In In the realm of this stable setup, the PID coefficients align as


Kp = 0.85, Ki = 0.8, while the sample rate is pegged at
SAMPLE_RATE_MS ms. This configuration yields a system
marked by stability. Moreover, the total number of interrupts per
rotation remains at TOTAL_INTERRUPTS_PER_ROTATION,
and the rotation direction GPIO is designated as GPIO 10.

Figure 22: Step Response

Within this less stable framework, the PID coefficients retain their
values (Kp = 0.85, Ki = 0.8), though the sample rate is curtailed to
SAMPLE_RATE_MS ms. This modification precipitates a
situation of system instability, underscored by the salient principle
that as the sample time dwindles, system stability wanes
proportionally. These experiments collectively unveil the
dynamics of system stability amidst varied settings and the
influence of network complexity.

33
Chapter 4
Conclusion
 Comprehending Machine-to-Machine (M2M) Concepts:
Gaining a solid grasp of M2M principles.

 Network Design and IP Address Assignment: Configuring


networks and allocating IP addresses effectively.

 Illustrative Example - Device Hive: Enhancing


understanding by citing the Device Hive as an example.

 Device IP Address Modification: Adjusting IP addresses


for devices as needed.

 Route Table Adjustments: Implementing and modifying


route tables using the appropriate commands.

 Packet Capture and Latency Analysis: Proficiently


capturing and analyzing IP packets to determine latency
between network devices.

 Secure M2M Access via SSH: Utilizing secure shell (SSH)


for passwordless M2M network login.

 IoT Application - Control System Integration: Connecting

34
a control system to a network device to enable remote
control, exemplifying the Internet of Things (IoT).

 PID Algorithm Implementation: Applying the


Proportional-Integral-Derivative (PID) algorithm to
understand closed-loop systems.

 Experiment Comparison and Network Complexity:


Contrasting the outcomes of Experiment 1 and Experiment
2 to draw conclusions about the impact of network
involvement on complexity and latency.

35
References

Ross, K. W., & Kurose, J. F. (2003). Computer Networking A Top-Down


Approach Featuring The Internet

Tanenbaum, A. S., & Wetherall, D. J. (2016). Computer Networks (fifth


edition ed.). Boston, Massachusetts: Pearson Education, Inc.

Appendices
a. Encoder C Program
#include <stdio.h>
#include <unistd.h>
#include <stdlib.h>
#include <poll.h>
#include <fcntl.h>
#include <pthread.h>
#include <time.h>
#include <sys/types.h>
#include <sys/stat.h>

#define SAMPLE_RATE_MS 20
#define TOTAL_INTERRUPTS_PER_ROTATION 500
#define ROTATION_DIRECTION_GPIO 10
#define INTERRUPT_GPIO9

pthread_mutex_t lock = PTHREAD_MUTEX_INITIALIZER;


volatile unsigned int interrupt_count=0;
void* frequency_thread(void* arg)
{

double frequency;
while(1)
{
usleep(SAMPLE_RATE_MS * 1000);

pthread_mutex_lock(&lock);
frequency=(double)( interrupt_count * 0.1);
interrupt_count = 0;
36
pthread_mutex_unlock(&lock);
printf("%1f\n", frequency);
fflush(stdout);
}
return NULL;
}

int main() {
pthread_t freq_thread;
char buffer[4];

system("echo 9 > /sys/class/gpio/unexport;\


echo 9 > /sys/class/gpio/export;\
echo in > /sys/class/gpio/gpio9/direction;\
echo rising > /sys/class/gpio/gpio9/edge;\
echo 10 > /sys/class/gpio/unexport;\
echo 10 > /sys/class/gpio/export;\
echo in > /sys/class/gpio/gpio10/direction;\
echo none > /sys/class/gpio/gpio10/edge");

//start the frequency measurement thread


pthread_create(&freq_thread, NULL, frequency_thread,
NULL);

struct pollfd pfd0;

// open GPIO for interrupt


pfd0.fd=open("/sys/class/gpio/gpio9/value",
O_RDONLY|O_NONBLOCK);
pfd0.events = POLLPRI|POLLERR;
int fd1;
fd1=open("/sys/class/gpio/gpio10/value", O_RDONLY|
O_NONBLOCK); // open gpio for direction
char str[4];
while (1) {
//sem_wait(encoderSemaphore);
lseek(pfd0.fd, 0, SEEK_SET);
read(pfd0.fd,str,1);
int ret = poll(&pfd0, 1, -1);
if(pfd0.revents & POLLPRI)
{
pthread_mutex_lock(&lock);
37
interrupt_count += 1;
pthread_mutex_unlock(&lock);
}

lseek(fd1, 0, SEEK_SET);
read(fd1,buffer,1);

if(buffer[0] == '1')
{
printf("+1\n");
}
else
{
printf("-1\n");
}
fflush(stdout);
}

close(pfd0.fd);
pthread_mutex_destroy(&lock);

return 0;
}

b. Regulator C Program
#include <stdio.h>

#include <stdlib.h>

#include <unistd.h>

#include <fcntl.h>

#include <sys/types.h>

#include <sys/stat.h>

#include <string.h>

#include <time.h>

#include <pthread.h>

#define Kp 0.85

#define Ki 0.8

38
#define Kd 0.0008

#define Km 65

volatile double Finp=0.0;

double I=0;

double Eold=0;

char buffer[100];

pthread_mutex_t lock = PTHREAD_MUTEX_INITIALIZER;

void *variableInput() {

while (1) {

usleep(10000000);

pthread_mutex_lock(&lock);

if(Finp==0.0) Finp=2.0;

else Finp=0.0;

pthread_mutex_unlock(&lock);

int main()

pthread_t threadOne;

double E, D, PID,Y;

double Tsample=0.02;

double Fenc;

char buf[100];

pthread_create(&threadOne, NULL, variableInput, NULL);

39
while(scanf("%lf\n", &Fenc) == 1){

E= Finp - Fenc;

I = I + (E * Tsample);

D = (E - Eold)*50;

PID = (Kp * E) + (Ki * I) + (Kd * D);

Y = 737 + PID * Km;

if(Y > 1337) Y = 1337;

if(Y < 137) Y = 137;

char command[100];

sprintf(command, "echo %d 1\\\\ > /dev/serial0", (int)Y);

system(command);

printf("%lf\n", Fenc);

Eold = E;

pthread_mutex_destroy(&lock);

return 0;

40

You might also like