Pages: [1]   Go Down
Author Topic: Why do you need delay  (Read 462 times)
0 Members and 1 Guest are viewing this topic.
Offline Offline
Newbie
*
Karma: 0
Posts: 5
View Profile
 Bigger Bigger  Smaller Smaller  Reset Reset

Hi I am doing a learning project using arduino ATMEGA1280 and a LED and a small 1.5V motor. Essentially I wanted to see how I can send serial commands from VB.net and read that series of commands in Arduino and execute the commands. Here is what I did:

VB:
When you press a button on the form and a checkmark is ticked (or not ticked) following gets executed:

Try
            With serialPort1
                .PortName = "COM19"
                .BaudRate = 9600
                .Parity = IO.Ports.Parity.None
                .DataBits = 8
                .StopBits = IO.Ports.StopBits.One
                .DtrEnable = True
                .RtsEnable = True
                .ReceivedBytesThreshold = 1
                .Encoding = System.Text.Encoding.ASCII
                .NewLine = Chr(13) + Chr(10)
            End With
            serialPort1.Open()
            serialPort1.DiscardInBuffer()
Dim command As Byte()
Dim curspeed As Integer
command = {1, curspeed, 41}
serialPort1.Write(command, 0, command.Length - 1)

''''''''''''''''' {1, curspeed, 41} = {status of the LED=0 or 1, PWM speed for motor(0 to 255), end of command character}

Arduino:
void loop()
if (Serial.available()>0)  {
     
        light=int(Serial.read());
        delay(100);
 
        curspeed=int(Serial.read());
 
        temp=Serial.read();
 
        }
                 
   if (light==1)  digitalWrite(52, HIGH); // there is a LED on pin 52
        if (light==0)  digitalWrite(52, LOW);
        analogWrite(9, curspeed); //PWM pin9 is used to drive the motor
    }
}

My question is:
If i dont use the delay(100) command after the "light=Serial.read();" line, this program doesnt work and "curspeed" gets a value of 255. This only works with a delay of any value put between the two Serial.read() commands. Why is this the case?

Also, if someone can point me to the maze of how these serial communications work, i would appreciate it very much. I am quiet confused as to the formats VB and arduino talk to each other in. I beleive VB is sending integers/characters and arduino is reading bytes and then converting them to integers or characters. I need to understand the serial communications protocols properly. Help is highly appreciated.

Cheers
Omi
Logged

Offline Offline
Newbie
*
Karma: 0
Posts: 5
View Profile
 Bigger Bigger  Smaller Smaller  Reset Reset

I found this on serial communications fundamentals
http://jhaskellsblog.blogspot.com/2011/05/serial-comm-fundamentals-on-arduino.html
Logged

Global Moderator
Boston area, metrowest
Online Online
Brattain Member
*****
Karma: 435
Posts: 23601
Author of "Arduino for Teens". Available for Design & Build services. Now with Unlimited Eagle board sizes!
View Profile
WWW
 Bigger Bigger  Smaller Smaller  Reset Reset

You check if there is 1 byte available to read, and then you read. 3

Code:
if (Serial.available()>0)  {  //<<<< try changing from ">0" to  ">2"
      
        light=int(Serial.read());
        delay(100);
 
        curspeed=int(Serial.read());
  
        temp=Serial.read();
Logged

Designing & building electrical circuits for over 25 years. Check out the ATMega1284P based Bobuino and other '328P & '1284P creations & offerings at  www.crossroadsfencing.com/BobuinoRev17.
Arduino for Teens available at Amazon.com.

Offline Offline
Newbie
*
Karma: 0
Posts: 5
View Profile
 Bigger Bigger  Smaller Smaller  Reset Reset

ahhh .... i see what maybe happening ... so the read commands should wait till all the three commands in the sequence are in the serial buffer and then read them sequentially. Is that correct? Also, i guessed as much but just to confirm: once you read a byte from the buffer using Serial.read(), that byte is pushed off the list?
Logged

Global Moderator
Boston area, metrowest
Online Online
Brattain Member
*****
Karma: 435
Posts: 23601
Author of "Arduino for Teens". Available for Design & Build services. Now with Unlimited Eagle board sizes!
View Profile
WWW
 Bigger Bigger  Smaller Smaller  Reset Reset

Wait for 3, yes.
Or check that 1 is available prior to each read.
Once read, are gone, yes.
Logged

Designing & building electrical circuits for over 25 years. Check out the ATMega1284P based Bobuino and other '328P & '1284P creations & offerings at  www.crossroadsfencing.com/BobuinoRev17.
Arduino for Teens available at Amazon.com.

Seattle, WA USA
Offline Offline
Brattain Member
*****
Karma: 547
Posts: 45982
Seattle, WA USA
View Profile
 Bigger Bigger  Smaller Smaller  Reset Reset

Quote
so the read commands should wait till all the three commands in the sequence are in the serial buffer and then read them sequentially.
That's one possibility.

Quote
Or check that 1 is available prior to each read.
That is another possibility.

However, both approaches rely on serial communication being 100% successful. Serial data delivery does not follow the UPS delivery guarantee (they guarantee to deliver your package). Instead, it follows the USPS delivery guarantee (the guarantee to try to deliver your package).

Serial data CAN get lost or corrupted. You need to consider this possibility, and plan for it happening.

If you send three values, for an RGB LED, for example, r, g, and b, and g gets lost, the LED will be lit using r1, b1, r2, then b2, g2, r3, then g3, r3, b4. Not a good thing.

If you send [, r, g, b, and ], then a lost value will be more easily recognized.
Logged

'round the world...
Offline Offline
Faraday Member
**
Karma: 41
Posts: 3097
View Profile
WWW
 Bigger Bigger  Smaller Smaller  Reset Reset

If you send [, r, g, b, and ], then a lost value will be more easily recognized.

You can also throw in a checksum just to be sure too. smiley-wink
Logged

Eu não sou o teu criado. Se respondo no fórum é para ajudar todos mediante a minha disponibilidade e disposição. Responder por mensagem pessoal iria contra o propósito do fórum e por isso evito-o.
Se realmente pretendes que eu te ajude por mensagem pessoal, então podemos chegar a um acordo e contrato onde me pagas pela ajuda que eu fornecer e poderás então definir os termos de confidencialidade do meu serviço. De forma contrária toda e qualquer ajuda que eu der tem de ser visível a todos os participantes do fórum (será boa ideia, veres o significado da palavra fórum).
Nota também que eu não me responsabilizo por parvoíces escritas neste espaço pelo que se vais seguir algo dito por mim, entende que o farás por tua conta e risco.

Dito isto, mensagens pessoais só se forem pessoais, ou seja, se já interagimos de alguma forma no passado ou se me pretendes convidar para uma churrascada com cerveja (paga por ti, obviamente).

Offline Offline
Newbie
*
Karma: 0
Posts: 5
View Profile
 Bigger Bigger  Smaller Smaller  Reset Reset

Thanks a lot everyone ... here is what I am trying to make and based on the feedback I got the bot moving yesterday ... here is first few trials...
http://www.youtube.com/watch?edit=vd&v=XyV2hLJiTOY
Logged

Pages: [1]   Go Up
Jump to: