dsyleixa123
Posts: 293
Joined: Mon Jun 11, 2018 11:22 am

code for UART comm from Pi to Arduino hangs up

Thu May 30, 2019 2:14 pm

hi,
I am despairing, my code for UART comm from Pi to Arduino hangs up.

I am trying to send strings built by
strcpy(formatstr, "§");
strcat(formatstr, "&i0=%d;&i1=%d;&i2=%d;&i3=%d;\n");
sprintf(mbuf, formatstr, i0,i1,i2,i3);

to my Arduino and receive similar ones.
At least I get it started, but it seems to hang up after the first 1 or 2 loops. The codes for Pi and Arduino are quite similar:

for the Pi (updated code):

Code: Select all


/*
   UART communication
   send/receive string of tokens
   *     
   Raspberry Pi  master
   ver 0701
 */
 
 /*
  * change log
  * 0701:
  * Serial Read delimiter
  * 0700
  * first adjustments
  * 0669:
  * UART 115200 baud  * 
  * 0667:
  * Arduino via USB = ACM0
  * 
  */


#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
#include <string>
#include <math.h>
#include <fcntl.h>
#include <string.h>
#include <sys/ioctl.h>
#include <stdint.h>
#include <time.h>
#include <sys/time.h>
#include <errno.h>
#include <pthread.h>


#include <wiringPi.h>
#include <wiringSerial.h>

#define  byte  uint8_t

char   uart[256]  =  "/dev/ttyACM0";
int    Serial;


//==================================================================

const uint32_t UARTclock = 115200;



int i0, i1, i2, i3, i4, i5, i6;             // int (common)
int a0,a1,a2,a3,a4,a5,a6,a7,a8,a9,a10,a11;  // int for analogRead(pin): a0=analogRead(A0), a1=analogRead(A1),... 
double f0, f1, f2, f3, f4, f5;              // double (common)

#define TOKLEN 30
#define MSGLEN 1024
#define iINVALID -29999


std::string  inputString="";
char   cval[TOKLEN];  // number as cstring
char   mbuf[MSGLEN];  // cstring msg buffer






//==================================================================
// debug monitor
//==================================================================

void displayvalue(char c[TOKLEN]) {
  
  
}



//==================================================================
// token tools
//==================================================================

int16_t  strstrpos(char * haystack,  char * needle)   // find 1st occurance of substr in str
{
   char *p = strstr(haystack, needle);
   if (p) return (int16_t) (p-haystack);
   return -1;   // Not found = -1.
}


//==================================================================
char * cstringarg( char* haystack, char* vname, char* carg ) {
   int i=0, pos=-1;
   unsigned char  ch=0xff;
   const char*  kini = "&";       // start of varname: '&'
   const char*  kin2 = "?";       // start of varname: '?'
   const char*  kequ = "=";       // end of varname, start of argument: '='
   char  needle[TOKLEN] = "";     // complete pattern:  &varname=abc1234

   strcpy(carg,"");
   strcpy(needle, kini);
   strcat(needle, vname);
   strcat(needle, kequ);
   pos = strstrpos(haystack, needle); 
   if(pos==-1) {
      needle[0]=kin2[0];
      pos = strstrpos(haystack, needle);
      if(pos==-1) return carg;
   }
   pos=pos+strlen(vname)+2; // start of value = kini+vname+kequ   
   while( (ch!='&')&&(ch!='\0') ) {
      ch=haystack[pos+i];    
      if( (ch=='&')||(ch==';')||(ch==' ')||(ch=='\0') ||(ch=='\n')
        ||(i+pos>=(int)strlen(haystack))||(i>TOKLEN-1) ) {
           carg[i]='\0';
           return carg;
      }       
      if( (ch!='&') ) {
          carg[i]=ch;          
          i++;       
      }      
   } 
   return carg;
}




//==================================================================
// serial TCP
//==================================================================


void loop() {
    
  while(1) {  
      
     static bool stringComplete = false;
     
     
     //-------------------------------------------------------------
     // send    
     
     char formatstr[MSGLEN];
     
     // debug, cut-down:
     strcpy(formatstr, "§");                                                    // initial key
     strcat(formatstr, "&i0=%d;&i1=%d;&i2=%d;&i3=%d;\n");
     sprintf(mbuf, formatstr, i0,i1,i2,i3);
                    
     for(uint8_t i=0; i<strlen(mbuf)-1; i++) {                 //
        serialPutchar( Serial, mbuf[i]);                      // Send values to the slave       
     }   
      
     strcpy(mbuf, "");  
     
     //delay?
     delay(1); 
   
     
     
     
     //-------------------------------------------------------------
     // receive
     
     inputString="";
     char cstr[TOKLEN];
   
     int  n=0;
     char inChar;
     
     while (serialDataAvail( Serial ) && n<MSGLEN-1) { 
       if(n==MSGLEN-2) inChar='\n'; // emergency brake
       else  
       inChar = serialGetchar( Serial ); 
    
       inputString += inChar;
       
       if (inChar == '\n')  {
         stringComplete = true;
       }
       n++;
     }
   
     
     if (stringComplete)  {
         
       //inputString.to_str(mbuf, len-1);
       strcpy (mbuf, inputString.c_str() );
       strcat(mbuf, "\0");
       fprintf(stderr,mbuf); fprintf(stderr,"\n"); 
   
       
       // cstringarg( char* haystack, char* vname, char* carg )
       // haystack pattern: &varname=1234abc;  delimiters &, \n, \0, SPACE, EOF 
   
       
       cstringarg(mbuf, "i0", cval); //    
       if(strlen(cval)>0) {          
          sprintf (cstr,  "i0=%d \n", atoi(cval));
          fprintf(stderr, cstr);
       }   
       cstringarg(mbuf, "i1", cval); //    
       if(strlen(cval)>0) {          
          sprintf (cstr,  "i1=%d \n", atoi(cval));
          fprintf(stderr, cstr);
       }
       cstringarg(mbuf, "i2", cval); //    
       if(strlen(cval)>0) {          
          sprintf (cstr,  "i2=%d \n", atoi(cval));
          fprintf(stderr, cstr);
       }
       cstringarg(mbuf, "i3", cval); //    
       if(strlen(cval)>0) {          
          sprintf (cstr,  "i3=%d \n", atoi(cval));
          fprintf(stderr, cstr);
       }  
       cstringarg(mbuf, "i4", cval); //    
       if(strlen(cval)>0) {          
          sprintf (cstr,  "i4=%d \n", atoi(cval));
          fprintf(stderr, cstr);
       }   
       
       inputString="";
       stringComplete = false;
   
       //delay?
       delay(1);
     }
   
   }     
}




//==================================================================

 
int main() {
     
    printf("initializing..."); printf("\n");
   
    // UART Serial com port
    Serial = serialOpen (uart, UARTclock);   
    printf("starting UART loop..."); printf("\n");   
    
    loop(); 
   
    serialClose( Serial);
    exit(0);
}



