построение динамической графики
- Войдите на сайт для отправки комментариев
Вс, 08/03/2015 - 20:59
Здравствуйте.
Я работаю с тримя датчиками ds18b20 для температуры, electret microphone для звука и piezo element для вибрации. все три датчика работают от одного кода, правда, piezo element не выдает данных на serial. Мне нужно построить графику из данных этих трех датчиков, чтоб график менялся в реальном времени. как это можно сделать в матлаб? или для этого есть какие нибудь другие программы?
вот код который я использовал
#include <OneWire.h>
// OneWire DS18S20, DS18B20, DS1822 Temperature Example
//
//
// The DallasTemperature library can do all this work for you!
OneWire ds(10); // on pin 10 (a 4.7K resistor is necessary)
//========================================================
const int sampleWindow = 500; // Sample window width in mS (50 mS = 20Hz)
unsigned int sample;
//=============================================================
const int ledPin = 9; // internal led in pin9 (Arduino Ethernet board)
const int knockSensor = A1; // the piezo is connected to analog pin 0
const int threshold = 10; // threshold value to decide when the detected sound is a knock or not
// these variables will change:
int sensorReading = 0; // variable to store the value read from the sensor pin. From 0 to 1023
int ledState = LOW; // variable used to store the last LED status
void setup(void) {
Serial.begin(9600);
pinMode(ledPin, OUTPUT); // declare the ledPin as as OUTPUT
}
void loop(void) {
byte i;
byte present = 0;
byte type_s;
byte data[12];
byte addr[8];
float celsius, kelvin, K;
if ( !ds.search(addr)) {
Serial.println();
ds.reset_search();
delay(250);
return;
}
for( i = 0; i < 8; i++) {
Serial.write(' ');
}
if (OneWire::crc8(addr, 7) != addr[7]) {
return;
}
Serial.println();
// the first ROM byte indicates which chip
switch (addr[0]) {
case 0x10:
// or old DS1820
type_s = 1;
break;
case 0x28:
type_s = 0;
break;
case 0x22:
type_s = 0;
break;
default:
return;
}
ds.reset();
ds.select(addr);
ds.write(0x44, 1); // start conversion, with parasite power on at the end
delay(500); // maybe 750ms is enough, maybe not
// we might do a ds.depower() here, but the reset will take care of it.
present = ds.reset();
ds.select(addr);
ds.write(0xBE); // Read Scratchpad
Serial.print(" ");
for ( i = 0; i < 9; i++) { // we need 9 bytes
data[i] = ds.read();
Serial.print(" ");
}
Serial.println();
// Convert the data to actual temperature
// because the result is a 16 bit signed integer, it should
// be stored to an "int16_t" type, which is always 16 bits
// even when compiled on a 32 bit processor.
int16_t raw = (data[1] << 8) | data[0];
if (type_s) {
raw = raw << 3; // 9 bit resolution default
if (data[7] == 0x10) {
// "count remain" gives full 12 bit resolution
raw = (raw & 0xFFF0) + 12 - data[6];
}
} else {
byte cfg = (data[4] & 0x60);
// at lower res, the low bits are undefined, so let's zero them
if (cfg == 0x00) raw = raw & ~7; // 9 bit resolution, 93.75 ms
else if (cfg == 0x20) raw = raw & ~3; // 10 bit res, 187.5 ms
else if (cfg == 0x40) raw = raw & ~1; // 11 bit res, 375 ms
//// default is 12 bit resolution, 750 ms conversion time
}
celsius = (float)raw / 16.0;
kelvin=celsius+273.15;
Serial.print(" Temperature = ");
Serial.print(celsius);
Serial.print("C,");
Serial.print("Kelvin=");
Serial.print(kelvin);
Serial.print("K,");
//========================
unsigned long startMillis= millis(); // Start of sample window
unsigned int peakToPeak = 0; // peak-to-peak level
unsigned int signalMax = 0;
unsigned int signalMin = 1024;
// collect data for 50 mS
while (millis() - startMillis < sampleWindow)
{
sample = analogRead(0);
if (sample < 1024) // toss out spurious readings
{
if (sample > signalMax)
{
signalMax = sample; // save just the max levels
}
else if (sample < signalMin)
{
signalMin = sample; // save just the min levels
}
}
}
peakToPeak = signalMax - signalMin; // max - min = peak-peak amplitude
double volts = (peakToPeak * 3.3) / 1024; // convert to volts
Serial.print("volts=");
Serial.print(volts);
//======================================================
// read the sensor and store it in the variable sensorReading:
sensorReading = analogRead(knockSensor);
// if the sensor reading is greater than the threshold:
if (sensorReading >= threshold) {
// toggle the status of the ledPin:
ledState = !ledState;
// update the LED pin itself:
digitalWrite(ledPin, ledState);
// send the string "Knock!" back to the computer, followed by the sensor value.
Serial.print(sensorReading);
}
delay(50); // delay to avoid overloading the serial port buffer
}
На форуме есть замечательная функция всавки кода, делая его более читабельным для других. Исправте своё сообщение.
Посмотрите эту статью: Термокоса под управлением Arduino и LabVIEW
По матлабу ничего не подскажу. Если надо, то ещё могу найти прогу друга на Java, которая считывала данные с термопары и выводила график в режиме реального времени на монитор.
Вот кстати соседняя тема по вашей части http://arduino.ru/forum/apparatnye-voprosy/arduino-hc-05-matlab
спасибо за ответ! и извиняюсь за не грамотность в использовании функций форума
есть вот такой код для матлаб, только проблема в том что он выдает какие то странные значение на графике. например от термо датчика в serial я получаю 25 градусов, а в матлабе на графике он показывает 118. А что за прога о которой вы говорите?
%run('clean'); clear all; close all; s = serial('COM1'); %assigns the object s to serial port set(s, 'InputBufferSize', 256); %number of bytes in inout buffer set(s, 'FlowControl', 'hardware'); set(s, 'BaudRate', 9600); set(s, 'Parity', 'none'); set(s, 'DataBits', 8); set(s, 'StopBit', 1); set(s, 'Timeout',10); %clc; disp(get(s,'Name')); prop(1)=(get(s,'BaudRate')); prop(2)=(get(s,'DataBits')); prop(3)=(get(s, 'StopBit')); prop(4)=(get(s, 'InputBufferSize')); disp(['Port Setup Done!!',num2str(prop)]); fopen(s); %opens the serial port t=1; disp('Running'); x=0; while(t < 200) %Runs for 200 cycles - if you cant see the symbol, it is "less than" sign. so while (t less than 200) a =fread(s); %reads the data from the serial port and stores it to the matrix a a=max(a); % in this particular example, I'm plotting the maximum value of the 256B input buffer x =[x a]; % Merging the value to an array, this is not very computationaly effective, as the array size is dynamic. %Consider pre allocation the size of the array to avoid this. But beware, You might loose some important %data at the end! plot(x); axis auto; grid on; disp([num2str(t),'th iteration max= ',num2str(a)]); hold on; t=t+1; a=0; %Clear the buffer drawnow; end fclose(s); %close the serial portможет кто-то сможет разобраться в этом
Попробуй по моей статье http://arduino-project.net/grafik/