I have a DC geared motor with an optical encoder. I can read MITSUMI M25N-2R-14 2241 and 25GA-370-12V-330RPM on the motor. I'm using this simple code to control the position of shaft. it works fine when I test it manually (turning shaft with hand when the motor is off) but when the motor is running by a L298N driver it shows random pulses on my output LCD so position control is impossible. What is wrong? Is there a noise source?
I'm using an Adruino Uno. 2,3 pins for 5v encoder, 6,7 pin for controlling the motor. Ground pin is connected to driver's GND.
#include <Wire.h> #include <U8g2lib.h> #include <LiquidCrystal_I2C.h> #include <Encoder.h> int motorA1 = 7 ; int motorA2 = 6 ; String Position, input; int newPosition = 0; int Input = 0; long pulse2go; LiquidCrystal_I2C lcd(0x3F, 20, 4); // Set the LCD address to 0x27 for a 16 chars and 2 line display U8G2_SSD1306_128X32_UNIVISION_F_HW_I2C oled(U8G2_R0, A5, A4, U8X8_PIN_NONE); Encoder myEncoder(2, 3); void setup() { oled.setI2CAddress(0x78);// 0x3C); oled.begin(); oled.setFont(u8g2_font_ncenB10_tr); oled.clear(); oled.setDrawColor(0xFF); oled.drawStr(45, 25, "Hello!"); oled.sendBuffer(); delay (1000); pinMode(motorA1 , "OUTPUT") ; pinMode(motorA2 , "OUTPUT") ; Serial.begin(250000) ; oled.clearDisplay(); } void loop() { if (Serial.available()) { input = Serial.readString(); input.remove(0, 1); Input = input.toInt(); pulse2go = Input - newPosition; while (abs(pulse2go) > 300) { if (pulse2go > 0) { digitalWrite(motorA1 , LOW) ; analogWrite(motorA2 , 75) ; } if (pulse2go < 0) { digitalWrite(motorA1 , HIGH) ; analogWrite(motorA2 , 75) ; } newPosition = myEncoder.read() ; Position = String(newPosition); oled.clearDisplay(); oled.drawStr(3, 15, "Position"); oled.sendBuffer(); oled.drawStr(3, 30, Position.c_str()); oled.sendBuffer(); oled.drawStr(75, 15, "Input"); oled.sendBuffer(); oled.drawStr(75, 30, input.c_str()); oled.sendBuffer(); } } } 


newPosition = myEncoder.read() ;suggests that it's an absolute encoder. \$\endgroup\$