//
// eof


for the Arduino (updated):

Code: Select all

// Arduino COM to Borland C++ Builder form 
// (C) 2018 by dsyleixa


/// history:
// 0701   Serial.read delimiters
// 0700   ported to RPi comm
//
// 0.0.9  
// 0.0.8  analog aX=analogRead(AX) (X=0...11), syntax "&AX=%d",aX
// 0.0.7  pin-loop, 6x out-pins OUTn(I/O/pwm), &_ALLPINS_=0 when BCB-close
// 0.0.6  output pins DPINn
// 0.0.3  send/receive strings
// 0.0.2  receiving strings, pattern: &varname1=value1;
// 0.0.1  receiving simple Serial char 

// BCB-Arduino: Arduino to Rpi
// ver 0701


// notice:
// on Mega2560 the anaolgWrite() pwm function works on all pins 2...13 (thus also for LED_BUILTIN) plus some evtra ones.
// on ATmega168 or ATmega328P the anaolgWrite() pwm function works on pins 3, 5, 6, 9, 10, and 11 
// thus (not for LED_BUILTIN).
// on Mega2560 the anaolgWrite() pwm function works on all pins 2...13 
// (thus also for LED_BUILTIN) plus some evtra ones.


// #define _DUE_MEGA_    // <<<<<<<<<<< outcomment/uncomment acc. to board type for available GPIO pins!



// i2c
#include <Wire.h>   // Incl I2C comm, but needed for not getting compile error


int i0, i1, i2, i3, i4, i5, i6;             // int (common)
int a0,a1,a2,a3,a4,a5,a6,a7,a8,a9,a10,a11;  // int for analogRead(pin): a0=analogRead(A0), a1=analogRead(A1),... 
double f0, f1, f2, f3, f4, f5;              // double (common)

#define TOKLEN 30
#define MSGLEN 1024
#define iINVALID -29999

String  inputString="";
char    cval[TOKLEN];  // number as cstring
char    mbuf[MSGLEN];  // cstring msg buffer


//==================================================================
// tools
//==================================================================

int16_t  strstrpos(char * haystack,  char * needle)   // find 1st occurance of substr in str
{
   char *p = strstr(haystack, needle);
   if (p) return (int16_t)(p - haystack);
   return -1;   // Not found = -1.
}


//------------------------------------------------------------
char * cstringarg( char* haystack, char* vname, char* carg ) {
   int i=0, pos=-1;
   unsigned char  ch=0xff;
   const char*  kini = "&";       // start of varname: '&'
   const char*  kin2 = "?";       // start of varname: '?'
   const char*  kequ = "=";       // end of varname, start of argument: '='
   char  needle[TOKLEN] = "";     // complete pattern:  &varname=abc1234

   strcpy(carg,"");
   strcpy(needle, kini);
   strcat(needle, vname);
   strcat(needle, kequ);
   pos = strstrpos(haystack, needle); 
   if(pos==-1) {
      needle[0]=kin2[0];
      pos = strstrpos(haystack, needle);
      if(pos==-1) return carg;
   }
   pos=pos+strlen(vname)+2; // start of value = kini+vname+kequ   
   while( (ch!='&')&&(ch!='\0') ) {
      ch=haystack[pos+i];    
      if( (ch=='&')||(ch==';')||(ch==' ')||(ch=='\0') ||(ch=='\n')
        ||(i+pos>=(int)strlen(haystack))||(i>TOKLEN-1) ) {
           carg[i]='\0';
           return carg;
      }       
      if( (ch!='&') ) {
          carg[i]=ch;          
          i++;       
      }      
   } 
   return carg;
}

//------------------------------------------------------------

void writeDPin(int pin, int ival) {
  pinMode(pin, OUTPUT);  // safety
  if(ival==0)   { digitalWrite(pin, LOW); }
  else
  if(ival==255) { digitalWrite(pin, HIGH); }
  else {       
     analogWrite(pin, ival); 
  }   
}




//==================================================================
// setup
//==================================================================
void setup() {
  Serial.begin(115200);
  
  pinMode(LED_BUILTIN, OUTPUT);
  digitalWrite(LED_BUILTIN, LOW);

  #define _DEBUG_      // <<<<<<<<<<< outcomment/uncomment for testing !!
  
  #ifdef _DEBUG_
  
  i0=0;
  i1=1;
  i2=-22;
  i3=33;
  i4=-444;
  i5=5555;
  i6= B10101010*256;
  i6+=B10101010;

  f0=0;
  f1=10.1; 
  f2=-20.22;
  f3=300.333;
  f4=-4000.4444;
  f5=50000.55555;

  a0=0;
  a1=1;
  a2=2;
  a3=3;
  a4=4;
  a5=5;
  a6=6;
  a7=7;
  a8=8;
  a9=9;
  a10=10;
  a11=11;

  #endif
}


//==================================================================
// loop
//==================================================================

void loop() {
  static bool stringComplete = false;

  //-------------------------------------------------------------
  // receive
  
  int  n=0;
  char inChar;
     
  while (Serial.available() && n<MSGLEN-1) { 
       if(n==MSGLEN-2) inChar='\n';
       else  
       inChar = (char)Serial.read();
    
       inputString += inChar;
       
       if (inChar == '\n')  {
         stringComplete = true;
       }
       n++;
  }

  if (stringComplete)  {
    inputString.toCharArray(mbuf, MSGLEN-1);
    
    // cstringarg( char* haystack, char* vname, char* carg )
    // haystack pattern: &varname=1234abc;  delimiters &, \n, \0, SPACE, EOF 
    
    cstringarg(mbuf, "LEDBI", cval); // LEDBI: LED_BUILTIN    
    if(strlen(cval)>0) {          
      writeDPin(LED_BUILTIN, atoi(cval) );     
    }  


    inputString="";
    stringComplete = false;

    //delay?
    delay(1);
  }
  //-------------------------------------------------------------
  // send  
  

  //----------------------
  
  char formatstr[MSGLEN];
  strcpy(formatstr, "§");                               // initial key
  strcat(formatstr, "&i0=%d;&i1=%d;&i2=%d;&i3=%d;&i4=%d;&i5=%d;&i6=%d;");
  strcat(formatstr, "&A0=%d;&A1=%d;&A2=%d;&A3=%d;&A4=%d;&A5=%d;&A6=%d;&A7=%d;&A8=%d;&A9=%d;&A10=%d;&A11=%d;");

  sprintf(mbuf, formatstr, i0,i1,i2,i3,i4,i5,i6, a0,a1,a2,a3,a4,a5,a6,a7,a8,a9,a10,a11 );                 
  for (int i=0; i<strlen(mbuf); i++ ) Serial.print(mbuf[i]);
  
  strcpy(mbuf, "");  
  
  i0++;

  //delay?
  delay(1); 
}




// end of file
output at the Pi console:
sometimes it does not even get a connection (not before restarting anew), but sometimes then it shows:

Code: Select all

