element14 Community
element14 Community
    Register Log In
  • Site
  • Search
  • Log In Register
  • Community Hub
    Community Hub
    • What's New on element14
    • Feedback and Support
    • Benefits of Membership
    • Personal Blogs
    • Members Area
    • Achievement Levels
  • Learn
    Learn
    • Ask an Expert
    • eBooks
    • element14 presents
    • Learning Center
    • Tech Spotlight
    • STEM Academy
    • Webinars, Training and Events
    • Learning Groups
  • Technologies
    Technologies
    • 3D Printing
    • FPGA
    • Industrial Automation
    • Internet of Things
    • Power & Energy
    • Sensors
    • Technology Groups
  • Challenges & Projects
    Challenges & Projects
    • Design Challenges
    • element14 presents Projects
    • Project14
    • Arduino Projects
    • Raspberry Pi Projects
    • Project Groups
  • Products
    Products
    • Arduino
    • Avnet & Tria Boards Community
    • Dev Tools
    • Manufacturers
    • Multicomp Pro
    • Product Groups
    • Raspberry Pi
    • RoadTests & Reviews
  • About Us
    About the element14 Community
  • Store
    Store
    • Visit Your Store
    • Choose another store...
      • Europe
      •  Austria (German)
      •  Belgium (Dutch, French)
      •  Bulgaria (Bulgarian)
      •  Czech Republic (Czech)
      •  Denmark (Danish)
      •  Estonia (Estonian)
      •  Finland (Finnish)
      •  France (French)
      •  Germany (German)
      •  Hungary (Hungarian)
      •  Ireland
      •  Israel
      •  Italy (Italian)
      •  Latvia (Latvian)
      •  
      •  Lithuania (Lithuanian)
      •  Netherlands (Dutch)
      •  Norway (Norwegian)
      •  Poland (Polish)
      •  Portugal (Portuguese)
      •  Romania (Romanian)
      •  Russia (Russian)
      •  Slovakia (Slovak)
      •  Slovenia (Slovenian)
      •  Spain (Spanish)
      •  Sweden (Swedish)
      •  Switzerland(German, French)
      •  Turkey (Turkish)
      •  United Kingdom
      • Asia Pacific
      •  Australia
      •  China
      •  Hong Kong
      •  India
      •  Japan
      •  Korea (Korean)
      •  Malaysia
      •  New Zealand
      •  Philippines
      •  Singapore
      •  Taiwan
      •  Thailand (Thai)
      •  Vietnam
      • Americas
      •  Brazil (Portuguese)
      •  Canada
      •  Mexico (Spanish)
      •  United States
      Can't find the country/region you're looking for? Visit our export site or find a local distributor.
  • Translate
  • Profile
  • Settings
Arduino
  • Products
  • More
Arduino
Arduino Forum Problem with Arduino serial rx program
  • Blog
  • Forum
  • Documents
  • Quiz
  • Events
  • Polls
  • Files
  • Members
  • Mentions
  • Sub-Groups
  • Tags
  • More
  • Cancel
  • New
Join Arduino to participate - click to join for free!
Actions
  • Share
  • More
  • Cancel
Forum Thread Details
  • Replies 1 reply
  • Subscribers 416 subscribers
  • Views 345 views
  • Users 0 members are here
  • receive
  • serial
  • arduino
Related

Problem with Arduino serial rx program

SGarciaV
SGarciaV over 13 years ago

Please help :-)

 

Hi all,

 

I am currently writing an Arduino app which will be acting upon data received through its serial port. I am using the Arduino Uno and the Arduino IDE Serial Monitor. The Uno is connected to the PC through the USB cable. The host will be sending commands in the following form:

 

<command>:<data>*

 

<command> is a one character command.

<data> may be a string of letters or digits

 

