Add files via upload

Add files via upload

This is the code for your esp8266 device.
Just upload to your esp8266, open a serial monitor window since by default the code is in debug mode.

/*
 * ESP8266 Manager
 *
 * Copyright (c) 2016, Serge Beland (sbeland@gmail.com)
 * All rights reserved.
 *
 * Redistribution and use in source and binary forms, with or without modification,
 * are permitted provided that the following conditions are met:
 *
 * * Redistributions of source code must retain the above copyright notice, this
 *   list of conditions and the following disclaimer.
 *
 * * Redistributions in binary form must reproduce the above copyright notice, this
 *   list of conditions and the following disclaimer in the documentation and/or
 *   other materials provided with the distribution.
 *
 * * Neither the name of <Serge Beland> nor the names of its
 *   contributors may be used to endorse or promote products derived from
 *   this software without specific prior written permission.
 *
 * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND
 * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
 * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
 * DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR
 * ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
 * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
 * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON
 * ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
 * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
 * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
 */

#include <ESP8266WiFi.h>
#include <EEPROM.h>
#include <WiFiClient.h>
#include <ESP8266WebServer.h>

char *ServerHost = "sbelandiot.com"; // where your php/html files are hosted, everything must be under the root directory

#define DEBUG // comment it out to remove debugging display on serial monitor
              // if you use, then esp will wait that you open the serial monitor window before starting

#ifdef DEBUG
#define DebugInit() Serial.begin(115200)
#define Debugln(...) Serial.println(__VA_ARGS__)
#define Debug(v) Serial.print(v)
#define Debugf(...) Serial.printf(__VA_ARGS__)
#else
#define DebugInit()
#define Debug(...)
#define Debugln(...)
#define Debugf(...)
#endif

#define STATE_AP_MODE            0
#define STATE_WAIT_INPUT         1
#define STATE_GET_INFO           2
#define STATE_SEND_MAIL_STARTED  3
#define STATE_WAIT_FOR_SENSOR    4
#define STATE_PENDING_MODE       5
#define STATE_UPDATE_INFO        6

#define SENDMAIL_OPTION_STARTED  0
#define SENDMAIL_OPTION_SENSOR1  1

#define SSID_AD            0
#define SSID_PASSWORD_AD   49
#define ESP_PASSWORD_AD    114
#define EMAIL_AD           131

char Ssid [49];
char SsidPassword [65];
char EspPassword [17];
char Email [65];

char EspName [17];
int NbOfSsid;
int state;                    // different state in loop
unsigned long StartTime = 0;  // keep the time passed in seconds since the module started
bool PendingMode = 0;         // use to say if this iot is activated on web server (so we can keep going) or not (so we must wait)
unsigned long TimeSet = 0;    // can be use to measure time elapse in millisecond between 2 points by using SetTime and TimeDiff
unsigned long UpdateTimeSet = 0; // is used by the update info interval
unsigned long UpdateInterval = 60000;
char *EspDefaultPW = "admin123";

ESP8266WebServer server (80);  // use for AP mode to setup the esp

/*
 * replace {v} with title
 * String page = Header;
 * page.replace ("{v}", "yourtitle");
 *
 /*
 * to add in the header of html to refresh the browser page every x seconds
 * <meta http-equiv='refresh' content='5'/>
 */
char *Header = "<!DOCTYPE html><meta name=\"viewport\" content=\"width=device-width, initial-scale=1, user-scalable=no\"/><title>{v}</title>"
""
""
"
";

char *Footer = "";

/*
 *  This function list all available AP on serial monitor
 *  it return the number of networks found
 *  you can access each network from WiFi.SSID (index) where index < number of network
 */
int ListAP (void)
{
   Debugln ("ListAP\nScanning...wait");

   // WiFi.scanNetworks will return the number of networks found
   NbOfSsid = WiFi.scanNetworks();

   if (NbOfSsid == 0)
   {
      Debugln ("\nNo networks found!!!");
      return 0;
   }

   Debugf ("%d networks found\n\n", NbOfSsid);

   for (int i = 0; i < NbOfSsid; ++i)
   {
      // Print SSID and RSSI for each network found
      Debug (i + 1);
      Debug (": ");
      Debug (WiFi.SSID(i));
      Debug (" (");
      Debug (WiFi.RSSI(i));
      Debug (")");
      Debugln ((WiFi.encryptionType (i) == ENC_TYPE_NONE) ? "   " : "*  ");
      //Debugln (WiFi.remoteIP ());
      delay(10);
   }
   Debugln ("\nScan done");

   return NbOfSsid;
}

void GetEEpromInfo ()
{
   EEPROM.begin(512);

   EEPROM.get (SSID_AD, Ssid);
   EEPROM.get (SSID_PASSWORD_AD, SsidPassword);
   EEPROM.get (ESP_PASSWORD_AD, EspPassword);
   EEPROM.get (EMAIL_AD, Email);

   Ssid [sizeof (Ssid) - 1] = 0;
   SsidPassword [sizeof (SsidPassword) - 1] = 0;
   EspPassword [sizeof (EspPassword) - 1] = 0;
   Email [sizeof (Email) - 1] = 0;

   Debugln ("\nEEPROM INFO READED");
   Debugf ("SSID: %s\n", Ssid);
   Debugf ("SsidPassword: %s\n", SsidPassword);
   Debugf ("ESP Password: %s\n", EspPassword);
   Debugf ("Email: %s\n\n", Email);
}

/*
 * Write in eeprom 4 variables: ssid, password, email and esp password
 */
void SetEEpromInfo ()
{
   EEPROM.begin(512);

   EEPROM.put (SSID_AD, Ssid);
   EEPROM.put (SSID_PASSWORD_AD, SsidPassword);
   EEPROM.put (ESP_PASSWORD_AD, EspPassword);
   EEPROM.put (EMAIL_AD, Email);
   EEPROM.commit ();

   Debugln ("\nEEPROM INFO WRITTEN");
   Debugf ("SSID: %s\n", Ssid);
   Debugf ("SsidPassword: %s\n", SsidPassword);
   Debugf ("ESP Password: %s\n", EspPassword);
   Debugf ("Email: %s\n\n", Email);
}

/*
 * Start wifi and try to connect inside the TimeOutInSec
 * return 1 if success
 *        0 if no success
 */
int ConnectToWifi (char *s, char *p, int TimeOutInSec)
{
   WiFi.begin (s, p);

   int t = 0;

   Debugf ("Trying to connect to wifi with:\nSsid: %s\nPassword: %s\n", s, p);

   while (WiFi.status () != WL_CONNECTED && t++ < TimeOutInSec)
   {
      delay (1000);
      Debug (".");
   }

   Debugln ();

   if (WiFi.status () != WL_CONNECTED)
      return 0;

   Debugf ("\nWiFi connected to: %s\n", s);
   Debugf ("with password: %s\n", p);
   Debug ("IP address: ");
   Debugln (WiFi.localIP ());

   return 1;
}

int TryToConnectToWifi (int nboftry)
{
   // try to connect nboftry times, delay (count x 2) sec between each try
   char count = 0;

   for (int i = 0; i < nboftry; i++)
   {
      if (ConnectToWifi (Ssid, SsidPassword, 30))
         return 1;
      if (++count >= nboftry)
      {
         Debugln ("Giving up to try to connect to wifi, return to AP mode now");
         WiFi.disconnect ();
         return 0;
      }
      delay (count * 2000);
   }
   return 0;
}

