Anda di halaman 1dari 26

MICROCOTROLLERBASED MOTION

&
POSITION CONTROL OF STEPPER
MOTOR

Guided by:
NIRAJ CHADHA

Organization:
Variable Energy Cyclotron Centre (VECC)
1/AF, Bidhan Nagar, Kolkata-700064

Prepared by:
ARUN BERA

TECHNO INDIA COLLEGE OF TECHNOLOGY (TICT)


(WBUT)
NEWTOWN, RAJARHAT, KOLKATA-
700156

CERTIFICATE

This is to certify that ARUN BERA of TECHNO INDIA COLLEGE OF


TECHNOLOGY, Kolkata has satisfactorily and successfully complete his project
on MICROCONTROLLER BASED POSITION & MOTION CONTROL OF
STEPPER MOTOR, from VARIABLE ENERGY AND CYCLOTORN
CENTERE (VECC), 1/AF, Bidhan Nagar ,Kolkata-700064 during the period 21st
June to 16th July 2010.

Date:

Signature of Professor: Head of Department


What is a Stepper Motor?
A stepper motor is an electromechanical device which converts electrical pulses into discrete mechanical
movements. The shaft or spindle of a stepper motor rotates in discrete step increments when electrical
command pulses are applied to it in the proper sequence. 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 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.

How Stepper Motor works:


Stepper motors behaves differently than standard DC
motors. First of all, they cannot run freely by themselves.
Stepper motors do as their name suggests -- they "step" a
little bit at a time. Stepper motors also differ from DC
motors in their torque-speed relationship. DC motors
generally are not very good at producing high torque at low
speeds, without the aid of a gearing mechanism. Stepper
motors, on the other hand, work in the opposite manner.
They produce the highest torque at low speeds. Stepper
motors also have another characteristic, holding torque,
which is not present in DC motors. Holding torque allows a
stepper motor to hold its position firmly when not turning.
This can be useful for applications where the motor may be
starting and stopping, while the force acting against the
motor remains present. This eliminates the need for a
mechanical brake mechanism. Steppers don't simply
respond to a clock signal, they have several windings which need to be energized in the correct sequence
before the motor's shaft will rotate. Reversing the order of the sequence will cause the motor to rotate the
other way. If the control signals are not sent in the correct order, the motor will not turn properly. It may
simply buzz and not move, or it may actually turn, but in a rough or jerky manner. A circuit which is
responsible for converting step and direction signals into winding energization patterns is called a
translator. Most stepper motor control systems include a driver in addition to the translator, to handle the
current drawn by the motor's windings.

A basic example of the "translator + driver" type


of configuration. Notice the separate voltages
for logic and for the stepper motor. Usually the
motor will require a different voltage than the
logic portion of the system. Typically logic voltage is +5 V dc and the stepper motor voltage can range
from +5 V dc up to about +48 V dc. The driver is also an "open collector" driver, wherein it takes its
outputs to GND to activate the motor's windings. Most semiconductor circuits are more capable of
sinking (providing a GND or negative voltage) than sourcing (outputting a positive
voltage).

When to use a Stepper Motor:


A stepper motor can be a good choice whenever controlled movement is required. They can be used to
advantage in applications where you need to control rotation angle, speed, position and synchronism.
Because of the inherent advantages listed previously, stepper motors have found their place in many
different applications. Some of these include printers, plotters, high-end office equipment, hard disk
drives, medical equipment, fax machines, automotive and many more.

Torque Generation:
The torque produced by a stepper motor depends on several factors.

• The step rate

• The drive current in the windings

• The drive design or type

In a stepper motor a torque is developed when the magnetic fluxes of the rotor and stator are displaced
from each other. The stator is made up of a high permeability magnetic material. The presence of this
high permeability material causes the magnetic flux to be confined for the most part to the paths defined
by the stator structure in the same fashion that currents are confined to the conductors of an electronic
circuit. This serves to concentrate the flux at the stator poles. The torque output produced by the motor is
proportional to the intensity of the magnetic flux generated when the winding is energized. The basic
relationship which defines the intensity of the magnetic flux is defined by:

H = (N × I) ÷l where: N = The number of winding turns

I = current, H = Magnetic field intensity, l = Magnetic flux path length.

This relationship shows that the magnetic flux intensity and consequently the torque is proportional to the
number of winding turns and the current and inversely proportional to the length of the magnetic flux
path. From this basic relationship one can see that the same frame size stepper motor could have very
different torque output capabilities simply by changing the winding parameters. More detailed
information on how the winding parameters affect the output capability of the motor can be found in the
application note entitled “Drive Circuit Basics”.

Stepping Modes:
The following are the most common drive modes.

• Full Step Drive (2 phases on):

Standard (hybrid) stepping motors have 200 rotor teeth, or 200 full steps per revolution of the motor shaft.
Dividing the 200 steps into the 360º's rotation equals a 1.8º full step angle. Normally, full step mode is
achieved by energizing both windings while reversing the current alternately. Essentially one digital input
from the driver is equivalent to one step.

• Half Step Drive (1 & 2 phases on):

Half step simply means that the motor is rotating at 400 steps per revolution. In this mode, one winding is
energized and then two windings are energized alternately, causing the rotor to rotate at half the distance,
or 0.9º's. (The same effect can be achieved by operating in full step mode with a 400 step per revolution
motor). Half stepping is a more practical solution however, in industrial applications. Although it
provides slightly less torque, half step mode reduces the amount "jumpiness" inherent in running in a full
step mode.

• Micro stepping (Continuously varying motor currents)

Micro stepping is a relatively new stepper motor technology that controls the
current in the motor winding to a degree that further subdivides the number of
positions between poles. AMS micro steppers are capable of rotating at 1/256 of a
step (per step), or over 50,000 steps per revolution.

TYPES OF STEPPER MOTORS


Stepper motors fall into two basic categories: Permanent magnet and variable reluctance. The type of
motor determines the type of drivers, and the type of translator used. Of the permanent magnet stepper
motors, there are several "sub flavors" available. These include the Unipolar, Bipolar, and Multiphase
varieties.
 Permanent Magnet Stepper Motors

Unipolar Stepper Motors

Unipolar motors are relatively easy to control. A simple 1-of-'n' counter circuit can generate the proper
stepping sequence, and drivers as simple as 1 transistor per winding are possible with unipolar motors.
Unipolar stepper motors are characterized by their center-tapped windings. A common wiring scheme is
to take all the taps of the center-tapped windings and feed them +MV (Motor voltage). The driver circuit
would then ground each winding to energize it.

Figure 2.1 - A typical unipolar stepper motor driver circuit. Note the 4 back EMF protection
diodes.
Unipolar stepper motors are recognized by their center-tapped windings. The number of phases is twice
the number of coils, since each coil is divided in two. So the diagram below (Figure 3.1), which has two
center-tapped coils, represents the connection of a 4-phase unipolar stepper motor.
Figure 3.1 - Unipolar stepper motor coil setup (left) and 1-phase drive pattern
(right).
In addition to the standard drive sequence, high-torque and half-step drive sequences are also possible. In
the high-torque sequence, two windings are active at a time for each motor step. This two-winding
combination yields around 1.5 times more torque than the standard sequence, but it draws twice the
current. Half-stepping is achieved by combining the two sequences. First, one of the windings is
activated, then two, then one, etc. This effectively doubles the number of steps the motor will advance for
each revolution of the shaft, and it cuts the number of degrees per step in half.

Full-stepping animation Half-stepping animation

Figure 4.1 - Two-phase stepping sequence (left) and half-stepsequence (right).


 Variable Reluctance Stepper Motors
Sometimes referred to as Hybrid motors, variable reluctance stepper motors are the simplest to control
over other types of stepper motors. Their drive sequence is simply to energize each of the windings in
order, one after the other This type of stepper motor will often have only one lead, which is the common
lead for all the other leads. This type of motor feels like a DC motor when the shaft is spun by hand; it
turns freely and you cannot feel the steps. This type of stepper motor is not permanently magnetized like
its unipolar and bipolar
counpolar counterparts.

Figure 7.1 -
Variable reluctance
stepper motor coil
setup (left) and drive
pattern (right).

Advantages:
1. The rotation angle of the motor is proportional to the input pulse.
2. The motor has full torque at stand-still (if the windings are energized)
3. Precise positioning and repeat-ability of movement since good stepper motors have an accuracy of 3 –
5% of a step and this error is non cumulative from one step to the next.
4. Excellent response to starting/stopping/reversing.
5. Very reliable since there are no contact brushes in the motor. Therefore the life of the motor is simply
dependant on the life of the bearing.

Disadvantages:
1. Resonances can occur if not properly controlled.
2. Not easy to operate at extremely high speeds.

APPLICATIONS:
Numerically Controlled Machine: Profile cutting, Grinding, Drilling, Milling and Boring
Machines
Tools and Machining Centres: Lathes, Spark Erosion Machines, Sheet Metal Presses.

Plastic and Packaging: Mark registration, labeling and cut to length.


Graphics: Photo Printing and Developing, Photo Type Setting, Printing Presses, Film Projectors
and Cameras, etc.

Process Control and Instrumentation: Textile web control, Valve controls, Material Handling
Sys Assembly Lines, Carburetor Adjusting, In process gauging, Chart Recorders, Servo
Mechanism, Electronic Gear Box, Precise RPM Control, RPM meter calibration.

Medical Instruments: Infusion Pumps, X-ray and Radioactive Machinery, Blood analysers etc.

Office Automation Equipments: Printers, Plotters, Hard Disk and Floppy Disk Drive, Telepri
and Typewriters, Copying Machines and Accounting Machines.

Motor Specification:
Model:-STM 602 Torque:-4kg. Step:-200

Motor Drive

Switching
Logic Sequence (Clockwise rotation):
Green Orange Blue Red
Full Step
1 1 0 0

0 1 1 0

0 0 1 1

1 0 0 1
Red Orange Blue Green

0 1 0 1

0 0 0 1

1 0 0 1

1 0 0 0

1 0 1 0

0 0 1 0

0 1 1 0

0 1 0 0

Half Step
Microcontroller AT89C51
A microcontroller is an entire computer manufactured on a single chip. Microcontrollers are
usually dedicated devices embedded within an application. For example, microcontrollers are
used as engine controllers in automobiles and as exposure and focus controllers in cameras. In
order to serve these applications, they have a high concentration of on-chip facilities such as
serial ports, parallel input-output ports, timers, counters; interrupt control, analog-to-digital
converters, random access memory, read only memory, etc. The I/O, memory, and on-chip
peripherals of a microcontroller are selected depending on the specifics of the target application.
Since microcontrollers are powerful digital processors, the degree of control and
programmability they provide significantly enhances the effectiveness of the application. The
8051 is the first microcontroller of the MCS-51 family introduced by Intel Corporation at the end
of the 1970s. The 8051 family with its many enhanced members enjoys the largest market share,
estimated to be about 40%, among the various microcontroller architectures. The architecture of
the 8051 family of the microcontrollers is presented in this chapter. First, the original 8051
microcontroller is discussed, followed by the enhanced features of the 8032, and the 80C515.
Block diagram of the 8051 Microcontroller:

Pin diagram of the 8051 Microcontroller:


Port Description of AT89C51:

