Robofun 機器人論壇

標題: 想請問兩塊感應器的程式合併問題 (已解決) [打印本頁]

作者: 小新手    時間: 2017-12-28 18:58
標題: 想請問兩塊感應器的程式合併問題 (已解決)
本帖最後由 小新手 於 2017-12-29 20:45 編輯

我目前這裡有一個感應心跳後藍芽傳送的程式和gps定位的程序,我想將兩個結合在一起讓他可以同時運作,可是合併後,雖然心跳的部分沒有問題,藍芽也是都能順利連上手機並顯示心跳和GPS的訊息,不過gps部分總是一直沒收到訊號,可以請教各位大師我哪裡錯了嗎? (用心跳程序當基底將gps寫上去)
心跳採用pluse sensor 藍芽採用hc-05 gps採用neo-6m
因為有點長如果看不下去的話請點這裡下程式碼QAQ : https://drive.google.com/open?id ... z1L2kD7qXPZSihbP--H
原來的藍芽pluse sensor(pluse seror分成3個檔案了)


(心跳第一個PulseSensor_wt_BT.ino)
#include <SoftwareSerial.h>// import the serial library

SoftwareSerial Genotronex(10, 11); // RX, TX
int ledpin=12; // led on D13 will show blink on / off
int BluetoothData; // the data given from Computer

//  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.

// Regards Serial OutPut  -- Set This Up to your needs
static boolean serialVisual = true;   // Set to 'false' by Default.  Re-set to 'true' to see Arduino Serial Monitor ASCII Visual Pulse


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
   // UN-COMMENT THE NEXT LINE IF YOU ARE POWERING The Pulse Sensor AT LOW VOLTAGE,
   // AND APPLY THAT VOLTAGE TO THE A-REF PIN
//   analogReference(EXTERNAL);   
Genotronex.begin(9600);
  Genotronex.println("Bluetooth On please press 1 or 0 blink LED ..");
  pinMode(ledpin,OUTPUT);
}


//  Where the Magic Happens
void loop(){
  
    serialOutput() ;      
   
  if (QS == true){     //  A Heartbeat Was Found
                       // BPM and IBI have been Determined
                       // Quantified Self "QS" true when arduino finds a heartbeat
        digitalWrite(blinkPin,HIGH);     // Blink LED, we got a beat.
        fadeRate = 255;         // Makes the LED Fade Effect Happen
                                // Set 'fadeRate' Variable to 255 to fade LED with pulse
        serialOutputWhenBeatHappens();   // A Beat Happened, Output that to serial.     
        QS = false;                      // reset the Quantified Self flag for next time   
       }
      else {

      digitalWrite(blinkPin,LOW);            // There is not beat, turn off pin 13 LED
      }
     
   ledFadeToBeat();                      // Makes the LED Fade Effect Happen
  if (Genotronex.available()){
BluetoothData=Genotronex.read();
   if(BluetoothData=='1'){   // if number 1 pressed ....
   digitalWrite(ledpin,1);
   Genotronex.println("LED  On D12 ON ! ");
   }
  if (BluetoothData=='0'){// if number 0 pressed ....
  digitalWrite(ledpin,0);
   Genotronex.println("LED  On D12 Off ! ");
  }
}
  delay(20);                             //  take a break
}


心跳第二個(AllSerialHandling.ino)
void serialOutput(){   // Decide How To Output Serial.
if (serialVisual == true){  
     arduinoSerialMonitorVisual('-', Signal);   // goes to function that makes Serial Monitor Visualizer
} else{
      sendDataToSerial('S', Signal);     // goes to sendDataToSerial function
}        
}


//  Decides How To OutPut BPM and IBI Data
void serialOutputWhenBeatHappens(){   
if (serialVisual == true){            //  Code to Make the Serial Monitor Visualizer Work
    Serial.print("*** Heart-Beat Happened *** ");  //ASCII Art Madness
    Serial.print("BPM: ");
     Genotronex.println("HEART RATE IS  ");
      Genotronex.println(BPM);
    Serial.print(BPM);
    Serial.print("  ");
} else{
        sendDataToSerial('B',BPM);   // send heart rate with a 'B' prefix
        sendDataToSerial('Q',IBI);   // send time between beats with a 'Q' prefix
}   
}



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





