If statement refreshing

Hello. Im new here not sure if im in the right place but hopefully.
Im doing motor rotator with encoder and code works basically like it should. Only thing is that the encoder direction does not change.
I have lcd shield with buttons. When I press right/left button, motor starts turning and encoder starts reading direction, but the direction does not change. If I press right/left again then I see new value.




// blinks once per second to indicate healthy main loop; (13) for built-in LED on UNO
#define HEARTBEAT_LED (13)

// analog input pin for FORWARD power reading
#define FWD_PIN (14)

// analog input pin for REFLECTED power reading
#define REF_PIN (15)


///////////////////////////////////////////////////////////////////////////////
//
//  REQUIRED: numeric limits for SWR hardware sensor
//

// define power limits (W); this is the power reading corresponding
//    to a full-scale A/D reading; to report the power as a percentage
//    of full scale, set this to 100.0.
#define FULL_SCALE_FORWARD (20.0)
#define FULL_SCALE_REFLECTED (20.0)

// MINIMUM A/D for SWR - this is the minimum A/D reading that will produce an
//   SWR != 1.0; this helps to prevent unnecessarily high SWR readings at low
//   power levels where there is insufficient A/D resolution to make accurate
//   SWR calculations.  This value is the RAW value used as a minimum FORWARD
//   power limit.  Below this RAW value, the SWR will be reported as 1.0.
#define MIN_POWER (5)

//
//  Serial Port - assign a specific hardware port to be the interface to
//	  the host; by default, the USB connection on most boards is 'Serial',
//	  which is also the hardware TTL serial port on the UNO board.  Make
//    sure to only select ONE option.
//

///////////////////////////////////////////////////////////////////////////////
//
//  OPTIONAL: select host serial port
//

// default for most boards' USB port
#define HostSerial Serial

// default for Leonardo UART, and second MEGA port
//#define HostSerial Serial1

// default for third MEGA port
//#define HostSerial Serial2

// default for fourth MEGA port
//#define HostSerial Serial3

// the 'baud rate' for the serial port
#define SerialRate (9600)

///////////////////////////////////////////////////////////////////////////////
//
//  OPTIONAL: enable persistence of settings
//
//  If this is set to 'true', the firmware will store the values of 'alpha'
//  into the EEPROM whenever the value is changed by user commands.
//

#define PERSIST_SETTINGS false

///////////////////////////////////////////////////////////////////////////////
//
//  Items below this level are OPTIONAL, and can enable display and lighting
//  features that were shown as examples in the website.  You can use these
//  examples as-is, or you can add your own display options
//

///////////////////////////////////////////////////////////////////////////////
//
//  OPTIONAL: Enable LED bar graph for SWR; LED pin definitions below
//
#define SWR_BAR_GRAPH false

#if SWR_BAR_GRAPH == true
#include "LightBar.h"
//
//  BAR - Configuration for the 'soft' bar graph (if enabled)
//    For each LED in the bar, you will need to specify a
//    threshold and digital output pin number (use A# macros
//    for analog pins), and an inversion flag, which should
//    probably always be false.
//

// specify the total number of bar elements
const int BarLength = 10;

// specify the configuration for the individual elements
const LightBarItem barItems[BarLength] = {
	// GREEN LEDs
	{ 1.01,  2, false },
	{ 1.25,  4, false },
	{ 1.50,  5, false },
	{ 1.75,  6, false },
	
	// YELLOW LEDs
	{ 2.00,  7, false },
	{ 2.33,  8, false },
	{ 2.66,  9, false },
	
	// RED LEDs
	{ 3.0,  10, false },
	{ 4.0,  11, false },
	{ 5.0,  12, false },
};

///////////////////////////////////////////////////////////////////////////////
//
//  OPTIONAL: Enable PWM follower, to control LED bar brightness using a
//            hardware potentiometer
//
#define SWR_BAR_FOLLOWER false

#if SWR_BAR_FOLLOWER == true
#include "FollowPWM.h"
//
//  PWM Brightness Control - if you have enabled SWR_BAR_FOLLOWER, this
//    will set up a 'PWM follower' that will adjust a PWM output according
//    to the value of an A/D input.  You can connect a potentiometer to an
//    A/D input, and the output PWM value will follow the A/D voltage at
//    runtime.  You can use this on the common side of the LEDs of your
//    bar graph to control their brightness.  CAUTION: Make sure that you
//    don't consume too much current on the PWM pin; if you need more net
//    current than the PWM line can supply, use a buffer transistor.
//
// PWM follower (output pin, input pin)
FollowPWM brightness(3, 5);

#endif // SWR_BAR_FOLLOWER
#endif // SWR_BAR_GRAPH

///////////////////////////////////////////////////////////////////////////////
//
//  OPTIONAL: Enable serial 7-segment display
//
#define SERIAL_SEGMENTED_DISPLAY false

// 7-segment SWR display support
#if SERIAL_SEGMENTED_DISPLAY == true
#include <SoftwareSerial.h>
#include "SegmentSWR.h"
//
//  Serial 7-Segment Display Support - this is an example of a digital
//    display for showing SWR.
//
SegmentSWR segment(7, 8);		// 7-segment object (rx pin, tx pin)
#endif // SERIAL_SEGMENTED_DISPLAY

///////////////////////////////////////////////////////////////////////////////
//
//  OPTIONAL: Enable display/OLED character display
//
//  Set this to 'true' to enable 16x2 display; otherwise leave 'false'; if set
//  to 'true', you will need to configure a display object, below.
//
#define ENABLE_DISPLAY true
#if ENABLE_DISPLAY == true
//
//  Configure display
//
//  Add a 'display' object below.  Examples are provided for standard display and
//  OLED displays in 16x2 format, using parallel interface.
//
//  You can use types other than 'LiquidCrystal' as long as the display object
//  is called 'display' and implements the same interface as the 'LiquidCrystal'
//  type.
//

//
//  display example
//
//  This example is for a 16x2 display display connected to D6 through D12, using
//  4-bit data transfer mode.
//
#include <LiquidCrystal.h>
//display pin to Arduino
const int pin_RS = 8;
const int pin_EN = 9;
const int pin_d4 = 4;
const int pin_d5 = 5;
const int pin_d6 = 6;
const int pin_d7 = 7;

const int pin_BL = 10;

LiquidCrystal display( pin_RS,  pin_EN,  pin_d4,  pin_d5,  pin_d6,  pin_d7);

int R = 0;
int U = 0;
int D = 0;
int L = 0;


//
//  OLED example
//
//  This example uses the AdaFruit enhanced Adafruit_CharacterOLED type
//  that is optimized for OLEDs. This type works with both AdaFruit and
//  SparkFun displays based on the RS0010 chip.
//
//  See this hookup guide for an example:
//     https://learn.sparkfun.com/tutorials/oled-display-hookup-guide/all
//
// This is the display type used in the web article.
//#include <Adafruit_CharacterOLED.h>
//Adafruit_CharacterOLED display(OLED_V2, 6, 7, 8, 9, 10, 11, 12);

//
//   Configure display size (default is 16x2)
// 
#define DISPLAY_ROWS (2)
#define DISPLAY_COLS (16)

//
//   Backlight - set this to 'true' if your display supports a
//               'setBacklight' option and you want to enable
//               the backlight; otherwise leave this set to 'false'
//
#define DISPLAY_BACKLIGHT false
#endif // ENABLE_DISPLAY

//
// ================== END OF CONFIGURATION SETTINGS ==================
//

// The version string
#define VERSION_DATE "20160920b"
#define VERSION_STRING "MeterSWR 1.0 (beta-" VERSION_DATE ")"

// local headers
#include "Elapsed.h"
#include "Heartbeat.h"
#include "Bounce2.h"
#include "SWR.h"
#include "utils.h"

//
//  Constants and Globals
//

// Maximum Arduino A/D reading; used only to scale the power readings.
const int ARDUINO_AD_MAX = 1023;

// maximum auto-poll interval (msec)
const int MaxAutoPoll = 1000;

