You are on page 1of 86

Master thesis

Title:
The conception and the implementation of
control system for servomotor with application
of local area network

Authors:
Bartomiej Beko
Mateusz wika

Promoter:
prof. dr hab. in. Zygfryd Gowacz

Course: Electrical Engineering


Faculty of Electrical Engineering, Automatics, Computer Science and Electronics

Department of Electrical Machines


Cracow, 2010

Aware of criminal liability for making untrue statements I declare that the following
thesis was written personally by myself and that I did not use any sources but the ones
mentioned in the dissertation itself.

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

.................................................................
(readable signatures)

We would like to thank our promoter,


dr hab. in. Zygfryd Gowacz for his insights and overall help with our work on this thesis.

Contents
1.

2.

3.

4.

5.

Introduction........................................................................................................................ 5
1.1.

Preface ......................................................................................................................... 5

1.2.

Aim of this thesis ......................................................................................................... 5

Servomotors ....................................................................................................................... 6
2.1.

Description of servomotors ......................................................................................... 6

2.2.

Basic concept of controlling servomotors. .................................................................. 8

2.3.

Parameters characterizing servomotors ..................................................................... 9

2.4.

Various types of servomotors ................................................................................... 11

2.5.

Few history facts about servomechanisms ............................................................... 15

2.6.

The areas of servomotors usage .............................................................................. 18

2.7.

The pros and cons of using servomechanisms. ......................................................... 22

2.8.

How to select a servo to fit Your application ......................................................... 23

Stepper motor control methods ...................................................................................... 24


3.1.

Stepper motors overview .......................................................................................... 24

3.2.

Stepper motor control ............................................................................................... 25

3.3.

Unipolar and Bipolar stepper motors ........................................................................ 26

3.4.

Stepping modes ......................................................................................................... 28

Design of our controller to work with servomechanisms ................................................ 32


4.1.

Aims of our design ..................................................................................................... 32

4.2.

Controller schematics ................................................................................................ 32

4.3.

Description of parts and their tasks - External overview .......................................... 34

4.4.

Description of parts and their tasks - Interior ........................................................... 37

Local area network (LAN), OSI and TCP/IP model ............................................................ 51


5.1.

Characteristic of Local area network ......................................................................... 51

5.2.

Ethernet specification................................................................................................ 51
3

6.

7.

5.3.

OSI model .................................................................................................................. 52

5.4.

TCP/IP Model ............................................................................................................. 54

LPT port description ......................................................................................................... 55


6.1.

History........................................................................................................................ 55

6.2.

Signals definition ....................................................................................................... 56

6.3.

LPT program access ................................................................................................... 59

Description of C# language and our application .............................................................. 60


7.1.

.NET framework and C# language ............................................................................. 60

7.2.

Description of our application ................................................................................... 61

7.2.1.

Methods, functions, events and classes used in step_server: ........................... 61

7.2.2.

Methods, functions, events and classes used in client_socket_gui: ................. 63

7.2.3.

Lpt.cs class .......................................................................................................... 64

7.2.4.

Namespaces ....................................................................................................... 65

7.3.
8.

Code of server and client programs .......................................................................... 66

Conclusions & summary ................................................................................................... 86

1. Introduction
1.1.

Preface

A servomotor (also called as or servo) is an electromechanical device that uses error-sensing


feedback to correct the performance of a mechanism. The term correctly applies only to
systems where the feedback or error-correction signals help control mechanical position or
other parameters. For example the car's cruise control uses closed loop feedback, which
classifies it as a servomechanism.
Important fact is, that servomechanism may or may not use a servomotor in its design. An
example of this, could be a household furnace. The furnace which is controlled by
thermostat is a servomechanism, however there is no motor being controlled directly by the
servomechanism. In our work, we are using servomotor as an object of exploration and we
will be generally concentrating on the motor devices.
Usually, servos operate on the principle of negative feedback, where the control input is
compared to the actual position of the mechanical system as measured by some sort of
transducer at the output. Any difference between the actual and wanted values (an "error
signal") is amplified and used to drive the system in the direction necessary to reduce or
eliminate the error. This procedure is one widely used application of control theory.
In other words servomotor is device that has an output shaft. This shaft can be positioned to
specific angular positions by sending the servo a coded signal. As long as the coded signal
exists on the input line, the servo will maintain the angular position of the shaft. As the
coded signal changes, the angular position of the shaft changes.
In practice, servos are used in radio controlled airplanes to position control surfaces like the
elevators and rudders, automatic machine tools, satellite-tracking antennas, automatic
navigation systems on boats and planes, and antiaircraft-gun control systems. They are also
used in radio controlled cars, and of course, robots. Servomechanisms were first used in
military fire-control and marine navigation equipment. Many autofocus cameras also use a
servomechanism to accurately move the lens, and thus adjust the focus. A modern hard disk
drive has a magnetic servo system with sub-micrometer positioning accuracy.

1.2.

Aim of this thesis

The aim of this thesis is to write program used to control servomotor in Windows XP
network environment concretely in local area network environment. The program will
utilize the potential of LPT port. Program written as a result of this work will then be used for
educational purposes to demonstrate the work of servomotor.

2. Servomotors
2.1.

Description of servomotors

The term servomotor does not really apply to the motor itself, but rather the way in which
the motor is used and controlled. In a position servomotor application, the idea is to hold
the target load (generally attached to the motor shaft through a series of gears for speed
and torque adjustment) in a given position.
Servos are constructed from three basic pieces, a motor, a feedback device, and a control
board. In hobbyist environments the feedback device is typically a potentiometer (variable
resistor). The motor, through a series of gears, turns the output shaft and the potentiometer
simultaneously. The potentiometer is fed into the servo control circuit and when the control
circuit detects that the position is correct, it stops the motor.

Figure 1 Examples of servomotors


In industrial environments the potentiometer can be also a hall effect sensor monitoring
passing teeth on a metal gear, an encoder (optical or magnetic) mounted directly to the
motor, or any other such sensor which can provide position feedback of the motor shaft or
connected portion of the gear train.
It is also possible to determine motor shaft position by counting the commutation pulses on
the terminals of the motor. Some drivers have current re-copy capability, which allows a
fraction of the load current to be output through a reference resistor and measured with an
6

analog-to-digital converter (AC/DC). In this way, it might be possible to monitor the load
current and detect variations in the load current which correspond with the commutation of
the brushes in the motor. However, this method requires additional software and hardware
complexity which do not justify their inclusion, given that encoders are just as effective and
much simpler to implement.
The typical servo varies most in its internal mechanics from other servos and this is generally
the difference between hobbyist and industrial servos. The servo mechanism subsystems are
the motor, the gear train, the potentiometer, the electronics, and the output shaft bearing.
The gears also vary from servo to servo. Inexpensive servos have plastic gears that will wear
out after less than 100 hours of use. More expensive servos have metal gears which are
much more durable. The potentiometer is the feedback device and often the first thing to
fail in servos. If it gets dirty, or the contacts get oxidized, the servo will fail to work properly,
sometimes by "jittering or hunting" since the feedback is inaccurate, or turning completely
to one side and drawing lots of current since the servo doesn't know where its output shaft
is pointing.

Figure 2 Cross-section of servomotor

The last subsystem is the output shaft bearing. Cheap servos invariably have a plastic on
plastic bearing that will not take much load. Medium priced servos generally have metal on
metal bearings that stand up better under extended use and expensive servos have ball
bearings which work best (see also figure 8).
Servomechanisms have a very wide range of applications and are used in hundreds of
numbers devices. On the next figure, presented is one example of the huge usability of
servomotor. The servo is part of stamping press. Connected directly to the crank, it provides
precise accuracy and reliability, which improves the critical areas of press performance
(more interesting examples of servomotor usage are presented in chapter 2.6 of our work).

Figure 3 Cutaway of stamping press including servomotor in it's design

2.2.

Basic concept of controlling servomotors.

There is basically two types of controlling methods of servomotors: using open-loop and
closed-loop system.
An open-loop system operates with no feedback from the object being controlled. This is
sort of a fire and forget approach to control. An input stimulus is provided and the
8

controller commands the system to go to a particular location, speed, and hopes that the
system responds accordingly. There is no information from the system under control to
indicate that it even received the command.
The key to a closed-loop control system is the introduction of feedback. If speed is being
controlled, a measure of the current speed is provided back to the controller, allowing it to
adjust its commands as the system responds to the commands. Likewise is true with
position. We can compare it to gymnast on a balance beam. They are constantly
commanding their muscles to adjust the pressure and position of their feet to maintain a set
position. This is done based on inputs from vision, sense of balance, and even tactile
feedback from contact with the beam itself. This is a perfect example of a closed-loop
system.
The performance of a closed-loop system is partially a function of the speed at which the
feedback is returned to the controller. This closing of the loop will always take a set amount
of time, and the longer that time is the less responsive the controller will be to fast changing
conditions. For example, if the gymnasts are very tired they are not able to perform as
adeptly due to slow response to the feedback received and as conditions change more
rapidly they are more likely to fall off the bar.
Depending on the performance requirements of the application, either a closed-loop or
open-loop control system can be used to control motor position, speed, or other similar
application.
Servos are controlled by sending them a pulse of variable width. The parameters for this
pulse are that it has a minimum width, a maximum width, and a repetition rate. These values
are not standard but there are conventions that are generally accepted. The convention is
that a pulse of approximately 1500 s (1.5 ms) is the neutral point for the servo. Given the
rotation constraints of the servo, neutral is defined to be the position where the servo has
exactly the same amount of potential rotation in the counter clockwise direction as it does in
the clockwise direction. It is important to note that different R/C servos will have different
constraints on their rotation but they all have a neutral position, and that position is always
around 1500 s.

2.3.

Parameters characterizing servomotors

In general, the servos are "active" devices. Thus this means that, when commanded to move
they will actively hold their position. In other words, if a servo is commenced to the neutral
position and then an external force is used to push against the servomechanism (supposedly
through the mechanical linkage), it would result in actively resist being moved out of that
position.
The maximum amount of force that the mechanism can utilize is the torque rating of the
servomotor. The typical value of this quantity is about the equivalent of 1kg at 1 inch away
9

from the shaft of the servo motor. Like in every similar cases, the servomotors can't hold
their position forever. The generation of position pulse must be repeated after a specific
amount of time, in order to instruct the mechanism to stay in the desired position. The
maximum value of this time, which can pass before the device will stop holding its position is
called the command repetition rate. Typical values for the command repetition rate are
chosen from the range of 20 to 30 ms. Of course the pulse can be repeated more often (in
shorter time ranges) than these boundaries, but it can't be generated less often. When the
settled timeout expires and there still hasn't appeared another pulse, then servomechanism
de-energizes the motor. In this state it can be manually pushed out of its position and later it
will not return to the commanded position, as it normally should.
Other case is when the pulse sent to the device is less than 1500 s. The servo positions and
then holds its output shaft for some number of degrees anti-clockwise from the neutral
point. Secondly, when generated pulse is wider than 1500 s, then the opposite effect takes
place. As a result of above facts, we can say that the minimal width and the maximum width
of pulse that will command the servomotor to turn into the desired valid position, are
functions of each servo. On the world market, there are of course different brands, and even
different servomechanism of the same specific brand, which are specified with different
maximums and minimums. But generally, the typical ranges were set so that minimum pulse
will be about 1000 s wide and the maximum pulse will be 2000 s wide. However, these
are just guidelines and every case of usage should be individually established on the servos
of ones use. Especially if there is a need to command the servomotor over its maximum or
minimum rotation, it could occur in use of the maximum amount of current, resulting in
unsuccessful attempts to achieve that position.
Another parameter which describes and varies different servomechanisms is called the slew
rate. This attribute is a time which takes the device from changing from one position to
another. The worst case of the slewing time value is when the servo is holding at the
minimum rotation and then it is being commanded to change to a maximum rotation. Such
operation can take several seconds when performed on very high torque servomotors (to
compare, the typical time of this action takes less than two seconds).
Sticking friction of the actuator is another very important parameter which describes and
differs each servomotor devices. When the actuator is at rest, there is need of using an extra
force in order to initiate motion of the mechanism. After a while, when the actuator begins
to move, there is also an unwanted possibility that it may suddenly perform a slight jump
(which depends on how tight the mechanical tolerances of the actuator are). In each case
while we are determining response times required for the control systems, this rapid rate of
change should be considered, to avoid problems of usage.
The last property which we should describe is the ratio of output movement to feedback
data acquisition. This attribute also highly affects the accuracy and response of the control
system. To show it on example, consider a basic actuator, where the motor and output shaft
10

has been joined by a series of gears and the potentiometer (used as a feedback mechanism)
is connected to another gear in the system. So the ratio of movement parameter of the
output shaft to the movement of the potentiometer shaft is required to relate rate of
change of the actuator output to the rate of change of the feedback.

2.4.

Various types of servomotors

There are numerous types of servos available on the market. This devices have a wide
variety of very different applications. Because of this, their types vary widely in case of form
and configuration. First important division criteria is the difference between the hobbyist
and industrial servomotors, where the internal mechanics are the reason of varying one
servos from others. Of course different servomotors are varied in case of their precision,
speed, and strength. When looking further into different types of servomechanisms, and
using the construction and working principle as the criteria of division, we can specify three
main groups of servomotors used in modern servo systems:
-

The AC servo motors, which are based on induction motor designs;

The DC servo motors, second group which is based on DC motor designs;

The AC/DC brushless servo motors, the last group which is based on synchronous
motor designs.

Figure 4 Different types and subtypes of servomechanisms


The AC servo motors are basically a two-phase, reversible, induction motors, which are
modified for different servo operations. Those types of motors are used in applications
11

which requires rapid and accurate response characteristics. In order to obtain such
characteristics, these devices have small diameter, high resistance rotors. The small
diameter property of AC servos, provides a low inertia for fast starts, stops, and reversals
motions. The high resistance property, provides nearly linear speed-torque characteristics
which is very useful in accurate servo motor control.
The induction motor types, which are designed for servo use, are wound with two phases
physically at right angles or in space quadrature. In case of this motor types, a fixed or
reference winding is being excited by a fixed voltage source, while on the other side the
control winding is excited by an adjustable or variable control voltage (which comes usually
from a servo amplifier). This type servomotor windings are usually designed with the same
voltage/turns ratio. This keeps at balance both the maximum control phase signals, and the
power inputs at maximum fixed phase excitation. The important issue is that the inherent
damping of servo motors decreases, while the ratings increase. The servo motors are
designed to have a reasonable efficiency at the sacrifice of speed-torque linearity.
DC servo motors are mostly a very high performance devices. They are designed to meet
demanding requirements of industrial motion control. Those servomechanisms can be
supplied with many electrical and mechanical options in order to fit various needs and
applications. Some of the options which are available can be: tachometers, encoders,
brakes, shafts, windings, mountings, speeds or connectors. Dc servomotor characteristics
include inertia, physical shape, costs, shaft resonance, shaft configuration, speed, and
weight. Although these type of motors have similar torque ratings, their physical and
electrical constants differ.
The DC servomotors are normally used as prime movers in computers, numerically
controlled machinery, or in any other applications where there is need of quick and accurate
start and stop motions. DC servo motors are designed to have lightweight, low-inertia
armatures which can respond quickly to excitation-voltage changes. Other important
property of these motors is, a very low armature inductance, which results in a low electrical
time constant (the typical ranges are from 0.05 to 1.5 ms). This values of time constant
improves servomotor response to command signals. Servomotor devices also includes a
permanent-magnetic, printed-circuit, and moving-coil (or shell) DC servo motors. The rotor
of a shell DC servo motor is combined of a cylindrical shell of copper or aluminum wire coils.
This coils are rotating in a magnetic field in the annular space, between a magnetic pole
pieces and a stationary iron core. This types of servomotors features a field, which is
provided by cast of Al-Ni-Co (aluminum, nickel, cobalt) magnets (where magnetic axis is
radial). The DC servos usually have two, four, or six poles.
The brushless servomotors as the name implies, are servomotors designed to operate
without brushes. More thoroughly, it means that the commutation which normally is
provided by the brushes, now must be provided electronically. The electronic type of
commutation is provided by switching transistors on and off at appropriate times. Figure 5
12

shows three sets of transistors that are similar to the transistors in the output stage of the
variable-frequency drive (the transistors are connected to the three windings of the motor).

Figure 5 Conceptual schematics of transistors connected to the motor


The below figures shows three examples of the voltage and current waveforms which are
sent to the brushless servomotor in order to power it. The main attribute of the brushless
servomotor is that it can be powered by either AC voltage or DC voltage.

Figure 6 Trapezoidal EMF and square-wave current

Figure 7 Sinusoidal EMF and square-wave current

13

Figure 8 Sinusoidal EMF and sinusoidal current

First presented figure shows a trapezoidal EMF (voltage, Electro-Magnetic field) input and a
square wave current input (figure 6). Second one presents a sinusoidal waveform for the
input voltage and a square wave current waveform (figure 7). Last one shows a sinusoidal
input waveform and a sinusoidal current waveform, this type of input and sinusoidal current
waveform are the most popular voltage supplies for the brushless servomotor (figure 8).
The next, one of the most usable, type of motor used in nowadays servo systems is the
PM motor type (permanent magnet). In this case of device , we can use AC voltage or the
DC voltage type for the field winding of the permanent magnet.

Figure 9 Construction elements of PM servomotor


The permanent magnet servomotor is similar to the other PM type of motors. The figure
above shows a cutaway diagram of this type of machine. As we can see the housing, rotor
and stator are very similar to their correspondents in other permanent magnet motors. On
the other hand, major difference with this type of device is that it may have a gear
reduction, which is enabling it to move larger loads more quickly from a stand still position.
14

This permanent magnet motor is equipped also with an encoder or resolver (built directly
into the motor housing). Such solution ensures that the motor will be indicating the position
or velocity of the motor shaft, more accurately.
It would be worth to mention also a special type of stainless steel servo motors. This motor
types are also directed for the motion control industry. The AC brushless servo motors are
designed for motion control applications which requires wash down and very high hygiene.
It finds applications in industrial markets such as: food processing, pharmaceutics, liquid
processing and many others. This motor types may be used in very harsh, corrosive
environments They may be applied in harsh, corrosive environments. They are designed as
waterproof and can withstand up to 1500 psi (pounds per square inch) wash down
conditions.
Slightly different branch of servomechanisms are RC servos. This are hobbyist remote
control devices, which are typically employed in radio-controlled models, where they are
used to provide actuation for various mechanical systems such as the steering of a car, the
flaps on a plane, or the rudder of a boat. Of course they are also very useful in many kinds of
small robotics experiments (because of small size and low purchase costs). This servomotors
have built in motor, gearbox, position feedback mechanism and controlling electronics. They
servo can be easily controlled to move into any positions, just by using simply pulse
controlling.

2.5.

Few history facts about servomechanisms

The word "servo" comes from the Latin statement "servus". This can be translated to English
as: servant, slave or helper. More recent origin of the word is believed to come from the
French statement Le Servomoteur which means a "slavemotor". First person to use this
statement was believed to be J. J. L. Farcot. In 1868 year he used it to describe hydraulic and
steam engines for use in ship steering.
In the machine devices industry, the servo drives were generally an auxiliary drives.
Nonetheless, this situation has changed over the years, and nowadays the main drives are
also implemented using the servo technology. So we can say that the terms "servo drive"
and "dynamic drive", now means one and the same thing. This statements are always
referring to the AC permanent-field synchronous motors, along with their associated control
systems.

15

Figure 10 James Watt (1736-1819)


Looking back into time, we find that James Watts steam engine governor, has been
generally considered as the first powered feedback system in the world. The windmill fantail
could be an earlier, less mechanized, example of automatic control. But the lack of any
amplifier or gain in its architecture, it is usually not considered as a servomechanism. On the
other hand, the first feedback position control device was the steering device of a ship. This
device was used to position the rudder of large ships based on the position of ships wheel.
This type of technology was used for the first time on the ship "SS Great Eastern" in year
1866. The steam steering engines, generally found on the ships of that times, had the
characteristics of a modern servomechanism. This included an input part, an output, an error
signal, and part used for amplifying the error signal, so the negative feedback would drive
the error towards zero.

Figure 11 Windmill structure with a fantail

16

Figure 12 UNIVAC computer from the year 1951


Invented and built later, electrical servomechanisms required a power amplifier. In times of
World War I, there were seen the development of electrical fire-control servomechanisms,
which used an amplidyne (usually an AC motor driving a DC generator) as the power
amplifier. Vacuum tube amplifiers were used in the UNISERVO tape drive (primary I/O
device) for the UNIVAC I (UNIVersal Automatic Computer I) computer.
In the modern years, the servomechanisms are using a solid state power amplifiers, usually
built from MOSFET or thyristor devices. On the other hand, the small servos may use power
transistors.
When looking more into history, for many years the only one type of control for large
currents, was through SCRs (The Silicon-Controlled Rectifier - this are true rectifiers: they
only allow current through them in one direction). Because of this, the early servomotors
were generally a DC motors. Later in the future, the transistors became capable of
controlling larger currents and also switching those large currents at higher frequencies.
That was the when the AC servomotor became used more often. It's worth to mention that
early servomotors were specifically designed for servo amplifiers. Nowadays we can use a
class of motors which is designed for applications that may use a servo amplifier, and also a
variable-frequency controller. Because of this fact, we can use a motor in a servo system in
one application, and also in a variable-frequency drive in another application.
When designing a device as a servomotor, we must made some changes from any motor
which must include the ability to operate at a various speed-ranges without overheating,
especially to work at very low speeds for long periods of time without overheating. Second
important change is the ability to operate at zero speed and also the skill of retaining
sufficient torque to hold a load in position. The older types of servomotors had a cooling
fans, included in their construction that were connected directly to the motor shaft. But
because of this, when the motor were running at low speeds, the cooling fan didn't move
enough air to cool the mechanism. In later years, newer models of servos have a separate
17

fan mounted on them, so that have provided optimum cooling air for the motor. This cooling
devices are usually powered by a constant voltage sources, so they are able to turn at
maximum RPM (revolutions per minute) - this is performed at all times regardless of the
speed of the servomotor.
Interesting fact in case of servomotors is that, some companies also calls any closed-loop
system as a servo system, even if it does not use a stepper motor. Coming from this fact, we
are able to call simple AC induction motor (connected to a velocity controller) as a
servomotor.

2.6.

The areas of servomotors usage

Servomotors are used in many different applications, a few of them are presented below:

a) Automotive market:
-

