Interrupt hanl

Interrupt hanl

--- TrafficCounter/TrafficCounter.ino
+++ TrafficCounter/TrafficCounter.ino
@@ -49,7 +49,10 @@
 #define WHEEL_DELAY     50 //number of milliseconds to create accurate readings for cars. prevents bounce.
 #define WHEEL_SPACEING  2.75 //average spacing between wheels of car (METERS)
 #define CAR_TIMEOUT     3000
-#define SPEED_BUFFER_SIZE     10
+#define SPEED_BUFFER_SIZE     40
+
+//#define INTERRUPT_FREQENCY 31250  // compare match register 16MHz/256/2Hz
+#define INTERRUPT_FREQENCY 409600 // 100Hz

 // These are the interrupt and control pins
 #define ADAFRUIT_CC3000_IRQ   3  // MUST be an interrupt pin!
@@ -74,7 +77,7 @@

 char* topic = (char*) malloc(1);

-// byte server[] = { 172, 16, 0, 2 };
+// byte server[] = { 192, 168, 1, 121 };
 char server[] = "aceone.se";

 Adafruit_CC3000 cc3000 = Adafruit_CC3000(ADAFRUIT_CC3000_CS, ADAFRUIT_CC3000_IRQ, ADAFRUIT_CC3000_VBAT, SPI_CLOCK_DIVIDER);
@@ -95,410 +98,505 @@

 unsigned long timeStamp;

