How to input numbers in serial monitor?

Hey guys, so I am creating a code, but I am stuck as to how I can actually input values into the serial monitor. I want different values such as AgeAdult, AgeTeen, and AgeKid to show different settings within my device, can you guys help me with this(P.S., I have been working on this for a long time and if you need any reference, please go to my profile and see my other questions)

#include <CountUpDownTimer.h>
#include <Wire.h>
#include <LiquidCrystal_I2C.h>
const int FSRPin = A0; // force sensitive resistor
const int ColorPin = 9; // ColorStat Sensor
const int LedPin = 13; // OUTPUTPIN
CountUpDownTimer T(DOWN);
LiquidCrystal_I2C lcd(0x27, 16, 2);
// time values
int initial = 1;
int timeon = 0;
int mins = 0;
int secs = 10;
int start_time = 0;
int end_time = 0;
int elapased_time = 0;
// sensor values
int colorValue = 0;
int FSRValue = 0;
float temp = 0.0;
int sensorValue = 0;
// control values
int flag = 1;
int command = 0;
#define ONTIME 10
//Linear Actuator
int Threshold = 0; // Add more threshold integers based on different cases?

const int A1B = 7; // In1
const int A1A = 8; // In2
int RESISTOR_READING = 0;

//Serial Monitor Variables


String TheAge;
int AgeAdult;
int AgeTeen;
int AgeKid;
int Retract;

String mesg="Enter Age.";

void setup()
{
lcd.init();
lcd.backlight();
lcd.clear();
lcd.setCursor(0, 0);
lcd.print("Started...");
Serial.begin(9600);
Serial.println("Initializing...");
Serial.println("Started...");
pinMode(FSRPin, INPUT);
pinMode(ColorPin, INPUT);
pinMode(LedPin, OUTPUT);
digitalWrite(LedPin, LOW);
T.SetTimer(0, 0, 0, 10);
T.StartTimer();
command = 0;

pinMode(A1A, OUTPUT);
pinMode(A1B, OUTPUT);
}
int smooth()
{
return analogRead(FSRPin);
}
void loop()
{
FSRValue = smooth();
colorValue = digitalRead(ColorPin);
RESISTOR_READING = digitalRead(FSRValue);


Serial.println(mesg);
while (Serial.available() ==0) {
  Serial.println("I am waiting...");
  delay(10000);
}
TheAge=Serial.readString();
  if(TheAge = AgeAdult) {
      Serial.println("Age: Adult");
      analogWrite(A1B, 0);
      analogWrite(A1A, 225);
      takeMeasurement("Adult");
      delay(1000);
      lcd.print("Starting");
      delay(250);
  }
  TheAge=Serial.readString();
    if(TheAge = AgeTeen) {
      Serial.println("Age: Teen");
      takeMeasurement("teen");
      delay(1000);
      lcd.print("Starting");
      analogWrite(A1B, 0);
      analogWrite(A1A, 225);
      delay(250);
  }
  TheAge=Serial.readString();
    if(TheAge = AgeKid) {
      Serial.println("Age: Kid");
      takeMeasurement("Kid");
      delay(1000);
      lcd.print("Starting");
      analogWrite(A1B, 0);
      analogWrite(A1A, 225);
      delay(250);
  }
  TheAge=Serial.readString();
    if (TheAge = Retract); {
    analogWrite(A1B, 201);
    analogWrite(A1A, 0);
    delay(250);
  }
//if(TheAge=0)
{
lcd.setCursor(0, 0);
lcd.print("Need More Pressure");
Serial.print(" -> Need More Pressure");
analogWrite(A1B, 201);
analogWrite(A1A, 225);
sensorValue = 0;
Threshold = 0;
}
}
void takeMeasurement(String age)
{
if (age == "Kid")
{
Threshold = 300;
lcd.setCursor(0, 0);
lcd.print("Kids 6-12 Years");
Serial.print(" -> Kids 6-12 Years");
sensorValue = 1;
if (RESISTOR_READING >= 300)
{
analogWrite(A1B, 201);
analogWrite(A1A, 225);
}
}
else if (age == "Teen")
{
Threshold = 400;
lcd.setCursor(0, 0);
lcd.print("Teen 13-19 Years");
Serial.print("-> Teens 13-19 Years");
sensorValue = 1;
if (RESISTOR_READING >= 400)
{
analogWrite(A1B, 201);
analogWrite(A1A, 225);
}
}
else if (age == "Adult")
{
Threshold = 600;
lcd.setCursor(0, 0);
lcd.print("Adult");
Serial.print("-> Adult");
sensorValue = 1;
}
if (RESISTOR_READING >= 600)
{
analogWrite(A1B, 201);
analogWrite(A1A, 225);
delay(1000);
}
if (sensorValue == 1)
{
timeon = 1;
}
else
{
timeon = 0;
}
if (timeon == 1)
{
// T.Timer();
digitalWrite(LedPin, HIGH);
if (T.TimeHasChanged())
{
Serial.print(":");
Serial.print(T.ShowSeconds());
lcd.setCursor(0, 1);
lcd.print(T.ShowSeconds());
}
if (T.ShowSeconds() == 0)
{
T.ResetTimer();
lcd.clear();
lcd.print("Release Pressure");
Serial.println("Release the Pressure");
digitalWrite(LedPin, LOW);
command = 2;
// timeon=0;
// sensorValue=0;
// break;
}
}
Serial.println("");
// case 2:
//delay(10);
if (FSRValue == 0 && colorValue == 0)
{
// T.ResetTimer();
// T.Timer(); // run the timer
Serial.print(" ");
Serial.print(millis());
Serial.println("");
T.SetTimer(0, 0, 0, 5);
lcd.clear();
lcd.print("Start Time");
command = 3;
start_time = millis();
// break;
}
Serial.println("");
// case 3:
if (FSRValue == 0 && colorValue == 1) // (flag==1)
{
// Serial.print(" ");
// Serial.print(millis());
// Serial.println("");
//Serial.println("State :3");
command = 4;
T.SetTimer(0, 0, 0, 5);
end_time = millis();
lcd.clear();
lcd.print("End Time");
flag = 0;
elapased_time = (end_time - start_time) / 1000;
Serial.print("Elapased Time : ");
Serial.println(elapased_time);
delay(1000);
lcd.clear();
lcd.print("elapased_time : "); // Added this print statement
lcd.print(elapased_time);
// break;
}
else
{
Serial.print("");
}
Serial.println("");
// case 4:
if (flag == 0)
{
T.Timer(); // run the timer
if (T.TimeHasChanged()) // this prevents the time from being constantly shown.
{
Serial.print(":");
Serial.print(T.ShowSeconds());
// lcd.clear();
// lcd.print(T.ShowSeconds());
}
if (T.ShowSeconds() == 0)
{
T.ResetTimer();
command = 0;
T.SetTimer(0, 0, 0, 10);
flag = 1;
// break;
}
}
Serial.println("");
// }
delay(1000);
}

