|
本帖最後由 leo0983405269 於 2017-11-10 15:40 編輯
我主要還是要做 超音波跟溫溼度感應的功能 所以是下面這邊
#include <SoftwareSerial.h> //Arduino I2C library
#include "DHT.h"
#define DHTPIN A1
#define DHTTYPE DHT11 // DHT 11
const int trig = 8; //define Arduino pin
const int echo = 7;
const int TX = 1;
const int RX = 0;
const int delay_time = 400; //delay 1000 ms for every measurment
const int Motor_E2 = 11;
const int Motor_E1 = 10;
const int Motor_M1 = 12;
const int Motor_M2 = 13;
char val; // variable to receive data from the serial port(bluetooth)
DHT dht(DHTPIN, DHTTYPE);
void setup()
{
Serial.begin(9600); //set baud rate of Bluetooth
pinMode(Motor_M1, OUTPUT);
pinMode(Motor_M2, OUTPUT);
pinMode(trig, OUTPUT); //set trigger pin to OUTPUT (-> pin trig of Ultrasonic Sensor)
pinMode(echo, INPUT); //set echo pin to INPUT (-> pin echo of Ultrasonic Sensor)
dht.begin();
}
void loop()
{
byte Data[9];
byte cmmd[20];
int insize;
float duration;
float distance;
digitalWrite(trig, HIGH); //trigger sona for 1 ms
delayMicroseconds(1000);
digitalWrite(trig, LOW);
duration = pulseIn(echo, HIGH);
distance = (duration / 2) * 0.034;
int x = (int) (distance * 100); //times 100 and convert disance to integer
//float y = dht.readHumidity();
//float t = dht.readTemperature();
int y = dht.readHumidity();
int z = dht.readTemperature();
Data[0]=97;
Data[1]=x/256;
Data[2]=x%256;
Data[3]='b' ;
Data[4]=y/256;
Data[5]=y%256;
Data[6]='c' ;
Data[7]=z/256;
Data[8]=z%256;
delay(200);
if(Serial.available()>0)
{
val = Serial.read();
switch(val)
{
case 97: //測距離
for(int i = 0; i < 9; i++)
Serial.write(Data[ i]); //send Data to phone
break;
case 'f': // car forward
forward(0, 255);
break;
case 'd': // car backward
backward(0, 255);
break;
case 'l': // car turn left
left(0, 255);
break;
case 'r': // car turn right
right(0, 255);
break;
case 's': // car stop
motorstop(0, 0);
break;
}
}
}
void motorstop(byte flag, byte motorspeed)
{
digitalWrite( Motor_E1, motorspeed);
digitalWrite( Motor_E2, motorspeed);
}
void forward(byte flag, byte motorspeed)
{
digitalWrite( Motor_M1, HIGH);
digitalWrite( Motor_M2, HIGH);
analogWrite( Motor_E1, 200);
analogWrite( Motor_E2, 200);
}
void backward(byte flag, byte motorspeed)
{
digitalWrite( Motor_M1, LOW);
digitalWrite( Motor_M2, LOW);
analogWrite( Motor_E1, 200);
analogWrite( Motor_E2, 200);
}
void right(byte flag, byte motorspeed)
{
digitalWrite( Motor_M1, HIGH);
digitalWrite( Motor_M2, HIGH);
analogWrite( Motor_E1, 150);
analogWrite( Motor_E2, 0);
}
void left(byte flag, byte motorspeed)
{
digitalWrite( Motor_M1, HIGH);
digitalWrite( Motor_M2, HIGH);
analogWrite( Motor_E1, 0);
analogWrite( Motor_E2, 150);
}
以上這是arduino端
以下是手機端 把前天說的 使用 ReceiveUnsigned1ByteNumber if then 裡面的因為不用在加回去256
所以直接把它拿掉了
但是現在使用這個程式 只有遙控車的功能 超音波跟溫溼度 在手機畫面都沒有數值進來
|
|