initializing...
starting UART loop...
§&i0=0;&i1=1;&i2=-226;&A0=0;&A1=1;&A2=2;&A3=3;&A4=4;&A5=5;&A6=6;&A7=7;&A8=8;&A9=9;&A�11;
§&i0=331;&i1=1;&i2=-22;&i3=33;&i4=-444;&i5=5555;&i6=-21846;&A0=0;&A1=1;&A2=2;&A3=3;&A4=4;&A5=5;&A6=6;&A7=7;&A8=8;&A9=9;&A�11;
§&i0=331;&i1=1;&i2=-22;&i3=33;&i4=-444;&i5=5555;&i6=-21846;&A0=0;&A1=1;&A2=2;&A3=3;&A4=4;&A5=5;&A6=6;&A7=7;&A8=8;&A9=9;&A
i0=0 
i1=1 
i2=-226 
i3=33 
i4=-444 

and by that it's stalling...
(no idea BTW about how the � chars appear)

I'm afraid the increment of the i0 value in the Arduino code is not made resp not transmitted repetetively to the Pi.

I actually think that my simple comm program is not failsafe - is there a better way to send such "complete" strings there and back, using wiringPi?

dsyleixa123
Posts: 293
Joined: Mon Jun 11, 2018 11:22 am

Re: code for UART comm from Pi to Arduino hangs up

Thu May 30, 2019 8:45 pm

any idea anybody why it's stalling?

User avatar
scruss
Posts: 2259
Joined: Sat Jun 09, 2012 12:25 pm
Location: Toronto, ON
Contact: Website

Re: code for UART comm from Pi to Arduino hangs up

Thu May 30, 2019 9:19 pm

it might help to cut down your examples to the bare minimum that still shows the problem. It took me too long to find the serial open commands.
‘Remember the Golden Rule of Selling: “Do not resort to violence.”’ — McGlashan.

dsyleixa123
Posts: 293
Joined: Mon Jun 11, 2018 11:22 am

Re: code for UART comm from Pi to Arduino hangs up

Fri May 31, 2019 8:18 am

yes, thank you,
I cut it down to the basic essentials, but now again it stalls after a couple of loops sending there and back:

Raspi code:

Code: Select all

/*
   UART communication
   send/receive string of tokens
    
   Raspberry Pi  master
   ver 0101
 */



#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
#include <string>
#include <math.h>
#include <fcntl.h>
#include <string.h>
#include <sys/ioctl.h>
#include <stdint.h>
#include <time.h>
#include <sys/time.h>
#include <errno.h>
#include <pthread.h>

#include <wiringPi.h>
#include <wiringSerial.h>

#define  byte  uint8_t

char   uart[256]  =  "/dev/ttyACM0";
int    Serial;

const uint32_t UARTclock = 115200;



int i0;

#define TOKLEN 30
#define MSGLEN 1024
#define iINVALID -29999


std::string  inputString="";
char   cval[TOKLEN];  // number as cstring
char   mbuf[MSGLEN];  // cstring msg buffer





//==================================================================
// serial TCP
//==================================================================


void loop() {
    
  while(1) {  
      
     static bool stringComplete = false;
     
     
     //-------------------------------------------------------------
     // send    
     
     char formatstr[MSGLEN];
     
     // debug, cut-down:
     strcpy(formatstr, "§");
     strcat(formatstr, "message from Raspi: %d;\n");
     sprintf(mbuf, formatstr, i0);
                    
     for(uint8_t i=0; i<strlen(mbuf); i++) {           //
        serialPutchar( Serial, mbuf[i]);               // Send values to the slave       
     }   
     
     //delay?
     delay(1); 
   
     
     
     
     //-------------------------------------------------------------
     // receive
     
     inputString="";
     char cstr[TOKLEN];
   
     int  n=0;
     char inChar;
     
     
     while (serialDataAvail( Serial ) && n<MSGLEN-1) { 
       if(n==MSGLEN-2) inChar='\n'; // emergency brake
       else  
       inChar = serialGetchar( Serial ); 
    
       inputString += inChar;
       
       if (inChar == '\n')  {
         stringComplete = true;
       }
       n++;
     }
   
     
     if (stringComplete)  {

       strcpy (mbuf, inputString.c_str() );
       fprintf(stderr,mbuf); fprintf(stderr,"\n"); 
       
       // process mbuf !
   
       
       inputString="";
       stringComplete = false;
   
       //delay?
       delay(1);
     }
   
   }     
}




//==================================================================

 
int main() {
     
    printf("initializing..."); printf("\n");
   
    // UART Serial com port
    Serial = serialOpen (uart, UARTclock);   
    printf("starting UART loop..."); printf("\n");   
    
    loop(); 
   
    serialClose( Serial);
    exit(0);
}


//
// eof

Arduino code:

Code: Select all

// Arduino COM to Raspi
// (C) 2018 by dsyleixa

// ver 0101


// i2c
#include <Wire.h>    


int i0 = 0;

#define TOKLEN 30
#define MSGLEN 1024
#define iINVALID -29999

String  inputString="";
char    cval[TOKLEN];  // number as cstring
char    mbuf[MSGLEN];  // cstring msg buffer


//==================================================================
// setup
//==================================================================
void setup() {
  Serial.begin(115200);
  
  pinMode(LED_BUILTIN, OUTPUT);
  digitalWrite(LED_BUILTIN, LOW);

}


//==================================================================
// loop
//==================================================================

void loop() {
  static bool stringComplete = false;

  //-------------------------------------------------------------
  // receive
  
  int  n=0;
  char inChar;

     
  while (Serial.available() && n<MSGLEN-1) { 
       if(n==MSGLEN-2) inChar='\n';
       else  
       inChar = (char)Serial.read();
    
       inputString += inChar;
       
       if (inChar == '\n')  {
         stringComplete = true;
       }
       n++;
  }

  if (stringComplete)  {
    inputString.toCharArray(mbuf, MSGLEN-1);

    // process mbuf !
    
    //
    
    inputString="";
    stringComplete = false;

    //delay?
    delay(1);
  }
  //-------------------------------------------------------------
  // send  
  

  //----------------------
  
  char formatstr[MSGLEN];
  strcpy(formatstr, "§");
  strcat(formatstr, "message from Arduino: %d;\n");
  sprintf(mbuf, formatstr, i0);                 
  
  for (int i=0; i<strlen(mbuf); i++ ) Serial.print(mbuf[i]);
  
  i0++;

  //delay?
  delay(1); 
}




// end of file

console output:

Code: Select all

initializing...
starting UART loop...
§message from Arduino: 0;
§message fr211;
§message from Arduino: 2212;
§message from Arduino: 2213;
§message from Arduino: 221�no: 2210;
§message from Arduino: 2211;
§message from Arduino: 2212;
§message from Arduino: 2213;
§message from Arduino: 221�





then stopping...

restart, new output:

Code: Select all

