Controlling *Servo Motor*s with an *RaspberryPi* + *Servo/PWM-Pi Hat!* using *MATLAB*

10 views (last 30 days)
Hi, I have to control one or more Servo motors which are plugged in a Servo/PWM-Pi Hat which is plugged in a RaspBerryPi 3 on the other hand. VIA Matlab.
if true
% >> rpi = raspi
rpi =
raspi with properties:
Port: 18732
BoardName: Raspberry Pi 3 Model B
AvailableLEDs: {'led0'}
AvailableDigitalPins: [4,5,6,12,13,14,15,16,17,18,19,20,21,22,23,24,25,26,27]
AvailableSPIChannels: {'CE0','CE1'}
AvailableI2CBuses: {'i2c-1'}
AvailableWebcams: {}
I2CBusSpeed: 0
Supported peripherals
>> showPins(rpi) >> rpi.AvailableI2CBuses
ans =
>> rpi.I2CBusSpeed
ans =
>> scanI2CBus(rpi,'i2c-1')
ans =
1×2 cell array
'0x40' '0x70'
>> i2csensor = i2cdev(rpi,'i2c-1','0x70')
i2csensor =
i2cdev with properties:
Bus: 'i2c-1'
Address: '0x70'
>> output1 = read(i2csensor,2)
output1 =
1×2 uint8 row vector
17 17
>> output2 = readRegister(i2csensor,14)
output2 =
>> i2csensor
%what do I type in here, to define the Servo motor which is connected to Pin 0 at the Servo/PWM Hat ?
>> s = servo(i2csensor,0) Undefined function 'servo' for input arguments of type 'raspi.internal.i2cdev'.
Tobias Schuster
Tobias Schuster on 24 Nov 2021
Hi Kenan, your script worked for me as well on Matlab R2021b and Raspberry Pi 4 B.
However, using the operating system of the file "" coming from the MATLAB Support Package for Raspberry Pi Hardware, I'm not able to control the servos. I can execute the script without any error message, but nothing happens on the hardware.
So far, I managed to control a DC Motor (direction and speed) which is also connected to the same Raspberry Pi via a motor hat. By using built-in functions like "configurePin(rpi,Pin,'PWM')" or "writePWMDutyCycle(rpi,Pin,speed)" I can access the relevant GPIO Pins. Maybe there is a posibility to realise a servo motor control in a similar way.
The support package also provides the functions
s = servo(mypi, 12, 'MinPulseDuration', 1e-3, 'MaxPulseDuration', 2e-3);
writePosition(s, 90);
but I don't know how to acces the servo in this way. Maybe it is only possible if the servo is directly connected to the Raspberry Pi without the motor hat in between.
Thank you in advance!

Sign in to comment.

Answers (0)


More Answers in the  Power Electronics Control

Community Treasure Hunt

Find the treasures in MATLAB Central and discover how the community can help you!

Start Hunting!