질문게시판 > 소스파일

인기검색어 > 아두이노 센서 ATMEGA128

최신글 질문게시판 동영상강좌 가입하기

▼ BASIC4MCU 후원업체 신제품 정보 ▼

▲ BASIC4MCU 후원업체 신제품 정보 ▲

BASIC4MCU > 질문게시판

소스파일

페이지 정보

작성자 cucumber 작성일18-06-06 18:16 조회5,493회 댓글0건

본문

#include <SoftwareSerial.h>

#define BT_RXD 8

#define BT_TXD 7

SoftwareSerial bluetooth(BT_RXD,BT_TXD);

SoftwareSerial gps(11,12); //tx,rx를 각각의 핀에 연결

//

#include <OneWire.h>

int DS18S20_Pin=2; //온도센서를 2번 핀으로 연결

OneWire ds(DS18S20_Pin); //2번 핀과 연결되 OneWire 객체 생성

//

int red=11; //빨간색led를 11번 핀으로 연결

int blue=10; //파란색led를 10번 핀으로 연결

//

void setup(){

  pinMode(red,OUTPUT); pinMode(blue,OUTPUT);

  Serial.begin(9600);

  bluetooth.begin(9600);

  gps.begin(9600);

}

//

void loop(){

  if(gps.available()){ Serial.write(gps.read()); }

  //

  if(bluetooth.available()){ Serial.write(bluetooth.read()); }

  if(Serial.available()){ bluetooth.write(Serial.read()); }

  //

  float temperature=getTemp(); //온도 측정 후 변수에 저장

  Serial.println(temperature);

  if(temperature<24){ digitalWrite(red,LOW); digitalWrite(blue,HIGH); delay(100); } //온도가 24도 이하일 때,파란색 LED 점등

  else{ digitalWrite(red,HIGH); digitalWrite(blue,LOW); delay(100); } //온도가 24도 이상일 때,빨간색 LED 점등

}

//

float getTemp(){ //온도 측정 후 반환하는 함수

  byte data[12];

  byte addr[8];

  if(!ds.search(addr)){ ds.reset_search(); return-1000; }

  if(OneWire:: crc8(addr,7)!=addr[7]){ Serial.println("CRC is not valid!"); return-1000; }

  if(addr[0]!=0x10&&addr[0]!=0x28){ Serial.print("Device is not recognized"); return-1000; }

  ds.reset();

  ds.select(addr);

  ds.write(0x44,1);

  byte present=ds.reset();

  ds.select(addr);

  ds.write(0xBE);

  for(int i=0; i<9; i++){ data[i]=ds.read(); }

  ds.reset_search();

  byte MSB=data[1]; byte LSB=data[0];

  float tempRead=((MSB<<8)|LSB);

  float TemperatureSum=tempRead/16;

  return TemperatureSum;

 

--------------------------------------------------------------------------------------------------------------------

심장박동센서1

------------------------


/*  Pulse Sensor Amped 1.5    by Joel Murphy and Yury Gitman   http://www.pulsesensor.com

----------------------  Notes ----------------------  ----------------------
This code:
1) Blinks an LED to User's Live Heartbeat   PIN 13
2) Fades an LED to User's Live HeartBeat    PIN 5
3) Determines BPM
4) Prints All of the Above to Serial

Read Me:
https://github.com/WorldFamousElectronics/PulseSensor_Amped_Arduino/blob/master/README.md
 ----------------------       ----------------------  ----------------------
*/

#define PROCESSING_VISUALIZER 1
#define SERIAL_PLOTTER  2

//  Variables
int pulsePin = 0;                 // Pulse Sensor purple wire connected to analog pin 0
int blinkPin = 13;                // pin to blink led at each beat
int fadePin = 5;                  // pin to do fancy classy fading blink at each beat
int fadeRate = 0;                 // used to fade LED on with PWM on fadePin

// Volatile Variables, used in the interrupt service routine!
volatile int BPM;                   // int that holds raw Analog in 0. updated every 2mS
volatile int Signal;                // holds the incoming raw data
volatile int IBI = 600;             // int that holds the time interval between beats! Must be seeded!
volatile boolean Pulse = false;     // "True" when User's live heartbeat is detected. "False" when not a "live beat".
volatile boolean QS = false;        // becomes true when Arduoino finds a beat.

// SET THE SERIAL OUTPUT TYPE TO YOUR NEEDS
// PROCESSING_VISUALIZER works with Pulse Sensor Processing Visualizer
//      https://github.com/WorldFamousElectronics/PulseSensor_Amped_Processing_Visualizer
// SERIAL_PLOTTER outputs sensor data for viewing with the Arduino Serial Plotter
//      run the Serial Plotter at 115200 baud: Tools/Serial Plotter or Command+L
static int outputType = SERIAL_PLOTTER;


void setup(){
  pinMode(blinkPin,OUTPUT);         // pin that will blink to your heartbeat!
  pinMode(fadePin,OUTPUT);          // pin that will fade to your heartbeat!
  Serial.begin(115200);             // we agree to talk fast!
  interruptSetup();                 // sets up to read Pulse Sensor signal every 2mS
   // IF YOU ARE POWERING The Pulse Sensor AT VOLTAGE LESS THAN THE BOARD VOLTAGE,
   // UN-COMMENT THE NEXT LINE AND APPLY THAT VOLTAGE TO THE A-REF PIN
//   analogReference(EXTERNAL);
}

 

--------------------------------------------------------------------------------------------------------------------

심장박동센서2

---------------------


//////////
/////////  All Serial Handling Code,
/////////  It's Changeable with the 'outputType' variable
/////////  It's declared at start of code.
/////////

void serialOutput(){   // Decide How To Output Serial.
  switch(outputType){
    case PROCESSING_VISUALIZER:
      sendDataToSerial('S', Signal);     // goes to sendDataToSerial function
      break;
    case SERIAL_PLOTTER:  // open the Arduino Serial Plotter to visualize these data
      Serial.print(BPM);
      Serial.print(",");
      Serial.print(IBI);
      Serial.print(",");
      Serial.println(Signal);
      break;
    default:
      break;
  }

}

//  Decides How To OutPut BPM and IBI Data
void serialOutputWhenBeatHappens(){
  switch(outputType){
    case PROCESSING_VISUALIZER:    // find it here https://github.com/WorldFamousElectronics/PulseSensor_Amped_Processing_Visualizer
      sendDataToSerial('B',BPM);   // send heart rate with a 'B' prefix
      sendDataToSerial('Q',IBI);   // send time between beats with a 'Q' prefix
      break;

    default:
      break;
  }
}

//  Sends Data to Pulse Sensor Processing App, Native Mac App, or Third-party Serial Readers.
void sendDataToSerial(char symbol, int data ){
    Serial.print(symbol);
    Serial.println(data);
  }

 

--------------------------------------------------------------------------------------------------------------------

심장박동센서3

------------------------

 

 


volatile int rate[10];                    // array to hold last ten IBI values
volatile unsigned long sampleCounter = 0;          // used to determine pulse timing
volatile unsigned long lastBeatTime = 0;           // used to find IBI
volatile int P =512;                      // used to find peak in pulse wave, seeded
volatile int T = 512;                     // used to find trough in pulse wave, seeded
volatile int thresh = 530;                // used to find instant moment of heart beat, seeded
volatile int amp = 0;                   // used to hold amplitude of pulse waveform, seeded
volatile boolean firstBeat = true;        // used to seed rate array so we startup with reasonable BPM
volatile boolean secondBeat = false;      // used to seed rate array so we startup with reasonable BPM


void interruptSetup(){  // CHECK OUT THE Timer_Interrupt_Notes TAB FOR MORE ON INTERRUPTS
  // Initializes Timer2 to throw an interrupt every 2mS.
  TCCR2A = 0x02;     // DISABLE PWM ON DIGITAL PINS 3 AND 11, AND GO INTO CTC MODE
  TCCR2B = 0x06;     // DON'T FORCE COMPARE, 256 PRESCALER
  OCR2A = 0X7C;      // SET THE TOP OF THE COUNT TO 124 FOR 500Hz SAMPLE RATE
  TIMSK2 = 0x02;     // ENABLE INTERRUPT ON MATCH BETWEEN TIMER2 AND OCR2A
  sei();             // MAKE SURE GLOBAL INTERRUPTS ARE ENABLED
}

 

--------------------------------------------------------------------------------------------------------------------

심장박동센서4

---------------------

 

/*
  These notes put together by Joel Murphy for Pulse Sensor Amped, 2015
  The code that this section is attached to uses a timer interrupt
  to sample the Pulse Sensor with consistent and regular timing.
  The code is setup to read Pulse Sensor signal at 500Hz (every 2mS).
  The reasoning for this can be found here:
  http://pulsesensor.com/pages/pulse-sensor-amped-arduino-v1dot1

  There are issues with using different timers to control the Pulse Sensor sample rate.
  Sometimes, user will need to switch timers for access to other code libraries.
  Also, some other hardware may have different timer setup requirements. This page
  will cover those different needs and reveal the necessary settings. There are two
  part of the code that will be discussed. The interruptSetup() routine, and
  the interrupt function call. Depending on your needs, or the Arduino variant that you use,
  check below for the correct settings.


  ******************************************************************************************
  ARDUINO UNO, Pro 328-5V/16MHZ, Pro-Mini 328-5V/16MHz (or any board with ATmega328P running at 16MHz)

 >> Timer2

    Pulse Sensor Arduino UNO uses Timer2 by default.
    Use of Timer2 interferes with PWM on pins 3 and 11.
    There is also a conflict with the Tone library, so if you want tones, use Timer1 below.

      void interruptSetup(){
        // Initializes Timer2 to throw an interrupt every 2mS.
        TCCR2A = 0x02;     // DISABLE PWM ON DIGITAL PINS 3 AND 11, AND GO INTO CTC MODE
        TCCR2B = 0x06;     // DON'T FORCE COMPARE, 256 PRESCALER
        OCR2A = 0X7C;      // SET THE TOP OF THE COUNT TO 124 FOR 500Hz SAMPLE RATE
        TIMSK2 = 0x02;     // ENABLE INTERRUPT ON MATCH BETWEEN TIMER2 AND OCR2A
        sei();             // MAKE SURE GLOBAL INTERRUPTS ARE ENABLED
      }

    use the following interrupt vector with Timer2

      ISR(TIMER2_COMPA_vect)

 >> Timer1

    Use of Timer1 interferes with PWM on pins 9 and 10.
    The Servo library also uses Timer1, so if you want servos, use Timer2 above.

      void interruptSetup(){
        // Initializes Timer1 to throw an interrupt every 2mS.
        TCCR1A = 0x00; // DISABLE OUTPUTS AND PWM ON DIGITAL PINS 9 & 10
        TCCR1B = 0x11; // GO INTO 'PHASE AND FREQUENCY CORRECT' MODE, NO PRESCALER
        TCCR1C = 0x00; // DON'T FORCE COMPARE
        TIMSK1 = 0x01; // ENABLE OVERFLOW INTERRUPT (TOIE1)
        ICR1 = 16000;  // TRIGGER TIMER INTERRUPT EVERY 2mS
        sei();         // MAKE SURE GLOBAL INTERRUPTS ARE ENABLED
      }

    Use the following ISR vector for the Timer1 setup above

      ISR(TIMER1_OVF_vect)

 >> Timer0

    DON'T USE TIMER0! Timer0 is used for counting delay(), millis(), and micros().
                      MESSING WITH Timer0 IS HIGHLY UNADVISED!

  ******************************************************************************************
  ARDUINO Fio, Lilypad, ProMini328-3V/8MHz (or any board with ATmega328P running at 8MHz)

  >> Timer2

    Pulse Sensor Arduino UNO uses Timer2 by default.
    Use of Timer2 interferes with PWM on pins 3 and 11.
    There is also a conflict with the Tone library, so if you want tones, use Timer1 below.

      void interruptSetup(){
        // Initializes Timer2 to throw an interrupt every 2mS.
        TCCR2A = 0x02;     // DISABLE PWM ON DIGITAL PINS 3 AND 11, AND GO INTO CTC MODE
        TCCR2B = 0x05;     // DON'T FORCE COMPARE, 128 PRESCALER
        OCR2A = 0X7C;      // SET THE TOP OF THE COUNT TO 124 FOR 500Hz SAMPLE RATE
        TIMSK2 = 0x02;     // ENABLE INTERRUPT ON MATCH BETWEEN TIMER2 AND OCR2A
        sei();             // MAKE SURE GLOBAL INTERRUPTS ARE ENABLED
      }

    use the following interrupt vector with Timer2

      ISR(TIMER2_COMPA_vect)

 >> Timer1

    Use of Timer1 interferes with PWM on pins 9 and 10.
    The Servo library also uses Timer1, so if you want servos, use Timer2 above.

      void interruptSetup(){
        // Initializes Timer1 to throw an interrupt every 2mS.
        TCCR1A = 0x00; // DISABLE OUTPUTS AND PWM ON DIGITAL PINS 9 & 10
        TCCR1B = 0x11; // GO INTO 'PHASE AND FREQUENCY CORRECT' MODE, NO PRESCALER
        TCCR1C = 0x00; // DON'T FORCE COMPARE
        TIMSK1 = 0x01; // ENABLE OVERFLOW INTERRUPT (TOIE1)
        ICR1 = 8000;  // TRIGGER TIMER INTERRUPT EVERY 2mS
        sei();         // MAKE SURE GLOBAL INTERRUPTS ARE ENABLED
      }

    Use the following ISR vector for the Timer1 setup above

      ISR(TIMER1_OVF_vect)

 >> Timer0

    DON'T USE TIMER0! Timer0 is used for counting delay(), millis(), and micros().
                      MESSING WITH Timer0 IS HIGHLY UNADVISED!


  ******************************************************************************************
  ARDUINO Leonardo (or any board with ATmega32u4 running at 16MHz)

  >> Timer1

    Use of Timer1 interferes with PWM on pins 9 and 10.

      void interruptSetup(){
          TCCR1A = 0x00;
          TCCR1B = 0x0C; // prescaler = 256
          OCR1A = 0x7C;  // count to 124
          TIMSK1 = 0x02;
          sei();
      }

  The only other thing you will need is the correct ISR vector in the next step.

      ISR(TIMER1_COMPA_vect)


  ******************************************************************************************
  ADAFRUIT Flora, ARDUINO Fio v3 (or any other board with ATmega32u4 running at 8MHz)

  >> Timer1

    Use of Timer1 interferes with PWM on pins 9 and 10.

      void interruptSetup(){
          TCCR1A = 0x00;
          TCCR1B = 0x0C; // prescaler = 256
          OCR1A = 0x3E;  // count to 62
          TIMSK1 = 0x02;
          sei();
      }

  The only other thing you will need is the correct ISR vector in the next step.

      ISR(TIMER1_COMPA_vect)
  ******************************************************************************************
  ADAFRUIT Gemma, ADAFRUIT Trinket 8MHz, Digispark Pro 8MHz, (or any other board with ATtiny85 running at 8MHz)

    NOTE: Gemma does not do serial communication! Comment out or remove the Serial code in the Arduino sketch!
   
    NOTE: You must use Software Serial with the Trinket or Digispark!
          A the top of the main code page put these lines
         
            #define rxPin 3
            #define txPin 4
            SoftwareSerial uart(rxPin, txPin);

          Then, whenever the word 'Serial' is used, replace it with 'uart'
            example:
              change Serial.begin(115200); to uart.begin(57600);
           
    NOTE: Use pin 2 to connect the Pulse Sensor Purple Pin on Trinket and Gemma!

  Timer1

    Use of Timer1 breaks PWM output on pin D1

      void interruptSetup(){
        TCCR1 = 0x88;      // Clear Timer on Compare, Set Prescaler to 128 TEST VALUE
        GTCCR &= 0x81;     // Disable PWM, don't connect pins to events
        OCR1C = 0x7C;      // Set the top of the count to  124 TEST VALUE
        OCR1A = 0x7C;      // Set the timer to interrupt after counting to TEST VALUE
        bitSet(TIMSK,6);   // Enable interrupt on match between TCNT1 and OCR1A
        sei();             // Enable global interrupts
      }
    The only other thing you will need is the correct ISR vector in the next step.

      ISR(TIMER1_COMPA_vect)

  ******************************************************************************************
  ADAFRUIT Trinket with 16MHz software setting, Digispark Pro 16MHz, (or any other board with ATtiny85 running at 16MHz)

    NOTE: Use analog pin 2 for the Pulse Sensor purple wire.
   
    NOTE: You must use Software Serial with the Trinket or Digispark!
          A the top of the main code page put these lines
         
            #define rxPin 3
            #define txPin 4
            SoftwareSerial uart(rxPin, txPin);

          Then, whenever the word 'Serial' is used, replace it with 'uart'
            example:
              change Serial.begin(115200); to uart.begin(57600);

  Timer1

    Use of Timer1 breaks PWM output on pin D1

      void interruptSetup(){
        TCCR1 = 0x89;      // Clear Timer on Compare, Set Prescaler to 256
        GTCCR &= 0x81;     // Disable PWM, don't connect pins to events
        OCR1C = 0x7C;      // Set the top of the count to  124
        OCR1A = 0x7C;      // Set the timer to interrupt after counting to 124
        bitSet(TIMSK,6);   // Enable interrupt on match between TCNT1 and OCR1A
        sei();             // Enable global interrupts
      }
    The only other thing you will need is the correct ISR vector in the next step.

      ISR(TIMER1_COMPA_vect)
     
  ******************************************************************************************

  IF YOU DON'T SEE THE MICROCONTROLLER YOU ARE USING, BUT YOU WANT A QUICK AND DIRTY SOLUTION

  So many new micros are coming out that it's kind of mind boggling. We will add to this list with
  code that uses interupts when we can, but if your micro is not listed here, and you are not willing
  or able to grab a hardware timer yourself, here is a shortcut that will work.
  It won't have the tight timing of a hardware interrupt, but it just might be good enough.
  We are calling this the 'Software Interrupt' version.
  The code below will set up a microsecond timer and 'trigger' every 2mS (or so).
 
  FIRST:
  You will need to change the name of the funcion in the Interrupts tab from
  'ISR(TIMER2_COMPA_vect)'
  to
  'void getPulse()'
 
  THEN:
  Comment out the entire interruptSetup() function in the interrupts tab in order for this to work.
 
  USE:
  The code example below. Notice that we are using the micros() and the millis() to time the sample rate and the fade rate.
  DO NOT put any delays in the loop, or it will break the sample timing!

  Happy Hacking!

 

  // FIRST, CREATE VARIABLES TO PERFORM THE SAMPLE TIMING AND LED FADE FUNCTIONS
  unsigned long lastTime; // used to time the Pulse Sensor samples
  unsigned long thisTime; // used to time the Pulse Sensor samples
  unsigned long fadeTime; // used to time the LED fade
 
  void setup(){
    pinMode(blinkPin,OUTPUT);         // pin that will blink to your heartbeat!
    pinMode(fadePin,OUTPUT);          // pin that will fade to your heartbeat!
    Serial.begin(115200);             // we agree to talk fast!
    // ADD THIS LINE IN PLACE OF THE interruptSetup() CALL
    lastTime = micros();              // get the time so we can create a software 'interrupt'
    // IF YOU ARE POWERING The Pulse Sensor AT VOLTAGE LESS THAN THE BOARD VOLTAGE,
    // UN-COMMENT THE NEXT LINE AND APPLY THAT VOLTAGE TO THE A-REF PIN
    //   analogReference(EXTERNAL);
  } //end of setup()

  //IN THE LOOP, ADD THE CODE THAT WILL DO THE 2mS TIMING, AND CALL THE getPulse() FUNCTION.
  void loop(){

    serialOutput() ;

    thisTime = micros();            // GET THE CURRENT TIME
    if(thisTime - lastTime > 2000){ // CHECK TO SEE IF 2mS HAS PASSED
      lastTime = thisTime;          // KEEP TRACK FOR NEXT TIME
      getPulse();                   //CHANGE 'ISR(TIMER2_COMPA_vect)' TO 'getPulse()' IN THE INTERRUPTS TAB!
    }

  if (QS == true){     // A Heartbeat Was Found
                       // BPM and IBI have been Determined
                       // Quantified Self "QS" true when arduino finds a heartbeat
        fadeRate = 255;         // Makes the LED Fade Effect Happen
                                // Set 'fadeRate' Variable to 255 to fade LED with pulse
        fadeTime = millis();    // Set the fade timer to fade the LED
        serialOutputWhenBeatHappens();   // A Beat Happened, Output that to serial.
        QS = false;                      // reset the Quantified Self flag for next time
  }
 
  if(millis() - fadeTime > 20){
    fadeTime = millis();
    ledFadeToBeat();                      // Makes the LED Fade Effect Happen
    }
   
} // end of loop

 

 

 

 

 

 

 

맨 위에 코드랑 심장박동센서코드랑 합쳐주세요.

LCD기능은 없애버리고 측정만 할 수 있게 해주세요.

 

  • BASIC4MCU 작성글 SNS에 공유하기
  • 페이스북으로 보내기
  • 트위터로 보내기
  • 구글플러스로 보내기
  • 카카오톡으로 보내기

댓글 : 0

조회수 : 5,493

등록된 댓글이 없습니다.

게시물 검색

BASIC4MCU > 질문게시판 목록

제목 날짜
공지 MCU, AVR, 아두이노 등 전자공학에 관련된 질문은… 스태프  19-01-15
공지 사이트 이용 안내 댓글[25] master  17-10-29
질문 아두이노 센서값 출력 질문입니다! 아궁2 새글 22-06-24
질문 ATmega128, ATmega28 RS232통신 첨부파일Moon4201 새글 22-06-24
질문 서보모터, 온습도센서 코드 질문 댓글[2] 첨부파일kshdlfaldfh  22-06-22
답변 답변 : 서보모터, 온습도센서 코드 질문 댓글[15] master  22-06-22
질문 steppermulti5 질문 응애  22-06-21
답변 답변 : steppermulti5 질문 댓글[1] master  22-06-22
질문 atmega128 avr usart 질문 snoflak  22-06-21
답변 답변 : atmega128 avr usart 질문 댓글[5] master  22-06-21
질문 사용자 정의 함수 변환 하는 방법 댓글[2] 첨부파일da0800  22-06-21
질문 atmega128 댓글[1] 양의노래  22-06-20
질문 아두이노 동시동작 재질문 댓글[9] 첨부파일죠르디  22-06-20
질문 초음파센서로 dc모터 제어하기 댓글[1] 첨부파일난쟁2  22-06-20
질문 아두이노 동시동작 댓글[7] 죠르디  22-06-19
질문 ATMEGA128 UART,FND 연동 질문 JMOD  22-06-19
답변 답변 : ATMEGA128 UART,FND 연동 질문 댓글[1] master  22-06-20
질문 atmeg128 질문이요 댓글[1] 첨부파일공대생er  22-06-18
질문 atmega128 초음파 센서로 신호등 시간초 늘리기 서동씨  22-06-18
답변 답변 : atmega128 초음파 센서로 신호등 시간초… 댓글[1] master  22-06-18
질문 atmega128 댓글[2] 망경이  22-06-18
질문 앱인벤터 이용해서 수동 자동 할라고하는데 ..잘안됩니다… 댓글[1] 따랑해영  22-06-18
답변 질문 : 앱인벤터 이용해서 수동 자동 할라고하는데 ..… 댓글[1] 첨부파일따랑해영  22-06-19
답변 질문 : 앱인벤터 이용해서 수동 자동 할라고하는데 .… 첨부파일따랑해영  22-06-19
질문 서보모터와 초음파센서 댓글[1] 브링미히어  22-06-17
질문 LCD 도와주세요 ㅜㅠㅠㅠ 댓글[2] 첨부파일dentist22  22-06-17
질문 안녕하세요 atmega128 질문드리고 싶습니다. (자… 댓글[3] dlcldl  22-06-17
질문 아두이노 delay를 millis로 바꾸고 싶습니다. 슨슨슨모  22-06-16
답변 답변 : 아두이노 delay를 millis로 바꾸고 싶… master  22-06-17
질문 아두이노 LCD 시계 첨부파일dentist22  22-06-16
게시물 검색


Privacy Policy
MCU BASIC ⓒ 2017
PC버전