Commit df1c83b1 authored by Alexes Pagan's avatar Alexes Pagan

Initial commit

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"
],
"unwantedRecommendations": [
"ms-vscode.cpptools-extension-pack"
]
}
{
"C_Cpp_Runner.msvcBatchPath": "",
"C_Cpp_Runner.cCompilerPath": "gcc",
"C_Cpp_Runner.cppCompilerPath": "g++",
"C_Cpp_Runner.debuggerPath": "gdb",
"C_Cpp_Runner.cStandard": "",
"C_Cpp_Runner.cppStandard": "",
"C_Cpp_Runner.useMsvc": false,
"C_Cpp_Runner.warnings": [
"-Wall",
"-Wextra",
"-Wpedantic",
"-Wshadow",
"-Wformat=2",
"-Wcast-align",
"-Wconversion",
"-Wsign-conversion",
"-Wnull-dereference"
],
"C_Cpp_Runner.msvcWarnings": [
"/W4",
"/permissive-",
"/w14242",
"/w14287",
"/w14296",
"/w14311",
"/w14826",
"/w44062",
"/w44242",
"/w14905",
"/w14906",
"/w14263",
"/w44265",
"/w14928"
],
"C_Cpp_Runner.enableWarnings": true,
"C_Cpp_Runner.warningsAsError": false,
"C_Cpp_Runner.compilerArgs": [],
"C_Cpp_Runner.linkerArgs": [],
"C_Cpp_Runner.includePaths": [],
"C_Cpp_Runner.includeSearch": [
"*",
"**/*"
],
"C_Cpp_Runner.excludeSearch": [
"**/build",
"**/build/**",
"**/.*",
"**/.*/**",
"**/.vscode",
"**/.vscode/**"
],
"C_Cpp_Runner.useAddressSanitizer": false,
"C_Cpp_Runner.useUndefinedSanitizer": false,
"C_Cpp_Runner.useLeakSanitizer": false,
"C_Cpp_Runner.showCompilationTime": false,
"C_Cpp_Runner.useLinkTimeOptimization": false,
"C_Cpp_Runner.msvcSecureNoWarnings": false
}
\ No newline at end of file
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:esp32doit-devkit-v1]
platform = espressif32
board = esp32doit-devkit-v1
framework = arduino
lib_deps = knolleary/PubSubClient@^2.8
#include <Arduino.h>
#include <WiFi.h>
#include <PubSubClient.h>
const char* ssid = "AlexesIphone";
const char* password = "bluecomet";
const char* mqtt_server = "test.mosquitto.org"; //broker, test server
#define mqtt_port 1883 //defualt port number
#define MQTT_SERIAL_PUBLISH_CH "bcomet/serialdata/tx"
#define MQTT_SERIAL_SUBSCRIBE_CH "bcomet/serialdata/tx"
#define uS_TO_S_FACTOR 1000000ULL /* Conversion factor for micro seconds to seconds */
#define TIME_TO_SLEEP 10 /* Time ESP32 will go to sleep (in seconds) */ //"csc113/serialdata/tx"
//these are all pins based on the esp32s device
const int player1ButtonPin = 15;
const int player2ButtonPin = 4;
const int ledPin = 2;
const int buttonStart = 0;
const int buzzerPin = 12;
//variables to check the button presses.
int buttonState;
int buttonState2;
int buttonState3;
//variables to control the pace and setup of the game
bool gameSetup = false;
bool gameStart = false;
bool winnerFound = false;
bool isConnected = false;
bool goToSleep = false;
WiFiClient wifiClient;
PubSubClient client(wifiClient); //making pubsubclient
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-AlexesP"; //unique id for each client
clientId += String(random(0xffff), HEX); //makes sure the id is unique.
// Attempt to connect
//if (client.connect(clientId.c_str(),MQTT_USER,MQTT_PASSWORD))
if (client.connect(clientId.c_str()) )
{
Serial.println("connected");
isConnected = true;
// 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);
}
}
}
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();
}
void print_wakeup_reason(){
esp_sleep_wakeup_cause_t wakeup_reason;
wakeup_reason = esp_sleep_get_wakeup_cause();
switch(wakeup_reason)
{
case ESP_SLEEP_WAKEUP_EXT0 : Serial.println("Wakeup caused by external signal using RTC_IO"); break;
case ESP_SLEEP_WAKEUP_EXT1 : Serial.println("Wakeup caused by external signal using RTC_CNTL"); break;
case ESP_SLEEP_WAKEUP_TIMER : Serial.println("Wakeup caused by timer"); break;
case ESP_SLEEP_WAKEUP_TOUCHPAD : Serial.println("Wakeup caused by touchpad"); break;
case ESP_SLEEP_WAKEUP_ULP : Serial.println("Wakeup caused by ULP program"); break;
default : Serial.printf("Wakeup was not caused by deep sleep: %d\n",wakeup_reason); break;
}
}
void setup() {
Serial.begin(9600);
Serial.setTimeout(500);// Set time out for
setup_wifi();
client.setServer(mqtt_server, mqtt_port);
client.setCallback(callback);
reconnect();
Serial.setTimeout(5000);
//Initialize all pins used.
pinMode(player1ButtonPin, INPUT_PULLUP);
pinMode(player2ButtonPin, INPUT_PULLUP);
pinMode(buttonStart, INPUT_PULLUP);
pinMode(ledPin, OUTPUT);
pinMode(buzzerPin, OUTPUT);
}
//function that plays the countdown melody.
void playMelody() {
int melody[] = { 659, 0, 659, 0, 659, 0 }; //plays the first 3 beats of the melody, 0's are pauses.
int noteDurations[] = { 400, 400, 400, 400, 400, 400 }; // duration of each note in milliseconds
// Play the countdown melody
for (int i = 0; i < sizeof(melody) / sizeof(melody[0]); i++) {
int noteDuration = noteDurations[i];
tone(buzzerPin, melody[i], noteDuration);
// Pause between notes
delay(noteDuration + 50);
noTone(buzzerPin);
}
// pause before playing the final note
delay(500);
// plays the final note
tone(buzzerPin, 1000, 500);
delay(700);
noTone(buzzerPin);
}
//function that sets several game variables, turns led on/off and calls the melody function.
void startGame(){
if(gameSetup == true){
digitalWrite(ledPin, HIGH);
delay(3000);
digitalWrite(ledPin, LOW);
delay(2000);
playMelody();
gameStart = true;
}
}
void loop() {
client.loop();
//checks state of start button
buttonState2 = digitalRead(buttonStart);
//if the start button is pressed, the game hasn't been setup already, and the esp32 is connected to the mqtt, enter the statement.
if(buttonState2 == LOW && gameSetup == false && isConnected == true){
Serial.println("game started");
gameSetup = true;
startGame();
//while neither player has pressed their button, the program will continuosly look for a button press.
while(winnerFound != true){
buttonState = digitalRead(player1ButtonPin);
buttonState3 = digitalRead(player2ButtonPin);
//if player1 pressed their button first
if(buttonState == LOW && gameStart == true){
Serial.println("player1 is the winner!");
winnerFound = true;
client.publish(MQTT_SERIAL_PUBLISH_CH, "Player1 is the Winner!");
goToSleep = true;
}
//if player2 pressed their button first
if(buttonState3 == LOW && gameStart == true){
Serial.println("player2 is the winner!");
winnerFound = true;
client.publish(MQTT_SERIAL_PUBLISH_CH, "Player2 is the Winner!");
goToSleep = true;
}
}
}
if(goToSleep == true && winnerFound == true){
delay(5000);
//Print the wakeup reason for ESP32
print_wakeup_reason();
//the esp32 will wakeup after 10 seconds.
esp_sleep_enable_timer_wakeup(TIME_TO_SLEEP * uS_TO_S_FACTOR);
//after the sleep the game will restart, allowing it to be replayed.
Serial.println("Going to sleep now");
Serial.flush();
esp_deep_sleep_start();
}
}
\ No newline at end of file
This directory is intended for PlatformIO Test Runner 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/en/latest/advanced/unit-testing/index.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