Problem with converting variable types & serial communication


hi everyone,

it's been while since last visited arduino forums, , got hang of how work arduino. great fun!
right now, working on project want computer send rgb-values arduino, want cast integers. use processing communicating on serial connection arduino.

setting serial connection not of problem, far good. tried "make sense" of output processing (i send string "255,112,145"), glue chars come in together, checking "," sort of delimiter.
the first problem ran into, somehow string put (serialbuffer) contains new lines besides chars glue together. can't casted integers:
code: [select]
instead of: 225
code: [select]
it becomes: 2
2
5


so tried else. casted serialbuffer int (with toint() function). worked fine first 2 rgb-values, third seemed mess little.
code: [select]
input processing: 255,212,111
code: [select]
output: r:255 g:212 b:-19817

i don't grip on problem here. guys me making sense out of happens here?

thanks in advance!
jeroen

----

i'll post both processing code , arduino code below.
arduino:
code: [select]
char inchar = '\0';
int incolor[3] = {0,0,0};
string serialbuffer = "";
int currentcolor = 0;
void setup(){
  serial.begin(9600);
}
void loop(){
  while(serial.available() > 0){
    inchar = serial.read();
    if(currentcolor < 3){
      if(inchar==','){
        incolor[currentcolor] = serialbuffer.toint();
        currentcolor++;
        serialbuffer = "";
      }
      else {
        //serial.println(string(inchar).trim());
        serialbuffer += (char)inchar;
        delay(5);
      }
    }
    else {     
      serial.println("r:"+string(incolor[0])+" g:"+string(incolor[1])+" b:"+string(incolor[2])+" cc:"+currentcolor);
      incolor[0] = 0;
      incolor[1] = 0;
      incolor[2] = 0;
      currentcolor = 0;
    }
  }
}


processing:
code: [select]
import processing.serial.*;
serial port;
string serial;

void setup() {
  port = new serial(this, "com9", 9600);
  port.clear();
  serial = port.readstringuntil(10);
  serial = null;
}

void draw(){
  port.write("255,212,111");
  while (port.available() > 0) { //as long there data coming serial port, read , store
    serial = port.readstringuntil(10);
  }
  if (serial != null) {
    println("incoming:");
    println(serial);
  }
  delay(100);
}

the problem third number store number when followed comma:
code: [select]

      if(inchar==','){
        incolor[currentcolor] = serialbuffer.toint();
        currentcolor++;
        serialbuffer = "";
      }


Arduino Forum > Using Arduino > Programming Questions > Problem with converting variable types & serial communication


arduino

Comments

Popular posts from this blog

opencv3, tbb and rasp pi 2 - Raspberry Pi Forums

small ethernet problem - Raspberry Pi Forums

Multithumb configuration params not working? - Joomla! Forum - community, help and support