/*
 * return 1 if good answer
 *  0 if not good answer
 * -1 if not connected to wifi
 * -2 if server did not answer, timeout reached
 */
int GetRequestExt (char *ahost, char *request, char *data, int aport, char *answer, int TimeOutInSec, char *mem, int memsize)
{
   WiFiClient client;

   Debugf ("\nGet Request\nConnecting to: %s\nRequest: %s\nPort: %d\nData: %s\n", ahost, request, aport, data);

   if (mem)
      memset (mem, 0, memsize);

   if (!client.connect(ahost, aport))
   {
      Debugln ("Connection failed");
      return -1;
   }

   client.print ("GET /");
   client.print (request);
   client.print (data);
   client.println (" HTTP/1.1");
   client.print ("Host: ");
   client.println (ahost);
   client.println ("Cache-Control: no-cache");
   client.println ("Connection: Close");
   client.println ();
   client.println ();

   unsigned long timeout = millis();
   int to = TimeOutInSec * 1000;
   String line;

   while (client.available () == 0)
      if (millis() - timeout > to)
      {
         Serial.println(">>> Client Timeout !");
         client.stop();
         return -2;
      }

   char gotanswer = 0;
   int nbofchar = 0;

   // Read all the lines of the reply from server and print them to Serial
   char *p;
   char ret302 = 0;
   //String redirect;

   while (client.available ())
   {
      line = client.readStringUntil ('\r');
      Debug (line);
      if (strstr (line.c_str (), "Location: http:") ||
         (strstr (line.c_str (), "HTTP/") && strstr (line.c_str (), "30")))
      {
         Debugln ("\nRedirection detected!");
         ret302++;
      }

      if (answer && !gotanswer && (p = strstr (line.c_str (), answer)) != NULL)
      {
         if (mem)
            strncpy (mem, line.c_str(), memsize - 1);
         Debugf ("\n\n*** GotAnswer: %s ***\n", p);
         Debugln (line);
         gotanswer = 1;
      }
   }

/*   if (ret302 >= 2 && !gotanswer)
   {
    code to manage redirection, for example: hotspot with login page require username + password
   }
*/
   Debugln ("\nClosing connection");
   if (answer == NULL || gotanswer)
      return 1;
   return 0;
}

/*
 * return 1 if good answer or answer is NULL and we got reply from server
 * if answer is NULL, mem will not be filled with reply from server
 *  0 if not good answer
 * -1 if not connected to wifi
 * -2 if server did not answer, timeout reached
 */
int PostRequestExt (char *ahost, char *request, char *data, int aport, char *answer, int TimeOutInSec, char *mem, int memsize)
{
   WiFiClient client;

   Debugf ("\nPost Request\nConnecting to: %s\nRequest: %s\nPort: %d\n", ahost, request, aport);
   Debugf ("Data: %s\n", data);

   if (mem)
      memset (mem, 0, memsize);

   if (!client.connect(ahost, aport))
   {
      Debugln ("Connection failed");
      return -1;
   }

   client.print ("POST /");
   client.print (request);
   client.println (" HTTP/1.1");
   client.print ("Host: ");
   client.println (ahost);
   client.println ("Cache-Control: no-cache");
   client.println ("Content-Type: application/x-www-form-urlencoded");
   client.print ("Content-Length: ");
   client.println (strlen (data));
   client.println ("Connection: Close");
   client.println ();
   client.println ();
   client.println (data);

   unsigned long timeout = millis();
   int to = TimeOutInSec * 1000;
   String line;

   while (client.available () == 0)
      if (millis() - timeout > to)
      {
         Serial.println(">>> Client Timeout !");
         client.stop();
         return -2;
      }

   char gotanswer = 0;
   int nbofchar = 0;

   // Read all the lines of the reply from server, copy in mem and print them to Serial
   char *p;

   if (answer)
      Debugf ("\nWaiting for answer: %s\n\n", answer);

   while (client.available ())
   {
      line = client.readStringUntil ('\r');
      Debug (line);
      if (answer && !gotanswer && (p = strstr (line.c_str (), answer)) != NULL)
      {
         if (mem)
            strncpy (mem, line.c_str(), memsize - 1);
         Debugf ("\nGotAnswer: %s\n", p);
         Debugln (line);
         gotanswer = 1;
      }
   }

   Debugln ("\r\nClosing connection");
   if (answer == NULL || gotanswer)
      return 1;
   return 0;
}

void handleRoot()
{
   Debugln ("Root");
   char *buf2 = "
<form action=\"/wifilist\" method=\"get\"><button>Configure WiFi</button></form>
<form action=\"wifinoscan\" method=\"get\"><button>Configure WiFi (No Scan)</button></form>
<form action=\"/info\" method=\"get\"><button>Info</button></form>
<form action=\"/reset\" method=\"post\"><button>Reset</button></form>";

   String page = Header;
   page.replace ("{v}", EspName);
   page += "";
   page += EspName;
   page += buf2;
   page += Footer;
   server.send(200, "text/html", page);
}

int getRSSIasQuality(int RSSI)
{
   int quality = 0;

   if (RSSI <= -100)
      quality = 0;
   else if (RSSI >= -50)
      quality = 100;
   else
      quality = 2 * (RSSI + 100);

   return quality;
}

void handleWifiList ()
{
   Debugln ("Wifi selection");
   ListAP ();

   char *buf = "

";
   char *itemvar = "
{v} {r}%
";
   char *submit = "<form method='get' action='wifisave'>"
                  "<input id='s' name='s' length=32 placeholder='SSID'>
"
                  "<input id='p' name='p' length=64 type='password' placeholder='password'>
"
                  "<input id='e' name='e' length=128 placeholder='youremailaddress@domain.com'>

"
                  "<button type='submit'>save</button></form>

Scan";

   String page = Header;
   page.replace ("{v}", EspName);
   page += "";
   page += EspName;
   page += "";
   page += buf;

   String item;
   int quality;

   for (int i = 0; i < NbOfSsid; i++)
   {
      quality = getRSSIasQuality (WiFi.RSSI(i));

    //  if (_minimumQuality == -1 || _minimumQuality < quality)
      {
         item = itemvar;
         String rssiQ;
         rssiQ += quality;
         item.replace("{v}", WiFi.SSID(i));
         item.replace("{r}", rssiQ);
         if (WiFi.encryptionType(i) != ENC_TYPE_NONE)
            item.replace("{i}", "l");
         else
            item.replace("{i}", "");
         page += item;
      }
   }

   page += submit;
   page += Footer;
   server.send (200, "text/html", page);
}

