Control A Servo Motor With Visual Basic
Control A Servo Motor With Visual Basic
Code vb.net
Imports System.IO
Imports System.IO.Ports
Imports System.Threading
Public Class Form1
Shared _continue As Boolean
Shared _serialPort As SerialPort
Private Sub Form1_Load(ByVal sender As System.Object, ByVal e As
System.EventArgs) Handles MyBase.Load
SerialPort1.Close()
SerialPort1.PortName = "com6" 'you need to check which com port your
arduino is using, and change them if you need
SerialPort1.BaudRate = 9600
SerialPort1.DataBits = 8
SerialPort1.Parity = Parity.None
SerialPort1.StopBits = StopBits.One
SerialPort1.Handshake = Handshake.None
SerialPort1.Encoding = System.Text.Encoding.Default
End Sub
Private Sub btn90L_Click(ByVal sender As System.Object, ByVal e As
System.EventArgs) Handles btn90L.Click
SerialPort1.Open()
SerialPort1.Write("0")
SerialPort1.Close()
End Sub
Code arduino
#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)
}
}
}