initializing...
starting UART loop...
§message from Arduino: 0gno: 618;
§message fr��message from Arduino: 615;
§message from Arduino: 616;
§message from Arduino: 617;
§message from Arduino: 618;
§message fr




then again stopping...
Last edited by dsyleixa123 on Sat Jun 01, 2019 8:06 pm, edited 1 time in total.

dsyleixa123
Posts: 293
Joined: Mon Jun 11, 2018 11:22 am

Re: code for UART comm from Pi to Arduino hangs up

Fri May 31, 2019 6:18 pm

update:
adding delay(10) instead of (1) doesn't change anything, UART clock 19200 instead neither.

But:
uploading to a Arduino Due (SAM3X8E) it works like a charm, at either clock or delays! :shock:
replugging to the Mega: again always hangs up... :shock:

is that normal to the Mega ? :?

LdB
Posts: 1143
Joined: Wed Dec 07, 2016 2:29 pm

Re: code for UART comm from Pi to Arduino hangs up

Sun Jun 02, 2019 1:45 am

Looking at your code there is an obvious problem

Follow what happens if Serial.available() returns false :-)

The Pi is very fast it will see the gap between characters when the next character is incoming but not yet received, and I would expect that it returns false at times.

I suspect you need to stay in the loop until stringComplete rather than serialDataAvail( Serial ). The alternative bail from that loop needs to be a timeout or keypress, like on any well designed comms setup. So my guess is your code fails on a fast CPU because it is wrong and badly designed.

If you want to bail from that loop on a timer simply get the system timertick and add a timeout tickcount before entering. On each loop along with the stringComplete check if you current timertick is greater than the timeout tick number you calculated. So when you come out the loop you can check if you got stringComplete, if not then your code timed out.

dsyleixa123
Posts: 293
Joined: Mon Jun 11, 2018 11:22 am

Re: code for UART comm from Pi to Arduino hangs up

Sun Jun 02, 2019 7:24 am

thank you very much for your hints!
Actually the original code was derived from an original Arduino-to-Arduino-Code which already worked fine, and now one Arduino code had been substituted by a Raspi-wiringPi portation.
But yes, indeed by the following changes it now works much better:

Code: Select all

    if (serialDataAvail(Serial)) { 
        while(!stringComplete && n<MSGLEN-1) {    
          if(n==MSGLEN-2) inChar='\n'; // emergency brake
          else  
            inChar = serialGetchar(Serial); 
       
          if(inChar=='\n' || inChar>=' ') inputString += inChar;       
          if (inChar == '\n')  {
            stringComplete = true;
          }
          n++;
        } 
     }