void handleWifiSave ()
{
   Debugln ("Wifi save");

   char s [33];
   char p [65];
   char e [129];

   strcpy (s, server.arg("s").c_str());
   strcpy (p, server.arg("p").c_str());
   strcpy (e, server.arg("e").c_str());

   Debugf ("Received from client\nSsid: %s\nSsidPassword: %s\nEmail: %s\n", s, p, e);

   int ret = ConnectToWifi (s, p, 30);
   String page = Header;
   page.replace ("{v}", EspName);
   page += EspName;
   if (ret)
      page += "
Connection successfull!
Info saved!
";
   else
   {
      page += "
Unable to connect with this info:
";
      Debugln ("\nUnable to connect to wifi");
   }

   page += "Ssid: ";
   page += s;
   page += "
";

   page += "SsidPassword: ";
   page += p;
   page += "
";

   page += "Email: ";
   page += e;
   page += "
";

   if (!ret)
   {
      page += "Go back and rescan
";
      page += Footer;
      server.send(200, "text/html", page);
      state = STATE_AP_MODE;
      return;
   }

   page += "Check your email, you should receive an email soon!
";
   page += Footer;
   server.send(200, "text/html", page);

   strcpy (Ssid, s);
   strcpy (SsidPassword, p);
   strcpy (Email, e);

   SetEEpromInfo ();
   state = STATE_GET_INFO;
}

void handleReset ()
{
   Debugln ("Reset");

   String page = Header;
   page.replace ("{v}", EspName);
   page += EspName;
   page += " will reset in a few seconds";
   if (Ssid [0] && SsidPassword [0])
   {
      page += " and try to reconnect to wifi";
      state = STATE_SEND_MAIL_STARTED;
   }
   else
   {
      page += " and restart in Access Point mode";
      state = STATE_AP_MODE;
   }
   page += Footer;
   server.send(200, "text/html", page);

   ESP.reset();
   delay(2000);
}

void handleInfo ()
{
   Debugln ("Show Info");

   String page = Header;
   page.replace("{v}", "Info");

   page += "
";

   page += "
Chip ID

";
   page += ESP.getChipId();
   page += "
";

   page += "
Flash Chip ID

";
   page += ESP.getFlashChipId();
   page += "
";

   page += "
IDE Flash Size

";
   page += ESP.getFlashChipSize();
   page += " bytes
";

   page += "
Real Flash Size

";
   page += ESP.getFlashChipRealSize();
   page += " bytes
";

   page += "
Soft AP IP

";
   page += WiFi.softAPIP().toString();
   page += "
";

   page += "
Soft AP MAC

";
   page += WiFi.softAPmacAddress();
   page += "
";

   page += "
Station MAC

";
   page += WiFi.macAddress();
   page += "
";

   page += "
Memory Stored Info

";
   page += "Ssid: ";
   page += Ssid;
   page += "
";
   page += "SsidPassword: ";
   page += SsidPassword;
   page += "
";
   page += "Email: ";
   page += Email;
   page += "
";
   page += "
";

   page += "
";
   page += Footer;

   server.send(200, "text/html", page);
}

bool CheckPassword (char *p)
{
   for (int i = 0; p [i] != 0; i++)
      if (!((p [i] >= '0' && p [i] <= '9') ||
         (p [i] >= 'a' && p [i] <= 'z') ||
         (p [i] >= 'A' && p [i] <= 'Z')))
         return 0;
   return 1;
}

void StartInAPMode ()
{
   if (EspPassword [0] == 0 || strlen (EspPassword) < 8 || CheckPassword (EspPassword) == 0)
   {
      strcpy (EspPassword, EspDefaultPW);
      SetEEpromInfo ();
   }

   if (CheckPassword (SsidPassword) == 0)
   {
      strcpy (SsidPassword, "");
      SetEEpromInfo ();
   }

   WiFi.softAP (EspName, EspPassword);
   IPAddress myIP = WiFi.softAPIP();

   Debug ("\nStarting Access Point\nAP IP address: ");
   Debugln (myIP);
   server.on("/", handleRoot);
   server.on("/reset", handleReset);
   server.on("/info", handleInfo);
   server.on("/wifilist", handleWifiList);
   server.on("/wifisave", handleWifiSave);
   server.begin();
   Debugln ("HTTP server started");
   Debugf ("Must connect at: %s\nPassword: %s\n", EspName, EspPassword);
}

char encode[] =
{
  'A', 'B', 'C', 'D', 'E', 'F', 'G', 'H',
  'I', 'J', 'K', 'L', 'M', 'N', 'O', 'P',
  'Q', 'R', 'S', 'T', 'U', 'V', 'W', 'X',
  'Y', 'Z', 'a', 'b', 'c', 'd', 'e', 'f',
  'g', 'h', 'i', 'j', 'k', 'l', 'm', 'n',
  'o', 'p', 'q', 'r', 's', 't', 'u', 'v',
  'w', 'x', 'y', 'z', '0', '1', '2', '3',
  '4', '5', '6', '7', '8', '9', '+', '/'
};

long encode_base64 (const void *pdata, long len, char *code)
{
   unsigned char *s, *end;
   unsigned char *data = (unsigned char *) pdata;
   unsigned int x;
   long n;
   int i, j;

   end = data + len - 3;
   n = 0;

   for (s = data; s < end;)
   {
      x = *s++ << 24;
      x |= *s++ << 16;
      x |= *s++ << 8;

      *(code++) = encode[x >> 26];
      x <<= 6;
      *(code++) = encode[x >> 26];
      x <<= 6;
      *(code++) = encode[x >> 26];
      x <<= 6;
      *(code++) = encode[x >> 26];
      n += 4;
   }

   end += 3;

   x = 0;
   for (i = 0; s < end; i++)
      x |= *s++ << (24 - 8 * i);

   for (j = 0; j < 4; j++)
   {
      if (8 * i >= 6 * j)
      {
         *(code++) = encode [x >> 26];
         x <<= 6;
         n++;
      }
      else
      {
         *(code++) = '=';
         n++;
      }
   }

   *code = 0;
   return n;
}

void SetTime ()
{
   TimeSet = millis ();
}

unsigned long TimeDiff ()
{
   return (millis () - TimeSet);
}

void SetUpdateTime ()
{
   UpdateTimeSet = millis ();
}

unsigned long UpdateTimeDiff ()
{
   return (millis () - UpdateTimeSet);
}

int GetInfo (bool create)
{
   char *request = "getinfo.php?";
   int port = 80;
   char mem [256];
   char *sep = "!#";
   char code [128];
   String data;

   if (create)
      data = "create=1&iot=";
   else data = "create=0&iot=";
   encode_base64 (EspName, strlen (EspName), code);
   data += code;

   data += "&email=";
   encode_base64 (Email, strlen (Email), code);
   data += code;

   data += "&modpw=";
   encode_base64 (EspPassword, strlen (EspPassword), code);
   data += code;

   char *p = (char*) data.c_str ();

   int ret = GetRequestExt (ServerHost, request, p, port, "&Inf0", 30, mem, sizeof (mem));
   if (ret == -1 || ret == -2)
      return 0;

   Debugf ("Inf0 return in mem: %s\n", mem);
   if (strstr (mem, "&pending"))
      PendingMode = 1;
   else PendingMode = 0;

   p = strstr (mem, "&interval=");
   if (p)
   {
      p += 10;
      UpdateInterval = (atoi (p) * 1000);
      Debugf ("UpdateInterval set to: %d\n", UpdateInterval);
   }

   if (UpdateInterval < 30000)
   {
      Debugln ("UpdateInterval below 30 sec, set to 1 min.");
      UpdateInterval = 60000; // 1 minute
   }
   return ret;
}

int SendMail (char Option)
{
   //($use64, $mailtoe, $subjecte, $bodye, $fn, $buf) = split ('``!#`', $array);
   char *request = "smf.php";
   int port = 80;
   char mem [256];
   char *sep = "!#";
   char code [128];
   String data;

   encode_base64 (Email, strlen (Email), code);
   data = code; // mailto
   data += sep;

   // subject
   switch (Option)
   {
      case SENDMAIL_OPTION_STARTED:
         sprintf (mem, "%s: Started!", EspName);
         break;
      case SENDMAIL_OPTION_SENSOR1:
          sprintf (mem, "%s: Sensor Alert!", EspName);
         break;
   }

   encode_base64 (mem, strlen (mem), code);
   data += code;
   data += sep;

   // body
   switch (Option)
   {
      case SENDMAIL_OPTION_STARTED:
         strcpy (mem, "Info from web server has been readed\r\nModule updated!\r\n");
         break;
      case SENDMAIL_OPTION_SENSOR1:
         strcpy (mem, "Movement has been detected!");
         break;
   }

   encode_base64 (mem, strlen (mem), code);
   data += code;

   char *p = (char*) data.c_str ();

   // answer is Mai1~S3nt
   //                 | is number 3
   //              | is number 1
   int ret = PostRequestExt (ServerHost, request, p, port, "Mai1~S3nt", 30, mem, sizeof (mem));
   if (ret == -1 || ret == -2)
      return 0;
   return ret;

}

int count = 0;
int CountRequest = 0;
int PendingRequest = 0;
int MissedSendMail = 0;
void loop()
{
   int ret;

   switch (state)
   {
      case STATE_AP_MODE:
         // if no connection or no ssid or no password
         // then enter in AP mode, list AP and let the user select an AP from our page so
         // he can select an AP, type a password and an email address
         StartInAPMode ();
         SetTime ();
         state = STATE_WAIT_INPUT;
         break;

      case STATE_WAIT_INPUT:
         // wait the user to select an AP from a web page
         // the handleRoot function will set state to STATE_GET_INFO once we get ssid+password

         // if we have already a ssid & password and 5 minutes have elapsed
         // then try to connect again, maybe wifi came back
         if (Ssid [0] && SsidPassword [0] && TimeDiff () > 180000)
         {
            Debugln ("\nWas waiting for new AP info, but now time passed\nMust retry to connect to wifi again");
            if (TryToConnectToWifi (1))
            {
               state = STATE_GET_INFO;
               break;
            }
            state = STATE_AP_MODE;
            SetTime ();
         }
         else server.handleClient();
         break;

      case STATE_GET_INFO:
         if (WiFi.status () != WL_CONNECTED)
            if (!TryToConnectToWifi (3))
            {
               state = STATE_AP_MODE;
               break;
            }
         if ((ret = GetInfo (1)) == 1)
         {
            if (PendingMode)
            {
               state = STATE_PENDING_MODE;
               Debugln ("Going to: STATE_PENDING_MODE");
               PendingRequest = 0;
               SetTime ();
               break;
            }
            else
            {
               state = STATE_SEND_MAIL_STARTED;
               Debugln ("Going to: STATE_SEND_MAIL_STARTED");
               CountRequest = 0;
               break;
            }
         }
         if (++CountRequest > 2)
         {
            CountRequest = 0;
            if (ret == 0)
            {
               state = STATE_WAIT_FOR_SENSOR;
               SetUpdateTime ();
            }
            else state = STATE_AP_MODE;
            MissedSendMail++;
            Debugln ("Giving up to try to get info from server, return to SENSOR MODE now");
         }
         delay (CountRequest * 3000);
         break;

      case STATE_PENDING_MODE: // will check 15 times only (15 minutes), after will recreate the file on server
         if (TimeDiff () > 60000) // 1 min
         {
            SetTime ();
            if (GetInfo (0))
            {
               if (!PendingMode)
               {
                  state = STATE_SEND_MAIL_STARTED;
                  Debugln ("Got it activated\nGoing to STATE_SEND_MAIL_STARTED");
                  CountRequest = 0;
                  break;
               }
               Debugln ("Still in STATE_PENDING_MODE, user did not activate yet");
            }
            if (++PendingRequest >= 15)
            {
              state = STATE_GET_INFO;
              Debugln ("Did not get activated after 15 tries, giving up\nGoing to STATE_GET_INFO");
              break;
            }
            Debugln ("Waiting to get activated by the user");
         }
         break;

      case STATE_SEND_MAIL_STARTED:
         if (WiFi.status () != WL_CONNECTED)
            if (!TryToConnectToWifi (3))
            {
               state = STATE_AP_MODE;
               break;
            }
         if ((ret = SendMail (SENDMAIL_OPTION_STARTED)) == 1)
         {
            state = STATE_WAIT_FOR_SENSOR;
            SetUpdateTime ();
            CountRequest = 0;
            Debugln ("WiFi Disconnect\nGoing in WaitForSensor mode now");
            WiFi.disconnect ();
            break;
         }
         if (++CountRequest > 2)
         {
            CountRequest = 0;
            if (ret == 0)
            {
               state = STATE_WAIT_FOR_SENSOR;
               SetUpdateTime ();
            }
            else state = STATE_AP_MODE;
            MissedSendMail++;
            Debugln ("Giving up to try to send an email, return to SENSOR MODE now");
         }
         delay (CountRequest * 3000);
         break;

      case STATE_UPDATE_INFO:
         if (UpdateTimeDiff () > UpdateInterval)
         {
            Debugln ("Going to update info on/from server");
            if (WiFi.status () != WL_CONNECTED)
               TryToConnectToWifi (1);
            if (WiFi.status () == WL_CONNECTED)
               GetInfo (0);
         }

         SetUpdateTime ();
         state = STATE_WAIT_FOR_SENSOR;
         break;

      case STATE_WAIT_FOR_SENSOR:
         if (UpdateTimeDiff () > UpdateInterval)
         {
            state = STATE_UPDATE_INFO;
            break;
         }
         // code to do: check for whatever is connected to the esp
         break;
   }
}

void setup ()
{
   DebugInit ();
   delay (100);
   Debugln ();

   StartTime = millis ();
   Debug ("\nChip ID: ");
   Debugln (ESP.getChipId ());

   sprintf (EspName, "ESPINO-%X", ESP.getChipId ());
   Debugf ("EspName: %s\n", EspName);

   GetEEpromInfo ();
   if (EspPassword [0] == 0)
      strcpy (EspPassword, EspDefaultPW);
   if (Ssid [0] == 0 || SsidPassword [0] == 0 || Email [0] == 0)
      state = STATE_AP_MODE;
   else state = STATE_GET_INFO;
}

error: pathspec 'espmanager.ino' did not match any file(s) known to git


init electronique

init electronique

#include <Servo.h>

Servo servo;
const int buttonPin = 2; // broche du capteur PIR
int buttonState = 0; // etat de la sortie du capteur

void setup()
{
  servo.attach(9);
  pinMode(buttonPin, INPUT); //la broche du capteur est mise en entree
}

void loop()
{
  buttonState = digitalRead(buttonPin);//lecture du capteur
  if (buttonState == HIGH) //si quelquechose est detecte
  {
    for (int position = 0; position <= 180; position++) {
    servo.write(position);
    delay(15);
    }
  delay(1000);

  // Fait bouger le bras de 180° à 10°
  for (int position = 180; position >= 0; position--) {
    servo.write(position);
    delay(15);
    }
  delay(1000);
  }
}

error: pathspec 'electro/Projet/Projet.ino' did not match any file(s) known to git


New blink example

New blink example

#include <Arduino.h>
#include "Threads.h"

const int LED = 13;

volatile int blinkcode = 0;

void blinkthread() {
  while(1) {
    if (blinkcode) {
      for (int i=0; i<blinkcode; i++) {
        digitalWrite(LED, HIGH);
        threads.delay(150);
        digitalWrite(LED, LOW);
        threads.delay(150);
      }
      blinkcode = 0;
    }
    threads.yield();
  }
}

void setup() {
  delay(1000);
  pinMode(LED, OUTPUT);
  threads.addThread(blinkthread);
}

int count = 0;

void loop() {
  count++;
  blinkcode = count;
  delay(5000);
}

error: pathspec 'examples/Blink/Blink.ino' did not match any file(s) known to git


Create RS485_UnoR3_Master.ino

Create RS485_UnoR3_Master.ino

#include <SimpleModbusMaster.h>

#define baud 9600
#define timeout 1000
#define polling 200
#define retry_count 10

#define TxEnablePin 2

#define LED 9

#define TOTAL_NO_OF_REGISTERS 1

enum
{
  PACKET1,
  PACKET2,
  TOTAL_NO_OF_PACKETS // leave this last entry
};
int sensorValue = 0;        // value read from the pot
int outputValue = 0;

Packet packets[TOTAL_NO_OF_PACKETS];

unsigned int regs[TOTAL_NO_OF_REGISTERS];

void setup()
{
  modbus_construct(&packets[PACKET1], 1, READ_HOLDING_REGISTERS, 0, 1, 0);
  modbus_construct(&packets[PACKET2], 1, PRESET_MULTIPLE_REGISTERS, 1, 1, 0);

  modbus_configure(&Serial, baud, SERIAL_8N2, timeout, polling, retry_count, TxEnablePin, packets, TOTAL_NO_OF_PACKETS, regs);

  pinMode(LED, OUTPUT);
}

void loop()
{
  modbus_update();
  regs[0] = analogRead(0);
  analogWrite(LED, regs[0]>>2);
}

error: pathspec 'rs485/RS485_UnoR3_Master.ino' did not match any file(s) known to git


Add 10-key support

Add 10-key support

remote: Support for password authentication was removed on August 13, 2021.
remote: Please see https://docs.github.com/en/get-started/getting-started-with-git/about-remote-repositories#cloning-with-https-urls for information on currently recommended modes of authentication.
fatal: Authentication failed for 'https://github.com/mvines/futboard.git/'


Add Arduino firmware for right gripper-v6

#include <SPI.h>
#include <ros.h>
#include <std_msgs/Bool.h>
#include <std_msgs/Float64.h>
#include <std_msgs/UInt16.h>

unsigned long int temp_raw, pres_raw;
signed long int t_fine;

uint16_t dig_T1;
int16_t dig_T2;
int16_t dig_T3;
uint16_t dig_P1;
int16_t dig_P2;
int16_t dig_P3;
int16_t dig_P4;
int16_t dig_P5;
int16_t dig_P6;
int16_t dig_P7;
int16_t dig_P8;
int16_t dig_P9;

ros::NodeHandle nh; //write with IDE
// ros::NodeHandle_<ArduinoHardware, 1, 2, 512, 512> nh;

std_msgs::Float64 pressure_msg;
std_msgs::Bool bool_msg;
std_msgs::UInt16 r_finger_flex_msg;
std_msgs::UInt16 l_finger_flex_msg;

ros::Publisher pressure_pub("gripper_front/limb/right/pressure/state", &pressure_msg);
ros::Publisher state_pub("gripper_front/limb/right/pressure/grabbed/state", &bool_msg);
ros::Publisher r_finger_flex_pub("gripper_front/limb/right/r_finger_flex/state", &r_finger_flex_msg);
ros::Publisher l_finger_flex_pub("gripper_front/limb/right/l_finger_flex/state", &l_finger_flex_msg);

unsigned long  publisher_timer = 0;

void setup() {
    nh.getHardware()->setBaud(115200);
    nh.initNode();
    nh.advertise(pressure_pub);
    nh.advertise(state_pub);
    nh.advertise(r_finger_flex_pub);
    nh.advertise(l_finger_flex_pub);

    SPI.begin();
    SPI.setClockDivider(SPI_CLOCK_DIV8);
    initBME();
    readTrim();
}

void loop() {
    float temp_act = 0.0, press_act = 0.0;
    unsigned long int press_cal, temp_cal;

    if (millis() > publisher_timer) {
        // Pressure
        readData();
        temp_cal = calibration_T(temp_raw);
        press_cal = calibration_P(pres_raw);
        temp_act = (float)temp_cal / 100.0;
        press_act = (float)press_cal / 100.0;

        bool_msg.data = (press_act < 840);
        pressure_msg.data = press_act;

        state_pub.publish(&bool_msg);
        pressure_pub.publish(&pressure_msg);

        // Finger Flex
        r_finger_flex_msg.data = analogRead(A0);
        l_finger_flex_msg.data = analogRead(A1);
        r_finger_flex_pub.publish(&r_finger_flex_msg);
        l_finger_flex_pub.publish(&l_finger_flex_msg);

        publisher_timer = millis() + 100;
    }
    nh.spinOnce();
}

void initBME()
{
    digitalWrite(SS, LOW);
    SPI.transfer((0xF5 & 0x7F));
    SPI.transfer(0xA0);
    SPI.transfer((0xF4 & 0x7F));
    SPI.transfer(0x27);
    digitalWrite(SS, HIGH);
}

void readTrim()
{
    uint8_t data[32];
    int i;
    digitalWrite(SS, LOW);
    SPI.transfer((0x88 | 0x80));
    for (i = 0; i < 24; i++) {
        data[i] = SPI.transfer(0);
    }
    digitalWrite(SS, HIGH);
    delay(1);
    digitalWrite(SS, LOW);
    SPI.transfer((0xA1 | 0x80));
    data[24] = SPI.transfer(0);
    digitalWrite(SS, HIGH);
    delay(1);
    digitalWrite(SS, LOW);
    SPI.transfer((0xE1 | 0x80));
    for (i = 25; i < 32; i++) {
        data[i] = SPI.transfer(0);
    }
    digitalWrite(SS, HIGH);

    dig_T1 = (data[1] << 8) | data[0];
    dig_T2 = (data[3] << 8) | data[2];
    dig_T3 = (data[5] << 8) | data[4];
    dig_P1 = (data[7] << 8) | data[6];
    dig_P2 = (data[9] << 8) | data[8];
    dig_P3 = (data[11] << 8) | data[10];
    dig_P4 = (data[13] << 8) | data[12];
    dig_P5 = (data[15] << 8) | data[14];
    dig_P6 = (data[17] << 8) | data[16];
    dig_P7 = (data[19] << 8) | data[18];
    dig_P8 = (data[21] << 8) | data[20];
    dig_P9 = (data[23] << 8) | data[22];
}

void readData()
{
    uint32_t data[8];
    int i;
    digitalWrite(SS, LOW);
    SPI.transfer((0xF7 | 0x80));
    for (i = 0; i < 8; i++) {
        data[i] = SPI.transfer(0x00);
    }
    digitalWrite(SS, HIGH);
    pres_raw = (data[0] << 12) | (data[1] << 4) | (data[2] >> 4);
    temp_raw = (data[3] << 12) | (data[4] << 4) | (data[5] >> 4);
}

signed long int calibration_T(signed long int adc_T)
{

    signed long int var1, var2, T;
    var1 = ((((adc_T >> 3) - ((signed long int)dig_T1 << 1))) * ((signed long int)dig_T2)) >> 11;
    var2 = (((((adc_T >> 4) - ((signed long int)dig_T1)) * ((adc_T >> 4) - ((signed long int)dig_T1))) >> 12) * ((signed long int)dig_T3)) >> 14;

    t_fine = var1 + var2;
    T = (t_fine * 5 + 128) >> 8;
    return T;
}

unsigned long int calibration_P(signed long int adc_P)
{
    signed long int var1, var2;
    unsigned long int P;
    var1 = (((signed long int)t_fine) >> 1) - (signed long int)64000;
    var2 = (((var1 >> 2) * (var1 >> 2)) >> 11) * ((signed long int)dig_P6);
    var2 = var2 + ((var1 * ((signed long int)dig_P5)) << 1);
    var2 = (var2 >> 2) + (((signed long int)dig_P4) << 16);
    var1 = (((dig_P3 * (((var1 >> 2) * (var1 >> 2)) >> 13)) >> 3) + ((((signed long int)dig_P2) * var1) >> 1)) >> 18;
    var1 = ((((32768 + var1)) * ((signed long int)dig_P1)) >> 15);
    if (var1 == 0)
    {
        return 0;
    }
    P = (((unsigned long int)(((signed long int)1048576) - adc_P) - (var2 >> 12))) * 3125;
    if (P < 0x80000000)
    {
        P = (P << 1) / ((unsigned long int) var1);
    }
    else
    {
        P = (P / (unsigned long int)var1) * 2;
    }
    var1 = (((signed long int)dig_P9) * ((signed long int)(((P >> 3) * (P >> 3)) >> 13))) >> 12;
    var2 = (((signed long int)(P >> 2)) * ((signed long int)dig_P8)) >> 13;
    P = (unsigned long int)((signed long int)P + ((var1 + var2 + dig_P7) >> 4));
    return P;
}

error: pathspec 'jsk_arc2017_baxter/firmware/gripper_v6/sensor_manager_right/sensor_manager_right.ino' did not match any file(s) known to git


Simple Sketch. This Sketch spins the wheels.

#include <Servo.h>

Servo m_left;
Servo m_right;

void setup()
{
  m_left.attach(9);
  m_right.attach(10);
}

void loop()
{
  // Spin !!!
  m_right.write(180);
  m_left.write(0);
}

error: pathspec 'SOURCE/sumobot/sumobot.ino' did not match any file(s) known to git


Latest version for Backup

Latest version for Backup

error: pathspec 'Tempreature' did not match any file(s) known to git
error: pathspec 'Datalogger.ino' did not match any file(s) known to git


Code-Lock V0.1

Code-Lock V0.1

#include <Key.h>
#include <Keypad.h>

/******************************
***INICIALIZACIA KLAVESTNICE***
*******************************/

const byte rows = 4;
const byte cols = 4;
char keys[rows][cols] =
{
{'1','2','3','A'},
{'4','5','6','B'},
{'7','8','9','C'},
{'*','0','#','D'}
};
byte rowsPin[rows] = {50, 51, 52, 53};
byte colsPin[cols] = {46, 47, 48, 49};
Keypad keyPad = Keypad(makeKeymap(keys), rowsPin, colsPin, rows, cols);

void setup()
{
 Serial.begin(9600);
}

void loop()
{
char charRead = keyPad.getKey();
if (charRead)
{
Serial.println(charRead);
}
}

error: pathspec 'opening-modules/code-lock/src/main/main.ino' did not match any file(s) known to git


Arduino Uno Wifi only works with thingspeak... testing

error: pathspec 'Documentation/unit' did not match any file(s) known to git
error: pathspec 'tests/ciao_test/ciao_test.ino' did not match any file(s) known to git


Add cert test application

Add cert test application

/*******************************************************************************
 * Copyright (c) 2019 Terry Moore, MCCI
 *
 * Permission is hereby granted, free of charge, to anyone
 * obtaining a copy of this document and accompanying files,
 * to do whatever they want with them without any restriction,
 * including, but not limited to, copying, modification and redistribution.
 * NO WARRANTY OF ANY KIND IS PROVIDED.
 *
 *******************************************************************************/

#include <lmic.h>
#include <hal/hal.h>
#include <SPI.h>
#include <arduino_lmic_hal_boards.h>

//
// For certification tests with the RWC5020A, we use the default addresses
// from the tester.
//

// This EUI must be in little-endian format, so least-significant-byte
// first.  This corresponds to 0x0000000000000001
static const u1_t PROGMEM APPEUI[8]= { 1, 0, 0, 0, 0, 0, 0, 0 };
void os_getArtEui (u1_t* buf) { memcpy_P(buf, APPEUI, 8);}

// This should also be in little endian format, see above.
// This corresponds to 0x0000000000000001
static const u1_t PROGMEM DEVEUI[8]= { 1, 0, 0, 0, 0, 0, 0, 0 };
void os_getDevEui (u1_t* buf) { memcpy_P(buf, DEVEUI, 8);}

// This key should be in big endian format (or, since it is not really a
// number but a block of memory, endianness does not really apply).
static const u1_t PROGMEM APPKEY[16] = { 0, 0, 0, 0, 0, 0, 0, 0,  0, 0, 0, 0, 0, 0, 0, 2 };
void os_getDevKey (u1_t* buf) {  memcpy_P(buf, APPKEY, 16);}

static uint8_t mydata[] = "Hello, world!";
static osjob_t sendjob;

// Schedule TX every this many seconds (might become longer due to duty
// cycle limitations).
const unsigned TX_INTERVAL = 60;

lmic_event_cb_t myEventCb;