thank you

Whoops.

Try Robin2's serial input basics topic.

Double whoops

despite the thread title -- "input numbers in serial monitor" it seems that you're really looking for a string, "AgeKid" that identifies what your trying to read

look this over


int adult;
int teen;
int kid;

char buf [80];
char s [80];

void loop()
{
    if (Serial.available ())  {
        int n = Serial.readBytesUntil ('\n', buf, sizeof(buf)-1);
        buf [n] = '\0';

        int   val;
        sscanf (buf, "%*s %d", &val);   // ignore leading string

        if (strstr (buf, "adult"))  {
            adult = val;
            sprintf (s, " %3d %s", adult, "Adult");
        }
        else if (strstr (buf, "teen"))  {
            teen = val;
            sprintf (s, " %3d %s", teen, "Teen");
        }
        else if (strstr (buf, "kid"))  {
            kid = val;
            sprintf (s, " %3d %s", kid, "Kid");
        }
        else
            sprintf (s, " invalid %s", buf);

        Serial.println (s);
        // and/or display on LCD
    }
}

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

int intVar = Serial.parseInt(); or
float floatVar = Serial.parseFloat();

(post deleted by author)

Okay guys, I do not understand any of this, can you help me understand because I cannot find it in Arduino references

You're joking, surely?
This (as the URL suggests) is from the reference.

No, variables like strstr and sprintf

So you are saying that I should use the variable string for these instead of int?

Here?

I will come back after seeing Robin2's topic

not sure what you expected if(TheAge = AgeAdult) to do, besides it being an assignment, "=", why compare, "==", an "int" to a "String"?

Okay, so my underlying plan is that once an integer (AgeAdult, AgeTeen, AgeKid) is inputed into the serial monitor, the arduino will take that information to use. I am trying to make a device that checks perfusion using a linear actuator (to blanch a fingernail) and a force sensitive resistor to tell it when to stop. I have values already for when the FSR should tell the actuator when to stop (300, 400, and 600 as Threshold). Once this is done, the arduino will wait for 10 seconds before retracting the actuator. Once the nailbed returns to its original color, elapsed time will show how long it took.

Perhaps this will help you understand the use of my code

I have looked over this code and I think I understand it. However, your integers, are they different than mine or do you expect them to be the same?

my comment hasn't been addressed.

  • why is there what looks like a comparison between an "int" and a "String"?
  • why is the even an if statement?
  • where is there a translation between the "String" variable to an "int"?

