Using two different readStringUntil "characters"

  • Now that it seems all’s been sorted out, how about some optimization?
  • The range [-10 to 10] is so small (5-bit) that it comfortably fits in a byte (8-bit).
  • So, rather than send those 2 small values as TSV, w/ lotsa extra separator characters, we can simply send 2 bytes only using Serial.write():
    https://www.Arduino.cc/reference/en/language/functions/communication/serial/write/
  • We just need to create a char array of length = 2: signed char xy[2];
#define BAUDS 115200
#define DELAY 10
#define BYTES 2

#define MIN 0
#define MAX 1023
#define MIN_RANGE -10
#define MAX_RANGE 10

signed char xy[BYTES];

void setup() {
  Serial.begin(BAUDS);
}

void loop() {
  xy[0] = map(analogRead(A1), MIN, MAX, MIN_RANGE, MAX_RANGE);
  xy[1] = map(analogRead(A0), MIN, MAX, MIN_RANGE, MAX_RANGE);

  Serial.write(xy);
  delay(DELAY);
}
/**
 * Serial readBytes() Line-Drawing (v1.0)
 * GoToLoop (2019/May/02)
 *
 * https://Discourse.Processing.org/t/
 * using-two-different-readstringuntil-characters/10769/23
 */

import processing.serial.Serial;

static final String PORT = "COM12";
static final float FPS = 100;
static final int BAUDS = 115200, INDEX = 1, BYTES = 2;
static final color STROKE = -1;

final byte[] xy = new byte[BYTES];
final PVector vec = new PVector(), mov = new PVector();

void setup() {
  size(1300, 700);
  noLoop();
  frameRate(FPS);

  stroke(STROKE);
  clear();

  vec.set(width>>1, height>>1);

  final String[] ports = Serial.list();
  printArray(ports);

  new Serial(this, PORT, BAUDS).buffer(BYTES);
  //new Serial(this, ports[INDEX], BAUDS).buffer(BYTES);
}

void draw() {
  line(vec.x, vec.y, vec.add(mov).x, vec.y);

  if (outtaBounds(vec)) {
    vec.set(width>>1, height>>1);
    System.err.println("Coords reset back to center of canvas!");
  }

  println(vec, mov);
}

boolean outtaBounds(final PVector v) {
  return v.x < 0 | v.x >= width | v.y < 0 | v.y >= height;
}

void serialEvent(final Serial s) {
  s.readBytes(xy);
  mov.set(xy[0], xy[1]);
  redraw = true;
}
1 Like