Serial monitor and integers

The input to the atoi function is an ASCII string (null terminated character array) that represents a number.

Another way is to use the parseInt function.. That function takes a string, too.

What is being sent from the MIT ai2 Android app? I am not familiar with that. I use the Serial Bluetooth Terminal app.. If I send a number from that app, it comes in through the HC05 as ASCII and must be converted before it is a number that can be use in math functions.

Here is a demo using methods from the serial input basics tutorial that receives a number as a string from Bluetooth terminal via a HC05 Bluetooth module connected to an Uno. The Bluetooth app must send a line feed (\n) as a terminator. Connect the HC05 Tx to Uno pin 4 and HC05 RX connected to Uno pin 7 through a 5V to 3.3V voltage divider or modify the code with your connection.


#include <SoftwareSerial.h>
SoftwareSerial bt(4, 7); // RX | TX

const byte numChars = 16;
char receivedChars[numChars];   // an array to store the received data

const byte ledPin = 13;

boolean newData = false;

void setup()
{
   Serial.begin(9600);
   bt.begin(9600);
   Serial.println("<Arduino is ready>");
   pinMode(ledPin, OUTPUT);
   digitalWrite(ledPin, LOW);
}

void loop()
{
   recvWithEndMarker();
   if (newData == true)
   {
      Serial.print("The received string = ");
      Serial.println(receivedChars);
      Serial.print("The string converted to a number = ");
      Serial.println(atoi(receivedChars));      
      newData = false;
   }
}

void recvWithEndMarker()
{
   static byte ndx = 0;
   char endMarker = '\n';
   char rc;

   while (bt.available() > 0 && newData == false)
   {
      rc = bt.read();
      //Serial.print(rc);
      if (rc == '\r')
      {
         return;
      }
      if (rc != endMarker)
      {
         receivedChars[ndx] = rc;
         ndx++;
         if (ndx >= numChars)
         {
            ndx = numChars - 1;
         }
      }
      else
      {
         receivedChars[ndx] = '\0'; // terminate the string
         ndx = 0;
         newData = true;
      }
   }
}