new communication system

new communication system

--- resilient_network/resilient_network.ino
+++ resilient_network/resilient_network.ino
@@ -5,8 +5,8 @@

 #define leds1pin 11
 #define leds2pin 3
-#define button1pin 2
-#define button2pin 4
+#define button1pin 2 // isSource jumper
+#define button2pin 4 // alert button

 #define SERIAL_DEBUG true

@@ -16,9 +16,14 @@
 #define NUM_CONN 3

 SoftwareSerial* bus[NUM_CONN];
-
 int RX[NUM_CONN] = {A1, A3, A5};
 int TX[NUM_CONN] = {A0, A2, A4};
+volatile uint8_t *rxPortRegister[NUM_CONN];
+uint8_t rxBitMask[NUM_CONN];
+int activeBus = -1;
+unsigned long listenStartTime = 0;
+#define listenTimeout 20
+
 int coil[NUM_CONN] = {6, 5, 10}; // magnets
 int distanceToSource[NUM_CONN] = {99, 99, 99};
 int shortestDistanceToSource;
@@ -30,8 +35,9 @@
 void sendEnergy() {
   if(SERIAL_DEBUG) Serial.println("send energy");
   // source sends energy, as 0, meaning 0 distance to source
-  char distance = 0;
-  for (int i=0; i<NUM_CONN; i++) bus[i]->write(distance);
+  // Note: using distance 1, because initial pulse is read as 0
+  char distance = 1;
+  for (int i=0; i<NUM_CONN; i++) txWrite(i, distance);
   addTimer(100, sendEnergy);
 }

@@ -53,8 +59,7 @@

 void dropConnector() {
   // send out message that we're going to drop a connector
-  char c = DROPPING_CONNECTOR;
-  for (int i=0; i<NUM_CONN; i++) bus[i]->write(c);
+  for (int i=0; i<NUM_CONN; i++) txWrite(i, DROPPING_CONNECTOR);

   // pick random connected connector to drop
   // count number of ports with a low distance to source
@@ -96,8 +101,8 @@
   if (shortestDistanceToSource<99) {
     if (!lampState) switchLampOn();
     // send shortest distance to ports with a higher distance
-    for (int i =0; i<NUM_CONN; i++) if (distanceToSource[i] > shortestDistanceToSource) bus[i]->write(shortestDistanceToSource);
-    addTimer(100, processEnergy);
+    for (int i =0; i<NUM_CONN; i++) if (distanceToSource[i] > shortestDistanceToSource) txWrite(i, shortestDistanceToSource);
+    addTimer(500, processEnergy);
   }
   // if not, switch off the lamp and drop connectors if we were cut out
   else {
@@ -109,13 +114,106 @@
   }

   for (int i=0; i<NUM_CONN; i++) distanceToSource[i] = 99;
+  //addTimer(50, processEnergy);
+}
+
+uint8_t rxRead(int index) {
+  return *rxPortRegister[index] & rxBitMask[index];
+}
+
+void txWrite(int index, int value) {
+  // writeCounter++;
+  // if(writeCounter < MAX_WRITES) return;
+  if(SERIAL_DEBUG) {
+    Serial.print("w");
+    Serial.println(index);
+  }
+  // begin with pulse so other side can start listening
+  digitalWrite(TX[index], LOW);
+  delay(2);
+  digitalWrite(TX[index], HIGH);
+  bus[index]->write(value);
+}
+
+void setActiveBus(int index) {
+  if(SERIAL_DEBUG) {
+    Serial.print("l");
+    Serial.println(index);
+  }
+  activeBus = index;
+  listenStartTime = millis();
+  bus[index]->listen();
+}
+
+void readActiveBus() {
+  while(bus[activeBus]->available()) {
+    if(SERIAL_DEBUG) {
+      Serial.print("a");
+      Serial.println(activeBus);
+    }
+    int message = int(bus[activeBus]->read());
+    if(message != 0) {
+      if(SERIAL_DEBUG) {
+        Serial.print(activeBus);
+        Serial.print(": ");
+        Serial.println(message);
+      }
+      parseMessage(activeBus, message);
+      activeBus = -1;
+      break;
+    }
+  }
+  if (millis()-listenStartTime > listenTimeout) {
+    if(SERIAL_DEBUG) {
+      Serial.print("t");
+      Serial.println(activeBus);
+    }
+    activeBus = -1;
+  }
+}
+
+void parseMessage(int busIndex, int message) {
+  switch(message) {
+    case ALERT: // button is pressed
+      if (!isSource && !alertState) {
+        // set alert state and set random timer
+        alertState = true;
+        alertTimer = addTimer(random(1000, 5000), dropConnector);
+        // propagate signal though network
+        for (int j=0; j<NUM_CONN; j++) if (j!=busIndex) txWrite(j, ALERT);
+      }
+      break;
+    case DROPPING_CONNECTOR: // some connector in the network is dropped
+      if(alertState) {
+        // relax alert state and timer
+        removeTimer(alertTimer); // cancel dropping connector
+        alertState = false;
+        // propagate signal though network
+        for (int j=0; j<NUM_CONN; j++) if (j!=busIndex) txWrite(j, DROPPING_CONNECTOR);
+      }
+      break;
+    default: // distance to source
+      if (!isSource) {
+        // if new distance is shorter, take that as distance to source for this port
+        if (message<distanceToSource[busIndex]+1) distanceToSource[busIndex] = message+1;
+        // if we are not connected (yet) and a new distance was received start timer to process energy
+        // (hopefully this does enhances asynchronous updating between the nodes)
+        // ToDo: why use timer here? can't it get triggered to much, shouldn't this simply debounce? why not call on fixed interval?
+        if (shortestDistanceToSource == 99) addTimer(10, processEnergy);
+      }
+  }
 }

 void setup() {
   // set up pins
   for (int i=0; i<NUM_CONN; i++) {
     bus[i] = new SoftwareSerial(RX[i], TX[i]);
+    bus[i]->begin(115200); //(9600); //1200
     pinMode(coil[i], OUTPUT);
+
+    uint8_t port = digitalPinToPort(RX[i]);
+    rxPortRegister[i] = portInputRegister(port);
+    rxBitMask[i] = digitalPinToBitMask(RX[i]);
   }
   pinMode(leds1pin, OUTPUT);
   pinMode(leds2pin, OUTPUT);
@@ -156,47 +254,19 @@
     if (!digitalRead(button2pin)) {
       if(SERIAL_DEBUG) Serial.println("alert");
       char c = ALERT;
-      for (int i=0; i<NUM_CONN; i++) bus[i]->write(c);
+      for (int i=0; i<NUM_CONN; i++) txWrite(i, ALERT);
     }
   }

   // check all lines for incoming data
-  for (int i=0;i<NUM_CONN;i++) if(bus[i]->available()) {
-    char c = bus[i]->read();
-    if(SERIAL_DEBUG) {
-      Serial.print(i);
-      Serial.print(": ");
-      Serial.println(int(c));
-    }
-    switch(c) {
-      case ALERT: // button is pressed
-        if (!isSource && !alertState) {
-          // set alert state and set random timer
-          alertState = true;
-          alertTimer = addTimer(random(1000, 5000), dropConnector);
-          // propagate signal though network
-          for (int j=0; j<NUM_CONN; j++) if (j!=i) bus[j]->write(c);
-        }
-        break;
-      case DROPPING_CONNECTOR: // some connector in the network is dropped
-        if(alertState) {
-          // relax alert state and timer
-          removeTimer(alertTimer); // cancel dropping connector
-          alertState = false;
-          // propagate signal though network
-          for (int j=0; j<NUM_CONN; j++) if (j!=i) bus[j]->write(c);
-        }
-        break;
-      default: // distance to source
-        if (!isSource) {
-          // if new distance is shorter, take that as distance to source for this port
-          if (c<distanceToSource[i]+1) distanceToSource[i] = c+1;
-          // if we are not connected (yet) and a new distance was received start timer to process energy
-          // (hopefully this does enhances asynchronous updating between the nodes)
-          // ToDo: why use timer here? can't it get triggered to much, shouldn't this simply debounce? why not call on fixed interval?
-          if (shortestDistanceToSource == 99) addTimer(10, processEnergy);
-        }
-    }
+  if (activeBus==-1) {
+    for (int i=0; i<NUM_CONN; i++) {
+      if (!rxRead(i)) {
+        setActiveBus(i);
+      }
+    }
+  } else {
+    readActiveBus();
   }

   // update timed processes


Just some version defines stuff.

Just some version defines stuff.

Merge branch 'master' of github.com:floathub/device

--- mega/mega.ino
+++ mega/mega.ino
@@ -505,13 +505,14 @@
   //   	Or a uBlox NEO-6M
   //

+
   Serial3.println("$PUBX,40,GLL,0,0,0,0,0,0*5C");
   Serial3.println("$PUBX,40,GGA,0,1,0,0,0,0*5B");
   Serial3.println("$PUBX,40,GSA,0,0,0,0,0,0*4E");
   Serial3.println("$PUBX,40,RMC,0,1,0,0,0,0*46");
   Serial3.println("$PUBX,40,GSV,0,0,0,0,0,0*59");
   Serial3.println("$PUBX,40,VTG,0,0,0,0,0,0*5E");
-
+
   //
   //	Assuming a NEO-6M, try and set it to "at-sea" mode
   //
@@ -552,7 +553,6 @@
   */

-
   uint8_t configure_gps_command[] = {
     0xB5, 0x62,			// Ublox "sync" characters
     0x06, 0x24, 		// Message class and ID (class is configuration, id is navigation confiuration
@@ -581,6 +581,7 @@
   }
   Serial3.println();

+
   /*
   byte gps_set_sucess = 0 ;
   while(!gps_set_sucess)
@@ -1641,6 +1642,14 @@
             parse_gps_buffer_as_gga();
 	  }
         }
+        #ifdef GPS_DEBUG_ON
+        else
+	{
+          debug_info(F("Other GPS sentence ----------"));
+	  debug_info(gps_read_buffer);
+          debug_info(F("------------------ ----------"));
+	}
+        #endif
       }
       gps_read_buffer = "";
     }


fixed pointer bug

fixed pointer bug

--- client/client.ino
+++ client/client.ino
@@ -81,8 +81,11 @@
   /* go trough all the button and check which one was pressed */
   for ( i = 2; i <= 6; i++ )
     if ( digitalRead( i ) ) *button = i; else continue;
-  Serial.print( "button was pressed, nr " );
-  Serial.println( *button );
+  if ( *button != 0 ) {
+    Serial.print( "button was pressed, nr " );
+    Serial.println( *button );
+  }
+
   return SUCCESS;
 }

@@ -98,7 +101,7 @@
   /* when nothing was received */
   if ( !Mirf.dataReady() ) return 1;
   byte b;