void ledFadeToBeat(){
    fadeRate -= 15;                         //  set LED fade value
    fadeRate = constrain(fadeRate,0,255);   //  keep LED fade value from going into negative numbers!
    analogWrite(fadePin,fadeRate);          //  fade LED
  }


//  Code to Make the Serial Monitor Visualizer Work
void arduinoSerialMonitorVisual(char symbol, int data ){   
  const int sensorMin = 0;      // sensor minimum, discovered through experiment
const int sensorMax = 1024;    // sensor maximum, discovered through experiment

  int sensorReading = data;
  // map the sensor range to a range of 12 options:
  int range = map(sensorReading, sensorMin, sensorMax, 0, 11);

  // do something different depending on the
  // range value:
  switch (range) {
  case 0:     
    Serial.println("");     /////ASCII Art Madness
    break;
  case 1:   
    Serial.println("---");
    break;
  case 2:   
    Serial.println("------");
    break;
  case 3:   
    Serial.println("---------");
    break;
  case 4:   
    Serial.println("------------");
    break;
  case 5:   
    Serial.println("--------------|-");
    break;
  case 6:   
    Serial.println("--------------|---");
    break;
  case 7:   
    Serial.println("--------------|-------");
    break;
  case 8:  
    Serial.println("--------------|----------");
    break;
  case 9:   
    Serial.println("--------------|----------------");
    break;
  case 10:   
    Serial.println("--------------|-------------------");
    break;
  case 11:   
    Serial.println("--------------|-----------------------");
    break;
  
  }
}





作者: 小新手    時間: 2017-12-28 19:00
本帖最後由 小新手 於 2017-12-28 19:16 編輯

心跳第三個(Interrupt.ino)
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 = 525;                // used to find instant moment of heart beat, seeded
volatile int amp = 100;                   // 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(){     
  // 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      
}


