Nucleo 303k8 Serial problem

Hi, all!

Now I am porting the code from Arduino to MBED, and I encountered the following problem that the ported code to MBED does not work, although the code from Arduino works. The comparison does not work, apparently due to the fact that the “buffer ” is reset. The purpose of this code is to read strings of arbitrary length from a serial port without line termination characters (\n,\r, \0). My board is Nucleo 32 f303k8

Mbed code:

     #include "mbed.h"
     #include <string>
      
 
    Serial pc(SERIAL_TX, SERIAL_RX);

    DigitalOut myled(LED1);
 
    const int BUFFER_SIZE = 48;
    char buffer[BUFFER_SIZE] = {0};
    int ch;
    int StrCompare(const char *str1,const char *str2);
    int main()
      {
         Serial pc(SERIAL_TX, SERIAL_RX);
       
         pc.baud(115200);
 
         while(1) {
            
                 while (pc.readable()>0)
                  {
                   while ((ch = pc.getc())!= EOF)
                     {
                       int i = 0;
                       buffer[i]=ch;
                       i++;
                       //buffer[i]= '\0';
                     } 
                       if (StrCompare(buffer,"PRINT" ))
                              {
                               pc.printf("ok");
                              }
                   }
             //memset (buffer,0, sizeof(buffer));
           }
     }
 
       int StrCompare(const char *str1,const char *str2){
             if(!*str1 || !*str2)return 0;
             while(*str1){
               if(*str1++!=*str2++)return 0;
            }
       return 1;
     }

Arduino code:

 const int BUFFER_SIZE = 48;
 char bufferx[BUFFER_SIZE] = {0};
 int ch;

 void setup() {Serial.begin(115200);}

 void loop() {
 while (Serial.available()>0)
         {
            while ((ch = Serial.read())!= EOF)
             {
                     int i = 0;
                     bufferx[i]=ch;
                     i++;
                    //bufferx[i]= '\0';
             } 
            
           if (StrCompare(bufferx,"PRINT" ))
            {
               Serial.print("OK");
            }
           }
        //memset (bufferx,0, sizeof(bufferx));
        }
        int StrCompare(const char *str1,const char *str2){
         if(!*str1 || !*str2)return 0;
         while(*str1){ if(*str1++!=*str2++)return 0;}
    return 1;
  }

It’s a bit difficult to read because of bad indentations… (Please use code blocks.)

I think you want to put int i = 0; outside the while loop. You are not resetting the buffer. You are always writing to buffer[0].

Also, what is the purpose of StrCompare? You can compare two strings with strncmp.
http://www.cplusplus.com/reference/cstring/strncmp/

if (strncmp((const char*)buffer, "PRINT", 6) == 0) {

A code block starts and ends with triple backticks.

```
// your code here
```