I have created a small circuit with a 220 Ohm resistor and a LED connected to PIN9 for power.
I want to measure the Voltage of the current flowing through the circuit. In order to do that I connected a bridge from between the resistor and the LED to the A3 PIN and used this code:
int ledPin=9;
int inPin=A3;
long int in=0;
float V_in=0;
int val;
void setup() {
analogReference(DEFAULT);
pinMode(ledPin, OUTPUT);
pinMode(inPin, INPUT);
Serial.begin(9600);
}
void loop() {
if (Serial.available() > 0) {
val = Serial.parseInt();
if (val>=0 && val<=155) {
analogWrite(ledPin, val);
//Serial.println(val);
for (int i=0; i<10; i++) {
val+=5;
analogWrite(ledPin, val);
//Serial.println(val);
delay(1000);
in = analogRead(inPin);
V_in=float(5.0)*(float(in)/float(1023));
Serial.println(V_in);
delay(1000);
}
}
else {
Serial.println("Dio è morto.");
}
}
}
The problem is that when I run it, with an Input of 55, I get what seams to be a random arrangement of 0s and 2.56s. While I expect a increasing sequence of numbers between 0 and 2.5.
What am I doing wrong?
I measured the Voltage on the A3 Pin using a voltimeter, and it increases every step by 0.2, exactly as expected.
This is an output example:
1 Answer 1
The analogWrite
function, despite its name, outputs PWM (pulse width modulation) which is either fully on or fully off, with varying duty cycles. If you run that through a RC network (eg. 4.7k in series and 10 μF to ground), it will smooth out the pulses and you will actually get a varying voltage.
So in your case you are measuring on or off depending on the timing. However since you are measuring between the resistor and the LED, you won't get 5V because of the voltage drop over the resistor. An LED, depending on the colour, might have a voltage drop of around 2.2V, and thus you might expect 2.8V at that junction. This is approximately what you got.
I want to measure the Voltage of the current ...
This doesn't make any sense electrically. You are either measuring the voltage (in volts) or the current (in amps). You don't measure the "voltage of the current". I suppose you mean "the voltage at that point".
Reference
Arduino functions reference:
-
Measuring the voltage of the current does make sense if you measure the voltage across a known, fixed resistor. You can then use Ohm's law to determine the current through that resistor (and through the LED).tttapa– tttapa2017年12月26日 09:52:37 +00:00Commented Dec 26, 2017 at 9:52
-
Thank you for the grat and detailed answer. I am quite new to arduino, but this answer clarified the doubts I hadDaniele– Daniele2017年12月26日 18:55:54 +00:00Commented Dec 26, 2017 at 18:55
analogWrite
function doesn't output an analog voltage. It can only output 5V or 0V, nothing in between. It's called PWM.