// THIS IS THE TIMER 2 INTERRUPT SERVICE ROUTINE.
// Timer 2 makes sure that we take a reading every 2 miliseconds
ISR(TIMER2_COMPA_vect){                         // triggered when Timer2 counts to 124
  cli();                                      // disable interrupts while we do this
  Signal = analogRead(pulsePin);              // read the Pulse Sensor
  sampleCounter += 2;                         // keep track of the time in mS with this variable
  int N = sampleCounter - lastBeatTime;       // monitor the time since the last beat to avoid noise

    //  find the peak and trough of the pulse wave
  if(Signal < thresh && N > (IBI/5)*3){       // avoid dichrotic noise by waiting 3/5 of last IBI
    if (Signal < T){                        // T is the trough
      T = Signal;                         // keep track of lowest point in pulse wave
    }
  }

  if(Signal > thresh && Signal > P){          // thresh condition helps avoid noise
    P = Signal;                             // P is the peak
  }                                        // keep track of highest point in pulse wave

  //  NOW IT'S TIME TO LOOK FOR THE HEART BEAT
  // signal surges up in value every time there is a pulse
  if (N > 250){                                   // avoid high frequency noise
    if ( (Signal > thresh) && (Pulse == false) && (N > (IBI/5)*3) ){        
      Pulse = true;                               // set the Pulse flag when we think there is a pulse
//      digitalWrite(blinkPin,HIGH);                // turn on pin 13 LED
      IBI = sampleCounter - lastBeatTime;         // measure time between beats in mS
      lastBeatTime = sampleCounter;               // keep track of time for next pulse

      if(secondBeat){                        // if this is the second beat, if secondBeat == TRUE
        secondBeat = false;                  // clear secondBeat flag
        for(int i=0; i<=9; i++){             // seed the running total to get a realisitic BPM at startup
          rate = IBI;                     
        }
      }

      if(firstBeat){                         // if it's the first time we found a beat, if firstBeat == TRUE
        firstBeat = false;                   // clear firstBeat flag
        secondBeat = true;                   // set the second beat flag
        sei();                               // enable interrupts again
        return;                              // IBI value is unreliable so discard it
      }   


      // keep a running total of the last 10 IBI values
      word runningTotal = 0;                  // clear the runningTotal variable   

      for(int i=0; i<=8; i++){                // shift data in the rate array
        rate = rate[i+1];                  // and drop the oldest IBI value
        runningTotal += rate;              // add up the 9 oldest IBI values
      }

      rate[9] = IBI;                          // add the latest IBI to the rate array
      runningTotal += rate[9];                // add the latest IBI to runningTotal
      runningTotal /= 10;                     // average the last 10 IBI values
      BPM = 60000/runningTotal;               // how many beats can fit into a minute? that's BPM!
      QS = true;                              // set Quantified Self flag
      // QS FLAG IS NOT CLEARED INSIDE THIS ISR
    }                       
  }

  if (Signal < thresh && Pulse == true){   // when the values are going down, the beat is over
//    digitalWrite(blinkPin,LOW);            // turn off pin 13 LED
    Pulse = false;                         // reset the Pulse flag so we can do it again
    amp = P - T;                           // get amplitude of the pulse wave
    thresh = amp/2 + T;                    // set thresh at 50% of the amplitude
    P = thresh;                            // reset these for next time
    T = thresh;
  }

  if (N > 2500){                           // if 2.5 seconds go by without a beat
    thresh = 512;                          // set thresh default
    P = 512;                               // set P default
    T = 512;                               // set T default
    lastBeatTime = sampleCounter;          // bring the lastBeatTime up to date        
    firstBeat = true;                      // set these to avoid noise
    secondBeat = false;                    // when we get the heartbeat back
  }

  sei();                                   // enable interrupts when youre done!
}// end isr


GPS部分

#include <SoftwareSerial.h>
#include <TinyGPS.h>

SoftwareSerial mySerial(10, 11);
TinyGPS gps;

void gpsdump(TinyGPS &gps);
void printFloat(double f, int digits = 2);

void setup()  
{
  // Oploen serial communications and wait for port to open:
  Serial.begin(9600);
  // set the data rate for the SoftwareSerial port
  mySerial.begin(9600);
  delay(1000);
  Serial.println("uBlox Neo 6M");
  Serial.print("Testing TinyGPS library v. "); Serial.println(TinyGPS::library_version());
  Serial.println("by Mikal Hart");
  Serial.println();
  Serial.print("Sizeof(gpsobject) = ");
  Serial.println(sizeof(TinyGPS));
  Serial.println();
}

void loop() // run over and over
{
  bool newdata = false;
  unsigned long start = millis();
  // Every 5 seconds we print an update
  while (millis() - start < 5000)
  {
    if (mySerial.available())
   
    {
      char c = mySerial.read();
      //Serial.print(c);  // uncomment to see raw GPS data
      if (gps.encode(c))
      {
        newdata = true;
        break;  // uncomment to print new data immediately!
      }
    }
  }
  
  if (newdata)
  {
    Serial.println("Acquired Data");
    Serial.println("-------------");
    gpsdump(gps);
    Serial.println("-------------");
    Serial.println();
  }
  
}

