2016-08-02 5 views
0

Я работаю над проектом, в котором я использую двойной сервопривод и один сонар hc-sr04 для отображения вещей. Я все еще на начальных этапах, но я работаю с простыми вещами, такими как отображение коробки. В настоящее время я беру серийные данные arduino, где у меня есть (R, theta, phi) и превращая это в (x, y, z), а затем на Matlab. После полного сканирования я загрузил файл txt в matlab и запустил его. Я хочу, чтобы это было в реальном времени. Это мой Arduino кодПопытка в реальном времени Данные датчика положения от Arduino

#include <Servo.h> 
#include <NewPing.h> 
Servo myservo,myservo2; // create servo object to control a servo 
#define TRIGGER_PIN 7 
#define ECHO_PIN 2 
#define MAX_DISTANCE 200 
NewPing s1(TRIGGER_PIN,ECHO_PIN,MAX_DISTANCE); 
double smoothedValue1,smoothedValue2; 
float filterValue; 
const int numReadings = 100; 

int readings[numReadings];  // the readings from the analog input 
int readIndex = 0;    // the index of the current reading 
int total = 0;     // the running total 
int average = 0;    // the average 
int myCounter = 0; 
int Counter = 0; 
int upper=2; 
// twelve servo objects can be created on most boards 

int pos = 0; // variable to store the servo position 

void setup() { 
    myservo.attach(12); // attaches the servo on pin 9 to the servo object 
    myservo2.attach(11); 
    myservo.write(pos); 
    myservo2.write(pos); 
    for (int thisReading = 0; thisReading < numReadings; thisReading++) { 
    readings[thisReading] = 0; 
    } 
    Serial.begin(9600); 
} 

void loop() { 
    if(myCounter<182/upper) 
    { 
    for (pos = 0; pos <= 180; pos += 1) { // goes from 0 degrees to 180 degrees 
    // in steps of 1 degree 
    myservo.write(pos);    // tell servo to go to position in variable 'pos' 
    delay(15); // waits 15ms for the servo to reach the position 
    total = total - readings[readIndex]; 

    int Input1=s1.ping_cm(); 
    if (Input1 == 0 || Input1 >100) 
     { 
      Input1=100; 
     } 
     readings[readIndex] = Input1; 
    // add the reading to the total: 
    total = total + readings[readIndex]; 
    // advance to the next position in the array: 
    readIndex = readIndex + 1; 

    // if we're at the end of the array... 
    if (readIndex >= numReadings) { 
    // ...wrap around to the beginning: 
    readIndex = 0; 
    } 

    // calculate the average: 
    filterValue=.2; 
    average = total/numReadings; 
    smoothedValue1 = (average * (1 - filterValue)) + (smoothedValue1 * filterValue); 
      smoothedValue2 = (smoothedValue1 * (1 - filterValue)) + (smoothedValue2 * filterValue); 
    // send it to the computer as ASCII digits 
    // send it to the computer as ASCII digits 




Serial.print(smoothedValue2); 
Serial.print("\t"); 
Serial.print(pos); 
Serial.print('\t'); 
Serial.println(Counter); 
delay (30); 

    } 
    for (pos = 180; pos >= 0; pos -= 1) { // goes from 180 degrees to 0 degrees 
    myservo.write(pos);    // tell servo to go to position in variable 'pos' 
    delay(15); // waits 15ms for the servo to reach the position 
    total = total - readings[readIndex]; 

    int Input1=s1.ping_cm(); 
    if (Input1 == 0 || Input1 >100) 
     { 
      Input1=100; 
     } 
     readings[readIndex] = Input1; 
    // add the reading to the total: 
    total = total + readings[readIndex]; 
    // advance to the next position in the array: 
    readIndex = readIndex + 1; 

    // if we're at the end of the array... 
    if (readIndex >= numReadings) { 
    // ...wrap around to the beginning: 
    readIndex = 0; 
    } 

    // calculate the average: 
    average = total/numReadings; 
    filterValue=.2; 
      smoothedValue1 = (average * (1 - filterValue)) + (smoothedValue1 * filterValue); 
      smoothedValue2 = (smoothedValue1 * (1 - filterValue)) + (smoothedValue2 * filterValue); 
    // send it to the computer as ASCII digits 

Serial.print(smoothedValue2); 
Serial.print("\t"); 
Serial.print(pos); 
Serial.print('\t'); 
Serial.println(Counter); 
delay (30); 

    } 
    myCounter = myCounter + 1; 
    Counter=Counter+upper; 
    myservo2.write(Counter); 
    } 

} 

Это мой код. Мой Matlab код в настоящее время

clc;clear; 

[A,B,C]=textread('CoolTerm Capture 2016-08-01 13-49-13.asc','','headerlines',6); 
[A]; 
[X]=A.*sind(B).*cosd(C); 
[Y]=A.*sind(B).*sind(C); 
[Z]=A.*cosd(B); 
scatter3(X,Z,Y,3) 

Я знаю немного о чтении COM-порты и сделать несколько сценариев, но ни один из них не было в реальном масштабе времени. Любая помощь будет оценена по достоинству.

ответ

0

Некоторые вещи, которые могут помочь вам.

В Matlab вы можете использовать hold all для того, чтобы рисовать на том же рисунке, чтобы вы могли добавлять точки или кривые или что угодно на свой участок. Эта короткая процедура показывает, что я говорю:

plot(0,0, '*r'); 
xlim([0 100]); 
ylim([0 100]); 
hold all 
for x=1:100 
    plot(x,x,'*r'); 
    pause(1) 
end 

С другой стороны, для связи с Arduino вы можете использовать последовательный порт связи доступны в Matlab и читать последовательные данные отправить по Arduino непосредственно в Matlab , Вы можете найти информацию here.

Ваша цель состоит в том, чтобы интегрировать две части, упомянутые мной в один код, который работает с вашим предыдущим кодом.

Надеюсь, это поможет.

Смежные вопросы