-  Mirf.getData( &b );
+  Mirf.getData( (byte *) b );
   /* according to our status we save the received byte and go to next state */
   switch ( rx_stat ) {
     case 0: rx_message.destination = b; rx_stat = 1; break;
@@ -125,10 +128,10 @@
   tx_message.checksum ^= tx_message.source;
   tx_message.checksum ^= tx_message.data;
   /* Send the data packet */
-  Mirf.send( &tx_message.destination );
-  Mirf.send( &tx_message.source );
-  Mirf.send( &tx_message.data );
-  Mirf.send( &tx_message.checksum );
+  Mirf.send( (byte *) tx_message.destination );
+  Mirf.send( (byte *) tx_message.source );
+  Mirf.send( (byte *) tx_message.data );
+  Mirf.send( (byte *) tx_message.checksum );

   /* Wait for data to be transmitted */
   while ( Mirf.isSending() );
@@ -162,19 +165,21 @@
 }

 void loop() {
-  uint8_t button;
-  readButtons( &button );
+  //uint8_t button;
+  //readButtons( &button );
   /* Wait for button to be pressed, TODO: implement interrupt */
-  if ( button > NO_BUTTON ) {
+  /*if ( button > NO_BUTTON ) {
     digitalWrite( 9, HIGH );
-    Serial.println( "Finished sending!" );
-  }
+    delay(1000);
+  }*/

   /* transmit and receive acknowledgement */
-  //transmitPacket();
-  //timeoutReceive();
+  transmitPacket();
+  while( !Mirf.dataReady() );
+  if ( timeoutReceive() == SUCCESS )
+    Serial.println( "Verification received!" );

   /* don't freeze the MCU */
-  delay( 100 );
+  delay( 100000 );
 }


bug fix

bug fix

--- client/client.ino
+++ client/client.ino
@@ -137,6 +137,7 @@
         //the rest => blink slow
         if(atoi(p.id) == atoi(deviceId)) {
           statePending = false;
+          digitalWrite(ledStatePin, HIGH);
         } else {
           ledStateInterval = 500;
           statePending = true;


Update variables

Update variables

--- Arduino/Arduino.ino
+++ Arduino/Arduino.ino
@@ -10,9 +10,8 @@
 Servo leftRight;
 Servo upDown;

-int pos = 90;    // variable to store the servo position
-int ByteReceived;
-int Change = 0;
+int pos = 90;       // variable to store the servo position
+int ByteReceived;   // store byte recieved via serial

 void setup() {


Delete AuroraInverter2.ino

Delete AuroraInverter2.ino

--- AuroraInverter2.ino
+++ AuroraInverter2.ino
@@ -1,193 +0,0 @@
-
-/*
-  Autora Communication Protocol
-
-  This example code is in the public domain.
-
-  created June 2nd, 2013
-  by Fabio Morgana
-  morganaf@me.com
-*/
-
-#include <Ethernet.h>
-#include <SPI.h>
-
-#define  _STATE     1
-#define  _VERSION   2
-#define  _POWER     3
-#define  _VOLTAGE1  4
-#define  _VOLTAGE2  5
-#define  _CURRENT1  6
-#define  _CURRENT2  7
-#define  _POWERDAY  8
-#define  _POWERTOT  9
-#define  _POWERPEAK 10
-#define  _POWERPEAKDAY  11
-
-#define _SERIALLOG  0
-
-#define _DELAYBETWEENCOMMAND 100
-#define _DELAYBETWEENLOG     10000
-
-// digital pin 2 has a pushbutton attached to it. Give it a name:
-byte enableRS485Pin = 2;
-
-char inBytes[8];
-byte commandState[10]         = {2, 50,  0, 0, 0, 0, 0, 0, 0, 0};
-byte commandVersion[10]       = {2, 58,  0, 0, 0, 0, 0, 0, 0, 0};
-byte commandGridPower[10]     = {2, 59,  3, 0, 0, 0, 0, 0, 0, 0};
-byte commandInput1Voltage[10] = {2, 59, 23, 0, 0, 0, 0, 0, 0, 0};
-byte commandInput2Voltage[10] = {2, 59, 26, 0, 0, 0, 0, 0, 0, 0};
-byte commandInput1Current[10] = {2, 59, 25, 0, 0, 0, 0, 0, 0, 0};
-byte commandInput2Current[10] = {2, 59, 27, 0, 0, 0, 0, 0, 0, 0};
-byte commandPowerDay[10]      = {2, 78,  0, 0, 0, 0, 0, 0, 0, 0};
-byte commandPowerTotal[10]    = {2, 78,  5, 0, 0, 0, 0, 0, 0, 0};
-byte commandPowerPeak[10]     = {2, 59, 34, 0, 0, 0, 0, 0, 0, 0};
-byte commandPowerPeakDay[10]  = {2, 59, 35, 0, 0, 0, 0, 0, 0, 0};
-
-float power, voltage1, current1, voltage2, current2, powerpeak, powerpeakday;
-unsigned long powerday, powertot;
-
-byte mac[] = { metter il mac address del vostro Arduino Ethernet };
-IPAddress ip(192,168,1,254);
-boolean incoming = 0;
-EthernetServer server(80);
-byte requestValue = 0;
-
-// the setup routine runs once when you press reset:
-void setup() {
- // initialize serial communication at 9600 bits per second:
- Serial.begin(19200);
-
- //initialize enableRS485Pin
- pinMode(enableRS485Pin, OUTPUT);
- digitalWrite(enableRS485Pin, HIGH);
-
- //initialize Ethernet Connection
- Ethernet.begin(mac, ip);
- server.begin();
- Serial.print("server is at ");
- Serial.println(Ethernet.localIP());
-}
-
-int numC;
-void loop() {
- // listen for incoming clients
- EthernetClient client = server.available();
- if (client) {
-   numC = 0;
-   requestValue = 0;
-   Serial.println("New client");
-   // an http request ends with a blank line
-   boolean currentLineIsBlank = true;
-   while (client.connected()) {
-     if (client.available()) {
-       char c = client.read();
-       Serial.write(c);
-       // if you've gotten to the end of the line (received a newline
-       // character) and the line is blank, the http request has ended,
-       // so you can send a reply
-       //reads URL string from $ to first blank space
-       if(incoming && c == ' '){
-         incoming = 0;
-       }
-       if(c == '$'){
-         incoming = 1;
-       }
-
-       //Checks for the URL string parameter
-       if(incoming == 1){
-         if (numC)
-            requestValue = requestValue*10 + (c - 48);
-         numC++;
-       }
-
-       if (c == '\n' && currentLineIsBlank) {
-         Serial.print("Start command: ");
-         Serial.println(requestValue);
-         delay(_DELAYBETWEENCOMMAND);
-         // send a standard http response header
-         client.println("HTTP/1.1 200 OK");
-         client.println("Content-Type: text/xml");
-         client.println("Connection: close");  // the connection will be closed after completion of the response
-         client.println();
-         client.println("<?xml version = \"1.0\" ?>");
-         client.print("<values>");
-         switch (requestValue) {
-           default:
-             sendCommand(_POWER);
-             delay(_DELAYBETWEENCOMMAND);
-             sendCommand(_VOLTAGE1);
-             delay(_DELAYBETWEENCOMMAND);
-             sendCommand(_CURRENT1);
-             delay(_DELAYBETWEENCOMMAND);
-             sendCommand(_VOLTAGE2);
-             delay(_DELAYBETWEENCOMMAND);
-             sendCommand(_CURRENT2);
-             delay(_DELAYBETWEENCOMMAND);
-             sendCommand(_POWERDAY);
-             delay(_DELAYBETWEENCOMMAND);
-             sendCommand(_POWERTOT);
-             delay(_DELAYBETWEENCOMMAND);
-             sendCommand(_POWERPEAK);
-             delay(_DELAYBETWEENCOMMAND);
-             sendCommand(_POWERPEAKDAY);
-             delay(_DELAYBETWEENCOMMAND);
-
-             client.print("<power>");
-             client.print(power);
-             client.print("</power>");
-
-             client.print("<voltage1>");
-             client.print(voltage1);
-             client.print("</voltage1>");
-
-             client.print("<current1>");
-             client.print(current1);
-             client.print("</current1>");
-
-             client.print("<voltage2>");
-             client.print(voltage2);
-             client.print("</voltage2>");
-
-             client.print("<current2>");
-             client.print(current2);
-             client.print("</current2>");
-
-             client.print("<powerday>");
-             client.print(powerday);
-             client.print("</powerday>");
-
-             client.print("<powertot>");
-             client.print(powertot);
-             client.print("</powertot>");
-
-             client.print("<powerpeak>");
-             client.print(powerpeak);
-             client.print("</powerpeak>");
-
-             client.print("<powerpeakday>");
-             client.print(powerpeakday);
-             client.print("</powerpeakday>");
-             break;
-         }
-         client.println("</values>");
-         break;
-       }
-       if (c == '\n') {
-         // you're starting a new line
-         currentLineIsBlank = true;
-       }
-       else if (c != '\r') {
-         // you've gotten a character on the current line
-         currentLineIsBlank = false;
-       }
-     }
-   }
-   // give the web browser time to receive the data
-   delay(1);
-   // close the connection:
-   client.stop();
-   Serial.println("client disconnected");
- }
-}


simplifying alphablink a bit

simplifying alphablink a bit

--- lesson-3/alphablink/alphablink.ino
+++ lesson-3/alphablink/alphablink.ino
@@ -24,8 +24,6 @@
       // how many times should we blink?
       int numberOfTimesToBlink = (incomingByte - 'A') + 1;

-      Serial.print("I am about to blink " + String(numberOfTimesToBlink) + " time(s)...");
-
       // okay, blink that many times
       for(int i=0; i < numberOfTimesToBlink; i++) {
         digitalWrite(ledPin, HIGH);
@@ -33,8 +31,6 @@
         digitalWrite(ledPin, LOW);
         delay(200);
       }
-
-      Serial.println(" okay, done.");
     }
   }
 }


Adding support for adding and reading various sensor types

--- arduino/autogarten_probe/autogarten_probe.ino
+++ arduino/autogarten_probe/autogarten_probe.ino
@@ -14,11 +14,28 @@
  *
  *  !!! Important -- Reserved PINs !!!
  *
- *  + The Arduino WiFi sheild uses the SPI bus and other digital pins.
+ *  + The Arduino WiFi shield uses the SPI bus and other digital pins.
  *      Do not use pins 7, 10, 11, 12 or 13 in your sketch as they are in use
  *      For more details: http://arduino.cc/en/Main/ArduinoWiFiShield
- *  + Currently pin 9 is reserved for OneWire protocol communication.
- *      Use it for your OneWire devices
+ *
+ *  + Currently pin 9 is reserved for all OneWire protocol communication.
+ *      See local functions that use OneWire for more details:
+ *      - readOneWireTempSensor()
+ *
+ *
+ * Error Codes:
+ *
+ *  Code   Message
+ *  ----   ------------------------------------------------
+ *   100   Trying to use a reserved pin.
+ *   101   Must specify a valid analog pin.
+ *   102   Must specify a valid digital pin.
+ *   103   Must specify the OneWire pin.
+ *   104   Too many OneWire devices. Increase maxOneWireDevices.
+ *   105   Invalid sensor type
+ *   200   No 1-wire devices found
+ *   201   Invalid CRC
+ *   202   Unsupported 1-wire device type
  *
  *
  * https://github.com/lbracken/autogarten
@@ -27,19 +44,20 @@
 #include <WiFi.h>
 #include <OneWire.h>

-const int SENSOR_TYPE_TEMP_DIGITAL  = 1;
-const int SENSOR_TYPE_TEMP_ONE_WIRE = 2;
-const int SENSOR_TYPE_LIGHT_ANALOG  = 3;
-
-// TODO: Currently always setting on fixed pins to use OneWire protocol,
-//       however, need to determine a better way to set this on the fly after
-//       a user has called addSensor() with a OneWire sensor type.
+const int SENSOR_TYPE_ANALOG_GENERIC = 1;
+const int SENSOR_TYPE_DIGITAL_GENERIC = 2;
+const int SENSOR_TYPE_ONEWIRE_TEMP = 3;
+
+const int ERROR_VALUE = -1000;
+
+const int oneWirePin = 9;
+const int maxOneWireDevices = 3;
+int oneWireDeviceCount = 0;
 OneWire oneWire(9);

 /* WiFi variables */
 const int wifiConnectionWait = 10000;  // In ms
 const int maxWiFiConnectionAttempts = 10;
-
 WiFiClient wifiClient;
 int wifiStatus = WL_IDLE_STATUS;
 int wifiStatusLEDPin;
@@ -50,13 +68,18 @@

 /* Probe and Control Server variables */
 const int maxControlServerConnectionAttempts = 10;
-
 char *probeId;
 char *controlServerAddress;
 int  controlServerPort;
 char *controlServerToken;
 int  controlServerSyncCount = 1;

+/* Sensor indices */
+char *sensorIds[19];
+char *oneWireSensorIds[maxOneWireDevices];
+
+
+

 void setup() {
   Serial.begin(9600);
@@ -64,21 +87,38 @@

   // Initialize the probe and wifi configuration
   initProbe("autogarten_probe", "-----", 5000, "changeme");
-  initWiFi("-----", "-----", true);
+  initWiFi("-----", "-----", false);

   // Add any sensors
+  addSensor("light_level_1", A0, SENSOR_TYPE_ANALOG_GENERIC);
+  addSensor("light_level_2", A1, SENSOR_TYPE_ANALOG_GENERIC);
+  addSensor("switch_1", 2, SENSOR_TYPE_DIGITAL_GENERIC);
+  addSensor("soil_temp", oneWirePin, SENSOR_TYPE_ONEWIRE_TEMP);
+  addSensor("air_temp", oneWirePin, SENSOR_TYPE_ONEWIRE_TEMP);

   // Add any actuators
-
-
-}
-
-
-void loop() {
-
-   delay(10000);
-   syncWithControlServer();
-}
+  // TODO...
+}
+
+
+void loop() {
+  delay(5000);
+
+  Serial.println();
+  Serial.print("Free Memory: ");
+  Serial.println(memoryFree());
+
+  readAnalogGenericSensor("light_level_1");
+  readAnalogGenericSensor("light_level_2");
+  readDigitalGenericSensor("switch_1");
+  readOneWireTempSensor("soil_temp");
+  readOneWireTempSensor("air_temp");
+
+  //syncWithControlServer();
+}
+
+
+

 /**
  * Initialize settings and behavior for the probe
@@ -93,8 +133,8 @@
   controlServerAddress = address;
   controlServerPort = port;
   controlServerToken = token;
-
-}
+}
+

 /**
  * Initialize settings and behavior for WiFi connections
@@ -148,8 +188,10 @@
   }

   // Once connected, print connection information
-  Serial.print("... connection successful");
-  printWiFiConnectionInfo();
+  Serial.print("... connection successful IP:");
+  Serial.print(WiFi.localIP());
+  Serial.print(" RSSI:");
+  Serial.println(WiFi.RSSI());
 }

@@ -161,6 +203,7 @@
   WiFi.disconnect();
   wifiStatus = WL_IDLE_STATUS;
 }
+

 /**
  * Do a probe sync with the connection server
@@ -217,7 +260,9 @@
   Serial.println("... failed to connect to Control Server.  Max attemps reached.");
 }

-
+/**
+ * Construct the body of a probe sync request to the control server
+ */
 String createProbeSyncRequest(int connectionAttempts) {

   // TODO: Start using a proper JSON library here.  Some options could include..
@@ -245,62 +290,235 @@
   return syncRequest;
 }

