[Project 22] – Arduino & C# Servo Motor Control

In this project,we will do the servo motor control through the application we created with C # (Visual Studio). During this project, we used 5 different objects which are ComboBax, Button, Trackbar, Serialport and 6 Labels to create form in C#. You can control much more servo motor by adding more Trackbar. To run the application you should choose the correct port.

Interface and Circuit:


Arduino-c#-servo-control-serial-communication-visual-stduio-1

 

Materials:


Arduino Uno/Mega  x1
Servo Motor  x1
Jumper Cable

 

Arduino Program:


#include <Servo.h>

Servo servoMotor;
int servoPin=13;
int value=0;
int angle;
int x;

void setup(){
  Serial.begin(9600);
  servoMotor.attach(servoPin);
}

void loop(){
  if(Serial.available() >0) 
  {
    value = Serial.read();
    if(value>0){
      x=value;
    }
  }
  else if (x>=0 && x<=180){
    angle=x;
    servoMotor.write(angle); 
  }
}



 

C# Program:

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;
using System.IO.Ports;

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

        private void button1_Click(object sender, EventArgs e)
        {
          
            serialPort1.PortName = comboBox1.Text;
            serialPort1.Open();
           
        }

        private void Form1_Load(object sender, EventArgs e)
        {
            comboBox1.DataSource = SerialPort.GetPortNames();
        }

        private void trackBar1_Scroll(object sender, EventArgs e)
        {
            
            if (serialPort1.IsOpen == true)
            {
                
                int PWM = trackBar1.Value;
                label2.Text = trackBar1.Value.ToString();
            
                byte[] b = BitConverter.GetBytes(PWM);
                serialPort1.Write(b, 0, 4);
                
            }
      }
  }
}

 

Interface Design:


Arduino-c#-servo-control-serial-communication-visual-stduio



You may also like...