0
votes

i am sending a string from Arduino. the string looks like this

2,0/3,0/4,0/5,0/6,0/7,0/8,1/9,1/10,1/11,1/12,1/13,1/ 

where the first number is a Arduino pin, then separated by a comer and then pin status 1 = high 0 = low

so here it's pin 2 = low, pin 3 = low .... pin 13 = high

when this string gets to processing i need to split the string up and assign the values to variables corresponding to the pins

something like

int p2 = 0; int p3 = 0; .. .. .. int pin8 = 1;

What would be a nice efficient way of achieving this?

with the input i got here here is what i have done,

rawInput = "2,0/3,0/4,0/5,0/6,0/7,0/8,1/9,1/10,1/11,1/12,1/13,1";
pinNumber = split(rawInput, '/');
for (int i =0; i < pinNumber.length; i++) {
  pinValue = split(pinNumber[i], ",");
  hm.put(Integer.parseInt(pinValue[0]), Integer.parseInt(pinValue[1]));
}

is there any obvious flaw here? seems to be working

1
Sounds like a job for a HashMap to me, unique keys with a value. Then you don't even have to maintain multiple variables. You could then have an enum if you wanted to get the actual text of high/low or to give your code readability, or you could just evaluate on the value if that isn't important - Michael

1 Answers

0
votes

Addition to storing as an HashMap. You can split the string by ",/" into array of string. Then with your pattern, even indices are your pin number and odd indices are your pin value. One loop can quickly achieve this.

String str = "1,0/2,1"
String[] strArr = str.split("/,");
Map<String, Integer> storeMap = new HashMap(); 
for (int i = 0, i < strArr.length; i++) {
    if (i % 2 == 0) {
        storeMap.put(String.valueOf(i), Integer.parseInt(strArr[i + 1]));
    }
}