Port 0
Port 0 is an 8-bit open-drain bi-directional I/O port. As an output port, each pin can
sink eight TTL inputs. When 1sare written to port 0 pins, the pins can be used as
high-impedance inputs. Port 0 may also be configured to be the multiplexed low-
order address/data bus during accesses to external pro-gram and data memory. In
this mode P0 has internal pull-ups. Port 0 also receives the code bytes during Flash
programming, and outputs the code bytes during program verification. External
pull-ups are required during program verification.
Port 1
Port 1 is an 8-bit bi-directional I/O port with internal pull-ups. The Port 1 output
buffers can sink/source four TTL inputs. When 1s are written to Port 1 pins they are
pulled high by the internal pull-ups and can be used as inputs. As inputs, Port 1 pins
that are externally being pulled low will source current (IIL) because of the internal
pull-ups. Port 1 also receives the low-order address bytes during Flash programming
and verification.
Port 2
Port 2 is an 8-bit bi-directional I/O port with internal pull-ups. The Port 2 output
buffers can sink/source four TTL inputs. When 1s are written to Port 2 pins they are
pulled high by the internal pull-ups and can be used as inputs. As inputs, Port 2 pins
that are externally being pulled low will source current (IIL) because of the internal
pull-ups. Port 2 emits the high-order address byte during fetches from external
program memory and during accesses to external data memory that uses 16-bit
addresses (MOVX @DPTR). In this application, it uses strong internal pull-ups when
emitting 1s. During accesses to external data memory that uses 8-bit addresses
(MOVX @ RI), Port 2 emits the contents of the P2 Special Function Register.
Port 3
Port 3 is an 8-bit bi-directional I/O port with internal pull-ups. The Port 3 output
buffers can sink/source four TTL inputs. When 1s are written to Port 3 pins they are
pulled high by the internal pull-ups and can be used as inputs. As inputs , Port 3
pins that are externally being pulled low will source current (IIL) because of the pull-
ups. Port 3 also serves the functions of various special features of the AT89C51 as
listed below:

Port pin Alternate Features

P3.0 RXD (serial input port)

P3.1 TXD (serial output port)

P3.2 INT0 (external interrupt 0)

P3.3 INT1 (external interrupt 1)

P3.4 T0 (timer 0 external input)

P3.5 T1 (timer 1 external input)

P3.6 WR (external data memory write strobe)

P3.7 RD (external data memory read strobe)


RST
Reset input. A high on this pin for two machine cycles while the oscillator is running
resets the device.
ALE/PROG
Address Latch Enable output pulse for latching the low byte of the address during
accesses to external memory. This pin is also the program pulse input (PROG)
during Flash programming. In normal operation ALE is emitted at a constant rate of
1/6the oscillator frequency, and may be used for external timing or clocking
purposes. Note, however, that one ALE pulse is skipped during each access to
external Data memory. If desired, ALE operation can be disabled by setting bit 0 of
SFR location 8EH. With the bit set, ALE is active only during a MOVX or MOVC
instruction. Otherwise, the pin is weakly pulled high.
PSEN:
Program Store Enable is the read strobe to external pro-gram memory. When the
AT89C51 is executing code from external pro-gram memory, PSEN is activated
twice each machine cycle, except that two PSEN activations are skipped during
each access to external data memory.
EA/VPP:
External Access Enable. EA must be strapped to GND in order to enable the device
to fetch code from external pro-gram memory locations starting at 0000H up to
FFFFH. Note, however, that if lock bit 1 is programmed, EA will be internally latched
on reset. EA should be strapped to VCC for internal program executions. This pin
also receives the 12-volt programming enable volt-age (VPP) during Flash
programming, for parts that require12-volt VPP.
XTAL1
Input to the inverting oscillator amplifier and input to the internal clock operating
circuit.
XTAL2
Output from the inverting oscillator amplifier.
What Are SFRs?
The 8051 is a flexible microcontroller with a relatively large number of modes of operations.
Your program may inspect and/or change the operating mode of the 8051 by manipulating the
values of the 8051's Special Function Registers (SFRs).
SFRs are accessed as if they were normal Internal RAM. The only difference is that Internal
RAM is from address 00h through 7Fh whereas SFR registers exist in the address range of 80h
through FFh.
Each SFR has an address (80h through FFh) and a name. The following chart provides a
graphical presentation of the 8051's SFRs, their names, and their address.

As we can see, although the address range of 80h through FFh offer 128 possible addresses, there
are only 21 SFRs in a standard 8051. All other addresses in the SFR range (80h through FFh) are
considered invalid. Writing to or reading from these registers may produce undefined values or
behavior.

