Hi, I have an Arduino being controlled by a VB program, and also the Arduino sending data to VB. The problem is, it sends data too fast, so I had to use a delay, but this in turn delays the rest of my code which is problematic.
So I guess is there a way to have 2 loops running? 1 so I can send data over serial and one to receive it? Or is there some other way to delay it without delaying the rest of the code?
Hmm, strange, doesn't seem to have fixed the problem.
What I am doing is having the Arduino read from an analog input, and send that to VB. When I open the port in VB to the Arduino, I get either "Overflow" or "Type Mismatch". I have found adding a delay in the loop fixes this, as I think the Arduino is trying to send data before it is ready, but that delay effects the rest of my loop. Here is my current code that works, but has the delay problem:
int pres = 0;
void setup(){
Serial.begin(115200);
pinMode(12, OUTPUT);
}
void loop()
{
pres = analogRead(0);
pres = pres; //*10 for pressure sensor
Serial.print(pres);
delay(250);
char c, t;
int nnn;
if(Serial.available() > 0) // If there is data to read
{
c = Serial.read(); // Get a character
delay(10);
if(c >= 'a' && c <= 'z') // If it's a command
{
nnn = 0;
while(Serial.available() > 0) // While there is still data
{
t = Serial.read(); // Read next character
if(t == ',' || t == ' ')
continue; // Skip commas and spaces
if(t >= '0' && t <= '9') // If it's a number
{
nnn *= 10; // Multiply previous value by 10
nnn += t - '0'; // Add the new digit
}
else
break;
delay(10);
}
}
}
// Now, do something with c and nnn
switch(c)
{
case 's':
analogWrite(3,nnn);
break;
case 'f':
analogWrite(6,nnn);
break;
case 'u':
if (nnn > 100){
digitalWrite(12, HIGH);
}
if (nnn < 100){
digitalWrite(12, LOW);
}
break;
case 'r':
analogWrite(9,nnn);
break;
case 'g':
analogWrite(10,nnn);
break;
case 'b':
analogWrite(11,nnn);
case 'a':
analogWrite(3, nnn);
analogWrite(6, nnn);
analogWrite(9, nnn);
analogWrite(10, nnn);
analogWrite(11, nnn);
digitalWrite(12, LOW);
break;
// Add other letters here, with break after each one
}
}
And a snippet of the VB code for receiving:
Case comEvReceive ' Received RThreshold # of chars.
serin = MSComm1.Input
inbox.Caption = serin
pres.Caption = serin & "hPa"
presbar.Value = serin
Debugging shows that the type mismatch occurs on the last line of that VB code where it is putting the value onto a slider, though the overflow is shown all over the place where received data is displayed.
Try doing some sort of handshake between the two sides.
Have the arduino check for (say) a ? Sent from vb before it sends the data - this will stop the overflow. Have the arduino frame the data it's sending to vb with(say) a [ at the beginning and a ] at the end. Vb should ignore anything that doesn't look like that just wait a bit, flush it's buffers and send ?