Page 293 - Programming Microcontrollers in C
P. 293
278 Chapter 5 Programming Large 8-Bit Systems
new_speed = 10*new_speed + new_character-’0';
else if(new_character==’\r’)
{
/* reject any number out of range */
/* and start over again */
if(new_speed>=1000 && new_speed<=10000)
motor_speed=new_speed;
new_speed=0;
}
else
new_speed=0; /* reject everything else */
}
The variable new_speed is initialized to 0 outside of this portion
of the program. If the input character is a number (a number is any
character that lies between ‘0’ and ‘9’), it is converted from a character
to a number when the character ‘0’ is subtracted from it. This value
is added to ten times the value stored in new_speed , and the result
is saved in new_speed . Repeated executions of this code sequence
will convert a series of ASCII character numbers to an appropriate
unsigned integer value. The entry sequence is terminated when a
nonnumber character is received. If this character is a line terminator
(a carriage return escape character in this case), the new speed value
is put into motor_speed to cause the motor to change to the new
value, and new_speed is reset to zero to await for the next input.
If any other character is received, the data saved in new_speed is
lost, and the whole entry of a new speed into the system must be
repeated from the beginning.
In Listing 5-7 there was a lonely line of code
/* input the new motor speed */
That line has been replaced by the above and entered into Listing
5-8. The new motor speed input is placed in the main loop of the
applications program, so a test is made each time through the loop to
determine if there is a new input from the serial port. This routine
also sends out the current speed of the motor once each half second.
This output is controlled by the parameters tick1 and in_process.
tick1 is set to TRUE each half second, and if in_process is
FALSE the motor speed is calculated and sent to the serial port output.