The command line is terminated by the trialing asterisk. At this time I have various versions of the routine that receives and interprets 2 possible commands, but none are working as they should. I have tried various techniques but I am not sure which is recommended:

 

  • Locate the serial receive code in the main Loop routine. Use Serial.available(). Interpret the command line as the characters are received.
  • Same as above, but first accumulate the command line and then parse and interpret when the asterisk is received.
  • Locate code to receive and interpret command line in the serialEvent routine.
  • Locate code that accumulates received characters into a string in the serialEvent routine. When done set a Boolean flag. Locate code that parses and interprets command in the main Loop routine and is executed when flag becomes True (all data in).
  • In the serialEvent routine use while (Serial.available()).
  • In the serialEvent routine use if (Serial.available())
  • In the serialEvent routine don’t use neither of the above since the event is fired when there is serial data available

 

The code below is my latest attempt. It does not work. When I uncomment the “Serial.print("strInComm: ");” lines it seems to print garbage or it stops halfway through the “strInComm’ text.

 

If I uncomment the lines inside the switch statement ("Percent dec: " and "Delay: ") sometimes they never execute, as though execution does not go into the switch. In some cases gibberish is printed out. I note that both the code and the Serial Monitor are set to 9600 baud.

 

At this time I am going to start from scratch, but if anyone can look at my code and provide feedback I’d greatly appreciate it. I could use another pair of eyes looking at it. Perhaps it is something trivial that I missed. I took the basic infrastructure of the code from the serial examples. I also watched Jeremy Blum’s episode 6 Arduino tutorial series. This episode describes serial communications. I was introduced to Serial.flush(), a statement that I have not tried (yet).

 

Thank you for your time and assistance. Salvador

 

 

/*

 

Test program to receive commands from a host computer.

 

Command format:

 

  <command>:<data>*

 

* indicates end of command line.

 

*/

 

float PercentData;

 

//For serial reception chars and control.

String strInComm = "";

boolean bComplete = false;

 

int intDelay = 0;

//int iInChar;

int iCmdType;

 

void setup()

{

  Serial.begin(9600);

//  Serial.begin(115200);

 

  // reserve 40 bytes for the settings information:

  //strInComm.reserve(40);

  strInComm ="";

 

  //Initialize percent variable

  PercentData = 0.03;  

 

  //Initialize delay variable.

  intDelay = 3;

}

 

 

void loop() //Main Loop

{

 

  String sCmd = "";

  String sData = "";

  char chInChar;

 

 

  if (bComplete) {

    //I have the complete line, parse.

   

//Serial.print("strInComm: ");

//Serial.println(strInComm);

 

        //The entire line is in, now parse the command and interptret.

        //Get the command. The command is 1 char.

        sCmd = strInComm.substring(0,1);

        //Get the data. This goes from the : to the end.

        sData = strInComm.substring(strInComm.indexOf(':') + 1);

               

//Serial.print("sCmd: ");

//Serial.println(sCmd);

//Serial.print("sData: ");

//Serial.println(sData);

 

        if (sCmd=="p" or sCmd=="P")

          chInChar = 'p';

        if (sCmd=="d" or sCmd=="D")

          chInChar = 'd';

 

        switch (chInChar) {

          case 'p':

            char cmdChar[sData.length() + 1];

            sData.toCharArray(cmdChar, (sData.length() + 1));

            PercentData = atoi(cmdChar) / 100.0;

//Serial.print("Percent dec: ");

//Serial.println(PercentData);

           

            break;

          case 'd':

            char cmdChar2[sData.length() + 1];

            sData.toCharArray(cmdChar2, (sData.length() + 1));

            intDelay = atoi(cmdChar2);

//Serial.print("Delay: ");

//Serial.println(intDelay);

 

            break; 

        }  //Switch chInChar

 

   

    Serial.print("Percent dec: ");

    Serial.println(PercentData);

    Serial.print("Delay: ");

    Serial.println(intDelay);

    //delay(1000); 

 

    bComplete = false;

 

     //Reinitialize the input buffer.

    strInComm="";

 

  }

}

 

void serialEvent() {

 

  String sCmd = "";

  String sData = "";

 

//Serial.println("In serialEvent");

 

    char inChar = (char)Serial.read();

    // if the incoming character is an *, set a flag

    // so the main loop can do something about it:

    if (inChar == '*') {

      bComplete = true;

    }

    else {

      strInComm += inChar;

    }

 

//Serial.println(strInComm); 

}

  • Sign in to reply
  • Cancel
