pls help to find what's wrong with my code

edited September 2014 in Questions about Code

I wrote a piece of code to read serial data (hex) and turns the data to dec for future usage, the code is as follows. But there's something wrong with the line: brightness=unhex(brightnessHEX). I have no idea about it and really hope somebosy here to help me with that.

import processing.serial.*;
Serial myPort;
int brightness = 0;
PFont font;
String brightnessHEX;

void setup() {
  size(800, 600);
  smooth();

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

void draw() {
  background(0);

  while (myPort.available () > 0) {
    brightnessHEX = myPort.readStringUntil('\n');
    if (brightnessHEX != null) {
      println(brightnessHEX);
      brightness=unhex(brightnessHEX);
      println(brightness);
    }
  }
  ......
}

scapture001

Tagged:

Answers

  • Answer ✓

    Add this line before you unhex(): brightnessHEX = brightnessHEX.replaceAll("\n", "");

  • thanks amnon very much, I changed the code as you suggested, but the problem is still existed there. scapture002

  • edited September 2014 Answer ✓

    Perhaps try out trim(): http://processing.org/reference/trim_.html
    brightnessHEX = trim( myPort.readStringUntil('\n') );

    or: http://docs.oracle.com/javase/8/docs/api/java/lang/String.html#trim--

    brightnessHEX = myPort.readStringUntil('\n').trim();

  • thanks GoToLoop a lot! the problem get resolved with via using trim() method. the workable code is as follows.

        import processing.serial.*;
        Serial myPort;
        int brightness = 0;
        PFont font;
        String brightnessHEX;
        String brightnessHEXClean;
    
        void setup() {
          size(800, 600);
          smooth();
    
          String portName = Serial.list()[0];
          myPort = new Serial(this, portName, 9600);
          myPort.bufferUntil('\n');
        }
    
        void draw() {
          background(0);
    
          while (myPort.available () > 0) {
            brightnessHEX = myPort.readStringUntil('\n');
    
            if (brightnessHEX != null) {
              brightnessHEXClean = trim(brightnessHEX);//Removes whitespace characters from the beginning and end of a String
              println(brightnessHEXClean);
              brightness = unhex(brightnessHEXClean);
              println(brightness);
            }
          }
        ...
        }
    
  • Answer ✓

    it's often helpful to do this, add things before and after your string, so you can see if it is really how it looks:

    println("[" + brightnessHEX + "]");
    
  • edited September 2014 Answer ✓

    Also method length() is useful to check whether the # of char values are indeed what's expected:
    http://processing.org/reference/String_length_.html

  • koogs and GoToLoop, your tips are really great!

Sign In or Register to comment.