Problem sending data from MATLAB to Arduino

I’m trying to control a servo from MATLAB, but I’m having trouble and I don’t find the solution.

Here is my Arduino code:

#include <Servo.h>
Servo myservo;
int angle = 0;
int newAngle = 0;
const int MaxChars = 4;
char strValue[MaxChars+1];
int index = 0;

void setup()
{
 Serial.begin(9600);
 myservo.attach(9);
 angle = 90;
}
void loop()
{}

void serialEvent()
{
   while(Serial.available()) 
   {
      char ch = Serial.read();
      Serial.write(ch);
      if(index < MaxChars && isDigit(ch))       {                    strValue[index++] = ch;              }else{                    strValue[index] = 0;                    newAngle = atoi(strValue);                    if(newAngle > 0 && newAngle <180){
            if(newAngle < angle)                                for(; angle > newAngle; angle -= 1) {
                   myservo.write(angle);
               }  
            else 
               for(; angle < newAngle; angle += 1){
                   myservo.write(angle);
                } 
         }
         index = 0;
         angle = newAngle;
      }  
   }
}

Here is my MATLAB code:

import serial
s = serial('COM4','BaudRate',9600);
pause(1)
fopen(s)


angle = 1;


while angle ~= 0
    angle = input('Write servo angle: ');
    
    if angle ~= 200
        fwrite(s, angle, 'uint8')
        pause(1)
    elseif angle == 0
        fclose(s)
        delete(s)
        clear s
        delete(instrfindall)
        break;
    end
end

There are no error messages, but the servo doesn’t move…

Thanks in advance!

        fwrite(s, angle, 'uint8')

Is this writing the value as a string? Or is it writing the data as a binary value?

The only acceptable number of statements on one line is ONE! Fix your code!

The examples in serial input basics may be useful.

It does not look as if your Matlaab code is waiting for the Arduino to reset after it opens the serial port. And it should keep the serial port open until it is completely finished using the Arduino.

This Python example illustrates the process.

...R