Parents
  • SGarciaV
    SGarciaV over 13 years ago

    I got it to work. I started from scratch and added code in sections until I found the snippet that was causing the weird issue

     

    For some reason the two statements inside the switch were causing the problem:

     


    char cmdChar[sData.length() + 1];

    sData.toCharArray(cmdChar, sizeof(cmdChar));

     

    I moved these out of the switch and it worked as expected. Of course, I have no idea why it was not working as I had it. So in summary, this was the old code:

     


    switch (chInChar) {

    case 'p':

       char cmdChar[sData.length() + 1];

       sData.toCharArray(cmdChar, (sData.length() + 1));

       PercentData = atoi(cmdChar) / 100.0;



       break;

    case 'd':

       char cmdChar2[sData.length() + 1];

       sData.toCharArray(cmdChar2, (sData.length() + 1));

       intDelay = atoi(cmdChar2);

     


       break; 

    }  //Switch chInChar

     

    And the new code: (Note that I also used sizeof() now)

     


    char cmdChar[sData.length() + 1];

    sData.toCharArray(cmdChar, sizeof(cmdChar));

     


    switch (chInChar) {

    case 'p':

       PercentData = atof(cmdChar) / 100.0;



       break;

    case 'd':

       intDelay = atoi(cmdChar);

       break; 

    }  //Switch chInChar

     

    Thanks to all that took the time to read my original question. Find below the full sketch of the working code. Salvador

     

    PS: I don't know why the editor enclosed the above snippets in tables. My apologies for any visual inconvenience.

     

     

     

    String strInComm = "";

    boolean bComplete = false;

     

    float PercentData;

    int intDelay;

     

    void setup()

    {

      Serial.begin(9600);

    //  Serial.begin(115200);

     

    }

     

     

    void loop() //Main Loop

    {

     

      String sCmd = "";

      String sData = "";

      char chInChar;

     

      if (bComplete) {

        //The enire line is in, now parse the command and interptret.

        //Get the command. The command is 1 char.

        sCmd = strInComm.substring(0,1);

        //Get the data. This goes from the : to the end.

        sData = strInComm.substring(strInComm.indexOf(':') + 1);

     

     

        //Serial.print("strInComm: ");

        //Serial.println(strInComm);

        //Serial.print("Cmd: ");

        //Serial.println(sCmd);

        //Serial.print("Data: ");

        //Serial.println(sData);

     

        if (sCmd=="p" or sCmd=="P")

          chInChar = 'p';

        if (sCmd=="d" or sCmd=="D")

          chInChar = 'd';

     

            char cmdChar[sData.length() + 1];

            sData.toCharArray(cmdChar, sizeof(cmdChar));

     

        switch (chInChar) {

          case 'p':

            PercentData = atof(cmdChar) / 100.0;

    //Serial.print("Percent dec: ");

    //Serial.println(PercentData);

     

            break;

          case 'd':

            intDelay = atoi(cmdChar);

    //Serial.print("Delay: ");

    //Serial.println(intDelay);

     

            break; 

        }  //Switch chInChar

     

     

       bComplete = false;

       strInComm = "";

      }

     

        Serial.print("Percent dec: ");

        Serial.println(PercentData);

        Serial.print("Delay: ");

        Serial.println(intDelay);

        delay(1000); 

     

    }

     

    void serialEvent() {

     

      while (Serial.available() > 0)  {

        char inChar = (char)Serial.read();

        // if the incoming character is an *, set a flag

        // so the main loop can do something about it:

        if (inChar == '*') {

          bComplete = true;

        }

        else {

          strInComm += inChar;

        }

      }

     

    }

    • Cancel
    • Vote Up 0 Vote Down
    • Sign in to reply
    • Cancel