SFR Types:
As mentioned in the chart itself, the SFRs that have a blue background are SFRs related to the
I/O ports. The 8051 has four I/O ports of 8 bits, for a total of 32 I/O lines. Whether a given I/O
line is high or low and the value read from the line are controlled by the SFRs in green.
The SFRs with yellow backgrounds are SFRs which in some way control the operation or the
configuration of some aspect of the 8051. For example, TCON controls the timers, SCON
controls the serial port.
The remaining SFRs, with green backgrounds, are "other SFRs." These SFRs can be thought of
as auxiliary SFRs in the sense that they don't directly configure the 8051 but obviously the 8051
cannot operate without them. For example, once the serial port has been configured using
SCON, the program may read or write to the serial port using the SBUF register.
TCON (Timer Control, Addresses 88h, Bit-Addressable): The Timer Control SFR is used to
configure and modify the way in which the 8051's two timers operate. This SFR controls
whether each of the two timers is running or stopped and contains a flag to indicate that each
timer has overflowed. Additionally, some non-timer related bits are located in the TCON SFR.
These bits are used to configure the way in which the external interrupts are activated and also
contain the external interrupt flags which are set when an external interrupt has occurred.
Bit
Bit Name Explanation of Function Timer
Address

7 TF1 8Fh Timer 1 Overflow. This bit is set by the microcontroller when Timer 1 overflows. 0

Timer 1 Run. When this bit is set Timer 1 is turned on. When this bit is clear Timer
6 TR1 8Eh 1
1 is off.

5 TF0 8Dh Timer 0 Overflow. This bit is set by the microcontroller when Timer 0 overflows. 0

Timer 0 Run. When this bit is set Timer 0 is turned on. When this bit is clear Timer
4 TR0 8Ch 0
0 is off.

TMOD (Timer Mode, Addresses 89h): The Timer Mode SFR is used to configure the mode of
operation of each of the two timers. Using this SFR your program may configure each timer to
be a 16-bit timer, an 8-bit auto reload timer, a 13-bit timer, or two separate timers. Additionally,
you may configure the timers to only count when an external pin is activated or to count "events"
that are indicated on an external pin.
Lets first talk about our first control SFR: TMOD (Timer Mode). The TMOD SFR is used to
control the mode of operation of both timers. Each bit of the SFR gives the microcontroller
specific information concerning how to run a timer. The high four bits (bits 4 through 7) relate to
Timer 1 whereas the low four bits (bits 0 through 3) perform the exact same functions, but for
timer 0.
Bit Name Explanation of Function Timer

When this bit is set the timer will only run when INT1 (P3.3) is high.
7 GATE1 0
When this bit is clear the timer will run regardless of the state of INT1.

When this bit is set the timer will count events on T1 (P3.5). When this
6 C/T 0
bit is clear the timer will be incremented every machine cycle.

5 T1M1 Timer 1 mode bit 1

4 T1M0 Timer 1mode bit 0

When this bit is set the timer will only run when INT0 (P3.2) is high.
3 GATE0 0
When this bit is clear the timer will run regardless of the state of INT0.

When this bit is set the timer will count events on T0 (P3.4). When this
2 C/T0 0
bit is clear the timer will be incremented every machine cycle.

1 T0M1 Timer 0 mode bit 0

0 T0M0 Timer 0mode bit 0

Serial Communication:
One of the 8051s many powerful features is its integrated UART, otherwise known as a serial
port. The fact that the 8051 has an integrated serial port means that you may very easily read and
write values to the serial port. If it were not for the integrated serial port, writing a byte to a serial

line would be a rather tedious process requring turning on and off one of the I/O lines in rapid
succession to properly "clock out" each individual bit, including start bits, stop bits, and parity
bits.