// compute scaling constants for power readings
const float FORWARD_SCALE = (float)FULL_SCALE_FORWARD / (float)ARDUINO_AD_MAX;
const float REFLECT_SCALE = (float)FULL_SCALE_REFLECTED / (float)ARDUINO_AD_MAX;

#if SERIAL_SEGMENTED_DISPLAY == true
const uint16_t SegmentUpdateInterval = 500; // msec between segmented display updates
unsigned long lastSegment = 0;	// used to track the update interval
#endif

#if SWR_BAR_FOLLOWER == true
const uint16_t BrightnessUpdateInterval = 500; // set the msec between follower control A/D readings
unsigned long lastBrightness = 0; // used to track the update inteval
#endif

#if ENABLE_DISPLAY == true
const uint16_t DisplayUpdateInterval = 150; // set the msec between follower control A/D readings
unsigned long lastDisplay = 0;
#endif

#if SWR_BAR_GRAPH == true
// the light bar
LightBar Bar(barItems, BarLength);
#endif

// the SWR calculator
SWR swr(FWD_PIN, REF_PIN);

// a string to hold incoming data
String inputString;

// and another for command data
String cmdText = "";

// command parsing
String command = "";
String argument = "";

// whether the string is complete
boolean inputReady;

// maximum string lengths
const int InputLength = 16;
const int CommandLength = 16;
const int BufferLength = 24;

// I/O buffer
char ioBuffer[BufferLength];

#ifdef CMD_LED
// the last RX data from the host
unsigned long lastRxData;
bool lastCmdLED = false;
#endif

// echo USB RX data back to host
bool echo = false;

// currently parsing a command
bool cmd = false;

// autopolling
unsigned autoPoll = 0;
unsigned long lastPoll = 0;
bool autoRaw = false;

// global timer (amoritize clock read to one/loop)
unsigned long now;

#if PERSIST_SETTINGS == true
#include "persist.h"
#endif

//
//  UpdateDisplays() - update user displays, if any.
//
//  This is where you can update any bar graphs, digital displays, etc.
//  to show readings to the user.
//
static void UpdateDisplays() {
	//
	//  NOTE: the 'swr' object will always be updated immediately prior
	//        to calling UpdateDisplays(), so we can use it directly to
	//        get the values we need.
	//
	//  Current SWR is read using swr.Value()
	//  Current Power Forward is read using swr.Forward()
	//  Current Power Reflected is read using swr.Reflected()
	//

	// refresh the clock
	unsigned long now = millis();

	//
	//  EXAMPLE: update bar graph
	//
	#if SWR_BAR_GRAPH == true
	Bar.Update(swr.Value());
	#if SWR_BAR_FOLLOWER == true
	if (Elapsed(now, lastBrightness) >= BrightnessUpdateInterval) {
		brightness.Process();
		lastBrightness = now;
	}
	#endif
	#endif

	//
	//  EXAMPLE: update segmented display
	//
	#if SERIAL_SEGMENTED_DISPLAY == true
	// update 7-segment display
	if (Elapsed(now, lastSegment) >= SegmentUpdateInterval) {
		segment.Update(swr.Value());
		lastSegment = now;
	}
	#endif
	
	#if ENABLE_DISPLAY == true
	// Example: line 1 - display the forward power level
	display.setCursor(0, 0);
	uint8_t count = 0;
	// the label
	display.print(strcpy_P(ioBuffer, PSTR("F: ")));
	count += strlen(ioBuffer);
	// the number
	FormatFloat(ioBuffer, sizeof(ioBuffer), swr.Forward());
	display.print(ioBuffer);
	count += strlen(ioBuffer);
	// spaces
	for (uint8_t i = count; i < (DISPLAY_COLS - 4); ++i) {
		display.print(' ');
	}
	// SWR label
	display.print(strcpy_P(ioBuffer, PSTR("SWR ")));

	// Example: line 2 - display the reflected power and SWR
	display.setCursor(0, 1);
	// the label
	count = 0;
	snprintf(ioBuffer, sizeof(ioBuffer), strcpy_P(ioBuffer, PSTR("R: ")));
	display.print(ioBuffer);
	count += strlen(ioBuffer);
	// the number
	FormatFloat(ioBuffer, sizeof(ioBuffer), swr.Reflected());
	display.print(ioBuffer);
	count += strlen(ioBuffer);
	// spaces and SWR value
	FormatFloat(ioBuffer, sizeof(ioBuffer), swr.Value());
	for (uint8_t i = count; i < (DISPLAY_COLS - strlen(ioBuffer)); ++i) {
		display.print(' ');
	}
	display.print(ioBuffer);
	#endif

	//
	//  OPTIONAL: update other items
	//
	//  If you have added other display hardware, perform updates to
	//  it here.
	//
}

#include <Encoder.h>
Encoder windvane(21, 20);



//
//  setup()
//
void setup() {

  display.begin(16, 2);
  display.setCursor(0, 0);
  display.print("Select up / down");
  display.setCursor(0, 1);
  display.print("Rotate <-- -->");

     //Setup Channel A
  pinMode(12, OUTPUT); //Initiates Motor Channel A pin
  pinMode(9, OUTPUT); //Initiates Brake Channel A pin
	// start the serial port
	HostSerial.begin(SerialRate);
	
	// allocate string storage
	inputString.reserve(InputLength);
	cmdText.reserve(CommandLength);

	// prime the command pipeline with a version command
	inputString = strcpy_P(ioBuffer, PSTR("#VERSION;"));
	inputReady = true;

	// the A/D inputs
	pinMode(FWD_PIN, INPUT);
	pinMode(REF_PIN, INPUT);

	// configure the SWR algorithm
	swr.MinPower(MIN_POWER);
	swr.ScaleForward(FORWARD_SCALE);
	swr.ScaleReflected(REFLECT_SCALE);
	
	#if SWR_BAR_GRAPH == true
	// initialize the bar graph
	Bar.Initialize();
	#endif

	#if SERIAL_SEGMENTED_DISPLAY == true
	// initialize the 7-segment display
	segment.Initialize();
	#endif

	// initialize the display
	#if ENABLE_DISPLAY == true
	// initialize the display
	display.begin(DISPLAY_COLS, DISPLAY_ROWS);
	delay(1000);
	display.clear();
	display.home();
	display.clear();
	display.home();
	#if DISPLAY_BACKLIGHT == true
	// enable backlight
	display.setBacklight(HIGH);
	#endif
	// print banner including version number
//	strcpy_P(ioBuffer, PSTR("OH1CJO"));
//	const uint8_t x = (DISPLAY_COLS - strlen(ioBuffer)) / 2;
	display.setCursor(0, 0);
	display.print("SWR UP - LED DWN");
	display.setCursor(0, 1);
	display.print("Rotate <--- --->");
	// pause to let user actually *read* the banner
	delay(1500);
	#endif

	// set up the HB LED
	HeartbeatSetup();

	// load EEPROM settings
	#if PERSIST_SETTINGS == true
	load_eeprom();
	#endif

}
int old_pos = windvane.read();
const char  wd[][17]={{"POHJOiNEN   "},{"KOILLINEN   "},{"ITA         "},{"KAAKKO      "},{"ETELA       "},{"LOUNAS      "}, {"LANSI       "},{"LUODE       "}};

