Can you comment on this Serialport code?

Pages: 12
There is only one byte to send to the PC so no need for start or end byte I think.

I decided to go back to basics. I think my biggest problem and why the simplest solution did not work is that I am NOT WAITING for the reply. I couldn't figure out why I did not get a symmetrical response to my request. If I request x, I should get x,x1,x2,255-x. This escalated into sending multiple requests and a soup of bytes in the stream that I need to fish out data from and only with an id. So here is my latest attempt and I am getting symmetrical response to my request.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
uint16_t sendno(uint8_t x){
  uint8_t buff[4]={0};

  //Read all in buffer to clear it
  while (Serial.available())
    Serial.read();

  //Send the request
  Serial.write(x);

  //Check if there is a reply
  long stime=millis();
  
  do {
     
     delay(1);
     
     if ((millis()-stime) > 50)  // I am going to have to fine tune this
        break;
  } while (Serial.available() <4);   

  if (Serial.available() ==4 )
         Serial.readBytes((&buff[0]),4);

 
  return Decode((uint16_t) ( buff[1]+(buff[2]<<8) ) );

} 


I am not even checking for x or 255 - x . And I can see on the PC side console output that there is exactly one request for each data byte.

I am thinking that I will reduce the size of the data transfer from the PC to the arduino to two bytes as I don't think I need the header byte and the trailing byte anymore.

I was going into the rabbit hole again. Amazing the clarity of thought I get when driving to work.

Any thoughts?

Chris
Last edited on
Here is a two byte version with delay of 4 milliseconds that also works:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
uint16_t sendnop(uint8_t x){
  uint8_t buff[2]={0};

  //Read all in buffer to clear
  while (Serial.available())
    Serial.read();

  //Send the request
  Serial.write(x);

  //Check if there is a reply
  long stime=millis();
  
  do {
     
     delay(1);
     
     if ((millis()-stime) > 4)
        break;
  } while (Serial.available() <2);   

  if (Serial.available() ==2 )
         Serial.readBytes((&buff[0]),2);

  return Decode((uint16_t) ( buff[0]+(buff[1]<<8) ) );

}          


So with this approache, I decongested the serial stream and have a lot more bandwidth available now for many more requests.

Chris
Last edited on
Topic archived. No new replies allowed.
Pages: 12