furthermore

  • why is there a 10 second delay if there is no serial input

  • why are these reads done regardless if serial input is available()?

  • i'm confused why there are inputs for adult, teen and kid, shouldn't there only be one

  • i don't understand the case where "Retract" is used (and yes there is an erroneous ";" )

  • and why is this done each iteration of loop()

it would make more sense that loop() monitors for serial input. when serial input is available, it reads some value from the serial interface that inidicates adult, teen OR kid which then initiates some action

while this action is enabled, loop() presumably repeatedly monitors the actoin (force sensor) and stops the action when the sensor exceeds some threshold.

Maybe a different example that has character matching, numerics, and subsequent cases that can easily be extended.

The example below is for the Uno/Nano AVR boards and implements a terminal-based calculator. It shows many useful concepts.

// Extensible calculator by M. Ray Burnette 20130906
// Nano: Binary sketch size: 12056 bytes (of a 30,720 byte maximum)

#include <Streaming.h>
#define BAUD 9600
#define Err 2
#define timeoutPeriod 2147483647// Long var... about 25 days
//#define timeoutPeriod 10000   // 10 seconds
#define operations 27           // 1-27 not 0-26

byte j;
byte decimals = 7;
byte DigPinNo;
byte AnaPinNo;
boolean Degrees = true;  // Trig input is in degrees
float a;
float b;
float Pi = 3.141592654;
float LastX;
unsigned long temp;  // factorials
unsigned long T0;    // timing
unsigned long T1;    // timing
String Operation;
float* Mem[43] = {};  // memory registers 0-9, :-@, A-Z == 10 + 7 + 26
char* Inst = "XYZ\n";
char* sStack[ ] = {
  "DIV","MUL","ADD","SUB","Y^X","LOG","NLG","10X","1/X","e^X",
  "SQR","X^2","SIN","COS","TAN","ASN","ACS","ATN","DEG","RAD",
  "DEC","RTT","DPR","APR","LTX","FN!","MEM"};

void setup()
{
  Serial.begin(BAUD);
  Serial.setTimeout(timeoutPeriod); // default is 1 second
  // 20130208 Added Command DRP to read digital pin state
  pinMode(3, INPUT);      //  sets the digital pin 3 as input
  pinMode(6, INPUT);      //  sets the digital pin 6 as input
  pinMode(7, INPUT);      //  sets the digital pin 7 as input
  pinMode(8, INPUT);      //  sets the digital pin 8 as input
  pinMode(9, INPUT);      //  sets the digital pin 9 as input
  pinMode(10, INPUT);      // sets the digital pin 10 as input
  pinMode(11, INPUT);      // sets the digital pin 11 as input
  pinMode(12, INPUT);      // sets the digital pin 12 as input
}

