-Tutorial by Rui Santos, RandomNerdTutorials
(Edited by TechToast)
Today I’ll show how you can control a servo with Visual basic. Before this project I’ve never used Visual basic so if anyone finds any mistake in my code please leave a comment here and help me improve it.
I’ve always used the Serial Monitor of the Arduino IDE to communicate with the Arduino, but today we will use a visual basic program that I’ve created. Basically in the VB program we have 4 buttons that will interact with the Arduino when we press them.
I’ll be showing a program in Visual Basic that allows the user to rotate a servo attached to the Arduino. You need to make 3 connections from the servo to your arduino:
- Red: 3.3V (depends on your Servo motor)
- Brown: Ground
- Orange: Digital Pin 9
Parts required
You can use the preceding links or go directly to MakerAdvisor.com/tools to find all the parts for your projects at the best price!
Upload the Arduino code below
/*
* Control a servo motor with Visual Basic
* Created by Rui Santos, https://randomnerdtutorials.com
*/
#include <Servo.h>
Servo myservo; // create servo object to control a servo
void setup()
{
myservo.attach(9); // attaches the servo on pin 9 to the servo object
Serial.begin(9600); //begins serial communication
}
void loop()
{
int pos;
if (Serial.available()){
delay(100);
while(Serial.available()>0){
pos=Serial.read(); //reads the value sent from Visual Basic
if(pos=='0')
myservo.write(90); //rotates the servo 90 degrees (Left)
else if(pos=='1')
myservo.write(-90); //rotates the servo 90 degrees (right)
else if(pos=='2')
myservo.write(180); //rotates the servo 180 degrees (Left)
else if(pos=='3')
myservo.write(-180); //rotates the servo 180 degrees (right)
}
}
}
Run the Visual Basic script
Click here to download the Visual Basic Script
NOTE:
- When you’re using the Visual Basic Program the Serial monitor on the Arduino IDE must be closed
- You need to match the com port on your Visual Basic Code to the right com port you’re Arduino is using
I don’t know why, but YouTube cropped my video, the tast two buttons are “Rotate 180º Left” and “Rotate 180º right” .
Watch the video demonstration
Thanks for reading, you can contact me by leaving a comment. If you like this post probably you might like my next ones, so please support me by subscribing my blog and my Facebook Page.