Power mirror positioning (fig. a)

Power seats positioning motors

Power
door
mechanisms

Windshield wiper motors

and

trunk

lock

Fig. a Car mirror moved by using a


servo

Fig. b Switch used to position car headlights

18

Power sliding door, sunroof,


and convertible top actuators

Headlight
positioning
leveling actuators (fig. b)

and

b) Industrial markets:
-

proportioning valves for gasses and


liquids

paper
and
materials
equipment (fig. c)

sheet metal processing (fig. d)

HVAC ventilation control

satellite-tracking antennas (fig. e)

handling

Fig. c Paper production assembly lines


automatic navigation systems on boatsin factory
and planes
-

antiaircraft-gun control systems

robotics (fig. g, k)

military fire-control and marine


navigation equipment

hard disk drives (fig. f)

assembly equipment (fig. g, h)

Fig. d A punching machine used in metal


processing industry. Includes a servomotor
turret punching press in its elements
Fig. e Moving mechanism of a satellite
TV set. Servomotor is the main part
which is enabling the physical
movement of the satellite dish. The
small motor is mounted to the
feedhorn, the part which is pointing at
the face of the dish. The servomotor
used in this type of device has an
integrated circuit in it, along with
many other static electricity sensitive
components (what makes the device
exposed to damage done by lightning)

19

Fig. f Hard Disk Drive. The servo system


included in this device must be able to
perform a track following (which means
achieving a precise positioning of the
read/write head on a desired track) and track
seeking (a fast transition from one track to
another target track)

Fig. g Robotic assembly apparatus.


This device includes an integrated
vision system, which can give assembly
robots more capability for jobs that are
difficult to automate

Fig. h Servo Assembly Press. Device which


includes an array of servo assembly presses
which are developed in order to meet the
specific requirements in various industrial
applications. An notching-type presses
includes also the hydraulic and PLC based
technologies

Fig. i X-Y Table. This devices are motorized


linear slides with linear motion based in
bearings which are driven by a drive
mechanism (i.e. servomotors)
20

laboratory equipment

coil winders

X-Y tables (fig. j)

factory automation

insertion machines

ick and place (fig. k)

converting equipment

Fig. j "Pick and place" robot type. This


devices are usually called SPP (Servo
Pick and Place), and can be provided
by any combination of servo horizontal
and servo vertical units.

c) Household
market:

and

consumer

pharmaceutics (fig. l)

packaging systems

food handling/processing

bakery machinery

beverage equipment

meat/dairy processing

entertainment equipment
(powered,
remotely
controlled volume controls)
(fig. e)

measuring & dispensing

autofocus cameras

labeling equipment

woodworking

RC (radio controlled) toys

Fig. k Tablet machine, common apparatus


used in pharmaceutical industries

Fig. l Radio controlled toy helicopter

d) Heating,
Ventilation,
and
Air
Conditioning (HVAC) vent controls
21

2.7.

The pros and cons of using servomechanisms.

To shortly sum up the knowledge of servomechanisms, we can say that many applications
place high demands on modern drive technology, which is mostly based on:
-

Positioning accuracy

Speed accuracy

Torque stability

Overload capability

Dynamic performance

The nowadays servo drives are drive systems that show a dynamic and accurate response
over a wide speed range. They are also capable of coping with various overload situations.

In general, the main advantages of using servomotors in our applications includes:


-

Excellent dynamic performance

Excellent speed holding

Wide speed range

High positioning accuracy

Static torque (speed is zero)

High overload capability

Wearless commutation

Lower moment of inertia through the use of unwound rotors

Simpler cooling, as power loss occurs in the stator rather than the rotor

Greater efficiency, as there is no loss caused by the excitation winding

On the other side, there are only few significant disadvantages:


-

Relatively high system cost

Sensor expenditure

22

Some servomotor types are thermally inefficient, because the heat must
dissipate through the external magnets

The brushed motor types requires maintenance, as the brushes will wear off with
time and needs replacement

Increased control complexity could also be viewed as an disadvantage

2.8.

How to select a servo to fit Your application

When we stand before a problem of choosing proper servo motor type which would bring
the most benefit to our application, the first selection approach is to choose a servo motor
large enough for the machine that has already been in the designing phase. The second step
would be to select the best available servomotor with a specific feature and then build the
system around it. Later step would be studying the servo performance and our system
requirements - and then meet the two requirements. The final servomotor system design
would finally meet our performance specifications reliably.
Selecting different servomotor requirements may include such parameters as: control of
acceleration, speed, and position to very close tolerances. This means that when we are
designing a servo, we must define the whole system carefully, establish the servo motor's
performance specifications, determine critical areas, and set up tolerances. This would be
the only moment when we will be able to propose an adequate servo system and choose a
servo motor type for it. Selecting the motor for initial installation or for a replacement, we
must consider parameters like: rated power, rated speed, rotor inertia and for maintenance
purposes even the motor weight and size. Another approach to select a suitable servo to fit
our needs would start with the consideration if whether the motor will be used for
continuous duty or intermittent duty (we need to select device that can produce proper
amount of continuous stall torque). The second rating which should be thoroughly
considered is the amount of peak torque. Finally the maximum continuous AC input power
and the rotor inertia would be the later properties which we should take under
consideration.