+int initError = 1;
+
+
+
 void setup() {
-	pinMode(PRESSURE_READING_PIN, INPUT);
-//	pinMode(CONFIGURE_BUTTON_PIN, INPUT_PULLUP);
-	pinMode(LED_INDICATOR_PIN, OUTPUT);
-	pinMode(PRESSURE_IRQ_PIN, INPUT);
-
-	Serial.begin(115200);
-	 Serial.print("Free RAM: "); Serial.println(getFreeRam(), DEC);
-
-	Serial.println();
-	eeprom_read_string(0, placeName, PLACE_NAME_LENGTH);
-	buildTopic();
-
-	Serial.print(F("Conecting to WIFI ."));
-	digitalWrite(LED_INDICATOR_PIN, HIGH);
-
-	if (!cc3000.begin()) {
-		Serial.println();
-		Serial.println(F("Faild to begin"));
-		while (1)
-			;
-	}
-
-	Serial.print(F("."));
-
-	Serial.println(F(" OK"));
-
-	uint8_t macAddress[MAC_LENGTH];
-
-	cc3000.getMacAddress(macAddress);
-
-	bytesToHexString(macAddress, macHex, MAC_LENGTH);
-
-	// read local air pressure and create offset.
-	triggerValue = analogRead(A0) + THRESHOLD;
+  pinMode(PRESSURE_READING_PIN, INPUT);
+  //	pinMode(CONFIGURE_BUTTON_PIN, INPUT_PULLUP);
+  pinMode(LED_INDICATOR_PIN, OUTPUT);
+  pinMode(PRESSURE_IRQ_PIN, INPUT);
+
+  Serial.begin(115200);
+  Serial.print("Free RAM: ");
+  Serial.println(getFreeRam(), DEC);
+
+  Serial.println();
+  eeprom_read_string(0, placeName, PLACE_NAME_LENGTH);
+  buildTopic();
+
+  Serial.print(F("Conecting to WIFI ."));
+  digitalWrite(LED_INDICATOR_PIN, HIGH);
+
+  if (!cc3000.begin()) {
+    Serial.println();
+    Serial.println(F("Faild to begin"));
+    errorMessage(2);
+  }
+
+  Serial.print(F("."));
+
+  if (!cc3000.deleteProfiles()) {
+    Serial.println(F("Failed!"));
+    errorMessage(3);
+  }
+
+  Serial.println(F(" OK"));
+
+  uint8_t macAddress[MAC_LENGTH];
+
+  cc3000.getMacAddress(macAddress);
+
+  bytesToHexString(macAddress, macHex, MAC_LENGTH);
+
+  // read local air pressure and create offset.
+  triggerValue = analogRead(A0) + THRESHOLD;
+  delay(1000);
+  Serial.println(F("Traffic Counter"));
+  Serial.println(F("___________________________________________________"));
+  Serial.println();
+  Serial.print(F("Place: "));
+  Serial.println(placeName);
+  Serial.print(F("Local Air Pressure: "));
+  Serial.println(triggerValue - THRESHOLD);
+  Serial.println(F("___________________________________________________"));
+
+  String tmpName = "TC-";
+  tmpName.concat(macHex);
+  mqttName[tmpName.length()];
+  tmpName.toCharArray(mqttName, tmpName.length() + 1);
+  Serial.print(F("Mqtt name: "));
+  Serial.println(mqttName);
+
+  while(!enableConnection()) {
+    Serial.print(F("Failed to enable connection"));
+    //while(1);
+    shutdownConnection();
+    delay(1000);
+    Serial.print(F("Retrying to connect"));
+  }
+
+
+  digitalWrite(LED_INDICATOR_PIN, LOW);
 	delay(1000);
-	Serial.println(F("Traffic Counter"));
-	Serial.println(F("___________________________________________________"));
-	Serial.println();
-	Serial.print(F("Place: "));
-	Serial.println(placeName);
-	Serial.print(F("Local Air Pressure: "));
-	Serial.println(triggerValue - THRESHOLD);
-	Serial.println(F("___________________________________________________"));
-
-	String tmpName = "TC-";
-	tmpName.concat(macHex);
-	mqttName[tmpName.length()];
-	tmpName.toCharArray(mqttName, tmpName.length() + 1);
-	Serial.print(F("Mqtt name: "));
-	Serial.println(mqttName);
-
-	while (!enableConnection()) {
-		delay(100);
-	}
-	timeStamp = millis();
-
-	digitalWrite(LED_INDICATOR_PIN, LOW);
-//	delay(10000);
-//	Serial.println(F("Shut down!"));
-//	shutdownConnection();
-//	delay(10000);
-//	Serial.println(F("Sleep now!"));
-//	delay(100);
-//	sleepNow();
-	 Serial.print("Free RAM: "); Serial.println(getFreeRam(), DEC);
-
+  	Serial.println(F("Shut down!"));
+  	shutdownConnection();
+  	delay(1000);
+  	Serial.println(F("Sleep now!"));
+  	delay(100);
+  	sleepNow();
+  Serial.print("Free RAM: ");
+  Serial.println(getFreeRam(), DEC);
+  initError = 0;
 }

 void loop() {
-	//Serial.println(analogRead(A0));
-
-	client.loop();
-
-	//1 - TUBE IS PRESSURIZED INITIALLY
-	if (analogRead(A0) > triggerValue) {
-		if (strikeNumber == 0 && isMeasuring == 0) { // FIRST HIT
-			Serial.println();
-			Serial.println(F("Car HERE. "));
-			firstWheel = millis();
-			isMeasuring = 1;
-		}
-		if (strikeNumber == 1 && isMeasuring == 1) { // SECOND HIT
-			Serial.println(F("Car GONE."));
-			secondWheel = millis();
-			isMeasuring = 0;
-		}
-	}
-
-	//2 - TUBE IS STILL PRESSURIZED
-	while (analogRead(A0) > max && isMeasuring == 1) { //is being pressed, in all cases. to measure the max pressure.
-		max = analogRead(A0);
-	}
-
-	//3 - TUBE IS RELEASED
-	if (analogRead(A0) < triggerValue - 1 && countThis == 0) { //released by either wheel
-		if (strikeNumber == 0 && isMeasuring == 1 && (millis() - firstWheel > WHEEL_DELAY)) {
-			strikeNumber = 1;
-		}
-		if (strikeNumber == 1 && isMeasuring == 0 && (millis() - secondWheel > WHEEL_DELAY)) {
-			countThis = 1;
-		}
-	}
-
-	//4 - PRESSURE READING IS ACCEPTED AND RECORDED
-	if ((analogRead(A0) < triggerValue - 1) && ((countThis == 1 && isMeasuring == 0) || ((millis() - firstWheel) > CAR_TIMEOUT) && isMeasuring == 1)) { //has been released for enough time.
-		Serial.print(F("Pressure Reached = "));
-		Serial.println(max);
-		//Serial.print("time between wheels = ");
-		wheelTime = ((secondWheel - firstWheel) / 3600000);
-		//Serial.println(wheelTime);
-		int time = ((millis() / 1000) / 60) + 1; // the number of seconds since first record.
-		speed = (WHEEL_SPACEING / 1000) / wheelTime;
-		if (speed > 0) {
-			Serial.print(F("Estimated Speed (km/h) = "));
-			Serial.println(speed);
-		} else {
-			speed = 1.0;
-		}
-		publish(speed);
-		//RESET ALL VALUES
-		max = 0;
-		strikeNumber = 0;
-		countThis = 0;
-		isMeasuring = 0;
-	}
-	unsigned long ml = millis();
-	if (connected() && ml > timeStamp + CONNECTION_ALIVE_TIME) {
-		shutdownConnection();
-	}
-	if (!bufferEmpty() && ml > timeStamp + PUBLISH_DELAY) {
-		if (connected()) {
-			publishBuffer();
-		} else {
-			if (!enableConnection()) {
-				delay(100);
-			}
-		}
-	}
+  client.loop();
+  checkPressure();
+
+  unsigned long ml = millis();
+
+  if (connected() && ml > timeStamp + CONNECTION_ALIVE_TIME) {
+    shutdownConnection();
+    delay(100);
+    sleepNow();
+  }
+  if (!bufferEmpty() && ml > timeStamp + PUBLISH_DELAY) {
+    if (connected()) {
+      publishBuffer();
+    }
+    else {
+      if (!enableConnection()) {
+        shutdownConnection();
+        timeStamp += PUBLISH_DELAY;
+      }
+    }
+  }
+}
+
+void checkPressure(){
+  //1 - TUBE IS PRESSURIZED INITIALLY
+  if (analogRead(A0) > triggerValue) {
+    if (strikeNumber == 0 && isMeasuring == 0) { // FIRST HIT
+      Serial.println();
+      Serial.println(F("Car HERE. "));
+      firstWheel = millis();
+      isMeasuring = 1;
+    }
+    if (strikeNumber == 1 && isMeasuring == 1) { // SECOND HIT
+      Serial.println(F("Car GONE."));
+      secondWheel = millis();
+      isMeasuring = 0;
+    }
+  }
+
+  //2 - TUBE IS STILL PRESSURIZED
+  while (analogRead(A0) > max && isMeasuring == 1) { //is being pressed, in all cases. to measure the max pressure.
+    max = analogRead(A0);
+  }
+
+  //3 - TUBE IS RELEASED
+  if (analogRead(A0) < triggerValue - 1 && countThis == 0) { //released by either wheel
+    if (strikeNumber == 0 && isMeasuring == 1 && (millis() - firstWheel > WHEEL_DELAY)) {
+      strikeNumber = 1;
+    }
+    if (strikeNumber == 1 && isMeasuring == 0 && (millis() - secondWheel > WHEEL_DELAY)) {
+      countThis = 1;
+    }
+  }
+
+  //4 - PRESSURE READING IS ACCEPTED AND RECORDED
+  if ((analogRead(A0) < triggerValue - 1) && ((countThis == 1 && isMeasuring == 0) || ((millis() - firstWheel) > CAR_TIMEOUT) && isMeasuring == 1)) { //has been released for enough time.
+    Serial.print(F("Pressure Reached = "));
+    Serial.println(max);
+    //Serial.print("time between wheels = ");
+    wheelTime = ((secondWheel - firstWheel) / 3600000);
+    //Serial.println(wheelTime);
+    int time = ((millis() / 1000) / 60) + 1; // the number of seconds since first record.
+    speed = (WHEEL_SPACEING / 1000) / wheelTime;
+    if (speed > 0) {
+      Serial.print(F("Estimated Speed (km/h) = "));
+      Serial.println(speed);
+    }
+    else {
+      speed = 1.0;
+    }
+    publish(speed);
+    //RESET ALL VALUES
+    max = 0;
+    strikeNumber = 0;
+    countThis = 0;
+    isMeasuring = 0;
+  }
 }

 void publishBuffer() {
-	while(!bufferEmpty()){
-		float speed = bufferRead();
-		char tmp[6];
-		dtostrf(speed, 1, 2, tmp);
-		client.publish(topic, tmp);
-	}
-	timeStamp = millis();
+  while(!bufferEmpty()){
+    float speed = bufferRead();
+    publishToClient(speed)
+  }
+  timeStamp = millis();
 }

 void publish(float speed) {
-	timeStamp = millis();
-	if (connected()) {
-		char tmp[6];
-		dtostrf(speed, 1, 2, tmp);
-		client.publish(topic, tmp);
-	} else {
-		bufferWrite(speed);
-	}
-}
+  timeStamp = millis();
+  if (bufferEmpty() && connected()) {
+    publishToClient(speed)
+  } else {
+    bufferWrite(speed);
+  }
+}
+
+void publishToClient(float speed) {
+    char tmp[6];
+    dtostrf(speed, 1, 2, tmp);
+    client.publish(topic, tmp);
+}
+

 int bufferFull() {
-	return speed_buffer_count == SPEED_BUFFER_SIZE;
+  return speed_buffer_count == SPEED_BUFFER_SIZE;
 }

 int bufferEmpty() {
-	return speed_buffer_count == 0;
+  return speed_buffer_count == 0;
 }

 void bufferWrite(float speed) {
-	int end = (speed_buffer_start + speed_buffer_count) % SPEED_BUFFER_SIZE;
-	speed_buffer[end] = speed;
-	if (speed_buffer_count == SPEED_BUFFER_SIZE) {
-		speed_buffer_start = (speed_buffer_start + 1) % SPEED_BUFFER_SIZE; /* full, overwrite */
-		Serial.println(F("Buffer full ower writing"));
-	} else {
-		++speed_buffer_count;
-	}
+  int end = (speed_buffer_start + speed_buffer_count) % SPEED_BUFFER_SIZE;
+  speed_buffer[end] = speed;
+  if (speed_buffer_count == SPEED_BUFFER_SIZE) {
+    speed_buffer_start = (speed_buffer_start + 1) % SPEED_BUFFER_SIZE; /* full, overwrite */
+    Serial.println(F("Buffer full ower writing"));
+  }
+  else {
+    ++speed_buffer_count;
+  }
 }

 float bufferRead() {
-	float speed = speed_buffer[speed_buffer_start];
-	speed_buffer_start = (speed_buffer_start + 1) % SPEED_BUFFER_SIZE;
-	--speed_buffer_count;
-	return speed;
+  float speed = speed_buffer[speed_buffer_start];
+  speed_buffer_start = (speed_buffer_start + 1) % SPEED_BUFFER_SIZE;
+  --speed_buffer_count;
+  return speed;
 }

 void sleepNow()         // here we put the arduino to sleep
 {
-	// Turn off the ADC while asleep.
-	power_adc_disable();
-	power_all_disable();
-
-	/* Now is the time to set the sleep mode. In the Atmega8 datasheet
-	 * http://www.atmel.com/dyn/resources/prod_documents/doc2486.pdf on page 35
-	 * there is a list of sleep modes which explains which clocks and
-	 * wake up sources are available in which sleep mode.
-	 *
-	 * In the avr/sleep.h file, the call names of these sleep modes are to be found:
-	 *
-	 * The 5 different modes are:
-	 *     SLEEP_MODE_IDLE         -the least power savings
-	 *     SLEEP_MODE_ADC
-	 *     SLEEP_MODE_PWR_SAVE
-	 *     SLEEP_MODE_STANDBY
-	 *     SLEEP_MODE_PWR_DOWN     -the most power savings
-	 *
-	 * For now, we want as much power savings as possible, so we
-	 * choose the according
-	 * sleep mode: SLEEP_MODE_PWR_DOWN
-	 *
-	 */
-	set_sleep_mode (SLEEP_MODE_PWR_DOWN);   // sleep mode is set here
-
-	sleep_enable();          // enables the sleep bit in the mcucr register
-							 // so sleep is possible. just a safety pin
-
-	/* Now it is time to enable an interrupt. We do it here so an
-	 * accidentally pushed interrupt button doesn't interrupt
-	 * our running program. if you want to be able to run
-	 * interrupt code besides the sleep function, place it in
-	 * setup() for example.
-	 *
-	 * In the function call attachInterrupt(A, B, C)
-	 * A   can be either 0 or 1 for interrupts on pin 2 or 3.
-	 *
-	 * B   Name of a function you want to execute at interrupt for A.
-	 *
-	 * C   Trigger mode of the interrupt pin. can be:
-	 *             LOW        a low level triggers
-	 *             CHANGE     a change in level triggers
-	 *             RISING     a rising edge of a level triggers
-	 *             FALLING    a falling edge of a level triggers
-	 *
-	 * In all but the IDLE sleep modes only LOW can be used.
-	 */
-
-	attachInterrupt(PRESSURE_IRQ, wakeUpNow, RISING); // use interrupt 0 (pin 2) and run function
-	// wakeUpNow when pin 2 gets LOW
-
-	sleep_mode();            // here the device is actually put to sleep!!
-							 // THE PROGRAM CONTINUES FROM HERE AFTER WAKING UP
-
-	sleep_disable();         // first thing after waking from sleep:
-							 // disable sleep...
-	detachInterrupt(PRESSURE_IRQ);      // disables interrupt 0 on pin 2 so the
-	// wakeUpNow code will not be executed
-	// during normal running time.
-	power_all_enable();
-	Serial.print(F("Back from sleep"));
-
+  // Turn off the ADC while asleep.
+  power_adc_disable();
+  power_all_disable();
+
+  /* Now is the time to set the sleep mode. In the Atmega8 datasheet
+   	 * http://www.atmel.com/dyn/resources/prod_documents/doc2486.pdf on page 35
+   	 * there is a list of sleep modes which explains which clocks and
+   	 * wake up sources are available in which sleep mode.
+   	 *
+   	 * In the avr/sleep.h file, the call names of these sleep modes are to be found:
+   	 *
+   	 * The 5 different modes are:
+   	 *     SLEEP_MODE_IDLE         -the least power savings
+   	 *     SLEEP_MODE_ADC
+   	 *     SLEEP_MODE_PWR_SAVE
+   	 *     SLEEP_MODE_STANDBY
+   	 *     SLEEP_MODE_PWR_DOWN     -the most power savings
+   	 *
+   	 * For now, we want as much power savings as possible, so we
+   	 * choose the according
+   	 * sleep mode: SLEEP_MODE_PWR_DOWN
+   	 *
+   	 */
+  set_sleep_mode (SLEEP_MODE_PWR_DOWN);   // sleep mode is set here
+
+  sleep_enable();          // enables the sleep bit in the mcucr register
+  // so sleep is possible. just a safety pin
+
+  /* Now it is time to enable an interrupt. We do it here so an
+   	 * accidentally pushed interrupt button doesn't interrupt
+   	 * our running program. if you want to be able to run
+   	 * interrupt code besides the sleep function, place it in
+   	 * setup() for example.
+   	 *
+   	 * In the function call attachInterrupt(A, B, C)
+   	 * A   can be either 0 or 1 for interrupts on pin 2 or 3.
+   	 *
+   	 * B   Name of a function you want to execute at interrupt for A.
+   	 *
+   	 * C   Trigger mode of the interrupt pin. can be:
+   	 *             LOW        a low level triggers
+   	 *             CHANGE     a change in level triggers
+   	 *             RISING     a rising edge of a level triggers
+   	 *             FALLING    a falling edge of a level triggers
+   	 *
+   	 * In all but the IDLE sleep modes only LOW can be used.
+   	 */
+
+  attachInterrupt(PRESSURE_IRQ, wakeUpNow, FALLING); // use interrupt 0 (pin 2) and run function
+  // wakeUpNow when pin 2 gets LOW
+
+  sleep_mode();            // here the device is actually put to sleep!!
+  // THE PROGRAM CONTINUES FROM HERE AFTER WAKING UP
+
+  sleep_disable();         // first thing after waking from sleep:
+  // disable sleep...
+  detachInterrupt(PRESSURE_IRQ);      // disables interrupt 0 on pin 2 so the
+  // wakeUpNow code will not be executed
+  // during normal running time.
+  power_all_enable();
+  Serial.print(F("Back from sleep"));
+
+}
+
+void startTimeIntrrupt(){
+  // initialize timer1
+  noInterrupts();           // disable all interrupts
+  TCCR1A = 0;
+  TCCR1B = 0;
+  TCNT1  = 0;
+
+  OCR1A =  INTERRUPT_FREQENCY;
+  TCCR1B |= (1 << WGM12);   // CTC mode
+  TCCR1B |= (1 << CS12);    // 256 prescaler
+  TIMSK1 |= (1 << OCIE1A);  // enable timer compare interrupt
+  interrupts();             // enable all interrupts
+}
+
+void stopTimeIntrrupt(){
+  noInterrupts();           // disable all interrupts
+  TIMSK1 &= ~(1 << OCIE1A);  // disable timer compare interrupt
+  interrupts();             // enable all interrupts
+}
+
+ISR(TIMER1_COMPA_vect)          // timer compare interrupt service routine
+{
+  checkPressure();
 }

 // Enable the CC3000 and connect to the wifi network.
 // Return true if enabled and connected, false otherwise.
 boolean enableConnection() {
-	Serial.println(F("Turning on CC3000."));
-
-	if (!digitalRead(ADAFRUIT_CC3000_VBAT)) {
-		unsigned long t = millis();
-		// Turn on the CC3000.
-		wlan_start(0);
-		Serial.print(F("CC3000 Started in "));
-		Serial.print(millis()-t);
-		Serial.println(F(" millis"));
-		return false;
-	}
-	if (!cc3000.checkConnected()) {
-		unsigned long t = millis();
-		// Connect to the AP.
-		if (!cc3000.connectToAP(WLAN_SSID, WLAN_PASS, WLAN_SECURITY)) {
-			// Couldn't connect for some reason.  Fail and move on so the hardware goes back to sleep and tries again later.
-			Serial.println(F("Failed!"));
-			return false;
-		}
-		Serial.print(F("Connected in "));
-		Serial.print(millis()-t);
-		Serial.println(F(" millis"));
-		return false;
-	}
-	// Wait for DHCP to be complete.  Make a best effort with 5 attempts, then fail and move on.
-	Serial.println(F("Request DHCP"));
-//	int attempts = 0;
-//	while (!cc3000.checkDHCP()) {
-//		if (attempts > 5) {
-//			Serial.println(F("DHCP didn't finish!"));
-//			return false;
-//		}
-//		attempts += 1;
-//		delay(100);
-//	}
-	if (!cc3000.checkDHCP()) {
-		Serial.println(F("DHCP didn't finish!"));
-		return false;
-	}
-	Serial.println(F("Finished DHCP"));
-
-	if (!client.connected()) {
-		if (!client.connect(mqttName)) {
-			Serial.println(F("MQTT Connetion error"));
-			return false;
-		}
-		client.publish("traffic/counter/start", mqttName);
-		client.publish("traffic/counter/place", placeName);
-		client.subscribe("traffic/counter/config");
-		Serial.print(F("Conneted to: "));
-		Serial.println(server);
-	}
-	// Return success, the CC3000 is enabled and connected to the network.
-	return true;
+  Serial.println(F("Turning on CC3000."));
+
+  if(!initError){
+    startTimeIntrrupt();
+  }
+  if (!digitalRead(ADAFRUIT_CC3000_VBAT)) {
+    unsigned long t = millis();
+    // Turn on the CC3000.
+    wlan_start(0);
+    Serial.print(F("CC3000 Started in "));
+    Serial.print(millis()-t);
+    Serial.println(F(" millis"));
+  }
+  if (!cc3000.checkConnected()) {
+    Serial.print(F("Connectint to AP"));
+    unsigned long t = millis();
+    // Connect to the AP.
+    if (!cc3000.connectToAP(WLAN_SSID, WLAN_PASS, WLAN_SECURITY)) {
+      // Couldn't connect for some reason.  Fail and move on so the hardware goes back to sleep and tries again later.
+      Serial.println(F("Failed!"));
+      if(initError){
+        errorMessage(4);
+      }
+      Serial.println();
+      return false;
+    }
+    Serial.print(F(" in "));
+    Serial.print(millis()-t);
+    Serial.println(F(" millis"));
+  }
+  /*
+  Serial.println(F("Set static IP"));
+   uint32_t ipAddress = cc3000.IP2U32(192, 168, 1, 19);
+   uint32_t netMask = cc3000.IP2U32(255, 255, 255, 0);
+   uint32_t defaultGateway = cc3000.IP2U32(192, 168, 1, 1);
+   uint32_t dns = cc3000.IP2U32(8, 8, 4, 4);
+   if (!cc3000.setStaticIPAddress(ipAddress, netMask, defaultGateway, dns)) {
+   Serial.println(F("Failed to set static IP!"));
+   if(initError){
+   errorMessage(5);
+   }
+   while(1);
+   }
+   */
+  /* Optional: Revert back from static IP addres to use DHCP.
+   See note for setStaticIPAddress above, this only needs to be
+   called once and will be remembered afterwards by the CC3000.
+   */
+  /*
+   if (!cc3000.setDHCP()) {
+   Serial.println(F("Failed to set DHCP!"));
+   while(1);
+   }
+   */
+
+
+  Serial.print(F("Request DHCP"));
+  unsigned long t = millis();
+  int attempts = 0;
+  while (!cc3000.checkDHCP()) {
+    if (attempts > 50) {
+      Serial.println(F(" DHCP didn't finish!"));
+      //      if(initError){
+      //         errorMessage(5);
+      //      }
+      return false;
+    }
+    attempts += 1;
+    delay(200);
+  }
+  Serial.print(" in ");
+  Serial.print(millis()-t);
+  Serial.println(F(" millis"));
+  //	while (!cc3000.checkDHCP()) {
+  //		delay(100);
+  //	}
+  Serial.println(F("Finished DHCP"));
+
+  Serial.println(F("Connecting to MQTT server"));
+  if (!client.connected()) {
+    if (!client.connect(mqttName)) {
+      Serial.println(F("MQTT Connetion error"));
+      if(initError){
+        errorMessage(6);
+      }
+      return false;
+    }
+    client.publish("traffic/counter/start", mqttName);
+    client.publish("traffic/counter/place", placeName);
+    client.subscribe("traffic/counter/config");
+    Serial.print(F("Conneted to: "));
+    Serial.print(server);
+    Serial.println();
+  }
+
+  if(!initError){
+    startTimeIntrrupt();
+  }
+
+  // Return success, the CC3000 is enabled and connected to the network.
+  timeStamp = millis();
+  return true;
 }

 // Disconnect from wireless network and shut down the CC3000.
 void shutdownConnection() {
-	if (client.connected()) {
-		client.disconnect();
-		Serial.println(F("Disconnected MQTT"));
-	}
-	// Disconnect from the AP if connected.
-	// This might not be strictly necessary, but I found
-	// it was sometimes difficult to quickly reconnect to
-	// my AP if I shut down the CC3000 without first
-	// disconnecting from the network.
-	if (cc3000.checkConnected()) {
-		cc3000.disconnect();
-	}
-
-	// Wait for the CC3000 to finish disconnecting before
-	// continuing.
-	while (cc3000.checkConnected()) {
-		delay(100);
-	}
-	Serial.println(F("Disconnected CC3000"));
-
-	// Shut down the CC3000.
-	wlan_stop();
-
-	Serial.println(F("CC3000 shut down."));
+  if (client.connected()) {
+    client.disconnect();
+    Serial.println(F("Disconnected MQTT"));
+  }
+  // Disconnect from the AP if connected.
+  // This might not be strictly necessary, but I found
+  // it was sometimes difficult to quickly reconnect to
+  // my AP if I shut down the CC3000 without first
+  // disconnecting from the network.
+  if (cc3000.checkConnected()) {
+    cc3000.disconnect();
+  }
+
+  // Wait for the CC3000 to finish disconnecting before
+  // continuing.
+  while (cc3000.checkConnected()) {
+    delay(100);
+  }
+  Serial.println(F("Disconnected CC3000"));
+
+  // Shut down the CC3000.
+  wlan_stop();
+
+  Serial.println(F("CC3000 shut down."));
 }

 boolean connected() {
-	return digitalRead(ADAFRUIT_CC3000_VBAT) && cc3000.checkConnected() && client.connected();
+  return digitalRead(ADAFRUIT_CC3000_VBAT) && cc3000.checkConnected() && client.connected();
 }

 void buildTopic() {
-	free(topic);
-	String tmpTopic = "traffic/counter/car/";
-	tmpTopic.concat(placeName);
-	topic = (char*) malloc(tmpTopic.length());
-	tmpTopic.toCharArray(topic, tmpTopic.length() + 1);
+  free(topic);
+  String tmpTopic = "traffic/counter/car/";
+  tmpTopic.concat(placeName);
+  topic = (char*) malloc(tmpTopic.length());
+  tmpTopic.toCharArray(topic, tmpTopic.length() + 1);
 }

 void wakeUpNow()        // here the interrupt is handled after wakeup
 {
-	// execute code here after wake-up before returning to the loop() function
-	// timers and code using timers (serial.print and more...) will not work here.
-	// we don't really need to execute any special functions here, since we
-	// just want the thing to wake up
 }

 void callback(char* topic, byte* payload, unsigned int length) {
-	// handle message arrived
-	if (length < MAC_HEX_LENGTH) {
-		return;
-	}
-
-	for (int i = 0; i < MAC_HEX_LENGTH - 1; i++) {
-		if (payload[i] != macHex[i]) {
-			return;
-		}
-	}
-
-	int len = length - MAC_HEX_LENGTH + 1;
-	// Allocate the correct amount of memory for the payload copy
-	char* p = (char*) malloc(len);
-	int i;
-	// Copy the payload to the new buffer
-	for (i = 0; i < len; i++) {
-		p[i] = payload[MAC_HEX_LENGTH + i];
-	}
-	p[i] = '\0';
-	eeprom_write_string(0, p);
-	memcpy(placeName, p, i + 1);
-	// Free the memory
-	free(p);
-	buildTopic();
+  // handle message arrived
+  if (length < MAC_HEX_LENGTH) {
+    return;
+  }
+
+  for (int i = 0; i < MAC_HEX_LENGTH - 1; i++) {
+    if (payload[i] != macHex[i]) {
+      return;
+    }
+  }
+
+  int len = length - MAC_HEX_LENGTH + 1;
+  // Allocate the correct amount of memory for the payload copy
+  char* p = (char*) malloc(len);
+  int i;
+  // Copy the payload to the new buffer
+  for (i = 0; i < len; i++) {
+    p[i] = payload[MAC_HEX_LENGTH + i];
+  }
+  p[i] = '\0';
+  eeprom_write_string(0, p);
+  memcpy(placeName, p, i + 1);
+  // Free the memory
+  free(p);
+  buildTopic();
 }

 static char nibbleToChar(uint8_t nibble) {
-	if (nibble >= 0 && nibble < 10) {
-		return '0' + nibble;
-	}
-	return 'A' + nibble - 10;
+  if (nibble >= 0 && nibble < 10) {
+    return '0' + nibble;
+  }
+  return 'A' + nibble - 10;
 }

 /* Convert a buffer of binary values into a hex string representation */
 void bytesToHexString(uint8_t *bytes, char *retval, int buflen) {
-	int i;
-	for (i = 0; i < buflen; i++) {
-		retval[i * 2] = nibbleToChar(bytes[i] >> 4);
-		retval[i * 2 + 1] = nibbleToChar(bytes[i] & 0x0f);
-	}
-	retval[i * 2] = '\0';
+  int i;
+  for (i = 0; i < buflen; i++) {
+    retval[i * 2] = nibbleToChar(bytes[i] >> 4);
+    retval[i * 2 + 1] = nibbleToChar(bytes[i] & 0x0f);
+  }
+  retval[i * 2] = '\0';
 }

 //
