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!