I am pretty sure this is a faq but how can I control a servo using inputs from the serial monitor with serial.read()?
I have spent the last two days and nights trying to figure this out. I understand enough now to know that if I enter in a number into the serial input, it reads as a numerical value with atoi (i.e. '9' serial is 9 integer). Now I'm having the issue of being able to get angles with a numerical value larger than the tens or hundredth place.
I still do not understand how to have Serial.read() the value '999' as 999 integer or '39' as 39 integer.
I've tried modifying and using this tid bit here but is giving me undesired values such that if I enter in 129. It enters (Serial.print) 1 on first line, 12 on 2nd line and 129 on 3rd line. I just want to have '129' be 129 to set the angle to 129.
Here's the code. A different approach I figured out was to define the serial read to be a character value which can then just converted straight to integer if it's a numerical value.
int numFromPort;
void setup(){
Serial.begin(9600);
}
void loop()
{
numFromPort = 0;
while(Serial.available() > 0)
{
char inChar = Serial.read();
if(inChar >= '0' && inChar <= '9')
{
numFromPort = numFromPort*10 + (inChar - '0');
}
Serial.println(numFromPort);
}
// numFromPort now contains the data read from the port, as an integer
}
The problem still remains where it prints 1, 12, and 129. I know that the serial.read has to read the number in queue one after the other and not all at once but I want just the "final" number to be what the angle should set to be is.
My criteria for a servo program is
*pushbutton is pressed for the first time, servo should go to center of its range of motion and on serial monitor display "System active" followed by something like "please enter in an angle between 0 and 180".
*after the system is "activated" the user can enter in a value into the serial and the servo will set to that angle from 0 - 180. any other value should display an error message on the serial
*if pushbutton is pressed a 2nd time or 999 is entered into the serial monitor, the system displays "system deactivated" and turns off the program until push button is pressed again.
If anyone has a code similar to this criteria, can you help me? I thought this was going to be simple and ends up that I spend friday, saturday and sunday working on this and still don't understand a lot of the c language. I'm still somewhat a beginner but I am trying to learn but a lot on the internet on c language on arrays, atoi, char is foreign to me.