23

3. Stepper motor control methods


3.1.

Stepper motors overview

One of the types of Servomotors is the brushless type - the stepper motor (also called step
motor). This device is synchronous electric motor that can divide a full rotation into a large
number of steps (so the name implies). Stepper motors are constant power devices, as the
motor speed increases, on the other side, the torque decreases.
Describing more thoroughly, we can say, that stepper motor is an electromechanical device
which converts electrical pulses into discrete mechanical movements. The shaft (or spindle)
of the motor rotates in discrete step increments when electrical command pulses are
applied to it in the proper sequence (sent from the user of the device using an appropriate
control gear). The motors rotation has several direct relationships to these applied input
pulses. The sequence of the applied pulses is directly related to the direction of motor shafts
rotation, the control methods would be described further, later in this chapter. The speed of
the motor shafts rotation is directly related to the frequency of the input pulses and the
length of rotation is directly related to the number of input pulses applied. In industry we
can differ three basic stepper motor types, those are:
Variable-reluctance (VR motors)
Permanent-magnet (PM motors)
Hybrid step motors

Figure 13 Cross section of the Hybrid motor.


The variable reluctance motors type, have a plain iron rotor and they operation is based on
the principle that minimum reluctance occurs with minimum gap, hence the rotor points are
attracted toward the stator magnet poles.
24

The permanent magnet motors use a permanent magnet in the rotor. They are operating on
the attraction or repulsion between the rotor magnet and the stator electromagnets.
The last type, which are hybrid stepper motors, as the name implies, they are using
combination of the Permanent-magnet and Variable-reluctance techniques in order to
achieve maximum power, while the sizes of the devices itself are slightly smaller than the
other types.

3.2.

Stepper motor control

Main advantage in the Stepper motor usage is, that the motor's position can be controlled
very precisely. This is obtained without any feedback mechanism, as long as the motor is
carefully sized to fit the application it would be working with. One of the most significant
advantages of a stepper motor is its ability to be accurately controlled in an open loop
system (this means that no feedback information about position is needed). This type of
control eliminates the need for expensive sensing and feedback devices such as optical
encoders. The actual position of motor is known simply by keeping track of the input step
pulses.
When describing the traditional motor types, it comes to a series of coils which are
automatically switched on and off by a set of brushes in contact with the commutator. Once
power is applied, the motor runs itself at a speed proportional to the voltage and the load.
Main difference here would be, that the stepper motor has no commutator. Instead, there
are five or six wires coming out of the motor - one wire for each coil (there are usually four
coils) and one or two common ground wires. Because of this, we must apply power from one
coil to another in the proper sequence when we want the motor to be turned on. In order to
obtain the maximum torque, two coils are always on at any time.

Figure 14 Cross section of the Variable Reluctance motor.

25