Reply
  • SGarciaV
    SGarciaV over 13 years ago

    I got it to work. I started from scratch and added code in sections until I found the snippet that was causing the weird issue

     

    For some reason the two statements inside the switch were causing the problem:

     


    char cmdChar[sData.length() + 1];

    sData.toCharArray(cmdChar, sizeof(cmdChar));

     

    I moved these out of the switch and it worked as expected. Of course, I have no idea why it was not working as I had it. So in summary, this was the old code:

     


    switch (chInChar) {

    case 'p':

       char cmdChar[sData.length() + 1];

       sData.toCharArray(cmdChar, (sData.length() + 1));

       PercentData = atoi(cmdChar) / 100.0;



       break;

    case 'd':

       char cmdChar2[sData.length() + 1];

       sData.toCharArray(cmdChar2, (sData.length() + 1));

       intDelay = atoi(cmdChar2);

     


       break; 

    }  //Switch chInChar

     

    And the new code: (Note that I also used sizeof() now)

     


    char cmdChar[sData.length() + 1];

    sData.toCharArray(cmdChar, sizeof(cmdChar));

     


    switch (chInChar) {

    case 'p':

       PercentData = atof(cmdChar) / 100.0;



       break;

    case 'd':

       intDelay = atoi(cmdChar);

       break; 

    }  //Switch chInChar

     

    Thanks to all that took the time to read my original question. Find below the full sketch of the working code. Salvador

     

    PS: I don't know why the editor enclosed the above snippets in tables. My apologies for any visual inconvenience.

     

     

     

    String strInComm = "";

    boolean bComplete = false;

     

    float PercentData;

    int intDelay;

     

    void setup()

    {

      Serial.begin(9600);

    //  Serial.begin(115200);

     

    }

     

     

    void loop() //Main Loop

    {

     

      String sCmd = "";

      String sData = "";

      char chInChar;

     

      if (bComplete) {

        //The enire line is in, now parse the command and interptret.

        //Get the command. The command is 1 char.

        sCmd = strInComm.substring(0,1);

        //Get the data. This goes from the : to the end.

        sData = strInComm.substring(strInComm.indexOf(':') + 1);

     

     

        //Serial.print("strInComm: ");

        //Serial.println(strInComm);

        //Serial.print("Cmd: ");

        //Serial.println(sCmd);

        //Serial.print("Data: ");

        //Serial.println(sData);

     

        if (sCmd=="p" or sCmd=="P")

          chInChar = 'p';

        if (sCmd=="d" or sCmd=="D")

          chInChar = 'd';

     

            char cmdChar[sData.length() + 1];

            sData.toCharArray(cmdChar, sizeof(cmdChar));

     

        switch (chInChar) {

          case 'p':

            PercentData = atof(cmdChar) / 100.0;

    //Serial.print("Percent dec: ");

    //Serial.println(PercentData);

     

            break;

          case 'd':

            intDelay = atoi(cmdChar);

    //Serial.print("Delay: ");

    //Serial.println(intDelay);

     

            break; 

        }  //Switch chInChar

     

     

       bComplete = false;

       strInComm = "";

      }

     

        Serial.print("Percent dec: ");

        Serial.println(PercentData);

        Serial.print("Delay: ");

        Serial.println(intDelay);

        delay(1000); 

     

    }

     

    void serialEvent() {

     

      while (Serial.available() > 0)  {

        char inChar = (char)Serial.read();

        // if the incoming character is an *, set a flag

        // so the main loop can do something about it:

        if (inChar == '*') {

          bComplete = true;

        }

        else {

          strInComm += inChar;

        }

      }

     

    }

    • Cancel
    • Vote Up 0 Vote Down
    • Sign in to reply
    • Cancel
Children
No Data
element14 Community

element14 is the first online community specifically for engineers. Connect with your peers and get expert answers to your questions.

  • Members
  • Learn
  • Technologies
  • Challenges & Projects
  • Products
  • Store
  • About Us
  • Feedback & Support
  • FAQs
  • Terms of Use
  • Privacy Policy
  • Legal and Copyright Notices
  • Sitemap
  • Cookies

An Avnet Company © 2026 Premier Farnell Limited. All Rights Reserved.

Premier Farnell Ltd, registered in England and Wales (no 00876412), registered office: Farnell House, Forge Lane, Leeds LS12 2NE.

Follow element14

  • X
  • Facebook
  • linkedin
  • YouTube