Just now it just was running about 2000-3000 loops, but then again it stalled.
Making similar changes to the Arduino code didn't make it better though.
(OTOH, all communication code is running at 115200 baud, and the Arduino Due doesn't stall as far as I observed, already >80000 loops right now... )
edit, corrected: stalled then later at >130000, too.

As to the timer: I honestly do not understand how I should write that code. Do you or anybode else have or know a code which works better than mine, just reading complete strings until '\n', and acting more failsafe for Arduino <-> Raspi communication?
Finally Arduinos and Raspis exist already a decade, I can't imagine that I am supposed to be the first one who is looking for such a communication code.

LdB
Posts: 1143
Joined: Wed Dec 07, 2016 2:29 pm

Re: code for UART comm from Pi to Arduino hangs up

Mon Jun 03, 2019 4:10 am

Still wrong the serialDataAvail(Serial) is problematic .. don't use it.

Okay I am going to a guess at the code and I look up arduino and it has a millis() function which I will use for timeout
https://www.arduino.cc/reference/en/lan ... me/millis/

So here is my guess .. will report 2 errors buffer overrun or timeout (over 1 sec wait).

Code: Select all

void loop() {
    
  while(1) 
  {  
     //-------------------------------------------------------------
     // send    
  
     char formatstr[MSGLEN];     
     // debug, cut-down:
     strcpy(formatstr, "§");
     strcat(formatstr, "message from Raspi: %d;\n");
     sprintf(mbuf, formatstr, i0);
     for(uint8_t i=0; i<strlen(mbuf); i++) {           //
        serialPutchar( Serial, mbuf[i]);               // Send values to the slave       
     }   
     
     //delay?
    //delay(1);
    // Suspect you had to have the delay is because it dropped straight
    // thru the next section because your loop had serialDataAvail(Serial)
    // If the other end hasn't sent the response it would drop straight thru 
      
     //-------------------------------------------------------------
     // receive
     
     inputString="";
     char cstr[TOKLEN];
   
     int  n=0;
     char inChar = 0;
     
     unsigned long timeout = millis() + 1000;   /* 1 second in the future */
     while (inChar != '\n' && n < MSGLEN-2
	        && millis() < timeout) 
     { 
	   inChar = serialGetchar( Serial ); 
           inputString += inChar;   
           n++;
     }
   
     if (inChar == '\n')  // termonated correctly  
     {
          strcpy (mbuf, inputString.c_str() );
          fprintf(stderr,mbuf); fprintf(stderr,"\n");    
          // process mbuf !
           inputString="";
     } else {
	   if (n == MSGLEN-1)
		fprintf(stderr,"Buffer error %i characters sent\n", n);
                else fprintf(stderr, "Timeout error no data for 1 sec\n", n);
	  }
     }     
}

dsyleixa123
Posts: 293
Joined: Mon Jun 11, 2018 11:22 am

Re: code for UART comm from Pi to Arduino hangs up

Mon Jun 03, 2019 7:53 am

thank you, I'll try it immediately!
what I hadn't understood at first is that a timeout is needed at all, because the Arduino Serial class (providing available()) has got a built-in timeout and probably many more built-in features, opposite to the wiringPi/wiringSerial thing; tbh, I assumed both were working quite similar what wiringSerial probably doesn't (which is confusing because the wiringPi namings suggest that it would).

dsyleixa123
Posts: 293
Joined: Mon Jun 11, 2018 11:22 am

Re: code for UART comm from Pi to Arduino hangs up

Mon Jun 03, 2019 11:21 am

update:

I just let it run about 40 min, and it was fine, not showing either error!

Now with an advanced message string from Arduino constructed by

Code: Select all

int32_t i0=0,i1=0,i2=0,i3=0,i4=0,i5=0,i6=0,i7=0,i8=0,i9=0;    

// test
  i0=0;
  i1=1;
  i2=-22;
  i3=33;
  i4=-444;
  i5=5555;
  i6= B10101010*256;
  i6+=B10101010;     

  char formatstr[MSGLEN];
  strcpy(formatstr, "§");
  strcat(formatstr, "&i0=%d;&i1=%d;&i2=%d;&i3=%d;&i4=%d;&i5=%d;&i6=%d;\n");  
  sprintf(mbuf, formatstr, i0,i1,i2,i3,i4,i5,i6 );            


the Raspi received ~7200 loops, and then again it hung up.
(additionally, the string was faulty by it's values, but that's another issue I guess)

Raspi code:

Code: Select all


/*
   UART communication
   send/receive string of tokens
   *     
   Raspberry Pi  master
   ver 0701
 */
 
 /*
  * change log
  * 0701:
  * Serial Read delimiter
  * 0700
  * first adjustments
  * 0669:
  * UART 115200 baud  * 
  * 0667:
  * Arduino via USB = ACM0
  * 
  */
 
// (C) dsyleixa 2015
// freie Verwendung für private Zwecke
// für kommerzielle Zwecke nur nach Genehmigung durch den Autor.
// Programming language: gcc C/C++
// protected under the friendly Creative Commons Attribution-NonCommercial-ShareAlike 3.0 Unported License
// http://creativecommons.org/licenses/by-nc-sa/3.0/



#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
#include <string>
#include <math.h>
#include <fcntl.h>
#include <string.h>
#include <sys/ioctl.h>
#include <stdint.h>
#include <time.h>
#include <sys/time.h>
#include <errno.h>
#include <pthread.h>


#include <wiringPi.h>
#include <wiringSerial.h>

#define  byte  uint8_t

char   uart[128]  =  "/dev/ttyACM0";
int    Serial;

const  uint32_t UARTclock = 115200;



volatile static int32_t i0=0,i1=0,i2=0,i3=0,i4=0,i5=0,i6=0,i7=0,i8=0,i9=0;          // int (general)
volatile static int16_t a0=0,a1=0,a2=0,a3=0,a4=0,a5=0,a6=0,a7=0,a8=0,a9=0,a10=0,a11=0;  // int for analogRead(pin): a0=analogRead(A0)=0, a1=analogRead(A1),... 
volatile static double  f0=0,f1=0,f2=0,f3=0,f4=0,f5=0,f6=0,f7=0,f8=0,f9=0;          // double (general)

#define TOKLEN 30
#define MSGLEN 512
#define iINVALID -29999


std::string  inputString="";
char   cval[TOKLEN];  // number as cstring
char   mbuf[MSGLEN];  // cstring msg buffer






//==================================================================
// debug monitor
//==================================================================

void displayvalue(char c[TOKLEN]) {
  
  
}



//==================================================================
// token tools
//==================================================================

int16_t  strstrpos(char * haystack,  char * needle)   // find 1st occurance of substr in str
{
   char *p = strstr(haystack, needle);
   if (p) return (int16_t) (p-haystack);
   return -1;   // Not found = -1.
}


//==================================================================
char * cstringarg( char* haystack, char* vname, char* carg ) {
   int i=0, pos=-1;
   unsigned char  ch=0xff;
   const char*  kini = "&";       // start of varname: '&'
   const char*  kin2 = "?";       // start of varname: '?'
   const char*  kequ = "=";       // end of varname, start of argument: '='
   char  needle[TOKLEN] = "";     // complete pattern:  &varname=abc1234

   strcpy(carg,"");
   strcpy(needle, kini);
   strcat(needle, vname);
   strcat(needle, kequ);
   pos = strstrpos(haystack, needle); 
   if(pos==-1) {
      needle[0]=kin2[0];
      pos = strstrpos(haystack, needle);
      if(pos==-1) return carg;
   }
   pos=pos+strlen(vname)+2; // start of value = kini+vname+kequ   
   while( (ch!='&')&&(ch!='\0') ) {
      ch=haystack[pos+i];    
      if( (ch=='&')||(ch==';')||(ch==' ')||(ch=='\0') ||(ch=='\n')
        ||(i+pos>=(int)strlen(haystack))||(i>TOKLEN-1) ) {
           carg[i]='\0';
           return carg;
      }       
      if( (ch!='&') ) {
          carg[i]=ch;          
          i++;       
      }      
   } 
   return carg;
}




//==================================================================
// serial TCP
//==================================================================


void loop() {
    
    
  while(1) {  
      
     static bool stringComplete = false;
     
     
     //-------------------------------------------------------------     
     // send    
     
     char formatstr[MSGLEN];     
     // debug, cut-down:
     strcpy(formatstr, "§");
     strcat(formatstr, "message from Raspi: %d;\n");
     sprintf(mbuf, formatstr, i0);
     for(uint8_t i=0; i<strlen(mbuf); i++) {           //
        serialPutchar( Serial, mbuf[i]);               // Send values to the slave       
     }   
     
   
     
     
     
     ///-------------------------------------------------------------
     // receive
     
     inputString="";
     char cstr[TOKLEN];
   
     int  n=0;
     char inChar = 0;
     
     unsigned long timeout = millis() + 1000;   /* 1 second in the future */
     while (inChar != '\n' && n < MSGLEN-2
	        && millis() < timeout) 
     { 
	   inChar = serialGetchar( Serial ); 
           inputString += inChar;   
           n++;
     }
   
     if (inChar == '\n')  // terminated correctly  
     {
        strcpy (mbuf, inputString.c_str() );
        if(1) {
            fprintf(stderr,mbuf); fprintf(stderr,"\n");    
        }
        
        
        // process mbuf !
        
       cstringarg(mbuf, "i0", cval); //    
       if(strlen(cval)>0) {          
          sprintf (cstr,  "i0=%d \n", atoi(cval));
          fprintf(stderr, cstr);
       }   
       cstringarg(mbuf, "i1", cval); //    
       if(strlen(cval)>0) {          
          sprintf (cstr,  "i1=%d \n", atoi(cval));
          fprintf(stderr, cstr);
       }
       cstringarg(mbuf, "i2", cval); //    
       if(strlen(cval)>0) {          
          sprintf (cstr,  "i2=%d \n", atoi(cval));
          fprintf(stderr, cstr);
       }
       cstringarg(mbuf, "i3", cval); //    
       if(strlen(cval)>0) {          
          sprintf (cstr,  "i3=%d \n", atoi(cval));
          fprintf(stderr, cstr);
       }  
       cstringarg(mbuf, "i4", cval); //    
       if(strlen(cval)>0) {          
          sprintf (cstr,  "i4=%d \n", atoi(cval));
          fprintf(stderr, cstr);
       }   
        
        inputString="";
        
     } else {
	     if (n == MSGLEN-1)
		 fprintf(stderr,"Buffer error %i characters sent\n", n);
                else fprintf(stderr, "Timeout error no data for 1 sec\n", n);
	   }
       

    }     
   
   
}




//==================================================================

 
int main() {
     
    printf("initializing..."); printf("\n");
   
    // UART Serial com port
    Serial = serialOpen (uart, UARTclock);   
    printf("starting UART loop..."); printf("\n");   
    
    loop(); 
   
    serialClose( Serial);
    exit(0);
}



//
// eof



Arduino code:

Code: Select all

// Arduino Serial to Raspi USB
// (C) 2018 by dsyleixa


// history:
// 0703  simple msg str 
// 0702
// 0701   Serial.read delimiters
// 0700   
// 0101   ported for RPi USB
//
// 0009  
// 0008  analog aX=analogRead(AX) (X=0...11), syntax "&AX=%d",aX
// 0007  pin-loop, 6x out-pins OUTn(I/O/pwm), &_ALLPINS_=0 when BCB-close
// 0006  output pins DPINn
// 0003  send/receive strings
// 0002  receiving strings, pattern: &varname1=value1;
// 0001  receiving simple Serial char 

// BCB-Arduino: Arduino to RPi
// ver 0701


#define _DUE_MEGA_    // <<<<<<<<<<< outcomment/uncomment acc. to board type for available GPIO pins!


const uint32_t UARTclock = 115200;

int32_t i0=0,i1=0,i2=0,i3=0,i4=0,i5=0,i6=0,i7=0,i8=0,i9=0;          // int (general)


#define TOKLEN 30
#define MSGLEN 512
#define iINVALID -29999

String  inputString="";
char    cval[TOKLEN];  // number as cstring
char    mbuf[MSGLEN];  // cstring msg buffer


//==================================================================
// tools
//==================================================================

int16_t  strstrpos(char * haystack,  char * needle)   // find 1st occurance of substr in str
{
   char *p = strstr(haystack, needle);
   if (p) return (int16_t)(p - haystack);
   return -1;   // Not found = -1.
}


//------------------------------------------------------------
char * cstringarg( char* haystack, char* vname, char* carg ) {
   int i=0, pos=-1;
   unsigned char  ch=0xff;
   const char*  kini = "&";       // start of varname: '&'
   const char*  kin2 = "?";       // start of varname: '?'
   const char*  kequ = "=";       // end of varname, start of argument: '='
   char  needle[TOKLEN] = "";     // complete pattern:  &varname=abc1234

   strcpy(carg,"");
   strcpy(needle, kini);
   strcat(needle, vname);
   strcat(needle, kequ);
   pos = strstrpos(haystack, needle); 
   if(pos==-1) {
      needle[0]=kin2[0];
      pos = strstrpos(haystack, needle);
      if(pos==-1) return carg;
   }
   pos=pos+strlen(vname)+2; // start of value = kini+vname+kequ   
   while( (ch!='&')&&(ch!='\0') ) {
      ch=haystack[pos+i];    
      if( (ch=='&')||(ch==';')||(ch==' ')||(ch=='\0') ||(ch=='\n')
        ||(i+pos>=(int)strlen(haystack))||(i>TOKLEN-1) ) {
           carg[i]='\0';
           return carg;
      }       
      if( (ch!='&') ) {
          carg[i]=ch;          
          i++;       
      }      
   } 
   return carg;
}

//------------------------------------------------------------

void writeDPin(int pin, int ival) {
  pinMode(pin, OUTPUT);  // safety
  if(ival==0)   { digitalWrite(pin, LOW); }
  else
  if(ival==255) { digitalWrite(pin, HIGH); }
  else {       
     analogWrite(pin, ival); 
  }   
}




//==================================================================
// setup
//==================================================================
void setup() {
  Serial.begin(UARTclock);
  
  pinMode(LED_BUILTIN, OUTPUT);
  digitalWrite(LED_BUILTIN, LOW);

  #define _DEBUG_      // <<<<<<<<<<< outcomment/uncomment for testing !!  
  #ifdef _DEBUG_
  
  i0=0;
  i1=1;
  i2=-22;
  i3=33;
  i4=-444;
  i5=5555;
  i6= B10101010*256;
  i6+=B10101010;


  #endif
}


//==================================================================
// loop
//==================================================================

void loop() {
  static bool stringComplete = false;

  //-------------------------------------------------------------
  // receive
  
  int  n=0;
  char inChar;     

  while(Serial.available() && !stringComplete && n<MSGLEN-1) { 
       if(n==MSGLEN-2) inChar='\n';
       else  
       inChar = inChar = (char)Serial.read();    
       inputString += inChar;
       
       if (inChar == '\n')  {
         stringComplete = true;
       }
       n++;
  }

  if (stringComplete)  {
    inputString.toCharArray(mbuf, MSGLEN-1);
    
   
    //----------------------
    // process mbuf!

    

    //----------------------
    
    inputString="";
    stringComplete = false;

    //delay?
    delay(1);
  }

  
  //-------------------------------------------------------------
  // send  
  
  
  char formatstr[MSGLEN];
  strcpy(formatstr, "§");
  strcat(formatstr, "&i0=%d;&i1=%d;&i2=%d;&i3=%d;&i4=%d;&i5=%d;&i6=%d;\n");
 
  
  sprintf(mbuf, formatstr, i0,i1,i2,i3,i4,i5,i6 );                 
  for (int i=0; i<strlen(mbuf); i++ ) Serial.print(mbuf[i]); 
   
   //delay?
  delay(1);
    
  i0++;

  
}




// end of file
Raspi console output:

Code: Select all

i0=7157 
i1=0 
i2=1 
i3=0 
i4=-22 
§&i0=7158;&i1=0;&i2=1;&i3=0;&i4=-22;&i5=-1;&i6=33;

i0=7158 
i1=0 
i2=1 
i3=0 
i4=-22 
§&i0=7159;&i1=0;&i2=1;&i3=0;&i4=-22;&i5=-1;&i6=33;

i0=7159 
i1=0 
i2=1 
i3=0 
i4=-22 
§&i0=7160;&i1=0;&i2=1;&i3=0;&i4=-22;&i5=-1;&i6=33;

PS,
last int values and cstring instead are expected to be
i0=7159;
i1=1;
i2=-22;
i3=33;
i4=-444;
§&i0=7160;&i1=1;&i2=22;&i3=33;&i4=-44;&i5=5555;&i6=43690;
which is actually performed correctly by my Arduino Due...

LdB
Posts: 1143
Joined: Wed Dec 07, 2016 2:29 pm

Re: code for UART comm from Pi to Arduino hangs up

Mon Jun 03, 2019 11:43 am

the Raspi received ~7200 loops, and then again it hung up.
FYI "stringComplete" is no longer in use stop putting back the lines with it .. it does nothing now on the RASPI code cut them all out.

Testing:
1.) Fire the RASPI end but don't send anything from the audrino end and check it times out properly on serialGetChar .