void loop()
{
  Serial.readBytes( Inst, 4);
  Operation = Inst; Operation.trim();

  for ( j= 0; j<operations; j++) {
    if (Operation.equalsIgnoreCase(sStack[j])) {
      T0 = millis();
      break;
    }
  }
  
  switch (j) 
    {
    case 0:  // DIVide
          a = Serial.parseFloat();
          b = Serial.parseFloat();
          LastX = a / b;
          Serial << _FLOAT(LastX , decimals);
          break;

    case 1:  // MULtiply
          a = Serial.parseFloat();
          b = Serial.parseFloat();
          LastX = a * b;
          Serial << _FLOAT(LastX, decimals);
          break;

    case 2:  // ADD
          a = Serial.parseFloat();
          b = Serial.parseFloat();
          LastX = a + b;
          Serial << _FLOAT(LastX, decimals);
          break;

    case 3:  // SUBstract
          a = Serial.parseFloat();
          b = Serial.parseFloat();
          LastX = a - b;
          Serial << _FLOAT(LastX, decimals);
          break;

    case 4:    // Y ^ X : Y to the X power
            b = Serial.parseFloat();
            a = Serial.parseFloat();
            LastX = pow(b, a);
            Serial << _FLOAT(LastX, decimals);
            break;

    case 5:    // LOGrithm of X
            b = Serial.parseFloat();
            LastX = log10(b);
            Serial << _FLOAT(LastX, decimals);
            break;

    case 6:    // Natural LOGrithm of X
            b = Serial.parseFloat();
            LastX = log(b);
            Serial << _FLOAT(LastX, decimals);
            break;

    case 7:    // 10 ^ X : 10 raised to X power
            b = Serial.parseFloat();
            LastX = pow(10.00, b);
            Serial << _FLOAT(LastX, decimals);
            break;

    case 8:    // 1/X : reciprocal of X
            b = Serial.parseFloat();
            LastX = 1.00 / b;
            Serial << _FLOAT(LastX, decimals);
            break;

    case 9:    // e ^ X : e = 2.718281828459045 raised to X
            b = Serial.parseFloat();
            LastX = pow(2.718281828459045, b);
            Serial << _FLOAT(LastX, decimals);
            break;

    case 10:   // SQRoot X
            b = Serial.parseFloat();
            LastX = sqrt(b);
            Serial << _FLOAT(LastX, decimals);
            break ;

    case 11:    // x^2
            b = Serial.parseFloat();
            LastX = b * b;
            Serial << _FLOAT(LastX, decimals);
            break;

    case 12:    // SIN
            b = Serial.parseFloat();
            if (Degrees){b = b * Pi / 180.0; }
            LastX = sin(b);
            Serial << _FLOAT(LastX, decimals);
            break;

    case 13:    // COS
            b = Serial.parseFloat();
            if (Degrees){b = b * Pi / 180.0; }
            LastX = cos(b);
            Serial << _FLOAT(LastX, decimals);
            break;

    case 14:    // TAN
            b = Serial.parseFloat();
            if (Degrees){b = b * Pi / 180.0; }
            LastX = tan(b);
            Serial << _FLOAT(LastX, decimals);
            break;

    case 15:    // ASN   ArcSin
            b = Serial.parseFloat();
            if (Degrees) {LastX = asin(b) * 180.0 / Pi;
            }  else {LastX = asin(b); }
            Serial << _FLOAT(LastX, decimals);
            break;

    case 16:    // ACS   ArcCos
            b = Serial.parseFloat();
            if (Degrees) {LastX = acos(b) * 180.0 / Pi;
            }  else {LastX = acos(b); }
            Serial << _FLOAT(LastX, decimals);
            break;

    case 17:    // ATN  ArcTan
            b = Serial.parseFloat();
            if (Degrees) {LastX = atan(b) * 180.0 / Pi;
            }  else {LastX = atan(b); }
            Serial << _FLOAT(LastX, decimals);
            break;

    case 18:    // DEG (normal startup)
            Degrees = true;
            break;

    case 19:    // RAD (alterate input in radians)
            Degrees = false;
            break;

    case 20:    // DEC set decimal places
            b = Serial.parseInt();
            if (b>10) {b = 10; }
            decimals = b;
            break;
    
    case 21:    // RTT calculate the Hypotenuse of a right triangle from sides a and b
            a = Serial.parseFloat();
            b = Serial.parseFloat();
            LastX = sqrt(a*a + b*b);
            Serial << _FLOAT(LastX, decimals);
            break;

    case 22:    //DPR DigitalPin Read # valid 3, 6 - 12 (Nano)  Returns: 0, 1 for state or 2 for Error
            DigPinNo = Serial.parseInt(); 
            if (DigPinNo < 3 || DigPinNo > 12) {
                Serial << Err; break; }
            if (DigPinNo == 4 || DigPinNo == 5) {
                Serial << Err; break; }
            Serial << digitalRead(DigPinNo);
            break;

    case 23:    //APR Analog Pin Read - A0 through A7 (Nano)  Return 0 - 1024 value for 10-bit A/D or "Err" for Error
            AnaPinNo = Serial.parseInt(); 
            if (AnaPinNo < 0 || AnaPinNo > 7) {
              if (AnaPinNo == 255) {
                for (byte q = 0; q < 8; q++) {
                  Serial << analogRead(q) << " " ; }
                  break; }
                  Serial << "Err\n"; break; }
            Serial << analogRead(AnaPinNo);
            break;

    case 24:    //LTX  send value of LTX
            Serial << _FLOAT(LastX, decimals);
            break;

    case 25:    // Factorial FN!  Max value of x! is 12 for Arduino== 479,001,600
            a = Serial.parseFloat();
            temp = a;    // need an unsigned double here
            if ( a > 12 ) {
              Serial << "Err\n" ; break ; }
            for ( j= 1; j < int (a); j++) {
              temp = temp * byte (j); }
            if (a == 0) temp = 1;  // special by definition
            LastX = float (temp);
            Serial << temp;
            break;

    default:
            Serial << "?\n" ;
            break;
    }

  Serial.println();    // cr lf   Adjust if receiver expects different termination
  T1 = millis();
  // Serial.print(F("Milliseconds = ")); Serial.print( T1 - T0);
  // un-remark the next line and recompile if you want to see RAM usage
  // Serial.print(F("  Free RAM = ")); Serial.println(freeRam()); Serial.println();
}

From an ancient forum post here

Hey guys, this is legitimately really hard to understand because I have never worked with inputting values and integers into the serial monitor.