2

I would like to do,

analogWrite(3,100); analogWrite(6,200);

at the same time. But the problem is that only the led on pin 3 lights up. I want both to light up at the same time. I've heard about direct port manipulation, but I can only find an alternate for digitalWrite() but I couldn't find one for analogWrite(). Can someone please help me with just a simple example on just how to do the above operation?

Lundin
  • 195,001
  • 40
  • 254
  • 396
Rishi Swethan
  • 23
  • 1
  • 4

4 Answers4

0

It's analogWrite(pin, value) not analogWrite(value, pin) as you're using it. Swapping those numbers should solve your problem.

See https://cdn.arduino.cc/reference/en/language/functions/analog-io/analogWrite/

Piglet
  • 27,501
  • 3
  • 20
  • 43
0

The code you are using is fine, and should set pin 3 to 39% power and pin 6 to 78% power using pulse width modulation. analogWrite() takes a number between 0 (off) and 255 (on).

You should check if your pins and your LEDs are working properly. You can do so by swapping both LEDs, as you already know your pin 3 and its LED are working fine.

Your pin 6 or the LED may be broken or burnt, or you could be using a LED at pin 6 that needs more current or voltage to turn on.

0

Arduino has a port manipulation function. To turn both pin 3 and 5 on at the same time, do

DDRD = B11111110; //set pins 1-7 as output EXCEPT for 0 AT THE SAME TIME
PORTD = B00101000; // sets digital pins 5 and 3 HIGH AT THE SAME TIME
PORTD = B00000000; // sets all digital pins LOW AT THE SAME TIME

AnalogWrite works by PWM, so you can just toggle those with a delay that depends on the desired output voltage. Note that you can't use this method to turn on, let's say, pins 2 and 12 at the same time, because they're in different registers. I'm sure that if you browse around in your arduino folder, you'll find a C/C++ file containing the definition for analogWrite. Just take that copy it, and replace digitalWrite with the port manipulation functions below. Hope this helps!

ndrewxie
  • 172
  • 3
  • 10
-1

You could come across this situation if you forget to set pinMode in setup:

pinMode(3, OUTPUT);
pinMode(6, OUTPUT);
fcdt
  • 2,371
  • 5
  • 14
  • 26
Tim
  • 1