void myEventCb(void *pUserData, ev_t ev) {
    Serial.print(os_getTime());
    Serial.print(": ");
    switch(ev) {
        case EV_SCAN_TIMEOUT:
            Serial.println(F("EV_SCAN_TIMEOUT"));
            break;
        case EV_BEACON_FOUND:
            Serial.println(F("EV_BEACON_FOUND"));
            break;
        case EV_BEACON_MISSED:
            Serial.println(F("EV_BEACON_MISSED"));
            break;
        case EV_BEACON_TRACKED:
            Serial.println(F("EV_BEACON_TRACKED"));
            break;
        case EV_JOINING:
            Serial.println(F("EV_JOINING"));
            break;
        case EV_JOINED:
            Serial.println(F("EV_JOINED"));
            {
              u4_t netid = 0;
              devaddr_t devaddr = 0;
              u1_t nwkKey[16];
              u1_t artKey[16];
              LMIC_getSessionKeys(&netid, &devaddr, nwkKey, artKey);
              Serial.print("netid: ");
              Serial.println(netid, DEC);
              Serial.print("devaddr: ");
              Serial.println(devaddr, HEX);
              Serial.print("artKey: ");
              for (int i=0; i<sizeof(artKey); ++i) {
                if (i != 0)
                  Serial.print("-");
                Serial.print(artKey[i], HEX);
              }
              Serial.println("");
              Serial.print("nwkKey: ");
              for (int i=0; i<sizeof(nwkKey); ++i) {
                      if (i != 0)
                              Serial.print("-");
                      Serial.print(nwkKey[i], HEX);
              }
              Serial.println("");
            }
            // Disable link check validation (automatically enabled
            // during join, but because slow data rates change max TX
            // size, we don't use it in this example.
            LMIC_setLinkCheckMode(0);
            break;
        /*
        || This event is defined but not used in the code. No
        || point in wasting codespace on it.
        ||
        || case EV_RFU1:
        ||     Serial.println(F("EV_RFU1"));
        ||     break;
        */
        case EV_JOIN_FAILED:
            Serial.println(F("EV_JOIN_FAILED"));
            break;
        case EV_REJOIN_FAILED:
            Serial.println(F("EV_REJOIN_FAILED"));
            break;
            break;
        case EV_TXCOMPLETE:
            Serial.println(F("EV_TXCOMPLETE (includes waiting for RX windows)"));
            if (LMIC.txrxFlags & TXRX_ACK)
              Serial.println(F("Received ack"));
            // Schedule next transmission
            os_setTimedCallback(&sendjob, os_getTime()+sec2osticks(TX_INTERVAL), do_send);
            break;
        case EV_LOST_TSYNC:
            Serial.println(F("EV_LOST_TSYNC"));
            break;
        case EV_RESET:
            Serial.println(F("EV_RESET"));
            break;
        case EV_RXCOMPLETE:
            // data received in ping slot
            Serial.println(F("EV_RXCOMPLETE"));
            break;
        case EV_LINK_DEAD:
            Serial.println(F("EV_LINK_DEAD"));
            break;
        case EV_LINK_ALIVE:
            Serial.println(F("EV_LINK_ALIVE"));
            break;
        /*
        || This event is defined but not used in the code. No
        || point in wasting codespace on it.
        ||
        || case EV_SCAN_FOUND:
        ||    Serial.println(F("EV_SCAN_FOUND"));
        ||    break;
        */
        case EV_TXSTART:
            Serial.println(F("EV_TXSTART"));
            break;
        default:
            Serial.print(F("Unknown event: "));
            Serial.println((unsigned) ev);
            break;
    }
}

lmic_rxmessage_cb_t myRxMessageCb;

void myRxMessageCb(
	void *pUserData,
	uint8_t port,
	const uint8_t *pMessage,
	size_t nMessage
	)
	{
	Serial.print(F("Received message on port "));
	Serial.print(port);
	Serial.print(F(": "));
	Serial.print(nMessage);
	Serial.println(F(" bytes"));
	}

void do_send(osjob_t* j){
    // Check if there is not a current TX/RX job running
    if (LMIC.opmode & OP_TXRXPEND) {
        Serial.println(F("OP_TXRXPEND, not sending"));
    } else {
        // Prepare upstream data transmission at the next possible time.
        LMIC_setTxData2(1, mydata, sizeof(mydata)-1, 0);
        Serial.println(F("Packet queued"));
    }
    // Next TX is scheduled after TX_COMPLETE event.
}

void myFail(const char *pMessage) {
    pinMode(LED_BUILTIN, OUTPUT);
    for (;;) {
        // alert
        Serial.println(pMessage);
        // flash lights, sleep.
        for (int i = 0; i < 5; ++i) {
            digitalWrite(LED_BUILTIN, 1);
            delay(100);
            digitalWrite(LED_BUILTIN, 0);
            delay(900);
        }
    }
}

void setup() {
    delay(5000);
    while (! Serial)
        ;
    Serial.begin(115200);
    Serial.println(F("Starting"));

    // LMIC init using the computed target
    const lmic_pinmap *pPinMap = Arduino_LMIC::GetPinmap_ThisBoard();

    // don't die mysteriously; die noisily.
    if (pPinMap == nullptr) {
        myFail("board not known to library; add pinmap or update getconfig_thisboard.cpp");
    }

    // now that we have a pinmap, initalize the low levels accordingly.
    os_init_ex(pPinMap);

    // Reset the MAC state. Session and pending data transfers will be discarded.
    LMIC_reset();

    // Reset resets *everything*, so we need to register after the LMIC_reset().
    if (! (LMIC_registerRxMessageCb(myRxMessageCb, /* userData */ nullptr) &&
           LMIC_registerEventCb(myEventCb, /* userData */ nullptr))) {
        myFail("couldn't register callbacks");
    }

    LMIC_setLinkCheckMode(0);
    LMIC_setDrTxpow(DR_SF7, 14);
    LMIC_selectSubBand(1);

    // Start job (sending automatically starts OTAA too)
    do_send(&sendjob);
}

void loop() {
    os_runloop_once();
}

error: pathspec 'examples/rwccert-otaa-halconfig-us915/rwccert-otaa-halconfig-us915.ino' did not match any file(s) known to git


This works. Complexerizing.

This works. Complexerizing.

error: pathspec 'Motor' did not match any file(s) known to git
error: pathspec 'Speed/testInterrupts2/testInterrupts2.ino' did not match any file(s) known to git


This looks good, and it compiles, but it's warm out and it's bbq time so I'll have to test it in the lab later. Added statistical magic, lots of text, and automatic continuation of the script (just wait a bit and it'll keep going). I'll test it soon!


Premier prototype de la station de chargement. Les numeros de pins ne sont pas bons, j'attends le breadboard pour avoir les vrais. Aussi, j'ai mis un servo comme placeholder pour l'ascenseur en attendant, mais ça risque de changer.

#include <Servo.h>

//////// Pins ////////
#define ELEVATOR_SWITCH_PIN     46
#define DOOR_SWITCH_PIN         50
#define ELEVATOR_PIN            4
#define DOOR_PIN                5
#define CONVEYOR1_PIN           6
#define CONVEYOR2_PIN           7

//////// PWM ////////
#define ELEVATOR_STOP  1500
#define ELEVATOR_RUN   1400
#define DOOR_STOP      1500
#define DOOR_RUN       1400
#define CONVEYOR_RUN   1400
#define CONVEYOR_STOP  1500

struct LimitSwitch {
    const uint8_t PIN;
    LimitSwitch(uint8_t PIN) : PIN(PIN), active(false), lastStatusChange(0) {};
    void Setup() { pinMode(PIN, INPUT_PULLUP); };
    const bool IsActive() const { return active; };
    const bool ReadInput()
    {
        active = (digitalRead(PIN) == 0);
        return IsActive();
    };

    unsigned long lastStatusChange;
    const static int DEBOUNCE_TIME = 100;

    void WaitForPress(){
      while(millis() < lastStatusChange + DEBOUNCE_TIME); //Debounce
      while(digitalRead(PIN) == 0);
      lastStatusChange = millis();
    }

    void WaitForRelease(){
      while(millis() < lastStatusChange + DEBOUNCE_TIME); //Debounce
      while(digitalRead(PIN) != 0);
      lastStatusChange = millis();
    }

private:
    bool active;
};

//////// Variables ////////
LimitSwitch elevatorSwitch(ELEVATOR_SWITCH_PIN);
LimitSwitch doorSwitch(DOOR_SWITCH_PIN);
Servo elevator;
Servo door;
Servo conveyor1;
Servo conveyor2;

