Discover MakerZone

MATLAB and Simulink resources for Arduino, LEGO, and Raspberry Pi

Learn more

Discover what MATLAB® can do for your career.

Opportunities for recent engineering grads.

Apply Today

New to MATLAB?

MATLAB communication with Arduino Uno (with servos)

Asked by Maria Lopez

Maria Lopez (view profile)

on 7 Aug 2012

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);     
    }
  }

0 Comments

Maria Lopez

Maria Lopez (view profile)

Products

No products are associated with this question.

1 Answer

Answer by Walter Roberson

Walter Roberson (view profile)

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.

0 Comments

Walter Roberson

Walter Roberson (view profile)

Contact us