@@ -509,16 +607,16 @@
 // If false is returned, nothing gets written to the eeprom.
 //
 boolean eeprom_write_string(int addr, char* string) {
-	// actual number of bytes to be written
-	int numBytes;
-
-	// we'll need to write the string contents
-	// plus the string terminator byte (0x00)
-	numBytes = strlen(string) + 1;
-	for (int i = 0; i < numBytes; i++) {
-		EEPROM.write(addr + i, string[i]);
-	}
-	return true;
+  // actual number of bytes to be written
+  int numBytes;
+
+  // we'll need to write the string contents
+  // plus the string terminator byte (0x00)
+  numBytes = strlen(string) + 1;
+  for (int i = 0; i < numBytes; i++) {
+    EEPROM.write(addr + i, string[i]);
+  }
+  return true;
 }

 //
@@ -535,55 +633,69 @@
 // The last condition is what should normally occur.
 //
 boolean eeprom_read_string(int addr, char* buffer, int bufSize) {
-	// byte read from eeprom
-	byte ch;
-
-	// number of bytes read so far
-	int bytesRead;
-
-	// how can we store bytes in an empty buffer ?
-	if (bufSize == 0) {
-		return false;
-	}
-
-	// is there is room for the string terminator only,
-	// no reason to go further
-	if (bufSize == 1) {
-		buffer[0] = 0;
-		return true;
-	}
-
-	// initialize byte counter
-	bytesRead = 0;
-
-	// read next byte from eeprom
-	ch = EEPROM.read(addr + bytesRead);
-
-	// store it into the user buffer
-	buffer[bytesRead] = ch;
-
-	// increment byte counter
-	bytesRead++;
-
-	// stop conditions:
-	// - the character just read is the string terminator one (0x00)
-	// - we have filled the user buffer
-	// - we have reached the last eeprom address
-	while ((ch != 0x00) && (bytesRead < bufSize)) {
-		// if no stop condition is met, read the next byte from eeprom
-		ch = EEPROM.read(addr + bytesRead);
-
-		// store it into the user buffer
-		buffer[bytesRead] = ch;
-
-		// increment byte counter
-		bytesRead++;
-	}
-
-	// make sure the user buffer has a string terminator
-	// (0x00) as its last byte
-	if ((ch != 0x00) && (bytesRead >= 1)) {
-		buffer[bytesRead - 1] = 0;
-	}
-	return true;
-}
+  // byte read from eeprom
+  byte ch;
+
+  // number of bytes read so far
+  int bytesRead;
+
+  // how can we store bytes in an empty buffer ?
+  if (bufSize == 0) {
+    return false;
+  }
+
+  // is there is room for the string terminator only,
+  // no reason to go further
+  if (bufSize == 1) {
+    buffer[0] = 0;
+    return true;
+  }
+
+  // initialize byte counter
+  bytesRead = 0;
+
+  // read next byte from eeprom
+  ch = EEPROM.read(addr + bytesRead);
+
+  // store it into the user buffer
+  buffer[bytesRead] = ch;
+
+  // increment byte counter
+  bytesRead++;
+
+  // stop conditions:
+  // - the character just read is the string terminator one (0x00)
+  // - we have filled the user buffer
+  // - we have reached the last eeprom address
+  while ((ch != 0x00) && (bytesRead < bufSize)) {
+    // if no stop condition is met, read the next byte from eeprom
+    ch = EEPROM.read(addr + bytesRead);
+
+    // store it into the user buffer
+    buffer[bytesRead] = ch;
+
+    // increment byte counter
+    bytesRead++;
+  }
+
+  // make sure the user buffer has a string terminator
+  // (0x00) as its last byte
+  if ((ch != 0x00) && (bytesRead >= 1)) {
+    buffer[bytesRead - 1] = 0;
+  }
+  return true;
+}
+
+void errorMessage(int nr){
+  while(1){
+    for(int i = 0; i < nr; i++){
+      digitalWrite(LED_INDICATOR_PIN, HIGH);
+      delay(200);
+      digitalWrite(LED_INDICATOR_PIN, LOW);
+      delay(200);
+    }
+    delay(1000);
+  }
+}
+
+


cleaning up unused code

cleaning up unused code

--- Helios.ino
+++ Helios.ino
@@ -29,35 +29,12 @@
   Serial.begin(9600);
   strip.begin();
   strip.show(); // Initialize all pixels to 'off'
-  //powerOn(strip.Color(255, 150, 110), 750);
-  powerOn(red, green, blue, 500);
+  powerOn(red, green, blue, 5);
   delay(1000);
-  powerOff();
+ // powerOff();
 }

 void loop() {
-  // Some example procedures showing how to display to the pixels:
- // colorWipe(strip.Color(255, 0, 0), 50); // Red
- // colorWipe(strip.Color(0, 255, 0), 50); // Green
- // colorWipe(strip.Color(0, 0, 255), 50); // Blue
-  // Send a theater pxel chase in...
- // theaterChase(strip.Color(127, 127, 127), 50); // White
- // theaterChase(strip.Color(127,   0,   0), 50); // Red
- // theaterChase(strip.Color(  0,   0, 127), 50); // Blue
- // 255 152 96
-
- //powerOn(0,100,0, 100);
- //delay(10);
- /*
- powerOn(strip.Color(255, 0, 0), 100);
- powerOn(strip.Color(0, 255, 0), 100);
- powerOn(strip.Color(0, 0, 255), 100);
- powerOn(strip.Color(255, 255, 255), 100);
-
-*/
- // rainbow(20);
- // rainbowCycle(20);
- // theaterChaseRainbow(50);
 }

 uint8_t splitColor ( uint32_t c, char value )
@@ -71,7 +48,6 @@
 }

 void powerOn(int r, int g, int b, int wait) {
- // uint8_t a = 0;
   for(int a = 0; a < strip.numPixels()/2; a++) {
     for(int i = 1; i <= 100; i++) {
       double percentage = (double)i/100;
@@ -85,7 +61,7 @@
       strip.setPixelColor(a, strip.Color(red,green,blue));
       strip.setPixelColor(((strip.numPixels() - 1) - a), strip.Color(red,green,blue));
       strip.show();
-      delay(10);
+     // delay(1);
     }
     delay(wait);
   }
@@ -106,10 +82,10 @@
      // Serial.println(r);
       strip.setPixelColor(a, strip.Color((int)r,(int)g,(int)b));
       strip.setPixelColor(((strip.numPixels() - 1) -a), strip.Color((int)r,(int)g,(int)b));
-      delay(10);
+      //delay(10);
       strip.show();
     }
-    delay(10);
+    delay(1);
   }
 }

@@ -121,20 +97,6 @@
       delay(wait);
   }
 }
-
-/*
-void rainbow(uint8_t wait) {
-  uint16_t i, j;
-
-  for(j=0; j<256; j++) {
-    for(i=0; i<strip.numPixels(); i++) {
-      strip.setPixelColor(i, Wheel((i+j) & 255));
-    }
-    strip.show();
-    delay(wait);
-  }
-}
-*/

 // Slightly different, this makes the rainbow equally distributed throughout
@@ -150,44 +112,6 @@
   }
 }

-/*
-//Theatre-style crawling lights.
-void theaterChase(uint32_t c, uint8_t wait) {
-  for (int j=0; j<10; j++) {  //do 10 cycles of chasing
-    for (int q=0; q < 3; q++) {
-      for (int i=0; i < strip.numPixels(); i=i+3) {
-        strip.setPixelColor(i+q, c);    //turn every third pixel on
-      }
-      strip.show();
-
-      delay(wait);
-
-      for (int i=0; i < strip.numPixels(); i=i+3) {
-        strip.setPixelColor(i+q, 0);        //turn every third pixel off
-      }
-    }
-  }
-}
-*/
-/*
-//Theatre-style crawling lights with rainbow effect
-void theaterChaseRainbow(uint8_t wait) {
-  for (int j=0; j < 256; j++) {     // cycle all 256 colors in the wheel
-    for (int q=0; q < 3; q++) {
-        for (int i=0; i < strip.numPixels(); i=i+3) {
-          strip.setPixelColor(i+q, Wheel( (i+j) % 255));    //turn every third pixel on
-        }
-        strip.show();
-
-        delay(wait);
-
-        for (int i=0; i < strip.numPixels(); i=i+3) {
-          strip.setPixelColor(i+q, 0);        //turn every third pixel off
-        }
-    }
-  }
-}
-*/

 // Input a value 0 to 255 to get a color value.
 // The colours are a transition r - g - b - back to r.


paar Kleinigkeiten

paar Kleinigkeiten

--- MazeSolver/MazeSolver.ino
+++ MazeSolver/MazeSolver.ino
@@ -220,16 +220,7 @@
 		else if (isDeadEnd())
 		{
 			direction = backward;
-			if (isFirstRun)
-			{
-				path[pathLength] = backward;
-				simplifyMaze();
-				pathLength++;
-			}
-			else
-			{
-				pathPositionInLaterRun++;
-			}
+			storeTurnToPath();
 		}
 		break;

@@ -242,9 +233,9 @@
 	}
 }

-void lightLed(unsigned char index)
-{
-	digitalWrite(ledPins[index], HIGH);
+void lightLed(unsigned char ledIndex)
+{
+	digitalWrite(ledPins[ledIndex], HIGH);
 }

 void turnOffAllLeds()
@@ -307,61 +298,68 @@
 	{
 		direction = path[pathPositionInLaterRun];
 		pathPositionInLaterRun++;
-		return;
-	}
-
-	// Check if there is a way up front
-	for (unsigned char i = 1; i < sizeof(sensorPins) - 1; i++)
-	{
-		if (sensorValues[i] > threshold)
-		{
-			isEachDiversionOnCrossing[forward] = true;
-			break;
-		}
-	}
-
-	// check if the destination was reached
-	bool destinationWasReached = true;
-	for (int i = 0; i < sizeof(sensorPins); i++)
-	{
-		if (sensorValues[i] < threshold)
-		{
-			destinationWasReached = false;
-		}
-	}
-
-	// Stop if destination was reached
-	// Else go left preferably
-	if (destinationWasReached)
-	{
-		printPath();
-		direction = none;
 	}
 	else
 	{
-		if (isEachDiversionOnCrossing[left])
-		{
-			direction = left;
-		}
-		else if (isEachDiversionOnCrossing[forward])
-		{
-			direction = forward;
+		// Check if there is a way up front
+		for (unsigned char i = 1; i < sizeof(sensorPins) - 1; i++)
+		{
+			if (sensorValues[i] > threshold)
+			{
+				isEachDiversionOnCrossing[forward] = true;
+				break;
+			}
+		}
+
+		// check if the destination was reached
+		bool destinationWasReached = true;
+		for (int i = 0; i < sizeof(sensorPins); i++)
+		{
+			if (sensorValues[i] < threshold)
+			{
+				destinationWasReached = false;
+			}
+		}
+
+		// Stop if destination was reached
+		// Else go left preferably
+		if (destinationWasReached)
+		{
+			printPath();
+			direction = none;
 		}
 		else
 		{
-			direction = right;
-		}
-
-		path[pathLength] = direction;
-		pathLength++;
-		simplifyMaze();
-	}
-
-	// Reset for next crossing
-	for (unsigned char i = 0; i < sizeof(isEachDiversionOnCrossing); i++)
-	{
-		isEachDiversionOnCrossing[i] = false;
-	}
+			if (isEachDiversionOnCrossing[left])
+			{
+				direction = left;
+			}
+			else if (isEachDiversionOnCrossing[forward])
+			{
+				direction = forward;
+			}
+			else
+			{
+				direction = right;
+			}
+
+			storeTurnToPath();
+		}
+
+		// Reset for next crossing
+		for (unsigned char i = 0; i < sizeof(isEachDiversionOnCrossing); i++)
+		{
+			isEachDiversionOnCrossing[i] = false;
+		}
+	}
+}
+
+void storeTurnToPath()
+{
+	Serial.println(direction);
+	path[pathLength] = direction;
+	pathLength++;
+	//simplifyMaze();
 }

 void startFurtherDiversionCheckingTime()
@@ -421,6 +419,8 @@
 	}

 	// The path is now two steps shorter.
+	path[pathLength - 1] = none;
+	path[pathLength - 2] = none;
 	pathLength -= 2;
 }


Fixed formatting.

Fixed formatting.

--- src/ros/src/ros_homebot_base/src/firmware/torso2/main.ino
+++ src/ros/src/ros_homebot_base/src/firmware/torso2/main.ino
@@ -25,6 +25,7 @@
 #include "UltrasonicSensor.h"
 #include "AccelGyroSensor.h"
 #include "PowerController.h"
+#include "ArduinoTemperatureSensor.h"

 //#define PING_TIMEOUT_MS 10000

@@ -88,6 +89,8 @@
     // We're only fully docked and charging when both EP1 and EP2 are high.
 };

+ArduinoTemperatureSensor arduino_temperature_sensor = ArduinoTemperatureSensor();
+
 PowerController power_controller = PowerController();

 BooleanSensor edge_sensors[3] = {
@@ -154,6 +157,8 @@
 ros::Publisher imu_calibration_gyr_publisher = ros::Publisher("imu/calibration/gyr", &int16_msg);
 ros::Publisher imu_calibration_acc_publisher = ros::Publisher("imu/calibration/acc", &int16_msg);
 ros::Publisher imu_calibration_mag_publisher = ros::Publisher("imu/calibration/mag", &int16_msg);
+
+ros::Publisher arduino_temperature_publisher = ros::Publisher("temperature", &float_msg);

 /*
  * End publisher definitions.
@@ -281,6 +286,7 @@
     nh.advertise(imu_calibration_gyr_publisher);
     nh.advertise(imu_calibration_acc_publisher);
     nh.advertise(imu_calibration_mag_publisher);
+    nh.advertise(arduino_temperature_publisher);

     // Join I2C bus as Master with address #1
     Wire.begin(1);
@@ -341,6 +347,12 @@
         }
     }

+    // Temperature.
+    if (arduino_temperature_sensor.get_and_clear_changed() || force_sensors) {
+        float_msg.data = arduino_temperature_sensor.temperature.get();
+        arduino_temperature_publisher.publish(&float_msg);
+    }
+
     // Motion controller.
     motion_controller.update();
     if (motion_controller.a_encoder.get_and_clear_changed() || force_sensors) {


Davor recommended

Davor recommended


Added broadcast options to the time sync example

--- Libraries/TimeSync/examples/TimeSyncExample/TimeSyncExample.ino
+++ Libraries/TimeSync/examples/TimeSyncExample/TimeSyncExample.ino
@@ -121,16 +121,16 @@
     }

     case 't': {
-      if (numtokens < 2) return;
-      uint16_t address = atoi(tokens[1]);
+      if (numtokens < 1) return;
+      uint16_t address = (numtokens >= 2 ? atoi(tokens[1]) : SOCKET_ADDR_ANY);
       DEBUG1_VALUE("* Time sync to: ", address);
       time.synchronize(&rs485, address, NULL);
       break;
     }

     case 'r': {
-      if (numtokens < 2) return;
-      uint16_t address = atoi(tokens[1]);
+      if (numtokens < 1) return;
+      uint16_t address = (numtokens >= 2 ? atoi(tokens[1]) : SOCKET_ADDR_ANY);
       DEBUG1_VALUE("* Time resync to: ", address);
       time.resynchronize(&rs485, address);
       break;
@@ -145,8 +145,8 @@
     }

     case 'c': {
-      if (numtokens < 2) return;
-      uint16_t address = atoi(tokens[1]);
+      if (numtokens < 1) return;
+      uint16_t address = (numtokens >= 2 ? atoi(tokens[1]) : SOCKET_ADDR_ANY);
       DEBUG1_VALUE("* Time check to: ", address);
       time.check(&rs485, address);
       break;


save to storage, random was fucked

save to storage, random was fucked

--- MASTER_crusher/MASTER_crusher.ino
+++ MASTER_crusher/MASTER_crusher.ino
@@ -3,6 +3,7 @@
 #include <Pushbutton.h>
 #include <ZumoMotors.h>
 #include <PLabBTSerial.h>
+#include <EEPROM.h>

 ZumoReflectanceSensorArray reflectanceSensors(QTR_NO_EMITTER_PIN);
@@ -37,7 +38,6 @@
   Serial.begin(9600);
   btSerial.begin(9600);
   reflectanceSensors.init();
-  randomSeed(analogRead(0));
   Serial.println("Starting master crusher");
   setBluetoothProgram();
   button.waitForButton();
@@ -69,19 +69,19 @@

 void setBluetoothProgram() {
   if (!useBt) {
+    byte value = EEPROM.read(0);
+
     Serial.println("We are not using bluetooth");
-    random(2, 500);
-    random(1, 4000);
-    int nr = random(1, 399);
-    Serial.println(nr);
-    if (nr < 200) {
+    if (value == 1) {
       useRightProgram = true;
       Serial.println("Using right prog, setting led high");
       digitalWrite(yellowLedPin, HIGH);
+      EEPROM.write(0, 0);
     } else {
       Serial.println("Using left prog, setting led low");
       useRightProgram = false;
       digitalWrite(yellowLedPin, LOW);
+      EEPROM.write(0, 1);
     }
     return;
   }


send update to subtopic

send update to subtopic

--- _70-homekit-accessories-light/_70-homekit-accessories-light.ino
+++ _70-homekit-accessories-light/_70-homekit-accessories-light.ino
@@ -94,6 +94,24 @@
   sendmqttMsg(reporting_topic, payload, true);
 }

+void ICACHE_RAM_ATTR sendUpdate()
+{
+  DynamicJsonBuffer jsonBuffer;
+  JsonObject& root = jsonBuffer.createObject();
+  if (bRelayState)
+  {
+     root["cmd"] = "on";
+  }
+  else
+  {
+     root["cmd"] = "off";
+  }
+  String json;
+  root.printTo(json);
+
+  sendmqttMsg(subscribe_topic, json, true);
+}
+
 void ICACHE_RAM_ATTR parseMqttMsg(String receivedpayload, String receivedtopic)
 {
   char json[] = "{\"cmd\":\"off\"}";
@@ -202,6 +220,7 @@
     Serial.println(WIFI_SSID);

     //wifi_set_phy_mode(PHY_MODE_11N);
+    //WiFi.setOutputPower(18);
     WiFi.mode(WIFI_STA);
     WiFi.begin(WIFI_SSID, WIFI_PASSWORD);
     WiFi.hostname("esp-bedroomlight");
@@ -262,7 +281,7 @@
   ArduinoOTA.setPassword(OTA_PASSWORD);
   ArduinoOTA.onStart([]()
   {
-     ticker.attach(0.1, tick);
+     //ticker.attach(0.1, tick);
   });
   ArduinoOTA.onEnd([]() { });
   ArduinoOTA.onProgress([](unsigned int progress, unsigned int total) { });
@@ -329,7 +348,10 @@
       change_light();
       if (client.connected())
       {
+         sendUpdate();
+         client.loop();
          sendCheck();
+         client.loop();
       }
       lastRelayActionmillis = millis();
       bUpdated = false;


Adjust smoothSploch

Adjust smoothSploch

--- pug.ino
+++ pug.ino
@@ -132,9 +132,13 @@
  * Do a smooth sploch! (vertical to horizontal)
  **/
 void smoothSploch () {
-  for (int i = 130; i > 30; i--) {
+  for (int i = 130; i > 90; i--) {
     starterServo.write(i);
     delay(50);
+  }
+  for (int i = 90; i > 30; i--) {
+    starterServo.write(i);
+    delay(10);
   }
   starterServo.detach();
 }


Add Start timer

Add Start timer

--- pug.ino
+++ pug.ino
@@ -20,6 +20,9 @@
 #define GREEN_LED_PIN 7
 #define YELLOW_LED_PIN 6
 #define STARTER_SERVO_PIN 19
+
+// Timer de start en ms
+#define START_TIMER 15000

 // Ultrason
 #define MIN_DISTANCE_IN_CM 20
@@ -203,7 +206,9 @@
   //  goBackward(20);
   //  delay(3000);
   //  stopMotors();
-  delay(1000);
+
+  // Tempo before start.
+  delay(START_TIMER);

   // Forward
   goForward(30, 850);


Correction rotation

Correction rotation

--- pug.ino
+++ pug.ino
@@ -1,10 +1,10 @@
 #include <Servo.h>

-#define rightMotorPin1 6
-#define rightMotorPin2 5
-
-#define leftMotorPin1 3
-#define leftMotorPin2 4
+#define rightMotorPin1 11
+#define rightMotorPin2 10
+
+#define leftMotorPin1 8
+#define leftMotorPin2 9

 IntervalTimer motorTimer;

@@ -13,10 +13,13 @@

 #define starterServoPin 19

-#define rotateTime 600
+#define rotateTimeLeft 570
+#define rotateTimeRight 500

 #define pinColor 2

+#define JUMPER 3
+bool endScript = false;
 IntervalTimer ultraTimer;
 int ultraBuffer[10] = {0, 0, 0, 0, 0, 0, 0, 0, 0, 0};
 int ultraCompteur;
@@ -117,7 +120,7 @@
 void rotateRight() {
   setLeftSpeed( 60 );
   setRightSpeed( -60 );
-  delay(rotateTime);
+  delay(rotateTimeRight);
   stopMotors();
 }

@@ -127,7 +130,7 @@
 void rotateLeft() {
   setLeftSpeed( -60 );
   setRightSpeed( 60 );
-  delay(rotateTime);
+  delay(rotateTimeLeft);
   stopMotors();
 }

@@ -187,14 +190,40 @@

   //DebugLed
   pinMode(13, OUTPUT);
+
+  //Init Jumper
+  pinMode(JUMPER, INPUT);

   // Serial
   Serial.begin(9600);
+
+    if (isGreen()) {
+    digitalWrite(13,LOW);
+  } else {
+    digitalWrite(13,HIGH);
+  }
+

   //  initializeTimer1();
 }

 void loop() {
+
+  if (!endScript){
+    for (int i = 0; i<2000; i++);
+    Serial.println("DEBUT DE SCRIPT");
+    Serial.println("Attente de Jumper...");
+    while(!digitalRead(JUMPER));
+    Serial.println("Debout!");
+    prepareToStart();
+    Serial.println("Retirer le jumper...");
+    while(digitalRead(JUMPER));
+
+
+    endScript = true;
+    Serial.println("FIN DE SCRIPT");
+    while(42);
+    }

 }

@@ -204,13 +233,6 @@

 void serialEvent()
 {
-    Serial.println("Ready to rock");
-  if (isGreen()) {
-    Serial.println("Je suis force verte");
-  } else {
-    Serial.println("Je suis force Jaune!!");
-  }
-
   while (Serial.available())
   {
     char inChar = (char)Serial.read();
@@ -295,6 +317,13 @@
       Serial.println("left on");
       setLeftSpeed( 30);
       break;
+
+    case 'j':
+    case 'J':
+      JUMPER != JUMPER;
+      if (JUMPER) Serial.println("Jumper On!");
+      else Serial.println("Jumper off");
+      break;

     default:


using strtok function

using strtok function

--- invPendulum/invPendulum.ino
+++ invPendulum/invPendulum.ino
@@ -23,7 +23,7 @@
 // Infomation from glove
 enum state {idle,forward_drive, backup, left_turn,right_turn};
 state gesture_state = idle;
-uint8_t turning_speed;
+int turning_speed;
 bool should_catapult;

@@ -46,24 +46,22 @@
 }

 void receive_info() {
+  int intState;
    String command1 =  Serial.readStringUntil('#');
-   String combine_string = NULL;
-   String string1;
-   String string2;
-   String string3;
-   int int_command1;
-   int int_command2;
-   int int_command3;
-   int pos = 0;
-   int pre_pos = 0;
-   for (int i = 0; i < string.length(command1);i++){
-     pos++;
-     if (command1.substring(i,i+1) == " "){
-        string1 = command1.substring(pos-i,i-1);
-
-     }
-
-    }
+   char command[30];
+   command1.toCharArray(command, 30);
+   char *parseChar;
+   parseChar = strtok(command, " ");
+
+   intState = atoi(parseChar);
+   //todo map interger state to enum
+   parseChar = strtok(NULL, " ");
+   turning_speed = atoi(parseChar);
+   parseChar = strtok(NULL, " ");
+   should_catapult = (atoi(parseChar) > 0);
+   Serial.println(command1);
+   Serial.println(command);
+


added reading/writing ID number

added reading/writing ID number

--- software/serial_dmm/serial_dmm.ino
+++ software/serial_dmm/serial_dmm.ino
@@ -2,6 +2,7 @@
 // Copyright (C) 2016 Theodore C. Yapo

 #include <SoftwareSerial.h>
+#include <EEPROM.h>

 class DMM
 {
@@ -278,11 +279,13 @@
   }
 };

+const int ID_location = 0;
+int ID = 0;
 int rx_pin = 10;
 SoftwareSerial dmm_port(rx_pin, 11); // RX, TX (note: TX not used)
 DMM dmm;
 byte sample_pending;
-byte result_format;
+byte command;

 void setup()
 {
@@ -290,6 +293,9 @@
   while(!Serial){
     // busy wait
   }
+
+  // retrieve ID from EEPROM
+  EEPROM.get(ID_location, ID);

   dmm.setPort(dmm_port, rx_pin);
   sample_pending = false;
@@ -298,14 +304,23 @@
 void loop()
 {
   if (Serial.available()){
-    result_format = Serial.read();
+    command = Serial.read();
+    if ('I' == command){
+      Serial.println(ID);
+      return;
+    }
+    if ('W' == command){
+      ID = Serial.parseInt();
+      EEPROM.put(ID_location, ID);
+      return;
+    }
     sample_pending = true;
     dmm.sync();
   }

   if (dmm.poll() && sample_pending){
     sample_pending = false;
-    switch(result_format){
+    switch(command){
     case 'n': // number only
     default:
       Serial.println(dmm.asciiValue());
@@ -315,6 +330,9 @@
       Serial.print(" ");
       Serial.println(dmm.units());
       break;
+    case 'U': // units only
+      Serial.println(dmm.units());
+      break;
     case 'b': // low battery status
       Serial.println(dmm.flags.low_batt);
       break;


Adds Serial.begin/end to mcu_dis/enable_usbserial

--- mcu.ino
+++ mcu.ino
@@ -9,6 +9,8 @@
 }

 void mcu_disable_usbserial() {
+  Serial.end();
+
   power_usart1_disable();
   power_usb_disable();
   Xadow.greenLed(LEDOFF);
@@ -22,6 +24,8 @@
   power_usart1_enable();
   power_usb_enable();
   Xadow.greenLed(LEDON);
+
+  Serial.begin(9600);
 }

 /**


remove the cause of the association delay, drop pingin functionality on startup

--- WeatherStation/WeatherStation.ino
+++ WeatherStation/WeatherStation.ino
@@ -63,19 +63,19 @@

 void loop() {
   digitalWrite(XBEESLEEPPIN, LOW);  //Wake UP XBEE
-  delay(4000);
-
-  blink(25, 50);
-  digitalWrite(LEDPIN, LOW);
-  delay(1000);
+//  delay(4000);
+
+  blink(10, 50);                    //1 sec delay on wake up to allow the sample to be sent
+//  digitalWrite(LEDPIN, LOW);
+//  delay(1000);

   digitalWrite(LEDPIN, HIGH);

   sample += 1;

-  if (!pingDestination()){          //check if xbee woke up and got its association address. blink LED rapidly and quit loop otherwise
-    blink(50, 100);
-  } else {                          //connected to the destination
+//  if (!pingDestination()){          //check if xbee woke up and got its association address. blink LED rapidly and quit loop otherwise
+//    blink(50, 100);
+//  } else {                          //connected to the destination

     Serial.print("{\"__device\": \"weather\", \"__sample\": {\"__id\":");
     Serial.print(sample);
@@ -117,7 +117,7 @@

     Serial.println("}}");

-    delay(2000);   //Delay at the end to allow xbee to flush its send buffer
+    delay(500);   //Delay at the end to allow xbee to flush its send buffer
   }

   digitalWrite(LEDPIN, LOW);
@@ -156,6 +156,8 @@
   }
 }

+
+/*
 int pingDestination(void){

     for(int i = 0; i<10; i++){
@@ -182,6 +184,7 @@
   }
   return NULL;
 }
+*/

 void configureLightSensor(void)
 {


Revert "Add note set switching capabilities"

This reverts commit 14bdc8510426fa06bfbe9dd548d83b6c2d706097.

--- Guzheng/Guzheng.ino
+++ Guzheng/Guzheng.ino
@@ -63,72 +63,68 @@

 // Function for playing note based on ID
 void musicOn(int ID) {
-  if (noteSet == 1) {
-    switch (ID) {
-      case 1:
-        noteOn(NOTEON, note1, VOLUME);
-        break;
-      case 2:
-        noteOn(NOTEON, note2, VOLUME);
-        break;
-      case 3:
-        noteOn(NOTEON, note3, VOLUME);
-        break;
-      case 4:
-        noteOn(NOTEON, note4, VOLUME);
-        break;
-    }
-  } else if (noteSet == 2) {
-    switch (ID) {
-      case 1:
-        noteOn(NOTEON, note5, VOLUME);
-        break;
-      case 2:
-        noteOn(NOTEON, note6, VOLUME);
-        break;
-      case 3:
-        noteOn(NOTEON, note7, VOLUME);
-        break;
-      case 4:
-        noteOn(NOTEON, note8, VOLUME);
-        break;
-    }
+  switch (ID) {
+  case 1:
+    noteOn(NOTEON, note1, VOLUME);
+    break;
+  case 2:
+    noteOn(NOTEON, note2, VOLUME);
+    break;
+  case 3:
+    noteOn(NOTEON, note3, VOLUME);
+    break;
+  case 4:
+    noteOn(NOTEON, note4, VOLUME);
+    break;
+  case 5:
+    noteOn(NOTEON, note5, VOLUME);
+    break;
+  case 6:
+    noteOn(NOTEON, note6, VOLUME);
+    break;
+  case 7:
+    noteOn(NOTEON, note7, VOLUME);
+    break;
+  case 8:
+    noteOn(NOTEON, note8, VOLUME);
+    break;
+  default:
+    noteOn(NOTEOFF, note1, 0x00);
+    break;
   }
 }

 // Function for turning off a specific note based on ID
 // Just a slightly modified version of musicOn()
 void musicOff(int ID) {
-  if (noteSet == 1) {
-    switch (ID) {
-      case 1:
-        noteOn(NOTEOFF, note1, VOLUME);
-        break;
-      case 2:
-        noteOn(NOTEOFF, note2, VOLUME);
-        break;
-      case 3:
-        noteOn(NOTEOFF, note3, VOLUME);
-        break;
-      case 4:
-        noteOn(NOTEOFF, note4, VOLUME);
-        break;
-    }
-  } else if (noteSet == 2) {
-    switch (ID) {
-      case 1:
-        noteOn(NOTEOFF, note5, VOLUME);
-        break;
-      case 2:
-        noteOn(NOTEOFF, note6, VOLUME);
-        break;
-      case 3:
-        noteOn(NOTEOFF, note7, VOLUME);
-        break;
-      case 4:
-        noteOn(NOTEOFF, note8, VOLUME);
-        break;
-    }
+  switch (ID) {
+  case 1:
+    noteOn(NOTEOFF, note1, 0x7F);
+    break;
+  case 2:
+    noteOn(NOTEOFF, note2, 0x7F);
+    break;
+  case 3:
+    noteOn(NOTEOFF, note3, 0x7F);
+    break;
+  case 4:
+    noteOn(NOTEOFF, note4, 0x7F);
+    break;
+  case 5:
+    noteOn(NOTEOFF, note5, 0x7F);
+    break;
+  case 6:
+    noteOn(NOTEOFF, note6, 0x7F);
+    break;
+  case 7:
+    noteOn(NOTEOFF, note7, 0x7F);
+    break;
+  case 8:
+    noteOn(NOTEOFF, note8, 0x7F);
+    break;
+  default:
+    noteOn(NOTEOFF, note1, 0x00);
+    break;
   }
 }


Few fixes

Few fixes

Replaced all hard coded 21 values with NUM_LEDS constant.
Set default mode to be set to anti gravity (looks better when they're on
the top of your head, and fucking everyone is short)

--- InfinityGoggles.ino
+++ InfinityGoggles.ino
@@ -42,7 +42,7 @@
 long nodStart = 0;
 long nodTime = 2000;

-bool antiGravity = false;  // The pendulum will anti-gravitate to the top.
+bool antiGravity = true;  // The pendulum will anti-gravitate to the top.
 bool mirroredEyes = false; // The left eye will mirror the right.

 const float halfWidth = 2; // half-width of pupil (in pixels)
@@ -131,8 +131,8 @@
    pos += MomentumH + MomentumV;

    // handle the wrap-arounds at the top
-   while (round(pos) < 0) pos += 21.0;
-   while (round(pos) > 20) pos -= 21.0;
+   while (round(pos) < 0) pos += NUM_LEDS;
+   while (round(pos) > 20) pos -= NUM_LEDS;

    CRGB color = selectColor(heading);

@@ -147,7 +147,7 @@
      lightOn[lightIndex] = wrapAround(i);
      lightIndex++;
    }
-   for (int i = 0; i <21; i++) {
+   for (int i = 0; i <NUM_LEDS; i++) {
       int rightIndex = i;
       int leftIndex = wrapAround(i - 10); // This is because the strips aren't installed in the same place
       boolean turnedOn = false;
@@ -168,10 +168,10 @@

 int wrapAround(int value) {
   if(value < 0) {
-    return value + 21;
-  }
-  if(value > 20) {
-    return value - 21;
+    return value + NUM_LEDS;
+  }
+  if(value > NUM_LEDS -1) {
+    return value - NUM_LEDS;
   }
   return value;
 }
@@ -215,7 +215,7 @@

 // Reset to default
 void resetModes() {
-   antiGravity = false;
+   antiGravity = true;
    mirroredEyes = false;

    /// spin-up
@@ -261,3 +261,4 @@
   }
 }

+


Protocol change

Protocol change

--- Master.ino
+++ Master.ino
@@ -13,16 +13,16 @@
 #define blueLED 4 //acknowledgement & blue led port
 #define thErrON 0.9 //threshold multipler HIGH leds
 #define thErrOFF 1.5 //threshold multipler LOW leds
-#define setupWaitTime 50 //(ms) delay at setup time
-#define fbTime 1000 //(ms) feedback led on time
-#define cycTime 1000 //(ms) feedback led off time
+#define setupWaitTime 0 //(ms) delay at setup time
+#define fbTime 250 //(ms) feedback led on time
+#define cycTime 250 //(ms) feedback led off time
 #define sync "MODE_sync" // keyword for start sync seq (transmitter side)
 #define recal "MODE_recal" // keyword for start sync seq (receiver side)
 #define partyM "MODE_party" // keyword for party mode (eastern egg)
 #define crdM "MODE_credits" // keyword to show contributors
 #define initDelay 200 //(ms) synchronization sequence delay
-#define redONtime 5 //(ms)
-#define redOFFtime 5 //(ms)
+#define redONtime 20 //(ms)
+#define redOFFtime 20 //(ms)
 #define trnsDELAY 0 //(ms)

 void flashDotOrDash(int color, bool dotOrDash);
@@ -232,7 +232,7 @@
   tcs.getRawData(&r, &g, &b, &c);
   if(g > th_Val[2].g_t)
   {
-   lisSTART:
+    listenSTR:
      //send start bacon
      digitalWrite(greenLED, HIGH);
      delay(fbTime);
@@ -287,7 +287,8 @@
        }
        digitalWrite(redLED, LOW);
        delay(redOFFtime);
-       goto lisSTART;
+       if(ch != '\n')
+           goto listenSTR;
       }
   }

@@ -306,7 +307,6 @@
       //Serial.print("\n");
       for(int j=0; j<inputHOLD.length(); ++j)
         {
-          Serial.print(inputHOLD[j]);
           flashSequence(inputHOLD[j]);
         }
         flashSequence('\n');
@@ -379,7 +379,7 @@
       flashDotOrDash(redLED, false);
       flashDotOrDash(blueLED, false);
       flashDotOrDash(greenLED, false);
-    delay(trnsDELAY);
+    delay(trnsDELAY);
   }
   Serial.println(); //for testing **************************************


Make files sendable bit by bit

Make files sendable bit by bit

--- SDPArduinoCode/SDPArduinoCode.ino
+++ SDPArduinoCode/SDPArduinoCode.ino
@@ -15,6 +15,7 @@
 #define RIGHT 4
 #define KICK 5
 #define GRAB 6
+#define STORE 7

 // Outbound message definitions
 #define DONE "Robot ignores"
@@ -23,6 +24,8 @@

 int  lastSeqNo;
 bool done;
+
+bool bytes_to_store;

 // Encoder Board Variables
 #define ROTARY_SLAVE_ADDRESS 5
@@ -272,17 +275,14 @@
   return f;
 }

-void storeFileInRegister(String file, long freq){
+void storeByte(byte one_byte){
   int register_address = 69;

-  // Change this if 1st or 2nd bit is relevant, etc.
-  for (int i = 1; i <= 250; i++) {
-      Wire.beginTransmission(register_address); // open I2C communication to intended receiver
-      //Wire.setClock(freq);
-      Wire.write( (byte) (file.charAt(i)) );   // sends the string (which is the file contents)
-      // sleep 1/frequency
-      Wire.endTransmission(); // end I2C communcation.
-  }
+  Wire.beginTransmission(register_address); // open I2C communication to intended receiver
+  Wire.write( one_byte );   // sends the string (which is the file contents)
+  Wire.endTransmission(); // end I2C communcation.
+
+  bytes_to_store--;
 }

 ///////////////////////////////////////////////////////////////////////////////////////////////////////////
@@ -298,6 +298,14 @@

     // save message sent from PC to STRING c.
     String c = Serial.readString();
+
+    if (bytes_to_store > 0) {
+      byte buf[1];
+      c.getBytes(buf, 1);
+      storeByte((buf[0]);
+      return;
+    }
+

     if(c.length()< 7){
       Serial.println("Robot input too short");
@@ -354,6 +362,9 @@
           break;

           case GRAB: robotGrab(arg);
+          break;
+
+          case STORE: bytes_to_store = arg;
           break;

           default: Serial.println(UNRECOGNIZED_COMMAND);


removing old display_test sketch

removing old display_test sketch

--- src/display_test.ino
+++ src/display_test.ino
@@ -1,63 +0,0 @@
-#include <TimerOne.h>
-#include "SevenSegController.h"
-
-// ---------------------- //
-// display control pins
-// ---------------------- //
-#define DIGIT0_PIN 7
-#define DIGIT1_PIN 6
-#define DIGIT2_PIN 5
-#define DIGIT3_PIN 4
-#define COLON_PIN  3
-#define DEGREE_PIN 2
-#define LATCH_PIN  8
-#define CLOCK_PIN 12
-#define DATA_PIN  11
-
-SevenSegController controller(DIGIT0_PIN, DIGIT1_PIN, DIGIT2_PIN, DIGIT3_PIN, COLON_PIN, DEGREE_PIN, LATCH_PIN, DATA_PIN, CLOCK_PIN);
-
-void setup()
-{
-}
-
-void setRandomMode()
-{
-  int i;
-  int j;
-
-  for (i = 0; i < 4; i++)
-  {
-    j = random(3);
-    switch(j)
-    {
-      case 0:
-        controller.disableDigit(i);
-        break;
-      case 1:
-        controller.enableDigit(i);
-        break;
-      case 2:
-        controller.enableBlink(i);
-        break;
-    }
-  }
-}
-
-void writeRandomNo()
-{
-  controller.writeDigit(0, random(10));
-  controller.writeDigit(1, random(10));
-  controller.writeDigit(2, random(10));
-  controller.writeDigit(3, random(10));
-}
-
-void loop()
-{
-  controller.enableClockDisplay();
-  controller.enableBlink(3);
-  writeRandomNo();
-  delay(3000);
-
-  controller.enableTempDisplay();
-  delay(3000);
-}


Delayed startup tone by 250ms, increased stars back to 30 ;)

--- arduboy-game/arduboy-game.ino
+++ arduboy-game/arduboy-game.ino
@@ -16,8 +16,8 @@
 // TODO highScore should be replaced with table in EEPROM
 unsigned int score, highScore = 0;
 byte livesRemaining = 4;
-int numStars = 10;
-Star stars[10];
+int numStars = 30;
+Star stars[30];

 // Placeholders
 bool shouldPlayTone1,
@@ -42,9 +42,10 @@
   arduboy.clear();
   draw(0, 0, modusLogo, 0);
   arduboy.display();
+  delay(250);
   playMusic(0);

-  delay(3000);
+  delay(2800);
 }

 byte titleScreen() {


got feature toggling implemented.

got feature toggling implemented.

--- arduino_code/arduino_code.ino
+++ arduino_code/arduino_code.ino
@@ -15,12 +15,14 @@

 // --- Feature toggles

-#define HAS_INCREMENT_COMMAND
-#define HAS_DECREMENT_COMMAND
+#define HAS_BOOT_MESSAGE
+//#define HAS_INCREMENT_COMMAND
+//#define HAS_DECREMENT_COMMAND
 #define HAS_VOLTS_COMMAND
-#define HAS_HEX_COMMAND
-//#define HAS_ERROR_PRINTING
-//#define HAS_SUCCESS_PRINTING
+#define HAS_VOLTS_COMMAND_DEBUGGING
+//#define HAS_HEX_COMMAND
+#define HAS_ERROR_PRINTING
+#define HAS_SUCCESS_PRINTING

 // ATiny85 pinout:
@@ -116,18 +118,24 @@
 */

 #define MIN_EXPECTED_LEN 2 // +;
-#define MAX_EXPECTED_LEN 8 // v12.345;
+#define MAX_EXPECTED_LEN 9 // v12.3456;

 #define BUFF_LEN (MAX_EXPECTED_LEN + sizeof('\0'))
 char buffer[BUFF_LEN];
 char *buff_ptr;

+
 void setup()
 {
-  delay(1);
   serial.begin(9600);
-  serial.print("OK;");
-  serial.flush();
+
+  #ifdef HAS_BOOT_MESSAGE
+  {
+    delay(1);
+    serial.print("OK;");
+    serial.flush();
+  }
+  #endif

   // start up the SPI bus
   mySPI.begin();
@@ -141,46 +149,75 @@
   buff_ptr = buffer;
 }

+
 void loop()
 {
   command_t command = read_command(&serial, buffer, BUFF_LEN);
   if (command >= END_OF_COMMANDS_SECTION)
   {
+    #ifdef HAS_ERROR_PRINTING
     printError(command);
+    #endif
     return;
   }

   error_t error;

-  if (command == COMMAND_INCREMENT)
-  {
-    error = increment_output_voltage();
-  }
-  else if (command == COMMAND_DECREMENT)
-  {
-    error = decrement_output_voltage();
-  }
-  else if (command == COMMAND_SET_VOLTS)
-  {
-    error = parse_and_run_voltage_command(buffer);
-  }
-  else if (command == COMMAND_SET_HEX)
-  {
-    error = parse_and_run_hex_command(buffer);
-  }
-  else
-  {
-    error = ERROR_UNKNOWN_COMMAND;
-  }
-
+  switch(command)
+  {
+
+    #ifdef HAS_INCREMENT_COMMAND
+    case COMMAND_INCREMENT:
+    {
+      error = increment_output_voltage();
+      break;
+    }
+    #endif
+
+    #ifdef HAS_DECREMENT_COMMAND
+    case COMMAND_DECREMENT:
+    {
+      error = decrement_output_voltage();
+      break;
+    }
+    #endif
+
+    #ifdef HAS_VOLTS_COMMAND
+    case COMMAND_SET_VOLTS:
+    {
+      error = parse_and_run_voltage_command(buffer);
+      break;
+    }
+    #endif
+
+    #ifdef HAS_HEX_COMMAND
+    case COMMAND_SET_HEX:
+    {
+      error = parse_and_run_hex_command(buffer);
+      break;
+    }
+    #endif
+
+    default:
+    {
+      error = ERROR_UNKNOWN_COMMAND;
+      break;
+    }
+  }
+
   if (error != OK_NO_ERROR)
   {
+    #ifdef HAS_ERROR_PRINTING
     printError(error);
+    #endif
     return;
   }

+  #ifdef HAS_SUCCESS_PRINTING
   printSuccess(command);
-}
+  #endif
+}
+

 command_t read_command(SoftwareSerial *serial, char *buffer, uint8_t buff_len)
 {
@@ -193,66 +230,83 @@

   char ch = serial->read();

-  if (ch == '+')
-  {
-    uint8_t num_chars_consumed = consume_until_sentinel(serial, ';');
-    if (num_chars_consumed == 1)
-    {
-      return COMMAND_INCREMENT;
-    }
-    else
-    {
-      return ERROR_PARSING_INCREMENT_COMMAND;
-    }
-  }
-  else if (ch == '-')
-  {
-    uint8_t num_chars_consumed = consume_until_sentinel(serial, ';');
-    if (num_chars_consumed == 1)
-    {
-      return COMMAND_DECREMENT;
-    }
-    else
-    {
-      return ERROR_PARSING_DECREMENT_COMMAND;
-    }
-  }
-  else if (ch == 'x')
-  {
-    // prepend buffer with '0x'
-    buffer[0] = '0';
-    buffer[1] = 'x';
-    buff_ptr = buffer+2;
-
-    // read the hex characters into buffer
-    error_t error = read_until_sentinel(serial, buffer, buff_len-2, ';');
-    if (error == OK_NO_ERROR)
-    {
-      return COMMAND_SET_HEX;
-    }
-    else // i.e. if (error == ERROR_BUFFER_FILLED_UP_BEFORE_SENTINEL_REACHED)
-    {
-      return ERROR_BUFFER_FILLED_UP_BEFORE_SENTINEL_REACHED_WHILE_PARSING_HEX_COMMAND;
-    }
-  }
-  else if (ch == 'v')
-  {
-    // read the floating point string into buffer
-    error_t error = read_until_sentinel(serial, buffer, buff_len, ';');
-    if (error == OK_NO_ERROR)
-    {
-      return COMMAND_SET_VOLTS;
-    }
-    else // i.e. if (error == ERROR_BUFFER_FILLED_UP_BEFORE_SENTINEL_REACHED)
-    {
-      return ERROR_BUFFER_FILLED_UP_BEFORE_SENTINEL_REACHED_WHILE_PARSING_VOLTS_COMMAND;
-    }
-  }
-  else
-  {
-    return ERROR_UNKNOWN_COMMAND;
-  }
-}
+  switch(ch)
+  {
+    #ifdef HAS_INCREMENT_COMMAND
+    case '+':
+    {
+      uint8_t num_chars_consumed = consume_until_sentinel(serial, ';');
+      if (num_chars_consumed == 1)
+      {
+        return COMMAND_INCREMENT;
+      }
+      else
+      {
+        return ERROR_PARSING_INCREMENT_COMMAND;
+      }
+    }
+    #endif
+
+    #ifdef HAS_DECREMENT_COMMAND
+    case '-':
+    {
+      uint8_t num_chars_consumed = consume_until_sentinel(serial, ';');
+      if (num_chars_consumed == 1)
+      {
+        return COMMAND_DECREMENT;
+      }
+      else
+      {
+        return ERROR_PARSING_DECREMENT_COMMAND;
+      }
+    }
+    #endif
+
+    #ifdef HAS_HEX_COMMAND
+    case 'x':
+    {
+      // prepend buffer with '0x'
+      buffer[0] = '0';
+      buffer[1] = 'x';
+      buff_ptr = buffer+2;
+
+      // read the hex characters into buffer
+      error_t error = read_until_sentinel(serial, buffer, buff_len-2, ';');
+      if (error == OK_NO_ERROR)
+      {
+        return COMMAND_SET_HEX;
+      }
+      else // i.e. if (error == ERROR_BUFFER_FILLED_UP_BEFORE_SENTINEL_REACHED)
+      {
+        return ERROR_BUFFER_FILLED_UP_BEFORE_SENTINEL_REACHED_WHILE_PARSING_HEX_COMMAND;
+      }
+    }
+    #endif
+
+    #ifdef HAS_VOLTS_COMMAND
+    case 'v':
+    {
+      // read the floating point string into buffer
+      error_t error = read_until_sentinel(serial, buffer, buff_len, ';');
+      if (error == OK_NO_ERROR)
+      {
+        return COMMAND_SET_VOLTS;
+      }
+      else // i.e. if (error == ERROR_BUFFER_FILLED_UP_BEFORE_SENTINEL_REACHED)
+      {
+        return ERROR_BUFFER_FILLED_UP_BEFORE_SENTINEL_REACHED_WHILE_PARSING_VOLTS_COMMAND;
+      }
+    }
+    #endif
+
+
+    default:
+    {
+      return ERROR_UNKNOWN_COMMAND;
+    }
+  }
+}
+

 uint8_t consume_until_sentinel(SoftwareSerial *serial, char sentinel)
 {
@@ -274,6 +328,7 @@
     }
   }
 }
+

 error_t read_until_sentinel(SoftwareSerial *serial, char *buffer, uint8_t buff_len, char sentinel)
 {
@@ -308,99 +363,115 @@
   }
 }

+
+void set_DAC_bits(uint8_t bits)
+{
+  bool use_2x_gain = true;
+  voltageDAC.setVoltageOutputBits(bits, use_2x_gain);
+}
+
+
+#ifdef HAS_INCREMENT_COMMAND
+bool DAC_would_overflow(uint8_t num_bits)
+{
+  return DAC_data == (1 << num_bits) - 1;
+}
+#endif
+
+
+#ifdef HAS_DECREMENT_COMMAND
+bool DAC_would_underflow()
+{
+  return DAC_data == 0;
+}
+#endif
+
+
+#ifdef HAS_INCREMENT_COMMAND
+error_t increment_output_voltage()
+{
+  if (DAC_would_overflow(DAC_num_bits))
+  {
+    return ERROR_INCREMENT_WOULD_CAUSE_OVERFLOW;
+  }
+
+  DAC_data++;
+  set_DAC_bits(DAC_data);
+  return OK_NO_ERROR;
+}
+#endif
+
+
+#ifdef HAS_DECREMENT_COMMAND
+error_t decrement_output_voltage()
+{
+  if (DAC_would_underflow())
+  {
+    return ERROR_DECREMENT_WOULD_CAUSE_UNDERFLOW;
+  }
+
+  DAC_data--;
+  set_DAC_bits(DAC_data);
+  return OK_NO_ERROR;
+}
+#endif
+
+
+#ifdef HAS_VOLTS_COMMAND
+error_t parse_and_run_voltage_command(char *buffer)
+{
+  float v = atof(buffer);
+
+  #ifdef HAS_VOLTS_COMMAND_DEBUGGING
+  {
+    serial.println();
+    serial.print("parsed volts: ");
+    serial.println(v, 4);
+    serial.flush();
+  }
+  #endif
+
+  DAC_data = voltageDAC.setVoltageOutput(v);
+  return OK_NO_ERROR;
+}
+#endif
+
+
+#ifdef HAS_HEX_COMMAND
+error_t parse_and_run_hex_command(char *buffer)
+{
+  uint16_t bits = 0;
+  int num_matches_found = sscanf(buffer, "%x", &bits);
+  if (num_matches_found != 1)
+  {
+    return ERROR_PARSING_HEX_VALUE;
+  }
+
+  DAC_data = bits;
+  set_DAC_bits(DAC_data);
+  return OK_NO_ERROR;
+}
+#endif
+
+
+#ifdef HAS_ERROR_PRINTING
 void printError(error_t error)
 {
-#ifdef HAS_ERROR_PRINTING
   serial.print("!e");
   serial.print(error);
   serial.print(";");
   serial.flush();
-#endif
-}
-
+}
+#endif
+
+
+#ifdef HAS_SUCCESS_PRINTING
 void printSuccess(command_t command)
 {
-#ifdef HAS_SUCCESS_PRINTING
   serial.print("ok");
   serial.print(command);
   serial.print(";");
   serial.flush();
-#endif
-}
-
-bool DAC_would_overflow(uint8_t num_bits)
-{
-  return DAC_data == (1 << num_bits) - 1;
-}
-
-bool DAC_would_underflow()
-{
-  return DAC_data == 0;
-}
-
-void set_DAC_bits(uint8_t bits)
-{
-  bool use_2x_gain = true;
-  voltageDAC.setVoltageOutputBits(bits, use_2x_gain);
-}
-
-#ifdef HAS_INCREMENT_COMMAND
-error_t increment_output_voltage()
-{
-  if (DAC_would_overflow(DAC_num_bits))
-  {
-    return ERROR_INCREMENT_WOULD_CAUSE_OVERFLOW;
-  }
-
-  DAC_data++;
-  set_DAC_bits(DAC_data);
-  return OK_NO_ERROR;
-}
-#endif
-
-#ifdef HAS_DECREMENT_COMMAND
-error_t decrement_output_voltage()
-{
-  if (DAC_would_underflow())
-  {
-    return ERROR_DECREMENT_WOULD_CAUSE_UNDERFLOW;
-  }
-
-  DAC_data--;
-  set_DAC_bits(DAC_data);
-  return OK_NO_ERROR;
-}
-#endif
-
-#ifdef HAS_VOLTS_COMMAND
-error_t parse_and_run_voltage_command(char *buffer)
-{
-  float v = atof(buffer);
-
-  // debug
-  serial.println();
-  serial.print("parsed volts: ");
-  serial.println(v);
-  serial.flush();
-
-  DAC_data = voltageDAC.setVoltageOutput(v);
-  return OK_NO_ERROR;
-}
-#endif
-
-#ifdef HAS_HEX_COMMAND
-error_t parse_and_run_hex_command(char *buffer)
-{
-  uint16_t bits = 0;
-  int num_matches_found = sscanf(buffer, "%x", &bits);
-  if (num_matches_found != 1)
-  {
-    return ERROR_PARSING_HEX_VALUE;
-  }
-
-  DAC_data = bits;
-  set_DAC_bits(DAC_data);
-  return OK_NO_ERROR;
-}
-#endif
-
+}
+#endif
+