However, we do not have to do this. Instead, we simply need to configure the serial ports
operation mode and baud rate. Once configured, all we have to do is write to an SFR to write a
value to the serial port or read the same SFR to read a value from the serial port. The 8051 will
automatically let us know when it has finished sending the character we wrote and will also let
us know whenever it has received a byte so that we can process it. We do not have to worry
about transmission at the bit level--which saves us quite a bit of coding and processing time.The
first thing we must do when using the 8051s integrated serial port is, obviously, configure it.
This lets us tell the 8051 how many data bits we want, the baud rate we will be using, and how
the baud rate will be determined.
SCON (Serial Control, Addresses 98h, Bit-Addressable):
The Serial Control SFR is used to configure the behavior of the 8051's on-board serial port. This
SFR controls the baud rate of the serial port, whether the serial port is activated to receive data,
and also contains flags that are set when a byte is successfully sent or received.
Bit Name Bit Addres Explanation of Function Timer

7 SM0 9Fh Serial port mode bit 0 0

6 SM1 9Eh Serial port mode bit 1. 1

5 SM2 9Dh Mutliprocessor Communications Enable (explained later) 0

4 REN 9Ch Receiver Enable. This bit must be set in order to receive characters. 1

3 TB8 9Bh Transmit bit 8. The 9th bit to transmit in mode 2 and 3. 0

2 RB8 9Ah Receive bit 8. The 9th bit received in mode 2 and 3. 0

1 TI 99h Transmit Flag. Set when a byte has been completely transmitted. 0

0 RI 98h Receive Flag. Set when a byte has been completely received. 0

Additionally, it is necessary to define the function of SM0 and SM1 by an additional table:
SM0 SM1 Serial Mode Explanation Baud Rate

0 0 0 8-bit Shift Register Oscillator / 12

0 1 1 8-bit UART Set by Timer 1 (*)

1 0 2 9-bit UART Oscillator / 64 (*)

1 1 3 9-bit UART Set by Timer 1 (*)

To achieve 9,600 baud rate we simply need to set PCON.7 (SMOD).


Th1=256-((k*Oscillator frequency)/2*32*9,600)

?
?

SBUF (Serial Control, Addresses 99h): The Serial Buffer SFR is used to send and receive data
via the on-board serial port. Any value written to SBUF will be sent out the serial port's TXD
pin. Likewise, any value which the 8051 receives via the serial port's RXD pin will be delivered
to the user program via SBUF. In other words, SBUF serves as the output port when written to
and as an input port when read from.

Note: To use the 8051's on-board serial port, it is generally necessary to initialize the
following SFRs: SCON, TCON, and TMOD. This is because SCON controls the serial port.
However, in most cases the program will wish to use one of the timers to establish the serial
port's baud rate. In this case, it is necessary to configure timer 1 by initializing TCON and
TMOD.

Addressing Modes:
An "addressing mode" refers to how you are addressing a given memory location. In summary,
the addressing modes are as follows, with an example of each:

Immediate Addressing MOV A,#20h

Direct Addressing MOV A,30h

Indirect Addressing MOV A,@R0

External Direct MOVX A,@DPTR

Code Indirect MOVC A,@A+DPTR

Each of these addressing modes provides important flexibility

Interrupts:
An interrupt is a special feature which allows the 8051 to provide the illusion of "multi-tasking,"
although in reality the 8051 is only doing one thing at a time. The word "interrupt" can often be
subsituted with the word "event."
An interrupt is triggered whenever a corresponding event occurs. When the event occurs, the
8051 temporarily puts "on hold" the normal execution of the program and executes a special
section of code referred to as an interrupt handler. The interrupt handler performs whatever
special functions are required to handle the event and then returns control to the 8051 at which
point program execution continues as if it had never been interrupted.
The topic of interrupts is somewhat tricky and very important. For that reason, an entire chapter
will be dedicated to the topic. For now, suffice it to say that Interrupts can cause program flow to
change.
Setting up Interrupts:
By default at power up, all interrupts are disabled. This means that even if, for example, the TF0
bit is set, the 8051 will not execute the interrupt. Our program must specifically tell the 8051 that
it wishes to enable interrupts and specifically which interrupts it wishes to enable.
Our program may enable and disable interrupts by modifying the IE SFR (A8h):
Bit Value
Bit Name Explanation of Function
Address

