VBA Communication with Arduino

Hi,
I'm trying to control an Arduino via Excel VBA using the MSCOMM control

The following sketch accepts serial input, and controls the brightness of a led

It works fine when data is entered via a serial monitor

int  outPort=3 ;
char buffer[8] ;
char character ;
int  nBright = 0 ;
int  i=0;
char digit ;

void setup()
{
  Serial.begin(9600) ; // set up the serial monitor
  pinMode(outPort,OUTPUT);
}

void loop() 
{
  i=0;
  
//  Serial.flush(); // clear any 'junk' out of the serial buffer before waiting
  while (Serial.available() == 0)
  {
    // do nothing until something enters the serial buffer
  } 
  while (Serial.available() > 0)
  {
   nBright = Serial.parseInt();
  }
  
  Serial.print("You entered: ");
  Serial.println(nBright);
  Serial.flush();
  
  // Control the brightness of a LED attached to Outport
  // First make sure the number is 0-255
  
  if(nBright < 0){nBright=0;}
  if(nBright >255){nBright=255;}
  
  analogWrite(outPort,nBright) ;

The following VBA code sends the number (0-255) in a TextBox to the Arduino (the D13 led flashes) , but the LED I want to control is not activated.

Private Sub CommandButton1_Click()
   ' Buffer to hold input string
   Dim Instring As String
   ' Use COM13
   MSComm1.CommPort = 13
   ' 9600 baud, no parity, 8 data, and 1 stop bit.
   MSComm1.Settings = "9600,N,8,1"
   ' Tell the control to read entire buffer when Input
   ' is used.
   MSComm1.InputLen = 0
   ' Open the port.
   MSComm1.PortOpen = True
   ' Send the data to the port
   
   data = TextBox1.Text  ' The brightness required, 0-255
   Debug.Print "Data=" & data
   
   ' Send the data to the Arduino.
   
   MSComm1.Output = data & vbCrLf
   
' Close the Port
 
   MSComm1.PortOpen = False
End Sub

Any thoughts ?

Moderator edit:
</mark> <mark>[code]</mark> <mark>

</mark> <mark>[/code]</mark> <mark>
tags added.

   MSComm1.PortOpen = True
   ' Send the data to the port
   
   data = TextBox1.Text  ' The brightness required, 0-255
   Debug.Print "Data=" & data
   
   ' Send the data to the Arduino.
   
   MSComm1.Output = data & vbCrLf
   
' Close the Port
 
   MSComm1.PortOpen = False

Open the port, resetting the Arduino. Immediately, jam some data out, before the Arduino is done resetting. Then, close the port, resetting the Arduino again. Then, wonder why the Arduino doesn't use the data.

Well, I know why it doesn't.

I humbly apologise o mighty one, I should have said I'm new to this. Didn't realise opening and closing the port resets the Arduino.

Can anyone suggest a civilised way of handling this ?

1 Like

OK I've solved the problem

Thank you all for your help

I am glad you solved it... but for the other newbies, could you share your solution :stuck_out_tongue: