Commit d4bbb47e authored by Franklin Chen's avatar Franklin Chen

init

parents
.pio
.vscode/.browse.c_cpp.db*
.vscode/c_cpp_properties.json
.vscode/launch.json
.vscode/ipch
{
// See http://go.microsoft.com/fwlink/?LinkId=827846
// for the documentation about the extensions.json format
"recommendations": [
"platformio.platformio-ide"
]
}
This directory is intended for project header files.
A header file is a file containing C declarations and macro definitions
to be shared between several project source files. You request the use of a
header file in your project source file (C, C++, etc) located in `src` folder
by including it, with the C preprocessing directive `#include'.
```src/main.c
#include "header.h"
int main (void)
{
...
}
```
Including a header file produces the same results as copying the header file
into each source file that needs it. Such copying would be time-consuming
and error-prone. With a header file, the related declarations appear
in only one place. If they need to be changed, they can be changed in one
place, and programs that include the header file will automatically use the
new version when next recompiled. The header file eliminates the labor of
finding and changing all the copies as well as the risk that a failure to
find one copy will result in inconsistencies within a program.
In C, the usual convention is to give header files names that end with `.h'.
It is most portable to use only letters, digits, dashes, and underscores in
header file names, and at most one dot.
Read more about using header files in official GCC documentation:
* Include Syntax
* Include Operation
* Once-Only Headers
* Computed Includes
https://gcc.gnu.org/onlinedocs/cpp/Header-Files.html
This directory is intended for project specific (private) libraries.
PlatformIO will compile them to static libraries and link into executable file.
The source code of each library should be placed in a an own separate directory
("lib/your_library_name/[here are source files]").
For example, see a structure of the following two libraries `Foo` and `Bar`:
|--lib
| |
| |--Bar
| | |--docs
| | |--examples
| | |--src
| | |- Bar.c
| | |- Bar.h
| | |- library.json (optional, custom build options, etc) https://docs.platformio.org/page/librarymanager/config.html
| |
| |--Foo
| | |- Foo.c
| | |- Foo.h
| |
| |- README --> THIS FILE
|
|- platformio.ini
|--src
|- main.c
and a contents of `src/main.c`:
```
#include <Foo.h>
#include <Bar.h>
int main (void)
{
...
}
```
PlatformIO Library Dependency Finder will find automatically dependent
libraries scanning project source files.
More information about PlatformIO Library Dependency Finder
- https://docs.platformio.org/page/librarymanager/ldf.html
; PlatformIO Project Configuration File
;
; Build options: build flags, source filter
; Upload options: custom upload port, speed and extra flags
; Library options: dependencies, extra library storages
; Advanced options: extra scripting
;
; Please visit documentation for the other options and examples
; https://docs.platformio.org/page/projectconf.html
[env:esp32dev]
platform = espressif32
board = esp32dev
framework = arduino
monitor_speed = 115200
upload_port = COM4
lib_deps =
adafruit/DHT sensor library @ ^1.4.0
adafruit/Adafruit Unified Sensor @ ^1.1.4
knolleary/PubSubClient @ ^2.8
\ No newline at end of file
// INCLUDE
#include <Arduino.h>
#include <WiFi.h>
#include <PubSubClient.h>
#include "DHT.h"
//#include "esp_timer.h"
//#include "esp_sleep.h"
// PIN
#define LED_PIN 2
#define VOUT_PIN 4
#define BUZ_PIN 21
// MQTT
const char* ssid = "BELL834";
const char* password = "A6DA7A52DAAA";
const char* mqtt_server = "test.mosquitto.org"; // default test server = "test.mosquitto.org";
#define PUBLISH_DELAY 100
#define mqtt_port 1883
#define MQTT_SERIAL_PUBLISH_CH "csc113/serialdata/th-wcv3"
#define MQTT_SERIAL_PUBLISH_CH_TEMP_C "csc113/serialdata/th-wcv3/temp_c"
#define MQTT_SERIAL_PUBLISH_CH_TEMP_F "csc113/serialdata/th-wcv3/temp_f"
#define MQTT_SERIAL_PUBLISH_CH_HUMIDITY "csc113/serialdata/th-wcv3/humidity"
#define MQTT_SERIAL_SUBSCRIBE_CH "csc113/serialdata/th-wcv3/switch"
WiFiClient wifiClient;
PubSubClient client(wifiClient);
// MQTT_PRE_DECLARATION
void setup_wifi();
void reconnect();
void callback(char* topic, byte *payload, unsigned int length);
void publishSerialData(const char *serialData);
void publishSerialData(const char *serialData, const char *channel);
// DHT
#define DHTPIN 22 // Digital pin connected to the DHT sensor
#define DHTTYPE DHT11
DHT dht(DHTPIN, DHTTYPE);
// DHT_PRE_DECLARATION
float measureHumidity();
float measureTemp();
void publishDHT();
// TIMER
#define TIMER_SECS 1 // s
#define TIMER_MILLIS TIMER_SECS * 1000 // → ms
#define TIMER_MICROS TIMER_MILLIS * 1000 // → µs
esp_timer_handle_t esp_timer;
// TIMER_PRE_DECLARATION
//..
static void timer_callback(void* arg);
const esp_timer_create_args_t esp_timer_args = {
.callback = &timer_callback,
/* argument specified here will be passed to timer callback function */
.arg = (void*)esp_timer
};
/*************************************Main*************************************/
// SETUP
void setup() {
Serial.begin(115200);
Serial.setTimeout(500);
pinMode(LED_PIN, OUTPUT);
//Buzzer
ledcSetup(0, 1024, 16); //PWM setup
ledcAttachPin(BUZ_PIN, 0);
// mqtt
setup_wifi();
client.setServer(mqtt_server, mqtt_port);
client.setCallback(callback);
reconnect();
Serial.setTimeout(5000);
// dht
pinMode(VOUT_PIN,OUTPUT);
digitalWrite(VOUT_PIN,HIGH);
Serial.println("before dht begin");
dht.begin();
// timer
ESP_ERROR_CHECK(esp_timer_create(&esp_timer_args, &esp_timer));
ESP_ERROR_CHECK(esp_timer_start_periodic(esp_timer, TIMER_MICROS));
}
bool volatile toScan = true;
bool volatile LED_I_O = true;
bool volatile BUZ_I_O = true;
// LOOP
void loop() {
// Get from Broker
client.loop();
if(toScan){
// Reset
toScan = false;
// Scan + Publish
if(LED_I_O) digitalWrite(LED_PIN, HIGH);
publishDHT();
if(LED_I_O) digitalWrite(LED_PIN, LOW);
// Sleep
usleep(TIMER_MICROS * .75);
}
else{
}
}
/*****************************Function Definitions*****************************/
// TIMER
static void timer_callback(void* arg){
toScan = true;
}
// MQTT
void setup_wifi() {
delay(10);
// We start by connecting to a WiFi network
Serial.println();
Serial.print("Connecting to ");
Serial.println(ssid);
WiFi.begin(ssid, password);
while (WiFi.status() != WL_CONNECTED) {
delay(500);
Serial.print(".");
}
randomSeed(micros());
Serial.println("");
Serial.println("WiFi connected");
Serial.println("IP address: ");
Serial.println(WiFi.localIP());
}
void reconnect() {
// Loop until we're reconnected
while (!client.connected()) {
Serial.print("Attempting MQTT connection...");
// Create a random client ID
String clientId = "ESP32Client-";
clientId += String(random(0xffff), HEX);
// Attempt to connect
if (client.connect(clientId.c_str()) )
{
Serial.println("connected");
// subscribe
client.subscribe(MQTT_SERIAL_SUBSCRIBE_CH);
} else {
Serial.print("failed, rc=");
Serial.print(client.state());
Serial.println(" try again in 5 seconds");
// Wait 5 seconds before retrying
delay(5000);
}
}
}
bool testFor(const byte target[], byte *payload, unsigned int length){
int pos = 0;
for(pos = 0; pos < (length); pos++){
if(payload[pos] != target[pos]){
break;
}
}
if(pos == (length)){
return true;
}
return false;
}
const byte PROGMEM bLEDTrue[] = {'l', 'e', 'd', 't'};
const byte PROGMEM bLEDFalse[] = {'l', 'e', 'd', 'f'};
const byte PROGMEM bBUZTrue[] = {'b', 'u', 'z', 't'};
const byte PROGMEM bBUZFalse[] = {'b', 'u', 'z', 'f'};
void callback(char* topic, byte *payload, unsigned int length) {
Serial.println("-------new message from broker-----");
Serial.print("channel:");
Serial.println(topic);
Serial.print("data:");
Serial.write(payload, length);
Serial.println();
if(testFor(bLEDTrue, payload, length)){
LED_I_O = true;
}
else if(testFor(bLEDFalse, payload, length)){
LED_I_O = false;
}
if(testFor(bBUZTrue, payload, length)){
BUZ_I_O = true;
}
else if(testFor(bBUZFalse, payload, length)){
BUZ_I_O = false;
}
}
void publishSerialData(const char *serialData){
if (!client.connected()) {
reconnect();
}
Serial.println(String("publishing: ") + serialData);
client.publish(MQTT_SERIAL_PUBLISH_CH, serialData);
}
void publishSerialData(const char *serialData, const char *channel){
if (!client.connected()) {
reconnect();
}
Serial.println(String("publishing: ") + serialData);
client.publish(channel, serialData);
}
// DHT
void publishDHT() {
float h = dht.readHumidity();
// Read temperature as Celsius (the default)
float t = dht.readTemperature();
// Read temperature as Fahrenheit (isFahrenheit = true)
float f = dht.readTemperature(true);
// Check if any reads failed and exit early (to try again).
if (isnan(h) || isnan(t) || isnan(f)) {
if(BUZ_I_O) ledcWrite(0, 207);
Serial.println(F("Failed to read from DHT sensor!"));
delay(3 * PUBLISH_DELAY);
if(BUZ_I_O) ledcWrite(0, 0);
return;
}
publishSerialData(String(h, 2).c_str(), MQTT_SERIAL_PUBLISH_CH_HUMIDITY);
delay(PUBLISH_DELAY);
publishSerialData(String(t, 2).c_str(), MQTT_SERIAL_PUBLISH_CH_TEMP_C);
delay(PUBLISH_DELAY);
publishSerialData(String(f, 2).c_str(), MQTT_SERIAL_PUBLISH_CH_TEMP_F);
delay(PUBLISH_DELAY);
}
\ No newline at end of file
This directory is intended for PlatformIO Unit Testing and project tests.
Unit Testing is a software testing method by which individual units of
source code, sets of one or more MCU program modules together with associated
control data, usage procedures, and operating procedures, are tested to
determine whether they are fit for use. Unit testing finds problems early
in the development cycle.
More information about PlatformIO Unit Testing:
- https://docs.platformio.org/page/plus/unit-testing.html
Markdown is supported
0% or
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or to comment