void loop() {
  
  int x;
  x = analogRead (0);

  if (x < 60) {
    R = 1; //Right;
    display.clear();
    display.setCursor(0, 0);
    display.print ("Rotating right");
  digitalWrite(12, HIGH); //Establishes forward direction of Channel A
  digitalWrite(9, LOW);   //Disengage the Brake for Channel A
  analogWrite(3, 100);   //Spins the motor on Channel A at full speed
    U = 0;
    D = 0;
    L = 0;

                    
                    int e = windvane.read();;
                    e = windvane.read();    
                    display.setCursor(0, 1);
                    display.print(wd[abs(e % 2400)/280]);
                    old_pos = windvane.read();
                     
                   }
                    
  else if (x < 200) {
    U = 1; //Up;
    display.clear();
    display.setCursor(0, 0);
    display.print ("SWR / Power?");
    display.setCursor(0, 1);
    display.print ("Press Select");
    R = 0;
    D = 0;
    L = 0;
  }
  else if (x < 400) {
    D = 1; //Down;
    display.clear();
    display.setCursor(0, 0);
    display.print ("LED CONTROL");
    display.setCursor(0, 1);
    display.print ("Press Select");
    R = 0;
    U = 0;
    L = 0;
  }
  else if (x < 600) {
    L = 1; //Left;
    display.clear();
    display.setCursor(0, 0);
    display.print ("Rotating left");
  digitalWrite(12, LOW); //Establishes backward direction of Channel A
  digitalWrite(9, LOW);   //Disengage the Brake for Channel A
  analogWrite(3, 100);   //Spins the motor on Channel A at half speed
    R = 0;
    U = 0;
    D = 0;

             int e = windvane.read();;
             e = windvane.read();
             display.setCursor(0, 1);
             display.print(wd[abs(e % 2400)/280]);
             old_pos = windvane.read();
          

  
}

  else if (x < 800) {
    if (R == 1) {
      display.clear();
      display.setCursor(0, 0);
      display.print ("Motor STOP");
       analogWrite(3, 0);   //Spins the motor on Channel A at full speed
      R = 0;
      // Your code here
    }
    if (U == 1) {

     
      display.clear();
      display.setCursor(0, 0);
      display.print ("SWR / POWER");
      display.setCursor(0, 1);
      display.print ("Selected, wait...");
      U = 0;
      delay(3000);
       for(int i = 0; i < 1000000; i++)
   {

                                    // service auto-polling
                                      now = millis();
                                    
                                      // HB update
                                      HeartbeatLoop();
                                    
                                      // spend all our spare time reading the transducer
                                      swr.Poll();
                                    
                                      // auto-polling
                                      if (autoPoll && (Elapsed(now, lastPoll) >= autoPoll)) {
                                        lastPoll = now;
                                        
                                        if (autoRaw) {
                                          HostSerial.write(strcpy_P(ioBuffer, PSTR("#RAW=")));
                                          snprintf(ioBuffer, sizeof(ioBuffer), "%d", swr.ForwardRaw());
                                          HostSerial.write(ioBuffer);
                                          HostSerial.write(",");
                                          snprintf(ioBuffer, sizeof(ioBuffer), "%d", swr.ReflectedRaw());
                                          HostSerial.write(ioBuffer);
                                          HostSerial.write(";");
                                          if (echo) {
                                            HostSerial.write("\r\n");
                                          }
                                        } else {
                                          HostSerial.write(strcpy_P(ioBuffer, PSTR("#SWR=")));
                                          FormatFloat(ioBuffer, sizeof(ioBuffer), swr.Value());
                                          HostSerial.write(ioBuffer);
                                          HostSerial.write(';');
                                          if (echo) {
                                            HostSerial.write(strcpy_P(ioBuffer, PSTR("\r\n")));
                                          }
                                        }
                                      }
                                      
                                      #if ENABLE_DISPLAY == true
                                      // update user displays, bar graphs, etc.
                                      if (Elapsed(now, lastDisplay) > DisplayUpdateInterval) {
                                        UpdateDisplays();
                                        lastDisplay = now;
                                      }
                                      #endif // ENABLE_DISPLAY == true
                                      
                                      // if user input ready
                                      if (inputReady) {
                                        // for each char received from the USB...
                                        for (int i = 0; i != inputString.length(); ++i) {
                                          char ch = inputString.charAt(i);
                                          
                                          // if we are in command mode...
                                          if (cmd) {
                                            if (ch == '#') {
                                              // if a '#' sent mid-command, start over
                                              cmdText = "";
                                            } else if (ch == ';') {
                                              // terminate and process the command string
                                              cmd = false;
                                              bool ok = false;
                                              if (echo) HostSerial.print(';');
                                    
                                              // parse the command and argument
                                              SplitCommand(cmdText, command, argument);
                                              if (command.equalsIgnoreCase(strcpy_P(ioBuffer, PSTR("SWR")))) {
                                                //
                                                //  SWR: read A/D and compute SWR
                                                //
                                                
                                                // add the SWR value to the response
                                                cmdText += "=";
                                                FormatFloat(ioBuffer, sizeof(ioBuffer), swr.Value());
                                                cmdText += ioBuffer;
                                                ok = true;
                                              } else if (command.equalsIgnoreCase(strcpy_P(ioBuffer, PSTR("RAW")))) {
                                                //
                                                //  RAW: read A/D and output raw values
                                                //            
                                                cmdText += "=";
                                                snprintf(ioBuffer, sizeof(ioBuffer), "%d", swr.ForwardRaw());
                                                cmdText += ioBuffer;
                                                cmdText += ",";
                                                snprintf(ioBuffer, sizeof(ioBuffer), "%d", swr.ReflectedRaw());
                                                cmdText += ioBuffer;
                                                ok = true;
                                              } else if (command.equalsIgnoreCase("PWR")) {
                                                //
                                                //  POWER: read A/D and output scaled values
                                                //            
                                                cmdText += "=";
                                                FormatFloat(ioBuffer, sizeof(ioBuffer), swr.Forward());
                                                cmdText += ioBuffer;
                                                cmdText += ",";
                                                FormatFloat(ioBuffer, sizeof(ioBuffer), swr.Reflected());
                                                cmdText += ioBuffer;
                                                ok = true;
                                              } else if (command.equalsIgnoreCase("ALL")) {
                                                //
                                                //  ALL: read A/D and output scaled values + SWR
                                                //            
                                                cmdText += "=";
                                                FormatFloat(ioBuffer, sizeof(ioBuffer), swr.Value());
                                                cmdText += ioBuffer;
                                                cmdText += ",";
                                                FormatFloat(ioBuffer, sizeof(ioBuffer), swr.Forward());
                                                cmdText += ioBuffer;
                                                cmdText += ",";
                                                FormatFloat(ioBuffer, sizeof(ioBuffer), swr.Reflected());
                                                cmdText += ioBuffer;
                                                ok = true;
                                              } else if (command.equalsIgnoreCase("ECHO")) {
                                                //
                                                //  QUERY/SET ECHO
                                                //
                                                if (argument.length() == 0) {
                                                  ok = true;
                                                  cmdText += "=";
                                                  cmdText += echo ? "1" : "0";
                                                } else {
                                                  int newEcho = argument.toInt();
                                                  echo = newEcho ? true : false;
                                                  ok = true;
                                                }
                                              } else if (command.equalsIgnoreCase(strcpy_P(ioBuffer, PSTR("AUTO")))) {
                                                //
                                                //  QUERY/SET AUTO-POLL
                                                //
                                                if (argument.length() == 0) {
                                                  ok = true;
                                                  cmdText += "=";
                                                  cmdText += autoPoll;
                                                } else {
                                                  int newAuto = argument.toInt();
                                                  if (newAuto >= 0 && newAuto < MaxAutoPoll) {
                                                    autoPoll = newAuto;
                                                    ok = true;
                                                  }
                                                }
                                              } else if (command.equalsIgnoreCase(strcpy_P(ioBuffer, PSTR("AUTORAW")))) {
                                                //
                                                //  QUERY/SET AUTO-POLL RAW MODE
                                                //
                                                if (argument.length() == 0) {
                                                  ok = true;
                                                  cmdText += "=";
                                                  cmdText += autoRaw ? "1" : "0";
                                                } else {
                                                  int newAuto = argument.toInt();
                                                  autoRaw = newAuto ? true : false;
                                                  ok = true;
                                                }
                                              } else if (command.equalsIgnoreCase(strcpy_P(ioBuffer, PSTR("VERSION")))) {
                                                //
                                                //  QUERY VERSION NUMBER
                                                //
                                                ok = true;
                                                cmdText += "=";
                                                cmdText += VERSION_STRING;
                                              } else if (command.equalsIgnoreCase(strcpy_P(ioBuffer, PSTR("ALPHAFWD")))) {
                                                //
                                                //  QUERY/SET ALPHA - FORWARD
                                                //
                                                if (argument.length() == 0) {
                                                  ok = true;
                                                  cmdText += "=";
                                                  cmdText += swr.AlphaForward();
                                                } else {
                                                  // read the value (float)
                                                  for (uint8_t i = 0; i != argument.length(); ++i) {
                                                    ioBuffer[i] = argument.charAt(i);
                                                  }
                                                  ioBuffer[argument.length()] = 0;
                                                  float alpha = atof(ioBuffer);
                                                  // set the value
                                                  swr.AlphaForward(alpha);
                                                  // read-back to see what actually got set
                                                  cmdText = command + "=" + swr.AlphaForward();
                                                  ok = true;
                                    #if PERSIST_SETTINGS == true
                                                  save_eeprom();
                                    #endif
                                                }
                                              } else if (command.equalsIgnoreCase(strcpy_P(ioBuffer, PSTR("ALPHAREF")))) {
                                                //
                                                //  QUERY/SET ALPHA - REFLECTED
                                                //
                                                if (argument.length() == 0) {
                                                  ok = true;
                                                  cmdText += "=";
                                                  cmdText += swr.AlphaReflected();
                                                } else {
                                                  // read the value (float)
                                                  for (uint8_t i = 0; i != argument.length(); ++i) {
                                                    ioBuffer[i] = argument.charAt(i);
                                                  }
                                                  ioBuffer[argument.length()] = 0;
                                                  float alpha = atof(ioBuffer);
                                                  // set the value
                                                  swr.AlphaReflected(alpha);
                                                  // read-back to see what actually got set
                                                  cmdText = command + "=" + swr.AlphaReflected();
                                                  ok = true;
                                    #if PERSIST_SETTINGS == true
                                                  save_eeprom();
                                    #endif
                                                }
                                    #if PERSIST_SETTINGS == true
                                              } else if (command.equalsIgnoreCase(strcpy_P(ioBuffer, PSTR("EREAD")))) {
                                                //
                                                //  READ: get startup settings from EEPROM
                                                //
                                                load_eeprom();
                                                ok = true;
                                              } else if (command.equalsIgnoreCase(strcpy_P(ioBuffer, PSTR("EWRITE")))) {
                                                //
                                                //  WRITE: commit settings to EEPROM
                                                //
                                                save_eeprom();
                                                ok = true;
                                              } else if (command.equalsIgnoreCase(strcpy_P(ioBuffer, PSTR("ECLEAR")))) {
                                                //
                                                //  FACTORY: reset EEPROM data
                                                //
                                                clear_eeprom();
                                                ok = true;
                                    #endif
                                              }
                                    
                                              //
                                              //  TODO: process other command contents
                                              //
                                    
                                              // respond with #OK or #ERR
                                              if (echo)
                                                HostSerial.print(strcpy_P(ioBuffer, PSTR("\r\n")));
                                              HostSerial.print(ok ? strcpy_P(ioBuffer, PSTR("#OK:")) : strcpy_P(ioBuffer, PSTR("#ERR:")));
                                              HostSerial.print(cmdText);
                                              HostSerial.print(';');
                                              if (echo)
                                                HostSerial.print(strcpy_P(ioBuffer, PSTR("\r\n")));
                                              cmdText = "";
                                            } else {
                                              if (cmdText.length() < CommandLength) {
                                                cmdText += ch;
                                              }
                                              if (echo) {
                                                HostSerial.print(ch);
                                              }
                                            }
                                            continue;
                                          }
                                          
                                          // start command mode??
                                          if ((!cmd) && (ch == '#')) {
                                            cmd = true;
                                            if (echo) HostSerial.print('#');
                                            continue;
                                          }
                                        }
                                        
                                        // clear the string:
                                        inputString = "";
                                        inputReady = false;
                                      }
                                    
                                      // service the serial port
                                      while (HostSerial.available()) {
                                        // get a new byte
                                        char inChar = (char)HostSerial.read();
                                    
                                        // add it to the inputString
                                        if (inputString.length() < InputLength)
                                          inputString += inChar;
                                        inputReady = true;
                                      }
                                      delay(1000);
    }}
    
    if (D == 1) {
      display.clear();
      display.setCursor(0, 0);
      display.print ("LED CONTROL");
      display.setCursor(0, 1);
      display.print ("NOT AVAILABLE");
      D = 0;
      // Your code here
    }
    if (L == 1) {
      display.clear();
      display.setCursor(0, 0);
      display.print ("Motor STOP");
       analogWrite(3, 0);   //Stops the motor
      L = 0;
      // Your code here
    }
  }
}

Here is the full code.
The part that reads direction is inside the if statment

 int e = windvane.read();;
             e = windvane.read();
             display.setCursor(0, 1);
             display.print(wd[abs(e % 2400)/280]);
             old_pos = windvane.read();

IF I edit the code like this

        for(int i = 0; i < 1000000; i++)
   {
    
    int e = windvane.read();;
    e = windvane.read();


           
            display.setCursor(0, 1);
            display.print(wd[abs(e % 2400)/280]);
            old_pos = windvane.read();
          

  }
  }

Then it starts refreshing the seccond line on lcd like it should.
Like this everything works like it should. only problem is now that it wont accept any more commands until I reset arduino.
If motor is turning right, direction changed everything is fine. I cannot stop the motor or I cannot make the motor to change direction.
If I remove the "for(int i = 0....." part, then buttons start working agian but direction does not change.

Hopefully my explantion was good enough.
Im pretty new to arduino coding. I know some stuff but not enough.
If someone know how to fix this issue then please edit my original code. with that I can compare two codes and I see what has been changed.

Thank you.

As advised in the topic: How to get the best out of this forum - Using Arduino / Project Guidance - Arduino Forum
Post links to the datasheets of the devices You refer to.
Make a test code just exercising the encoder.

rotary encoder lpd3806, arduino mega and random dc motor that is turning 7rpm.
lcd keypad shield and motor controller is l298 shield.

No help from that.
Please post a link to the encoder and schematics for the setup.

anything else?

Thanks. One step on the way.

Quoting the data:
Output:
AB rectangular two-phase quadrature pulse output circuit output NPN open collector output type, this output type can and with internal pull-up resistor connected directly to the microcontroller Vcc.

I don't find the encoder inputs definition. Pullups are needed for the inputs reading the encoder.

Can You post the test code just exercising the encoder?
I don't manage to identify the encoder specific parts.

I think I'd move this line up to the top of the loop() function:

e = windvane.read();

...because it is the encoder reading command and it ought to be read/updated as often as possible.
Oh, you're probably on a Arduino Mega, so the Encoder - Arduino Reference library would use interrupts to read pins 21 & 20 so it handles the updates in the background.

I dont have your hardware, so I can't really test or debug your code, and it's a mess to read. I'd paste it into an arduino window and use Tools/Auto-format to make the indentation match the syntax.

At a glance, I see that you aren't using old_pos anywhere, so assigning it seems useless; you declared a number of local int e = windvane.read();; variables that also don't seem necessary. The 1000000-long for-loop is blocking the other other parts of your program from operating. Maybe there's other parts of the code that are blocking the screen upating from happening.

I think I'd start by putting the display update code into a non-blocking function with a state machine that prints at 10Hz maximum:

void updateDispDaveX(void){
   static unsigned long nextReport = 0;
   if ((signed long)(millis() - nextReport) <=0 ) // too soon 
      return ;
   nextReport = millis() + 100; // update display every 100ms
   display.setCursor(0, 1);
   e = windvane.read();
   display.print(wd[abs(e % 2400)/280]);
}

And then put updateDispDaveX() in its place.

Your code is difficult to read to see what it is that might be blocking the display code, but the solution isn't to make the display code block the rest of the code.

Here is auto format code




// blinks once per second to indicate healthy main loop; (13) for built-in LED on UNO
#define HEARTBEAT_LED (13)

// analog input pin for FORWARD power reading
#define FWD_PIN (14)

// analog input pin for REFLECTED power reading
#define REF_PIN (15)


///////////////////////////////////////////////////////////////////////////////
//
//  REQUIRED: numeric limits for SWR hardware sensor
//

