Hi, I just recently got an Arduino Mega2560 and after spending hours messing with the serial communication I finally got it to work. Now I just need Visual Basic to send a PWM value over serial to the Arudino to control an LED. Only problem is, I keep getting an error that access to the serial port is denied (A first chance exception of type 'System.UnauthorizedAccessException' occurred in System.dll).
I have a program I wrote in order to test the serial with VB that seems to work fine.
Public Class Form1 Private Sub Button1_Click(sender As System.Object, e As System.EventArgs) Handles Button1.Click Try SerialPort1.Open() SerialPort1.Write(TextBox1.Text) SerialPort1.Close() Catch ex As Exception MsgBox(Err.Description) End Try End Sub Private Sub Form1_Load(sender As System.Object, e As System.EventArgs) Handles MyBase.Load SerialPort1.Close() SerialPort1.PortName = "com3" 'change com port to match your Arduino port SerialPort1.BaudRate = 9600 SerialPort1.DataBits = 8 SerialPort1.Parity = Parity.None SerialPort1.StopBits = StopBits.One SerialPort1.Handshake = Handshake.None SerialPort1.Encoding = System.Text.Encoding.Default 'very important! End Sub End Class
But when I try to call this method in another program to write the serial value when a slider is moved I get the error. Sometimes I will be able to get a few slides in with no error, and other times I get it right away. It seems almost random.
Private Sub SendSerialValues(redVal As Integer, greenVal As Integer, blueVal As Integer) Label2.Text = ("Serial Write: " & redVal.ToString.PadLeft(3, "0")) 'For debugging only Dim LedSerial As New SerialPort LedSerial.Close() LedSerial.PortName = "COM3" 'change com port to match your Arduino port LedSerial.BaudRate = 9600 LedSerial.DataBits = 8 LedSerial.Parity = Parity.None LedSerial.StopBits = StopBits.One LedSerial.Handshake = Handshake.None LedSerial.Encoding = System.Text.Encoding.Default 'very important! Try LedSerial.Open() LedSerial.Write(redVal.ToString.PadLeft(3, "0")) LedSerial.Close() Catch ex As Exception MsgBox(Err.Description) End Try End Sub