Forum Rule: Always post complete source code & details to reproduce any issue!
Results 1 to 5 of 5

Thread: Can I look at last byte in serial buffer?

  1. #1

    Can I look at last byte in serial buffer?

    T4.1 project here.

    I'm expecting a serial packet, packet length can vary, and can be > 100 bytes (will have to adjust buffer size).

    I'm polling, so I don't want to process the packet until I receive all the bytes. The 2 last bytes are 0x0D 0x0A.

    Can I query the buffer to look at the last byte or two?

    Or should I be loading the incoming bytes into a separate array, then I can index those bytes?

    Thanks.

  2. #2
    Senior Member
    Join Date
    Aug 2013
    Location
    Gothenburg, Sweden
    Posts
    398
    Serial.peek() ??

    Sorry that's the first, you probably have to read them as they come in to a buffer and process the when them end markers arrive

  3. #3
    Senior Member
    Join Date
    Dec 2016
    Location
    Montreal, Canada
    Posts
    3,666
    use Circular_Buffer to queue serial bytes, you can easily peek() into the queue at any position:

    buffer.peek(7) // checks the 8th byte in the queue

  4. #4
    Senior Member manicksan's Avatar
    Join Date
    Jun 2020
    Location
    Sweden
    Posts
    270
    Your can use a simple buffer as in this post (#29)
    https://forum.pjrc.com/threads/66086...l=1#post268825
    And when you have received 0x0a (LF or '\n')
    You just check the last byte like this
    Code:
    void setup() {}
    
    void readAndPrintLine() {
     static char buf[80];
     static unsigned idx = 0;
    
     while (Serial.available())
     {  
      char c = Serial.read();
      buf[idx] = c;
      idx++;
      buf[idx] = '\0'; 
      if ( (c == '\n') || (idx >= sizeof(buf) -1) ) {    
        if (buf[idx-3] == charToLookFor) {
      
        }
        idx = 0;
      }
     }
    }
    
    void loop() {
      readAndPrintLine();
    }

  5. #5
    Circular_Buffer is the one I'm now using. Makes it really easy.

Posting Permissions

  • You may not post new threads
  • You may not post replies
  • You may not post attachments
  • You may not edit your posts
  •