Serial communication problem

I have a problem with sending two values using serial communication. Sometimes everything works well, but when I turn the potentiometer, my program goes crazy. Any idea?

Transmiter:

#include <SoftwareSerial.h>

#define tx 4
#define rx 3
#define txrx 2

SoftwareSerial rs(3, 4);

void setup() 
{ 
  pinMode(tx, OUTPUT);
  pinMode(rx, INPUT);
  pinMode(txrx, OUTPUT);

  digitalWrite(txrx, HIGH); // high = t

  rs.begin(9600);
  Serial.begin(9600);
} 
 
void loop() 
{  
  rs.write(analogRead(A5)/4); 
  rs.write(analogRead(A4)/4);  
  Serial.print(analogRead(A5));   
  Serial.print(" ");   
  Serial.println(analogRead(A4));   
}

Receiver

#include <SoftwareSerial.h>

#define tx 4
#define rx 3
#define txrx 2

SoftwareSerial rs(3, 4);

int val1 = 0;
int val2 = 0;

void setup() 
{ 
  pinMode(tx, OUTPUT);
  pinMode(rx, INPUT);
  pinMode(txrx, OUTPUT);

  digitalWrite(txrx, LOW); // low = r

  rs.begin(9600);
  Serial.begin(9600);
} 
 
void loop() 
{ 

  if(rs.available() > 1)
    {
        val1 = rs.read();
        val2 = rs.read();
     }
     
    Serial.print(val1); 
    Serial.print("  "); 
    Serial.println(val2); 
}

:slight_smile:

:frowning:

Have a look at the examples in Serial Input Basics - simple reliable ways to receive data.

...R

I assume that you have the Arduino UNO.

The UNO has one hard UART which is connected with your PC/Serial Monitor.

You have created another soft UART. This soft UART is connected with another PC or another Arduino (UNO/NANO/MEGA/DUE)?

**BTW:**This soft UART is supposed to communicate with another controller that could be a UNO (direct connection) or a HC-05 Bluetooth (direct connection) or a PC via suitable converters (TTL <—> RS232 <----> USB).