Bug with serial print an multiple weights.

--- Weight.ino
+++ Weight.ino
@@ -48,14 +48,14 @@
 #define BUTTON_PIN   0

 // initialize the library with the numbers of the interface pins
-//LiquidCrystal lcd(13, 12, 8, 9, 10, 11); //PROD
-LiquidCrystal lcd(8, 9, 4, 5, 6, 7); //DEBUG
+LiquidCrystal lcd(13, 12, 8, 9, 10, 11); //PROD
+//LiquidCrystal lcd(8, 9, 4, 5, 6, 7); //DEBUG
 HX711 scales[] = {
   HX711 (A1, A2), HX711 (A3, A4)}; //A1 = ANALOG1 = DT // A2=SCK
 int eepromAddress[WEIGHT_SENSORS] = {0};

-unsigned long last = 0;
-unsigned long lastPrint = 0;
+unsigned long last[WEIGHT_SENSORS];
+unsigned long lastPrint[WEIGHT_SENSORS];
 const String kilo = "kg";

 // KEY VARIABLES
@@ -67,13 +67,13 @@
 unsigned long debounceTime = 0;

 // WEIGHT VARIABLES
-float lastValue = 0;
+float lastValue[WEIGHT_SENSORS];
 unsigned int useFastWeight = 0;

 //MENU
 char* EMPTY = "                ";
 char* menu[] = {"Calibrate       " ,"Tare           ", "Beersize       "};
