How can I work Servo motor with ESP32?

Hi, now I’m trying to use servo motor with ESP32 and mongoose os.

My goal is when I put a button that is connected to PIN No.13, servo motor rotating CW or CCW.(servo motor’s signal cable is connected to PIN No.14)

The following is my javascript code.


load(‘api_gpio.js’);
load(‘api_pwm.js’);

GPIO.set_mode(13, GPIO.MODE_INPUT);
GPIO.set_button_handler(13, GPIO.PULL_UP, GPIO.INT_EDGE_NEG, 20, function(x) {
PWM.set(14, 500, 50)
}, true);


Is my understanding correct?
This is my first time to make IoT device and use javascript.
Please help.

I suggest you to instrument the code with some tracing, e.g.:

load('api_gpio.js');
load('api_pwm.js');

GPIO.set_mode(13, GPIO.MODE_INPUT);
GPIO.set_button_handler(13, GPIO.PULL_UP, GPIO.INT_EDGE_NEG, 20, function(x) {
  print('button pressed, activating servo');
  PWM.set(14, 500, 50)
}, true);

Please clarify on:

  1. What is your issue?
  2. What are the corresponding device logs

The 3rd argument of PWM.set is the duty cycle of the generated square wave.
Ref: https://github.com/mongoose-os-libs/pwm/blob/5818662baa7e8bc8e965420f0c1a78203dba0a76/mjs_fs/api_pwm.js#L1-L19

AFAIK, the servo motors are driven with 50Hz.
Typically, a pulse width of 1000 micro seconds (duty 1000/20000=0.05 at 50Hz) will move the servo to one end (let’s say 0 degrees), while a 2000 micro seconds pulse (duty 2000/20000=0.1) will move it to the other end (180 degrees).

1 Like

Thank you for replying.

1.What is your issue?
I put an above code , but my servo motor did’nt working.
But I can’t find what is wrong.

2.What are the corresponding device logs
OK, i will check device log.

And I will change fleq to 50Hz and check the result, thanks.

Following your advice, I check my code.
I use the servo motor SG90.
This motor’s spec is;

PWM period is 20ms(50Hz), Position “0” (1.45 ms pulse) is middle, “90” (~2.4 ms pulse) is all the way to the right,"-90" (~ 0.5 ms pulse) is all the way left.
So I changed my code like this. “PWM.set(14, 50, 0.115)”
And my system working correct.


Thank you for the useful advice.:grin:

Hi, when I include: load(‘api_pwm.js’);
into my init.js, my ESP-32 freezes.

Am I doing this right?
Thanks

nvm, I found the sollutions, I had to include " - origin: https://github.com/mongoose-os-libs/pwm
" in the mos.yml

Could not build with lib api_pwm.js included.as part of init.js…also tried adding origin: https://github.com/mongoose-os-libs/pwm
" in the mos.yml
Still could not build…will it help if I download (https://github.com/mongoose-os-libs/pwm)…
if so…which folder should I download it into…