Personally I prefer using Serial.print() instead of Serial.write(). Then you can do just:
Serial.print(t);
Which will send the value as text. Which makes it easier to read/test/debug. Drawback is that at the receiver, you must translate it back to an integer. Also, if more is being sent/printed through the serial connection, how to determine what-is-what? I prefer to send things in human readable form. So if I would have to send a variable t, I would send it like: "t: 133", using:
Serial.print("t: "); Serial.println(t);
Pay attention to the last print, it uses println
, to end the line with a newline.
An example from assignment 6, send the score as text "Score: 12". Would need this conversion at the receiver side:
// global variables:
String line;
int score=0;
void loop() {
// receive stuff
while (Serial.available() > 0) { // Code that reads lines from serial connection
line = Serial.readString(); // read the incoming data
}
if (line.length()>1) {
if (line.startsWith("score")) { // did we receive the "score XXX"?
// code to read score
String word2 = getValue(line, ' ', 1); // get second part of line
score = word2.toInt(); // convert the String to an integer
if (score>0) { // print the received value:
display.clearLine(0);
display.setCursor(0,0);
display.print("score=");
display.print(score);
}
}
line=""; // make line empty to be able to receive a next line
}
}
// https://stackoverflow.com/questions/9072320/split-string-into-string-array
String getValue(String data, char separator, int index) {
int found = 0;
int strIndex[] = {0, -1};
int maxIndex = data.length()-1;
for(int i=0; i<=maxIndex && found<=index; i++){
if(data.charAt(i)==separator || i==maxIndex){
found++;
strIndex[0] = strIndex[1]+1;
strIndex[1] = (i == maxIndex) ? i+1 : i;
}
}
return found>index ? data.substring(strIndex[0], strIndex[1]) : "";
}
Some more info:
https://arduino.stackexchange.com/questions/10088/what-is-the-difference-between-serial-write-and-serial-print-and-when-are-they
https://forum.arduino.cc/index.php?topic=323119.0