void gpsdump(TinyGPS &gps)
{
  long lat, lon;
  float flat, flon;
  unsigned long age, date, time, chars;
  int year;
  byte month, day, hour, minute, second, hundredths;
  unsigned short sentences, failed;

  gps.get_position(&lat, &lon, &age);
  Serial.print("Lat/Long(10^-5 deg): "); Serial.print(lat); Serial.print(", "); Serial.print(lon);
  Serial.print(" Fix age: "); Serial.print(age); Serial.println("ms.");
  
  // On Arduino, GPS characters may be lost during lengthy Serial.print()
  // On Teensy, Serial prints to USB, which has large output buffering and
  //   runs very fast, so it's not necessary to worry about missing 4800
  //   baud GPS characters.

  gps.f_get_position(&flat, &flon, &age);
  Serial.print("Lat/Long(float): "); printFloat(flat, 5); Serial.print(", "); printFloat(flon, 5);
    Serial.print(" Fix age: "); Serial.print(age); Serial.println("ms.");

  gps.get_datetime(&date, &time, &age);
  Serial.print("Date(ddmmyy): "); Serial.print(date); Serial.print(" Time(hhmmsscc): ");
    Serial.print(time);
  Serial.print(" Fix age: "); Serial.print(age); Serial.println("ms.");

  gps.crack_datetime(&year, &month, &day, &hour, &minute, &second, &hundredths, &age);
  Serial.print("Date: "); Serial.print(static_cast<int>(month)); Serial.print("/");
    Serial.print(static_cast<int>(day)); Serial.print("/"); Serial.print(year);
  Serial.print("  Time: "); Serial.print(static_cast<int>(hour+8));  Serial.print(":"); //Serial.print("UTC +08:00 Malaysia");
    Serial.print(static_cast<int>(minute)); Serial.print(":"); Serial.print(static_cast<int>(second));
    Serial.print("."); Serial.print(static_cast<int>(hundredths)); Serial.print(" UTC +08:00 Malaysia");
  Serial.print("  Fix age: ");  Serial.print(age); Serial.println("ms.");
  Serial.print("Alt(cm): "); Serial.print(gps.altitude()); Serial.print(" Course(10^-2 deg): ");
    Serial.print(gps.course()); Serial.print(" Speed(10^-2 knots): "); Serial.println(gps.speed());
  Serial.print("Alt(float): "); printFloat(gps.f_altitude()); Serial.print(" Course(float): ");
    printFloat(gps.f_course()); Serial.println();
  Serial.print("Speed(knots): "); printFloat(gps.f_speed_knots()); Serial.print(" (mph): ");
    printFloat(gps.f_speed_mph());
  Serial.print(" (mps): "); printFloat(gps.f_speed_mps()); Serial.print(" (kmph): ");
    printFloat(gps.f_speed_kmph()); Serial.println();

  gps.stats(&chars, &sentences, &failed);
  Serial.print("Stats: characters: "); Serial.print(chars); Serial.print(" sentences: ");
    Serial.print(sentences); Serial.print(" failed checksum: "); Serial.println(failed);
}






作者: 小新手    時間: 2017-12-28 19:02
本帖最後由 小新手 於 2017-12-28 19:19 編輯

void printFloat(double number, int digits)
{
  // Handle negative numbers
  if (number < 0.0)
  {
     Serial.print('-');
     number = -number;
  }

  // Round correctly so that print(1.999, 2) prints as "2.00"
  double rounding = 0.5;
  for (uint8_t i=0; i<digits; ++i)
    rounding /= 10.0;
  
  number += rounding;

  // Extract the integer part of the number and print it
  unsigned long int_part = (unsigned long)number;
  double remainder = number - (double)int_part;
  Serial.print(int_part);

  // Print the decimal point, but only if there are digits beyond
  if (digits > 0)
    Serial.print(".");

  // Extract digits from the remainder one at a time
  while (digits-- > 0)
  {
    remainder *= 10.0;
    int toPrint = int(remainder);
    Serial.print(toPrint);
    remainder -= toPrint;
  }
}


接下來是以心跳藍芽為基底合併後的程式碼(INTERRUPPT的程式沒有變動,然後將Genotronex改為btSerial,myserial改為gpsSerial並錯開腳位))個人覺得是rxd txd的問題,不知道是不是,請問怎麼解決才好

合併後的第一個程式(PulseSensor_wt_BTGPS.ino)