// define power limits (W); this is the power reading corresponding
//    to a full-scale A/D reading; to report the power as a percentage
//    of full scale, set this to 100.0.
#define FULL_SCALE_FORWARD (20.0)
#define FULL_SCALE_REFLECTED (20.0)

// MINIMUM A/D for SWR - this is the minimum A/D reading that will produce an
//   SWR != 1.0; this helps to prevent unnecessarily high SWR readings at low
//   power levels where there is insufficient A/D resolution to make accurate
//   SWR calculations.  This value is the RAW value used as a minimum FORWARD
//   power limit.  Below this RAW value, the SWR will be reported as 1.0.
#define MIN_POWER (5)

//
//  Serial Port - assign a specific hardware port to be the interface to
//	  the host; by default, the USB connection on most boards is 'Serial',
//	  which is also the hardware TTL serial port on the UNO board.  Make
//    sure to only select ONE option.
//

///////////////////////////////////////////////////////////////////////////////
//
//  OPTIONAL: select host serial port
//

// default for most boards' USB port
#define HostSerial Serial

// default for Leonardo UART, and second MEGA port
//#define HostSerial Serial1

// default for third MEGA port
//#define HostSerial Serial2

// default for fourth MEGA port
//#define HostSerial Serial3

// the 'baud rate' for the serial port
#define SerialRate (9600)

///////////////////////////////////////////////////////////////////////////////
//
//  OPTIONAL: enable persistence of settings
//
//  If this is set to 'true', the firmware will store the values of 'alpha'
//  into the EEPROM whenever the value is changed by user commands.
//

#define PERSIST_SETTINGS false

///////////////////////////////////////////////////////////////////////////////
//
//  Items below this level are OPTIONAL, and can enable display and lighting
//  features that were shown as examples in the website.  You can use these
//  examples as-is, or you can add your own display options
//

///////////////////////////////////////////////////////////////////////////////
//
//  OPTIONAL: Enable LED bar graph for SWR; LED pin definitions below
//
#define SWR_BAR_GRAPH false

#if SWR_BAR_GRAPH == true
#include "LightBar.h"
//
//  BAR - Configuration for the 'soft' bar graph (if enabled)
//    For each LED in the bar, you will need to specify a
//    threshold and digital output pin number (use A# macros
//    for analog pins), and an inversion flag, which should
//    probably always be false.
//

// specify the total number of bar elements
const int BarLength = 10;

// specify the configuration for the individual elements
const LightBarItem barItems[BarLength] = {
  // GREEN LEDs
  { 1.01,  2, false },
  { 1.25,  4, false },
  { 1.50,  5, false },
  { 1.75,  6, false },

  // YELLOW LEDs
  { 2.00,  7, false },
  { 2.33,  8, false },
  { 2.66,  9, false },

  // RED LEDs
  { 3.0,  10, false },
  { 4.0,  11, false },
  { 5.0,  12, false },
};

///////////////////////////////////////////////////////////////////////////////
//
//  OPTIONAL: Enable PWM follower, to control LED bar brightness using a
//            hardware potentiometer
//
#define SWR_BAR_FOLLOWER false

#if SWR_BAR_FOLLOWER == true
#include "FollowPWM.h"
//
//  PWM Brightness Control - if you have enabled SWR_BAR_FOLLOWER, this
//    will set up a 'PWM follower' that will adjust a PWM output according
//    to the value of an A/D input.  You can connect a potentiometer to an
//    A/D input, and the output PWM value will follow the A/D voltage at
//    runtime.  You can use this on the common side of the LEDs of your
//    bar graph to control their brightness.  CAUTION: Make sure that you
//    don't consume too much current on the PWM pin; if you need more net
//    current than the PWM line can supply, use a buffer transistor.
//
// PWM follower (output pin, input pin)
FollowPWM brightness(3, 5);

#endif // SWR_BAR_FOLLOWER
#endif // SWR_BAR_GRAPH

///////////////////////////////////////////////////////////////////////////////
//
//  OPTIONAL: Enable serial 7-segment display
//
#define SERIAL_SEGMENTED_DISPLAY false

// 7-segment SWR display support
#if SERIAL_SEGMENTED_DISPLAY == true
#include <SoftwareSerial.h>
#include "SegmentSWR.h"
//
//  Serial 7-Segment Display Support - this is an example of a digital
//    display for showing SWR.
//
SegmentSWR segment(7, 8);		// 7-segment object (rx pin, tx pin)
#endif // SERIAL_SEGMENTED_DISPLAY

///////////////////////////////////////////////////////////////////////////////
//
//  OPTIONAL: Enable display/OLED character display
//
//  Set this to 'true' to enable 16x2 display; otherwise leave 'false'; if set
//  to 'true', you will need to configure a display object, below.
//
#define ENABLE_DISPLAY true
#if ENABLE_DISPLAY == true
//
//  Configure display
//
//  Add a 'display' object below.  Examples are provided for standard display and
//  OLED displays in 16x2 format, using parallel interface.
//
//  You can use types other than 'LiquidCrystal' as long as the display object
//  is called 'display' and implements the same interface as the 'LiquidCrystal'
//  type.
//

//
//  display example
//
//  This example is for a 16x2 display display connected to D6 through D12, using
//  4-bit data transfer mode.
//
#include <LiquidCrystal.h>
//display pin to Arduino
const int pin_RS = 8;
const int pin_EN = 9;
const int pin_d4 = 4;
const int pin_d5 = 5;
const int pin_d6 = 6;
const int pin_d7 = 7;

const int pin_BL = 10;

LiquidCrystal display( pin_RS,  pin_EN,  pin_d4,  pin_d5,  pin_d6,  pin_d7);

int R = 0;
int U = 0;
int D = 0;
int L = 0;


//
//  OLED example
//
//  This example uses the AdaFruit enhanced Adafruit_CharacterOLED type
//  that is optimized for OLEDs. This type works with both AdaFruit and
//  SparkFun displays based on the RS0010 chip.
//
//  See this hookup guide for an example:
//     https://learn.sparkfun.com/tutorials/oled-display-hookup-guide/all
//
// This is the display type used in the web article.
//#include <Adafruit_CharacterOLED.h>
//Adafruit_CharacterOLED display(OLED_V2, 6, 7, 8, 9, 10, 11, 12);

//
//   Configure display size (default is 16x2)
//
#define DISPLAY_ROWS (2)
#define DISPLAY_COLS (16)

//
//   Backlight - set this to 'true' if your display supports a
//               'setBacklight' option and you want to enable
//               the backlight; otherwise leave this set to 'false'
//
#define DISPLAY_BACKLIGHT false
#endif // ENABLE_DISPLAY

//
// ================== END OF CONFIGURATION SETTINGS ==================
//

// The version string
#define VERSION_DATE "20160920b"
#define VERSION_STRING "MeterSWR 1.0 (beta-" VERSION_DATE ")"

// local headers
#include "Elapsed.h"
#include "Heartbeat.h"
#include "Bounce2.h"
#include "SWR.h"
#include "utils.h"

//
//  Constants and Globals
//

// Maximum Arduino A/D reading; used only to scale the power readings.
const int ARDUINO_AD_MAX = 1023;

// maximum auto-poll interval (msec)
const int MaxAutoPoll = 1000;

// compute scaling constants for power readings
const float FORWARD_SCALE = (float)FULL_SCALE_FORWARD / (float)ARDUINO_AD_MAX;
const float REFLECT_SCALE = (float)FULL_SCALE_REFLECTED / (float)ARDUINO_AD_MAX;

#if SERIAL_SEGMENTED_DISPLAY == true
const uint16_t SegmentUpdateInterval = 500; // msec between segmented display updates
unsigned long lastSegment = 0;	// used to track the update interval
#endif

#if SWR_BAR_FOLLOWER == true
const uint16_t BrightnessUpdateInterval = 500; // set the msec between follower control A/D readings
unsigned long lastBrightness = 0; // used to track the update inteval
#endif

#if ENABLE_DISPLAY == true
const uint16_t DisplayUpdateInterval = 150; // set the msec between follower control A/D readings
unsigned long lastDisplay = 0;
#endif

