I am using Arduino Uno with 4 scales connected with an RS232 cable. I want to read their data as fast as I can, hopefully without a blocking while loop. I am getting good reads for about ~20s each time, then one of the serial prints garbage, sometimes goes ok again etc. This is my code:
#include <SoftwareSerial.h>
#define SCALE_NUM 4
int rx[4] = {8, 9, 10, 11};
int tx[4] = {6, 7, 4, 2};
SoftwareSerial mySerial1 = SoftwareSerial(rx[0], tx[0]);
SoftwareSerial mySerial2 = SoftwareSerial(rx[1], tx[1]);
SoftwareSerial mySerial3 = SoftwareSerial(rx[2], tx[2]);
SoftwareSerial mySerial4 = SoftwareSerial(rx[3], tx[3]);
SoftwareSerial mySerial[4] = {mySerial1, mySerial2, mySerial3, mySerial4};
int baudRate = 9600;
float weights[4] = { 0 , 0 , 0 , 0 };
void setup() {
Serial.begin(baudRate);
for (int i = 0; i < SCALE_NUM; i++){mySerial[i].begin(baudRate);}
delay(500);
}
void loop() {
readString();
prints();
}
void readString() {
static String readString = "";
static int currentPort;
refreshSerialPorts(currentPort);
if (mySerial[currentPort].available()) {
char c = mySerial[currentPort].read();
readString = readString + c;
if (c == 'g') {
//Serial.println(String(currentPort) + " " + String(readString));
weights[currentPort] = readString.substring(7,14).toFloat();
weights[currentPort] = weights[currentPort] * 1000.0;
readString = "";
currentPort++;
if (currentPort == SCALE_NUM) {
currentPort = 0;
}
}
}
}
void refreshSerialPorts(int portNumber) {
mySerial[portNumber].listen();
}
void prints() {
static unsigned long lastPrintTime = 0;
#define PRINT_TIME 500
if ( millis() - lastPrintTime > PRINT_TIME ) {
for ( int i = 0 ; i < SCALE_NUM ; i++ ) {
Serial.print(String(weights[i]) + " ");
}
Serial.println();
Serial.flush();
lastPrintTime = millis();
}
}
Picture of the scale:
