MATLAB communication with Arduino Uno (with servos)

4 views (last 30 days)
Hello guys, I'm trying to connect 2 servos to Arduino so to move them by digiting the degrees in MATLAB. I hope you guys can help me.
Here´s the code for MATLAB:
clear all
clc
dato=[1 0];
arduino=serial('COM3','BaudRate',9600);
fopen(arduino);
while dato
fprintf(arduino,'%s',char(dato));
dato=input('Dame coordenadas: ');
end
fclose(arduino);
Here´s the code for Arduino.
#include <Servo.h>
Servo myservo;
int pos = 0;
int a;
void setup() {
Serial.begin(9600);
myservo.attach(9);
}
char cadena[24];
byte contador=0;
int valor = 0;
void loop(){
for(a; a<1; a++){
Serial.print("Introduzca posicion de servo :");
}
if(Serial.available()){
memset(cadena, 0, sizeof(cadena));
while (Serial.available()>0){
delay(5);
cadena[contador]=Serial.read();
contador++;
}
valor=atoi(cadena);
valor = min(valor, 180); //establece valor maximo
valor = max(valor, 0); //establece valor minimo
Serial.print(valor); //imprime en pantalla el valor introducido
Serial.println(" grados");
myservo.write(valor); //establece el valor como posicion myservo
a=0; //reiniciamos a para volver a mostrar aviso para introduccion de datos
contador=0;
delay(100);
}
}

Answers (1)

Walter Roberson
Walter Roberson on 8 Aug 2012
You have
dato=[1 0];
and then you have
while dato
When you apply "if" or "while" to a vector or array, the test is only considered to be true if all the elements are non-zero. Your second element of dato is 0, so the "while" fails the first time around, and the fprintf() is never executed.

Categories

Find more on Arduino Hardware in Help Center and File Exchange

Community Treasure Hunt

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

Start Hunting!