-/**
- * Wifi debugging function
- * From Arduino 'ConnectWithWPA' WiFi Exmaple
- */
-void printWiFiConnectionInfo() {
-  Serial.println();
-
-  // print the SSID of the network you're attached to:
-  Serial.print("    SSID: ");
-  Serial.println(WiFi.SSID());
-
-  // print the MAC address of the router you're attached to:
-  byte bssid[6];
-  WiFi.BSSID(bssid);
-  Serial.print("    BSSID: ");
-  Serial.print(bssid[5],HEX);
-  Serial.print(":");
-  Serial.print(bssid[4],HEX);
-  Serial.print(":");
-  Serial.print(bssid[3],HEX);
-  Serial.print(":");
-  Serial.print(bssid[2],HEX);
-  Serial.print(":");
-  Serial.print(bssid[1],HEX);
-  Serial.print(":");
-  Serial.println(bssid[0],HEX);
-
-  // print the received signal strength:
-  long rssi = WiFi.RSSI();
-  Serial.print("    signal strength (RSSI):");
-  Serial.println(rssi);
-
-  // print the encryption type:
-  byte encryption = WiFi.encryptionType();
-  Serial.print("    Encryption Type:");
-  Serial.println(encryption,HEX);
-
-  // print your MAC address:
-  byte mac[6];
-  WiFi.macAddress(mac);
-  Serial.print("    MAC address: ");
-  Serial.print(mac[5],HEX);
-  Serial.print(":");
-  Serial.print(mac[4],HEX);
-  Serial.print(":");
-  Serial.print(mac[3],HEX);
-  Serial.print(":");
-  Serial.print(mac[2],HEX);
-  Serial.print(":");
-  Serial.print(mac[1],HEX);
-  Serial.print(":");
-  Serial.println(mac[0],HEX);
-
-  // print your WiFi shield's IP address:
-  IPAddress ip = WiFi.localIP();
-  Serial.print("    IP Address: ");
-  Serial.println(ip);
-  Serial.println();
-}
+
+/*
+ * Adds the given sensor to this probe
+ */
+boolean addSensor(char *sensorId, int pin, int sensorType) {
+
+  // TODO: Verify a reserved PIN isn't being used...
+
+  switch (sensorType) {
+
+    case SENSOR_TYPE_ANALOG_GENERIC:
+      if (!isAnalogPin(pin)) {
+        Serial.print(sensorId);
+        Serial.println(" ERROR 101");
+        return false;
+      }
+      break;
+
+    case SENSOR_TYPE_DIGITAL_GENERIC:
+      if (!isDigitalPin(pin)) {
+        Serial.print(sensorId);
+        Serial.println(" ERROR 102");
+        return false;
+      }
+      pinMode(pin, INPUT);
+      break;
+
+    case SENSOR_TYPE_ONEWIRE_TEMP:
+      if (pin != oneWirePin) {
+        Serial.print(sensorId);
+        Serial.println(" ERROR 103");
+        return false;
+      }
+
+      if (oneWireDeviceCount >= maxOneWireDevices) {
+        Serial.println(" ERROR 104");
+        return false;
+      }
+
+      // 1-wire devices share a pin, so set the sensorId in the 1-wire array
+      oneWireSensorIds[oneWireDeviceCount++] = sensorId;
+      break;
+
+    default:
+        Serial.print(sensorId);
+        Serial.println(" ERROR 105");
+  }
+
+  sensorIds[pin] = sensorId;
+  Serial.print(sensorIds[pin]);
+  Serial.print(" added on pin ");
+  Serial.println(pin);
+  return true;
+}
+
+
+/**
+ * Returns the pin for the given sensorId
+ */
+int getPinForSensorId(char *sensorId) {
+  int ctr;
+  for (ctr=0; ctr < sizeof(sensorIds)/sizeof(char); ctr++) {
+    if (sensorIds[ctr] == sensorId) {
+      return ctr;
+    }
+  }
+  return -1;
+}
+
+
+/**
+ * Returns true if pin is a digital pin
+ */
+boolean isDigitalPin(int pin) {
+  return pin >= 0 && pin <= 13;
+}
+
+
+/**
+ * Retrurns true if pin is an analog pin
+ */
+boolean isAnalogPin(int pin) {
+  return pin >= A0 && pin <= A5;
+}
+
+
+/**
+ * Read a value from an analog sensor.  Examples include...
+ *  + Photoresistors for measuring light levels.
+ *  + ...
+ */
+float readAnalogGenericSensor(char *sensorId) {
+  int pin = getPinForSensorId(sensorId);
+  float value = analogRead(pin);
+
+  printSensorResult(sensorId, pin, value);
+  return value;
+}
+
+
+/**
+ * Read a value from an digital sensor.  Examples include...
+ *  + Switches
+ *  + ...
+ */
+int readDigitalGenericSensor(char *sensorId) {
+  int pin = getPinForSensorId(sensorId);
+  int value = digitalRead(pin);
+
+  printSensorResult(sensorId, pin, value);
+  return value;
+}
+
+
+/*
+ * Using the OneWire library, reads temperature from a 1-wire device.
+ * See: http://playground.arduino.cc/Learning/OneWire
+ *
+ * !! Important !!
+ *     This function has been streamlined to ONLY support a DS18S20 digital thermometer
+ *     running in non-parasitic power mode.  If using another 1-wire device then changes
+ *     are required. See the Arduino OneWire page for details and code.
+ *
+ *     Note that multiple DS18S20 devices can be wired together on the same bus.
+ *     Be sure to place a 4.7K resistor between VCC and Data.
+ *
+ *     When using multiple DS18S20 devices, the order that the addSensor() is called
+ *     matters.  Call addSensor() for the first item on the bus.
+ */
+float readOneWireTempSensor(char *sensorId) {
+
+  int deviceCount = 0;
+  byte addr[8];
+
+  // Iterate over all devices on the OneWire bus
+  oneWire.reset_search();
+  while (oneWire.search(addr) ){
+    delay(250);
+
+    // If this isn't the device we're looking for, continue.
+    if (sensorId != oneWireSensorIds[deviceCount++]) {
+      continue;
+    }
+
+    // Print the device's unique 64-bit ROM code
+    /*Serial.print(" * R=");
+    for( i = 0; i < 8; i++) {
+      Serial.print(addr[i], HEX);
+      Serial.print(" ");
+    }
+    Serial.println("---");
+    */
+
+    // Verify valid CRC, if not return error value
+    if (OneWire::crc8( addr, 7) != addr[7]) {
+      Serial.println("ERROR 201");
+      return ERROR_VALUE;
+    }
+
+    // Verify is chip is a DS18B20, if not return error value.
+    // The first ROM byte indicates which chip (0x28 = DS18B20).
+    if(addr[0] != 0x28) {
+      Serial.println("ERROR 202");
+      return ERROR_VALUE;
+    }
+
+    // Reset the 1-Wire bus, select a device then start a conversion
+    oneWire.reset();
+    oneWire.select(addr);
+    oneWire.write(0x44);
+    delay(800);
+
+    // Reset the 1-Wire bus, select a device then read scratchpad
+    oneWire.reset();
+    oneWire.select(addr);
+    oneWire.write(0xBE);
+
+    // Read the data on the bus (9 bytes)
+    byte data[12];
+    for (int i = 0; i < 9; i++) {
+      data[i] = oneWire.read();
+    }
+
+    // Convert the data (hex) to a temperature value.
+    // Since we're only supporting a DS18S20 device, we can assume
+    // 12 bit resolution (750ms conversion time).
+    int16_t raw = (data[1] << 8) | data[0];
+    float value = convertCelsiusToFahrenheit((float)raw / 16.0);
+    printSensorResult(sensorId, oneWirePin, value);
+    return value;
+  }
+
+  Serial.println("ERROR 200");
+  return ERROR_VALUE;
+}
+
+
+/**
+ * For debugging purposes, prints out the results of reading a sensor
+ */
+void printSensorResult(char *sensorId, int pin, float value) {
+  Serial.print(sensorId);
+  Serial.print(" on ");
+  Serial.print(pin);
+  Serial.print(" = ");
+  Serial.println(value);
+}
+
+
+/**
+ * Convert a celsius value to Fahrenheit, because Amurika
+ */
+float convertCelsiusToFahrenheit(float degreesCelsius) {
+  return degreesCelsius * 1.8 + 32.0;
+}
+
+
+/**
+ * Determine amount of free RAM
+ * From Arduino Cookbook: Page 587
+ */
+extern int __bss_end;
+extern void *__brkval;
+int memoryFree() {
+  int freeValue;
+  if((int)__brkval == 0)
+    freeValue = ((int)&freeValue) - ((int)&__bss_end);
+  else
+    freeValue = ((int)&freeValue) - ((int)__brkval);
+  return freeValue;
+}
+


More comments, addied some motor control stuff from my other sketches. Next up is motor handling.

--- Box_joint/Box_joint.ino
+++ Box_joint/Box_joint.ino
@@ -140,34 +140,6 @@
   jogMenuControl();
 }

-void jogMenuControl() { //This is the action code for jog mode
-
-  if (left_Rb.isHit()) {
-    testVar++;
-    slcd.setCursor(8, 1);
-    slcd.print("<--");
-    refreshScreen = 1;
-  }
-  else if (right_Rb.isHit()) {
-    testVar++;
-    slcd.setCursor(8, 1);
-    slcd.print("-->");
-    refreshScreen = 1;
-  }
-  else {
-    testVar = 0;
-  }
-  //if (refreshScreen == 1 && !left_Rb.isHit() && !right_Rb.isHit()) {
-  //  noClearBottom();
-  //  refreshScreen = 0;
-  //}
-
-  slcd.setCursor(12, 1);
-  slcd.print(testVar, DEC);
-  slcd.setCursor(0, 1);
-  slcd.print(refreshScreen, DEC);
-}
-
 void slewMenuMode() { //this is the slewing controller
   if (lcdRefreshOK()) {
     noClear;
@@ -180,9 +152,7 @@
   slcd.print(targetSteps, DEC);
 }

-void slewMenuControl() { //this is the sction code for slew mode.
-
-}
+//*************************************** LCD HANDLERS **********************************

 boolean lcdRefreshOK() { //Refresh the lcd screen, this is a better way, calls noClear()
   boolean OK = false;
@@ -239,10 +209,55 @@
   }
 }

-void rightLimitHandler() {
+
+//***************** MOTOR HANDLING *************************
+
+void rightLimitHandler() { //this controld the behavior of the system when the RIGHT limit switch is HIGH.
   // placeholder
 }

-void leftlimit() {
+void leftlimit() { //this controld the behavior of the system when the LEFT limit switch is HIGH.
   //placeholder
+}
+
+/*
+void stopMotor(){ //This is to stop the motor
+  digitalWrite(CWpin, LOW);
+  digitalWrite(CCWpin, LOW);
+}
+*/
+
+void slewMenuControl() { //this is the action code for slew mode.
+
+}
+
+void jogMenuControl() { //This is the action code for jog mode
+
+  boolean rightRed_b = digitalRead(rightRed);
+  boolean leftRed_b = digitalRead(leftRed);
+
+  if (left_Rb.isHit()) {
+    testVar++;
+    slcd.setCursor(8, 1);
+    slcd.print("<--");
+    refreshScreen = 1;
+  }
+  else if (right_Rb.isHit()) {
+    testVar++;
+    slcd.setCursor(8, 1);
+    slcd.print("-->");
+    refreshScreen = 1;
+  }
+  else {
+    testVar = 0;
+  }
+  if (refreshScreen == 1 && !rightRed_b && !leftRed_b) {
+    noClearBottom();
+    refreshScreen = 0;
+  }
+
+  slcd.setCursor(12, 1);
+  slcd.print(testVar, DEC);
+  slcd.setCursor(0, 1);
+  slcd.print(refreshScreen, DEC);
 }


Some more calibration

Some more calibration

--- otto/otto.ino
+++ otto/otto.ino
@@ -1,5 +1,26 @@
 #include <limits.h>
 #include <Servo.h>
+
+#define RIGHT_ANKLE_PIN         5
+#define LEFT_ANKLE_PIN          4
+#define RIGHT_HIP_PIN           3
+#define LEFT_HIP_PIN            2
+
+#define RIGHT_ANKLE_POS_MIN     1050
+#define RIGHT_ANKLE_POS_MIDDLE  1510
+#define RIGHT_ANKLE_POS_MAX     1860
+
+#define LEFT_ANKLE_POS_MIN      1140
+#define LEFT_ANKLE_POS_MIDDLE   1490
+#define LEFT_ANKLE_POS_MAX      2190
+
+#define RIGHT_HIP_POS_MIN       950
+#define RIGHT_HIP_POS_MIDDLE    1290
+#define RIGHT_HIP_POS_MAX       1600
+
+#define LEFT_HIP_POS_MIN        1100
+#define LEFT_HIP_POS_MIDDLE     1500
+#define LEFT_HIP_POS_MAX        1930

 #define DELAY 2

@@ -124,10 +145,10 @@
     }
 }

