-1

I am trying to get user input from the serial monitor to turn a stepper motor according to the input. However my code returns the ASCII value rather than the original input.

#include <Stepper.h>

Stepper small_stepper(steps_per_motor_revolution, 8, 10, 9, 11);

void setup() {
  // Put your setup code here, to run once:
  Serial.begin(9600);
  Serial.println("Ready");
}


void loop() {

  // Put your main code here, to run repeatedly:
  int Steps2Take = Serial.read();
  Serial.println(Steps2Take); // Printing
  if (Steps2Take == -1)
    Steps2Take = 0;
  else {
    small_stepper.setSpeed(1000); // Setting speed
    if (Steps2Take > 0)
      small_stepper.step(Steps2Take * 32);
    else
      small_stepper.step(-Steps2Take * 32);
    delay(2);
  }
}
Peter Mortensen
  • 30,738
  • 21
  • 105
  • 131
A_S
  • 3
  • 1
  • 1
  • 2

3 Answers3

1

Just use the .toInt() function.

You should read the string from your serial and after that convert it to integer.

Serial.print(Serial.readString().toInt());
Ali
  • 31
  • 4
0

You could do this three ways! Notice, if the number is greater than 65535 then you have to use a long variable. With decimals use float variable.

  1. You can use the toInt(), or toFloat() which require a String type variable. Heads up as the toFloat() is very time consuming.

       // CODE:
       String _int = "00254";
       String _float = "002.54"; 
       int value1 = _int.toInt();
       float value2 = _float.toFloat();
       Serial.println(value1);
       Serial.println(value2);
    
       // OUTPUT:
       254
       2.54
    
  2. You could use the atoi. The function accepts a character array and then converts it to an integer.

       // CODE:
       // For some reason you have to have +1 your final size; if you don't you will get zeros.
       char output[5] = {'1', '.', '2', '3'}; 
       int value1 = atoi(output);
       float value2 = atof(output);
       Serial.print(value1);
       Serial.print(value2);
    
       // OUTPUT:
       1
       1.23
    
  3. If you had a Character Array and and wanted to convert it to a string because you didn't know the length...like a message buffer or something, I dunno. You could use this below to change it to a string and then implement the toInt() or toFloat().

      // CODE:
      char _int[8];
      String data = "";
      for(int i = 0; i < 8; i++){
        data += (char)_int[i];
      }
    
      char buf[data.length()+1];
      data.toCharArray(buf, data.length()+1);
    
Kris Kizlyk
  • 151
  • 8
-1

If it is just a "type-conversion" problem, you can use something like this:

int a_as_int = (int)'a';

or

#include <stdlib.h>

int num = atoi("23"); //atoi = ascii to integer

as it was point out here.

Does it solve the problem?

Community
  • 1
  • 1
Leos313
  • 5,152
  • 6
  • 40
  • 69