
/*
 * necesita libraria arduino ps2 mouse
 * modul ESP32 S 
  mouse PS2 conectat: 
  data GPIO 4, clk la GPIO 0 prin convertor logic
 * trimite date pe terminal pe V12
 * afiseaza local pe aOled coordonatele
 * primeste comenzi de la buton sau joystick
 * de pe V1 pentru reset
 * comanda leduri pe GPIO 12, 14, 27
 * cu butoane pe D12, 14, 27 fara definitie
 * */
 
#include <SPI.h>

#define BLYNK_PRINT Serial
#include <WiFi.h>
#include <WiFiClient.h>
#include <BlynkSimpleEsp32.h>

#include <SimpleTimer.h>
SimpleTimer timer;

char auth[] = "e5beac0d31f4433da82dc64b99a03b30"; 
//grand neo

char ssid[] = "SSID";
char pass[] = "password";
 
#include "PS2Mouse.h"

#define DATA_PIN 4   
#define CLOCK_PIN 0

PS2Mouse mouse(CLOCK_PIN, DATA_PIN);

int distX =0; 
int distY =0;
int distZ =0; 

#include <Adafruit_SSD1306.h>
#include <Adafruit_GFX.h>
#define OLED_ADDR   0x3C
Adafruit_SSD1306 display(-1);

void setup(){
  Serial.begin(115200);
  mouse.initialize();
  
SPI.begin();
    Blynk.begin(auth, ssid, pass);
timer.setInterval(1000L, sendUptime);
//trimite date la 1000 milisecunde
display.begin(SSD1306_SWITCHCAPVCC, OLED_ADDR);
  display.clearDisplay();
  display.setTextSize(2);
  display.setTextColor(WHITE);
  display.setCursor(0,0);
  display.print("PS2 Mouse Blynk=");
  display.display();
  delay(1000); 

}

void sendUptime(){
  MouseData data = mouse.readData();
    Serial.print(data.status, BIN);
    Serial.print("\tx=");
    //Serial.print(data.position.x);
    distX+=data.position.x;

    Serial.print(distX);
    
    Serial.print("\ty=");
    //Serial.print(data.position.y);
    distY+=data.position.y;
    Serial.print(distY);
    
    Serial.print("\twheel=");
    //Serial.print(data.wheel);
    distZ+=data.wheel;
    Serial.print(distZ);
    Serial.println();

  display.clearDisplay(); 
  display.setCursor(0,0);
  display.print("X=");
  display.print(distX);

  display.setCursor(0,20);
  display.print("Y=");
  display.print(distY);

  display.setCursor(0,40);
  display.print("Z=");
  display.print(distZ);
  
  display.display();
    delay(20);
   Blynk.virtualWrite(12, "  dist X= ");
   //Blynk.virtualWrite(12, data.position.x);
   Blynk.virtualWrite(12, distX);  
  
   Blynk.virtualWrite(12, "  dist Y= ");
   Blynk.virtualWrite(12, distY);
   Blynk.virtualWrite(12, "  dist Z= ");
   Blynk.virtualWrite(12, distZ);
     } 

BLYNK_WRITE(V1)

{ //reseteaza date
  int Value = param.asInt(); 
  if (Value=1) 
{
  Serial.print("Reset V1 ");
  //reseteaza tot
distX=0;
distY=0;
distZ=0;
Blynk.virtualWrite(12, "  RESET ");
}  
}

/*
BLYNK_WRITE(V11)
{ incrementeaza dist X
  int Value = param.asInt(); // assigning incoming value from pin V1 to a variable

  if (Value=1) 
{
distX++;
} 
}


BLYNK_WRITE(V13)incrementeaza dist y
{
  int Value = param.asInt(); // assigning incoming value from pin V1 to a variable
  if (Value=1) 
{
  
distY++;

} 
}
*/
void loop()
{
Blynk.run(); // Initiates Blynk
  timer.run();
}