-unsigned int lastItem = 0;
+unsigned int lastItem = 1;
 unsigned int menuMarker = 0;

 //GUI VARIABLES
@@ -83,9 +83,12 @@
   Serial.begin(BAUD_RATE);

   lcd.begin(16, 2);
-  lcd.print("Starting....");
+  lcd.print("Starting...");
   for (int i = 0; i < WEIGHT_SENSORS; i++) {
     //scales[i].set_scale(-228.f);
+    lastValue[i] = 0;
+    last[i] = 0;
+    lastPrint[i] = 0;
     scales[i].set_scale(228.f);
     scales[i].tare();
     delay(DELAY);
@@ -153,31 +156,11 @@
   return value;
 }

-char* safeLCDString(const char* src) {
-  return safeLCDString(16, src);
-}
-
-char* safeLCDString(const int length, const char* src) {
-  char result[length];
-  for(int i = 0; i < length ; i++) {
-    result[i] = 'd';
-  }
-  //strncpy(result, src, sizeof(src));
-  for(int i = 0; i < length ; i++) {
-    if (result[i] == '\0') {
-      result[i] = ' ';
-    }
-  }
-  result[length - 1] = '\0';
-  Serial.println(result);
-  return result;
-}
-
-void printToSerial(const float value, const unsigned long now, String& weightName) {
-  if ((lastPrint + DEFAULT_WEIGHT_PRINT_TIME) < now || ((useFastWeight && (last + DEFAULT_WEIGHT_TIME_FAST) < now))) {
+void printToSerial(const float value, const unsigned long now, String& weightName, const int i) {
+  if ((lastPrint[i] + DEFAULT_WEIGHT_PRINT_TIME) < now || ((useFastWeight && (last[i] + DEFAULT_WEIGHT_TIME_FAST) < now))) {
     Serial.print(weightName);
     Serial.println(value, 1);
-    lastPrint = now;
+    lastPrint[i] = now;
   }
 }

@@ -247,22 +230,22 @@
     return;
   }
   unsigned long now = millis();
-  if (((last + DEFAULT_WEIGHT_TIME) < now) || ((useFastWeight && (last + DEFAULT_WEIGHT_TIME_FAST) < now))) {
+
     for (int i = 0; i < WEIGHT_SENSORS; i++) {
+      if (((last[i] + DEFAULT_WEIGHT_TIME) < now) || ((useFastWeight && (last[i] + DEFAULT_WEIGHT_TIME_FAST) < now))) {
       lcd.setCursor(0, 1);

       String weightName = getName(i);
       float value = getValue(scales[i]);
-
-
-      if ((value > (lastValue + 50)) || (value < (lastValue - 50))) {
+
+      if ((value > (lastValue[i] + 50)) || (value < (lastValue[i] - 50))) {
         useFastWeight = 1;
-        lastValue = value;
+        lastValue[i] = value;
       } else {
         useFastWeight = 0;
       }

-      printToSerial(value, now, weightName);
+      printToSerial(value, now, weightName, i);

       const int row = getRow(i);
       const int col = getCol(i);
@@ -270,7 +253,7 @@

       printWeightOnLCD(value, weightName);

-      last = millis();
+      last[i] = millis();
     }
   }
 }


[LedDude] Implemented RFID reader.

[LedDude] Implemented RFID reader.

Signed-off-by: Juri Berlanda <5bfdca9e82c53adb0603ce7083f4ba4f2da5cacf@hotmail.com>

--- laundry-dude-led-sensor/laundry-dude-led-sensor.ino
+++ laundry-dude-led-sensor/laundry-dude-led-sensor.ino
@@ -10,6 +10,8 @@

 #define FETCH_INTERVAL 100
 #define POST_INTERVAL 5000
+
+#define TAG_LENGTH 12

 const int numLedSamples = POST_INTERVAL / FETCH_INTERVAL;
 int ledSamples[numLedSamples];
@@ -31,13 +33,17 @@
 uint16_t fifoCount;     // count of all bytes currently in FIFO
 uint8_t fifoBuffer[64];

+char rfidTag[TAG_LENGTH + 1];
+
 // Software serial for XBee module
 SoftwareSerial xbeeSerial(2, 3); // RX, TX
+// Hardware serial for RFID reader
+#define rfidSerial Serial

 void setup() {
   // Setup serials
-  Serial.begin(SERIAL_BAUDRATE);
   xbeeSerial.begin(SERIAL_BAUDRATE);
+  rfidSerial.begin(SERIAL_BAUDRATE);

   // Setup lock
   pinMode(A0, OUTPUT);
@@ -51,7 +57,37 @@
   digitalWrite(A0, locked);
 }

+bool readRfid() {
+  char buffer[TAG_LENGTH];
+  int count = 0;
+  bool tagChanged = false;
+
+  if (rfidSerial.available()) {
+    if (rfidSerial.read() != 2)
+      return false;
+    while (count < TAG_LENGTH && rfidSerial.available()) {
+      buffer[count] = rfidSerial.read();
+      count++;
+    }
+
+    if (count == TAG_LENGTH) {
+      count = 0;
+      if (rfidSerial.read() != 3)
+        return false;
+      for (int i = 0; i < TAG_LENGTH; i++) {
+        tagChanged |= buffer[i] != rfidTag[i];
+      }
+    }
+    if (tagChanged) {
+      memcpy(rfidTag, buffer, TAG_LENGTH);
+      rfidTag[TAG_LENGTH] = 0;
+      Serial.print("Changed: "); Serial.println(rfidTag);
+    }
+  }
+}
+
 void loop() {
+  readRfid();
   readLightsensor();
   readDataFromMpu();

@@ -73,6 +109,9 @@
           setLockState(false);
           break;
       }
+      break;
+    case 'r':
+      xbeeSerial.print("r=");xbeeSerial.println(rfidTag);
       while (xbeeSerial.available())
         xbeeSerial.read();
       break;


oops remove mdns test

oops remove mdns test

--- examples/DEV/OnDemandConfigPortal/OnDemandConfigPortal.ino
+++ examples/DEV/OnDemandConfigPortal/OnDemandConfigPortal.ino
@@ -10,7 +10,6 @@
 #define USEOTA
 // enable OTA
 #ifdef USEOTA
-#include <ESPmDNS.h>
 #include <WiFiUdp.h>
 #include <ArduinoOTA.h>
 #endif


Updated Ethernet WebServer example to give more diagnostic info

--- libraries/Ethernet/examples/WebServer/WebServer.ino
+++ libraries/Ethernet/examples/WebServer/WebServer.ino
@@ -10,7 +10,7 @@

  created 18 Dec 2009
  by David A. Mellis
- modified 4 Sep 2010
+ modified 20 Mar 2012
  by Tom Igoe

  */
@@ -20,7 +20,8 @@

 // Enter a MAC address and IP address for your controller below.
 // The IP address will be dependent on your local network:
-byte mac[] = { 0xDE, 0xAD, 0xBE, 0xEF, 0xFE, 0xED };
+byte mac[] = {
+  0xDE, 0xAD, 0xBE, 0xEF, 0xFE, 0xED };
 IPAddress ip(192,168,1, 177);

 // Initialize the Ethernet server library
@@ -28,23 +29,27 @@
 // (port 80 is default for HTTP):
 EthernetServer server(80);

-void setup()
-{
+void setup() {
+  Serial.begin(9600);
   // start the Ethernet connection and the server:
   Ethernet.begin(mac, ip);
   server.begin();
+  Serial.print("server is at ");
+  Serial.println(Ethernet.localIP());
 }

-void loop()
-{
+
+void loop() {
   // listen for incoming clients
   EthernetClient client = server.available();
   if (client) {
+    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
@@ -52,16 +57,22 @@
           // send a standard http response header
           client.println("HTTP/1.1 200 OK");
           client.println("Content-Type: text/html");
+          client.println("Connnection: close");
           client.println();
-
+          client.println("<!DOCTYPE HTML>");
+          client.println("");
+                    // add a meta refresh tag, so the browser pulls again every 5 seconds:
+          client.println("<meta http-equiv=\"refresh\" content=\"5\">");
           // output the value of each analog input pin
           for (int analogChannel = 0; analogChannel < 6; analogChannel++) {
+            int sensorReading = analogRead(analogChannel);
             client.print("analog input ");
             client.print(analogChannel);
             client.print(" is ");
-            client.print(analogRead(analogChannel));
-            client.println("
");
+            client.print(sensorReading);
+            client.println("
");
           }
+          client.println("");
           break;
         }
         if (c == '\n') {
@@ -78,5 +89,7 @@
     delay(1);
     // close the connection:
     client.stop();
+    Serial.println("client disonnected");
   }
 }
+


Suppress mode output

Suppress mode output

--- HBridgePWM/Sabertooth/Sabertooth.ino
+++ HBridgePWM/Sabertooth/Sabertooth.ino
@@ -110,13 +110,13 @@
     Serial.println(alphaSigned);
     if (isSerialControl)
     {
-      Serial.println("S");
+      //Serial.println("S");
     }
     else
     {
       if (isManualControl)
       {
-        Serial.println("M");
+        //Serial.println("M");
       }
     }


Delete spark-plotly.ino

Delete spark-plotly.ino

--- firmware/spark-plotly.ino
+++ firmware/spark-plotly.ino
@@ -1,30 +0,0 @@
-#include "spark-plotly.h"
-
-#define DATA_POINTS 4
-
-char* data_point_tokens[NUM_TOKENS] = {"token1", "token2", "token3","token4"};
-plotly graph = plotly("username", "secret", streaming_tokens, "streamname", DATA_POINTS);
-
-void setup() {
-   graph.init();
-   graph.fileopt = "extend";
-   graph.openStream();
-}
-
-void loop() {
-
-    float val1;
-    float val2;
-    float val3;
-    float val4;
-
-    // up to you to decide what these values represent and how they get initialized/updated.
-
-    unsigned long x = millis();
-
-    graph.plot(x, val1, data_point_tokens[0]);
-    graph.plot(x, val2, data_point_tokens[1]);
-    graph.plot(x, val3, data_point_tokens[2]);
-    graph.plot(x, val4, data_point_tokens[3]);
-
-}


Eliminate elided code to clean up the source. Eliminate dead function. Eliminate 62 bytes from binary sketch size.

--- arduino/beestation/beestation.ino
+++ arduino/beestation/beestation.ino
@@ -26,7 +26,6 @@
 #define USE_CC3300 01
 #define USE_DS2401 1
 #define USE_DS18B20 1
-#define USE_BMP 0
 #define USE_BME 1
 #define MY_DEBUG 0

@@ -68,6 +67,10 @@

 #if USE_BME
 Adafruit_BME280 gBme280; // I2C
+// Variables to be exposed
+int gHumidity = 0;
+int gPressure = 0;
+int gTemperature = 0;
 #endif // USE_BME

 #if USE_DS18B20
@@ -75,6 +78,8 @@
 int gDevices;
 #define DS_COUNT 10
 byte gDsAddrs[DS_COUNT][8];
+// Use array for DS18B20 temperatures and simplify HTTP printout code
+int gDsTemps[DS_COUNT];
 #endif // USE_DS18B20

 // PHP server on backend
@@ -84,25 +89,6 @@

 //unsigned long gTimeNow;
 unsigned long gCycles = 0;
-
-// Variables to be exposed
-int gHumidity = 0;
-int gPressure = 0;
-int gTemperature = 0;
-// To do: use array for DS18B20 temperatures and simplify HTTP printout code
-int gDsTemps[DS_COUNT];
-#if 0
-int gTempHive2Inch = 0; //3
-int gTempHive6Inch = 0; //4
-int gTempHive10Inch = 0; //5
-int gTempBox = 0; //2
-int gTemp2Hive2Inch = 0; //6
-int gTemp2Hive6Inch = 0; //7
-int gTemp2Hive10Inch = 0; //8
-int gTemp3Hive2Inch = 0; //9
-int gTemp3Hive6Inch = 0; //10
-int gTemp3Hive10Inch = 0; //11
-#endif

 // Serial Number of this beestation
 char gSerialNumber[3]; // read from Maxim DS2401 on pin 9, use rightmost word
@@ -147,7 +133,6 @@
 	setupCc3000();
 	displayConnectionDetails();
 #endif // USE_CC3300
-	//digitalWrite(gRedLED, LOW);
 	delay(2000);
 #if USE_CC3300
 	gIp = gCc3000.IP2U32(WEB_SERVER_IP_COMMAS);
@@ -186,16 +171,11 @@
 #if USE_CC3300
 	Serial.println(F("Connecting to web server"));
 	wdt_reset();
-	postReadingsToWeb(gIp); /*, gTemperature, gHumidity, gPressure); */
-						   /* , gTempBox,
-		gTempHive2Inch, gTempHive6Inch, gTempHive10Inch,
-		gTemp2Hive2Inch, gTemp2Hive6Inch, gTemp2Hive10Inch,
-		gTemp3Hive2Inch, gTemp3Hive6Inch, gTemp3Hive10Inch);*/
+	postReadingsToWeb(gIp);
 	wdt_reset();
 	if (0 == (gCycles % 100)) {
 		char message[64];
 		char iBuf[12];
-		//strlcpy(message, ("Completed "), 64);
 		strlcpy(message, itoa(gCycles, iBuf, 10), 64);
 		strlcat(message, ("%20cycles"), 64);
 		postStatusToWeb(gIp, message);
@@ -215,14 +195,13 @@

 	if (!gCc3000.getIPAddress(&ipAddress, &netmask, &gateway, &dhcpserv, &dnsserv))
 	{
-		Serial.println(F("Can't get IP addr"));
+		Serial.println(F("Can't get IP"));
 		return false;
 	}
 	else
 	{
-		Serial.print(F("IP Addr: ")); gCc3000.printIPdotsRev(ipAddress);
-		Serial.print(F("\nGateway: ")); gCc3000.printIPdotsRev(gateway);
-		Serial.println("");
+		Serial.print(F("IP: ")); gCc3000.printIPdotsRev(ipAddress);
+		Serial.println(F("\nGateway: ")); gCc3000.printIPdotsRev(gateway);
 		return true;
 	}
 }
@@ -242,9 +221,7 @@
 #define OUTSTRSIZE 256
 // send sensor measurements to the webserver
 void
-postReadingsToWeb(uint32_t ip/*, int temperature, int humidity, int pressure //Save the stack space since using globals */
-							 /*,
-	int tBox, int t2In, int t6In, int t10In, int t2In2, int t6In2, int t10In2, int t2In3, int t6In3, int t10In3*/)
+postReadingsToWeb(uint32_t ip)
 {
 	// Build the URL string
 	char outStr[OUTSTRSIZE];
@@ -254,6 +231,7 @@
 	strlcat(outStr, ("sn="), OUTSTRSIZE);
 	strlcat(outStr, (gSerialNumber), OUTSTRSIZE);
 	strlcat(outStr, ("&"), OUTSTRSIZE);
+#if USE_BME
 	strlcat(outStr, ("t1="), OUTSTRSIZE);
 	itoa(gTemperature, itoaBuf, 10);
 	strlcat(outStr, (itoaBuf), OUTSTRSIZE);
@@ -265,7 +243,9 @@
 	strlcat(outStr, ("pr="), OUTSTRSIZE);
 	itoa(gPressure, itoaBuf, 10);
 	strlcat(outStr, (itoaBuf), OUTSTRSIZE);
+#endif // USE_BME
 	/* Write DS18B20 results */
+#if USE_DS18B20
 	for (int j = 0; j < DS_COUNT; j++) {
 		strlcat(outStr, ("&t"), OUTSTRSIZE);
 		itoa((j+2), itoaBuf, 10);
@@ -274,49 +254,8 @@
 		itoa(gDsTemps[j], itoaBuf, 10);
 		strlcat(outStr, (itoaBuf), OUTSTRSIZE);
 	}
-#if 0
-	strlcat(outStr, ("&"), OUTSTRSIZE);
-	strlcat(outStr, ("t2="), OUTSTRSIZE);
-	itoa(tBox, itoaBuf, 10);
-	strlcat(outStr, (itoaBuf), OUTSTRSIZE);
-	strlcat(outStr, ("&"), OUTSTRSIZE);
-	strlcat(outStr, ("t3="), OUTSTRSIZE);
-	itoa(t2In, itoaBuf, 10);
-	strlcat(outStr, (itoaBuf), OUTSTRSIZE);
-	strlcat(outStr, ("&"), OUTSTRSIZE);
-	strlcat(outStr, ("t4="), OUTSTRSIZE);
-	itoa(t6In, itoaBuf, 10);
-	strlcat(outStr, (itoaBuf), OUTSTRSIZE);
-	strlcat(outStr, ("&"), OUTSTRSIZE);
-	strlcat(outStr, ("t5="), OUTSTRSIZE);
-	itoa(t10In, itoaBuf, 10);
-	strlcat(outStr, (itoaBuf), OUTSTRSIZE);
-	strlcat(outStr, ("&"), OUTSTRSIZE);
-	strlcat(outStr, ("t6="), OUTSTRSIZE);
-	itoa(t2In2, itoaBuf, 10);
-	strlcat(outStr, (itoaBuf), OUTSTRSIZE);
-	strlcat(outStr, ("&"), OUTSTRSIZE);
-	strlcat(outStr, ("t7="), OUTSTRSIZE);
-	itoa(t6In2, itoaBuf, 10);
-	strlcat(outStr, (itoaBuf), OUTSTRSIZE);
-	strlcat(outStr, ("&"), OUTSTRSIZE);
-	strlcat(outStr, ("t8="), OUTSTRSIZE);
-	itoa(t10In2, itoaBuf, 10);
-	strlcat(outStr, (itoaBuf), OUTSTRSIZE);
-	strlcat(outStr, ("&"), OUTSTRSIZE);
-	strlcat(outStr, ("t9="), OUTSTRSIZE);
-	itoa(t2In3, itoaBuf, 10);
-	strlcat(outStr, (itoaBuf), OUTSTRSIZE);
-	strlcat(outStr, ("&"), OUTSTRSIZE);
-	strlcat(outStr, ("t10="), OUTSTRSIZE);
-	itoa(t6In3, itoaBuf, 10);
-	strlcat(outStr, (itoaBuf), OUTSTRSIZE);
-	strlcat(outStr, ("&"), OUTSTRSIZE);
-	strlcat(outStr, ("t11="), OUTSTRSIZE);
-	itoa(t10In3, itoaBuf, 10);
-	strlcat(outStr, (itoaBuf), OUTSTRSIZE);
-#endif
-    Serial.println(outStr);
+#endif
+	Serial.println(outStr);
 	postToWeb(ip, outStr);
 }

@@ -343,9 +282,7 @@
 	unsigned int gConnectTimeout = 2000;
 	unsigned long gTimeNow;

-	//cycleLed(gLED);
 	digitalWrite(gRedLED, HIGH);
-	//Serial.println(F("postToweb"));
 	gTimeNow = millis();
 	do {
 		Serial.println(F("->connectTCP"));
@@ -379,8 +316,7 @@
 	else
 	{ // you didn't get a connection to the server:
 		Serial.println(F("--> connection failed/n"));
-	}
-	//cycleLed(gLED);
+	}
 	digitalWrite(gRedLED, LOW);
 }

@@ -419,8 +355,6 @@
 void
 measureBme280(void)
 {
-	/* Get a new sensor event */
-	//sensors_event_t event;
 	float temperature;
 	float pressure;
 	float humidity;
@@ -493,25 +427,18 @@
 void
 checkAndResetWifi(void)
 {
-	unsigned long gTimeNow;
-
-	wdt_reset();
-	if (!gCc3000.checkConnected() /* || (gCycles>5)*/)
+	wdt_reset();
+	if (!gCc3000.checkConnected() )
 	{
 		Serial.print(F("Time: "));
+#if 0
 		gTimeNow = millis();
 		//prints time since program started
 		Serial.println(gTimeNow);
+#endif
 		Serial.println(F("Lost WiFi. Rebooting CC3000"));
 		gCc3000.disconnect();
 		gCc3000.stop();
-		/*
-		gCc3000 = Adafruit_CC3000(ADAFRUIT_CC3000_CS,
-			ADAFRUIT_CC3000_IRQ,
-			ADAFRUIT_CC3000_VBAT,
-			SPI_CLOCK_DIV2);
-		delay(20);
-		*/
 		wdt_reset();
 		gCc3000.reboot(0);
 		// setupCc3000() was rarely finishing before the watchdog bites, so let it
@@ -524,15 +451,6 @@
 	extern int __heap_start, *__brkval;
 	int v;
 	return (int)&v - (__brkval == 0 ? (int)&__heap_start : (int)__brkval);
-}
-
-void
-cycleLed(int pin)
-{
-	uint8_t mode = LOW;
-
-	mode = (mode == HIGH) ? LOW : HIGH;
-	digitalWrite(pin, mode);
 }

 // Feed the dog so it doesn't bite
@@ -564,11 +482,8 @@
 {
 	byte addr[8];
 	int deviceCount = 0;
-	/* uint16_t present = */

 	myDs.reset();
-	//Serial.print("OneWire presence on 6: ");
-	//Serial.println(present);
 	myDs.reset_search();
 	while (myDs.search(addr)) {
 		if (checkDsCrc(myDs, addr)) {
@@ -628,37 +543,11 @@
 void
 measureDs18B20(void) {
 	for (int i = 0; i < gDevices; i++) {
-#if 0
-		float fpTemp = getDsTempeature(gDs, gDsAddrs[i]);
-		int intTemp = (int)(fpTemp + 0.5);
-#else
 		int intTemp = getDsTempeature(gDs, gDsAddrs[i]);
-#endif
 #if MY_DEBUG
-		//Serial.print(fpTemp);
-		//Serial.print(F(" ==> "));
 		Serial.println(intTemp);
 #endif	// MY_DEBUG
-#if 0
-		switch (gDsAddrs[i][7]) {
-		case 0x67: // Blue
-			gTempHive2Inch = intTemp;
-			Serial.print(F("2in temp: "));
-			break;
-		case 0x36: //yellow
-			gTempHive6Inch = intTemp;
-			Serial.print(F("6in temp: "));
-			break;
-		case 0xC0: // red
-			gTempBox = intTemp;
-			Serial.print(F("box temp: "));
-			break;
-		case 0xB1: // blue
-			gTempHive10Inch = intTemp;
-			Serial.print(F("10in temp: "));
-			break;
-}
-#else // save some bytes over switch with cascading if's - ha ha
+ // save some bytes over switch with cascading if's - ha ha
 		if (0x67 == gDsAddrs[i][7]) {
 			gDsTemps[1] = intTemp;
 #if MY_DEBUG
@@ -719,7 +608,6 @@
 			Serial.print(F("10in temp2: "));
 #endif
 		}
-#endif
 #if MY_DEBUG
 		Serial.println(intTemp);
 #endif
@@ -727,12 +615,10 @@
 }

 // Testing shows 10-bit resolution give more than adequate precision and accuracy
-/*float*/
 int
 getDsTempeature(OneWire myDs, byte addr[8])
 {
 	byte data[12];
-	//int celsius;
 	wdt_reset();

 	// Get byte for desired resolution
@@ -783,7 +669,6 @@
 #endif // MY_DEBUG

 	// convert the data to actual temperature
-	/*unsigned int raw = (data[1] << 8) | data[0]; */
 	int raw = (data[1] << 8) + data[0];
 	// What about negative temps?
 	// look for sign bit per http://stackoverflow.com/questions/30646783/arduino-temperature-sensor-negative-temperatures
@@ -794,13 +679,11 @@
 	int celsius_100 = (6 * raw) + raw / 4;    // multiply by (100 * 0.0625) or 6.25

 	int whole = celsius_100 / 100;  // separate off the whole and fractional portions
-	//int fract = celsius_100 % 100;
-	//
-
-	//celsius = (float)raw / 16.0;
-	//celsius = whole;
-	//Serial.print("Temp (C): ");
-	return whole /* celsius*/;
+	//int fraction = celsius_100 % 100;
+#if MY_DEBUG
+	Serial.print("Temp (C): ");
+#endif // MY_DEBUG
+	return whole;
 	}

 void


Update default settings

Update default settings

We now run the system with the same schedule and settings all the time.
When the microcontroller starts it assumes that the time is 20:00 and it
runs the pump. Then every 20min it sprays the roots for 2s.

Also make some style changes to the code and clean up a k = k++ wtf...

Signed-off-by: Robin Hagman <a0ad21b4a5c77bde0f74c8a70cf9b810eabd0434@gmail.com>

--- arduino_sketch/arduino_sketch.ino
+++ arduino_sketch/arduino_sketch.ino
@@ -3,53 +3,53 @@
 #include <Time.h>       // For timekeeping
 #include <Wire.h>       // For I2C

-//Define LED pins (PWM pins: 3,5,6,9,10,11 on arduino UNO)
+// Define LED pins (PWM pins: 3,5,6,9,10,11 on arduino UNO)
 const int RED   = 11;
 const int GREEN = 10;
 const int BLUE  = 9;
 const int PUMP  = 2;
 const int NOZZLE = 12;
 const int FAN = 7;
-const int BOARDLED = 13; //Pin 13 and Arduino UNO board LED
-const int LIGHT = A0;           // Light sensor, Analog pin 0
-const int runInterval = 1;      // Define delay between the run and measure interval in seconds
+const int BOARDLED = 13; // Pin 13 and Arduino UNO board LED
+const int LIGHT = A0;    // Light sensor, Analog pin 0
+const int runInterval = 1;
 const int measureInterval = 3600;

 // Define DHT11 sensor
-#define DHTPIN 8         // what pin we're connected to
-#define DHTTYPE DHT11    // DHT 11
-DHT dht(DHTPIN, DHTTYPE);// make the object
+#define DHTPIN 8          // What pin we're connected to
+#define DHTTYPE DHT11     // DHT 11
+DHT dht(DHTPIN, DHTTYPE); // Make the object

 /**
  * User schedule of all settings
  * (7 settings, 1-9 predefined settinggroups, 1-7 days with 1h resolution)
  */
-int num_usr_settings = 2;     // Setting sets available (Default: 2)
-int num_usr_settings_day = 1; // Day setting sets available (Default: 1)
-const int NUM_SETTINGS = 7;         // Day setting sets
-const int NUM_SETTINGS_DAY = 24;    // Hour setting sets
+int num_usr_settings = 2;        // Setting sets available (Default: 2)
+int num_usr_settings_day = 1;    // Day setting sets available (Default: 1)
+const int NUM_SETTINGS = 7;      // Day setting sets
+const int NUM_SETTINGS_DAY = 24; // Hour setting sets
 // Setting sets
 int usrSch[9][NUM_SETTINGS] = {
-  {0,0,0,0,10,2,0}, // Spray the roots at a set interval and duration (Default)
-  {0,0,0,1,10,2,0}, // Run the pump (Default)
+  {0,0,0,0,20,2,0}, // Spray the roots at a set interval and duration (Default)
+  {0,0,0,1,20,2,0}, // Run the pump (Default)
   {25,25,0,0,20,2,0},
   {25,25,25,0,20,2,0},
   {50,50,50,0,20,2,0},
   {100,100,100,0,20,2,0},
-  {100,100,100,1,20,2,0},
   {100,100,100,0,20,2,0},
-  {100,100,100,1,20,2,0}
+  {100,100,100,0,20,2,0},
+  {100,100,100,0,20,2,0}
 };
 // Day setting sets (0:00-23:00)
 int usrSchInd[NUM_SETTINGS][NUM_SETTINGS_DAY] = {
   {0,0,0,0,0,0,0,0,0,0,1,0,0,0,0,0,0,0,0,0,1,0,0,0}, // Pump at 10:00 and 20:00
-  {0,0,0,0,1,2,3,4,5,6,5,5,5,5,5,5,4,3,2,1,0,0,0,0},
-  {0,0,0,0,1,2,3,4,5,6,5,5,5,5,5,5,4,3,2,1,0,0,0,0},
-  {0,0,0,0,1,2,3,4,5,6,5,5,5,5,5,5,4,3,2,1,0,0,0,0},
-  {0,0,0,0,1,2,3,4,5,6,5,5,5,5,5,5,4,3,2,1,0,0,0,0},
-  {0,0,0,0,1,2,3,4,5,6,5,5,5,5,5,5,4,3,2,1,0,0,0,0},
-  {0,0,0,0,1,2,3,4,5,6,5,5,5,5,5,5,4,3,2,1,0,0,0,0}
+  {0,0,0,0,0,0,0,0,0,0,1,0,0,0,0,0,0,0,0,0,1,0,0,0},
+  {0,0,0,0,0,0,0,0,0,0,1,0,0,0,0,0,0,0,0,0,1,0,0,0},
+  {0,0,0,0,0,0,0,0,0,0,1,0,0,0,0,0,0,0,0,0,1,0,0,0},
+  {0,0,0,0,0,0,0,0,0,0,1,0,0,0,0,0,0,0,0,0,1,0,0,0},
+  {0,0,0,0,0,0,0,0,0,0,1,0,0,0,0,0,0,0,0,0,1,0,0,0},
+  {0,0,0,0,0,0,0,0,0,0,1,0,0,0,0,0,0,0,0,0,1,0,0,0}
 };

 // Variables for RGB levels
@@ -58,10 +58,10 @@
 int bval = 0;

 // Variable for pump
-int pumpOn = 0; //0 off, 1 on
-int nozzleInterval = 10; //min interval between nozzle activation >60 == off
-int nozzleDuration = 2; //2 sec active nozzle <0 == off
-int fanStatus = 0; //0 off, 1 on
+int pumpOn = 0; // 0 off, 1 on
+int nozzleInterval = 20; // min interval between nozzle activation >60 == off
+int nozzleDuration = 2; // 2 sec active nozzle <0 == off
+int fanStatus = 0; // 0 off, 1 on

 // Run preprogrammed setup, oneReport after nozzle on
 int runProgram = 1;
@@ -76,12 +76,12 @@
 int sensorTempData[] = {0,0,0}; // temp, humid, light

 void setup() {
-  Wire.begin();       // conects I2C
-  Serial.begin(9600); //Serial port at 9600 baud
-  dht.begin();        //Start the dht object
+  Wire.begin();       // Connects I2C
+  Serial.begin(9600); // Serial port at 9600 baud
+  dht.begin();        // Start the dht object

   // Set the time
-  setTime(10,0,0,1,1,2014); // hour,min,sec,day,month,year
+  setTime(20,0,0,1,1,2014); // hour,min,sec,day,month,year

   // Set pins as outputs
   pinMode(RED, OUTPUT);
@@ -141,7 +141,7 @@
     if (sensorTempData[0] >= 30 || sensorTempData[1] >= 50) {
       setFan(1);
     }
-    if(sensorTempData[0] < 30 && sensorTempData[1] < 50) {
+    if (sensorTempData[0] < 30 && sensorTempData[1] < 50) {
       setFan(0);
     }

@@ -159,16 +159,16 @@
 void serialControl()
 {
     char c = Serial.read();
-    switch(c){
+    switch (c) {
       case 'S':
       {
-        rval   = Serial.parseInt(); //First valid integer
-        gval   = Serial.parseInt(); //Second valid integer
-        bval   = Serial.parseInt(); //Third valid integer
-        pumpOn = Serial.parseInt(); //Fourth valid integer
-        nozzleInterval = Serial.parseInt(); //Fifth valid integer
-        nozzleDuration = Serial.parseInt(); //sixth valid integer
-        fanStatus = Serial.parseInt(); //seventh valid integer
+        rval   = Serial.parseInt();         // First valid integer
+        gval   = Serial.parseInt();         // Second valid integer
+        bval   = Serial.parseInt();         // Third valid integer
+        pumpOn = Serial.parseInt();         // Fourth valid integer
+        nozzleInterval = Serial.parseInt(); // Fifth valid integer
+        nozzleDuration = Serial.parseInt(); // Sixth valid integer
+        fanStatus = Serial.parseInt();      // Seventh valid integer

         setLight();
         setPump();
@@ -184,13 +184,11 @@
       }
       case 'Q':
       {
-        if(runProgram == 1)
-        {
+        if (runProgram == 1) {
           runProgram = 0;
           break;
         }
-        if(runProgram == 0)
-        {
+        if (runProgram == 0) {
           runProgram = 1;
           break;
         }
@@ -201,7 +199,7 @@
         int h  = Serial.parseInt(); //First valid integer
         int m  = Serial.parseInt(); //Second valid integer
         int d  = Serial.parseInt(); //Third valid integer
-        setTime(h,m,0,d,1,2014); //hour,min,sec,day,month,year
+        setTime(h,m,0,d,1,2014);    //hour,min,sec,day,month,year
         t = now();
         tDelay = runInterval;
         tDelayMin = measureInterval;
@@ -210,13 +208,32 @@
       case 'U':
       {
         int k = 0;
-        num_usr_settings = Serial.parseInt();  //The first int is the number of user settings from the user
-        while(k < num_usr_settings){
-          for(int i = 0; i < NUM_SETTINGS; i++){
+        num_usr_settings = Serial.parseInt(); // The first int is the number
+        while (k < num_usr_settings) {        // of user settings from the user
+          for (int i = 0; i < NUM_SETTINGS; i++) {
             usrSch[k][i] = Serial.parseInt();
             Serial.print(usrSch[k][i]);
-            if(i==NUM_SETTINGS-1){
-              k = k++;
+            if (i == NUM_SETTINGS - 1) {
+              k++;
+              Serial.println("");
+            }
+            else {
+              Serial.print(",");
+            }
+          }
+        }
+        break;
+      }
+      case 'I':
+      {
+        int k = 0;
+        num_usr_settings_day = Serial.parseInt();
+        while (k < num_usr_settings_day) {
+          for (int i = 0; i < NUM_SETTINGS_DAY; i++) {
+            usrSchInd[k][i] = Serial.parseInt();
+            Serial.print(usrSchInd[k][i]);
+            if (i == NUM_SETTINGS_DAY - 1) {
+              k++;
               Serial.println("");
             }
             else{
@@ -226,31 +243,12 @@
         }
         break;
       }
-      case 'I':
-      {
-        int k = 0;
-        num_usr_settings_day = Serial.parseInt();  //The first int is the number of user settings for a day from the user
-        while(k < num_usr_settings_day){
-          for(int i = 0; i < NUM_SETTINGS_DAY; i++){
-            usrSchInd[k][i] = Serial.parseInt();
-            Serial.print(usrSchInd[k][i]);
-            if(i==NUM_SETTINGS_DAY-1){
-              k = k++;
-              Serial.println("");
-            }
-            else{
-              Serial.print(",");
-            }
-          }
-        }
-        break;
-      }
     }
 }

 void scheduleFromUser() {
   // Change every hour
-  int x = hour(t); //0-23
+  int x = hour(t); // 0-23
   int y = day(t) % num_usr_settings_day; // Rotate the days
   int z = usrSchInd[y][x];

@@ -281,14 +279,15 @@
   reportValues = reportValues + ",";
   reportValues = reportValues + fanStatus;

-  reportValues = timeReport() + "S" + sensorTempData[0] + "," + sensorTempData[1] + ","
+  reportValues = timeReport() + "S" + sensorTempData[0] + ","
+                                    + sensorTempData[1] + ","
                                     + sensorTempData[2] + reportValues;
   Serial.println(reportValues);
 }

 void setLight()
 {
-  //Set LED (value between 0 and 255)
+  // Set LED (value between 0 and 255)
   analogWrite(RED, rval);
   analogWrite(GREEN, gval);
   analogWrite(BLUE, bval);
@@ -308,20 +307,17 @@

 void setNozzle()
 {
-  if(nozzleDuration == 0)
-  {
+  if (nozzleDuration == 0) {
     digitalWrite(NOZZLE, LOW);
   }
 }

 void setFan(int setStatus)
 {
-  if(setStatus == 1)
-  {
+  if (setStatus == 1) {
     digitalWrite(FAN, HIGH);
   }
-  if(setStatus == 0)
-  {
+  if (setStatus == 0) {
     digitalWrite(FAN, LOW);
   }
 }
@@ -365,14 +361,12 @@
   float h = dht.readHumidity();
   float t = dht.readTemperature();

-  // check if returns are valid, if they are NaN (not a number) then something went wrong!
-  if (isnan(t) || isnan(h))
-  {
+  // check if returns are valid, if NaN (not a number) then set to 0
+  if (isnan(t) || isnan(h)) {
     sensorTempData[0] = 0;
     sensorTempData[1] = 0;
   }
-  else
-  {
+  else {
     sensorTempData[0] = (int)t;
     sensorTempData[1] = (int)h;
   }


sundry cuteness lol wuteva

sundry cuteness lol wuteva

--- colors_arduino/colors_arduino.ino
+++ colors_arduino/colors_arduino.ino
@@ -15,7 +15,6 @@
 const int LEFT = 3;

 // Game state
-const int blankBoard[4][4] = {{0, 0, 0, 0}, {0, 0, 0, 0}, {0, 0, 0, 0}, {0, 0, 0, 0}};
 int board[4][4];
 int tempBoard[4][4];
 bool gameInProgress = false;
@@ -135,7 +134,7 @@
 /* Resets internal game state and display. */
 void newGame() {
     // Clear board
-    memcpy(board, blankBoard, sizeof(board));
+    memset(board, 0, sizeof(board));

     // Add |initialTiles| new tiles to the board
     int initialTiles = 2;