Arduino serail communication error, 36 integers from touchdesigner

Hi. I'm working on arduino with touchdesigner using serial communication but I have a problem.

I'm sending 36 integers(0 or 1 or 2) calculated in touchdesigner and send the data to arduino.

send data format : "0,1,2,2,1,2,1,...\n" (36 intergers, comma in between, \n as end mark)

But as I check it on arduino the parsed data is not changing after the first income data is read.

when I checked the original received data, it changes almost every single sample but it doesn't match with the data on touchdesigner.

Is there anyone who can help me with it?

code below

It is not a code, it is a picture.
Please insert the code as text using code tags. If you don't know how to do that, read the forum guidelines.

const int numValues = 36;  // 받을 정수의 개수
int receivedValues[numValues];  // 수신된 정수 배열을 저장할 배열
int index = 0;  // 배열 인덱스 추적

void setup() {
  Serial.begin(9600);  // 시리얼 통신 속도 설정
}

void loop() {
  // 시리얼로 데이터가 들어왔는지 확인
  if (Serial.available() > 0) {
    // 한 바이트씩 데이터를 읽고 문자열로 수신
    String incomingData = Serial.readStringUntil('\n');  // '\n'으로 구분된 데이터를 받음

    // 수신된 문자열을 ','로 나눈 후 정수로 변환
    int i = 0;
    while (incomingData.length() > 0 && i < numValues) {
      int commaIndex = incomingData.indexOf(',');  // ','를 찾아서
      if (commaIndex == -1) {  // 마지막 값 처리
        receivedValues[i] = incomingData.toInt();
        break;
      } else {
        receivedValues[i] = incomingData.substring(0, commaIndex).toInt();  // ',' 이전 값을 추출
        incomingData = incomingData.substring(commaIndex + 1);  // 나머지 문자열을 처리
      }
      i++;
    }
    Serial.println(incomingData);
  }
}

this is arduino code.

width = int(op('new').par.resolutionw)
height = int(op('new').par.resolutionh)

def onValueChange(channel, sampleIndex, val, prev):
	# 정수 배열 데이터를 쉼표로 구분하여 전송
	value = []
	for w in range(width) :
		for h in range(height) :
			value.append(str(int(op('motor_status')[h, w])))
	data = ",".join(value)  # 0부터 35까지의 정수를 전송
	op('serial1').send(data + '\n')  # '\n'으로 끝맺음하여 한 줄로 전송
	return

and this is touchdesigner code

Do you see the correct received data if you print incomingData before parsing it? The parsing code is altering the contents of incomingData.

Not really.

I can see they change but they don't match with the original data.

and update speed is slower than data send speed.

So I thought it's just an delay but even I increase baudrate, it's still the same.

I'm using arduino mega btw.

avoid using String class on a Mega which has low memory - it can fragment memory causing problems

read the text into a char array and parse it using sscanf(), e.g.

// parse comma seperated int data, e.g. 0,1,2,2,1,2,1

const int numValues = 36;       // 받을 정수의 개수
int receivedValues[numValues];  // 수신된 정수 배열을 저장할 배열
int index = 0;                  // 배열 인덱스 추적

void setup() {
  Serial.begin(115200);  // 시리얼 통신 속도 설정
}

void loop() {
  char data[100] = { 0 };
  if (Serial.available() > 0) {
    // read text into char array
    Serial.readBytesUntil('\n', data, 100);   
    Serial.println(data);
    char *ptr = data;   // point at start of text
    for (index = 0; index < 36; index++) {
      // attempt to read an integer - break if it fails
      if (sscanf(ptr, "%d", &receivedValues[index]) != 1) break;
      // find next , add 1
      ptr = strchr(ptr, ',') + 1;
      //Serial.println(receivedValues[index]);
      //Serial.println(ptr);
    }
    // display parsed data
    Serial.print("receivedValues ");
    for (int i = 0; i < index; i++) {
      Serial.print(' ');
      Serial.print(receivedValues[i]);
    }
  }
}

when " 0,1,2,2,1,2,1\n" is entered serial monitor displays

0,1,2,2,1,2,1
receivedValues  0 1 2 2 1 2 1

an alternative is to use strtok() function to break the text into tokens, e.g.

// parse string extracting numeric values to comma seperated list

#include <stdio.h>
#include <string.h>
#include <stdlib.h>

void setup() {
  Serial.begin(115200);
  char str[] = "0,1,2,2,1,2,1";
  char* pch;
  Serial.print("\nextracting numeric values from comma seperated list: ");
  Serial.println(str);
  pch = strtok(str, ",");
  while (pch != NULL) {
    //Serial.print ("token found ");
    //Serial.println(pch);
    int data;
    if (sscanf(pch, "%d", &data) == 1) {
      Serial.print("int value ");
      Serial.println(data);
    }
    pch = strtok(NULL, ":,");
  }
}

void loop() {}

serial monitor displays

extracting numeric values from comma seperated list: 0,1,2,2,1,2,1
int value 0
int value 1
int value 2
int value 2
int value 1
int value 2
int value 1

Thanks a lot. the data is updating properly.

but another issue is the length is different every time and some numbers aren't separated.

I'm send 36 integers now and serial is printing like photo below.

Do you know why?

in the code of post 4 your baudrate was 9600baud
it is possible that the the transmitter is overrunning the receiver??
or the transmitter is overrunning the transmit buffer size?
try increasing the baudrate?
add a short delay in the Python code after transmitting a line of data?

avoid posting images of text output it wastes storage, is difficult to read and cannot be copied- copy the text and paste it using code tags </>

Oh, sorry for the image.

thanks for your advice.

I think I figured it out.

This topic was automatically closed 180 days after the last reply. New replies are no longer allowed.