Skip to content

Instantly share code, notes, and snippets.

@JayTheDaniels

JayTheDaniels/Exp5_Jay.ino Secret

Created Dec 8, 2020
Embed
What would you like to do?
/**
Experiment 5: NINE
NINE pins to rule them all, NINE array entries to find them,
NINE touch sensors to bring them all and with the LEDs bind them
**/
#include <WiFiNINA.h>
#define PubNub_BASE_CLIENT WiFiClient
#include <PubNub.h>
#include <ArduinoJson.h>
#include <SparkFunLSM6DS3.h>
#include "Wire.h"
#include "Adafruit_MPR121.h"
#ifndef _BV
#define _BV(bit) (1 << (bit))
#endif
Adafruit_MPR121 cap = Adafruit_MPR121();
uint16_t currtouched = 0;
uint16_t lasttouched = 0;
int tp = 9;
//**Details of your local Wifi Network
//Name of your access point
char ssid[] = "";
//Wifi password
char pass[] = "";
int status = WL_IDLE_STATUS; // the Wifi radio's status
// pubnub keys
char pubkey[] = "";
char subkey[] = "";
// channel and ID data
const char* myID = "Jay"; // place your name here, this will be put into your "sender" value for an outgoing messsage
char publishChannel[] = "JayData"; // channel to publish YOUR data
char readChannel[] = "BernData"; // channel to read THEIR data
// JSON variables
StaticJsonDocument<200> dataToSend; // The JSON from the outgoing message
StaticJsonDocument<200> inMessage; // JSON object for receiving the incoming values
//create the names of the parameters you will use in your message
String JsonParamName1 = "publisher";
String JsonParamName2 = "led";
int serverCheckRate = 1000; //how often to publish/read data on PN
unsigned long lastCheck; //time of last publish
//These are the variables that will hold the values we will be using
//some are calculated locally, some come from PubNub messages
int ledReadIn = 10; //stores the pin sent by the opponent. Default to 10, which doesn't exist
int lastReadIn = 0;
int pinTouched = 0; //stores the pin touched by the player
const char* inMessagePublisher;
int ledPins[] = {2, 3, 4, 5, 6, 7, 8, 9, 10};
boolean ledStates[] = {false, false, false, false, false, false, false, false, false};
int ledTotal = sizeof(ledPins) / sizeof(int);
void setup() {
Serial.begin(9600);
if (!cap.begin(0x5A)) {
Serial.println("MPR121 not found, check wiring?");
while (1);
}
Serial.println("MPR121 found!");
//run this function to connect
connectToPubNub();
for (int i = 0; i < ledTotal; i++) {
pinMode(ledPins[i], OUTPUT);
}
}
void loop()
{
//receive messages with PubNub, based on a timer
receiveMessages(serverCheckRate);
if (ledStates[ledReadIn] == false && ledReadIn != lastReadIn) { //check to make sure incoming pin is off and isn't the same number being read in
ledStates[ledReadIn] = true; //sets incoming pin from partner to on
lastReadIn = ledReadIn; //saves pin read in value so it doesn't keep the same LED on forever
}
checkAllPins(tp); //checks your own pins and updates the LEDs
for (int i = 0; i < ledTotal; i++)
{
digitalWrite(ledPins[i], ledStates[i]);
//Debugging code to check on the LEDs individually
//Serial.print("LED: ");
//Serial.print(ledPins[i]);
//Serial.print(" State: ");
//Serial.println(ledStates[i]);
}
}
void checkAllPins(int totalPins) {
currtouched = cap.touched();
for (uint8_t i = 0; i < totalPins; i++)
{
if ((currtouched & _BV(i)) && !(lasttouched & _BV(i)))
{
if (ledStates[i] == true) { //check if led is already on
ledStates[i] = false; //turns off the pin you touched
}
if(checkLEDs()==0) { //if ALL LEDs are off, you can send your pin to your partner
blinkLED(i); //quickly blink the LED to indicate it is being sent
pinTouched = i; //save the pin for publishing
Serial.print("Sending: ");
Serial.println(pinTouched);
sendMessage(publishChannel);
}
}
}
lasttouched = currtouched;
}
void blinkLED(int led){
Serial.print(led); //for some inexplicable reason, the led value is 2 off. Wiring issue?
digitalWrite(led+2, HIGH);
delay(300);
digitalWrite(led+2, LOW);
}
int checkLEDs(){ //quickly checks all of the LEDs and returns the numbe that are active
int ledsActive = 0;
for(int i = 0; i<ledTotal; i++){
if(ledStates[i]==true){
ledsActive++;
}
}
return ledsActive;
}
void connectToPubNub()
{
Serial.print("Attempting to connect to the network, SSID: ");
Serial.println(ssid);
// attempt to connect to Wifi network:
while ( status != WL_CONNECTED)
{
status = WiFi.begin(ssid, pass);
Serial.print("*");
// wait 2 seconds for connection:
delay(2000);
}
// once you are connected :
Serial.println();
Serial.print("You're connected to ");
Serial.println(ssid);
PubNub.begin(pubkey, subkey);
Serial.println("Connected to PubNub Server");
}
void receiveMessages(int pollingRate)
{
//connect, publish new messages, and check for incoming
if ((millis() - lastCheck) >= pollingRate)
{
//check for new incoming messages
readMessage(readChannel);
//save the time so timer works
lastCheck = millis();
}
}
void sendMessage(char channel[])
{
Serial.print("Sending Message to ");
Serial.print(channel);
Serial.println(" Channel");
char msg[64]; // variable for the JSON to be serialized into for your outgoing message
// assemble the JSON to publish
dataToSend[JsonParamName1] = myID; // first key value is publisher
dataToSend[JsonParamName2] = pinTouched; // second key value is the temperature
serializeJson(dataToSend, msg); // serialize JSON to send - sending is the JSON object, and it is serializing it to the char msg
Serial.println(msg);
WiFiClient* client = PubNub.publish(channel, msg); // publish the variable char
if (!client)
{
Serial.println("publishing error"); // if there is an error print it out
}
else
{
Serial.print(" ***SUCCESS");
}
}
void readMessage(char channel[])
{
String msg;
auto inputClient = PubNub.history(channel, 1);
if (!inputClient)
{
Serial.println("message error");
delay(1000);
return;
}
HistoryCracker getMessage(inputClient);
while (!getMessage.finished())
{
getMessage.get(msg);
//basic error check to make sure the message has content
if (msg.length() > 0)
{
Serial.print("**Received Message on ");
Serial.print(channel);
Serial.println(" Channel");
Serial.println(msg);
//parse the incoming text into the JSON object
deserializeJson(inMessage, msg); // parse the JSON value received
//read the values from the message and store them in local variables
inMessagePublisher = inMessage[JsonParamName1]; // this is will be "their name"
ledReadIn = inMessage[JsonParamName2]; // read in their chosen LED
Serial.print("LED INPUT: ");
Serial.println(ledReadIn);
}
}
inputClient->stop();
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment