Comparing Previous and Past Inputs to Serial Moniter

Hi, so I am not sure how to compare previous values on the arduino IDE to current values. I want to compare the last value from the serial monitor to the present value and I also want to Serial.write the character 5 if a new value is put into the serial monitor.

If you want to help me fix the whole code, that would be greatly appreciated :slight_smile:

#include <Servo.h>

Servo myservo;
int pos = 0;
String val;
String oldval;

void setup() {
  // put your setup code here, to run once:
pinMode(5, OUTPUT);
pinMode(6, OUTPUT);
pinMode(9, OUTPUT);

myservo.attach(5);
Serial.begin(9600);
}

void loop() {
  // put your main code here, to run repeatedly:
while(Serial.available() > 0);
{
  
oldval = val;
  val = Serial.read();
delay (10);

  Serial.print(val);
if(Serial.read(update())
{
  Serial.write('5')
}

  if(val == ('1'));
  {
    digitalWrite(6, HIGH);
    digitalWrite(9, LOW);
  }
  if(val == ('2'));
  {
  digitalWrite(9, HIGH);
  digitalWrite(6, LOW);
  }
if(val == ('3'));
{
  digitalWrite(6, HIGH);
  digitalWrite(9, LOW);
  pos = 45;
  myservo.write(pos);
}
if(val == ('4'));
{
  digitalWrite(6, HIGH);
  digitalWrite(9, LOW);
  pos = -45;
  myservo.write(pos);
}
if(val == ('5'));
{
 
}
}
}
while (Serial.available() > 0);

While most lines of C code require a semicolon at the end, this is not one of them.

Use the control-T auto format. It looks wrong in this case, which indicates that the code is wrong.

Remember you can get other characters in the Serial stream. Carriage return and linefeed, for example. Check that you don't have that kind of input before overwriting your previously-good value.

Can I make Serial.read only update if certain characters are displayed?

Philcoder:
Can I make Serial.read only update if certain characters are displayed?

If there is data available then Serial.read() will read it. You can, of course, choose to ignore it.