Tuesday, March 2, 2010

Controlling a Servo attached to an Arduino via Visual Basic.NET or C#.NET

Here is an example of using VB.NET to control a servo via serial port that is attached to an Arduino board.

Attach the servo to ground, 5v and digital pin 9.

My Arduino code is also outputting to a parallel LCD. If you do not have an LCD attached you can remove those lines.

As you can see in the picture I also have the WiiChuck adapter attached. I will demonstrate the use of this adapter in a future post.

Visual Basic.NET Code:



Public Class Form1

Private serialPort As New IO.Ports.SerialPort

Private Sub Form1_Load(ByVal sender As System.Object, _
ByVal e As System.EventArgs) Handles MyBase.Load

Try
With serialPort
.PortName = "COM3"
.BaudRate = 9600
.Parity = IO.Ports.Parity.None
.DataBits = 8
.StopBits = IO.Ports.StopBits.One
End With

serialPort.Open()
serialPort.Write("0s")

Catch ex As Exception
MsgBox(ex.ToString)
End Try

End Sub

Private Sub TrackBar1_Scroll(ByVal sender As System.Object, _
ByVal e As System.EventArgs) Handles TrackBar1.Scroll
serialPort.Write(TrackBar1.Value & "s")
End Sub

End Class

C#.NET Code:



using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;

namespace WindowsFormsApplication1
{
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}

private void trackBar1_Scroll(object sender, EventArgs e)
{
serialPort1.Write(trackBar1.Value + "s");
}

private void Form1_Load(object sender, EventArgs e)
{
serialPort1.Open();
serialPort1.Write("0s");
}
}
}

Arduino C/C++ Code:



#include <servo.h>
#include <liquidcrystal.h>

Servo myservo;

int servoPosition = 1;

LiquidCrystal lcd(12, 11, 5, 4, 3, 2);

void setup() {
lcd.begin(16, 2);
lcd.print("Position Data:");
myservo.attach(9);
Serial.begin(9600);
}

void loop() {

static int val = 0;
lcd.setCursor(0, 1);

if(Serial.available()) {

char ch = Serial.read();

switch(ch) {
case '0'...'9':
val = val * 10 + ch - '0';
break;
case 's':
myservo.write(val);
lcd.print((float)val);
val = 0;
break;
}

}
}

3 comments:

Laimonas said...

Thank you very much for sharing this with us i was looking this for ages

Anonymous said...

Awesome Project.

Please send me the C# source code for Visual Studio.

E-mail address: riaan.deyzel@live.co.za

Thank you.

mas kadi said...

me too.. i need visual at desain visual basic. please send file vb.net in masjawa16@gmail.com
thanks for information

Post a Comment