problems converting string to int

edited April 2014 in Arduino

Hi

I am a pretty novice Processing user so sorry if this is an obvious problem.

I am trying to interface my arduino with processing. I have been using the 'graph' sketch from the communication examples that comes with Arduino. I have had to change a few things, like changing 'readStringUntil' to 'readString' because of the current serial library. Anyway it's kind of working now apart from the problem that when I try and convert the string that has just been read in, it only works from values of 10 to 99. i.e. any 2 digit number. For some reason when it is below or above that, when I try and convert, it just returns 0.

I've put the code below if anyone has any ideas. I have tried using Integer.parseInt() and just parseInt(), both to no avail. The println(inByte); seems to only be able to handle 2 digit numbers......

 import processing.serial.*;

 Serial myPort;
 String inString;
 int inByte;

 void setup () {

 myPort = new Serial(this, Serial.list()[0], 9600);
 myPort.bufferUntil('\n');

 }

 void draw () {

 }

 void serialEvent (Serial myPort) {

 inString = myPort.readString();

 if (inString != null) {

 inString = trim(inString);
 inByte = int(inString);
 println(inString);
 println(inByte);

 }

 }

Many thanks

Tagged:

Answers

  • Answer ✓

    Try this:

    for (byte b : inString.getBytes())
    {
      print(hex(b));
    }
    println();
    

    to display the exact content of your string. Perhaps the one or three digits versions have some strange characters inside.

  • Hi, thanks. That helped.

    You were right, the 3 and 1 digit numbers were actually groups of 4 or 5 values with carriage returns between them I think.

    Anyway it was solved easily by changing the delay in the arduino sketch from the 2ms originally included, to 20ms. The data comes through fine now. I should have thought as I have had problems before with not putting enough delay time for proper serial comms with the arduino. Lesson learnt!(perhaps)

    Many thanks

Sign In or Register to comment.