If it doesn't timeout it means we need to put the timeout deeper actually in the loop code for "serialGetchar".
If you don't know how to code that, then find the serialGetChar code and post it for us to modify. Actually you might
as well do serialPutchar at same time because both really need timeouts.

FYI your audrino end code has same issues of not having proper timeouts etc and it is actually highly likely it has stopped sending which is why you get stuck.

Usually the RX/TX is done on interrupts, it is a bit clunky doing it like this because you can get stuck in loops without timeouts.

dsyleixa123
Posts: 293
Joined: Mon Jun 11, 2018 11:22 am

Re: code for UART comm from Pi to Arduino hangs up

Mon Jun 03, 2019 11:59 am

as stated (IIRC) the Serial class on Arduino has integrated timeouts, and people who use UART from Arduino to Arduino by Serial() never needed extra ones... (i used that Arduino code to another Aduino already successfully, also from an Arduino to a PC running Borland C++ Builder, just for the Raspi it don't work).
Last edited by dsyleixa123 on Mon Jun 03, 2019 12:05 pm, edited 1 time in total.

dsyleixa123
Posts: 293
Joined: Mon Jun 11, 2018 11:22 am

Re: code for UART comm from Pi to Arduino hangs up

Mon Jun 03, 2019 12:01 pm

firing the Raspi without sending from Arduino:

Code: Select all

   sprintf(mbuf, formatstr, i0,i1,i2,i3,i4,i5,i6 );                   
  //for (int i=0; i<strlen(mbuf); i++ ) Serial.print(mbuf[i]); 
initializing...
starting UART loop...
Timeout error no data for 1 sec
Timeout error no data for 1 sec
Timeout error no data for 1 sec
Timeout error no data for 1 sec
Timeout error no data for 1 sec

LdB
Posts: 1143
Joined: Wed Dec 07, 2016 2:29 pm

Re: code for UART comm from Pi to Arduino hangs up

Mon Jun 03, 2019 12:05 pm

Ok now try it without the audrino conencted and see if it gets stuck in send loop.

If it still loops correctly with the timeout error the problem is on audrino end.

Essentially what you are checking is the RASPI cant get stuck anywhere, it should just circulate with timeout errors.

The more I look at however I would like to see the code for serialGetchar & serialPutChar :-)

