-2

I am using analogWrite() in my code. Everything works fine when I am not using the servo library. In other words, everything is fine when I disable this line //servo_9.attach(9); If I enable this line, the PWM will be wrong and weird. Any idea why the Tinkercad simulator is acting weird?

#include <Servo.h>
int led =9;
Servo servo_9;

void setup() {
servo_9.attach(9);

Serial.begin(9600);

}


 void loop() {
 for(int n=0;n<255;n++){
     analogWrite(led,n);
     delay(5);
   }
 }

This video shows what is happening: click here

Mohamed Ibrahim
  • 191
  • 1
  • 12
  • 2
    Do you really have the servo and the led connected to the same pin? How do you propose one pin can do both things? – Delta_G Sep 22 '20 at 01:09
  • 2
    Never be afraid to check the documentation. Reading is fundamental. Check out the second sentence of the second paragraph under "Usage" https://www.arduino.cc/reference/en/libraries/servo/ – Delta_G Sep 22 '20 at 01:10

1 Answers1

1

The documentation for the servo library clearly states.

On boards other than the Mega, use of the library disables analogWrite() (PWM) functionality on pins 9 and 10, whether or not there is a Servo on those pins.

Delta_G
  • 2,927
  • 2
  • 9
  • 15
  • Thank you! That was very helpful. I used pin6, the signal looks much better but still different when the serve line is disabled. I also removed the led. – Mohamed Ibrahim Sep 22 '20 at 01:23
  • Different how? Is this real life or simulation? – Delta_G Sep 22 '20 at 01:40
  • that was the simulation, not the real hardware. – Mohamed Ibrahim Sep 22 '20 at 13:21
  • Then you don’t know what real hardware will do. Maybe the problem is the simulator. There was another question there also that you didn’t answer. – Delta_G Sep 22 '20 at 13:24
  • The signal is not exactly the same. It is like there is some noise. If you don't mind trying it yourself: https://www.tinkercad.com/things/6qIZvzIdVKb-lab2-part1/editel?sharecode=YlA0HPqGmjPHIHpfK7eHQ97BbuZkzDT20J-Zb4untO4 – Mohamed Ibrahim Sep 22 '20 at 13:30
  • disable the servo and see the difference. – Mohamed Ibrahim Sep 22 '20 at 13:30
  • No, I don’t work with simulators. You say it’s different but you won’t give me any indication as to what is different about it. So I can’t help you. – Delta_G Sep 22 '20 at 13:31
  • It’s probably just the crappy simulator. Try with real hardware and see what happens. – Delta_G Sep 22 '20 at 13:32
  • Let us [continue this discussion in chat](https://chat.stackoverflow.com/rooms/221876/discussion-between-mohamed-ibrahim-and-delta-g). – Mohamed Ibrahim Sep 22 '20 at 13:33