The motor speed and direction is controlled by a single pot. If it is in the middle position the motor is stopped. Moving from this position towards the upper end (see schematic) increases the motor speed in the forwards direction, which moving towards the grounded end increases the one in the backwards direction.
To control the motor speed we use PWM as in the previous experiments. The PIC reads the voltage coming out of the pot, which is in the range 0..5V, and redirects it to a built-in ADC with a 10-bit resolution. In this case, however, its two lower bits are ignored. The range of ADC values (0..255) is splitted into two parts: 0..127 and 128..255. If the voltage is in the second range, the motor rotates forwards (and backwards otherwise).
The ADC value is used to set up the duty cycle ratio of the PWM running at 244Hz. The low frequency is chosen to improve the motor efficiency. The PWM resolution in this case is 10 bits, out of which just 8 higher ones are used to simplify the code. If the ADC value v is in the range 0..127, it is updated as 128-v, otherwise it is updated as v-128. The obtained value is then multiplied by 2 by using the left shift operation to match the maximum value 255 used for the PWM period. This way we get a number in the range 0..254 which is used to setup the PWM duty cycle ration. Thus, we will get only 127 different PWM values, corresponding to a 7-bit resolution. This is more than sufficient for a smooth motor control. PIC pins RC3 and RC4 are used to control the motor direction. Their binary values must be complimentary, i.e. 10 or 01, corresponding to two rotation directions. This is needed for a correct operation of the L293D buffers. Those buffers introduce approx. 0.7V voltage drop, which suits very good to the normal working conditions of my 3V motor.
Download Source Code (PIC Microcontroller)