-Joint rightAnkle(5, 950, 1510, 1860);
-Joint leftAnkle(4, 1140, 1490, 2190);
-Joint rightHip(3, 950, 1290, 1650);
-Joint leftHip(2, 1100, 1500, 1930);
+Joint rightAnkle(RIGHT_ANKLE_PIN, RIGHT_ANKLE_POS_MIN, RIGHT_ANKLE_POS_MIDDLE, RIGHT_ANKLE_POS_MAX);
+Joint leftAnkle(LEFT_ANKLE_PIN, LEFT_ANKLE_POS_MIN, LEFT_ANKLE_POS_MIDDLE, LEFT_ANKLE_POS_MAX);
+Joint rightHip(RIGHT_HIP_PIN, RIGHT_HIP_POS_MIN, RIGHT_HIP_POS_MIDDLE, RIGHT_HIP_POS_MAX);
+Joint leftHip(LEFT_HIP_PIN, LEFT_HIP_POS_MIN, LEFT_HIP_POS_MIDDLE, LEFT_HIP_POS_MAX);

 void stepForward() {
     Move stepLeft[] = {


Several changes  Added sensor readings  Button behavior now records code on enable  Adapted website to show data

--- arduinofences.ino
+++ arduinofences.ino
@@ -1,20 +1,20 @@
-//#include <WiShield.h>
 #include <WiServer.h>
 #include <IRremote.h>
+#include <dht11.h>

 int RECV_PIN = 5;
-int BUTTON_PIN = 6;
-int ANALOG_LIGHT_PIN = 1;
+int ANALOG_BUTTON_PIN = 5;
+int ANALOG_LIGHTSENSOR_PIN = 1;
+int ledPin1 = 4;

 IRrecv irrecv(RECV_PIN);
 IRsend irsend;
+dht11 DHT11;

 decode_results results;

 #define WIRELESS_MODE_INFRA	1
 #define WIRELESS_MODE_ADHOC	2
-
-#define ledPin1 4

 // Wireless configuration parameters ----------------------------------------
 unsigned char local_ip[] = {10,0,0,50};	// IP address of WiShield
@@ -50,19 +50,23 @@
 char numAsCharBuff[2];
 char ledChange;

+// Weather
+float prevTemp = 0;
+float prevHumidity = 0;
+
 //---------------------------------------------------------------------------

 void setup()
 {
     irrecv.enableIRIn(); // Start the receiver
-    pinMode(BUTTON_PIN, INPUT);
+    DHT11.attach(6);
     Serial.begin(9600);

     // Initialize WiServer and have it use the sendMyPage function to serve pages
     pinMode(ledPin1, OUTPUT);
     pinMode(RECV_PIN, INPUT);
-    pinMode(BUTTON_PIN, INPUT);
-    pinMode(ANALOG_LIGHT_PIN, INPUT);
+    pinMode(ANALOG_BUTTON_PIN, INPUT);
+    pinMode(ANALOG_LIGHTSENSOR_PIN, INPUT);

     //WiFi.init();
     WiServer.init(sendPage);
@@ -115,7 +119,11 @@
    {
       WiServer.print("<title>Led switch</title>");

-      WiServer.print("Please select the led state:\n");
+      WiServer.print("Temperature: ");
+      WiServer.print(prevTemp);
+      WiServer.print("C
Humidity: ");
+      WiServer.print(prevHumidity);
+      WiServer.print("%
");
       for (stateCounter = 0; stateCounter < 1; stateCounter++) //for each led
       {
         numAsCharBuff[0] = (char)(stateCounter + 49); //as this is displayed use 1 - 3 rather than 0 - 2
@@ -138,7 +146,7 @@
         WiServer.print(tmpStrCat);
       }

-        WiServer.print(" ");
+        WiServer.print("");
         return true;
    }
    else {
@@ -152,8 +160,7 @@
 int codeLen; // The length of the code
 int toggle = 0; // The RC5/6 toggle state
 unsigned long sentLockMillis = 0;
-
-int lastButtonState;
+unsigned long tempLockMillis = 0;

 // Stores the code for later playback
 // Most of this code is just logging
@@ -231,23 +238,50 @@
 void sendCodeOnce() {
   unsigned long time = millis();

-  if ( (time - sentLockMillis) > 10000) { //10 seconds
+  if ( (time - sentLockMillis) > 2000) { //2 seconds
     Serial.println("Sending once");
     sendCode();
     sentLockMillis = time;
   }
 }

+void readTempHumidity() {
+    unsigned long time = millis();
+    if ( (time - tempLockMillis) > 2000) { //2 seconds
+
+      int chk = DHT11.read();
+
+      switch (chk)
+      {
+        case 0: Serial.println("OK"); break;
+        case -1: Serial.println("Checksum error"); break;
+        case -2: Serial.println("Time out error"); break;
+        default: Serial.println("Unknown error"); break;
+      }
+
+      prevTemp = (float)DHT11.temperature;
+      prevHumidity = (float)DHT11.humidity;
+      //Serial.println((float)DHT11.humidity, DEC);
+      //Serial.println((float)DHT11.temperature, DEC);
+
+      tempLockMillis = time;
+    }
+}
+
 void loop()
 {
-  int buttonState = digitalRead(BUTTON_PIN);
-  int lightValue = analogRead(ANALOG_LIGHT_PIN);
+  int analogButtonState = analogRead(ANALOG_BUTTON_PIN);
+  int lightValue = analogRead(ANALOG_LIGHTSENSOR_PIN);

   if (lightValue < 200) {
     sendCodeOnce();
   }

-  if (buttonState == HIGH) {
+  readTempHumidity();
+
+  // We use analog in as we don't have any other digital
+  // inputs, needed for sensors
+  if (analogButtonState >= 1000) {
     if (irrecv.decode(&results)) {
       storeCode(&results);
       irrecv.resume(); // resume receiver
@@ -257,7 +291,6 @@
   else {
     //sendCode();
   }
-  lastButtonState = buttonState;

   WiServer.server_task();
 }


bit_heart_rate_template_with battery_service done

--- libraries/BLE/examples/ble_heart_rate_template_with_battery_service/ble_heart_rate_template_with_battery_service.ino
+++ libraries/BLE/examples/ble_heart_rate_template_with_battery_service/ble_heart_rate_template_with_battery_service.ino
@@ -37,7 +37,6 @@
  */

 #include <SPI.h>
-#include <avr/pgmspace.h>
 #include "services.h"
 #include <ble_system.h>
 #include <lib_aci.h>
@@ -274,8 +273,8 @@
   /** We reset the nRF8001 here by toggling the RESET line connected to the nRF8001
    *  and initialize the data structures required to setup the nRF8001
    */
-
-  lib_aci_init(&aci_state);
+  //The second parameter is for turning debug printing on for the ACI Commands and Events so they be printed on the Serial
+  lib_aci_init(&aci_state, true);

 	pinMode(6, INPUT); //Pin #6 on Arduino -> PAIRING CLEAR pin: Connect to 3.3v to clear the pairing
 	if (0x01 == digitalRead(6))
@@ -296,12 +295,12 @@

 void aci_loop()
 {
+  static bool setup_required = false;

   // We enter the if statement only when there is a ACI event available to be processed
   if (lib_aci_event_get(&aci_state, &aci_data))
   {
     aci_evt_t * aci_evt;
-
     aci_evt = &aci_data.evt;
     //@todo change this so that the commands and events can be processed here in a switch case instead of callbacks
     //hal_aci_tl_msg_rcv_hook(&aci_data);
@@ -318,10 +317,7 @@
             */
             aci_state.device_state = ACI_DEVICE_SETUP;
             Serial.println(F("Evt Device Started: Setup"));
-            if (ACI_STATUS_TRANSACTION_COMPLETE != do_aci_setup(&aci_state))
-            {
-              Serial.println(F("Error in ACI Setup"));
-            }
+            setup_required = true;
             break;

             case ACI_DEVICE_STANDBY:
@@ -469,6 +465,18 @@
     // If No event in the ACI Event queue and No event in the ACI Command queue
     // Arduino can go to sleep
   }
+
+  /* setup_required is set to true when the device starts up and enters setup mode.
+   * It indicates that do_aci_setup() should be called. The flag should be cleared if
+   * do_aci_setup() returns ACI_STATUS_TRANSACTION_COMPLETE.
+   */
+  if(setup_required)
+  {
+    if (SETUP_SUCCESS == do_aci_setup(&aci_state))
+    {
+      setup_required = false;
+    }
+  }
 }

 /*


Fix seting time/date

Fix seting time/date

--- meteo_lcd/meteo_lcd.ino
+++ meteo_lcd/meteo_lcd.ino
@@ -376,42 +376,60 @@
                 if (val > 23) val = 0;
                 rtc.setHour(val);
                 lcd.setCursor(0, line);
+                if (val < 10)
+                    lcd.print(0);
                 lcd.print(val);
+                lcd.setCursor(0, line);
                 break;
             case 1:
                 if (val < 0)  val = 59;
                 if (val > 59) val = 0;
                 rtc.setMinute(val);
                 lcd.setCursor(3, line);
+                if (val < 10)
+                    lcd.print(0);
                 lcd.print(val);
+                lcd.setCursor(3, line);
                 break;
             case 2:
                 if (val < 0)  val = 59;
                 if (val > 59) val = 0;
                 rtc.setSecond(val);
                 lcd.setCursor(6, line);
+                if (val < 10)
+                    lcd.print(0);
                 lcd.print(val);
+                lcd.setCursor(6, line);
                 break;
             case 3:
                 if (val < 0)  val = 31; // this allows to set 31.02 as a date
                 if (val > 31) val = 0;
                 rtc.setDate(val);
                 lcd.setCursor(10, line);
+                if (val < 10)
+                    lcd.print(0);
                 lcd.print(val);
+                lcd.setCursor(10, line);
                 break;
             case 4:
                 if (val < 0)  val = 12;
                 if (val > 12) val = 0;
                 rtc.setDate(val);
-                lcd.setCursor(16, line);
+                lcd.setCursor(13, line);
+                if (val < 10)
+                    lcd.print(0);
                 lcd.print(val);
+                lcd.setCursor(13, line);
                 break;
             case 5:
                 if (val < 0)  val = 99;
                 if (val > 99) val = 0;
                 rtc.setYear(val);
                 lcd.setCursor(18, line);
+                if (val < 10)
+                    lcd.print(0);
                 lcd.print(val);
+                lcd.setCursor(18, line);
                 break;
             default: break;
         }
@@ -745,24 +763,16 @@
     if (enter_time_setup())
         time_setup(3 /* 4th row */);

-    // Update meteo data after every 'meteo_delay' time
-    if (delay_counter == 0) {
-        float temp_in, humid_in, temp_out, humid_out;
-        int32_t pressure;
-
-        read_meteo_data(temp_in, humid_in, temp_out, humid_out, pressure);
-//        draw_template();
-        fill_data(temp_in, temp_out, humid_in, humid_out, pressure);
-    }
-
-    // update delay_counter
-    delay_counter = (delay_counter + 1) % (meteo_delay / delay_time);
-
+    // Update meteo data
+    float temp_in, humid_in, temp_out, humid_out;
+    int32_t pressure;
+
+    read_meteo_data(temp_in, humid_in, temp_out, humid_out, pressure);
+    fill_data(temp_in, temp_out, humid_in, humid_out, pressure);

     // Update the displayed time
     print_time_string(3 /* 4th row */);

-
     LOG("delay "); LOGLN(delay_time);
     //delay(delay_time);
 }


fixed missing digit on D0

fixed missing digit on D0

--- range/arduino/led_8seg/led_8seg.ino
+++ range/arduino/led_8seg/led_8seg.ino
@@ -86,7 +86,7 @@

     // parse any incoming commands
     if (character == 'S' || character == 's') {
-      displayTime(timer);void displayTime(int number, int decimalplaces = DECIMAL_PLACES);
+      displayTime(timer);

       run_flag = true;
       counter = millis();
@@ -144,7 +144,7 @@
       // add decimal place if specified digit
       // but ignore for whole numbers
       shiftOut(SDO, CLK, LSBFIRST, segments[output] | segments[POINT]);
-    } else if (output == 0 && number == 0) {
+    } else if (output == 0 && number == 0 && i != 0) {
       if (negative == true) {
         // print a minus if we're at the first negative
         // (assumes we won't see max length number as a minus)


Added files via upload

Added files via upload

Sharing Arduino mini 05 source (used the 5Volt version)


Now works on Arduino (no C++11 features)

--- Synthduino.ino
+++ Synthduino.ino
@@ -1,59 +1,63 @@
-/* Synthduino - the Arduino Synthesizer program
- * v. 0.1
- * Milton Stanley, Milte Technologies
- *
- * REQUIRES the StandardCPlusPlus library for Arduino, found at
- * http://www.github.com/maniacbug/StandardCplusplus
- *
- */
-
-/* TODO
- *
- * 1) [DONE] Convert pitches to format nXX, instead of NOTE_XX
- * 2) Add support for Constant declarations of notes - EIGHTH instead of 8
- * 3) [DONE] Add enharmonics
- *   ------- 	All these following classes use memory format note->end, where end is an offset from
- *						the overall start time (instead of just duration), so
- 							{A4, 8}, {CS5, 8}, {E5, 8} becomes {A4, 8}, {CS5, 16}, {E5, 24}, converted to millis
- * 4) Build support for Melody class - vector<note>, with timing offsets
- * 5) Build support for Channel class - does the actual signalling to pin
- * 6) Possible add a mixer class, for handling multiple channels
- */
-
-#include "note.h"
-#include "pitches.h"
-
-
-/* HEADER SECTION
- * Declare your tempo and parts/pins (note parts/pins are recommended in the format below
- * Examples:
- * #define TEMPO = 120 // in bpm (beats per minute) - how many quarter notes per minute
- * #define BASS 12
- * Note bassline[] = { {NOTE_C3, 2}, {NOTE_DS3, 2}, {NOTE_F3, 1} };
- */
-
-#define TEMPO 120   // Tempo in bpm
-#define BASS 12  		// Bass will be output on pin 12
-#define MELODY 13
-
-//Note a440(nA4, 8);
-//Note bassLine[] = { {NOTE_C3, 2}, {NOTE_DS3, 2}, {NOTE_F3, 1} }; // The actual bass part
-Note melody[] = { {NOTE_E4,4}, {NOTE_D4,4}, {NOTE_C4,4}, {NOTE_D4,4}, {NOTE_E4,4}, {NOTE_E4,4}, {NOTE_E4,4} };
-int MELODY_LENGTH = 7;       // this will change later and be automatic
-
-
-// End header Section
-
-void setup(){
-	pinMode(MELODY, OUTPUT);
-  Serial.begin(9600);
-}
-
-void loop() {
-  for(int i=0; i<MELODY_LENGTH; i++){
-    melody[i].play(MELODY);
-  }
-
-  //a440.play(12);
-  delay(5000);
-}
+/* Synthduino - the Arduino Synthesizer program
+ * v. 0.1
+ * Milton Stanley, Milte Technologies
+ *
+ * REQUIRES the StandardCPlusPlus library for Arduino, found at
+ * http://www.github.com/maniacbug/StandardCplusplus
+ *
+ */
+
+/* TODO
+ *
+ * 1) [DONE] Convert pitches to format nXX, instead of NOTE_XX
+ * 2) Add support for Constant declarations of notes - EIGHTH instead of 8
+ * 3) [DONE] Add enharmonics
+ *   ------- 	All these following classes use memory format note->end, where end is an offset from
+ *						the overall start time (instead of just duration), so
+ 							{A4, 8}, {CS5, 8}, {E5, 8} becomes {A4, 8}, {CS5, 16}, {E5, 24}, converted to millis
+ * 4) Build support for Melody class - vector<note>, with timing offsets
+ * 5) Build support for Channel class - does the actual signalling to pin
+ * 6) Possible add a mixer class, for handling multiple channels
+ */
+
+#include "note.h"
+#include "pitches.h"
+
+
+/* HEADER SECTION
+ * Declare your tempo and parts/pins (note parts/pins are recommended in the format below
+ * Examples:
+ * #define TEMPO = 120 // in bpm (beats per minute) - how many quarter notes per minute
+ * #define BASS 12
+ * Note bassline[] = { {NOTE_C3, 2}, {NOTE_DS3, 2}, {NOTE_F3, 1} };
+ */
+
+#define TEMPO 120   // Tempo in bpm
+#define BASS 12  		// Bass will be output on pin 12
+#define MELODY 13
+
+//Note a440(nA4, 8);
+/*  The below line doesn't work on Windows, as Arduino uses an older version of gcc w/o specifying
+    c++11 support
+      Note bassLine[] = { {NOTE_C3, 2}, {NOTE_DS3, 2}, {NOTE_F3, 1} }; // The actual bass part
+    If you're on Linux (and I guess OSx), you can use the abbreviated notation. Otherwise:
+  */
+Note melody[] = { Note(NOTE_E4,4), Note(NOTE_D4,4), Note(NOTE_C4,4), Note(NOTE_D4,4), Note(NOTE_E4,4), Note(NOTE_E4,4), Note(NOTE_E4,4) };
+int MELODY_LENGTH = 7;       // this will change later and be automatic
+
+
+// End header Section
+
+void setup(){
+	pinMode(MELODY, OUTPUT);
+  Serial.begin(9600);
+}
+
+void loop() {
+  for(int i=0; i<MELODY_LENGTH; i++){
+    melody[i].play(MELODY);
+  }
+
+  //a440.play(12);
+  delay(5000);
+}


Adding ROS Support to the excavator driver.

--- src/ExcavatorDriverROS/ExcavatorDriverROS.ino
+++ src/ExcavatorDriverROS/ExcavatorDriverROS.ino
@@ -1,7 +1,9 @@
 #include <ros.h>
 // Include a custom command message.
 #include <command2ros/ExcavatorCommand.h>
-
+#include <std_msgs/String.h>
+
+void newExcavatorCommandCallback(const command2ros::ExcavatorCommand& newManualCommand);

 // Device constants
 const int NUM_TRANSPORT_MOTORS = 4;
@@ -43,15 +45,19 @@

 // State machine states
 const int STOPPED = 0;
-const int DRIVING = 1;
-const int DIGGING = 2;
-const int CONVEYING = 3;
+const int READY_TO_DRIVE = 1;
+const int DRIVING = 2;
+const int READY_TO_DIG = 3;
+const int DIGGING =  4;
+const int READY_TO_CONVEY = 5;
+const int CONVEYING = 6;

 int currentStatus = STOPPED;

 const int DRIVE_SPEED = 20;
 const int ROTATION_SPEED = 20;

+unsigned long driveUntilTime = 0;

 //
 // ROS Node Initialization
@@ -78,16 +84,31 @@
 //
 // ROS Subsribers
 //
-ros::Subscriber<command2ros::ManualCommand> commandSubscriber("ExcavatorCommand", &newExcavatorCommandCallback);
-
+ros::Subscriber<command2ros::ExcavatorCommand> commandSubscriber("ExcavatorCommand", &newExcavatorCommandCallback);
+command2ros::ExcavatorCommand lastExcavatorCommand;
 void newExcavatorCommandCallback(const command2ros::ExcavatorCommand& newManualCommand)
 {
- // TODO: excavator callback
+ lastExcavatorCommand.fl_drive_speed = newManualCommand.fl_drive_speed;
+ lastExcavatorCommand.fr_drive_speed = newManualCommand.fr_drive_speed;
+ lastExcavatorCommand.bl_drive_speed = newManualCommand.bl_drive_speed;
+ lastExcavatorCommand.br_drive_speed = newManualCommand.br_drive_speed;
+ lastExcavatorCommand.drive_duration = newManualCommand.drive_duration;
+ lastExcavatorCommand.e_stop = newManualCommand.e_stop;
+ if(lastExcavatorCommand.e_stop)
+ {
+  stopAllMotors();
+  currentStatus = STOPPED;
+ }
+ else
+ {
+   stopAllMotors();
+   currentStatus = READY_TO_DRIVE;
+ }
 }

 //Inbound wheel command
-command2ros::ManualCommand wheelTarget;
+command2ros::ExcavatorCommand wheelTarget;

 void stopAllMotors()
 {
@@ -150,6 +171,33 @@
   delayMicroseconds(1000);
 }

+// Function that takes a SIGNED speed value and converts it to an UNSIGNED drive command.
+void helpDrive(char motorID, char speed)
+{
+  if(speed < 0)
+  {
+    driveBackwards(motorID, -speed);
+  }
+  else
+  {
+    driveForwards(motorID, speed);
+  }
+}
+
+// Function to drive the wheels
+void driveTires()
+{
+ if(currentStatus == READY_TO_DRIVE)
+ {
+   helpDrive(FRONT_LEFT_DRIVE_MOTOR_ID, lastExcavatorCommand.fl_drive_speed);
+   helpDrive(FRONT_RIGHT_DRIVE_MOTOR_ID, lastExcavatorCommand.fr_drive_speed);
+   helpDrive(BACK_LEFT_DRIVE_MOTOR_ID, lastExcavatorCommand.bl_drive_speed);
+   helpDrive(BACK_RIGHT_DRIVE_MOTOR_ID, lastExcavatorCommand.br_drive_speed);
+   currentStatus = DRIVING;
+ }
+
+}
+
 // Wheel unit test.
 // Each wheel should rotate individually.
 void unitTest()
@@ -180,21 +228,28 @@
 {
  //Currently stopped, don't do anything.
   // ASSUMES the robot is stopped when currentStatus is set to STOPPED.
-  if (currentStatus == STOPPED) {
-    // do nothing
-  }
-  else if (currentStatus == DRIVING)
-  {
-   // TODO: Drive
-  }
-  else if(currentStatus == DIGGING)
-  {
-    // TODO: Dig
-  }
-  else if(currentStatus == CONVEYING)
-  {
-    // TODO: Convey
-  }
+switch(currentStatus)
+{
+ case READY_TO_DRIVE:
+   driveTires();
+   driveUntilTime = millis() + (long)lastExcavatorCommand.drive_duration;
+ break;
+ case DRIVING:
+   if(millis() > driveUntilTime)
+   {
+     stopAllMotors();
+     // TODO: Change this to excavating, if necessary.
+    currentStatus = STOPPED;
+   }
+ break;
+
+ case STOPPED:
+  // fall through
+ default:
+ // TODO: Convey / Dig
+ break;
+}
+
   //TODO: Publish sensor / state data?
   //Sync with ROS
   excavatorNode.spinOnce(); // Check for subscriber update/update timestamp


Adding ultrasonic sensor. Commented out for now.

--- src/robot_racing_car/arduino/arduino.ino
+++ src/robot_racing_car/arduino/arduino.ino
@@ -1,9 +1,12 @@
 #include <ros.h>
 #include <std_msgs/UInt8.h>
+#include <std_msgs/Int16.h>

 ros::NodeHandle nh;

 /*define logic control output pin*/
+int Echo = A4;
+int Trig = A5;
 int in1=6;
 int in2=7;
 int in3=8;
@@ -12,39 +15,40 @@
 /*define channel enable output pins*/
 int ENA=5;
 int ENB=11;
+int ABS = 100;

-void moveRobot(const std_msgs::UInt8& msg)
+void move_robot(const std_msgs::UInt8& msg)
 {
   switch(msg.data)
   {
    case 0:
    {
-     digitalWrite(ENA,HIGH);
-     digitalWrite(ENB,HIGH);
+     analogWrite(ENA,ABS);
+     analogWrite(ENB,ABS);
+     digitalWrite(in1,LOW);
+     digitalWrite(in2,HIGH);
+     digitalWrite(in3,HIGH);
+     digitalWrite(in4,LOW);
+
+     nh.logdebug("Moving forward");
+     break;
+   }
+   case 1:
+   {
+     analogWrite(ENA,ABS);
+     analogWrite(ENB,ABS);
      digitalWrite(in1,HIGH);
      digitalWrite(in2,LOW);
      digitalWrite(in3,LOW);
      digitalWrite(in4,HIGH);

-     nh.logdebug("Moving forward");
-     break;
-   }
-   case 1:
-   {
-     digitalWrite(ENA,HIGH);
-     digitalWrite(ENB,HIGH);
-     digitalWrite(in1,LOW);
-     digitalWrite(in2,HIGH);
-     digitalWrite(in3,HIGH);
-     digitalWrite(in4,LOW);
-
      nh.logdebug("Moving back");
      break;
    }
    case 2:
    {
-     digitalWrite(ENA,HIGH);
-     digitalWrite(ENB,HIGH);
+     analogWrite(ENA,ABS);
+     analogWrite(ENB,ABS);
      digitalWrite(in1,HIGH);
      digitalWrite(in2,LOW);
      digitalWrite(in3,HIGH);
@@ -55,8 +59,8 @@
    }
    case 3:
    {
-     digitalWrite(ENA,HIGH);
-     digitalWrite(ENB,HIGH);
+     analogWrite(ENA,ABS);
+     analogWrite(ENB,ABS);
      digitalWrite(in1,LOW);
      digitalWrite(in2,HIGH);
      digitalWrite(in3,LOW);
@@ -80,7 +84,24 @@
   }
 }

-ros::Subscriber<std_msgs::UInt8> robot_car_subscriber("robot_car_arduino", &moveRobot);
+int get_distance()
+{
+  digitalWrite(Trig, LOW);
+  delayMicroseconds(2);
+  digitalWrite(Trig, HIGH);
+  delayMicroseconds(20);
+  digitalWrite(Trig, LOW);
+
+  float distance = pulseIn(Echo, HIGH);
+  distance= distance/58;
+
+  return (int)distance;
+}
+
+ros::Subscriber<std_msgs::UInt8> steering_subscriber("robot_car_steering", &move_robot);
+
+std_msgs::Int16 ultrasonic_sensor_message;
+ros::Publisher ultrasonic_sensor_publisher("robot_car_ultrasonic_sensor", &ultrasonic_sensor_message);

 void setup()
 {
@@ -96,11 +117,14 @@

   nh.initNode();

-  nh.subscribe(robot_car_subscriber);
+  nh.subscribe(steering_subscriber);
 }

 void loop()
 {
+//  ultrasonic_sensor_message.data = get_distance();
+//  ultrasonic_sensor_publisher.publish(&ultrasonic_sensor_message);
+
   nh.spinOnce();

   delay(1);


Fix save to eprom

Fix save to eprom

--- examples/RF12/RF12demo/RF12demo.ino
+++ examples/RF12/RF12demo/RF12demo.ino
@@ -634,6 +634,7 @@
         if (value) {
          config.nodeId = (value << 6) + (config.nodeId & 0x3F);
          config.frequency = 1600;
+         rf12_control(0xA000 + config.frequency);
          saveConfig();
         } else {
             showHelp();
@@ -644,9 +645,10 @@
         config.frequency = value*(20*25*band);
         Serial.print("->");
         Serial.print(config.frequency);
-        rf12_config();
         rf12_control(0xA000 + config.frequency);
+        Serial.println(0xA000 + config.frequency, HEX);
         Serial.println();
+        saveConfig();
         break;
       case 'g': // set network group
         config.group = value;
@@ -770,6 +772,7 @@
     config.group = eeprom_read_byte(RF12_EEPROM_ADDR + 1);
     config.frequency = eeprom_read_byte(RF12_EEPROM_ADDR + 3)*256;
     config.frequency = config.frequency + eeprom_read_byte(RF12_EEPROM_ADDR + 2);
+    Serial.println(config.frequency);
   } else {
     config.nodeId = 0x41; // 433 MHz, node 1
     config.group = 0xD4;  // default group 212


Trying to add static color mode

Trying to add static color mode

running out of memory

--- lampka.ino
+++ lampka.ino
@@ -98,9 +98,9 @@
 }

-void sendByte( unsigned char byte ) {
-
-    for( unsigned char bit = 0 ; bit < 8 ; bit++ ) {
+void sendByte( uint8_t byte ) {
+
+    for( uint8_t bit = 0 ; bit < 8 ; bit++ ) {

       sendBit( bitRead( byte , 7 ) );                // Neopixel wants bit in highest-to-lowest order
                                                      // so send highest bit (bit #7 in an 8-bit byte since they start at 0)
@@ -128,7 +128,7 @@

 }

-void sendPixel( unsigned char r, unsigned char g , unsigned char b )  {
+void sendPixel( uint8_t r, uint8_t g , uint8_t b )  {

   sendByte(r);          // Neopixel wants colors in green then red then blue order
   sendByte(g);
@@ -165,7 +165,7 @@
 /*
 // Fill the dots one after the other with a color
 // rewrite to lift the compare out of the loop
-void colorWipe(unsigned char r , unsigned char g, unsigned char b, unsigned  char wait ) {
+void colorWipe(uint8_t r , uint8_t g, uint8_t b, unsigned  char wait ) {
   for(unsigned int i=0; i<PIXELS; i+= (PIXELS/60) ) {

     cli();
@@ -193,7 +193,7 @@

 #define THEATER_SPACING (PIXELS/20)

-void theaterChase( unsigned char r , unsigned char g, unsigned char b, unsigned char wait ) {
+void theaterChase( uint8_t r , uint8_t g, uint8_t b, uint8_t wait ) {

   for (int j=0; j< 3 ; j++) {

@@ -238,7 +238,7 @@

 // I rewrite this one from scrtach to use high resolution for the color wheel to look nicer on a *much* bigger string

-void rainbowCycle(unsigned char frames , unsigned int frameAdvance, unsigned int pixelAdvance ) {
+void rainbowCycle(uint8_t frames , unsigned int frameAdvance, unsigned int pixelAdvance ) {

   // Hue is a number between 0 and 3*256 than defines a mix of r->g->b where
   // hue of 0 = Full red
@@ -261,8 +261,8 @@
         currentPixelHue -= (3*256);
       }

-      unsigned char phase = currentPixelHue >> 8;
-      unsigned char step = currentPixelHue & 0xff;
+      uint8_t phase = currentPixelHue >> 8;
+      uint8_t step = currentPixelHue & 0xff;

       switch (phase) {

@@ -300,7 +300,7 @@
 // I added this one just to demonstrate how quickly you can flash the string.
 // Flashes get faster and faster until *boom* and fade to black.

-void detonate( unsigned char r , unsigned char g , unsigned char b , unsigned int startdelayms) {
+void detonate( uint8_t r , uint8_t g , uint8_t b , unsigned int startdelayms) {
   while (startdelayms) {

     showColor( r , g , b );      // Flash the color
@@ -330,15 +330,15 @@
 //#define SCALE8_C 1
 #define SCALE8_AVRASM 1
 #define LIB8_ATTINY
-static inline unsigned char scale8( unsigned char i, unsigned char scale)
+static inline uint8_t scale8( uint8_t i, uint8_t scale)
 {
 #if SCALE8_C == 1
     return
     ((int)i * (int)(scale) ) >> 8;
 #elif SCALE8_AVRASM == 1
 #if defined(LIB8_ATTINY)
-    unsigned char work=0;
-    unsigned char cnt=0x80;
+    uint8_t work=0;
+    uint8_t cnt=0x80;
     asm volatile(
         "LOOP_%=:                             \n\t"
         "  sbrc %[scale], 0             \n\t"
@@ -373,13 +373,13 @@
 #endif
 }

-static inline unsigned char scale8_video_LEAVING_R1_DIRTY( unsigned char i, unsigned char scale)
+static inline uint8_t scale8_video_LEAVING_R1_DIRTY( uint8_t i, uint8_t scale)
 {
 #if SCALE8_C == 1 || defined(LIB8_ATTINY)
-    unsigned char j = (((int)i * (int)scale) >> 8) + ((i&&scale)?1:0);
+    uint8_t j = (((int)i * (int)scale) >> 8) + ((i&&scale)?1:0);
     return j;
 #elif SCALE8_AVRASM == 1
-    unsigned char j=0;
+    uint8_t j=0;
     asm volatile(
         "  tst %[i]\n\t"
         "  breq L_%=\n\t"
@@ -398,7 +398,7 @@
 #endif
 }

-void hsv2rgb_rainbow(unsigned char hue, unsigned char colors[3])
+void hsv2rgb_rainbow(uint8_t hue, uint8_t colors[3])
 {
     // Yellow has a higher inherent brightness than
     // any other color; 'pure' yellow is perceived to
@@ -408,21 +408,21 @@
     // colors.
     // Level Y1 is a moderate boost, the default.
     // Level Y2 is a strong boost.
-    const unsigned char Y1 = 1;
-    const unsigned char Y2 = 0;
+    const uint8_t Y1 = 1;
+    const uint8_t Y2 = 0;

     // G2: Whether to divide all greens by two.
     // Depends GREATLY on your particular LEDs
-    const unsigned char G2 = 0;
+    const uint8_t G2 = 0;

     // Gscale: what to scale green down by.
     // Depends GREATLY on your particular LEDs
-    const unsigned char Gscale = 0;
-
-    unsigned char offset = hue & 0x1F; // 0..31
+    const uint8_t Gscale = 0;
+
+    uint8_t offset = hue & 0x1F; // 0..31

     // offset8 = offset * 8
-    unsigned char offset8 = offset;
+    uint8_t offset8 = offset;
     {
         offset8 <<= 1;
         asm volatile("");
@@ -431,7 +431,7 @@
         offset8 <<= 1;
     }

-    unsigned char third = scale8( offset8, (256 / 3));
+    uint8_t third = scale8( offset8, (256 / 3));

     memset(colors, 0, sizeof(colors));

@@ -454,8 +454,8 @@
                 }
                 if( Y2 ) {
                     colors[0] = K171 + third;
-                    //unsigned char twothirds = (third << 1);
-                    unsigned char twothirds = scale8( offset8, ((256 * 2) / 3));
+                    //uint8_t twothirds = (third << 1);
+                    uint8_t twothirds = scale8( offset8, ((256 * 2) / 3));
                     colors[1] = K85 + twothirds;
                 }
             }
@@ -466,7 +466,7 @@
                 // 010
                 //case 2: // Y -> G
                 if( Y1 ) {
-                    unsigned char twothirds = scale8( offset8, ((256 * 2) / 3));
+                    uint8_t twothirds = scale8( offset8, ((256 * 2) / 3));
                     colors[0] = K171 - twothirds;
                     colors[1] = K171 + third;
                 }
@@ -490,7 +490,7 @@
                 // 100
                 //case 4: // A -> B
                 //r = 0;
-                unsigned char twothirds = scale8( offset8, ((256 * 2) / 3));
+                uint8_t twothirds = scale8( offset8, ((256 * 2) / 3));
                 colors[1] = K171 - twothirds;
                 colors[2] = K85  + twothirds;
             } else {
@@ -524,8 +524,8 @@

 inline void interruptSetup() {
-    const unsigned char buttonPin=3;
-    //cli(); //disable interrupts
+    const uint8_t directionButtonPin=3;
+    const uint8_t constantButtonPin=0;
     // initialize the pushbutton pin as an input:
     // actually they are all inputs by default, so do nothing
     //DDRB |= _BV(buttonPin);
@@ -538,8 +538,8 @@

     //GIMSK |= (1<<6); //Bit 6 INT0: External Interrupt Request 0 Enable
     GIMSK |= (1<<5); //Bit 5 PCIE: Pin Change Interrupt Enable
-    PCMSK |= (1<<buttonPin); //PCINT[5:0]: Pin Change Enable Mask 5:0
-    //sei(); //enable interrupts
+    PCMSK |= (1<<directionButtonPin); //PCINT[5:0]: Pin Change Enable Mask 5:0
+    PCMSK |= (1<<constantButtonPin); //PCINT[5:0]: Pin Change Enable Mask 5:0
 }

 void setup() {
@@ -547,23 +547,46 @@
     ledsetup();
 }

-unsigned char led_colors[PIXELS][3];
-signed char direction = 1;
-const unsigned char delta = (256/PIXELS); //delta of hue between each pixel, spread out evenly
+const uint8_t delta = (256/PIXELS); //delta of hue between each pixel, spread out evenly
+volatile boolean constant=0;
+volatile int8_t direction = 1;
+//volatile uint8_t constant_color_hue=0;
+uint8_t led_colors[PIXELS][3];
+volatile uint8_t constant_color_index=0;
+
+
+const uint8_t rgb_colors[8][3] {
+255,0,0,
+255,128,0,
+255,255,0,
+0,255,0,
+0,255,255,
+0,0,255,
+255,0,255,
+//255,128,128,
+255,255,255
+};

 ISR(PCINT0_vect) {
-    //transition between -1,0,1
-    direction += 2;
-    direction = direction % 3;
-    direction -= 1;
-    //memset(led_colors, 0, sizeof(led_colors));
-    //show_all_led_colors();
-    //delay(255);
+
+    if (PINB & (1<<3)) { //change direction
+        //transition between -1,0,1
+        constant = 0;
+        direction += 2;
+        direction = direction % 3;
+        direction -= 1;
+    }
+    else if (PINB & 1) { //constant color
+        //stop color shifting
+        constant = 1;
+        //constant_color_hue += 32;
+        ++constant_color_index % 8;
+    }
 }

 void show_all_led_colors() {
     cli();
-    for (unsigned char index=0; index < PIXELS; index++) {
+    for (uint8_t index=0; index < PIXELS; index++) {
       sendPixel( led_colors[index][0] , led_colors[index][1] , led_colors[index][2] );
     }
     sei();
@@ -571,15 +594,30 @@
 }

 void loop() {
-  for (unsigned char hue=0; hue < 255; hue++) {
-    for (unsigned char index=0; index < PIXELS; index++) {
-        unsigned char offset = index * delta * direction;
-        hsv2rgb_rainbow(hue + offset, led_colors[index]);
+    if (constant) {
+        for (uint8_t index=0; index < PIXELS; index++) {
+            //hsv2rgb_rainbow(constant_color_hue, led_colors[index]);
+            memcpy(led_colors[index], rgb_colors[constant_color_index], 3);
+            //led_colors[index][0] = rgb_colors[constant_color_index][0];
+            //led_colors[index][1] = rgb_colors[constant_color_index][1];
+            //led_colors[index][2] = rgb_colors[constant_color_index][2];
         }
-    show_all_led_colors();
-    delay(20);
-  }
-}
-
-
-
+        show_all_led_colors();
+        delay(20);
+    } else {
+        for (uint8_t hue=0; hue < 255; hue++) {
+            for (uint8_t index=0; index < PIXELS; index++) {
+                uint8_t offset = index * delta * direction;
+                hsv2rgb_rainbow(hue + offset, led_colors[index]);
+            }
+            show_all_led_colors();
+            delay(20);
+            if (constant) {
+                break;
+            }
+        }
+    }
+}
+
+
+


Fix to manual answer to listeners.

Fix to manual answer to listeners.

git-svn-id: d8bfcd070c2c81762cca1b3912331324182919ba@19653 0d6f1817-ed0e-0410-87c9-987e46238f29

--- zimodem/zcommand.ino
+++ zimodem/zcommand.ino
@@ -793,6 +793,7 @@
         serial.prints("NO CARRIER ");
         serial.printf("%d %s:%d",current->id,current->host,current->port);
         serial.prints(EOLN);
+        serial.flush();
       }
       return ZIGNORE;
     }
@@ -837,6 +838,7 @@
           serial.prints("NO CARRIER ");
           serial.printf("%d %s:%d",c->id,c->host,c->port);
           serial.prints(EOLN);
+          serial.flush();
         }
         c=c->next;
       }
@@ -1492,6 +1494,7 @@
         &&(c->id = lastServerClientId))
         {
           current=c;
+          checkOpenConnections();
           streamMode.switchTo(c);
           lastServerClientId=0;
           if(ringCounter == 0)
@@ -2676,7 +2679,7 @@
     if(result != ZIGNORE_SPECIAL)
       previousCommand = saveCommand;
     if((suppressResponses)&&(result == ZERROR))
-        return ZERROR;
+      return ZERROR;
     if(crc8 >= 0)
       result=ZERROR; // setting S42 without a T command is now Bad.
     if((result != ZOK)||(index >= len))
@@ -3001,6 +3004,7 @@
             serial.prints("NO CARRIER ");
             serial.printf("%d %s:%d",current->id,current->host,current->port);
             serial.prints(EOLN);
+            serial.flush();
           }
         }
         delete current;
@@ -3124,6 +3128,7 @@
             serial.prints("NO CARRIER ");
             serial.printi(nextConn->id);
             serial.prints(EOLN);
+            serial.flush();
           }
           if(serial.getFlowControlType() == FCT_MANUAL)
           {


correct comments, leave only what's necessary use serial.write for single characters

--- ksp-gegi-mini/ksp-gegi-mini.ino
+++ ksp-gegi-mini/ksp-gegi-mini.ino
@@ -2,18 +2,21 @@
 #include <Arduino.h>

 // dł kabelków 15-20cm
-// diody LED: niebieskie (bez rezystora, krótka nóżka) do GND, białe (z rezystorem, długa nóżka) do pinu
-// potencjometr: niebieski z czarną kreską do GND, biały do +5V, niebieski do pinu A0 / A1
 // przełączniki2: niebieski do GND, biały do pinu, wszystkie zamontowane tak, aby niebieski był w środku, biały na dole, a niepodłączone u góry (wtedy gałka w górę==załączenie)
-// przełączniki3: środkowy (ciemny) do GND, boczne do pinów
+// przełączniki3: środkowy (ciemny) do GND, boczne do pinów, zamontowany bokiem

 // 595:
-// 15  A1 SCRCK(13) // clock
-// 16  A2 SERIN(3)  // data
-// 17  A3 RCK(12)   // latch
+// 15=A1 SCRCK(13) // clock
+// 16=A2 SERIN(3)  // data
+// 17=A3 RCK(12)   // latch
 // /SRCLR(8) -> +5V
 // /G (9) -> GND
 // /DRAINx = GND od LEDa (LED niebieskie, bez rezystora, krótka nożka do drain; białe, z rezystorem, długa nóżka do +5V)
+
+// UART:
+// receive commands like: ^L{GR}{id}={val}$
+// format: "^LG1=0$" turn off green led 1, "^LR2=1$" turn off red led 2
+// bits val=0 (OFF), val=1 (ON), val=3 (ON+BLINK)

 const uint8_t clockPin = A1;  // SCRCK (13)
 const uint8_t dataPin  = A2;  // SERIN (3)
@@ -35,6 +38,7 @@
     uint8_t m_lastLedState { 0 } ; // bits: 0=GxON, 1=RxON, 2=GxBLINK, 3=RxBLINK
 };

+// id=0..12
 digitalPin digiPins[] = {
   digitalPin(0,2,0,0),    // OLED mode1 switch 2
   digitalPin(1,3,0,0),    // OLED mode2 switch 3
@@ -47,8 +51,8 @@
   digitalPin(8,10,0,0),    // stage, switch pin 10
   digitalPin(9,11,0,0),    // stagemode, switch pin 11
   digitalPin(10,0,0,12),    // low fuel, yellow led 12
-  digitalPin(11,0,0,13),    // low fuel, yellow led 13
-  digitalPin(12,0,0,A0),    // low fuel, red led 14=A0
+  digitalPin(11,0,0,13),    // low power, yellow led 13
+  digitalPin(12,0,0,A0),    // overheat, red led 14=A0
 };

 digitalPin::digitalPin(const uint8_t id, const uint8_t pinSwitch, const uint8_t pinOn, const uint8_t pinOff) :
@@ -72,9 +76,9 @@
     // reverse logic because switches are connected to GND with internal pullup, so pushed state (ON) is 0V
     uint8_t state = !digitalRead(m_pinSwitch);
     if (state!=m_lastPinState) {
-      Serial.print('D');
+      Serial.write('D');
       Serial.print(m_id);
-      Serial.print('=');
+      Serial.write('=');
       Serial.println(state);
       m_lastPinState = state;
     }
@@ -176,8 +180,6 @@
   serialShiftWrite(shiftLeds);
 }

-// commands like: ^L{GR}{id}={val}$
-// format: "^LG1=0$" turn off green led 1 (RCS), "^LR2=1$" turn off red led 2 (SCS)
 void handleSerialInputLed() {
     const uint8_t c = Serial.read();
     const uint8_t id = Serial.parseInt();  // skip '='


better test

better test

--- longboard-ctl.ino
+++ longboard-ctl.ino
@@ -58,13 +58,15 @@

 // MAINLOOP
 void loop() {
-    uint16_t x, y, z;
-    mma.getRawData(&x, &y, &z);
-    Serial.print(x);
-    Serial.print(",");
-    Serial.print(y);
-    Serial.print(",");
-    Serial.println(z);
+    float x, y, z;
+    mma.getAcceleration(&x, &y, &z);
+    if (abs(x) > 0.05) {
+        Serial.print(x);
+        Serial.print(",");
+        Serial.print(y);
+        Serial.print(",");
+        Serial.println(z);
+    }
 }


on off

on off

--- btnLed/src/sketch.ino
+++ btnLed/src/sketch.ino
@@ -22,10 +22,16 @@
 void loop()
 {
   // wait for a button press
-  if (digitalRead(pushbuttonPIN) == HIGH)
+  if ((digitalRead(pushbuttonPIN) == HIGH) && (flag == LOW))
   {
     digitalWrite(onoffLED, HIGH);
-    delay(2000);
-    digitalWrite(onoffLED,LOW);
+    delay(20);
+    //digitalWrite(onoffLED,LOW);
+  }
+  if ((digitalRead(pushbuttonPIN) == HIGH) && (flag == HIGH))
+  {
+    digitalWrite(onoffLED, LOW);
+    delay(20);
+    //digitalWrite(onoffLED,LOW);
   }
 }


Round relatively humidity to nearest percent, instead of truncating it.

--- zg01_esp/zg01_esp.ino
+++ zg01_esp/zg01_esp.ino
@@ -87,7 +87,7 @@
                 break;
             case 'A':
                 // humidity
-                mqtt_send(TOPIC_HUMIDITY, value / 100, "%");
+                mqtt_send(TOPIC_HUMIDITY, (value + 50) / 100, "%");
                 break;
             default:
                 // ignore unhandled packet


erase comment.

erase comment.

--- easy-pomodoro.ino
+++ easy-pomodoro.ino
@@ -4,12 +4,10 @@
 extern  void  led_update(unsigned int value);

 void setup() {
-  // put your setup code here, to run once:
   led_init();
 }

 void loop() {
-  // put your main code here, to run repeatedly:
   led_update(millis() / 1000);
 }


FTPライブラリの動作がとくに不安定なので注意書きを追加しました。

FTPライブラリの動作がとくに不安定なので注意書きを追加しました。

--- 2_example/example25a_fs/example25a_fs.ino
+++ 2_example/example25a_fs/example25a_fs.ino
@@ -2,6 +2,13 @@
 Example 25a: センサ受信データ・ファイルシステム [FTPサーバ機能付き]
                                             Copyright (c) 2016 Wataru KUNINO
 *******************************************************************************/
+
+// ご注意：FTPサーバは簡易的なものです。
+// FTPクライアント側には FileZilla を使用してください。
+// FFFTP でも、おおむね使用可能なことを確認しています。
+// Windows エクスプローラのFTPクライアントでは動作確認ができていません。
+// FTPサーバに関わらず、すべての実装が実験目的のものです。補償は一切ありません。
+
 #include <FS.h>
 #include <ESP8266WiFi.h>                    // ESP8266用ライブラリ
 #include <WiFiClient.h>


Update for xinchejian

Update for xinchejian


HashMap code - before removing all mentions of hashmaps

--- Arduino_Code/Arduino_Code.ino
+++ Arduino_Code/Arduino_Code.ino
@@ -2,6 +2,10 @@
 Created by Geoff Spielman on 2016-06-25.
 Copyright (c) 2016 Geoff Spielman. All rights reserved.
 */
+
+#include <HashMap.h>
+#include <QueueList.h>
+
 const int btn0 = 2;
 const int btn1 = 3;
 const int btn2 = 4;
@@ -23,12 +27,31 @@
 int seqIndex = 0;
 int seqLength = 0;
 String recString = "";
+
 //since dynamic arrays are not advised in Arduino, it is unlikely the user will get past 50
 int seqArr[50];
 int btnLog[50];
 int btnLogIndex = 0;
+
 String sendSequence = "";
 String sendMorse = "";
+
+//The queue for the morse code
+QueueList<char> morQue;
+
+//To control how morse code is output
+const int dotLength = 500;
+const int dashLength = 3*dotLength;
+
+//hash morse code 'characters' to their appropriate responces.
+const byte HASH_SIZE = 5;
+HashType<char*,int> hashRawArray[HASH_SIZE];
+HashMap<char*,int> morseMap = HashMap<char*,int>(hashRawArray , HASH_SIZE );
+int morState = 0;
+unsigned long morLength = 0;
+unsigned long morStart = 0;
+boolean morseAvailable = false;
+const int dot = 700;

 //Status trackers
 boolean displayingSequence = false;
@@ -52,16 +75,34 @@
 boolean LEDon = false;

+
 void setup() {

- Serial.begin(9600);
-
- for (int i = 0; i < 4; i++)
- {
-  pinMode(btn[i], INPUT);
-  pinMode(led[i], OUTPUT);
- }
- recString.reserve(400);
+  Serial.begin(9600);
+  for (int i = 0; i < 4; i++)
+  {
+    pinMode(btn[i], INPUT);
+    pinMode(led[i], OUTPUT);
+  }
+  recString.reserve(400);
+
+
+/*Since you can't store anything other than integers in this HashMap:
+ * Last digit is if it should be on (1) or off(0) (use mod 10 to determine)
+ * All other digits are how many units to perform the action (truncate divide by 10 to determine)
+ */
+morseMap[0](".", 11);
+morseMap[1]("/", 31);
+morseMap[2](" ", 30); //space between letters
+morseMap[3]("|", 70); //space between words
+morseMap[4]("?", 120);//space between messages (arbitrary, in case there are multiple)
+//morseMap.debug(); //print it
+/*According to Wikiepedia:
+ * Length of dash is three times the length of a dot
+ * Space between dash or dot is equal to the length of a dot
+ * letters are seperated by a pause equal to the length of a dash (three dots)
+ * words are seperated by 7 dots
+ */
 }

@@ -185,9 +226,11 @@
       creatingSequence = false;
     }
   }
-
-
-  //seperate from status blocks of code -------------------------------------
+
+
+  //-----------------------------------------------------------------------------------------------
+  //----------------------seperate from status blocks of code -------------------------------------
+  //-----------------------------------------------------------------------------------------------
   if (listeningToButtons)
   {
     for (int i = 0; i < 4; i ++)
@@ -221,6 +264,38 @@
     prevButtonState[i] = cur;
     }
   }
+
+  //@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@2
+  //if we're not in bypass mode and a change needs to be made
+  if (morseAvailable && (millis() - morStart > morLength))
+  {
+    //converts next char to a char pointer (Extra character for null terminator
+    char next[2];
+    String(morQue.peek()).toCharArray(next, 2);
+    Serial.println(morseMap.getValueOf(next));
+    Serial.println(morQue.peek());
+    //if the state is currently on
+    if (morState)
+    {
+      //if the next character is another dit or dah, you must wait one dot duration worth
+      //if (morseMap.getValueOf(next) % 10 == 1)
+     // {
+
+     // }
+
+    }
+    //just finished a pause, so no matter what we need the next character
+    else{
+
+    }
+    //we have run out of characters
+    //if(!morQue.isEmpty())
+    //{
+      //morQue.pop(
+   //   Serial.println("Empty");
+   // }
+  }
+

 }//end loop

@@ -242,10 +317,15 @@
       recString = recString.substring(0, endIndex);

-      //PROCESS MORSE CODE
+      //PROCESS MORSE CODE (space between letters, pipe between words)
       if (recString.charAt(0) == '.' || recString.charAt(0) == '-')
       {
         //Add to Queue
+        for (int i = 0; i < recString.length(); i++)
+        {
+          morQue.push(recString.charAt(i));
+        }
+        morseAvailable = true;
       }

       //PROCESS SEQUENCE


Correct offset and its initial value

Correct offset and its initial value

--- Arduino/GroundUnit/GroundUnit.ino
+++ Arduino/GroundUnit/GroundUnit.ino
@@ -78,10 +78,11 @@
 #define POT_RANGE_DEG      300 // 300 is the value for standard potentiometer
 #define POT_USED_RANGE_DEG  60 // To normalize and saturate rotation
 #define POT_OFFSET        0.05 // Distance from rotation axis to lever arm (in m)
-#define NEUTRAL_ANGLE_DEG  225 // Zero of the potentiometer
+#define NEUTRAL_ANGLE_DEG    90 // Zero of the potentiometer
 // Linear encoder
 #define LINEAR_RESOLUTION 0.005// Resolution of the linear encoder
 #define LINEAR_USED_RANGE 0.05 // To normalize and saturate translation motion
+#define PI 3.1415

 #define ORDER_RATE_ms 100
 long last_order_ms = 0;
@@ -115,6 +116,12 @@
   // Saturate the output to the maximum range (values are normalized between -1 and 1)
   myPID1.SetOutputLimits(-1, 1);
   myPID2.SetOutputLimits(-1, 1);
+
+  for (int i=0;i<4;i++)
+  {
+    data[i] = 127;
+  }
+  data[0] = NEUTRAL_ANGLE_DEG*255./POT_RANGE_DEG+127;
 }

 /*
@@ -210,22 +217,14 @@
   }
 }

-#define POT_RANGE_DEG      300
-#define POT_USED_RANGE_DEG  60
-#define POT_OFFSET        0.05 //Distance from rotation axis to lever arm
-
-// Linear encoder
-#define LINEAR_RESOLUTION 0.005
-#define LINEAR_USED_RANGE 0.05
-#define PI 3.1415
 void computeFeedback()
 {

   // Feedbacks are normalized between -1 and 1

   // Potentiometer angle
-  float rawAngle_deg = data[0]/255.0*POT_RANGE_DEG;
-  Input1 = (rawAngle_deg - NEUTRAL_ANGLE_DEG)/POT_USED_RANGE_DEG;
+  float rawAngle_deg = (data[0]-127)/255.0*POT_RANGE_DEG;
+  Input1 = (rawAngle_deg - NEUTRAL_ANGLE_DEG)*1.0/POT_USED_RANGE_DEG;

   // Linear encoder position
   Input2 = (data[1]-127);//*LINEAR_RESOLUTION/2./LINEAR_USED_RANGE;
@@ -276,11 +275,11 @@
     Serial.print(", ");
     Serial.print((power2+127)*4);
     Serial.print(", ");
-    Serial.print((Input1+1)/2*1023);
+    Serial.print((Input1+1)/2.*1023);
     Serial.print(", ");
-    Serial.print((Input2/127+1)/2*1023);
+    Serial.print((Input2/127.+1)/2.*1023);
     Serial.print(", ");
-    Serial.print((Input3+1)/2*1023);
+    Serial.print((Input3+1)/2.*1023);
     Serial.println("");
     isFeedbackRequested = false;
   }


Corrected index for PID

Corrected index for PID

--- Elcano_C2_LowLevel/Elcano_C2_LowLevel.ino
+++ Elcano_C2_LowLevel/Elcano_C2_LowLevel.ino
@@ -855,10 +855,11 @@
   speed_errors[error_index] = error_speed_mmPs;
   error_sum += error_speed_mmPs;
   mean_speed_error = error_sum / ERROR_HISTORY;
-  i = (error_index-1) % ERROR_HISTORY;
+  i = (error_index -1) % ERROR_HISTORY;
+  if (++error_index >= ERROR_HISTORY)
+      error_index = 0;
   extrapolated_error = 2 * error_speed_mmPs - speed_errors[i];
-
-  PID_error = P_tune * error_speed_mmPs
+    PID_error = P_tune * error_speed_mmPs
             + I_tune * mean_speed_error
             + D_tune * extrapolated_error;
   if (PID_error > speed_tolerance_mmPs)


Refactor and update based on cycles

Refactor and update based on cycles

--- sega_controller/sega_controller.ino
+++ sega_controller/sega_controller.ino
@@ -1,8 +1,8 @@
 /*
  * Sega Controller Reader
  * Author: Jon Thysell <thysell@gmail.com>
- * Version: 1.1
- * Date: 9/29/2014
+ * Version: 1.2
+ * Date: 6/27/2017
  *
  * Reads buttons presses from Sega Genesis 3/6 button controllers
  * and reports their state via the Serial connection. Handles hot
@@ -12,74 +12,64 @@
  */

 const int PLAYERS = 2;
-
-// Controller Button Flags
-const int ON = 1;
-const int UP = 2;
-const int DOWN = 4;
-const int LEFT = 8;
-const int RIGHT = 16;
-const int START = 32;
-const int A = 64;
-const int B = 128;
-const int C = 256;
-const int X = 512;
-const int Y = 1024;
-const int Z = 2048;
-const int MODE = 4096;
-
-// Controller DB9 Pin 7 Mappings
-const int SELECT[] = { 8, 9 };
-
-typedef struct
-{
-  int player;
-  int pin;
-  int lowFlag;
-  int highFlag;
-  int pulse3Flag;
-} input;
-
-// Controller DB9 Pin to Button Flag Mappings
-// First column is the controller index, second column
-// is the Arduino pin that the controller's DB9 pin is
-// attached to, remaing columns are the button flags
-input inputMap[] = {
-  { 0,  2,  UP,    UP,     Z    }, // P0 DB9 Pin 1
-  { 0,  3,  DOWN,  DOWN,   Y    }, // P0 DB9 Pin 2
-  { 0,  4,  ON,    LEFT,   X    }, // P0 DB9 Pin 3
-  { 0,  5,  ON,    RIGHT,  MODE }, // P0 DB9 Pin 4
-  { 0,  6,  A,     B,      0    }, // P0 DB9 Pin 6
-  { 0,  7,  START, C,      0    }, // P0 DB9 Pin 9
-  { 1,  A0, UP,    UP,     Z    }, // P1 DB9 Pin 1
-  { 1,  A1, DOWN,  DOWN,   Y    }, // P1 DB9 Pin 2
-  { 1,  A2, ON,    LEFT,   X    }, // P1 DB9 Pin 3
-  { 1,  A3, ON,    RIGHT,  MODE }, // P1 DB9 Pin 4
-  { 1,  A4, A,     B,      0    }, // P1 DB9 Pin 6
-  { 1,  A5, START, C,      0    }  // P1 DB9 Pin 9
+const int INPUT_PINS_PER_PLAYER = 6;
+
+// Mapping controller DB9 pin 7 to Arduino pin
+const int SELECT[] = {
+  8, // Player 1
+  9 // Player 2
+};
+
+// Mapping controller DB9 input pins to Arduino pins
+int inputPins[][INPUT_PINS_PER_PLAYER] = {
+  // { DB9 Pin 1, DB9 Pin 2, DB9 Pin 3, DB9 Pin 4, DB9 Pin 6, DB9 Pin 9 }
+  { 2, 3, 4, 5, 6, 7 }, // Player 1
+  { A0, A1, A2, A3, A4, A5 } // Player 2
+};
+
+// Controller button flags
+enum flags {
+  ON = 1,
+  UP = 2,
+  DOWN = 4,
+  LEFT = 8,
+  RIGHT = 16,
+  START = 32,
+  A = 64,
+  B = 128,
+  C = 256,
+  X = 512,
+  Y = 1024,
+  Z = 2048,
+  MODE = 4096
 };

-// Controller State
-int currentState[] = { 0, 0 };
-int lastState[] = { -1, -1 };
+// Controller states
+word currentState[] = { 0, 0 };
+word lastState[] = { -1, -1 };

 // Default to three-button mode until six-button connects
 boolean sixButtonMode[] = { false, false };
-
+
+const int CYCLES = 8;
+
 void setup()
 {
   // Setup input pins
-  for (int i = 0; i < sizeof(inputMap) / sizeof(input); i++)
+  for (int player = 0; player < PLAYERS; player++)
   {
-    pinMode(inputMap[i].pin, INPUT);
-    digitalWrite(inputMap[i].pin, HIGH);
+    for (int pin = 0; pin < INPUT_PINS_PER_PLAYER; pin++)
+    {
+      pinMode(inputPins[player][pin], INPUT);
+      digitalWrite(inputPins[player][pin], HIGH);
+    }
   }

   // Setup select pins
-  for (int i = 0; i < PLAYERS; i++)
+  for (int player = 0; player < PLAYERS; player++)
   {
-    pinMode(SELECT[i], OUTPUT);
-    digitalWrite(SELECT[i], HIGH);
+    pinMode(SELECT[player], OUTPUT);
+    digitalWrite(SELECT[player], HIGH);
   }

   Serial.begin(9600);
@@ -87,22 +77,32 @@

 void loop()
 {
+  unsigned long loopStart = millis();
+
   readButtons();
   sendStates();
+
+  // Delay up to 16ms in order to simulate one frame @ 60 fps
+  delay(max(16 - (millis() - loopStart), 0));
 }

 void readButtons()
 {
-  for (int i = 0; i < PLAYERS; i++)
+  for (int player = 0; player < PLAYERS; player++)
   {
-    resetState(i);
-    if (sixButtonMode[i])
+    resetState(player);
+
+    digitalWrite(SELECT[player], LOW);
+
+    for (int cycle = 0; cycle < CYCLES; cycle++)
     {
-      read6buttons(i);
+      readButtons(player, cycle);
     }
-    else
+
+    // When a controller disconnects, revert to three-button polling
+    if ((currentState[player] & ON) == 0)
     {
-      read3buttons(i);
+      sixButtonMode[player] = false;
     }
   }
 }
@@ -111,71 +111,43 @@
 {
   currentState[player] = 0;
 }
-
-void read3buttons(int player)
+
+void readButtons(int player, int cycle)
 {
-  // Set SELECT LOW and read lowFlag
-  digitalWrite(SELECT[player], LOW);
-
-  delayMicroseconds(20);
-
-  for (int i = 0; i < sizeof(inputMap) / sizeof(input); i++)
+  digitalWrite(SELECT[player], cycle % 2 == 0 ? LOW : HIGH);
+
+  // Read flags
+  switch (cycle)
   {
-    if (inputMap[i].player == player && digitalRead(inputMap[i].pin) == LOW)
-    {
-      currentState[player] |= inputMap[i].lowFlag;
-    }
+    case 2:
+      currentState[player] |= (digitalRead(inputPins[player][0]) == LOW) ? UP : 0;
+      currentState[player] |= (digitalRead(inputPins[player][1]) == LOW) ? DOWN : 0;
+      currentState[player] |= (digitalRead(inputPins[player][2]) == LOW) ? ON : 0;
+      currentState[player] |= (digitalRead(inputPins[player][3]) == LOW) ? ON : 0;
+      currentState[player] |= (digitalRead(inputPins[player][4]) == LOW) ? A : 0;
+      currentState[player] |= (digitalRead(inputPins[player][5]) == LOW) ? START : 0;
+      break;
+    case 3:
+      currentState[player] |= (digitalRead(inputPins[player][0]) == LOW) ? UP : 0;
+      currentState[player] |= (digitalRead(inputPins[player][1]) == LOW) ? DOWN : 0;
+      currentState[player] |= (digitalRead(inputPins[player][2]) == LOW) ? LEFT : 0;
+      currentState[player] |= (digitalRead(inputPins[player][3]) == LOW) ? RIGHT : 0;
+      currentState[player] |= (digitalRead(inputPins[player][4]) == LOW) ? B : 0;
+      currentState[player] |= (digitalRead(inputPins[player][5]) == LOW) ? C : 0;
+      break;
+    case 4:
+      sixButtonMode[player] = (digitalRead(inputPins[player][0]) == LOW && digitalRead(inputPins[player][1]) == LOW);
+      break;
+    case 5:
+      if (sixButtonMode[player])
+      {
+        currentState[player] |= (digitalRead(inputPins[player][0]) == LOW) ? Z : 0;
+        currentState[player] |= (digitalRead(inputPins[player][1]) == LOW) ? Y : 0;
+        currentState[player] |= (digitalRead(inputPins[player][2]) == LOW) ? X : 0;
+        currentState[player] |= (digitalRead(inputPins[player][3]) == LOW) ? MODE : 0;
+      }
+      break;
   }
-
-  // Set SELECT HIGH and read highFlag
-  digitalWrite(SELECT[player], HIGH);
-
-  delayMicroseconds(20);
-
-  for (int i = 0; i < sizeof(inputMap) / sizeof(input); i++)
-  {
-    if (inputMap[i].player == player && digitalRead(inputMap[i].pin) == LOW)
-    {
-      currentState[player] |= inputMap[i].highFlag;
-    }
-  }
-
-  // When a six-button first connects, it'll spam UP and DOWN,
-  // which signals the game to switch to 6-button polling
-  if (currentState[player] == (ON | UP | DOWN))
-  {
-    sixButtonMode[player] = true;
-  }
-  // When a controller disconnects, revert to three-button polling
-  else if ((currentState[player] & ON) == 0)
-  {
-    sixButtonMode[player] = false;
-  }
-
-  delayMicroseconds(20);
-}
-
-void read6buttons(int player)
-{
-  // Poll for three-button states twice
-  read3buttons(player);
-  read3buttons(player);
-
-  // After two three-button polls, pulse the SELECT line
-  // so the six-button reports the higher button states
-  digitalWrite(SELECT[player], LOW);
-  delayMicroseconds(20);
-  digitalWrite(SELECT[player], HIGH);
-
-  for(int i = 0; i < sizeof(inputMap) / sizeof(input); i++)
-  {
-    if (inputMap[i].player == player && digitalRead(inputMap[i].pin) == LOW)
-    {
-      currentState[player] |= inputMap[i].pulse3Flag;
-    }
-  }
-
-  delayMicroseconds(1000);
 }

 void sendStates()
@@ -183,9 +155,9 @@
   // Only report controller states if at least one has changed
   boolean hasChanged = false;

-  for (int i = 0; i < PLAYERS; i++)
+  for (int player = 0; player < PLAYERS; player++)
   {
-    if (currentState[i] != lastState[i])
+    if (currentState[player] != lastState[player])
     {
       hasChanged = true;
     }
@@ -193,24 +165,24 @@

   if (hasChanged)
   {
-    for (int i = 0; i < PLAYERS; i++)
+    for (int player = 0; player < PLAYERS; player++)
     {
-      Serial.print((currentState[i] & ON) == ON ? "+" : "-");
-      Serial.print((currentState[i] & UP) == UP ? "U" : "0");
-      Serial.print((currentState[i] & DOWN) == DOWN ? "D" : "0");
-      Serial.print((currentState[i] & LEFT) == LEFT ? "L" : "0");
-      Serial.print((currentState[i] & RIGHT) == RIGHT ? "R" : "0");
-      Serial.print((currentState[i] & START) == START ? "S" : "0");
-      Serial.print((currentState[i] & A) == A ? "A" : "0");
-      Serial.print((currentState[i] & B) == B ? "B" : "0");
-      Serial.print((currentState[i] & C) == C ? "C" : "0");
-      Serial.print((currentState[i] & X) == X ? "X" : "0");
-      Serial.print((currentState[i] & Y) == Y ? "Y" : "0");
-      Serial.print((currentState[i] & Z) == Z ? "Z" : "0");
-      Serial.print((currentState[i] & MODE) == MODE ? "M" : "0");
+      Serial.print((currentState[player] & ON) == ON ? "+" : "-");
+      Serial.print((currentState[player] & UP) == UP ? "U" : "0");
+      Serial.print((currentState[player] & DOWN) == DOWN ? "D" : "0");
+      Serial.print((currentState[player] & LEFT) == LEFT ? "L" : "0");
+      Serial.print((currentState[player] & RIGHT) == RIGHT ? "R" : "0");
+      Serial.print((currentState[player] & START) == START ? "S" : "0");
+      Serial.print((currentState[player] & A) == A ? "A" : "0");
+      Serial.print((currentState[player] & B) == B ? "B" : "0");
+      Serial.print((currentState[player] & C) == C ? "C" : "0");
+      Serial.print((currentState[player] & X) == X ? "X" : "0");
+      Serial.print((currentState[player] & Y) == Y ? "Y" : "0");
+      Serial.print((currentState[player] & Z) == Z ? "Z" : "0");
+      Serial.print((currentState[player] & MODE) == MODE ? "M" : "0");

-      Serial.print((i == 0) ? "," : "\n");
-      lastState[i] = currentState[i];
+      Serial.print((player == 0) ? "," : "\n");
+      lastState[player] = currentState[player];
     }
   }
 }


Fixed firware - remember to import the lib!

--- sensor_firmware/sensor_firmware.ino
+++ sensor_firmware/sensor_firmware.ino
@@ -6,23 +6,37 @@

 #include "TimerOne.h"

+
+int counter = 0;
+int average = 0;
+
 void setup() {
-    int baud_rate = 115200;
+    int baud_rate = 9600;
     Serial.begin(baud_rate);

     // Set sample period in microseconds for 8kHz
     long timer_delay_us = 125;
-    Timer.initialize(timer_delay_us);
+    Timer1.initialize(timer_delay_us);
+    Timer1.attachInterrupt(interrupt_loop);
 }

 void loop() {
     // We don't need to do anything for now
 }

+/* Here is the routine that is run when the timer interrupt goes off */
 void interrupt_loop(){
-    // Sample sensor
     int sensorValue = analogRead(A0);
-    Serial.println(sensorValue);
+
+    // Prints out every 5000 samples
+    if(counter == 5000){
+        Serial.println(sensorValue);
+        counter = 0;
+    }
+    else{
+        average = (average + sensorValue)/2;
+        counter++;
+    }
 }


fix update msg

fix update msg

git-svn-id: d8bfcd070c2c81762cca1b3912331324182919ba@15326 0d6f1817-ed0e-0410-87c9-987e46238f29

--- zimodem/zcommand.ino
+++ zimodem/zcommand.ino
@@ -972,7 +972,7 @@
   }
   Serial.print("Done");
   Serial.print(EOLN);
-  Serial.print("Press the Reset button on your modem.");
+  Serial.print("Please wait for modem to restart...");
   ESP.restart();
   return ZOK;
 }


Version 2.05. Fixed time writing error.

Version 2.05. Fixed time writing error.

--- module/module.ino
+++ module/module.ino
@@ -197,10 +197,10 @@
 	// prepare data to be written, time is in format 0xAABBCCDD
 	// timeByte is in format { 0xAA, 0xBB, 0xCC, 0xDD }
 	unsigned char timeByte[4];
-	unsigned char timeByte[3] = time & MSB;
-	unsigned char timeByte[2] = (time >> 8) & MSB;
-	unsigned char timeByte[1] = (time >> 16) & MSB;
-	unsigned char timeByte[0] = (time >> 24) & MSB;
+	timeByte[3] = time & MSB;
+	timeByte[2] = (time >> 8) & MSB;
+	timeByte[1] = (time >> 16) & MSB;
+	timeByte[0] = (time >> 24) & MSB;

 	unsigned char A[] = { 0x00, 0x1A, CMD_WRITE, 0x01, numBlocks, startAddress,
 						0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF,


define to make knownSsid compatible with esp32

--- usermods/ssd1306_i2c_oled_u8g2/wled06_usermod.ino
+++ usermods/ssd1306_i2c_oled_u8g2/wled06_usermod.ino
@@ -69,7 +69,11 @@
   needRedraw = false;

   // Update last known values.
+  #ifdef(ESP8266)
   knownSsid = apActive ? WiFi.softAPSSID() : WiFi.SSID();
+  #else
+  knownSsid = WiFi.SSID();
+  #endif
   knownIp = apActive ? IPAddress(4, 3, 2, 1) : WiFi.localIP();
   knownBrightness = bri;
   knownMode = strip.getMode();


Minor update to WT12 Prep sketch

Minor update to WT12 Prep sketch

--- wt12_prep/wt12_prep.ino
+++ wt12_prep/wt12_prep.ino
@@ -1,3 +1,5 @@
+// use the following line if using Teensy or Teensy++
+// if using the Arduino Leonardo or Mega, comment it out
 HardwareSerial Serial1 = HardwareSerial();

 void setup() {


add attributions

add attributions

--- examples-ltc/2.Effects/4_MusicAndEffects/MusicAndEffects.ino
+++ examples-ltc/2.Effects/4_MusicAndEffects/MusicAndEffects.ino
@@ -2,6 +2,7 @@

 // Music and light effects template: play music on one pin while flashing lights on the others
 // Music code retrieved from http://www.instructables.com/id/Arduino-Tone-Music/
+// Special thanks to ShiCheng Lim

 // Effects Template
 enum effects {  CONSTANT = 0,  FADE = 1,  HEARTBEAT = 2,  TWINKLE = 3 }; // don't delete this line!


Serial.begin(115200)

--- Joystick/Joystick.ino
+++ Joystick/Joystick.ino
@@ -17,6 +17,7 @@
   radio.setChannel(radioChannel);
   radio.setPALevel(RF24_PA_HIGH);
   radio.openWritingPipe(address);
+  Serial.begin(115200);
 }

 void loop() {


Summary

Summary

--- crusty_363_lame_preset/crusty_363_lame_preset.ino
+++ crusty_363_lame_preset/crusty_363_lame_preset.ino
@@ -1,3 +1,8 @@
+//THIS CODE WILL MAKE THE ROBOT RUN A PRE-DETERMINED ROUTINE
+//WHEN THE EMG CHANNEL 1 IS ACTIVATED, THE ROBOT WILL PICK UP THE CUP AND BRING IT TO THE PATIENT
+//AND WHENEVER THE PATIENT WANTS, HE/SHE CAN ACTIVATE THE EMG CHANNEL 2 FOR THE ROBOT TO PUT THE CUP BACK IN THE ORIGINAL POSITION
+
+
 #include <Dynamixel_Serial.h>
 #include <readxBee.h>
 #include <SoftwareSerial.h>
@@ -85,6 +90,7 @@
     //delay(1000);
     emgsignal_counter++;
     emgcounter--;
+    Dynamixel.performMovement(2148, 2048, 2048, OPEN);   //"Erect" position
     break;
     }
   if(emg1 < 100 && emg2 < 100){


added stuff

added stuff


use multitasking instead of delays to calculate bac

--- BAC_Display/BAC_Display.ino
+++ BAC_Display/BAC_Display.ino
@@ -1,41 +1,63 @@
+#include <Thread.h>
 #include <Wire.h>
 #include "FourDigitLCD.h"
 #include "BAC_Lookup.h"

-#define SENSOR_PIN  A0
+#define SENSOR_PIN  A5
 #define S7_ADDR     0x71
 #define DEC_MASK    0b00000001
 #define BAC_START   410     // Beginning ADC value of BAC chart
-#define BAC_END     859     // Lastt ADC value in BAC chart
+#define BAC_END     859     // Last ADC value in BAC chart

 char temp_str[10];
 int sensor_read;
 uint8_t bac;
-FourDigitLCD lcd;
+FourDigitLCD lcd;
+String displayedBac = String("000");
+Thread bacThread = Thread();
+Thread displayThread = Thread();

 void setup() {
-  Serial.begin(9600);
   lcd.init();
   pinMode(SENSOR_PIN, INPUT);
+
+  bacThread.onRun(setBac);
+  bacThread.setInterval(100);
+
+  displayThread.onRun(displayBac);
+  displayThread.setInterval(1);
 }

-void loop() {
+void setBac() {
   sensor_read = analogRead(SENSOR_PIN);
-
-  if ( sensor_read < BAC_START ) {
+
+  if (sensor_read < BAC_START) {
       bac = 0;
-      lcd.display("000");
+      displayedBac = String("000");
   } else {
       sensor_read = sensor_read - BAC_START;
       bac = bac_chart[sensor_read];
       String prefix = String("");
-      if ( bac < 10 ) {
+      if (bac < 10) {
         prefix = String("00");
-      } else if ( bac < 100 ) {
+      } else if (bac < 100) {
         prefix = String("0");
       }
-      lcd.display(String(prefix + String(bac)));
+      displayedBac = String(prefix + String(bac));
   }
-  //delay(100);
 }

+void displayBac() {
+  lcd.display(displayedBac);
+}
+
+void loop() {
+  if (bacThread.shouldRun()) {
+    bacThread.run();
+  }
+
+  if (displayThread.shouldRun()) {
+    displayThread.run();
+  }
+}
+


GCS Update

GCS Update

--- BiotechHardware/gcs/gcs.ino
+++ BiotechHardware/gcs/gcs.ino
@@ -32,11 +32,16 @@
 int h_lower;
 int h_upper;
 int l_target;
+boolean fan_pump;

 int BH1750address = 0x23;
 byte buff[2];

 void setup(){
+  Serial.begin(9600);
+  Ethernet.begin(mac, ip);
+  Serial.println(Ethernet.localIP());
+
   pinMode(relay_1, OUTPUT);
   pinMode(relay_2, OUTPUT);
   pinMode(relay_3, OUTPUT);
@@ -56,9 +61,6 @@
   lcd.print((char)223);
   lcd.setCursor(19,3);
   lcd.print("C");
-  Serial.begin(9600);
-  Ethernet.begin(mac, ip);
-  Serial.println(Ethernet.localIP());
   delay(1000);
 }

@@ -91,8 +93,8 @@
   float temp = temp_sensor.getTempCByIndex(0);
   Serial.println(temp);

-  int h = constrain(analogRead(h_pin), 255, 1005);
-  int soil = map(h, 255, 1005, 100, 0);
+  int h = constrain(analogRead(h_pin), 255, 1023);
+  int soil = map(h, 255, 1023, 100, 0);
   Serial.println(soil);

   DHT11.read(ah_pin);
@@ -113,6 +115,22 @@

   if(soil > h_upper){
     digitalWrite(relay_2, LOW);
+  }
+
+  if(ah > 70){
+    fan_pump = true;
+    digitalWrite(relay_3, HIGH);
+    digitalWrite(relay_4, HIGH);
+  }else{
+    fan_pump = false;
+    digitalWrite(relay_3, LOW);
+    digitalWrite(relay_4, LOW);
+  }
+
+  if(temp > 40){
+    digitalWrite(relay_3, HIGH);
+  }else if(!fan_pump){
+    digitalWrite(relay_3, LOW);
   }

   send_log(lux, temp, soil, ah);