I am trying to check if a string matches the condition of having between 1-4 digits followed by a comma and 1-4 digits, for example: 0,0 = true, 1234,6 = true, 0,0, = false.
if (myString.matches("\\d{1,4},\\d{1,4}")) { trimmedString = trim(myString); } else { trimmedString = "0"; println("Bad data detected: "+myString); }
this code always seems to output Bad data detected: myString. even when the values should be valid, like 0,0. Thanks for any help.
I keep getting a NumberFormatException, I think due to garbage data from the arduino every once in a while, but it also seems to cause a NullPointerException, for which I have no explanation. The code runs successfully for a while, until it gets some bad data. Sometimes even seemingly good data will cause it to crash. I can't seem to figure out how to catch this thing properly to keep it from crashing. Please help?
// Processing code for this example
// Graphing sketch
// This program takes ASCII-encoded strings // from the serial port at 9600 baud and graphs them. It expects values in the // range 0 to 1023, followed by a newline, or newline and carriage return
// Created 20 Apr 2005 // Updated 18 Jan 2008 // by Tom Igoe // This example code is in the public domain.
import processing.serial.*;
Serial myPort; // The serial port int xPos = 1; // horizontal position of the graph
void setup () { // set the window size: size(1900, 1020);
// List all the available serial ports println(Serial.list()); // I know that the first port in the serial list on my mac // is always my Arduino, so I open Serial.list()[0]. // Open whatever port is the one you're using. myPort = new Serial(this, Serial.list()[0], 9600); // don't generate a serialEvent() unless you get a newline character: myPort.bufferUntil('\n'); // set inital background: background(0); } float inByte = 0; float[] inByteA = new float[2]; int[] inInt = new int[2]; String[] inString = new String[2]; int x = 0; int y = 0;
void draw () { // everything happens in the serialEvent() }
for (int i = 0; i < inString.length; i++) { if (inString[i] != null) {
// convert to an int and map to the screen height: try { inByte = float(inString[i]); } catch (NumberFormatException excp) { inByte = 0; println("fucking: "+excp); } inByteA[i] = map(inByte, 0, 1023, 0, height); String temp = inString[i]; println(temp); try { inInt[i] = Integer.parseInt(temp); } catch (Exception e) { println("goddamn: "+e); inInt[i]=0; println("i: "+i); } finally {}
if (inInt[i]>=1) { print(i); print(":"); println(inInt[i]); } } } // at the edge of the screen, go back to the beginning: if (xPos >= width) { xPos = 0; background(0); } else if (inInt[0]!=0 || inInt[1]!=0) { // draw the line: stroke(127, 34, 255); line(xPos, height/2, xPos, height/2 - inByteA[0]); stroke(216, 24, 24); line(xPos, height/2, xPos, height/2 + inByteA[1]);