3

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);
 }
}
BrettFolkins
4,4411 gold badge15 silver badges26 bronze badges
asked May 4, 2015 at 2:33

1 Answer 1

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.

answered May 4, 2015 at 3:16

Your Answer

Draft saved
Draft discarded

Sign up or log in

Sign up using Google
Sign up using Email and Password

Post as a guest

Required, but never shown

Post as a guest

Required, but never shown

By clicking "Post Your Answer", you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.