Picture presented above, shows that stepper motors have multiple "toothed"
electromagnets arranged around a central gear-shaped piece of iron. The electromagnets
are energized by an external control circuit, such as a microcontroller. In order to turn the
motor shaft, first of the electromagnet is given power. When it's powered up, it makes the
gear's teeth magnetically attracted to the electromagnet's teeth. When the gear's teeth are
aligned to the position of first electromagnet, they are slightly offset from the next
electromagnet. Next step then would be powering the next electromagnet and turning the
first one off. At this time the gear rotates slightly to align with the next one, and from there
the process is once more repeated. We call each one of these slight rotations simply, as
"steps" (and where an integer number of steps would be meaning the motor's full rotation).
Control of the motor in that way, means that it can be turned by a very precise angle.

3.3.

Unipolar and Bipolar stepper motors

When it comes to the VR motor types, they usually have three windings. When we want to
put the motor in motion, it is needed to power each of the windings in the correct order. In
order to change the direction of the motor rotation, we need to change the windings
powering up order. When windings are powered in the sequence: A, B, C, A, B, C, A, ... It
means the rotation in one direction. And powering sequence of: A, C, B, A, C, B,... means on
the other hand, the rotation in opposite direction. Change of the sequence could be
obtained, for example by changing the positions of two ends of the winding. Despite the
differences in the work principles, the PM and Hybrid motors, could be also controlled in the
way described above.

Figure 15 The Bipolar motor with two windings.


Although in reality, the PM and HB motors have several poles, they contain only two
windings which are divided into sections. In this chapter we are presenting only a simplified
model with two windings, but it is sufficient for further analysis and descriptions. As we
know, the engines have to produce a rotating magnetic field. This can be obtained by
changing the direction of current in the windings. Next figure shows a method of control,
when two transistor bridges are used . This is often called as "H bridge" (also a full-bridge),
because of its similarity to the letter H.

26

Figure 16 Bipolar motor - the "H" transistor bridge.


In the transistor bridges, are also used different transistor types (MOSFET N, MOSFET Q,
NPN, PNP, "Darlington pairs"), but usually they are either bipolar transistors NPN, or
MOSFET N transistors. Although this method of control allows users to operate the motors
using their full capabilities, the realization is not the easiest one. Because each of the eight
transistors has to be operated separately. In order to simplify the controller, a winding with
a branch in the middle can be used instead. In this simplified controller, currents are flowing
in the same direction, which is why engines with split windings are called Unipolar motors.

Figure 17 The Unipolar motor with two split windings.

Figure 18 Unipolar motor transistor bridge.


The motor currents (in successive cycle phases), as shown in the next figure, are flowing in
both directions, so these devices are called Bipolar motors.
27

Figure 19 Bipolar motor control - Wave Drive.

Figure 20 Unipolar motor control - Wave Drive.


Above figure presents the way in which the magnetic field changes are obtained for both
types of motors. The undoubted advantage of unipolar type is the ease of motor control - it
only requires four MOSFETs along with simple sequence generator. The bipolar type of
motor requires a more complex controller. However, it has also an important advantage. In
unipolar motor, as shown in earlier figures, half of the windings are working alternately, so
the rest of them is always not used, which reduces the peak performance of the machine. In
the bipolar motor full winding is working and the full potential of the motor can be
exploited. Bipolar control gives better results, especially for small and medium working
speeds, the torque is then increased by around the 30-40%.

3.4.

Stepping modes

The figures presented in following chapter are related with simple Permanent Magnet motor
with one pair of rotor poles. Although the Hybrid motor works in different way, and a typical
PM motor has more poles, presented rules applies to all motor types, PM and HB.
The following are the most common drive modes, which we will describe:
Wave Drive (1 phase on)
Full Step Drive (2 phases on)
Half Step Drive (1 & 2 phases on)
Microstepping (Continuously varying motor currents)
We have stated earlier, that unipolar motor shows weaker performance in comparison to
the second type, because one winding of each pair is always unused. The problem of control
28

is also related to this fact. Figure 21 shows that in every step of the cycle, only one of the
two motor windings is powered in the bipolar motor type. The second one is always unused.
Even worse situation presents the unipolar motor, where, as shown in the same picture, only
25% of all windings are used (of course, it means that the engine is not fully exploited). This
mode of control is called the Wave Drive (and it is also so-called Full Step drive). Contrary to
the first impressions, there is a very good way to use all of the bipolar motor windings. Next
figure shows this very clearly, when comparing it to the previous figure.

Figure 21 Bipolar motor control - Full Step Drive.


This time, at every stage of the cycle, both of the windings are powered up. Also there is
nothing wrong in this process, as the rotor poles are not lining up opposite to the poles of
the stator, but only halfway between them.
In the unipolar motor, we can power up two of the four coils, which improves engine power
and torque also.

Figure 22 Unipolar motor control - Full Step Drive.


Each of the two presented above control methods, for both bipolar and unipolar motors, are
used in practice. We are calling it Full Step Drive method, but to distinguish it from the first
described method (which is also a Full Step control method) we call that method a Wave
Drive.
The more often used method of control in contrary to the previous ones, is the Half Step
Drive. This control type is a combination of the two methods previously discussed. Driving

29

sequence and location of the bipolar and unipolar motors are shown on the following
pictures.

Figure 23 Bipolar motor control - Half Step Drive.

Figure 24 Unipolar motor control - Half Step Drive.


When we alternately power up one and then two windings, the rotor poles are setting at
either in front of the stator, or in the middle between them. Even tough, the motor
performance is somewhat worse than in the Full Step Drive (because both windings are not
constantly powered), the Half Step Drive has also significant advantages. Typical waveforms
30

of the unipolar motor control, for the Full Step and Half Step Drives are shown in the
following figure.

Figure 25 Unipolar motor control waveforms - Full Step (right) Half Step (left) Drive.
When we want to change the direction of rotation, most of the time it can be done by
changing the driving sequences. In simple applications, it can be easily done by replacing the
tip of A +, A- of the one windings pair.

31

4. Design of our controller to work with servomechanisms

Figure 26 Bi-Polar Stepper Motor used with our controller.

4.1.

Aims of our design

The general idea of our work is to create program in C# language in order to steer the
servomotor in MS Windows based computer systems. But the second and also very
important part of our work, was designing and creation of a controller which would be
connected directly to the PC class computer via the LPT port. The servomotor itself would be
connected to the controller inputs. Our main goal was to prepare such device, which would
give the user ability to steer motors of different power values. The potentiometer included
in controllers architecture, would allow changing the voltage of motor winding from 5 Volts
up to 12 Volts (so the higher power motors could also be controlled). In this chapter we
present the schematics of our controller. Also we describe each part used in its design and
the goals and parameters of these parts. During the work on building the control gear, it was
tested on different PC sets and with the use of 5 Volt, Bi-Polar Stepper Motor.

4.2.

Controller schematics

In order to start working on real parts, we needed to draw appropriate schematics for our
controller. To make the job much easier, we have used the "EAGLE" software from the
CadSoft Computer company.
32

The "EAGLE" program is a layout editor, easy to use tool for designing printed circuit boards
(PCBs). This program consists of three main modules: Layout Editor, Schematic Editor and
Autorouter. In our work we have worked mostly with the Schematic Editor part of the
program. This have allowed us to create a board from previously prepared schematics.
Following are presented the final versions of the schematics on which we based the
construction of our control gear. The schematics are divided into two parts, mainly because
of the space it required. The first "power" section, consists of executive power elements (i.e.
control module, Schottky diodes and controlled power supply).

Figure 27 The "power" part of schematics. (Circuit scheme of "power board" driver)

33

Figure 28 The "logic" part of schematics. (Circuit scheme of "logic board" driver)

4.3.

Description of parts and their tasks - External overview

To have better visualization of the whole controlling device and the parts which were
included in its design, we are presenting detailed pictures of our finished and completely
functioning control gear.

Figure 29 External view of the controller: Front.

34

Figure 30 External view of the controller: Rear.


Description of the elements seen on the pictures:
1. Electrical network switch with diode. This is simple switch, used to turn on/off our
controller from the electrical network. This part contains a diode inside (diode elements are
described more thoroughly later on). Diode element is lit when the controller is turned on
(the switch is pressed down, on the "I" position).
2. The output pins of L298 controller. The exact pin numbers are (from the left): 2; 3; 13;
and 14. This outputs were connected with the shell of the controller. Because of this, the
connection of any Bi-Polar Stepper Motor is easy and there is no need to interfere with the
interior parts of our device. The L298 part is described in following chapters.

3. The potentiometer knob. The potentiometer device is described in the next chapter. On
the picture, presented is only an ordinary, plastic knob connected with the potentiometer, in
order for the user to regulate the voltage which is supplying the stepper motor coil. The
range of the voltage is between 5V to 12V.

35

4. LED diodes (Light Emitting Diodes). This LED's are used as status diodes, on schematics
they are marked exactly as (from the left): LED1 through LED8. Each diode represents each
of the transistors. When diode is lit, the appropriate transistor is in conducting. This parts
are simple semiconductor light sources. The LEDs are emitting light, when an electric current
passes through them. When a diode is forward biased (switched on), electrons are able to
recombine with holes within the device, releasing energy in the form of photons. This effect
is called electroluminescence and the color of the light (corresponding to the energy of the
photon) is determined by the energy gap of the semiconductor. The LEDs are usually small
sized (less than 1 mm2), and integrated optical components are used to shape its radiation
pattern and assist in reflection.

When connecting the LEDs to a PCBs, we had to connect it the correctly, the diagram may be
labeled "a" or "+" for anode and "k" or "-" for cathode. The cathode is the short lead and
there may be a slight flat on the body of round LEDs. It should also be remembered that
LEDs can be damaged by heat when soldering, but the risk is small unless you are doing it
very slowly. No special precautions are needed for soldering most LEDs. The color of an LED
is determined by the semiconductor material used to build it. All the LEDs connected in
series pass the same current so it is best if they are all the same type.In our control gear, the
diodes are connected in two ways. In one way, they are used when connected directly to the
buffer. Second case is when they are connected to the logic gate outputs (through the
resistor 2.2 which reduces the current).

Figure 31 Symbol and example view.


5. The DIN8 socket. This socket is used to plug in the LPT cable. The steering signals from the
computer LPT port are sent via cable connected to this socket. This part is the "male" 8 pin
type of DIN connector. This socket is a connector that was originally standardized by the
German national standards organization (as the name implies, DIN stands for: Deutsches
Institut fr Normung). Generally there are DIN standards for a very large number of different
type of connectors. In the trade of consumer electronics, when using the term "DIN
connector", it is referring to a member of a family of circular connectors used for analog
audio signals (which were initially standardized by DIN).
36

The plugs (the "male" type of connectors) consist of a circular shielding metal skirt
protecting a number of straight round pins. There are seven common patterns, with any
number of pins from three to eight. The construction of plugs of the DIN family of
connectors feature a 13.2 mm diameter metal shield (along with a notch that limits the
orientation in which plug and socket can mate). Connectors of the same form which are
different from each other only in their pin configuration, exist and have been standardized
originally in DIN 41524 (3- and 5-pin), DIN 45322 (6-pin at 60), DIN 45326 (8-pin), DIN 45329
(7-pin), and other standards for a range of different applications. These connectors have
been used in analog video applications and for digital interfaces such as MIDI or the IBM
PS/2 computer keyboard and mouse cables (but nowadays replaced with the USB
connection types).

Figure 32 The DIN8 diagram.


6. Electrical Fuse 0.5A. This is simple fuse, used for security reasons (to avoid high
overcurrents, in our case we used the 0.5 amperes type of fuse). The main threats for our
device can be: short circuits, overload or device failure (which are the often reasons for
excessive currents). Fuses are a type of sacrificial overcurrent protection devices. The main
component, is a metal wire or strip, which melts when the flowing current value surpasses
the rated current - IN (a maximum current that the fuse can continuously conduct without
interrupting the circuit). When the wire melts, the circuit in which the fuse was connected is
interrupted. A fuse interrupts excessive current, in order to prevent the further damage
which can be caused by overheating or even fire.
7. Power cord (also: line cord, mains cable). This is a simple, commonly used cord/cable
that temporarily connects our control gear to the distribution circuits of an electrical power
source (simply by connecting the plug to a wall socket with standard 230V from the local line
voltage).

4.4.

Description of parts and their tasks - Interior

The internal view of the control gear could also be seen on the pictures presented later in
this chapter. The electrical power is supplied from external network via power cord, directly
to the switch with LED diode, and then to the toroidal transformer (the parts were described
in the earlier chapter).
37

Figure 33 Examples of toroidal transformers.


The transformer used in our device is TST 50/003 model. The voltage of typical Polish power
networks are 230 Volts and 50 Hertz frequency, the transformer is capable in changing
electric power to AC 12 Volts/50 Hertz. Later the transformer distributes power to each of
the power elements (as included on the schematics).

Figure 34 The interior view of our control gear.

38

Most of the elements have been soldered on one of the two separate circuit boards (as can
be seen on the above pictures). The following is description of each part and the goals they
fulfills in our control device. Parts are marked with appropriate characters, as can also be
seen on the earlier presented pictures. The descriptions:
A. Toroidal transformer. Toroidal transformers are built around a ring-shaped core, which
helps eliminating air gasps. The primary and secondary coils are often wound concentrically
to cover the entire surface of the core. This minimizes the length of wire needed, and also
provides screening to minimize the core's magnetic field from generating electromagnetic
interference.

Main advantages of this transformers are that, it's more efficient than the cheaper
laminated E-I types for a similar power level. More advantages over the E-I types are:
smaller size and lower weight of toroidal transformers (about half of the E-l type), they also
generates less mechanical hum, have lower exterior magnetic field (about one tenth), low
off-load losses (making them more efficient in standby circuits), single-bolt mounting, and
they are available in greater choice of shapes. The model of transformer used in our device is
TST 50/003.
Its particular properties are following:
Power: 50W
Voltage: 12V
Current: 4.1A
Dimensions: 85 x 35 (diameter x height)
B. PCB - Printed Circuit Board. We are using them of course, to mechanically support and
electrically connect electronic components. These boards are using conductive pathways,
tracks or signal traces etched from copper sheets laminated onto a non-conductive
substrate. Main advantage of the PCBs is their inexpensiveness, and that they can be very
highly reliable. On the other hand, this boards requires much more layout effort, and the
initial costs can be higher, compared to either the wire-wrapped or point-to-point
constructed circuits. But they are much cheaper and faster for high-volume production, and
in our work this type was the most convenient to obtain and use.

C. Potentiometer (Cannot be seen on the picture, it's hidden under the steel plate).
Generally this part is a three-terminal resistor with a sliding contact that forms an adjustable
voltage divider. This is a passive element of a circuit and in our case it is used as a control
input for the electronic circuit. This device is constructed with a resistive element formed
into an arc of a circle, and a sliding contact (wiper) travelling over that arc. The resistive
39

element of this part is made using a terminal at one or both ends, it can be flat or angled.
Commonly it is made of graphite, but many other materials may be used instead. The wiper
part is connected through another sliding contact, directly to another terminal.
Because the motor which we have used to test our control gear, was to work with 5 V
voltage, the potentiometer have given us the ability to change the voltage on the motor
windings between the values of 5V to 12V.

D. Heat sink. This is very common component which transfers heat generated within a solid
material to a fluid medium, such as air. It is used to cool down our controller (especially the
Dual Full-bridge driver). A heat sink uses its extended surfaces to increase the surface area in
contact with the cooling fluid (air). Generally this object transfers thermal energy from a
higher temperature to a lower temperature fluid medium. The most common heat sink
material is aluminium.

Parts soldered on the heat sink (in order to transfer the heat masses from the parts and
avoid overheating):
E. L298, Dual Full-bridge driver.
In our control gear we are using the Multiwatt15 model labeled - L298N, which is an
integrated monolithic circuit in a 15-lead Multiwatt packages. This driver is a high
voltage/high current dual full-bridge driver. It is designed to accept standard TTL logic levels
and drive inductive loads such a stepping motor - which is the object of our control work, or
other devices like relays, solenoids. This part contains two "enable" inputs, used for enabling
and disabling the device independently of the input signals. The emitters the lower
transistors of each bridge, that are also embedded in the driver, are connected together and
they can be used by the corresponding external terminal for the connection of an external
sensing resistor. Also this drive contains an additional supply input, which helps the logic to
work at a lower voltage values.
Other properties for the L298, are following (presented are maximum possible values):
Operating Supply Voltage: 46V
Total DC Current: 4A
Low saturation voltage.
Overtemperature protection.
Logical "0" Input Voltage, up to 1.5V (High noise Immunity)

40

Figure 35 The block diagram of Dual Full-Bridge Driver.


F. The voltage stabilizer is an electronic device able to deliver relatively constant output
voltage while input voltage and load current changes over time. This device is a subtype of
voltage regulators. Many voltage stabilizers regulate the voltage using a shunt regulator such
as a Zener diode (described thoroughly in following chapters), avalanche breakdown diode,
or voltage regulator tube. Each of these devices begins conducting at a specified voltage and
will conduct as much current as required to hold its terminal voltage to that specified
voltage. The power supply of this parts is designed to only supply a maximum amount of
current that is within the safe operating capability of the shunt regulating device. The
LM78T05 - the 3 A version, this is a voltage stabilizer used in our circuit. It main advantage is
that when it is starting to overheat it would automatically reduce the current flow. The
output voltage given in our case is stabilized 5 V. We have used this element over the
LM7805 - 1 A part, which must have been used along with an external power transistor.

G. TIP142 transistor. This part is the Darlington power transistor, it is designed for general
purpose amplifier and low frequency switching applications. This part has monolithic
construction with BuiltIn BaseEmitter shunt resistor.

41

Particular properties are following:


Power: 125W
Voltage: 60-100V
Current: 10A

Figure 36 Darlington Complementary Silicon Power Transistor - dimensions schematic.

Darlington transistor (also called Darlington pair). This part is a compound structure
consisting of two bipolar transistors. They can be either integrated or separate devices,
which are connected in such a way that the current amplified by the first transistor, would
be then amplified further by the second one. Using of this kind of configuration gives us a
much higher current gain, than the value which we could have obtained by using each
transistor taken separately. Also in the case of integrated devices, they are taking less space
than two individual transistors because they can use a shared collector. In our case the NPN
transistors are used as the pair.
When we consider a typical modern device, it has a current gain of 1000 or even more. In
that case only a small base current would be needed to make the pair switch on. But this
advantage of high current gain, comes with several drawbacks. One of the drawbacks is the
approximate doubling of base-emitter voltage. Since there are two junctions between the
base and emitter of the Darlington transistor, the equivalent base-emitter voltage would be
the sum of both base-emitter voltages. Second important disadvantage of the Darlington
pair is its increased saturation voltage. The output transistor is not allowed to saturate (for
example, when its base-collector junction must remain reverse-biased) because its collectoremitter voltage is now equal to the sum of its own base-emitter voltage and the collectoremitter voltage of the first transistor, both positive quantities in normal operation. When
the used collector currents are equal in values, this drawback would mean an increase in the
dissipated power for the Darlington transistor over a single transistor. Also a drawback is fact
that the Darlington pair has more phase shift at high frequencies than a single transistor and
hence can more easily become unstable with negative feedback.
42

Parts included on the first PBC:

Figure 37 The interior view of the controller: Logic elements.


1. Schottky Diode (sometimes referred to as the surface barrier diode or hot carrier diode).
The Schottky diodes, called also a "Schottky Barrier diodes" (this diodes uses a metal
semiconductor junction as a "Schottky Barrier"), are an electronics components with wide
usage in radio frequency (RF) applications (as a mixer or detector diodes), but also they are
used in power applications as a rectifier. Usefulness as a rectifier is obtained because of its
low forward voltage drop, which leads to lower levels of power loss compared to ordinary
PN junction diodes. This parts are one of the oldest semiconductor devices in existence (as a
metal-semiconductor devices, its applications can be traced back to before 1900), but
nowadays they are still used in various of applications of high tech electronics. This type of
diode is characteristic because of its very low forward-voltage drop (Schottky diode voltage
drop is between approximately 0.150.45 volts in comparison to other diodes 0.61.7 volt
voltage drop). Because of this fact, Schottky Diode provides higher switching speed and
better system efficiency. We are using this type of diode in our controller in order to avoid
overvoltages and power surges in times of stepper motor switching (The Dual full-bridge
driver lacks this kind of protection).

Figure 38 Schottky Diode symbol and example view.

43

2. Resistors. One of most commonly used parts in electronic industry. They are used to
restrict the flow of electric current. Energy is used up as the voltage across the component
drives the current through it and this energy appears as heat in the component. Resistor
values are normally shown using colored bands. Resistance is measured in ohms, the symbol
for ohm is an omega: . Most of resistors have four bands, where first two are the number
of digits and the third indicates the number of zeros. Fourth band is used to shows the
tolerance (precision) of the resistor. In our control gear we are using the 2.2/10W type of
resistors. They are used in order to reduce the current on engine windings (coming from the
driver module).

Figure 39 The resistor color code, symbol and example view.


3. L298, Dual Full-bridge driver. (This part was described in earlier chapter)

4. LM723CN, Voltage regulator. This is an electrical regulator designed to, as it name


implies, automatically maintain a constant voltage level. The electronic voltage regulators
are operating by the ability of comparing the actual output voltage to some internal fixed
reference voltage. Any difference of the obtained value is amplified and used to control the
regulation element in such a way as to reduce the voltage error. This process gives us form
of a negative feedback control loop, so when increasing the open-loop gain, it tends to
increase regulation accuracy but on the other hand it reduces stability.

In the circuit of LM723 regulator or LM78T05 voltage stabilizer, the Zener diodes were used.
While using it along with sufficient reverse voltage, we can experience on the p-n junction
(formed by joining p-type and n-type semiconductors together in very close contact) effect
of rapid avalanche breakdown along with conduction of current in the reverse direction.
Valence electrons (electrons in the outermost shell of an atom) which break free, when they
are influenced by the applied electric field, can be accelerated enough that they can knock
loose other electrons. This is causing more subsequent collisions, which quickly become an
avalanche. During this process, very small changes of the voltage are causing very large
44

changes in current. The breakdown process is dependent on the applied electric field. This
means that when we are changing the thickness of the layer to which the voltage is applied,
the zener diodes can be formed, which break down at voltages from about 4 volts to several
hundred volts.
Zener diodes are generally used to maintain a fixed voltage. The zener diode uses a p-n
junction in reverse bias to make use of the zener effect, which is a breakdown phenomenon
which holds the voltage close to a constant value called the zener voltage. This type of
diodes are widely used as voltage reference and as shunt regulators to regulate the voltage
across small circuits. Zener diodes can be distinguished from other ordinary diodes by their
code and breakdown voltage that are printed on their shells. In our circuit we are using (fast)
zener diodes in order to reduce the overvoltages.

Figure 40 Current characteristic for zener Diode, symbol and example view.
5. Graetz Bridge (diode bridge). Simply putting, a diode bridge is an arrangement of four
diodes in a bridge configuration. The essential feature which diode bridge provides, is that
the polarity of the output is the same, regardless of the polarity at the input. The diode
bridge circuit is also known as the Graetz circuit after its inventor, physicist Leo Graetz. The
part used in our controller is RS606 (6A, 600V, RoHS - which stands for: Restriction of
Hazardous Substances).

45

Figure 41 Graetz bridge: voltage characteristics, circuit and part overview.

Main use of this part in our control gear is to rectify the voltage. This bridge is used as fullwave rectifier (which is an electrical device that converts alternating current (AC) to direct
current (DC), in process known as rectification). Full-wave rectifier are converting the whole
of the input waveform, into output waveform which has constant polarity (which could be
either positive or negative). Four diode bridges used as full-wave rectifiers, converts both
polarities of the input waveform to DC (direct current).
6. Electrolytic Capacitor. Generally, capacitors (earlier named: condenser) are a passive
electronic components consisting of a pair of conductors separated by a dielectric
(insulator). The way of work for capacitor is when there is a potential difference (in voltage)
across the conductor pair, the static electric field is developing in the dielectric, which stores
energy and produces a mechanical force between these conductors.
An electrolytic capacitor, which we are using in our control gear, is a type of capacitor that
uses an electrolyte (ionic conducting liquid), as one of its plates. This helps to obtain a larger
capacitance per unit volume in comparison to other types of capacitors. Electrolytic
capacitors are polarized, which means that they must be correctly connected into the circuit.
There are two designs of electrolytic capacitors; axial where the leads are attached to each
end and radial where both leads are at the same end. The values of capacitance and voltage
rating, are always printed on the capacitor shell. In our control gear, the capacitors are used
as filters in order to reduce the pulsation of current. We are using parts of C = 4700F
capacitance values. Capacitance is a single constant value, measured in farads (F). It is
46

characterizing an ideal capacitor and it is the ratio of the electric charge on each conductor
to the potential difference between them.

Figure 42 Capacitor overwiev.

Parts included on the second PBC:

Figure 43 The interior view of the controller: Power elements.

47

1. Three-state logic (also written as: tri-state or 3-state). In the field of digital electronics
this device allows the output ports to assume a high impedance state in addition to the
fundamental states (the 0/1 levels), by effectively "removing" the output from the circuit.
Because of this, multiple circuits are allowed to share the same output line or lines (i.e. bus which is set of parallel wires). For example computer systems often use a bi-directional data
bus to allow convenient connection of memory and other devices to the registers of the
processor data path. Bi-directional means that devices connected to the bus can either take
input from the bus, or put output on the bus. In order for this to happen without outputs
colliding, three-state buffers are used. The bi-directional bus allows us to connect many
separate devices that have three-state outputs to the same set of wires, and then use logic
to select which devices will communicate to each other.

Figure 44 Symbol and truth table.


In case of automatic switches, their states are either on-state (the logical "1" or 5 Volts) or
off-state (logical "0", or 0 Volts). But in order to be either 5 or 0 volts, an output has to be
connected, through the logic gate circuit, to either the 5V or 0V (ground) power supply leads
of the gate. For a logic circuit output to prove it usefulness, it must be able to switch
between those two voltage states and the pass current. That is, if an output is 5V, it needs to
be able to pass some current to drive the inputs of the other gates to which it is connected.
Analogically, when the output is 0V, it needs to be able to "sink" current, in order to operate
the circuits it is tied to. The "cut wire" state is a third state, neither 1 nor 0, that is very
useful in many computer-based designs. This additional state is also called "high
impedance", because of the fact that current will not be able to flow either into or out of an
output that is in this state. The high impedance state can also be viewed as that the circuit is
having a very high resistance attached. We can shorten it to "High Z" (as marked on the
picture above), because Z is a common symbol for impedance (general term for resistance to
current flow).

Generally, the whole concept of the third state ("High Z") is to effectively remove the
device's influence from the rest of the circuit. If more than one device is electrically
48

connected, putting an output into the High-Z state is often used to prevent short circuits, or
one device driving high (logical 1) against another device driving low (logical 0).Three-state
logic can reduce the number of wires needed to drive a set of LEDs, as it was used in our
control gear. We are using the three-state buffer to separate the LPT port from the part
which controls the LED diodes set.

2. DIL20 socket (DIL stands for: Dual In-Line). This is a double-Row 2x10 pins socket. When
considering the ICs (chips), we know that they are easily damaged by heat when soldering
and their short pins cannot be protected with a heat sink. Instead of that, we can use an IC
holder, which is strictly called a DIL socket. This type of socket can be very safely soldered
onto the circuit board. When all soldering is completed, the IC is pushed into the holder. IC
holders are only needed when soldering so they are not used on breadboards.
Part's particular properties are following:
- raster: 2.54mm
- contacts: tinned
- current: 1A/pin
-contact resistance: 30mW max
-size: 7.62 mm x 25.40 mm
3. 7404 TTL (cannot be seen on the picture, hidden under the PCB plate, connected with
DIL20 socket). The NOT gate, it is a logic gate (which performs a logical operation on one or
more logic inputs and produces a single logic output) which implements logical negation. In
other words this part is very common electronic circuit that produces an inverted version of
the input at its output. Other simple name for it is an inverter. The principles of this gate are
that, when the input variable is A, the inverted output is known as NOT A. Usually we can
also mark this as A', or , as shown at the outputs (presented on figure below). The output
Q is true when the input A is NOT true, the output is the inverse of the input: Q = NOT A
The NOT gate can only have one input.

Figure 45 Symbol and truth table.

49

4. Resistor (0.15 ). Second type of resistors used in our work, but with slightly lower value
of resistance. This parts are used to reduce the current in the circuit containing the power
supply. If current overcome the value of 4A, the power supply would be cut off.

50

5. Local area network (LAN), OSI and TCP/IP model


5.1.

Characteristic of Local area network

A local area network (LAN) is a computer network covering a small physical area, like a
home, office, or small group of buildings, such as a school, or an airport. The defining
characteristics of LANs, in contrast to wide-area networks (WANs), include their usually
higher data-transfer rates, smaller geographic area, and lack of a need for leased
telecommunication lines.
Early LAN cabling had always been based on various grades of coaxial cable, but IBM's Token
Ring standard used shielded twisted pair cabling of their own design, and in 1984 StarLAN
showed the potential of simple Cat3 (Category 3) unshielded twisted pairthe same simple
cable used for telephone systems. This led to the development of 10Base-T (and its
successors) and structured cabling which is still the basis of most LANs today.
Nowadays the most popular standard used in Local area networks is for sure Ethernet
standard (described below) with Category 5 twisted pair cabling and Wi-Fi standard. LANs
may have connections with other LANs via leased lines, leased services, or by tunneling
across the Internet using virtual private network technologies (VPN). Depending on how the
connections are established and secured in a LAN, and the distance involved, a LAN may also
be classified as metropolitan area network (MAN) or wide area networks (WAN).

5.2.

Ethernet specification

Ethernet is a family of frame-based computer networking technologies for local area


networks (LANs). The name comes from the physical concept of the ether. It defines a
number of wiring and signaling standards for the Physical Layer of the OSI networking model
as well as a common addressing format and Media Access Control at the Data Link Layer.
Ethernet is standardized as IEEE 802.3. The combination of the twisted pair versions of
Ethernet for connecting end systems to the network, along with the fiber optic versions for
site backbones, is the most widespread wired LAN technology. It has been in use from
around 1980 to the present, largely replacing competing LAN standards such as token ring,
FDDI, and ARCNET.
From this early and comparatively simple concept, Ethernet evolved into the complex
networking technology that today underlies most LANs. The coaxial cable was replaced with
point-to-point links connected by Ethernet hubs and/or switches to reduce installation costs,
increase reliability, and enable point-to-point management and troubleshooting.

51

5.3.

OSI model

The Open System Interconnection Reference Model (OSI Reference Model or OSI Model) is
an abstract description for layered communications and computer network protocol design.
It was developed as part of the Open Systems Interconnection (OSI) initiative. In its most
basic form, it divides network architecture into seven layers which, from top to bottom, are
the Application, Presentation, Session, Transport, Network, Data Link, and Physical Layers. It
is therefore often referred to as the OSI Seven Layer Model.
A layer is a collection of conceptually similar functions that provide services to the layer
above it and receives service from the layer below it. On each layer an instance provides
services to the instances at the layer above and requests service from the layer below. For
example, a layer that provides error-free communications across a network provides the
path needed by applications above it, while it calls the next lower layer to send and receive
packets that make up the contents of the path. Conceptually two instances at one layer are
connected by a horizontal protocol connection on that layer. There are several protocols
dedicated for each layer, for example Internet Protocol (IP) is a protocol designed for
network layer and Transmission Control Protocol (TCP) for transport layer. Below we present
short description of each layer:
a) Layer 1: Physical Layer - The Physical Layer defines the electrical and physical
specifications for devices. In particular, it defines the relationship between a device
and a physical medium. This includes the layout of pins, voltages, cable specifications,
network adapters and more.
b) Layer 2: Data Link Layer - The Data Link Layer provides the functional and procedural
means to transfer data between network devices and to detect and possibly correct
errors that may occur in the Physical Layer. This layer manages the interaction of
devices with a shared medium, which is the function of a Media Access Control
sublayer. Above this MAC sublayer is the media-independent Logical Link Control
(LLC) sublayer, which deals with addressing and multiplexing on multiaccess media.
c) Layer 3: Network Layer - The Network Layer provides the functional of transferring
variable length data sequences from a source to a destination via one or more
networks, while maintaining the quality of service requested by the Transport Layer.
The Network Layer performs network routing functions, and might also perform
fragmentation and reassembly, and report delivery errors. Routers operate at this
layersending data throughout the extended network. The best-known example of a
Layer 3 protocol is the Internet Protocol (IP).
d) Layer 4: Transport Layer - The Transport Layer provides transparent transfer of data
between end users, providing reliable data transfer services to the upper layers. The
Transport Layer controls the reliability of a given link through flow control,
fragmentation/defragmentation, and error control. Typical examples of protocols
52

