Matlab-Arduino Multi Servos "for" loop ?


I am new  to arduino. I am struggling with basic problem i guess. I need to rotate 2 servo slowly with for loop in Matlab. To rotate one servo from 90 to 120, I am using this code in Matlab:

for i=90:120
fwrite(arduino, i);

I found zoomkat sample multi servo code but it requires string command   like:
fprintf(arduino,"%c", "700a,");

And of course ( for i=90:120 fprintf(arduino,"%c", "ia,"); pause(0.03); end ) Not working.

I thought that first number of i may represent servo number. For example; 
fwrite(arduino, 1100) -> Servo number 1 to 100 degree
fwrite(arduino, 2050) -> Servo number 2 to 50 degree

Arduino Code:
#include <Servo.h>
Servo servo1, servo2; 

void setup() {

void loop() {

  if( Serial.available() )
        int x =;
        int servoNum=x/1000;
        int w=x-(servoNum*1000);
        if (servoNum==1){
        if (servoNum==2){

And when i try fwrite command in matlab 
arduino = serial('COM3','BaudRate',9600);
for i=60:90
fwrite(arduino, a);  %Servo number 2  from 60 to 90 

But this one also not working... How can i do that? Please help..

sort by: active | newest | oldest
mr61 (author) 3 years ago

For those who may have same problem just use num2str method:

fprintf(arduino, '%c', [num2str(position) 'a,']); %run servo a to required position

Fwrite is not the correct function. Try Fprintf instead.

mr61 (author)  steveastrouk3 years ago

Actually i do not know fwrite specifications completely. I've been using it for one servo only. When i try fprintf (for i=90:120 fprintf(arduino,"%c", "ia,"); pause(0.03); end) with zoomkat multiservo code, Arduino runs servo to opposite direction and irrelevant position. Generally it moves quickly to 30-40 instead of 120.

Are you actually trying to transmit the PROGRAM to the Arduino over serial like that ??

mr61 (author)  steveastrouk3 years ago

You said try fprintf and as far as i know position is sent with string command in fprintf. I'm aware of that fprintf(....'ia,') is not correct syntax. To increase i number step by step, it must be integer but how can i send integer command with fprintf? Can you be more specific? Thanks for your help.

fprintf (arduino,%d,i)

To write two numbers

printf (arduino,'%d %d',i,j)

CHECK by connecting two PCs together with their serial ports.

What is the output of an fwrite ? ASCII representations or binary ? "90" in ascii is "9" and "0", 90 as binary is a "Z", 91 is "[", 92 is "/" etc etc

How is "not working" ? Can you run the arduino using PuTTY or Hyperterminal ? Check that first.