Solved: Sending string to Arduino

I figured it out by formatting z as z = ("<"+x+","+y+">");

Original post:

I wish to control individually assignable LEDs (Adafruit’s Neopixels) on an Arduino Uno, so I need to send it two integers; one for the pixel number and one for the brightness. Sending as a string seems to be a good solution, but I am not sure how to do this right.
I understand from the Arduino forum that I need to include beginning (<) and end (>) markers in the string since the numbers can otherwise get scrambled.
Sending just single integers using Arduino Write example under the SerialPort help file works fine, but I get stuck when needing to send two at the same time. See my code below. I have included the Arduino code for the single integer example at the bottom.
My question is:

  1. How should I turn the array of x and y variables into a string with a pre- and post fix of < and >, so that I get this: <x,y>.

Since the Arduino software cannot be open while sc is sending on the serial port, I cannot check what the data looks like when it arrives on the board (otherwise I could use Arduino’s serial monitor to troubleshoot).

(

p = SerialPort(
“/dev/tty.usbmodem14101”,
baudrate: 9600,
crtscts: true);
)

(
r= Routine({
inf.do{|i, x, y, z|
x = i.fold(0,7); // led number
y = i.fold(0, 100).linexp(0, 100, 1, 255).asInteger; // led brightness
z = [x,y];
p.putAll(z); // ideally the output would be “<x, y>”
0.1.wait;
};
}).play;
)

Arduino Code:

#include <Adafruit_NeoPixel.h>

#ifdef AVR
#include <avr/power.h>
#endif

#define PIN 9

#define NUMPIXELS 8

Adafruit_NeoPixel pixels = Adafruit_NeoPixel(NUMPIXELS, PIN, NEO_GRBW + NEO_KHZ800);

int pixnum = 2;
void setup() {
Serial.begin(9600); // initialize serial communication:
pixels.begin(); // This initializes the NeoPixel library.
}

void loop() {
byte brightness;

// For a set of NeoPixels the first NeoPixel is 0, second is 1, all the way up to the count of pixels minus one.
if (Serial.available()) {
brightness = Serial.read();
pixels.setPixelColor(pixnum, pixels.Color(0,0,0, brightness));
pixels.show(); // This sends the updated pixel color to the hardware.

}

}

Thank you

Hi Adam,

I don’t know much about Arduinos, but this bit

inf.do{|i, x, y, z|

looks wrong.

The way you are using them, x, y and z are variables, not arguments, so that should be

inf.do{|i|

var x, y, z;

About the format, you could try

z = “<%, %>”. format(x, y)

cheers,

eddi

Thank you Eddi, you’re right!