from layer 4 are the Transmission Control Protocol (TCP) and User Datagram Protocol
(UDP).
e) Layer 5: Session Layer - The Session Layer controls the connections between
computers. It establishes, manages and terminates the connections between the
local and remote application. It provides for example full-duplex, half-duplex and
establishes termination, and restart procedures.
f) Layer 6: Presentation Layer - The Presentation Layer establishes a context between
Application Layer entities, in which the higher-layer entities can use different syntax
and semantics, as long as the presentation service understands both and the
mapping between them. The presentation layer works to transform data into the
form that the application layer can accept. This layer formats and encrypts data to be
sent across a network, providing freedom from compatibility problems.
g) Layer 7: Application Layer - The application layer is the OSI layer closest to the end
user, which means that both the OSI application layer and the user interact directly
with the software application. This layer interacts with software applications that
implement a communicating component. Some examples of application layer
implementations include Hypertext Transfer Protocol (HTTP), File Transfer Protocol
(FTP), Simple Mail Transfer Protocol (SMTP).

Table 1 OSI model

OSI Model
Data unit

Layer

Function

7. Application
Host
layers

Data

Segment

Media
layers

Packet
Frame
Bit

Network process to application


Data representation, encryption and
6. Presentation
decryption
5. Session
Interhost communication
End-to-end
connections
and
4. Transport
reliability, flow control
Path determination and logical
3. Network
addressing
2. Data Link
Physical addressing
1. Physical
Media, signal and binary transmission

53

5.4.

TCP/IP Model

In the TCP/IP model protocols are deliberately not as rigidly designed into strict layers as the
OSI model. Even though the concept is different from the OSI model, these layers are
nevertheless often compared with the OSI layering scheme in the following way: Application
Layer includes the OSI Application Layer, Presentation Layer, and most of the Session Layer.
Transport Layer (from TCP/IP model) includes the graceful close function of the OSI Session
Layer as well as the OSI Transport Layer. The Internet Layer is a subset of the OSI Network
Layer, while the Link Layer last, four layer of TCP/IP model - includes the OSI Data Link and
Physical Layers, as well as parts of OSI's Network Layer.

54

6. LPT port description


6.1.

History

Parallel connections was used to transmit measurement signals long ago before personal
computers appeared. IBM company first introduce LPT port into personal computer. They
was searching a way to implement simple parallel connection through which computer can
communicate with printer. IBM company used then simplified version of Centronics
standard which in full version use 29 connection lines and logical levels. Originally this
standard used 36 pin connector but large dimensions was inconvenient and format of
connector was changed to 25 pin called type SUB_D (DB-25). To save original signal lines of
Centronics protocol they reduced number of ground wires to 8. Because of original usage
parallel port was unidirectional. Only information about state of printing for example about
lack of paper was send to computer. After a few years HP adopted Centronics parallel on
their printer models and introduced a bidirectional version known as Bitronics on the
LaserJet 4 in 1992.
Devices can communicate via LPT parallel port on distance of 2 meters. When we use special
cable transmission is possible on distance of 5 meters. IEEE 1284 standard that defines bidirectional parallel communications between computers and other devices does not offer
hot plug functionality. Disconnecting cable from port when power is on in some cases can
cause damage of system responsible for parallel transmission.

Figure 46 Parallel PCMCIA Card for laptops

55

6.2.

Signals definition

Output signals of the parallel port are defined as typical TTL logical level signals. High level is
defined by voltage from 3.5V to 5.5V and low level from 0V to 0.4V - figure below.

Figure 47 TTL voltage level definition (input voltage, output voltage)


Different values of maximal load currents of the parallel port are done by physical realization
of the port. Maximal current takes from pins should be from range 4mA and 20mA.
Therefore it's better use a buffer between PC and peripheral device.
IEEE 1284 standard defines 5 activity modes:
1. SPP mode - Compatibility Mode (Centronics mode).
This mode is also called Centronics mode and it is standard mode for parallel data
communication. It was originally intended only for communication PC with printer. There is
defined only forward data transfer, it means from a PC to a peripheral device and data rate
can be only to 150kbps. Communication process is described in following figure below.

Figure 48 Compatibility Mode (SPP mode) Data Transfer Cycle

56

Compatibility Mode phase transitions:


1. Write the data to the data register
2. Program reads the status register to check that the printer is not BUSY
3. If not BUSY, then Write to the Control Register to assert the STROBE line
4. Write to the Control register to de-assert the STROBE line

In nowadays, many of the integrated 1284 I/O controllers have implemented Fast Centronics
or Parallel Port FIFO Mode, which use FIFO buffers for data transfer. Then data written in
FIFO port are transferred to printer using hardware generated handshake signals and it
increases data rate up to 500KBbs. However this mode isn't defined in standard IEEE 1284.
The basic SPP mode of parallel port is controlled by 3 base registers:
a. Data Register - intended for writing of transmit data
b. Status Register - intended for reading states on the lines.
c. Control Register - intended for controlling of the peripheral device, which receives
transmitted data.

Pins allocation to bits in registers is in the following figure:

Figure 49 Bits allocation in the LPT parallel port

57

2. Nibble Mode.
Nibble mode is way how to get reverse channel and bidirectional communication between
peripheral device and PC directly from classical SPP Compatible mode without hardware
adjustment. It is necessary only software support. Therefore the data rate limit is up to
100kbps. The advantage is ability of bidirectional communication on all PCs with LPT.
For transfer it is used 5 inputs lines of PC port which are intended for the handshake. The
four ones are used for data transfer into PC. Using of these lines the periphery can transmit
byte as sequence of 2 nibbles (4 bits) in two followings data cycles.

3. Byte Mode.
After implementation of parallel port interface, some producers in the lead with IBM
increase transfer capacity by removing data lines drivers and provide bidirectional 8-bit
communication by way of data lines. Then data rate is up to 200kbps.

4. EPP Mode (Enhanced Parallel Port).


EPP - Enhanced Parallel Port protocol was originally developed by companies Intel, Xircom
and Zenith Data Systems to provide powefull connection through parallel port and still was
compatible with standard LPT. This protocol was for the first time implemented in 386SL
chipset (82360 I/O chip). After this it became a part of the IEEE 1284 standard.
The effect of this mode is data rate between 500kbps and 2Mbps. The transfer is as fast as
data rate of the slowest communicating devices. The rate is found from changing of
messages and responses from handshake signals nWait and nDataStrobe.

5. ECP Mode (Extended Capabilities Mode).


The Extended Capability Port, or ECP, protocol was proposed by Hewlett Packard and
Microsoft as an advanced mode for communication with printer and scanner type
peripherals. Data rate in this mode can be up to 800KBps without using DMA ( Direct
Memory Access) and up to 2MBps with help of DMA. It's true in implementation on ISA bus.
Nowadays LPT interface implemented on PCI bus can reach up to 3 or 5 MBps. Sometimes
it's presented possibility up to 8MBps.

58

Table 2 Pin Assignments of the D-Type 25 pin Parallel Port Connector


Pin No
(D-Type 25)
1
2
3
4
5
6
7
8
9
10
11

Pin No
(Centronics)
1
2
3
4
5
6
7
8
9
10
11

12
13
14
15
16

12
13
14
32
31

17
18-25

36
19-30

6.3.

SPP Signal
nStrobe
Data 0
Data 1
Data 2
Data 3
Data 4
Data 5
Data 6
Data 7
nAck
Busy
PaperOut/Paper-End
Select
nAuto-Linefeed
nError/nFault
nInitialize
nSelectPrinter/nSelect-In
Ground

Direction
In/out
In/Out
Out
Out
Out
Out
Out
Out
Out
Out
In
In

Regist
Hardware
er
Inverted
Control Yes
Data
Data
Data
Data
Data
Data
Data
Data
Status
Status Yes

In
In
In/Out
In
In/Out

Status
Status
Control Yes
Status
Control

In/Out
Gnd

Control Yes

LPT program access

With coming of OS Windows based on NT core, it appears problems with parallel port
access. Programs written with classical direct access to LPT, which works under OS DOS and
Windows95/98, will not work properly. This programs can't be used, because they show an
error message like "The exception privileged instruction occurred in the application at
location ...." and they are interrupted. It's caused by Windows NT/2000/XP security for being
more stable system. Windows NT assigns some privileges and restrictions to different types
of programs running on it. It classifies all the programs in to two categories , User mode and
Kernel mode, running in ring3 and ring0 modes. Generally written programs running in User
mode are not allowed to access to LPT port using certain instructions like IN, OUT etc..
Whenever the operating system find that a user mode program is trying to execute such
instructions, the operating system stops execution of those programs and will display an
error message .In Kernel mode is not such restrictions so it is necessary to use a driver which
runs there. Then the driver can be used for LPT port access by the program which access
needs.
Because writing a such driver is not an easy job, at the internet is possible to find a lot of
universal drivers for users and programmers requirements. They usually allows to write and
read data from LPT port and sometimes some other features. We used inpout32.dll
dynamic-link library.
59

7. Description of C# language and our application


7.1.

.NET framework and C# language

In the past programmers who use Microsoft environment had to use Windows API functions.
With regard for complexity and numerous errors caused by series of patches and extensions
Microsoft decide to change conception of creating applications. Until these days a lot of
troubles was caused by memory management and a huge number of existing API functions.
Additional problem was to be able to transfer code of program between different
programming languages. With introducing NET framework these problems disappeared.
NET framework is big collection of programming languages such as Visual Basic, Visual C++,
Visual C#, Visual J# etc and all of them are functioning in common environment of services
provided by NET enterprise servers, distributed services and services for mobile devices. In
picture below we can see components of NET framework existing above operating system.

Figure 50 NET framework components table.

60

Each program code written in language which use NET framework is compiled on common
byte code which is called Intermediate Language (IL). There is no matter whether we
compile code of program written in Visual Basic, Visual C++ or in C# because as a result of
compilation there is always created the same Intermediate Language. Codes of programs
written in different languages are consistent on byte level so it is easy to mix them.
Common Language Specification is an open specification developed by Microsoft that
describes the executable code and runtime environment. It defines an environment that
allows multiple high-level languages to be used on different computer platforms without
being rewritten for specific architectures. Complying with CLS programmers can ensure full
integration of all languages from NET framework.
C# programming language derive from C/C++ family. It is object-oriented language which
contains memory recovery mechanisms and thread servicing. Similarly like for example Java
programming language code of program consists of collection of classes. Inheritance
hierarchy is based on existing of one object class System.Object which is superior
element of hierarchy. It means that simple types of data like int, double, etc. are object with
build in methods for example:
int i=1;
string s = i.ToString();
There is no need to release memory used by objects which are stopped to be used because
memory is management by starting environment.

7.2.

Description of our application

Below is a description of the whole step_server and client_socket_gui applications.

7.2.1. Methods, functions, events and classes used in step_server:


Event RunS_Click(object sender, EventArgs e) handle click on Run button event and display
information about status of server application in console richTextBox1.
Event StopS_Click(object sender, EventArgs e) handle click on Stop button event. When
user click Stop button the server try to stop listening on TCP port and reset state of LPT port.
We used try-catch statement to handle any exceptions and if some will occur user will see
the message: Cannot shutdown service.
Event fClient_Tick(object sender, EventArgs e) occurs in every 100ms interval if fClient timer
is enable and if there are pending connection requests. This event is responsible for adding
new clients to list of TcpClient class, creating new thread using to manage data receiving
form client and display connected client IP address.
Method AppendLog(string s, LogColor b, bool bNewLine, bool lpt) has four parameters.
First one is a string text displayed in a console (richTextBox1), time and commands.
61

Second one is used to set color of displayed text. Third one describe if cursor should be
placed in new line. And the last one parameter is used for determine if command written in
log is a state of LPT port or if it is event report by server, e. g. new client connected. Calling
this method result in displaying text (from string s) in console in chosen color.
Function show_time() is used to split only time (in format [hh:mm:ss]) from date and time
returned by DateTime structure.
Event Form1_FormClosing(object sender, FormClosingEventArgs e) check if there are still
some clients connected to server and if yes it cause message box show with information
Users are still connected. If there is no active connection to server this event add two lines
at the end of log file and reset state of LTP port.
Function CloseConn() return Boolean value true if serverSocket variable (TcpListener class) is
not null or if there is no active connection (checking by using property Connected of
Tcpclient class). More information about TcpListener, TcpClient and other classes from
System.Net.Sockets namespace are described below. Value returned by CloseConn function
is used for example in event Form1_FormClosing to checking if there are some active
connection.
Event LookSlots_Tick(object sender, EventArgs e) occurs in every 5 ms interval and is used
to set values of two properties run and refuse from handleClinet class (defined by us).
Class handleClinet is used to handle each client request separately. Below is short
description of each function and method used inside this class.
Method startClient(TcpClient inClientSocket, bool rf, Form1 f1) has three parameters. First
parameter inClientSocket is used to store information about client: IP address and port
number. Second Boolean parameter rf is used to check if server is busy, especially when few
clients are connected. Third one parameter pass information where to display log text. In
this method there is also created new thread which execute the code of doCommand
method.
Method OnTimedEvent(object source, ElapsedEventArgs e) is called when aTimer timer
elapsed. This method count steps and check if all steps are already done, if no next_step()
function from lpt class is called. If all steps are done Stop() method is used to stop timer.
Method Stop() is used stop listening on chosen port by server application. There is no
parameters in this method.
Function show_cmd( byte[] m) is used to converting data received from client to string value
due to show these data in console. This function has one parameter - array of bytes and
return string value.
Function give_ip() return string which is an IP address of connected client.
62

Function check_bytes(byte[] m) is using to check whether data received from client is only
zeros and if yes it means that client was disconnected (this function return false what is used
in doCommand() method to check if client was disconnected).
Method exit() is used to display log message: Client disconnect and this client IP address.
Here is also place where network connection is closed.
Method doCommand() is executed in separate thread creating in startClient method.
doCommand() method is used for:
a) checking if data received from client is not sequence treating as disconnecting client
if it is there is exit() method invoke
b) if data received from client is not sequence treating as disconnecting client in this
place we display information about working mode of motor, direction steps number
and delay. In next new line there is displayed command accepted text if everything
is okay or server busy. In this place there is also conversion of string
serverResponse (command accepted or server busy) to byte type variable
sendBytes - this is necessary because there is no way to send string variable over
TCP/IP.
Class posC is used to define items of ToolStripComboBox - LogLevel

7.2.2. Methods, functions, events and classes used in client_socket_gui:


Method senddata(byte mode, byte direction, int stepsno, int delay) has four parameters:
mode, direction, stepsno, delay. They store information about mode of working, direction of
rotation, number of steps and delay. We used NetworkStream class from
System.Net.Sockets Namespace to provide the underlying stream of data for network
access. Here is also usage of BitConverter class to convert base data types to an array of
bytes. To write data to the NetworkStream we used Write method and Flush method to
immediately send data.
Event button1_Click(object sender, EventArgs e) handle click on Send button. Using class
posC we get data from comboBoxes, textbox and trackBar. If value of comboBox1 (mode) is
equal 4 there is calling on event DiscStr_Click which cause disconnecting client from server.
And of course main task of this event is to call method senddata.
Event trackBar1_ValueChanged(object sender, EventArgs e) occurs when the Value
property of a track bar changes and display this value in label4.
Method AppendLog(string s, LogColor b, bool bNewLine) is almost the same like in
step_server program except for TrimLog() method.

63

Method TrimLog() is used to cut older log information from console to save time and space
in console. If there is less than 522 lines in console nothing happen.
Function show_time() is exactly the same like in step_server program.
Event CommStr_Click(object sender, EventArgs e) handle click on Connect item from Tools
menu. Using TcpClient() class client connect to server which IP address is given in
ToolStripTextBox - ServerIPTxtBx and port given in ServerPortTxtBx.
Event DiscStr_Click(object sender, EventArgs e) handle click on Disconnect item from Tools
menu. When user click Disconnect client_socket_gui application send sequence of zeros
stream to server and server close connection.
Event exitToolStripMenuItem_Click(object sender, EventArgs e) handle click on Exit item
from File menu. This event cause exiting from client_socket_gui application.
Event MainWindow_FormClosing(object sender, FormClosingEventArgs
DiscStr_Click event which closing connection with server application.

e)

calling

Event clearLogToolStripMenuItem_Click(object sender, EventArgs e) is responsible for


clearing console where logging information are displayed (richTextBox1).
Event saveToolStripMenuItem_Click(object sender, EventArgs e) use SaveFileDialog class to
display window in which user can write file name and save data from richTextBox1.
Class posC is used to define items of comboBoxes in which user can choose mode of working
and direction of rotation.

7.2.3. Lpt.cs class


PortAccess class is used to import Dynamic-Link Library inpout32.dll which is needed to
connect through step_server application to servomotor via LPT port.
Lpt class contain declaration of arrays of byte: wave, fullstep, halfstep. These values describe
mode of working of servomotor. We set them on the basis of control waveforms and output
of servomotor controller. In lpt class we declared following methods:
set_lpt(byte val) method is using to send data to appropriate port registry.
Function stop() uses set_lpt method to send to port registry value which close all transistors.
Function next_step() return unsigned 32-bit integer value which represents number from
byte array: wave or fullstep or halfstep. These values can be displayed is server console
when LogLevel is set to Serv Msg + LPT.
Method lpt(int m , int d, uint start) is using to control working of servomotor by using
set_lpt method.
64

7.2.4. Namespaces
Here is description of each namespace (without standard, using by default when creating
new project) used in our project:
System.Net Namespace
The System.Net namespace provides a simple programming interface for many of the
protocols used on networks today. The WebRequest and WebResponse classes form the
basis of what are called pluggable protocols, an implementation of network services that
enables you to develop applications that use Internet resources without worrying about the
specific details of the individual protocols.
In our work we used only one class from this namespace IPEndPoint which represents a
network endpoint as an IP address and a port number.
System.Net.Sockets Namespace
The System.Net.Sockets namespace provides a managed implementation of the Windows
Sockets (Winsock) interface for developers who need to tightly control access to the
network.
The TcpClient, TcpListener, and UdpClient classes encapsulate the details of creating TCP and
UDP connections to the Internet. Some classes from this namespace:
Table 3 Class examples from System.Net.Sockets Namespace

Class

Description

NetworkStream

Provides the underlying stream of data for network access.

TcpClient

Provides client connections for TCP network services.

TcpListener

Listens for connections from TCP network clients.

It is also worth noting that TCP communication operates at the byte levelwe are sending
simple 8-bit bytes back and forth over the network. Due to this structure, many of the lower
level TCP classes operate on arrays of bytes, and we was working with these arrays to build
our application.
System.Threading Namespace
The System.Threading namespace provides classes and interfaces that enable multithreaded
programming. In addition to classes for synchronizing thread activities and access to data (
Mutex, Monitor, Interlocked, AutoResetEvent, and so on), this namespace includes a
65

