how to send 100 digit in serial communication from processing to arduino

痴心易碎 提交于 2019-12-24 19:29:20

问题


i am converting pixel array to String and send this String to arduino. but i Think this String is not converted properly because Serial.write send (8 bit or 8 character) i don’t know. and also want to send 100 character of string into Serial . please send your suggestion and getting help me out of this problem. for any mistake Sorry in advance.

  for(int x =0 ; x < img.height; x++)
   {
     for(int y=0; y <img.width; y++)
      {
        int i = x+y*width;
        if(img.pixels[i] == color(0,0,0))
       {
          i=1;
       }
       else
       {
        i=0;
       }

      String s = str(i);
      print(s);
      Serial.write(s);
      delay(2);
 }
}           

and also tell me how to stop string after 100 character by not using ("\n" or "\r" )


回答1:


It seems you are looking for the code below:

for (int x = 0; x < img.height; x++) { // iterate over height
  for (int y = 0; y < img.width; y++) { // iterate over width
    int i = x + y * width;
    if (img.pixels[i] == color(0, 0, 0)) { // determine if zero
      Serial.write('1'); // send non zero char
    } else {
      Serial.write('0'); // send zero char
    }
  }
  Serial.write("\n\r");
}

If you want to cluster your output in units the size of img.width you could do this:

for (int x = 0; x < img.height; x++) { // iterate over height
  String s;
  for (int y = 0; y < img.width; y++) { // iterate over width
    int i = x + y * width;
    if (img.pixels[i] == color(0, 0, 0)) { // determine if zero
      s += '1'; // append a non zero char to string s
    } else {
      s += '0'; // append a zero char to string s
    }
  }
  Serial.println(s);
}

Please remember:

Serial.write outputs raw binary value(s).

Serial.print outputs character(s).

Serial.println outputs character(s) and appends a newline character to output.


I have serious doubts about this calculation int i = x+y*width; as your data is probably structured as:

vertical data:      0      1      2
horizontal data:    [row 0][row 1][row 2]

Instead of:

horizontal data:    0         1         2
vertical data:      [column 0][column 1][column 2]


来源:https://stackoverflow.com/questions/56765632/how-to-send-100-digit-in-serial-communication-from-processing-to-arduino

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!