|
3#
樓主 |
發表於 2018-4-12 10:12:37
|
只看該作者
這是我兩段完整的程式碼
能請超新手大大幫我看一下麻
我是把led改成繼電器
謝謝!!
#include <SoftwareSerial.h>
#include <Wire.h>
#include "SparkFunHTU21D.h"
SoftwareSerial I2CBT(10,11); // TX:10, RX:11
byte serialA;
HTU21D myHumidity;
int raley =8;
void setup(){
pinMode(raley,OUTPUT);
Serial.begin(9600);
I2CBT.begin(9600);
myHumidity.begin();
}
void loop (){
//溫溼度
serialA=I2CBT.read();
int temp = myHumidity.readTemperature();
int humd = myHumidity.readHumidity();
Serial.print("Temperature:");
Serial.print(temp, 1);
Serial.print("C");
Serial.print(" Humidity:");
Serial.print(humd, 1);
Serial.println("%");
//溫溼度數值透過藍芽傳送到app
byte Data[3];
byte Data1[3];
byte cmmd[20];
int insize;
Data[0]='a';
Data[1]=temp/256;
Data[2]=temp%256;
Data1[0]='b';
Data1[1]=humd/256;
Data1[2]=humd%256;
Serial.print(temp);
Serial.print(" , ");
Serial.println(humd);
delay(1000);
if (serialA == 1){
for(int j=0;j<3;j++)
I2CBT.write(Data[j]);
serialA=0;
}
if (serialA == 2){
for(int j=0;j<3;j++)
I2CBT.write(Data1[j]);
serialA=0;
}
//空氣
while(Serial.available()){
CopeSerialData(Serial.read());
}
}
char CopeSerialData(unsigned char ucData){
static unsigned char ucRxBuffer[250];
static unsigned char ucRxCnt = 0;
long pmat25=0,pmat100=0;
long pmcount03=0,pmcount05=0,pmcount10=0;
long pmcount25=0,pmcount50=0,pmcount100=0;
ucRxBuffer[ucRxCnt++]=ucData;
if(ucRxBuffer[0]!=0x42&&ucRxBuffer[1]!=0x4D){
ucRxCnt=0;
return ucRxCnt;
}
if (ucRxCnt<24){
return ucRxCnt;
}
else{
// G3
pmat25=(int)ucRxBuffer[12]*256+(int)ucRxBuffer[13]; Serial.print("PM2.5:"); Serial.print(pmat25); Serial.print(" ");
pmat100=(int)ucRxBuffer[14]*256+(int)ucRxBuffer[15]; Serial.print("PM10:"); Serial.print(pmat100); Serial.println(" ");
ucRxCnt=0;
}
//空氣數值透過藍芽傳送到app
byte Data2[3];
byte Data3[3];
Data2[0]='c';
Data2[1]=pmat25/256;
Data2[2]=pmat25%256;
Data3[0]='d';
Data3[1]=pmat100/256;
Data3[2]=pmat100%256;
Serial.print(pmat25);
Serial.print(" , ");
Serial.println(pmat100);
if (serialA == 3){
for(int j=0;j<3;j++)
I2CBT.write(Data2[j]);
serialA=0;
}
if (serialA == 4){
for(int j=0;j<3;j++)
I2CBT.write(Data3[j]);
serialA=0;
}
return ucRxCnt;
delay(10000);
}
==========================================================
#include <SoftwareSerial.h>
#include <Wire.h>
int raley =8;
SoftwareSerial I2CBT(10,11);
void setup() {
Serial.begin(9600);
I2CBT.begin(9600);//bluetooth baud rate
pinMode(raley,OUTPUT);
}
///////////////////main///////////////////////////
void loop() {
byte cmmd[20];
int insize;
while(1){
/*
read message from bluetooth
*/
if ((insize=(I2CBT.available()))>0){
for (int i=0; i<insize; i++){
Serial.print(cmmd=char(I2CBT.read()));
Serial.print("\n");
}
}
switch (cmmd[0]) {
case 97: //"a"
digitalWrite(raley,HIGH);
break;
case 98://"b"
digitalWrite(raley,LOW);
break;
} //Switch
} //while
} |
|