#if SWR_BAR_GRAPH == true
// the light bar
LightBar Bar(barItems, BarLength);
#endif

// the SWR calculator
SWR swr(FWD_PIN, REF_PIN);

// a string to hold incoming data
String inputString;

// and another for command data
String cmdText = "";

// command parsing
String command = "";
String argument = "";

// whether the string is complete
boolean inputReady;

// maximum string lengths
const int InputLength = 16;
const int CommandLength = 16;
const int BufferLength = 24;

// I/O buffer
char ioBuffer[BufferLength];

#ifdef CMD_LED
// the last RX data from the host
unsigned long lastRxData;
bool lastCmdLED = false;
#endif

// echo USB RX data back to host
bool echo = false;

// currently parsing a command
bool cmd = false;

// autopolling
unsigned autoPoll = 0;
unsigned long lastPoll = 0;
bool autoRaw = false;

// global timer (amoritize clock read to one/loop)
unsigned long now;

#if PERSIST_SETTINGS == true
#include "persist.h"
#endif

//
//  UpdateDisplays() - update user displays, if any.
//
//  This is where you can update any bar graphs, digital displays, etc.
//  to show readings to the user.
//
static void UpdateDisplays() {
  //
  //  NOTE: the 'swr' object will always be updated immediately prior
  //        to calling UpdateDisplays(), so we can use it directly to
  //        get the values we need.
  //
  //  Current SWR is read using swr.Value()
  //  Current Power Forward is read using swr.Forward()
  //  Current Power Reflected is read using swr.Reflected()
  //

  // refresh the clock
  unsigned long now = millis();

  //
  //  EXAMPLE: update bar graph
  //
#if SWR_BAR_GRAPH == true
  Bar.Update(swr.Value());
#if SWR_BAR_FOLLOWER == true
  if (Elapsed(now, lastBrightness) >= BrightnessUpdateInterval) {
    brightness.Process();
    lastBrightness = now;
  }
#endif
#endif

  //
  //  EXAMPLE: update segmented display
  //
#if SERIAL_SEGMENTED_DISPLAY == true
  // update 7-segment display
  if (Elapsed(now, lastSegment) >= SegmentUpdateInterval) {
    segment.Update(swr.Value());
    lastSegment = now;
  }
#endif

#if ENABLE_DISPLAY == true
  // Example: line 1 - display the forward power level
  display.setCursor(0, 0);
  uint8_t count = 0;
  // the label
  display.print(strcpy_P(ioBuffer, PSTR("F: ")));
  count += strlen(ioBuffer);
  // the number
  FormatFloat(ioBuffer, sizeof(ioBuffer), swr.Forward());
  display.print(ioBuffer);
  count += strlen(ioBuffer);
  // spaces
  for (uint8_t i = count; i < (DISPLAY_COLS - 4); ++i) {
    display.print(' ');
  }
  // SWR label
  display.print(strcpy_P(ioBuffer, PSTR("SWR ")));

  // Example: line 2 - display the reflected power and SWR
  display.setCursor(0, 1);
  // the label
  count = 0;
  snprintf(ioBuffer, sizeof(ioBuffer), strcpy_P(ioBuffer, PSTR("R: ")));
  display.print(ioBuffer);
  count += strlen(ioBuffer);
  // the number
  FormatFloat(ioBuffer, sizeof(ioBuffer), swr.Reflected());
  display.print(ioBuffer);
  count += strlen(ioBuffer);
  // spaces and SWR value
  FormatFloat(ioBuffer, sizeof(ioBuffer), swr.Value());
  for (uint8_t i = count; i < (DISPLAY_COLS - strlen(ioBuffer)); ++i) {
    display.print(' ');
  }
  display.print(ioBuffer);
#endif

  //
  //  OPTIONAL: update other items
  //
  //  If you have added other display hardware, perform updates to
  //  it here.
  //
}

#include <Encoder.h>
Encoder windvane(21, 20);



//
//  setup()
//
void setup() {

  display.begin(16, 2);
  display.setCursor(0, 0);
  display.print("Select up / down");
  display.setCursor(0, 1);
  display.print("Rotate <-- -->");

  //Setup Channel A
  pinMode(12, OUTPUT); //Initiates Motor Channel A pin
  pinMode(9, OUTPUT); //Initiates Brake Channel A pin
  // start the serial port
  HostSerial.begin(SerialRate);

  // allocate string storage
  inputString.reserve(InputLength);
  cmdText.reserve(CommandLength);

  // prime the command pipeline with a version command
  inputString = strcpy_P(ioBuffer, PSTR("#VERSION;"));
  inputReady = true;

  // the A/D inputs
  pinMode(FWD_PIN, INPUT);
  pinMode(REF_PIN, INPUT);

  // configure the SWR algorithm
  swr.MinPower(MIN_POWER);
  swr.ScaleForward(FORWARD_SCALE);
  swr.ScaleReflected(REFLECT_SCALE);

#if SWR_BAR_GRAPH == true
  // initialize the bar graph
  Bar.Initialize();
#endif

#if SERIAL_SEGMENTED_DISPLAY == true
  // initialize the 7-segment display
  segment.Initialize();
#endif

  // initialize the display
#if ENABLE_DISPLAY == true
  // initialize the display
  display.begin(DISPLAY_COLS, DISPLAY_ROWS);
  delay(1000);
  display.clear();
  display.home();
  display.clear();
  display.home();
#if DISPLAY_BACKLIGHT == true
  // enable backlight
  display.setBacklight(HIGH);
#endif
  // print banner including version number
  //	strcpy_P(ioBuffer, PSTR("OH1CJO"));
  //	const uint8_t x = (DISPLAY_COLS - strlen(ioBuffer)) / 2;
  display.setCursor(0, 0);
  display.print("SWR UP - LED DWN");
  display.setCursor(0, 1);
  display.print("Rotate <--- --->");
  // pause to let user actually *read* the banner
  delay(1500);
#endif

  // set up the HB LED
  HeartbeatSetup();

  // load EEPROM settings
#if PERSIST_SETTINGS == true
  load_eeprom();
#endif

}

const char  wd[][17] = {{"POHJOiNEN   "}, {"KOILLINEN   "}, {"ITA         "}, {"KAAKKO      "}, {"ETELA       "}, {"LOUNAS      "}, {"LANSI       "}, {"LUODE       "}};

