简体   繁体   中英

converting string sent via Arduino Serial to Processing

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

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]));
    }
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM