BASIC4MCU | 질문게시판 | 아두이노 메가를 이용하여 lidar 거리 측정기 코딩 질문입니다. delay를 millis() 함수로 바꾸고 싶은데 잘 되지가…
페이지 정보
작성자 gktt3 작성일2020-03-15 23:03 조회6,704회 댓글0건첨부파일
본문
저는 라이더와 RTC, SD카드 리더기, LCD패널을 아두이노 메가에 연결하여, 거리측정기를 만드려고 하고 있습니다.
보드는 아두이노 메가, RTC는 ds3231, LCD패널은 1602, 라이더는 garmin lidar lite_v3 HP, sd카드 기록기는 SZH-EKBZ-005를 사용중입니다.
제가 원했던 것은, 순서대로,
1.라이더에서 측정값 50ms 단위로 빠르게 값들을 뽑아내기
->
2. LCD패널에 RTC를 이용하여 현재시각과 라이더가 측정한 측정값을 100ms 마다 리프레시하여 나타내기.
->
3. 해당 데이터 값들(현재시각, 라이더 거리 측정값)을 txt파일로 1초(1000ms) 단위로 기록하기.
였습니다.
라이더는 garmin lidar_lite v3 hp를 사용중입니다. 예제를 이용하여 짜집기하여 만들려고 하다보니, 형태가 굉장히 복잡하게 되었습니다.
사실 제가 필요한 것은 해당 예제에서 문자를 입력하여 여러 모드를 이용하는 것이 아닌, 오직 거리 데이터만 시간주기에 따라 뽑아오면 되는 것이기 때문에, 제 임의로 여러가지 시도를 하였고, 최대한 예제를 건들지 않으면서 제가 원하는 방향으로 바꿔서 사용하느라, 필요 없는 함수들도 많이 들어있는 것 같습니다..
혹시 더 간단하게 할 수 있는 방법이 있는지도 궁금합니다.. ㅠㅠ
또한, 원래는 delay함수를 사용하여 측정값들을 나타내었는데, 모든 값들이 전부 빠르게 실행되거나, 전체가 다 느리게 실행되거나 둘 중 하나였습니다.
그러나 라이더 거리값과 LCD패널에 표기되는 속도는 빠르게(100ms 정도), SD카드에 txt파일로 기록될때는 1초 단위(1000ms)로 서로 다른 시간주기를 두고 실행시키기 위해 여러가지 방법을 찾아보던 중에 milils함수를 알게 되어 적용을 하였는데, 구동이 잘 되지가 않았습니다..
너무 답답한 마음에 이렇게 글을 적습니다.. 혹시 어떤식으로 바꿔줘야할지 조금이라도 가이드만 주시면 정말 감사하겠습니다.. ㅠㅠ
또, 제가 가진 라이더 센서의 한계거리가 40m인데, 실제 측정을 해보면 40m 이상의 거리를 측정할 시에는 최댓값인 40m가 아닌 0m가 계속 표시됩니다. 혹시나 해당 소스코드에서 최대 거리값을 0이 아닌 40m(4000cm)로 바꿀 수 있는 방법이 있다면 알려주신다면 정말 감사하게 사용하겠습니다. 긴글 읽어주셔서 감사합니다..
제 소스코드를 첨부하겠습니다.
================================================================================================================
//Lidar용
#include <stdint.h>
#include <Wire.h>
#include <LIDARLite_v3HP.h>
//LCD용
#include <Wire.h>
#include <LiquidCrystal_I2C.h>
//SD카드용
#include <SPI.h>
#include <SD.h>
//RTC용
#include "RTClib.h"
LIDARLite_v3HP myLidarLite;
#define FAST_I2C
LiquidCrystal_I2C lcd(0x27,20,4);
RTC_DS3231 rtc;
char daysOfTheWeek[7][12] = {"Sunday", "Monday", "Tuesday", "Wednesday", "Thursday", "Friday", "Saturday"};
enum rangeType_T
{
RANGE_NONE,
RANGE_SINGLE,
RANGE_CONTINUOUS,
RANGE_TIMER
};
int chipSelect=53; //SD카드의 CS 연결선 : 53번
File myLidarData; // 저장할 파일 명
void setup(){
//Lidar용
// Initialize Arduino serial port (for display of ASCII output to PC)
Serial.begin(115200);
// Initialize Arduino I2C (for communication to LidarLite)
Wire.begin();
#ifdef FAST_I2C
#if ARDUINO >= 157
Wire.setClock(400000UL); // Set I2C frequency to 400kHz (for Arduino Due)
#else
TWBR = ((F_CPU / 400000UL) - 16) / 2; // Set I2C frequency to 400kHz
#endif
#endif
// Configure the LidarLite internal parameters so as to lend itself to
// various modes of operation by altering 'configure' input integer to
// anything in the range of 0 to 5. See LIDARLite_v3HP.cpp for details.
myLidarLite.configure(0);
//LCD용
//initialize the LCD
lcd.init();
lcd.backlight();
lcd.setCursor (1,0);
lcd.print("Initiating...");
lcd.setCursor (3,1);
lcd.print("Lidar!");
;
pinMode(53, OUTPUT); //Reserve pin10 SD.h가 핀 10에만 반응하니까 그냥 놔두기
SD.begin(chipSelect); //SD카드 시작
}
void loop(){
uint16_t distance;
uint8_t newDistance = 0;
uint8_t c;
rangeType_T rangeMode = RANGE_TIMER;
// Continuous loop
while (1)
{
// Each time through the loop, look for a serial input character
if (Serial.available() > 0)
{
// read input character ...
c = (uint8_t) Serial.read();
// ... and parse
switch (c)
{
case 'S':
case 's':
rangeMode = RANGE_SINGLE;
break;
case 'C':
case 'c':
rangeMode = RANGE_CONTINUOUS;
break;
case 'T':
case 't':
rangeMode = RANGE_TIMER;
break;
case '.':
rangeMode = RANGE_NONE;
break;
case 'D':
case 'd':
rangeMode = RANGE_NONE;
dumpCorrelationRecord();
break;
case 0x0D:
case 0x0A:
break;
default:
Serial.println("=====================================");
Serial.println("== Type a single character command ==");
Serial.println("=====================================");
Serial.println(" S - Single Measurement");
Serial.println(" C - Continuous Measurement");
Serial.println(" T - Timed Measurement");
Serial.println(" . - Stop Measurement");
Serial.println(" D - Dump Correlation Record");
break;
}
}
switch (rangeMode)
{
case RANGE_NONE:
newDistance = 0;
break;
case RANGE_SINGLE:
newDistance = distanceSingle(&distance);
break;
case RANGE_CONTINUOUS:
newDistance = distanceContinuous(&distance);
break;
case RANGE_TIMER:
delay(1000); // 4 Hz
newDistance = distanceFast(&distance);
break;
default:
newDistance = 0;
break;
}
// When there is new distance data, print it to the serial port
if (newDistance)
{
Serial.println("distance = ");
Serial.println(distance);
DateTime now = rtc.now();
myLidarData= SD.open("LDData.txt", FILE_WRITE); //open LDData.txt on the SD card as a file to write to
if (myLidarData) { //Only do these things if data file opened successfully SD카드가 정상적으로 열렸을 때 이런 작업 실행
\
Serial.print("Distance = ");
Serial.print(distance);
Serial.println("cm");
delay(50);
myLidarData.print("Date : ");
myLidarData.print(now.year(), DEC);
myLidarData.print("/");
myLidarData.print(now.month(), DEC);
myLidarData.print("/");
myLidarData.print(now.day(), DEC);
myLidarData.print(" . ");
myLidarData.print(daysOfTheWeek[now.dayOfTheWeek()]);
myLidarData.print(" . ");
myLidarData.print(now.hour(), DEC);
myLidarData.print(":");
myLidarData.print(now.minute(), DEC);
myLidarData.print(":");
myLidarData.print(now.second(), DEC);
myLidarData.print(" . ");
myLidarData.print("Distance : "); //write distance to the SD card
myLidarData.println(distance); //write distance to the SD card
myLidarData.close(); // close the file
delay(50);
lcd.clear();
lcd.setCursor(0,2);
lcd.print("Distance =");
lcd.setCursor(15,3);
lcd.print("cm");
lcd.setCursor( 10,3);
lcd.print(distance);
lcd.setCursor(1,0);
lcd.print("Date : ");
lcd.print(now.year(), DEC);
lcd.print('/');
lcd.print(now.month(), DEC);
lcd.print('/');
lcd.print(now.day(), DEC) ;
lcd.setCursor(5,1);
lcd.print(now.hour(), DEC);
lcd.print(':');
lcd.print(now.minute(), DEC);
lcd.print(':');
lcd.print(now.second(), DEC);
delay(50);
}
}
// Single measurements print once and then stop
if (rangeMode == RANGE_SINGLE)
{
rangeMode = RANGE_NONE;
}
}
}
uint8_t distanceSingle(uint16_t * distance)
{
// 1. Wait for busyFlag to indicate device is idle. This must be
// done before triggering a range measurement.
myLidarLite.waitForBusy();
// 2. Trigger range measurement.
myLidarLite.takeRange();
// 3. Wait for busyFlag to indicate device is idle. This should be
// done before reading the distance data that was triggered above.
myLidarLite.waitForBusy();
// 4. Read new distance data from device registers
*distance = myLidarLite.readDistance();
return 1;
}
uint8_t distanceContinuous(uint16_t * distance)
{
uint8_t newDistance = 0;
// Check on busyFlag to indicate if device is idle
// (meaning = it finished the previously triggered measurement)
if (myLidarLite.getBusyFlag() == 0)
{
// Trigger the next range measurement
myLidarLite.takeRange();
// Read new distance data from device registers
*distance = myLidarLite.readDistance();
// Report to calling function that we have new data
newDistance = 1;
}
return newDistance;
}
//---------------------------------------------------------------------
uint8_t distanceFast(uint16_t * distance)
{
// 1. Wait for busyFlag to indicate device is idle. This must be
// done before triggering a range measurement.
myLidarLite.waitForBusy();
// 2. Trigger range measurement.
myLidarLite.takeRange();
// 3. Read previous distance data from device registers.
// After starting a measurement we can immediately read previous
// distance measurement while the current range acquisition is
// ongoing. This distance data is valid until the next
// measurement finishes. The I2C transaction finishes before new
// distance measurement data is acquired.
*distance = myLidarLite.readDistance();
return 1;
}
void dumpCorrelationRecord()
{
myLidarLite.correlationRecordToSerial(256);
}
========================================================================================================
이러한 소스 코드를
==========================================================================================================
unsigned long t,t1,t2,t3;
//
void setup(){
t=t1=t2=t3=millis();
}
//
void loop(){
t=millis();
//
if(t-t1>=50){ t1=t; // 50ms
sensor1;
}
//
if(t-t2>=100){ t2=t; // 100ms
sensor2;
}
//
if(t-t3>=1000){ t3=t; // 1000ms
RTC;
sd card;
}
}
==========================================================================================================
이런 식으로 바꿔주면 가능하시다고 하는데, 저 예제 코드를 어떻게 뜯어서 이렇게 변경해야할지 감이 잡히지가 않습니다.. ㅠㅠ
댓글 0
조회수 6,704등록된 댓글이 없습니다.