// Libraries
#include <stdio.h>
#include <stdlib.h>
#include <string.h>

#define ENTER 13 // byte value of the Enter key (LF)
#define MCHARS 8 // max chars to accept 



char cmdbuf[4], intbuf[5], inStr[MCHARS];
byte nBytes = 0;
int inSerial = 0;
byte commaReceived = LOW;

void setup(){
  // set up Serial communication (through USB)
  Serial.begin(9600);
  Serial.flush();// clear receive buffer
  memset(cmdbuf, '\0', 4);
  memset(intbuf, '\0', 5);
  memset(inStr, '\0', (MCHARS+1) );
  Serial.println("Serial command test code ready: ");
   Serial.print(">");
}

void loop(){
  while(Serial.available() && inSerial != ENTER){
    inSerial = Serial.read();
    if(inSerial == ',') commaReceived = HIGH;
    Serial.print((char)inSerial);
    if(nBytes < MCHARS) inStr[nBytes] = (char)inSerial;
    if(nBytes < 3 && commaReceived == LOW) cmdbuf[nBytes] = (char)inSerial;
    else if((nBytes > 3 && nBytes < 8) && commaReceived == HIGH) intbuf[nBytes-4] = (char)inSerial;
    //    if(nBytes < 3 && commaReceived == LOW) cmdbuf[nBytes] = (char)inSerial;
    //    else if(nBytes < 7) intbuf[nBytes-3] = (char)inSerial;
    nBytes++;                          // increase the item string count
  }
 
  if(inSerial == ENTER){
    Serial.flush();                         // flush the serial data (overkill?)
    Serial.println("  ");
    Serial.print(nBytes);
    Serial.print(" B read from serial: ");
    Serial.println(inStr);                     // print a newline
    int convint = atoi(intbuf);
    Serial.print("command received: ");
    Serial.println(cmdbuf);
    Serial.print("Value received: ");
    Serial.print(intbuf);
    Serial.print(", value: ");
    Serial.println(convint);
    inSerial = 0;
    memset(cmdbuf, '\0', 4);
    memset(intbuf, '\0', 5);
    memset(inStr, '\0', MCHARS);
    nBytes = 0;
    commaReceived = LOW;
  }



}// loop