7 EA AFh Global Interrupt Enable/Disable 1

6 - AEh Undefined 0

5 - ADh Undefined 0

4 ES ACh Enable Serial Interrupt 1

3 ET1 ABh Enable Timer 1 Interrupt 0

2 EX1 AAh Enable External 1 Interrupt 0

1 ET0 A9h Enable Timer 0 Interrupt 0

0 EX0 A8h Enable External 0 Interrupt 0

As we can see, each of the 8051s interrupts has its own bit in the IE SFR. We enable a given
interrupt by setting the corresponding bit.

Circuit Diagram (Block):


Used ICs:
1>AT89C51 (Microprocessor)
2>MAX232 (SerialComm.)
3>ADC7896 (ADC)
4>74LS245 (Buffer)
5>PC847 (Optical Isolator)

Program: (It will have some changes)


#include<AT89x51.h>
#include <intrins.h>
/**********************Function Definition******************************/////
delay();
clock();
anticlock();
motor_stop();
void exec();
void Initialize();
unsigned char array[2];
unsigned char rxdata;
unsigned char index=0;
unsigned char motor, temp, c,i ;
unsigned char temp;
void serial_isr();
bit rxComm;
bit Rxflag;
bit cmdflag;
unsigned int step;
void SendSerial(unsigned char x);
bit dir, Txflag ;
#define CW 0
/*********************************************************************/
//****************************Initialization part******************************//
void initialize()
{
TH1=0xFD;
TMOD=0x20;
TCON=0x40;
SCON=0x50;
IE= 0x90;
TI=1;
TR1 = 1;
motor = 0xcc ;
}

/
*****************************************************************************
******/
/**********************************Main Function*******************************/
void main()
{
initialize();
while(1)
{
if(cmdflag)
{
SendSerial(array[0]) ; // Send command + Data
while(Txflag) ; // Wait till last tx. is over
SendSerial(array[1]) ;
while(Txflag) ;
cmdflag=0;
exec(); // Execute received command
}
if (step!=0) // Move Motor
{
if (dir == CW)
{
clock();
}
else
{
anticlock() ; //Move motor anti_clockwise

}
delay();
step--;
}
else
motor_stop(); //Make motor stop
}
}
delay() //Delay function
{
unsigned int k,j;
for(k=0;k<300;k++)
{
for(j=0;j<200;j++)
{
;
}
}
} //Anti_clockwise function
anticlock()
{
motor =_cror_(motor,1);
temp = motor & 0x0F ;
P0 &= 0xF0;
P0 = P0|temp;
delay();
}

clock() //Clockwise function


{
motor = _crol_(motor,1);
temp = motor & 0x0F ;
P0&= 0xF0;
P0 = P0|temp;
delay();
}
motor_stop() //Motor stop function
{
P0=0xFF;
step = 0;
}
void exec()
{
switch(array[0])
{
case 'S': // Stop
motor_stop();
break;
case 'A': // Anticlock move
if (step == 0)
{
step=array[1];
dir = !CW ;
}
break;
case 'C': // Clock move
if (step == 0)
{
step=array[1];
dir = CW ;
}
break;
case 'R': // Read

/// read adc


break;
default:
break;

}
}

void serial_isr(void) interrupt 4 using 2 //Serial inturrpts


{
if(RI)
{
RI=0;
rxdata=SBUF;
if (!Rxflag)
{
if((rxdata=='A')||(rxdata=='C')||(rxdata=='S')||(rxdata=='R'))
{
array[index]=rxdata;
index++;
Rxflag=1;
}
}
else
{
Rxflag=0;
array[index]=rxdata;
index++;
cmdflag=1;
if(index==2)
index=0;
}
}
else
{
TI=0;
Txflag = 0 ;
}
}
/****************************************************************************
********/

void SendSerial(unsigned char x)


{
SBUF=x;
Txflag = 1 ;
}

Anda mungkin juga menyukai