#include <SoftwareSerial.h>// import the serial library
#include <TinyGPS.h>
SoftwareSerial gpsSerial(12, 11); // RX, TX(gps腳位)
int ledpin=15; // l在D13上導致將顯示閃爍開/關ed on D13 will show blink on / off
int BluetoothData; // 計算機給出的數據the data given from Computer

//  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;                 // 用於在fadePin上用PWM淡出LEDused to fade LED on with PWM on fadePin

// Volatile Variables, used in the interrupt service routine!
volatile int BPM;                   // int保持原始的模擬輸入0.每2毫秒更新一次int that holds raw Analog in 0. updated every 2mS
volatile int Signal;                // 保存傳入的原始數據holds the incoming raw data
volatile int IBI = 600;             // int保存節拍之間的時間間隔! 必須種子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;        // 當Arduoino發現一個節拍成為現實becomes true when Arduoino finds a beat.

// /關心串行輸出 - 設置這符合您的需求Regards Serial OutPut  -- Set This Up to your needs
static boolean serialVisual = false;   // 默認設置為“false”。 重新設置為“真”來查看Arduino串行監視器ASCII可視脈衝Set to 'false' by Default.  Re-set to 'true' to see Arduino Serial Monitor ASCII Visual Pulse

SoftwareSerial btSerial(10, 9); // RX, TX(藍芽角為)
TinyGPS gps;

void gpsdump(TinyGPS &gps);
void printFloat(double f, int digits = 2);
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!
                 // 設置每2mS讀脈衝傳感器信號sets up to read Pulse Sensor signal every 2mS
   // 如果您正在為低電壓脈衝傳感器供電,請聯繫下一行UN-COMMENT THE NEXT LINE IF YOU ARE POWERING The Pulse Sensor AT LOW VOLTAGE,
   // 並將該電壓應用於A-REF引腳AND APPLY THAT VOLTAGE TO THE A-REF PIN
//   analogReference(EXTERNAL);   
btSerial.begin(9600);
  btSerial.println("Bluetooth On please press 1 or 0 blink LED ..");
  pinMode(ledpin,OUTPUT);
  // Oploen串行通信並等待端口打開:Oploen serial communications and wait for port to open:
  Serial.begin(9600);
  // 設置SoftwareSerial端口的數據速率set the data rate for the SoftwareSerial port
  gpsSerial.begin(9600);
  btSerial.begin(9600);
  delay(1000);
  Serial.println("uBlox Neo 6M");
  Serial.print("Testing TinyGPS library v. "); Serial.println(TinyGPS::library_version());
  Serial.println("by Mikal Hart");
  Serial.println();
  Serial.print("Sizeof(gpsobject) = ");
  Serial.println(sizeof(TinyGPS));
  Serial.println();
  interruptSetup();  
  
  }


//  Where the Magic Happens
void loop(){
  
    serialOutput() ;      
   
  if (QS == true){     //  心跳被發現A Heartbeat Was Found
                       // BPM和IBI已經確定BPM and IBI have been Determined
                       // 當arduino發現心跳時,量化的自我Quantified Self "QS" true when arduino finds a heartbeat
        digitalWrite(blinkPin,HIGH);     // 閃爍LED,我們得到了一個節拍Blink LED, we got a beat.
        fadeRate = 255;         // 使LED淡化效果發生Makes the LED Fade Effect Happen
                                // 將“fadeRate”變量設置為255,使脈沖淡入Set 'fadeRate' Variable to 255 to fade LED with pulse
        serialOutputWhenBeatHappens();   // 發生一擊,輸出串行A Beat Happened, Output that to serial.     
        QS = false;                      // 重新設置下一次的量化自標記reset the Quantified Self flag for next time   
       }
      else {

      digitalWrite(blinkPin,LOW);            // 沒有拍子,關掉13號LED指示燈There is not beat, turn off pin 13 LED
      }
     
   ledFadeToBeat();                      // 使LED淡化效果發生Makes the LED Fade Effect Happen
  if (btSerial.available()){
BluetoothData=btSerial.read();
   if(BluetoothData=='1'){   // if number 1 pressed ....
   digitalWrite(ledpin,1);
   btSerial.println("LED  On D12 ON ! ");
   }
  if (BluetoothData=='0'){// if number 0 pressed ....
  digitalWrite(ledpin,0);
   btSerial.println("LED  On D12 Off ! ");
  }
}

  delay(2000);  //  take a break
    bool newdata = true;
  unsigned long start = millis();
  // Every 5 seconds we print an update
   while (millis() - start < 5000)
  {
    if (gpsSerial.available())
   
    {
      char c = gpsSerial.read();
      //Serial.print(c);  // 取消註釋查看原始GPS數據uncomment to see raw GPS data
      if (gps.encode(c))
      {
        newdata = true;
        break;  // 立即取消打印新數據的註釋!uncomment to print new data immediately!
      }
    }
  }
  if (newdata)
  {
    Serial.println("Acquired Data");
    Serial.println("-------------");
    gpsdump(gps);
    Serial.println("-------------");
    Serial.println();
  }  
}


