2

I want to convert a string into a int value. in my real code, I receive a string "Slider 255" the number after slider changes from 0 to 255, so I want a int value to be equal to that number. This is a small example of the code:

#include <Servo.h>
Servo myServo;


int val = 0;
String s = "";
void setup() {

  Serial.begin(9600);
  myServo.attach(9);
}

void loop() {
  while(BT.available() >0){
  s =  Serial.read(); // which wiil be a number between 0 and 255
  // So I want val to be = to ehatever the string is. So far I have try this but it doesn´t work.
  // first attempt # 1
  val = s:
  myServo.write(val); 

  // Second attempt # 2 
  Serial.println(s)
  val = Serial.read();
   myServo.write(val);
  }
}
4

The easiest way is to use the parseInt method available to Serial like this

int val = Serial.parseInt()

But, you will have to be sure that the non-number part of the message ("Slider") has already been dealt with.

You could also put the data into an arduino String Object and use it's toInt method, or put it in a C style string and use the atoi method.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.