void loop() {
  int e = windvane.read();
  e = windvane.read();
  int x;
  x = analogRead (0);

  if (x < 60) {
    R = 1; //Right;
    display.clear();
    display.setCursor(0, 0);
    display.print ("Rotating right");
    digitalWrite(12, HIGH); //Establishes forward direction of Channel A
    digitalWrite(9, LOW);   //Disengage the Brake for Channel A
    analogWrite(3, 100);   //Spins the motor on Channel A at full speed
    U = 0;
    D = 0;
    L = 0;


    display.setCursor(0, 1);
    display.print(wd[abs(e % 2400) / 280]);


  }

  else if (x < 200) {
    U = 1; //Up;
    display.clear();
    display.setCursor(0, 0);
    display.print ("SWR / Power?");
    display.setCursor(0, 1);
    display.print ("Press Select");
    R = 0;
    D = 0;
    L = 0;
  }
  else if (x < 400) {
    D = 1; //Down;
    display.clear();
    display.setCursor(0, 0);
    display.print ("LED CONTROL");
    display.setCursor(0, 1);
    display.print ("Press Select");
    R = 0;
    U = 0;
    L = 0;
  }
  else if (x < 600) {
    L = 1; //Left;
    display.clear();
    display.setCursor(0, 0);
    display.print ("Rotating left");
    digitalWrite(12, LOW); //Establishes backward direction of Channel A
    digitalWrite(9, LOW);   //Disengage the Brake for Channel A
    analogWrite(3, 100);   //Spins the motor on Channel A at half speed
    R = 0;
    U = 0;
    D = 0;


    display.setCursor(0, 1);
    display.print(wd[abs(e % 2400) / 280]);




  }

  else if (x < 800) {
    if (R == 1) {
      display.clear();
      display.setCursor(0, 0);
      display.print ("Motor STOP");
      analogWrite(3, 0);   //Spins the motor on Channel A at full speed
      R = 0;
      // Your code here
    }
    if (U == 1) {


      display.clear();
      display.setCursor(0, 0);
      display.print ("SWR / POWER");
      display.setCursor(0, 1);
      display.print ("Selected, wait...");
      U = 0;
      delay(3000);
      for (int i = 0; i < 1000000; i++)
      {

        // service auto-polling
        now = millis();

        // HB update
        HeartbeatLoop();

        // spend all our spare time reading the transducer
        swr.Poll();

        // auto-polling
        if (autoPoll && (Elapsed(now, lastPoll) >= autoPoll)) {
          lastPoll = now;

          if (autoRaw) {
            HostSerial.write(strcpy_P(ioBuffer, PSTR("#RAW=")));
            snprintf(ioBuffer, sizeof(ioBuffer), "%d", swr.ForwardRaw());
            HostSerial.write(ioBuffer);
            HostSerial.write(",");
            snprintf(ioBuffer, sizeof(ioBuffer), "%d", swr.ReflectedRaw());
            HostSerial.write(ioBuffer);
            HostSerial.write(";");
            if (echo) {
              HostSerial.write("\r\n");
            }
          } else {
            HostSerial.write(strcpy_P(ioBuffer, PSTR("#SWR=")));
            FormatFloat(ioBuffer, sizeof(ioBuffer), swr.Value());
            HostSerial.write(ioBuffer);
            HostSerial.write(';');
            if (echo) {
              HostSerial.write(strcpy_P(ioBuffer, PSTR("\r\n")));
            }
          }
        }

#if ENABLE_DISPLAY == true
        // update user displays, bar graphs, etc.
        if (Elapsed(now, lastDisplay) > DisplayUpdateInterval) {
          UpdateDisplays();
          lastDisplay = now;
        }
#endif // ENABLE_DISPLAY == true

        // if user input ready
        if (inputReady) {
          // for each char received from the USB...
          for (int i = 0; i != inputString.length(); ++i) {
            char ch = inputString.charAt(i);

            // if we are in command mode...
            if (cmd) {
              if (ch == '#') {
                // if a '#' sent mid-command, start over
                cmdText = "";
              } else if (ch == ';') {
                // terminate and process the command string
                cmd = false;
                bool ok = false;
                if (echo) HostSerial.print(';');

                // parse the command and argument
                SplitCommand(cmdText, command, argument);
                if (command.equalsIgnoreCase(strcpy_P(ioBuffer, PSTR("SWR")))) {
                  //
                  //  SWR: read A/D and compute SWR
                  //

                  // add the SWR value to the response
                  cmdText += "=";
                  FormatFloat(ioBuffer, sizeof(ioBuffer), swr.Value());
                  cmdText += ioBuffer;
                  ok = true;
                } else if (command.equalsIgnoreCase(strcpy_P(ioBuffer, PSTR("RAW")))) {
                  //
                  //  RAW: read A/D and output raw values
                  //
                  cmdText += "=";
                  snprintf(ioBuffer, sizeof(ioBuffer), "%d", swr.ForwardRaw());
                  cmdText += ioBuffer;
                  cmdText += ",";
                  snprintf(ioBuffer, sizeof(ioBuffer), "%d", swr.ReflectedRaw());
                  cmdText += ioBuffer;
                  ok = true;
                } else if (command.equalsIgnoreCase("PWR")) {
                  //
                  //  POWER: read A/D and output scaled values
                  //
                  cmdText += "=";
                  FormatFloat(ioBuffer, sizeof(ioBuffer), swr.Forward());
                  cmdText += ioBuffer;
                  cmdText += ",";
                  FormatFloat(ioBuffer, sizeof(ioBuffer), swr.Reflected());
                  cmdText += ioBuffer;
                  ok = true;
                } else if (command.equalsIgnoreCase("ALL")) {
                  //
                  //  ALL: read A/D and output scaled values + SWR
                  //
                  cmdText += "=";
                  FormatFloat(ioBuffer, sizeof(ioBuffer), swr.Value());
                  cmdText += ioBuffer;
                  cmdText += ",";
                  FormatFloat(ioBuffer, sizeof(ioBuffer), swr.Forward());
                  cmdText += ioBuffer;
                  cmdText += ",";
                  FormatFloat(ioBuffer, sizeof(ioBuffer), swr.Reflected());
                  cmdText += ioBuffer;
                  ok = true;
                } else if (command.equalsIgnoreCase("ECHO")) {
                  //
                  //  QUERY/SET ECHO
                  //
                  if (argument.length() == 0) {
                    ok = true;
                    cmdText += "=";
                    cmdText += echo ? "1" : "0";
                  } else {
                    int newEcho = argument.toInt();
                    echo = newEcho ? true : false;
                    ok = true;
                  }
                } else if (command.equalsIgnoreCase(strcpy_P(ioBuffer, PSTR("AUTO")))) {
                  //
                  //  QUERY/SET AUTO-POLL
                  //
                  if (argument.length() == 0) {
                    ok = true;
                    cmdText += "=";
                    cmdText += autoPoll;
                  } else {
                    int newAuto = argument.toInt();
                    if (newAuto >= 0 && newAuto < MaxAutoPoll) {
                      autoPoll = newAuto;
                      ok = true;
                    }
                  }
                } else if (command.equalsIgnoreCase(strcpy_P(ioBuffer, PSTR("AUTORAW")))) {
                  //
                  //  QUERY/SET AUTO-POLL RAW MODE
                  //
                  if (argument.length() == 0) {
                    ok = true;
                    cmdText += "=";
                    cmdText += autoRaw ? "1" : "0";
                  } else {
                    int newAuto = argument.toInt();
                    autoRaw = newAuto ? true : false;
                    ok = true;
                  }
                } else if (command.equalsIgnoreCase(strcpy_P(ioBuffer, PSTR("VERSION")))) {
                  //
                  //  QUERY VERSION NUMBER
                  //
                  ok = true;
                  cmdText += "=";
                  cmdText += VERSION_STRING;
                } else if (command.equalsIgnoreCase(strcpy_P(ioBuffer, PSTR("ALPHAFWD")))) {
                  //
                  //  QUERY/SET ALPHA - FORWARD
                  //
                  if (argument.length() == 0) {
                    ok = true;
                    cmdText += "=";
                    cmdText += swr.AlphaForward();
                  } else {
                    // read the value (float)
                    for (uint8_t i = 0; i != argument.length(); ++i) {
                      ioBuffer[i] = argument.charAt(i);
                    }
                    ioBuffer[argument.length()] = 0;
                    float alpha = atof(ioBuffer);
                    // set the value
                    swr.AlphaForward(alpha);
                    // read-back to see what actually got set
                    cmdText = command + "=" + swr.AlphaForward();
                    ok = true;
#if PERSIST_SETTINGS == true
                    save_eeprom();
#endif
                  }
                } else if (command.equalsIgnoreCase(strcpy_P(ioBuffer, PSTR("ALPHAREF")))) {
                  //
                  //  QUERY/SET ALPHA - REFLECTED
                  //
                  if (argument.length() == 0) {
                    ok = true;
                    cmdText += "=";
                    cmdText += swr.AlphaReflected();
                  } else {
                    // read the value (float)
                    for (uint8_t i = 0; i != argument.length(); ++i) {
                      ioBuffer[i] = argument.charAt(i);
                    }
                    ioBuffer[argument.length()] = 0;
                    float alpha = atof(ioBuffer);
                    // set the value
                    swr.AlphaReflected(alpha);
                    // read-back to see what actually got set
                    cmdText = command + "=" + swr.AlphaReflected();
                    ok = true;
#if PERSIST_SETTINGS == true
                    save_eeprom();
#endif
                  }
#if PERSIST_SETTINGS == true
                } else if (command.equalsIgnoreCase(strcpy_P(ioBuffer, PSTR("EREAD")))) {
                  //
                  //  READ: get startup settings from EEPROM
                  //
                  load_eeprom();
                  ok = true;
                } else if (command.equalsIgnoreCase(strcpy_P(ioBuffer, PSTR("EWRITE")))) {
                  //
                  //  WRITE: commit settings to EEPROM
                  //
                  save_eeprom();
                  ok = true;
                } else if (command.equalsIgnoreCase(strcpy_P(ioBuffer, PSTR("ECLEAR")))) {
                  //
                  //  FACTORY: reset EEPROM data
                  //
                  clear_eeprom();
                  ok = true;
#endif
                }

                //
                //  TODO: process other command contents
                //

                // respond with #OK or #ERR
                if (echo)
                  HostSerial.print(strcpy_P(ioBuffer, PSTR("\r\n")));
                HostSerial.print(ok ? strcpy_P(ioBuffer, PSTR("#OK:")) : strcpy_P(ioBuffer, PSTR("#ERR:")));
                HostSerial.print(cmdText);
                HostSerial.print(';');
                if (echo)
                  HostSerial.print(strcpy_P(ioBuffer, PSTR("\r\n")));
                cmdText = "";
              } else {
                if (cmdText.length() < CommandLength) {
                  cmdText += ch;
                }
                if (echo) {
                  HostSerial.print(ch);
                }
              }
              continue;
            }

            // start command mode??
            if ((!cmd) && (ch == '#')) {
              cmd = true;
              if (echo) HostSerial.print('#');
              continue;
            }
          }

          // clear the string:
          inputString = "";
          inputReady = false;
        }

        // service the serial port
        while (HostSerial.available()) {
          // get a new byte
          char inChar = (char)HostSerial.read();

          // add it to the inputString
          if (inputString.length() < InputLength)
            inputString += inChar;
          inputReady = true;
        }
        delay(1000);
      }
    }

    if (D == 1) {
      display.clear();
      display.setCursor(0, 0);
      display.print ("LED CONTROL");
      display.setCursor(0, 1);
      display.print ("NOT AVAILABLE");
      D = 0;
      // Your code here
    }
    if (L == 1) {
      display.clear();
      display.setCursor(0, 0);
      display.print ("Motor STOP");
      analogWrite(3, 0);   //Stops the motor
      L = 0;
      // Your code here
    }
  }
}

