Movement controlled encoder


Simple rotation control with the geared motor that has a two-phase encoder mounted on the shaft of the electric motor. During the tests I burned the 16F84A I had and for this I used a 16F628A. The program is still in the memory of a 16F84A, with the special version.


No giudico this project finished him, I still have few ideas an area where you can use it for my purposes. I did driven by curiosity when I read this thread.

AI sell begun a type of work similar to the discussion, I was able to reconstruct this project. Son was involved in backwardnessthe necessary in wanting to add some other function.

Put together the components, the video shows how the assembly is able to do its job.

The program was developed with Proton Basic, but I would say in hybrid mode, since it contains so many parts written in assembly, risparm1are for space and improve the performance of all.

It was initially written for a 16F84A in 4 Mhz, with the hope that you can also be adapted for other micro-pin compatible with the sun changes the configuration. I'm not sure that fits the Micro ENHANCED class type 16F18xx. I somehow doubt that the assembly may be different for some points.

A funny thing happened to me, It was that I did not know that the Micro I was using was from 4 Mhz and put the quartz 20 Mhz. Sometimes also could work.

Questo project uses this type of motor that counts 11 pulses per revolution of the motor, which are then reduced with a ratio 1:600 from wormgearbox. To make two laps as the forum thread, must count 13200 pulses. The calculation would be:

2 rpm x 600 x 11 = 13200.

At least that is what I can see from the report of the serial, the motor that I'm using.

Apart from the idea of ​​having 2 rounds, as in the request, capacities are much higher, allowing to count over 65500 pulses, that would be next to 10 rpm slow post.

You can think of a nut coupled to the output shaft in order to make a linear movement, which allows a resolution of 1:6600, with stop advantage without risking the reversion of motion. In fact, the reduction unit is irreversible and even if loaded 's output shaft does not turn back.

It could be used as a servant, making him do even a few degrees of movement.

The program is also suitable with another assembly and that has a different reduction ratio or d 'pulse count. It seems that we can achieve very high count rates.

The program accepts some convenient controls, that associated with another master device is able to coordinate movements for some of these projects. Having also the possibility of storing up to sixteen most common commands in the control of the EEPROM.

Such as the pointing of a satellite dish for, or door control of a chicken coop.

the scheme

Lthe same materials

It is designed to be able to save the encoder position just in time to EEPROM, when the supply voltage is missing. Allowing then to recover the data last and be able to move with good accuracy from the same point that had stopped.

The diode in the microcontroller pin is used to keep 5 Volt even during an abrupt voltage drop to the circuit, via the capacitor C3. Doing a study, I found that serve the maximum 8 ms to save one byte in EEPROM. For this case you will need to save 4 bytes. Con i 100 mF you manage to save all the data necessary to start again. But better to be generous and to avoid mistakes I chose 330 mF.

With the use of the relay it is possible to work with continuous current motors or alternating, at the expense that you may not have a speed control. In any case it is easy to assemble with little modification of a speed control and take advantage of the two outputs to enable the direction of rotation.

The software

Education firmware use


The program source is commented plenty per to help understand what has been written, and maybe, in a subsequent period usally the MAINTENANCEne.

Nell'ultima version I had to adjust a lot to be the best and per quthis che There are a lotand parts in assembly. if also considering putting the watchdog, that in If one were to stop the program at some point then, the micro is reset. In particular way to when it has been detected a loss of power, need to restart the micro after saving the data in the EEPROM.

I adopted una particular attention that the encoder count does not exceed the values ​​defined as minimum and maximum, which are DRIFT and MAXLIMIT (see below for definitions).

I commented in English, because the video is on display for the whole world and maybe useful not only inthe Italian.

In Headerxx.Inc. There are many definitions in a way that allows you to change the settings in one place without the risk of having missed any in other parts of the program. (xx It is a numbering of the version in use). Same style follows for the program name.

There are two in order to use 16F84A or 16F628A, so that you can use the entire EEPROM. This one has to choose before building.

It should be noted the two top definitions that determine a compilation in a differentiated way of hardware utilization.

The options are:


It serves to allow the button or activation contact, (in the diagram RUN) to operate in a cyclic way. This method allows you to start and stop the movement, even before reaching the software limit switch.


Determina the addition of serial communication to the TXD and RXD pins.

They are permitted any changes in the pin assignments for use with the serial, but do not recommend it. In fact, I predicted that the circuit will also assemble other micro-controllers that are pin compatible with the 18F84A.

In this way you will be able to expand the program functions and even better performance with a top class micro-controller.


