Arduino Nano PWM with INA219 and OLED dispaly

This is the sketch I'm running, with 3 Red Leds each one with his own resistor from pin 9 to GND. The values displayed on serial monitor and OLED are very unstable, basically unusable, need some help, please.

#include <U8g2_for_Adafruit_GFX.h>




#include <Wire.h>
#include <Adafruit_INA219.h>
#include <SPI.h>
#include <Wire.h>
#include <Adafruit_GFX.h>
#include <Adafruit_SSD1306.h>
#define SCREEN_WIDTH 128 // OLED display width, in pixels
#define SCREEN_HEIGHT 32 // OLED display height, in pixels
#define OLED_RESET     -1 // Reset pin # (or -1 if sharing Arduino reset pin)
#define SCREEN_ADDRESS 0x3C ///< See datasheet for Address; 0x3D for 128x64, 0x3C for 128x32

Adafruit_SSD1306 display(SCREEN_WIDTH, SCREEN_HEIGHT, &Wire, OLED_RESET);
 
Adafruit_INA219 ina219;

int ledPin = 9;      // LED connected to digital pin 9
int analogPin = A0;  // potentiometer connected to analog pin A0
int val = 0;         // variable to store the read value

U8G2_FOR_ADAFRUIT_GFX u8g2_for_adafruit_gfx;




void setup() {
  // put your setup code here, to run once:
pinMode(ledPin, OUTPUT);  // sets the pin as output
Serial.begin(9600);
ina219.begin();
ina219.setCalibration_16V_400mA();

u8g2_for_adafruit_gfx.begin(display);                 // connect u8g2 procedures to Adafruit GFX

display.begin(SSD1306_SWITCHCAPVCC, SCREEN_ADDRESS);
 
  Serial.println("Measuring voltage, current, and power with INA219 ...");
}

void loop() {
  // put your main code here, to run repeatedly:
val = analogRead(analogPin);  // read the input pin
  analogWrite(ledPin, val / 4); // analogRead values go from 0 to 1023, analogWrite values from 0 to 255
  Serial.println(val);
  Serial.println(val/4);

 float shuntvoltage = 0;
  float busvoltage = 0;
  float current_mA = 0;
  float loadvoltage = 0;
  float power_mW = 0;
 
  shuntvoltage = ina219.getShuntVoltage_mV();
  busvoltage = ina219.getBusVoltage_V();
  current_mA = ina219.getCurrent_mA();
  power_mW = ina219.getPower_mW();
  loadvoltage = busvoltage + (shuntvoltage / 1000);
 
  Serial.print("Bus Voltage:   "); Serial.print(busvoltage); Serial.println(" V");
  Serial.print("Shunt Voltage: "); Serial.print(shuntvoltage); Serial.println(" mV");
  Serial.print("Load Voltage:  "); Serial.print(loadvoltage); Serial.println(" V");
  Serial.print("Current:       "); Serial.print(current_mA); Serial.println(" mA");
  Serial.print("Power:         "); Serial.print(power_mW); Serial.println(" mW");
  Serial.println("");
 
  //delay(1000); 

  display.clearDisplay();
      //display.setTextSize(2);
      u8g2_for_adafruit_gfx.setFontMode(1);                 // use u8g2 transparent mode (this is default)
  u8g2_for_adafruit_gfx.setFontDirection(0);            // left to right (this is default)
  u8g2_for_adafruit_gfx.setForegroundColor(BLACK);      // apply Adafruit GFX color
  u8g2_for_adafruit_gfx.setFont(u8g2_font_6x13_tf);  // select u8g2 font from here: https://github.com/olikraus/u8g2/wiki/fntlistall

      display.setTextSize(1);
      display.setTextColor(SSD1306_WHITE);
      display.setCursor(0, 0); 
      
      display.print("Load_voltage  "); display.print(loadvoltage); display.print("  V");
      //display.setTextSize(1);
      
      display.setCursor(0, 25);
      //display.print((vin));
      display.print("Current  "); display.print(current_mA); display.print("  mA");
      
      display.display();
      //delay(3000);

}

Are you trying to read a PWM signal by any chance? Maybe show us the serial output (in code tags, pls)

Sounds like a possible overload of pin 9. If you need to control 3 LEDs use a transistor of some sort.

Change the analogueWrite to a digitalWrite and see if that helps.

hi @mikemarcu
where does the voltage input on the A0 pin come from ? what is the voltage range of this input ? What sense does it make to output this value on 3 LEDs ? On my experience analog values read on the inputs is always a few digits unstable. Now it depends on how accurate you need your measurement. What you can do to make it more stable is built an average on multiple reads. For example in a loop read 10 times the input and sum them. After the loop devide the value by 10 and you have the average.

Which values are unstable?
The values coming from the ADC or the values coming from the INA219?
Or both?

Pin A0 is connected to the cursor of a trim pot, one end to 5V the other end to GND.
Yes, I'm measuring PWM. This goal of this experiment, to be able to use the "current_mA" as feedback to a PWM controlled voltage source.
Even with one single LED the same behaviour.

Using digitalwrite instead of analogwrite, as recommended, made a lot of difference, now the variation is about 9%, still too much, I'm looking for a 3%.

Monitoring the 5V from the USB I observed the voltage being all over, from 4.56 to 4.95.
Adding one LM78L05 and a 9 V battery totally made difference, now the current_mA reported by INA219 is in between 32.00 mA and 32.03 mA.
Problem solved.
Thanks everybody.

I'm a beginner with Arduino. I would like to know why using digitalWrite improved the behaviour, please?
Thanks,
Mike

The best way to learn is to read. Here is the link to analogWrite Notice it has two arguments; you, like many people, don't know about the second and what its purpose is. Based on your problem statement, you also did not know that for most boards, the analog output is a PWM signal. IIRC only 1 board puts out a true analog signal. Contrast that output to a digital digitalWrite To be a MCU programmer you need to learn more than the language, there is a certain amount of hardware you also need to know.

Thank you,
What hardware are you referring to, please?
I'm actually an engineer, electronics.

All the MCUs and MPUs. In your case, the NANO is an MCU.
Have you figured out why you experienced what you call unstable behaviour?

USB 5 v, varying, replacing it with 78L05 and a 9 v battery, the “current_mA”, 32.00 mA varying to the second decimal.

If that is a smoke detector type 9V battery, they are very underpowered. If you have a better battery I would swap it.
Do you understand why the analogWrite caused your problem?

In my analogwrite I have both parameters, port and duty cycle, I want PWM. The 9 v battery is a good quality.

Ok, glad you got it working.

Thanks for your help,

A personal observation, Adding a transistor in order to drive 8 LEDs, higher current, 160 mA, the value reported by INA219 are stable.

I went up to 300 mA current, all nice. Below 70 mA INA219 does not give reliable values, no matter the resolution setting.