dsyleixa123
Posts: 293
Joined: Mon Jun 11, 2018 11:22 am

Re: code for UART comm from Pi to Arduino hangs up

Mon Jun 03, 2019 12:16 pm

I unplugged the Arduino from USB, then again restarted the program from Geany by F5
now it says the same, very quickly no 1 sec delay in between:

Timeout error no data for 1 sec
Timeout error no data for 1 sec
Timeout error no data for 1 sec
Timeout error no data for 1 sec
Timeout error no data for 1 sec
Timeout error no data for 1 sec
Timeout error no data for 1 sec
Timeout error no data for 1 sec
Timeout error no data for 1 sec
Timeout error no data for 1 sec
Timeout error no data for 1 sec
Timeout error no data for 1 sec
Timeout error no data for 1 sec
Timeout error no data for 1 sec

dsyleixa123
Posts: 293
Joined: Mon Jun 11, 2018 11:22 am

Re: code for UART comm from Pi to Arduino hangs up

Mon Jun 03, 2019 12:20 pm

the code for serialGetchar & serialPutChar I don't know, it's somewhere in wiringSerial I guess...

LdB
Posts: 1143
Joined: Wed Dec 07, 2016 2:29 pm

Re: code for UART comm from Pi to Arduino hangs up

Mon Jun 03, 2019 12:25 pm

I found it .. try this now has a timeout on both send and recieve

Code: Select all

void loop() {   
  while(1) 
  {  
     unsigned long timeout;

     //-------------------------------------------------------------
     // send    
     char formatstr[MSGLEN];     
     // debug, cut-down:
     strcpy(formatstr, "§");
     strcat(formatstr, "message from Raspi: %d;\n");
     sprintf(mbuf, formatstr, i0);
	 timeout = millis() + 1000;   /* 1 second in the future */
     uint8_t i, len;
     len = strlen(mbuf);
     for(i=0; i<len && millis() < timeout; i++) { 
        serialPutchar( Serial, mbuf[i]);               // Send values to the slave       
     }   
     if (i  != len)
     {
            fprintf(stderr, "Timeout TX error send took over 1 sec\n", n);
     }
     
     //-------------------------------------------------------------
     // receive
     
     inputString="";
     char cstr[TOKLEN];
   
     int  n=0;
     char inChar = 0;
     
     timeout = millis() + 1000;   /* 1 second in the future */
     while (inChar != '\n' && n < MSGLEN-2
	        && millis() < timeout) 
     { 
	    if (Serial.available())
		{
			inChar = serialGetchar( Serial ); 
			inputString += inChar;   
			n++;
		}
     }
   
     if (inChar == '\n')  // terminated correctly  
     {
          strcpy (mbuf, inputString.c_str() );
          fprintf(stderr,mbuf); fprintf(stderr,"\n");    
          // process mbuf !
           inputString="";
     } else {
	   if (n == MSGLEN-1)
		fprintf(stderr,"Buffer error %i characters sent\n", n);
                else fprintf(stderr, "Timeout RX error no data for 1 sec\n", n);
	  }
     }     
}

dsyleixa123
Posts: 293
Joined: Mon Jun 11, 2018 11:22 am

Re: code for UART comm from Pi to Arduino hangs up

Mon Jun 03, 2019 12:34 pm

compile error: there is no
if (Serial.available())
for the Pi

dsyleixa123
Posts: 293
Joined: Mon Jun 11, 2018 11:22 am

Re: code for UART comm from Pi to Arduino hangs up

Mon Jun 03, 2019 12:38 pm

using serialDataAvailable(Serial):


§&i0=1362;&i1=0;&i2=1;&i3=0;&i4=-22;&i5=-1;&i6=33;

§&i0=1363;&i1=0;&i2=1;&i3=0;&i4=-22;&i5=-1;&i6=33;

§&i0=1364;&i1=0;&i2=1;&i3=0;&i4=-22;&i5=-1;&i6=33;

§&i0=1365;&i1=0;&i2=1;&i3=0;&i4=-22;&i5=-1;&i6=33;

§&i0=1366;&i1=0;&i2=1;&i3=0;&i4=-22;&i5=-1;&i6=33;

Timeout TX error send took over 1 sec
§&i0=1367;&i1=0;&i2=1;&i3=0;&i4=-22;&i5=-1;&i6=33;

Timeout TX error send took over 1 sec
§&i0=1368;&i1=0;&i2=1;&i3=0;&i4=-22;&i5=-1;&i6=33;

Timeout TX error send took over 1 sec
§&i0=1369;&i1=0;&i2=1;&i3=0;&i4=-22;&i5=-1;&i6=33;




restarting,

§&i0=3251;&i1=0;&i2=1;&i3=0;&i4=-22;&i5=-1;&i6=33;

§&i0=3252;&i1=0;&i2=1;&i3=0;&i4=-22;&i5=-1;&i6=33;

§&i0=3253;&i1=0;&i2=1;&i3=0;&i4=-22;&i5=-1;&i6=33;

§&i0=3254;&i1=0;&i2=1;&i3=0;&i4=-22;&i5=-1;&i6=33;

§&i0=3255;&i1=0;&i2=1;&i3=0;&i4=-22;&i5=-1;&i6=33;

§&i0=3256;&i1=0;&i2=1;&i3=0;&i4=-22;&i5=-1;&i6=33;

§&i0=3257;&i1=0;&i2=1;&i3=0;&i4=-22;&i5=-1;&i6=33;

§&i0=3258;&i1=0;&i2=1;&i3=0;&i4=-22;&i5=-1;&i6=33;