void setup() {
  Serial.begin(9600);

  elevatorSwitch.Setup();
  doorSwitch.Setup();

  elevator.attach(ELEVATOR_PIN);
  elevator.writeMicroseconds(ELEVATOR_STOP);

  door.attach(DOOR_PIN);
  door.writeMicroseconds(DOOR_STOP);

  conveyor1.attach(CONVEYOR1_PIN);
  Serial.print("Starting fixed conveyor belt.");
  conveyor1.writeMicroseconds(CONVEYOR_RUN);

  conveyor2.attach(CONVEYOR2_PIN);
  conveyor2.writeMicroseconds(CONVEYOR_STOP);
}

void loop(){
  // La porte est ouverte
  if ( ! doorSwitch.ReadInput() )
  {
    Serial.print("Elevator door opened. Closing...");
    // On la ferme et on attend
    door.writeMicroseconds(DOOR_RUN);
    doorSwitch.WaitForPress();
    door.writeMicroseconds(DOOR_STOP);
    Serial.print("Elevator door closed.");
  }

  // L'ascenseur n'est pas en haut
  if ( ! elevatorSwitch.ReadInput() )
  {
    // Arreter le tapis sur l'ascenseur (au cas ou il roulerait...)
    conveyor2.writeMicroseconds(CONVEYOR_STOP);
    // On monte l'ascenseur et on attend
    Serial.print("Starting elevator.");
    elevator.writeMicroseconds(ELEVATOR_RUN);
    elevatorSwitch.WaitForPress();
    // Arreter l'ascenseur
    elevator.writeMicroseconds(ELEVATOR_STOP);
    Serial.print("Stopping elevator.");
  }

  // Demarrer le tapis de l'ascenseur
  Serial.print("Starting elevator's conveyor belt.");
  conveyor2.writeMicroseconds(CONVEYOR_RUN);

}

error: pathspec 'Arduino/LoadingStation/LoadingStation.ino' did not match any file(s) known to git


Lab 9 done

Lab 9 done

/*
  LiquidCrystal Library - Serial Input

  Demonstrates the use a 16x2 LCD display.  The LiquidCrystal
  library works with all LCD displays that are compatible with the
  Hitachi HD44780 driver. There are many of them out there, and you
  can usually tell them by the 16-pin interface.

  This sketch displays text sent over the serial port
  (e.g. from the Serial Monitor) on an attached LCD.

  The circuit:
   LCD RS pin to digital pin 12
   LCD Enable pin to digital pin 11
   LCD D4 pin to digital pin 5
   LCD D5 pin to digital pin 4
   LCD D6 pin to digital pin 3
   LCD D7 pin to digital pin 2
   LCD R/W pin to ground
   10K resistor:
   ends to +5V and ground
   wiper to LCD VO pin (pin 3)

  Library originally added 18 Apr 2008
  by David A. Mellis
  library modified 5 Jul 2009
  by Limor Fried (http://www.ladyada.net)
  example added 9 Jul 2009
  by Tom Igoe
  modified 22 Nov 2010
  by Tom Igoe

  This example code is in the public domain.

  http://www.arduino.cc/en/Tutorial/LiquidCrystalSerial
*/

// include the library code:
#include <LiquidCrystal.h>
#include <avr/interrupt.h>
// initialize the library with the numbers of the interface pins
LiquidCrystal lcd(48, 46, 44, 42, 40, 38, 36, 34, 32, 30, 28);
int __counter = 0;

//arduino runs the setup function first, then the loop function below
void setup() {
  pinMode(24, OUTPUT); //K
  pinMode(26, OUTPUT); //A
  pinMode(54, OUTPUT); //VSS
  pinMode(52, OUTPUT); //VDD
  pinMode(50, OUTPUT); //Contrasty pin

  // digitalWrite(50, LOW);
  digitalWrite(24, LOW); //Backlight
  digitalWrite(26, HIGH); //Backlight
  digitalWrite(54, LOW); //GND
  digitalWrite(52, HIGH); //VDD
  // set up the LCD's number of columns and rows:
  lcd.begin(16, 2);
  // initialize the serial communications:
  Serial.begin(9600);
  // Timer0 is used for millis() - we'll just interrupt
  // in the middle and call the compA
  OCR0A = 0x01;
  TIMSK0 |= _BV(OCIE0A);

  Serial.setTimeout(1);
}

SIGNAL(TIMER0_COMPA_vect)
{
   __counter++;
   if (__counter > 14){
      digitalWrite(50,HIGH);
      __counter = 0;
   }
   else if (__counter > 3){
      digitalWrite(50, LOW);
   }
}

int min_ = -1;
int sec_ = -1;

//Must have input be of form t\d\d\d\d
void setTimer(String input) {

  //Invalid input
  if(input[0] != 't') {
    Serial.print("Invalid input\n");
    return;
  }

  //Else define min and sec
  min_ = input.substring(1,3).toInt();
  sec_ = input.substring(3,5).toInt();
}

//Assume 1 second has passed
void increaseTime() {
  if (sec_ == -1 || min_ == -1) return;
  sec_++;
  if (sec_ > 59) {
    sec_ = 0;
    min_++;
  }
  if (min_ > 59) {
    min_ = 0;
  }
}

int timeElapsed = -1;

//Here is where your code goes. Arduino runs this function in an infinite loop after running the setup function
void loop() {

  if (timeElapsed == -1) { timeElapsed = millis(); }

  String input_ = Serial.readString();// read a string sent from the computer
  Serial.print(input_);//prints hello world to the serial monitor

  //Stop if needed, otherwise do waht was requested.
  if (input_ == "Stop timer") {
    Serial.print("Stopped");
    min_  = sec_ = -1;
  }
  else if (input_ != "") {
    setTimer(input_);
  }

  //return cursor to starting position
  lcd.home();

  //clear the lcd screen
  lcd.clear();

  //displays a String on the lcd screen. You can also print a String object
  lcd.print("Blobby is god!");

  //sets the x,y position of the cursor. In this case we move the cursor to the second line.
  lcd.setCursor(1, 1);
  lcd.print("Time: ");

  if (min_ != -1 && sec_ != -1) {
    lcd.print(min_);
    lcd.print(":");
    if (sec_ < 10) { lcd.print("0"); }
    lcd.print(sec_);
  }

  //Increase the time
  increaseTime();

  //sleep for .5 seconds
  int tmp = (500-(millis() - timeElapsed));
  delay(tmp>=0?tmp:0);

  //Blink if needed
  if (!(min_ != -1 && sec_ != -1)) { lcd.print("1200"); }
  tmp = (1000-(millis() - timeElapsed));

  //sleep for .5
  delay(tmp>=0?tmp:0);
  timeElapsed = millis();

}

error: pathspec 'Lab9/arduino_lab_lcd_ex/arduino_lab_lcd_ex.ino' did not match any file(s) known to git


make it faster!!!!

make it faster!!!!

remote: Support for password authentication was removed on August 13, 2021.
remote: Please see https://docs.github.com/en/get-started/getting-started-with-git/about-remote-repositories#cloning-with-https-urls for information on currently recommended modes of authentication.
fatal: Authentication failed for 'https://github.com/telekom/dthack17.git/'