作者: 小新手    時間: 2017-12-28 19:04
void serialOutput(){   // Decide How To Output Serial.
if (serialVisual == true){  
     arduinoSerialMonitorVisual('-', Signal);   // 去串行監視器展示台的功能goes to function that makes Serial Monitor Visualizer
} else{
      sendDataToSerial('S', Signal);     // 去sendDataToSerial函數goes to sendDataToSerial function
}        
}


// 決定如何輸出BPM和IBI數據Decides How To OutPut BPM and IBI Data
void serialOutputWhenBeatHappens(){   
if (serialVisual == true){            // 使串行監視器可視化工作的代碼 Code to Make the Serial Monitor Visualizer Work
    Serial.print("*** Heart-Beat Happened *** ");  //ASCII藝術瘋狂ASCII Art Madness
    Serial.print("BPM: ");
     btSerial.println("HEART RATE IS  ");
      btSerial.println(BPM);
    Serial.print(BPM);
    Serial.print("  ");
} else{
        sendDataToSerial('B',BPM);   // 用“B”前綴發送心率send heart rate with a 'B' prefix
        sendDataToSerial('Q',IBI);   // 用“Q”前綴在節拍之間發送時間send time between beats with a 'Q' prefix
}   
}



//  將數據發送到脈衝傳感器處理應用程序,本地Mac應用程序或第三方串行讀取器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);               
  }





void ledFadeToBeat(){
    fadeRate -= 15;                         //  設置LED淡入值set LED fade value
    fadeRate = constrain(fadeRate,0,255);   //  保持LED衰減價值進入負數keep LED fade value from going into negative numbers!
    analogWrite(fadePin,fadeRate);          //  淡入LEDfade LED
  }