§&i0=3259;&i1=0;&i2=1;&i3=0;&i4=-22;&i5=-1;&i6=33;

§&i0=3260;&i1=0;&i2=1;&i3=0;&i4=-22;&i5=-1;&i6=33;

§&i0=3261;&i1=0;&i2=1;&i3=0;&i4=-22;&i5=-1;&i6=33;

Timeout TX error send took over 1 sec
§&i0=3262;&i1=0;&i2=1;&i3=0;&i4=-22;&i5=-1;&i6=33;

Timeout TX error send took over 1 sec
§&i0=3263;&i1=0;&i2=1;&i3=0;&i4=-22;&i5=-1;&i6=33;

Timeout TX error send took over 1 sec
§&i0=3264;&i1=0;&i2=1;&i3=0;&i4=-22;&i5=-1;&i6=33;

Timeout TX error send took over 1 sec
§&i0=3265;&i1=0;&i2=1;&i3=0;&i4=-22;&i5=-1;&i6=33;

Timeout TX error send took over 1 sec
§&i0=3266;&i1=0;&i2=1;&i3=0;&i4=-22;&i5=-1;&i6=33;

LdB
Posts: 1143
Joined: Wed Dec 07, 2016 2:29 pm

Re: code for UART comm from Pi to Arduino hangs up

Mon Jun 03, 2019 12:47 pm

Yep serialDataAvailable(Serial) was correct substitute

The audrino is handshaking it off by look, possibly can't process fast enough because it starts okay and than seems to catch it.

You need to fix arduino end .. the RASPI end is now correct :-)

What you could do is take the send timeout up to something like 3 seconds short term.

Code: Select all

timeout = millis() + 3000;   /* 3 second in the future */

dsyleixa123
Posts: 293
Joined: Mon Jun 11, 2018 11:22 am

Re: code for UART comm from Pi to Arduino hangs up

Mon Jun 03, 2019 12:58 pm

same thing for 3000ms send timeout :(

§&i0=3967;&i1=0;&i2=1;&i3=0;&i4=-22;&i5=-1;&i6=33;

§&i0=3968;&i1=0;&i2=1;&i3=0;&i4=-22;&i5=-1;&i6=33;

§&i0=3969;&i1=0;&i2=1;&i3=0;&i4=-22;&i5=-1;&i6=33;

§&i0=3970;&i1=0;&i2=1;&i3=0;&i4=-22;&i5=-1;&i6=33;

§&i0=3971;&i1=0;&i2=1;&i3=0;&i4=-22;&i5=-1;&i6=33;

§&i0=3972;&i1=0;&i2=1;&i3=0;&i4=-22;&i5=-1;&i6=33;

Timeout TX error send took over 3000 msec
§&i0=3973;&i1=0;&i2=1;&i3=0;&i4=-22;&i5=-1;&i6=33;

Timeout TX error send took over 3000 msec
§&i0=3974;&i1=0;&i2=1;&i3=0;&i4=-22;&i5=-1;&i6=33;

Timeout TX error send took over 3000 msec
§&i0=3975;&i1=0;&i2=1;&i3=0;&i4=-22;&i5=-1;&i6=33;

LdB
Posts: 1143
Joined: Wed Dec 07, 2016 2:29 pm

Re: code for UART comm from Pi to Arduino hangs up

Mon Jun 03, 2019 1:24 pm

You might have to ask Gordon if you are allowed to sit in loops like this with wiringPi, it almost looks to me like the linux serial device is blocking.

Out of interest lets sleep the thread for a 10ms after each character send .. so yield back to linux

Code: Select all

void loop() {   
  while(1) 
  {  
     unsigned long timeout;

     //-------------------------------------------------------------
     // send    
     char formatstr[MSGLEN];     
     // debug, cut-down:
     strcpy(formatstr, "§");
     strcat(formatstr, "message from Raspi: %d;\n");
     sprintf(mbuf, formatstr, i0);
	 timeout = millis() + 1000;   /* 1 second in the future */
     uint8_t i, len;
     len = strlen(mbuf);
     for(i=0; i<len && millis() < timeout; i++) { 
        serialPutchar( Serial, mbuf[i]);               // Send values to the slave   
        usleep(10000);  // sleep 10ms    
     }   
     if (i  != len)
     {
            fprintf(stderr, "Timeout TX error send took over 1 sec\n", n);
     }
     
     //-------------------------------------------------------------
     // receive
     
     inputString="";
     char cstr[TOKLEN];
   
     int  n=0;
     char inChar = 0;
     
     timeout = millis() + 1000;   /* 1 second in the future */
     while (inChar != '\n' && n < MSGLEN-2
	        && millis() < timeout) 
     { 
	    if (serialDataAvailable(Serial))
		{
			inChar = serialGetchar( Serial ); 
			inputString += inChar;   
			n++;
		}
             usleep(10000);  // sleep 10ms 
     }
   
     if (inChar == '\n')  // terminated correctly  
     {
          strcpy (mbuf, inputString.c_str() );
          fprintf(stderr,mbuf); fprintf(stderr,"\n");    
          // process mbuf !
           inputString="";
     } else {
	   if (n == MSGLEN-1)
		fprintf(stderr,"Buffer error %i characters sent\n", n);
                else fprintf(stderr, "Timeout RX error no data for 1 sec\n", n);
	  }
     }     
}

dsyleixa123
Posts: 293
Joined: Mon Jun 11, 2018 11:22 am

Re: code for UART comm from Pi to Arduino hangs up

Mon Jun 03, 2019 1:39 pm

now it's
initializing...
starting UART loop...
§&i0=0;&i1;3;

§&i0=803;&&i5=-1;&i6=33;

§&i0=801;&i1=0;&i2=1;&i3=0;&i4=-22;&i5=-1;&i6=33;

§&i0=802;&i1=0;&i2=1;&i3=0;&i4=-22;&i5=-1;&i6=33;

Timeout RX error no data for 1 sec
Timeout RX error no data for 1 sec
Timeout RX error no data for 1 sec
Timeout RX error no data for 1 sec
Timeout RX error no data for 1 sec
Timeout RX error no data for 1 sec

LdB
Posts: 1143
Joined: Wed Dec 07, 2016 2:29 pm

Re: code for UART comm from Pi to Arduino hangs up

Mon Jun 03, 2019 1:56 pm

Sorry that does not mean anything to me, what is happening.

From what I can work out the RASPI is looping waiting for data from the other device which isn't sending.
You can tell it is looping still because of the timeout messages.

So I am guessing the attached device is not responding ... any way to know if the other device is actually sending ????

If the other end is code just Arduino you can just follow the same thing with timeouts so it never locks up.

dsyleixa123
Posts: 293
Joined: Mon Jun 11, 2018 11:22 am

Re: code for UART comm from Pi to Arduino hangs up

Mon Jun 03, 2019 2:12 pm

I have no idea, I'm afraid

Return to “C/C++”