It serves to swing the movement within the two limits. See the following command description.

Here it is placed the condition to exclude it from the compilation in order to activate a different option, such as the use of timers. Since there is no place to try and fit everything.


Option that allows to give a movement command to a specific position. If you are interested in using, it will be possible to exclude.


This option determines whether to use the watcdog. One option that some education costs more for greater safety, but it might prevent another option to fill in.

Other important definitions:


It serves to determine the upper limits of the encoder values.

It is useful to set it properly, After the initial tests, in order to define the midpoint value (MIDDLE)


Automatically calculated. It serves to define an initial value to be set in the EEPROM.


Value that takes into account to calculate the stop before the encoder counter exceeds a word boundary (that are 16 bit).

The case to avoid that after switching off the engine, the count continues, given the inertia in movement. So if the bill, for example, It is close to zero and continues to decline, It would lead to the point that it becomes 65535 and decreases. The reason is precisely this calculation.


A value that is used for a period of milliseconds to wait that the motor has completely stopped. If it encounters other from 'encoder pulses, then the cycle repeats.


It needs to do some verification tests in cases of encounter problems.

How to Use

First method by button controls.

A single input is provided to start the motion towards a point defined as a stop. Closing the ground contact, the program will decide the path to the farthest software limit.

As aforementioned, also already planned, the contact can stop the movement before they have reached the limit switch. You may wish to disable this feature to stop during the motion.

As soon as the contact is closed, with maybe a few milliseconds of delay, It start the movement and the LED (LED0 schema) lights for the period that the engine is running. In my experiment I used a tricolor LED, for this is blue LED0.

If it has a certain inertia before complete immobility, This LED flashes to indicate the hold phase to a standstill. Maybe it's just a little flash, when the deceleration is fast.

Arriving at the software limit switch, turns on a switch of the two LEDs. With my LED2 tricolor LED is red and LED1 is green. The green lights at the end of the position A and the red for the position B.

Doing so, ensure the motor rotation direction. Indeed, it is expected that when the encoder count decreases the motorcycle moves to the position A. Its setting command from serial letter is lowercase p.

When the encoder count increases, the motorcycle moves to the position B. Its setting command from serial letter is a capital P.

It will be important in the first phase of connection of the motor and determine the direction of rotation.

second method Serial Commands.

communication has been provided with the micro, via serial. This can be a USB-RS232 adapter is compatible with voltage levels of micro. You can also use a Bluetooth module, who may need a focus on the voltage levels of the micro. I put a voltage divider to adapt to 3,3 Volt leg RX Bluetooth module. The TX pin does not create severe problems.

It remains ready to operate also the entrance to start the movement, which determines the movement depending on the distance to the limit switches. This input can be seen in the diagram with a definition of the button RUN.

List Commands from serial

The control model is based on an initial letter followed by numbers, if it is necessary.

For this the command would be the case:


X It means a letter (miniscola or uppercase) and with n one or more digits of an integer, only positive. Any other symbol or character ends valid input, until reaching 6 handwriting input.

To complete the command are the following conditions:

  • Il command is done by 6 invalid characters, buffer completo.

  • The command terminates if you put a space or Enter when you finish.

  • A cancellation character to the left (backspace), stops feeding current.

All serial signals, stop the movement.

The reason chose to stop when it reaches a character is the fact that the periods of rest for receiving one bit is corrupted by interrupts that are needed to keep up the encoder. This causes the loss of measurement of a bit and then received is no longer valid character.

Just feels a character stops, but not ready now to receive further commands, because it takes the motor deceleration phase. Depending on how well you set the definition waitTime.

The controls without numbers are the letters A, B, S, V, O, C. With the letter V, it does not matter if sent uppercase or lowercase you will have the most relevant information.

For every letter, see the details below.

For typos, the command to delete a character (backspace) interrupts the value input.

Commands in detail from the serial:


Indifferent active motion and decreases the count of 'encoder


Indifferent activates the motion to increase the count of 'encoder.

All other characters stop the motion when launched. Per this, better to wait until the motion is stopped and re-enter the command.


In uppercase move the pointer in EEPROM of the limit switches to the first location saved. In fact, even by turning off, the data remains.

In tiny, resets the default values, the current location.

See details for N.


Dimly whether lowercase or uppercase, moves the motor to the position encoder written in the figures that follow.


Indifferent, allows the change of the value counting dell’encoder.

So you can define a new value of the encoder position.

It may help to put the count within the permissible limits and eliminate the compulsion to have moved beyond the limit. Or to correct some slippage.