ThreadPool class that allows you to use a pool of system-supplied threads, and a Timer class
that executes callback methods on thread pool threads.
In our program we used only Thread class which creates and controls a thread, sets its
priority, and gets its status.
System.Timers Namespace
The System.Timers namespace provides the Timer component, which allows you to raise an
event on a specified interval. The server-based Timer is designed for use with worker threads
in a multithreaded environment. Server timers can move among threads to handle the
raised Elapsed event, resulting in more accuracy than Windows timers in raising the event on
time.
Table 4 Some classes from System.Timers Namespace:

Class

Description

ElapsedEventArgs

Provides data for the Timer.Elapsed event.

Timer

Generates recurring events in an application.

System.Runtime.InteropServices Namespace
The System.Runtime.InteropServices namespace provides a wide variety of members that
support COM interop and platform invoke services. We used in our application DllImport
class to import dynamic-link library inpout32.dll to manage LPT port.

7.3.

Code of server and client programs

step_server program:
using
using
using
using
using
using
using
using
using
using
using
using

System;
System.Collections.Generic;
System.ComponentModel;
System.Data;
System.Drawing;
System.Linq;
System.Text;
System.Windows.Forms;
System.Threading;
System.Net.Sockets;
System.Net;
System.Timers;

namespace step_server
{
// s_msg - server
// s_err - server
// c_msg - client
// s_res - server

message
error
message
response

66

public enum LogColor { s_msg=1, s_err, c_msg, s_res , s_m , lpt};


//enumeration used to set color of displayed log messages
enum Emode { wave=0, halfstep, fullstep, stop, exit }; //enumeration
used to set type of work of motor
enum Edirct { left = 0, right } //enumeration used to set direction of
rotation
public partial class Form1 : Form
{
int port = 8888;
bool locked = false;
bool server_exist = false;
List<handleClinet> cls = new List<handleClinet>(); //list of our
own Class handleClinet to handle each client request separatly
List<TcpClient> tcpl = new List<TcpClient>(); //list to store
TcpClients connections. TcpClient class has two parameters: host name and
port number
TcpListener serverSocket;
delegate void log_update(string message,LogColor c, bool newline,
bool lptm);
log_update d;
string filename = "log.txt";
public Form1()
{
InitializeComponent();
}
private void Form1_Load(object sender, EventArgs e)
{
d = AppendLog;
LogLevel.Items.Add( new posC(0, "Serv Msg") );
LogLevel.Items.Add( new posC(1, "Serv Msg + LPT") );
LogLevel.SelectedIndex = 0;
}
private void RunS_Click(object sender, EventArgs e)
{
if (server_exist != true)
{
serverSocket = new TcpListener(port);
serverSocket.Start();
fClient.Enabled = true; //enable timer fClient
server_exist = true;
StopS.Enabled = true;
RunS.Enabled = false;
d.Invoke(show_time() + "Server start", LogColor.s_msg,
true,false);
}
else
{
d.Invoke(show_time()
+
"Server
already
started",
LogColor.s_err, true,false);
}
}
private void StopS_Click(object sender, EventArgs e)
{
try

67

{
if(CloseConn()==false) throw new System.Exception("blad");
fClient.Enabled = false;
server_exist = false;
RunS.Enabled = true;
StopS.Enabled = false;
d.Invoke(show_time() + "Server stopped ", LogColor.s_msg,
true,false);
PortAccess.Output(888, 0);
}
catch
{
d.Invoke(show_time()
+
"Cannot
LogColor.s_err, true,false);
}
}

shutdown

service

",

private void fClient_Tick(object sender, EventArgs e)


{
if (serverSocket.Pending())
{
if (locked != true)
{
locked = true;
tcpl.Add( serverSocket.AcceptTcpClient());
cls.Add(new handleClinet());
cls[cls.Count-1].startClient(tcpl[tcpl.Count-1], false,
this);
d.Invoke(show_time()
+
"Client
connected
",
LogColor.s_msg, true,false);
AppendLog(show_time()
+
"Client
IP
"
+
((IPEndPoint)tcpl[tcpl.Count-1].Client.RemoteEndPoint).Address.ToString(),
LogColor.s_msg, true,false);
}
else
{
tcpl.Add(serverSocket.AcceptTcpClient());
cls.Add(new handleClinet());
cls[cls.Count - 1].startClient(tcpl[tcpl.Count - 1],
true, this);
d.Invoke(show_time()
+
"Client
connected
",
LogColor.s_msg, true,false);
AppendLog(show_time()
+
"Client
IP
"
+
((IPEndPoint)tcpl[tcpl.Count
1].Client.RemoteEndPoint).Address.ToString(), LogColor.s_msg, true,false);
}
}
}
public void AppendLog(string s, LogColor b, bool bNewLine, bool
lpt)
{
try
{
if (richTextBox1.InvokeRequired)
{
richTextBox1.BeginInvoke( new MethodInvoker(
delegate() { AppendLog( s,b,bNewLine,lpt); } ));
}

68

else if( !(LogLevel.SelectedIndex==0 && lpt==true) )


{
Color c = Color.Black;
switch (b)
{
case LogColor.s_msg:
c = Color.Blue;
break;
case LogColor.s_err:
c = Color.DarkRed;
break;
case LogColor.c_msg:
c = Color.DarkOrange;
break;
case LogColor.s_res:
c = Color.DarkViolet;
break;
case LogColor.s_m:
c = Color.Black;
break;
case LogColor.lpt:
c = Color.DarkSeaGreen;
break;
default:
break;
}
richTextBox1.SelectionColor = c;
richTextBox1.AppendText(s);
if
(bNewLine)
richTextBox1.AppendText(Environment.NewLine);
richTextBox1.SelectionStart = richTextBox1.TextLength;
richTextBox1.ScrollToCaret();
richTextBox1.Update();
}
}
catch
{
}
}
private string
{
DateTime t
string[] s
return "["
}

show_time()
= DateTime.Now;
= t.ToString().Split(' ');
+ s[1] + "] ";

private void Form1_FormClosing(object sender, FormClosingEventArgs


e)
{
if (CloseConn() == false)
{
MessageBox.Show("Users are still connected");
e.Cancel = true;
}
else
{
d.Invoke(show_time()
+
"Shutdown
in
progress
",
LogColor.s_msg, true,false);
d.Invoke(show_time()
+
"Saving
Log
to
file",
LogColor.s_msg, true,false);

69

richTextBox1.SaveFile(filename,RichTextBoxStreamType.PlainText);
PortAccess.Output(888,0);
System.Threading.Thread.Sleep(2000);
}
}
private bool CloseConn()
{
if ( serverSocket != null )
{
for (int i = cls.Count - 1; i >= 0; i--)
{
if (tcpl[i].Connected == true )
{
AppendLog(show_time()
+
"Not
all
clients
disconnect : " + i.ToString(), LogColor.s_err ,true,false);
return false;
}
else
{
if (cls[i].clientSocket != null)
{
cls[i].Stop();
AppendLog(show_time() + "Closing conn nr " +
i.ToString(), LogColor.s_msg, true,false);
}
}
}
serverSocket.Stop();
}
return true;
}
private void LookSlots_Tick(object sender, EventArgs e)
{
if (cls.Count != 1)
{
for (int i = 0; i <= cls.Count-1; i++)
{
if (cls[i].run == false)
{
cls[i].refuse = true;
}
else
{
cls[i].refuse = false;
return;
}
}
}
}
}
//Class to handle each client request separately
public class handleClinet
{
public TcpClient clientSocket;
NetworkStream networkStream;
Thread ctThread = null;

70

public bool run = true;


public bool refuse = false;
delegate void log_update(string mess , LogColor c , bool s, bool
l);
System.Timers.Timer aTimer = new System.Timers.Timer();
log_update lg;
lpt drv; //drv object from lpt class
public int itr;
public int itr_n;
public uint start_pos = 0;
private string
{
DateTime t
string[] s
return "["
}

show_time()
= DateTime.Now;
= t.ToString().Split(' ');
+ s[1] + "] ";

public void startClient(TcpClient inClientSocket, bool rf, Form1


f1)
{
lg = f1.AppendLog;
this.clientSocket = inClientSocket;
refuse = rf;
ctThread = new Thread(doCommand);
ctThread.Start();
aTimer.Elapsed += new ElapsedEventHandler(OnTimedEvent);
aTimer.Enabled = false;
}
public void OnTimedEvent(object source, ElapsedEventArgs e)
{
if (itr != 0)
{
itr_n++;
}
lg.Invoke(show_time() + " Lpt v=" + drv.next_step().ToString(),
LogColor.s_msg, true, true);
if (itr_n >= itr && itr!=0)
{
aTimer.Stop();
lg.Invoke(show_time() + "Server done task", LogColor.s_msg,
true,false);
}
start_pos = drv.pos;
}
public void Stop()
{
networkStream.Close();
clientSocket.Close();
run = false;
aTimer.Stop();
}
public string show_cmd( byte[] m)
{
StringBuilder sb = new StringBuilder();
sb.Append(m[0].ToString()+",");
sb.Append(m[1].ToString() + ",");
sb.Append(m[2].ToString() + ",");

71

sb.Append(m[3].ToString() + ",");
sb.Append(m[4].ToString() + ",");
sb.Append(m[5].ToString());
return sb.ToString();
}
public string give_ip()
{
return
((IPEndPoint)clientSocket.Client.RemoteEndPoint).Address.ToString();
}
public bool check_bytes(byte[] m)
{
if (m[0] == 0 && m[1] == 0 && m[2] == 0 && m[3] == 0 && m[4] ==
0 && m[5]==0)
{
return false;
}
return true;
}
public void exit()
{
aTimer.Stop();
lg.Invoke(show_time()
+
"Client
disconnect
=
((IPEndPoint)clientSocket.Client.RemoteEndPoint).Address.ToString(),
LogColor.s_msg, true,false);
networkStream.Close();
clientSocket.Close();
clientSocket = null;
networkStream = null;
refuse = true;
run = false;
}

"

private void doCommand()


{
byte[] bytesFrom = new byte[10025];
Byte[] sendBytes = null;
string serverResponse = null;
while ((run))
{
try
{
networkStream = clientSocket.GetStream();
networkStream.Read(bytesFrom,
0,
(int)clientSocket.ReceiveBufferSize);
if (run == false) break;
//checking if data received from client is not sequence
treating as disconnecting client
if
(!check_bytes(bytesFrom)
||
bytesFrom[0]
==
(int)Emode.exit)
{
exit();
}
else
{
lg.Invoke(show_time()
+
"
Cmd="
+
show_cmd(bytesFrom), LogColor.c_msg, true, false);

72

if (refuse == false)
{
int mode = Convert.ToInt32(bytesFrom[0]);
int direction = Convert.ToInt32(bytesFrom[1]);
byte[]
b1
=
new
byte[2]{bytesFrom[2],bytesFrom[3]};
int steps = BitConverter.ToUInt16(b1, 0);
byte[] b2 = new byte[2] { bytesFrom[4],
bytesFrom[5] };
int delay = BitConverter.ToUInt16(b2, 0);
lg.Invoke(show_time()
+
"",LogColor.s_m,false,false);
itr = steps;
itr_n = 0;
switch (mode)
{
case (int)Emode.wave:
drv
=
new
lpt(mode,
direction,start_pos);
aTimer.Interval = delay;
aTimer.Start();
lg.Invoke("wave,
",
LogColor.s_m,
false,false);
break;
case (int)Emode.stop:
if (drv != null)
{
aTimer.Stop();
}
lg.Invoke("stop,
",
LogColor.s_m,
false,false);
break;
case (int)Emode.halfstep:
drv
=
new
lpt(mode,
direction,
start_pos);
aTimer.Interval = delay;
aTimer.Start();
lg.Invoke("halfstep, ", LogColor.s_m,
false,false);
break;
case (int)Emode.fullstep:
drv
=
new
lpt(mode,
direction,
start_pos);
aTimer.Interval = delay;
aTimer.Start();
lg.Invoke("fullstep, ", LogColor.s_m,
false,false);
break;
case (int)Emode.exit:
lg.Invoke("exit,
",
LogColor.s_m,
false,false);
exit();
break;
default:
break;
}
switch (direction)
{
case (int)Edirct.left:

73

lg.Invoke("left,
",LogColor.s_m,false,false);
break;
case (int)Edirct.right:
lg.Invoke("right,
",LogColor.s_m,false,false);
break;
default:
break;
}
lg.Invoke("steps no=" + steps.ToString() + ",
", LogColor.s_m, false, false);
lg.Invoke("delay="
+
delay.ToString(),LogColor.s_m,true,false);
serverResponse = "Command Accepted";
lg.Invoke(show_time() + "[" + give_ip() + "]" +
serverResponse, LogColor.s_res, true,false);
}
else
{
serverResponse = "Server busy";
lg.Invoke(show_time() + "[" + give_ip() +"]" +
serverResponse, LogColor.s_res, true,false);
}
//here we convert string serverResponse to byte
type variable sendBytes - this is necessary because there is no way to send
string variable
sendBytes
=
Encoding.ASCII.GetBytes(serverResponse);
networkStream.Write(sendBytes,
0,
sendBytes.Length);
networkStream.Flush();
}
}
catch (Exception ex)
{
if (run == false || clientSocket.Connected == false)
{
lg.Invoke(show_time() + " client stoped " +
((IPEndPoint)clientSocket.Client.RemoteEndPoint).Address,
LogColor.s_err,
true,false);
if (clientSocket.Connected == false) run = false;
drv.set_lpt(0);
aTimer.Stop();
}
else
{
lg.Invoke(show_time()
+
""
+
ex.Message,
LogColor.s_err, true,false);
}
break;
}
}
}
}
//class using to define items of ToolStripComboBox - LogLevel
class posC
{
private int val;

74

private string nazwa;


public string Name
{
set { nazwa = value; }
get { return nazwa; }
}
public int Indx
{
set { val = value; }
get { return val; }
}
public posC()
{
val = 0;
nazwa = "Error";
}
public posC(int v, string n)
{
val = v;
nazwa = n;
}
public override string ToString()
{
return nazwa;
}
}
}

75

client_socket_gui program:
using
using
using
using
using

System;
System.Windows.Forms;
System.Net.Sockets;
System.Text;
System.Drawing;

namespace client_socket_gui
{
public partial class MainWindow : Form
{
// cl_msg - client message
// cl_err - client error
// sv_msg - server message
// st_chg - client status changed
public enum LogColor { cl_msg, cl_err, sv_msg, st_chg };
int _MaxLines = 512;
TcpClient clientSocket = null;
enum Emode { wave, halfstep, fullstep, stop, exit };
enum Edirct { left, right }
public MainWindow()
{
InitializeComponent();
}
private void Form1_Load(object sender, EventArgs e)
{
comboBox1.Items.Add( new posC(0,"wave") );
comboBox1.Items.Add( new posC(1, "half step") );
comboBox1.Items.Add( new posC(2, "full step") );
comboBox1.Items.Add( new posC(3, "stop") );
comboBox1.Items.Add( new posC(4, "exit") );
comboBox2.Items.Add(new posC(0, "left"));
comboBox2.Items.Add(new posC(1, "right"));
label4.Text = trackBar1.Value.ToString();
comboBox1.SelectedIndex = 0;
comboBox2.SelectedIndex = 0;
}
private void senddata(byte mode, byte direction, int stepsno, int
delay)
{
try
{
if (clientSocket != null)
{
if (clientSocket.Connected == true)
{
NetworkStream
serverStream
=
clientSocket.GetStream();
byte[] kr = BitConverter.GetBytes(stepsno);
byte[] md = BitConverter.GetBytes(delay);
byte[] outStream = new byte[6] { mode, direction,
kr[0], kr[1], md[0], md[1] };
serverStream.Write(outStream, 0, outStream.Length);
serverStream.Flush();

76

AppendLog("Sending

do

server

cmd

["

mode.ToString() + "," +
direction.ToString() + "," + kr[0].ToString() +
"," +
kr[1].ToString() + "," + md[0].ToString() + ","
+
md[1].ToString() + "]", LogColor.cl_msg, true);
byte[] inStream = new byte[10025];
serverStream.Read(inStream,
0,
(int)clientSocket.ReceiveBufferSize);
string
returndata
=
System.Text.Encoding.ASCII.GetString(inStream);
AppendLog("Server
response:
"
+
returndata,
LogColor.sv_msg, true);
}
else
{
throw new Exception("");
}
}
}
catch
{
AppendLog("No connection with server: ", LogColor.sv_msg,
true);
}
}
private void button1_Click(object sender, EventArgs e)
{
posC mode = (posC)comboBox1.SelectedItem;
posC direction = (posC)comboBox2.SelectedItem;
int steps_no = Convert.ToInt32(textBox3.Text);
int delay = trackBar1.Value;
if ((byte)mode.Indx == 4)
{
DiscStr_Click(this, null);
}
senddata((byte)mode.Indx,
(byte)direction.Indx,

steps_no,

delay);
}
private void trackBar1_ValueChanged(object sender, EventArgs e)
{
label4.Text = Convert.ToString(trackBar1.Value);
}
public void AppendLog(string s, LogColor b, bool bNewLine)
{
try
{
if (richTextBox1.InvokeRequired)
{
richTextBox1.BeginInvoke(new MethodInvoker(
delegate() { AppendLog(s, b, bNewLine); }));
}
else
{
Color c = Color.Black;
switch (b)

77

{
case LogColor.cl_err:
c = Color.DarkRed;
break;
case LogColor.cl_msg:
c = Color.DarkOliveGreen;
break;
case LogColor.st_chg:
c = Color.DarkOrange;
break;
case LogColor.sv_msg:
c = Color.Blue;
break;
default:
break;
}
richTextBox1.SelectionColor = c;
richTextBox1.AppendText(show_time() + s);
if
(bNewLine)
richTextBox1.AppendText(Environment.NewLine);
TrimLog();
richTextBox1.SelectionStart = richTextBox1.TextLength;
richTextBox1.ScrollToCaret();
richTextBox1.Update();
}
}
catch (Exception exc)
{
MessageBox.Show(exc.Message);
}
}
private void TrimLog()
{
try
{
// Extra lines as buffer to save time
if (richTextBox1.Lines.Length < _MaxLines + 10)
{
return;
}
else
{
string[] sTemp = richTextBox1.Lines;
string[] sNew = new string[_MaxLines];
int iLineOffset = sTemp.Length - _MaxLines;
for (int n = 0; n < _MaxLines; n++)
{
sNew[n] = sTemp[iLineOffset];
iLineOffset++;
}
richTextBox1.Lines = sNew;
}
}
catch (Exception exc)
{
MessageBox.Show(exc.Message);
}
}
private string show_time()

78

{
DateTime t = DateTime.Now;
string[] s = t.ToString().Split(' ');
return "[" + s[1] + "] ";
}
private void CommStr_Click(object sender, EventArgs e)
{
if (clientSocket == null)
{
try
{
clientSocket = new TcpClient();
clientSocket.Connect(ServerIPTxtBx.Text,
Convert.ToInt32(ServerPortTxtBx.Text));
AppendLog("Connected
to
server",
LogColor.st_chg,
true);
CommStr.Enabled = false;
DiscStr.Enabled = true;
}
catch
{
AppendLog("Bad
adress
or
port
already
used",
LogColor.cl_err, true);
}
}
else
{
AppendLog("Already connected", LogColor.cl_err, true);
}
}
private void DiscStr_Click(object sender, EventArgs e)
{
if (clientSocket!=null)
{
AppendLog("Disconnected", LogColor.st_chg, true);
NetworkStream serverStream = clientSocket.GetStream();
byte[] outStream = new byte[6] { 0, 0, 0, 0, 0, 0 };
serverStream.Write(outStream, 0, outStream.Length);
serverStream.Flush();
CommStr.Enabled = true;
DiscStr.Enabled = false;
clientSocket.Close();
clientSocket = null;
System.Threading.Thread.Sleep(1000);
}
}
private void exitToolStripMenuItem_Click(object sender, EventArgs
e)
{
Application.Exit();
}
private
void
FormClosingEventArgs e)
{

MainWindow_FormClosing(object

79

sender,

DiscStr_Click(this, null);
}
private
void
clearLogToolStripMenuItem_Click(object
EventArgs e)
{
richTextBox1.Clear();
}

sender,

private void saveToolStripMenuItem_Click(object sender, EventArgs


e)
{
SaveFileDialog dlg = new SaveFileDialog();
dlg.Filter = "txt files (*.txt)|*.txt|All files (*.*)|*.*";
dlg.FilterIndex = 1;
dlg.RestoreDirectory = true;
if (dlg.ShowDialog() == DialogResult.OK)
{
richTextBox1.SaveFile(dlg.FileName,RichTextBoxStreamType.PlainText);
}
}
}
class posC
{
private int val;
private string nazwa;
public string Name
{
set { nazwa = value; }
get { return nazwa; }
}
public int Indx
{
set { val = value; }
get { return val; }
}
public posC()
{
val = 0;
nazwa = "Error";
}
public posC(int v , string n)
{
val = v;
nazwa = n;
}
public override string ToString()
{
return nazwa;
}
}
}

80

Lpt class:
using
using
using
using
using

System;
System.Collections.Generic;
System.Linq;
System.Text;
System.Runtime.InteropServices;

namespace step_server
{
public class PortAccess
{
[DllImport("inpout32.dll", EntryPoint = "Out32")]
public static extern void Output(int adress, int value);
}
class lpt
{
enum Emode { wave = 0, halfstep, fullstep, stop, exit };
enum Edirct { left = 0, right }
public
public
public
public
public
public

uint mode;
uint dir;
uint pos;
byte[] wave = new byte[4]{ 7 , 49 , 11 , 81 };
byte[] fullstep = new byte[4] { 55, 59, 91, 87 };
byte[] halfstep = new byte[8] { 7, 55, 49, 59, 11, 91, 81,

87 };
public void set_lpt(byte val)
{
// lpt driver code
PortAccess.Output(888, (int)val);
}
public void stop()
{
// close all transistors
set_lpt(1);
}
public uint next_step()
{
byte[] m;
switch (mode)
{
case (int)Emode.wave:
m = wave;
break;
case (int)Emode.fullstep:
m = fullstep;
break;
case (int)Emode.halfstep:
m = halfstep;
break;
default:
m = new byte[4]{ 0 , 0 , 0 , 0 };
break;
}

81

uint val = 0;
switch (dir)
{
case (int)Edirct.left:
if (pos == 0) pos = (uint)m.Length - 1;
else pos--;
set_lpt(m[pos]);
val = m[pos];
break;
case (int)Edirct.right:
if (pos == m.Length-1) pos = 0;
else pos++;
set_lpt(m[pos]);
val = m[pos];
break;
default:
break;
}
return val;
}
public lpt(int m , int d, uint start)
{
mode = (uint)m;
dir = (uint)d;
switch (mode)
{
case (int)Emode.wave:
if (start > wave.Length) start = 0;
set_lpt(wave[start]);
pos = start;
break;
case (int)Emode.fullstep:
if (start > fullstep.Length) start = 0;
set_lpt(fullstep[start]);
pos = start;
break;
case (int)Emode.halfstep:
if (start > halfstep.Length) start = 0;
set_lpt(halfstep[start]);
pos = start;
break;
default:
break;
}
}
}
}

82

8. Conclusions & summary


The aim of this thesis was to design and build system which can control servomotor through
LPT parallel port. This was the first part of our work and the second was to write a program
consist of two application: server and client which can communicate in wired Local Area
Network. In our implementation there can be a few instances of client application and only
one server application in a given LAN segment. In other words several user (client program)
can control servomotor which is connected through LPT port to computer where server
application is running.
The whole program was written in Visual C# language. We used existing methods, functions
and classes like TcpClient or TcpListener from System.Net.Sockets namespace but also
implemented our own methods for example startClient that is based on those existing
classes. Handling of LPT port was done by using inpout32.dll and DllImport function to
import this Dynamic Link Library. We did it in our own lpt class in which we also implement
different types of working modes. The idea of those two applications is that user can see on
console screen what is doing in particular moment number of motor steps, direction and
working mode - and what was done before. Programs has also feature to save these logs on
disk in plain text log file.
There is no way to send data for example in plain text (string variable) through the network.
The only possibility is to send bytes using TCP/IP stack. We used Encoding.ASCII property to
convert string variables to ASCII characters (Encoding.ASCII.GetBytes) and in opposite way
(Encoding.ASCII.GetString).
Second part of our work was the design of a controller which could be operated via PC class
computer while using the program also written by us. This control gear, which we had
designed first, and then built later depending on the prepared plans, was constructed using
electromechanical parts which are commonly available to buy on the electrical market in our
country. The goals which we have put before ourselves, was in the end realized in every way.
We are hoping that our whole work, would give basic knowledge and would be a good start,
for other future students whom would be interested in the topic of Stepper Motors (and
other servomechanisms also) control, using computer applications written to be compatible
with
newest
operating
systems
such
as
Microsoft
"Windows
7".

83

Dictionary:
feedback - sprzenie zwrotne
cruise control tempomat
transducer - przetwornik
output shaft - wa zdawczy (przekadnia przyspieszajca, multiplikator)
rudder ster statku lub samolotu
gear train koa zbate
bearing oysko
actuator siownik
friction - tarcie
torque - moment obrotowy
slew rate - wskanik obrotu
rectifier - prostownik
RPM (Revolutions per minute) - obroty na minut
shell - obudowa
moving coil - ruchoma cewka
printed-circuit - obwd drukowany
cast - odlew
PM (Permanent magnet) - magnes trway
EMF (Electro-magnetic field) - pole elektro-magnetyczne
steam engine - silnik tokowy, parowy
governor - regulator Watta
windmill fantail - rodzaj maego wiatraka
vacuum tube - lampa prniowa (elektronowa)
intermittent - okresowy
control module - (w tym przypadku) stopieo mocy
84

driver module - stopieo sterujcy


logic board - pyta logiczna
sinking current -prd obniajcy
sourcing current -prd rdowy
diode bridge - mostek diodowy
monolithic - monolityczny
sink resistor - rezystor obniajcy
rectifier - prostownik

85

References:
1. IEEE Industry Applications Magazine March/April 1996, page 74
2. http://zone.ni.com/devzone/cda/ph/p/id/234
3. http://www.pc-control.co.uk/servo_control.htm
4. http://www.baldor.com/products/servomotors
5. http://www.electricmotors.machinedesign.com
6. http://www.aida-global.com/metalforming-solutions/servopro.cfm
7. http://jyotsnaj.wordpress.com/2009/07/26/servomechanisms-and-its-applications/
8. http://www.cadsoft.de
9. http://neil.fraser.name/hardware/stepper/
10. http://www.elportal.pl/pdf/k01/81_24.pdf
11. http://www.wikipedia.com
12. http://cpuville.com/three_state.htm
13. http://www.kpsec.freeuk.com/components
14. http://www.st.com/stonline/books/pdf/docs/1773.pdf
15. http://www.datasheetcatalog.org/datasheet/motorola/TIP145.pdf
16. http://www.microsemi.com/micnotes/401.pdf
17. http://msdn.microsoft.com/en-us/library/
18. http://www.solarbotics.net/library/pdflib/pdf/motorbas.pdf
19. http://hw-server.pl/

86

You might also like