//B. Vandeportaele 2019 //choisir la carte NodeMCU1.0(ESP12E module) //pour uploader, presser le bouton reset quand l'ide arduino affiche "connecting..." puis relacher //régler les macros suivantes pour régler le comportement de la carte: //#define HX711PRESENT #define JOYPRESENT #include #include #include WiFiUDP Client; #include #define WSout D2 #define PIXELCOUNT 2 Adafruit_NeoPixel pixels = Adafruit_NeoPixel(PIXELCOUNT, WSout, NEO_GRB + NEO_KHZ800); // A UDP instance to let us send and receive packets over UDP WiFiUDP udp; // wifi connection variables unsigned int localPort = 10000; // local port to listen for UDP packets #include "listereseauxwifi.h" //const char* ssid = "78BF39"; //const char* password = "6D842DAE4B"; char *MACADDRESS=NULL; #define TRANSMITOVERWIFI #ifdef TRANSMITOVERWIFI //String ip = "192.168.1.49"; // the remote IP address IPAddress Ip; #endif // /home/bvandepo/.arduino15/packages/esp8266/hardware/esp8266/2.3.0-rc2/libraries/ESP8266WiFi/src/ESP8266WiFi.h // /home/bvandepo/.arduino15/packages/esp8266/hardware/esp8266/2.3.0-rc2/cores/esp8266/IPAddress.h ////////////////////////// //i2c //#include //attention le code de la balance est bloquant, et donc si le module HX711 n'est pas présent mais que le code est executé, l'esp8266 va faire un watchdog reset et ceci apparait sur la console série: // esp8266 ets Jan 8 2013,rst cause:2, boot mode:(3,7) /* The codes are : 0 -> normal startup by power on 1 -> hardware watch dog reset 2 -> software watch dog reset (From an exception) 3 -> software watch dog reset system_restart (Possibly unfed watchdog got angry) 4 -> soft restart (Possibly with a restart command) 5 -> wake up from deep-sleep Looking at the provided code you can decide from what reason the chip is restarting. */ #ifdef HX711PRESENT #include "HX711.h" HX711 scale(D4, D3); // DOUT, SCK #endif #ifdef JOYPRESENT ////////////////////////////////////////// class JoystickESP8266CD4053B { //L'entrée analogique est forcément A0, car c'est la seule private: int16_t minX, maxX, minY, maxY; float xFactor, yFactor; int16_t centerX, centerY, dZ; uint8_t pinSelect, pinB; int16_t iX, iY; //position intégrée int16_t b; //bouton 1=pressé int16_t X, Y; //position lue int16_t dX, dY; //différence de position par rapport au Zero public: JoystickESP8266CD4053B(uint8_t pinSelectinit, uint8_t pinBinit, int16_t dZinit) { pinSelect = pinSelectinit; pinB = pinBinit; dZ = dZinit; //dead Zone //par défaut les limites pour x et y sont les valeurs min et max codable minX = -32768; maxX = 32767; minY = -32768; maxY = 32767; xFactor = 1; yFactor = 1; } void init() { //analogRead ne fonctionne pas avant appel de setup() pinMode(pinSelect, OUTPUT); pinMode(pinB, INPUT_PULLUP); //pull up pour bouton iX = 0; iY = 0; digitalWrite(pinSelect, LOW); delayMicroseconds(3); centerX = analogRead(A0); digitalWrite(pinSelect, HIGH); delayMicroseconds(3); centerY = analogRead(A0); b = !digitalRead(pinB); } void setLimits(int16_t minXinit, int16_t maxXinit, int16_t minYinit, int16_t maxYinit) { minX = minXinit; maxX = maxXinit; minY = minYinit; maxY = maxYinit; } void setPos(int16_t xinit, int16_t yinit) { iX = xinit; iY = yinit; } void setPosCenter() { iX = (maxX + minX) / 2; iY = (maxY + minY) / 2; } void setFactorOrientation(float xFactorInit, float yFactorInit) { xFactor = xFactorInit; yFactor = yFactorInit; } void update() { digitalWrite(pinSelect, LOW); delayMicroseconds(3); X = analogRead(A0); digitalWrite(pinSelect, HIGH); delayMicroseconds(3); Y = analogRead(A0); dX = (X - centerX) * xFactor; dY = (Y - centerY) * yFactor; /*if (abs(dX)>dZ) x=x+dX; if (abs(dY)>dZ) y=y+dY; */ if (dX > dZ) if (iX < maxX - dX) iX = iX + dX; else iX = maxX; if (dX < -dZ) if (iX > minX - dX) iX = iX + dX; else iX = minX; if (dY > dZ) if (iY < maxY - dY) iY = iY + dY; else iY = maxY; if (dY < -dZ) if (iY > minY - dY) iY = iY + dY; else iY = minY; b = !digitalRead(pinB); /* Serial.print("centerX: "); Serial.print(centerX); Serial.print("centerY: "); Serial.println(centerY); Serial.print("dX: "); Serial.print(dX); Serial.print("dY: "); Serial.println(dY); */ } int16_t getdX() { return dX; } int16_t getdY() { return dY; } int16_t getiX() { return iX; } int16_t getiY() { return iY; } int16_t getX() { return X; } int16_t getY() { return Y; } int16_t getB() { return b; } bool isUp() { return (Y > centerY + dZ); } bool isDown() { return (Y < centerY - dZ); } bool isLeft() { return (X > centerX + dZ); } bool isRight() { return (X < centerY - dZ); } }; ////////////////////////////////////////// JoystickESP8266CD4053B joy(D3, D4, 3); #endif ////////////////////////////////////////// void Debug(char * msg) { #if 1 Serial.print(msg); #endif } ////////////////////////////////////////// unsigned long computeDeltaTime(unsigned long time_begin) { unsigned long time_current; unsigned long time_delta; time_current = micros(); if (time_current > time_begin) time_delta = time_current - time_begin; else //in case micros has rolled over 2^32, may happen approx. once each hour (3600000000us) time_delta = time_current - (time_begin - (unsigned long )4294967296); return time_delta; } ////////////////////////////////////////// #ifdef TRANSMITOVERWIFI void sendMessage(byte message[]) { //sprintf((char*)message,"Hello ca va la?"); udp.beginPacket(Ip, 10000); udp.write(message, strlen((char*)message)); udp.endPacket(); } #endif ////////////////////////////////////////// int getMessage(byte message[], int maxByte) { int cb = udp.parsePacket(); if (cb == 0) return 0; //no dataavailable, quit if (cb > maxByte) cb = maxByte; //don't overrun the buffer, the remaining part of the message WILL BE LOST!! // We've received a packet, read the data from it udp.read(message, cb); // read the packet into the buffer message[cb] = 0; //add a 0 after the content in the buffer return cb; } ////////////////////////////////////////// #define BUFFER_RX_MAX 50 #define ERROR -1 #define NOTHING 0 #define STARTING 5 #define WAITINGFORCONNECTION 6 #define CONNECTED 7 class Communication { public: int state; //last message received byte message[BUFFER_RX_MAX + 1]; //+1 to add an additional 0 after the received bytes to ensure that the string is correctly finished, even if the sender sent some errors int numeroReseauWifi; int nbRetryConnectWifi; //////////// Communication() { state = STARTING; numeroReseauWifi=0; nbRetryConnectWifi=0; configListeReseauWifi(); } //////////// void loop() { //doc at https://www.arduino.cc/en/Reference/WiFiStatus if (state == STARTING) { //Wifi Configuration Serial.println ( "Wifi Configuration" ); #ifdef TRANSMITOVERWIFI Ip.fromString(listeReseauWifi[numeroReseauWifi].serverIP); #endif //WiFi.begin ( ssid, password ); WiFi.begin ( listeReseauWifi[numeroReseauWifi].ssid, listeReseauWifi[numeroReseauWifi].password ); //stocke l'adresse mac if (MACADDRESS==NULL){ MACADDRESS=strdup(WiFi.macAddress().c_str()); Serial.print ( "MAC address for this board: " ); Serial.println ( MACADDRESS); } // Wait for connection state = WAITINGFORCONNECTION; } else if (state == WAITINGFORCONNECTION) { if ( WiFi.status() != WL_CONNECTED ) { Serial.print ( "WAITINGFORCONNECTION to " ); Serial.print ( numeroReseauWifi); Serial.print ( " "); Serial.println ( listeReseauWifi[numeroReseauWifi].ssid); nbRetryConnectWifi++; //flash bleu pixels.setPixelColor(0, Color(0,0,255)); pixels.show(); delay(100); pixels.setPixelColor(0, Color(0,0,0)); pixels.show(); delay(100); #define MAX_NB_RETRY_CONNECT_WIFI 50 if (nbRetryConnectWifi>MAX_NB_RETRY_CONNECT_WIFI) { nbRetryConnectWifi=0; numeroReseauWifi=(numeroReseauWifi+1)%NbReseauWifi; WiFi.begin ( listeReseauWifi[numeroReseauWifi].ssid, listeReseauWifi[numeroReseauWifi].password ); Ip.fromString(listeReseauWifi[numeroReseauWifi].serverIP); //Serial.print ( "Now trying to connect to " ); //flash rouge pixels.setPixelColor(0, Color(255,0,0)); pixels.show(); delay(100); pixels.setPixelColor(0, Color(0,0,0)); pixels.show(); delay(100); } } else { state = CONNECTED; //flash vert pixels.setPixelColor(0, Color(0,255,0)); pixels.show(); delay(500); pixels.setPixelColor(0, Color(0,0,0)); pixels.show(); delay(500); } } else if (state == CONNECTED) { Serial.println ( "" ); Serial.print ( "Connected to " ); Serial.println (listeReseauWifi[numeroReseauWifi].ssid ); Serial.print ( "Local IP address: " ); Serial.println ( WiFi.localIP() ); Serial.print ( "Server IP address: " ); Serial.println (listeReseauWifi[numeroReseauWifi].serverIP ); Serial.println("Starting UDP socket"); udp.begin(localPort); Serial.print("Local port: "); Serial.println(udp.localPort()); state = NOTHING; } else { if ( WiFi.status() == WL_CONNECTION_LOST) { Serial.print ( "WL_CONNECTION_LOST\n" ); state = STARTING; } else if ( WiFi.status() == WL_DISCONNECTED) { Serial.print ( "WL_DISCONNECTED\n" ); state = STARTING; } else { int n = getMessage(message, BUFFER_RX_MAX); if (n == 0) Debug("."); else { Debug("packet received, length="); char msg[11]; snprintf(msg, 10, "%d", n); Debug(msg); Debug(", content= "); Debug((char*)message); /* if (strcmp((char*)message,"OpenTheDoorCompletelyPlease")==0){ state=OPENTHEDOOR; Debug(" -> Open The Door\n"); } else if (strcmp((char*)message,"CloseTheDoorCompletelyPlease")==0){ state=CLOSETHEDOOR; Debug(" -> Close The Door\n"); } else if (strcmp((char*)message,"StopTheDoor")==0){ state=STOPTHEDOOR; Debug(" -> StopTheDoor\n"); } else if (strcmp((char*)message,"SwitchTheLight")==0){ state=SWITCHTHELIGHT; Debug(" -> SwitchTheLight\n"); } else{ state=ERROR; Debug(" -> Error\n"); }*/ } } } } ////////////////////////// void EmitMessage() { #ifdef TRANSMITOVERWIFI /* static int counter=0; static int b1state=0; static int b2state=0; static int b3state=0; //simulate random presses/releases of buttons if(random(0, 20)==0) b1state=(b1state+1)%2; if(random(0, 15)==0) b2state=(b2state+1)%2; if(random(0, 25)==0) b3state=(b3state+1)%2; */ if (state == NOTHING) { /* counter++; sprintf((char*)message,"compteur= %6d b1:%d b2:%d b3:%d\n",counter,b1state,b2state,b3state); */ /*digitalWrite(D2,LOW); delay(3000); digitalWrite(D2,HIGH); delay(3000); */ //sprintf((char*)message, "%d %d %d\n", Ax - AxZero, Ay - AyZero, Sw); unsigned short int numero_data=0; //identification si le capteur fournit plusieurs messages #ifdef HX711PRESENT static float poidsmax=20000; float poids= scale.get_units(1); // scale.get_units(); // inversion!!!! if (abs(poids)>poidsmax) poidsmax=abs(poids); //Serial.println(poids, 1); unsigned char R=0; unsigned char G=0; unsigned char B=0; if (poids>0) R=poids*255./poidsmax; else if (poids<0) G=-poids*255./poidsmax; //else tout à 0 pixels.setPixelColor(0, Color(R,G,B)); pixels.show(); numero_data=0; //identification si le capteur fournit plusieurs messages //sprintf((char*)message, "%s %d %f %d %d\n",MACADDRESS, numero_data,poids,R,G); sprintf((char*)message, "%s %d %f\n",MACADDRESS, numero_data,poids); sendMessage(message); #endif #ifdef JOYPRESENT //joystick joy.update(); pixels.setPixelColor(0, Color(joy.getX()/ 8, joy.getY() / 8, 0)); //attention Ax,Ay va de 0 à 1024 inclus pixels.setPixelColor(1, Color(0, 0, joy.getB() * 128)); //attention Ax,Ay va de 0 à 1024 inclus pixels.show(); numero_data=1; //identification si le capteur fournit plusieurs messages sprintf((char*)message, "%s %d %d %d %d %d %d %d %d\n", MACADDRESS, numero_data, joy.getX() , joy.getY(),joy.getB(), joy.getdX(),joy.getdY(),joy.getiX(),joy.getiY()); sendMessage(message); #endif /* //compteur numero_data=1; //identification si le capteur fournit plusieurs messages static int cpt=0; cpt++; sprintf((char*)message, "%s %d %d\n", MACADDRESS, numero_data, cpt); sendMessage(message); */ //sprintf((char*)message,"%d\n",analogRead(A0)); } #endif } }; ////////////////////////////////////////// Communication communication; ////////////////////////////////////////// //Be carefull, The Watchdog resets every 4 seconds if the loop function is not finished ////////////////////////////////////////// uint32_t Color(byte r, byte g, byte b) { uint32_t c; c = r; c <<= 8; c |= g; c <<= 8; c |= b; return c; } ////////////////////////////////////////// void setup() { randomSeed(analogRead(0)); //serial communication setup for debugging Serial.begin ( 115200 ); delay(100); Serial.println ( "Serial Configuration Completed" ); Serial.println( "Compiled: " __DATE__ ", " __TIME__ ", " __VERSION__); //GPIOs Configuration Serial.println ( "GPIOs Configuration (some already done through constructors)" ); //Wifi Configuration done in first iterations of communication.loop #ifdef HX711PRESENT // scale.set_scale(250.f); //// this value is obtained by calibrating the scale with known weights scale.tare(10); //tare basée sur moyenne de 10 mesures #endif #ifdef JOYPRESENT joy.init(); joy.setLimits(-32767, 32767, -32767, 32767); joy.setPosCenter(); joy.setFactorOrientation(0.1, 0.1); #endif pixels.begin(); for (byte i = 0; i < PIXELCOUNT; i++) pixels.setPixelColor(i, Color(0, 0, 0)); pixels.show(); }; ////////////////////////////////////////// // the loop function runs over and over again forever void loop() { //Serial.println(micros()); //test_buttons_and_relays(); communication.loop(); communication.EmitMessage(); // if (communication.isSwitchTheLight()) light.commute(); if (communication.state!=CONNECTED) delay(100); //for debuging purposes, it slows the display delay(2); } //////////////////////////////////////////