//  Code to Make the Serial Monitor Visualizer Work
void arduinoSerialMonitorVisual(char symbol, int data ){   
  const int sensorMin = 0;      // 傳感器最小值,通過實驗發現sensor minimum, discovered through experiment
const int sensorMax = 1024;    // 傳感器最大值,通過實驗發現sensor maximum, discovered through experiment

  int sensorReading = data;
  // 將傳感器範圍映射到12個選項的範圍內map the sensor range to a range of 12 options:
  int range = map(sensorReading, sensorMin, sensorMax, 0, 11);

  // 做一些不同的取決於do something different depending on the
  // 範圍值range value:
  switch (range) {
  case 0:     
    Serial.println("");     /////ASCII Art Madness
    break;
  case 1:   
    Serial.println("---");
    break;
  case 2:   
    Serial.println("------");
    break;
  case 3:   
    Serial.println("---------");
    break;
  case 4:   
    Serial.println("------------");
    break;
  case 5:   
    Serial.println("--------------|-");
    break;
  case 6:   
    Serial.println("--------------|---");
    break;
  case 7:   
    Serial.println("--------------|-------");
    break;
  case 8:  
    Serial.println("--------------|----------");
    break;
  case 9:   
    Serial.println("--------------|----------------");
    break;
  case 10:   
    Serial.println("--------------|-------------------");
    break;
  case 11:   
    Serial.println("--------------|-----------------------");
    break;
  
  }
}
void printFloat(double number, int digits)
{
  // 處理負數Handle negative numbers
  if (number < 0.0)
  {
     Serial.print('-');
     number = -number;
  }

  // 圓形正確打印(1.999,2)打印為“2.00”Round correctly so that print(1.999, 2) prints as "2.00"
  double rounding = 0.5;
  for (uint8_t i=0; i<digits; ++i)
    rounding /= 10.0;
  
  number += rounding;

  // 提取數字的整數部分並打印出來Extract the integer part of the number and print it
  unsigned long int_part = (unsigned long)number;
  double remainder = number - (double)int_part;
  Serial.print(int_part);

  // 打印小數點,但只有在數字之外Print the decimal point, but only if there are digits beyond
  if (digits > 0)
    Serial.print(".");

  // 一次提取餘數中的數字Extract digits from the remainder one at a time
  while (digits-- > 0)
  {
    remainder *= 10.0;
    int toPrint = int(remainder);
    Serial.print(toPrint);
    remainder -= toPrint;
  }
}
void gpsdump(TinyGPS &gps)
{
  long lat, lon;
  float flat, flon;
  unsigned long age, date, time, chars;
  int year;
  byte month, day, hour, minute, second, hundredths;
  unsigned short sentences, failed;

  gps.get_position(&lat, &lon, &age);
  Serial.print("Lat/Long(10^-5 deg): "); Serial.print(lat); Serial.print(", "); Serial.print(lon);
  Serial.print(" Fix age: "); Serial.print(age); Serial.println("ms.");
  
  // 在Arduino上,在冗長的Serial.print()中可能會丟失GPS字符On Arduino, GPS characters may be lost during lengthy Serial.print()
  // 在Teensy上,串行打印到USB,它具有較大的輸出緩沖和On Teensy, Serial prints to USB, which has large output buffering and
  //   運行速度非常快,所以沒必要擔心丟失4800runs very fast, so it's not necessary to worry about missing 4800
  //   波特GPS字符。baud GPS characters.

  gps.f_get_position(&flat, &flon, &age);
  Serial.print("Lat/Long(float): "); printFloat(flat, 5); Serial.print(", "); printFloat(flon, 5);
    Serial.print(" Fix age: "); Serial.print(age); Serial.println("ms.");

  gps.get_datetime(&date, &time, &age);
  Serial.print("Date(ddmmyy): "); Serial.print(date); Serial.print(" Time(hhmmsscc): ");
    Serial.print(time);
  Serial.print(" Fix age: "); Serial.print(age); Serial.println("ms.");

  gps.crack_datetime(&year, &month, &day, &hour, &minute, &second, &hundredths, &age);
  Serial.print("Date: "); Serial.print(static_cast<int>(month)); Serial.print("/");
    Serial.print(static_cast<int>(day)); Serial.print("/"); Serial.print(year);
  Serial.print("  Time: "); Serial.print(static_cast<int>(hour+8));  Serial.print(":"); //Serial.print("UTC +08:00 Malaysia");
    Serial.print(static_cast<int>(minute)); Serial.print(":"); Serial.print(static_cast<int>(second));
    Serial.print("."); Serial.print(static_cast<int>(hundredths)); Serial.print(" UTC +08:00 Malaysia");
  Serial.print("  Fix age: ");  Serial.print(age); Serial.println("ms.");

  Serial.print("Alt(cm): "); Serial.print(gps.altitude()); Serial.print(" Course(10^-2 deg): ");
    Serial.print(gps.course()); Serial.print(" Speed(10^-2 knots): "); Serial.println(gps.speed());
  Serial.print("Alt(float): "); printFloat(gps.f_altitude()); Serial.print(" Course(float): ");
    printFloat(gps.f_course()); Serial.println();
  Serial.print("Speed(knots): "); printFloat(gps.f_speed_knots()); Serial.print(" (mph): ");
    printFloat(gps.f_speed_mph());
  Serial.print(" (mps): "); printFloat(gps.f_speed_mps()); Serial.print(" (kmph): ");
    printFloat(gps.f_speed_kmph()); Serial.println();

  gps.stats(&chars, &sentences, &failed);
  Serial.print("Stats: characters: "); Serial.print(chars); Serial.print(" sentences: ");
    Serial.print(sentences); Serial.print(" failed checksum: "); Serial.println(failed);
    btSerial.println("Date(ddmmyy): "); btSerial.println(date);
      btSerial.println(" Time(hhmmsscc): ");btSerial.println(time);
}


作者: 小新手    時間: 2017-12-28 19:07
以上就是合好後有問題的程式....對不起有點長,希望大神們可以幫忙找一下錯誤在哪,現在這樣只能測心跳,GPS沒訊號,改了好久還是找不到問題所在 (用的是UNO或是Leonardo)
作者: 超新手    時間: 2017-12-28 19:51
如果你是用 lenardo,
SoftwareSerial 的 RX 只能是以下接腳之一
8, 9, 10, 11, 14 (MISO), 15 (SCK), 16 (MOSI).
SoftwareSerial gpsSerial(12, 11); // RX, TX(gps腳位)
所以...程式對掉一下
接腳改一下試看看
作者: 超新手    時間: 2017-12-28 20:02
本帖最後由 超新手 於 2017-12-28 20:19 編輯

另一個限制是
如果使用了兩個以上(含)的 softwareserial
一次只能一個 RX 作用
所以在呼叫 .available() 之前
必須先呼叫 .listen()
這個使用上需要點技巧

建議是把 serial 拿來用
這個是硬體的,限制較少
尤其是 Leonardo ,直接改成 serial1 即可
作者: 小新手    時間: 2017-12-28 23:47
超新手 發表於 2017-12-28 20:02
另一個限制是
如果使用了兩個以上(含)的 softwareserial
一次只能一個 RX 作用

所以把Serial拿來用的意思是將SoftwareSerial gpsSerial(12, 11); // RX, TX(gps腳位)改為SoftwareSerial Serial1(1, 0); // RX, TX(gps腳位)嗎?
還是說SoftwareSerial gpsSerial(1 0)就行了嗎?(抱歉這樣問,對這個還不很熟悉)
因為晚上了不方便去屋外測試GPS,所以只好先問腳位的問題
作者: 超新手    時間: 2017-12-29 05:37
本帖最後由 超新手 於 2017-12-29 08:46 編輯

不是
如果你是用 Leonardo
1. 把SoftwareSerial gpsSerial(12, 11);這行拿掉
2. 把所有的 gpsSerial 改成 Serial1
3. 把 gps 接到 0 和 1
如果你是用 UNO
1.不改接腳
2.在 while(millis()-start <5000)加上 listen
gpsSerial.listen();
while(millis()-start <5000) {
.....
}
btSerial.listen();
但是uno 還是建議改用 serial ,然後 gps 接到 0和1
注意!!是 Serial, 和 Leonardo 不同
而且接到 0和1時,下載程式時可能先要拔 gps
否則不能下載

作者: 小新手    時間: 2017-12-29 09:12
本帖最後由 小新手 於 2017-12-29 09:16 編輯
超新手 發表於 2017-12-29 05:37
不是
如果你是用 Leonardo
1. 把SoftwareSerial gpsSerial(12, 11);這行拿掉


感謝超新手大大的幫助!!! 現在gps和心跳藍芽都能夠正常運行了!! 非常感謝QAQ





歡迎光臨 Robofun 機器人論壇 (https://robofun.net/forum/) Powered by Discuz! X3.2