Go Down

Topic: Arduino VB serial communication  (Read 1 time) previous topic - next topic

Leo12468

I want to send 4 digit numbers from a VB programm to an arduino and controll a motor with it.
That's my code, but it doesn't work.


VB Code:

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"
        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 ButtonON_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles ButtonON.Click

        Dim data As String
        Dim RPM1 As Double = RPM1 + 1
        Dim StartWinkel1 As Double = StartWinkel1 + 1
        Dim StopWinkel1 As Double = StopWinkel1 + 1

        SerialPort1.Open()
        data = ("R<RPM1>P<StartWinkel1>T<StopWinkel1>E")
        SerialPort1.WriteLine(data)
        SerialPort1.Close()
        data = 0

Lewis-H

/*
 * 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)     
    }
  }
}

Use this code if your motor is a servo motor. Hope this helps you!

Regards,
Lewis

Go Up