I put the first part beginning of loop like you said. No idea what you mean by rest of it...
This code is part of one and another code and its put together and removed things.

display.setCursor(0, 1);
    display.print(wd[abs(e % 2400) / 280]);

This is the code that prints direction on lcd line 2. It needs to be refreshing itself and at the same time accept all other IF's so when I press another button it stops doing this and changed lcd to something else.

Thanks for the reformatting. the code is much easier to read.

The way you get it to respect the other buttons is to let the code cycle back through loop() and get back to their if conditions.

Diagnosis-wise, x is in the 0-60 or 400-600 range or the display shouldn't/wouldn't be happening, and the if(...){ ..} else if(...){...}... construction makes each of the x cases independent....

What happens if x changes from 59 to 61 between iterations of the loop? nothing counteracts/cleans up these motor controls:

    digitalWrite(12, HIGH); //Establishes forward direction of Channel A
    digitalWrite(9, LOW);   //Disengage the Brake for Channel A
    analogWrite(3, 100);   //Spins the motor on Channel A at full speed

and I would suppose the motor would keep running at full speed to the forward/right direction.

How does x or whatever analogRead(0) is attached to behave?

When no buttons are pushed, what is supposed to happen?

analogWrite(3, 100); is slower than full speed.
255 would be full speed.

Im not sure what you mean.
analog read 0 is the buttons on the lcd shield.

Im trying to do antenna turner. So when I press "right" button, motor starts moving and encoder reads the direction the antenna is facing. and the direction has to update at least once a seccond.

atm when I press RIGHT or LEFT button, the motor turns and encoder tells me direction once.
lets say I press right button, motor turns half way, on the screen it still says north. I press right again, then it updates to south and motor keeps turning but does not update the direction.
The "select" button is for stopping the motor. and when motor is turning right, and I press left, then it stops and motor starts going left etc....
up and down buttons are for different thing try to ignore those.

when no button is pressed. nothing is supposed to happen.
arduino starts... it asks me what to do. I press right, motor starts turning. I press left... Motor changed direction to left. I press select.. motor stops.
when no button is pressed. nothing is supposed to happen. it keeps doing what it does until I press something again.

Is this what happens? I would guess that it keeps reporting while still have the button pressed, but when you let you finger up off the left button, x=analogRead(0) goes to maybe above 800 and no if-then-else cases apply, so the motor keeps running because nothing stops it, but there's also no part that reports.

If that is what happening, maybe you need an else clause after the else if (x < 800) { ...} section that does appropriate reporting when no button is pressed:


   } 
    else  { // no button pressed
    if ( R || L ){ // motor turning
        updateDisplayDaveX();
    }
    //...
   }

almost working now.
when I press "right"
Motor turn and it updates the encoder direction. like it should.
Also rest of the buttons work. but when I press "left". it says "motor stopped"
if I reset arduino and go straight left, still same motor stopped.
So the left button is now not working.

//edit seems like I broke my code myself :smiley:
//edit2 seems to be working fine now. thank you.

So if I understood the problem was that "if" no button is pressed "nothing" is refreshing?

I think so. With the x=analogRead(); and then the if (x <nnn){...}... stuff it was hard to understand. There are 5 ways those buttons could be: [None,left,right,up,down] and you only had code in loop() to handle 4 of the cases.

I'd have written something to interpret the button state into the five distinct states, then used a switch (buttonState){ case LEFT: .... case NONE: }` but the if-else if does work.

If Up or Down should stop the motor, you should add some code in those cases for stopping the motor. Or you could put it in the None/no button pressed code:

   } 
    else  { // no button pressed
    if ( R || L ){ // motor turning
        updateDisplayDaveX();
    } else { // not moving left or right -- ensure motor is stopped
           digitalWrite(9, HIGH);   //Engage the Brake for Channel A
           analogWrite(3, 0);   //Spins the motor on Channel A at zero speed
    }
     //...
   }

yep figured this part out already.
Actually here is 6 ways those buttons can be.
None,left,right,up,down... and then there is also "select" button.
https://create.arduino.cc/projecthub/electropeak/using-1602-lcd-keypad-shield-w-arduino-w-examples-e02d95
Here's the link for the keypad, there is also A0 values explaneid. what value means what button.

Anyway the code is fixxed now and works perfectly like it should.
Thanks :slight_smile:

now trying to figure out how to print Ä and Ö letters :smiley:
seems not so simple

I'd use the structure from that tutorial to write a function like:

enum B_states {NONE, LEFT,RIGHT,UP,DOWN};

int read_LCD_buttons(){
   int x = analogRead (0); 
   if (x < 60) return RIGHT;
   if (x < 200) return UP;
   if (x < 400) return DOWN;
   if (x < 600) return LEFT;
   if( x < 800) return SELECT;
   return NONE; 
}

then I'd have written the loop to use the function results for a switch-case statement:

//globals:
int e ;  // global for encoder

void loop(void){
   e = windvane.read();
   static int mode = NONE;
   switch(read_LCD_buttons){
     case RIGHT: {
        mode = RIGHT;
        driveMotor(RIGHT);
        report_motor();
        break;
     } 
     case LEFT: {
        mode = LEFT;
        driveMotor(LEFT);
        report_motor();
        break;
     } 
     case UP: {
        mode = UP;
        //...
        break;
     } 
     case DOWN: {
        mode = DOWN;
        //...
        break;
     } 
     case SELECT: {
        driveMotor(NONE);
        break;
     } 
      case NONE: {
        if ( mode == RIGHT || mode == LEFT ){ // motor turning
            reportMotor();
         } else { // not moving left or right -- ensure motor is stopped
           driveMotor(NONE);
        }
     //...
        break;
     } 
     default:
       ;
  }
}

With more than a screenful of chained if-elses that depend on their ordering, it is very easy to miss that you aren't doing any processing/refreshing/handling for the missing range of analogRead(0);

Thanks, I will be doing something like this. alot clearer(?) to read. But now in the hurry just needed to get code running.