NOTE: The code included AND mentioned in the comments will still work in 2021 - however not all parts are necessary. For example the very "weird" for loop that seems to do nothing was fixing a bug back when this tutorial was first posted. Keep that in mind :)
One of things people want to do with Arduino is controlling things with serial monitor. Here are some command project uses:
myservo.write(); - Sends a position information to the servo
if(Serial.availiable()) - If serial monitor is available, then continues the loop between { and }
intstate=Serial.parseInt(); - sets "state" to number, that has been sent to serial monitor
More about parseInt - reads every number, sent to the serial monitor. It can read only numbers, not letters etc.
Important - Servo coding in this project is a bit different:
10 degrees = 0 degrees
90 degrees = 90 degrees
169 degrees = 180 degrees
You may be saying. "What? That doesn't make any sense" Well, yes and no at the same time. Some servos cannot read properly and will take 170 as 180°- depends on the speed and quality.
🛠️ เจาะลึกเบื้องหลังการทำงาน (Deep Dive / Technical Analysis)
The Serial Monitor isn't just for reading errors; it is a powerful two-way communication tool. By typing commands into your PC, you can make the Arduino execute complex, precise physical actions.
Parsing the Serial Data
When you type the number 90 into the Serial Monitor and press Enter, the Arduino doesn't see a number—it sees the ASCII characters for '9' and '0' and a newline character (\n).
- The Check: The code uses
if(Serial.available() > 0)to wait for incoming data. - The Extraction: The
Serial.parseInt()function is magic—it strips away the text formatting and extracts the actual integer value (90). - The Action: The Arduino limits the value (ensuring it's between 0 and 180) and sends it directly to the servo:
myServo.write(angle);.
Required Hardware
- Arduino Uno/Nano.
- Micro Servo (SG90 or MG90S).
- USB Cable: This acts as the communication link.
Beyond the Basics
Once this code works, you no longer need the Arduino Serial Monitor. You can use Python (via the pyserial library) or C# to write custom desktop applications with sliders and buttons that talk directly to your robotic arm!