Uppercase, sets the function of oscillation between the two software limit switches. Any input character stops l 'oscillation, but to remove the option you must send the command in lowercase.


Lowercase sets the limit in the count to decrease. Care must be taken to enter an appropriate value in order to be accepted. This is in dIRECTORATE that the encoder fromcrementa the count with the command A.

Shift applies to the limit opposite to. This is in dIRECTORATE that the encoder increments the count with the command B.


Command to change the position of the EEPROM memory. It accepts one or due figures, sand greater then is chosen the highest available memory. By doing so it uses a different limitation of limit switches.


Much like the P command, only that you order to save the current position of the counter, why there are no numbers following the letter. Useful to see the current location is close to the limit and then you establish that as a valid. If the letter is tiny you'll want to save for side A, admitted consistent with the values ​​entered.


Optional, sacrificing other options, as the watchdog, oscillation and the command G. You can also fill out this option.
Indifferente, You are used to start an output with a timer. In this case, the first digit indicates which of the two timers use. Considering that 0 It will refer to the side A and 1 It will be the B-side. You agree to follow up to 9999, which can be seconds or less if you vary the definition of MAXTICK. This serves to count the 5 ms timer0, then it is by default set to 200, so that you get a minute.


Indifferent, displays information relating to the limit values ​​and dell’encoder, plus the EEPROM location number.

End Command Message:

At the end of each command is an information message. The program memory is the limit, should not make changes need, without knowing how.

The message by are “OK” If everything is done right, or “ERR n” if there was an operation error.
Per n There is an explanation of possible error. See the list below.


Report that tries to move beyond the default limits (OPERATION o MAXLIMIT)


The value entered is out of the lower limits, determined by the limit switches and the median position of the stroke. (In fact, there is a MIDDLE which is the median value)


The input value is outside the upper limits, MIDDLE and determined between the upper limit.


The value must be above MIDDLE


The value must be in the MIDDLE


The first character sent is invalid, perhaps corrupt.


The location you are trying to write in EEPROM is not correct

Active commands by filling without RS232

You can also fill out the option of using the serial.

For the trial was expected to use the command pulse with a single button with divese functions.

The functions are added in the program OneButton.Inc which can use a cadence of the periods measured by the Timer0, also used to flash the LED. This frequency determines the valid period for the press of the button, to filter out any mechanical vibrations pulse.

There is a possibility to set a time delay by software, which unfortunately does not allow the 'use of the LED flash during operation. I would say, do not change these parts.

Not all features are enabled, allowing you to keep the program in just over 600 machine instructions. It uses only the definitions useful for this program, although the program OneButton.Inc it offers some other.

Let those that are active:


Used to save in EEPROM, in the program phase.

Or to move in a direction, the program chooses the most distant. It is also to stop the motorcycle (if you use his option).

Double click

It used to start and end the programming phase. You can avoid saving in EEPROM when pressed a second time without having given a click for storing. The limits will be valid only in RAM. They are not saved in EEPROM.

Long Pressure

Used to move in the direction A, during the programming phase. The limit switch is placed at the maximum defined with DRIFT.

Click and short

long press

Used to move in the direction B, during the programming phase. The limit is set to the maximum. The limit switch is placed at the maximum defined with MAXLIMIT.

With these possibilities you can think of programming the limit positions with the sequence which requires a double click to start the programming phase. The LED0 (blu) flashes rapidly. At that point you will be able to act to move the motor in the stop position. With a long press it will start to move toward the limit A. When you release the button will store in the RAM limit. It should, however, move from the midpoint checkpoint necessary.

Similarly you can do for the other direction of rotation, the command which in this case will be a click followed by a long press, kept low. When the pressure will be long enough the engine will start the movement in the direction B, staying in motion as long as you hold the button down. You should then run the command after the completion of the first. In this case it will hold until it reaches the desired limit.

At this point there will be limits stored in RAM, but that they can always change them by repeating the 'operation. To make definitive you can save them in EEPROM with a command of a simple click.

This click will not take effect during the period d 'taxtion which is bordered by a sequence of double-clicking, or aO double beginning andO double after programming.

summing up, it is noted that in the phase of programming commands are initiated and are concluded with the double click. Outside of which do not take effect. With the exception of clicks it takes to start the motorcycle.

You can download the package and / or see the video


Use the project involves responsibility, that the 'author assumes to cause damage to persons or property.

0 replies

Leave a Reply

Want to join the discussion?
Feel free to contribute!

Leave a Reply