# Question
Title: CRC test fail on MS5803-14BA pressure sensor - what can I do?
**Problem:**

I bought two MS5803-14BA sensors and I soldered them myself to a SOIC-8 PCB to be able to use them. Only one sensor is used in my circuit. To access it, I use an Arduino Pro Mini 8MHz/3.3V with a library that has a CRC check for the sensor. When assembled to the circuit, one of the sensors pass the test, however the other fails. I'm using I2C to access the sensor.

I would like both sensors to pass the test so I could compare readings from two assembled circuits, but I really don't know how to do it. I have a three questions:

* Where this problem can be originating from?
* What kind of limitations I have for not passing the CRC test? Does it mean that the collected data can not be trusted?
* If I use the raw readings D1 and D2 from a sensor that have failed the CRC test and pos-compensate them in the computer, will I have trustful results?
* How to solve it?

**Schematic:**

simulate this circuit – Schematic created using CircuitLab

* The resistors R1 and R2 are pull-up resistors.
* The capacitor C1 is recommended by the sensor's datasheet.
* Sensor's PS pin is connected to Vcc in order to select I2C mode for communication. The other option was SDI.
* Sensor's CLS pin is connected to ground to select the address 0x77 to the sensor. Case it is connected to Vcc, the address is set to 0x76.

**Documentation**

# Answer
> 0 votes
### Where this problem can be originating from?

As per page 7 and page 14 of the data sheet, there are 16 bytes of PROM in the unit which contain calibration information determined and written at the factory. This calibration information includes coefficients that must be used by whatever's reading the sensor to adjust for manufacturing variations. The data also include a CRC check code to let you confirm you've read the PROM correctly.

So there are three possibilities here:

1. The CRC as written to PROM is wrong.
2. There was an error while transferring the data from PROM to your MCU.
3. The software is doing the CRC calculation incorrectly.

The source code suggests that the most likely reason for this sort of failure is faulty wiring between the MCU and the sensor.

### What kind of limitations I have for not passing the CRC test? Does it mean that the collected data can not be trusted?

Potentially, yes. To determine how bad things really are and what might be going wrong you need to do a bit more experimentation.

When you call the `initializeMS_5803()` function you pass it a boolean parameter determining whether it's running in verbose mode. Set this to true so it prints out the coefficients 0 through 7 to the serial port during initialization. Restart your Arduino several times, ideally under different conditions of temperature, power, physical wire configuration (if any), etc., and see if the values ever change. If they are ever different from a previous run, you have either cabling corrupting the data transfer or a defective sensor. You may be able to look at which bits change, if any change consistently, to get some insight into how "random" the problem really is. (Could it be that only a certain bit pattern is being transmitted unreliably?)

If all values always read the same, compare them to the values read from your good sensor. If they're quite similar, and you're generally getting similar readings under similar conditions from both sensors, I would suspect possibility 1 or 3 above, and reckon that you're likely to be getting reasonably reliable data from the sensor. If the values are vastly different this doesn't necessarily mean that the sensor will be unreliable; I have no idea how much these coefficients vary from unit to unit.

### If I use the raw readings D1 and D2 from a sensor that have failed the CRC test and pos-compensate them in the computer, will I have trustful results?

Again, that depends on whether or not it looks as if you're getting corruption on the data link. As above, if you ever read different PROM data from run to run on startup, the sensor is much less likely to be producing trustworthy data.

You could also try comparing the raw readings from both sensors under conditions as close to identical as you can make them. I don't know how close in calibration the two sensors are, but if they are close, the raw data should look similar and that would be a sign of reliability.

### How to solve it?

First, determine if you are getting the same or different PROM values across multiple startups. If they're always the same, send your good and bad values to the author of the driver and ask him if he thinks his CRC algorithm might have an error in it. (Or check it yourself against the application note mentioned in the data sheet, if you feel up to it.)

If the CRC algorithm in the software you're using is correct, given that you appear to reading successfully from another sensor, I'd send the sensor giving the CRC error back to the manufacturer, along with the coefficients you had read, with a query as to whether they have got the CRC wrong or you're reading the data wrong.

If you're getting different PROM values, that's either a faulty sensor or a wiring problem. You may be able to help isolate this with the usual tricks: slow down the transfer speed (with `Wire.setClock()`) to see if that reduces data corruption, re-wire the circuit with different (and preferably shorter) wires and other parts, make sure you've got caps in the appropriate places to filter noise, put a scope or a logic analyzer on the SCK and SDA lines to see if you can see any dodgy-looking waveforms, and so on. If anything looks strange, you can always use your working unit for comparison. If all that still looks good, it may well be a faulty sensor.

---
Tags: sensors, i2c, arduino-pro-mini, pressure
---


# Question
Title: Cannot locate Rx Tx pins on SIM800a GSM module
I recently bought a SIM800a GSM module in India and I am unable to find the Rx Tx pins of the module to make calls using a Arduino duimilanove.

The main problem is also that I can't find the data sheet for Sim800a in the net so that I can use a multi meter to determine the Rx Tx pins.

Here are some screenshots of the module-

There is no label showing Rx Tx here. There is I2C protocol(SCL,SDA) but I dont know how to code in Arduino for making a call using I2C.

I found a SIM800a picture on ebay with labels(not the data sheet) but when I tried using the pins in that manner it did not work. The SIM800a I have is connected to the network as the network led blinks after 3 sec and when I call it then the alarm rings. But it is unable to transmit calls or sms.

This is the code I am using. I remove the Rx Tx pins before uploading the code and immediately put them after uploading.

```
char phone_no[]="9953642386";
void setup()
{
Serial.begin(9600);  //Open Serial Connection at baudrate 9600
delay(5000);
Serial.println("AT"); // Wake up GSM
Serial.print("ATD"); //Dial the phone number using ATD command
Serial.print(phone_no);
Serial.println(";"); // Semicolon is a must at the end
delay(5000);
Serial.println("ATH"); // After a delay of 5 secs Hang the call
}
void loop()
{
// empty loop.If you enter the above code here,the call will be made FOR EVER repeatedly.
//Take Caution while coding under loop.At some condition you’ve to terminate the Call
}

```

Otherwise is it possible to use the SDA and SCL pins for this purpose of calling to a phone from the gsm module ? Any help would be appreciated.

# Answer
> 1 votes
This datasheet may help you. On page 14 you can see TXD and RXD are pins 9 and 10.

Orientation is hard to determine, but it appears that pin 1 is where the most red on the label is.

You should now be able to trace where those pins go to. They look like they go to high numbered pins, around the 11/12 area.

---
Tags: arduino-due, gsm
---


# Question
Title: Reading Arduino serial data in Octave on Mac
I am trying to read serial port data generated by Arduino in Octave on Mac. I installed and loaded the instrument-control package for the same. I used this piece of code to check if the package was installed properly

```
if (exist("serial") == 3) disp("Serial: Supported") else disp("Serial: Unsupported") endif

```

I do get an output saying Serial: Supported.

I am following the tutorial here for step by step guidance. I next use `s=serial('portname')` to create a serial port object. However, I am not sure what name to use instead of COM5 on Windows for Mac.

I checked and my Arduino is connected to cu.usbmodem1421 so I tried following 3 options a)cu.usbmodem1421 b) usbmodem1421 c)1421 but in each case I get an error saying "serial: Error opening the interface: No such file or directory".

Could anyone tell me what port name I can use or if there are any suggestions for the big picture problem as to how to read Arduino serial data in Octave (on Mac)? Thanks for the help in advance.

# Answer
> 1 votes
You most likely need the full canonical pathname for the port:

```
/dev/cu.usbmodem1421

```

On the Mac, as in Linux and other Unix derivatives, most devices, serial ports included, are special files in the `/dev` directory.

---
Tags: arduino-uno, serial
---


# Question
Title: Conditional compilation, how to determine whether a variable has been declared?
Whilst using #if/#end constructs, how can I determine whether a specific variable has already been declared?, e.g.,

```
#if [the variable "pinname" has been declared]
Serial.print(F("Pin name: "));
Serial.println(pinname);
#end

```

If this question has been addressed, I cannot find a reference for it.

# Answer
Normally you use the "#ifdef" directive.

The opposite is "#ifndef".

For example, if you only wanted to include variable definitions once many use this pattern for a header file named, say, "my\_variables.h":

```
#ifndef MY_VARIABLES_H
#def MY_VARIABLES_H

int counter;
bool flag;

#endif

```

In this way, no matter how many times you include this file, you only define the variables once. Because after the 1st time the compiler sees this file, the variable MY\_VARIABLES\_H is defined and the subsequent time the compiler sees this file, the compiler will skip over the variable defines.
> 1 votes

# Answer
You cannot. Simple as that.

I suspect this is an XY Problem. If you edit your post stating what you're actually trying to do, I'll edit my answer (or delete it if I don't know).
> 1 votes

---
Tags: programming, c++, variables
---


# Question
Title: Slackbot integration using ESP8266 gets "ssl->need_bytes=16432 > 6859"
I'm trying to use Uri Shaked Slackbot code using an Adafruit Feather Huzzah ESP8266 WiFi.

I have created the Slackbot integration and copied the API key. The code connects to the WiFi and does the time configuration but then hangs when connecting to slack with the error message in the serial monitor.

> ssl-need\_bytes=16432 \> 6859

```
/**
   Arduino Real-Time Slack Bot
   Copyright (C) 2016, Uri Shaked.
   Licensed under the MIT License
*/

#include <Arduino.h>
#include <ESP8266WiFi.h>
#include <ESP8266WiFiMulti.h>
#include <ESP8266HTTPClient.h>
#include <WebSocketsClient.h>
#include <ArduinoJson.h>
#include <Adafruit_NeoPixel.h>

#define SLACK_SSL_FINGERPRINT "AC 95 5A 58 B8 4E 0B CD B3 97 D2 88 68 F5 CA C1 0A 81 E3 6E" // If Slack changes their SSL fingerprint, you would need to update this
#define SLACK_BOT_TOKEN "https://slack.com/api/rtm.start?token=[MY TOKEN]" // Get token by creating new bot integration at https://my.slack.com/services/new/bot
#define WIFI_SSID       "[My WIFI]"
#define WIFI_PASSWORD   "[WiFi Password]"

#define LEDS_PIN        2
#define LEDS_NUMPIXELS  8
#define WORD_SEPERATORS "., \"'()[]<>;:-+&?!\n\t"

ESP8266WiFiMulti WiFiMulti;
WebSocketsClient webSocket;

Adafruit_NeoPixel pixels(LEDS_NUMPIXELS, LEDS_PIN, NEO_GRB + NEO_KHZ800);

long nextCmdId = 1;
bool connected = false;

/**
  Sends a ping message to Slack. Call this function immediately after establishing
  the WebSocket connection, and then every 5 seconds to keep the connection alive.
*/
void sendPing() {
  DynamicJsonBuffer jsonBuffer;
  JsonObject& root = jsonBuffer.createObject();
  root["type"] = "ping";
  root["id"] = nextCmdId++;
  String json;
  root.printTo(json);
  webSocket.sendTXT(json);
}

/**
  Input a value 0 to 255 to get a color value.
  The colors are a transition r - g - b - back to r.
*/
uint32_t wheel(byte wheelPos) {
  wheelPos = 255 - wheelPos;
  if (wheelPos < 85) {
    return pixels.Color(255 - wheelPos * 3, 0, wheelPos * 3);
  }
  if (wheelPos < 170) {
    wheelPos -= 85;
    return pixels.Color(0, wheelPos * 3, 255 - wheelPos * 3);
  }
  wheelPos -= 170;
  return pixels.Color(wheelPos * 3, 255 - wheelPos * 3, 0);
}

/**
  Animate a NeoPixel ring color change.
  Setting `zebra` to true skips every other led.
*/
void drawColor(uint32_t color, bool zebra) {
  int step = zebra ? 2 : 1;
  for (int i = 0; i < LEDS_NUMPIXELS; i += step) {
    pixels.setPixelColor(i, color);
    pixels.show();
    delay(30 * step);
  }
}

/**
  Draws a rainbow :-)
*/
void drawRainbow(bool zebra) {
  int step = zebra ? 2 : 1;
  for (int i = 0; i < LEDS_NUMPIXELS; i += step) {
    pixels.setPixelColor(i, wheel(i * 256 / LEDS_NUMPIXELS));
    pixels.show();
    delay(30 * step);
  }
}

/**
  Looks for color names in the incoming slack messages and
  animates the ring accordingly. You can include several
  colors in a single message, e.g. `red blue zebra black yellow rainbow`
*/
void processSlackMessage(char *payload) {
  char *nextWord = NULL;
  bool zebra = false;
  for (nextWord = strtok(payload, WORD_SEPERATORS); nextWord; nextWord = strtok(NULL, WORD_SEPERATORS)) {
    if (strcasecmp(nextWord, "zebra") == 0) {
      zebra = true;
    }
    if (strcasecmp(nextWord, "red") == 0) {
      drawColor(pixels.Color(255, 0, 0), zebra);
    }
    if (strcasecmp(nextWord, "green") == 0) {
      drawColor(pixels.Color(0, 255, 0), zebra);
    }
    if (strcasecmp(nextWord, "blue") == 0) {
      drawColor(pixels.Color(0, 0, 255), zebra);
    }
    if (strcasecmp(nextWord, "yellow") == 0) {
      drawColor(pixels.Color(255, 160, 0), zebra);
    }
    if (strcasecmp(nextWord, "white") == 0) {
      drawColor(pixels.Color(255, 255, 255), zebra);
    }
    if (strcasecmp(nextWord, "purple") == 0) {
      drawColor(pixels.Color(128, 0, 128), zebra);
    }
    if (strcasecmp(nextWord, "pink") == 0) {
      drawColor(pixels.Color(255, 0, 96), zebra);
    }
    if (strcasecmp(nextWord, "orange") == 0) {
      drawColor(pixels.Color(255, 64, 0), zebra);
    }
    if (strcasecmp(nextWord, "black") == 0) {
      drawColor(pixels.Color(0, 0, 0), zebra);
    }
    if (strcasecmp(nextWord, "rainbow") == 0) {
      drawRainbow(zebra);
    }
    if (nextWord[0] == '#') {
      int color = strtol(&nextWord[1], NULL, 16);
      Serial.println("Color");
      Serial.print(color);
      if (color) {
        drawColor(color, zebra);
      }
    }
  }
}

/**
  Called on each web socket event. Handles disconnection, and also
  incoming messages from slack.
*/
void webSocketEvent(WStype_t type, uint8_t *payload, size_t len) {
  switch (type) {
    case WStype_DISCONNECTED:
      Serial.printf("[WebSocket] Disconnected :-( \n");
      connected = false;
      break;

    case WStype_CONNECTED:
      Serial.printf("[WebSocket] Connected to: %s\n", payload);
      sendPing();
      break;

    case WStype_TEXT:
      Serial.printf("[WebSocket] Message: %s\n", payload);
      processSlackMessage((char*)payload);
      break;
  }
}

/**
  Establishes a bot connection to Slack:
  1. Performs a REST call to get the WebSocket URL
  2. Conencts the WebSocket
  Returns true if the connection was established successfully.
*/
bool connectToSlack() {
  // Step 1: Find WebSocket address via RTM API (https://api.slack.com/methods/rtm.start)
  HTTPClient http;

  Serial.printf("Connecting to\n");
  Serial.printf(SLACK_BOT_TOKEN);
  Serial.printf("\n");

  http.begin(SLACK_BOT_TOKEN, SLACK_SSL_FINGERPRINT);
  int httpCode = http.GET();

  if (httpCode != HTTP_CODE_OK) {
    Serial.printf("HTTP GET failed with code %d\n", httpCode);
    return false;
  }

  pixels.setPixelColor(3, pixels.Color(0, 2, 0));
  pixels.show();

  WiFiClient *client = http.getStreamPtr();
  client->find("wss:\\/\\/");
  String host = client->readStringUntil('\\');
  String path = client->readStringUntil('"');
  path.replace("\\/", "/");

  // Step 2: Open WebSocket connection and register event handler
  Serial.println("WebSocket Host=" + host + " Path=" + path);
  webSocket.beginSSL(host, 443, path, "", "");
  webSocket.onEvent(webSocketEvent);

  pixels.setPixelColor(4, pixels.Color(0, 2, 0));
  pixels.show();

  return true;
}

void setup() {
  Serial.begin(115200);
  Serial.setDebugOutput(true);

  pixels.begin();
  drawColor(pixels.Color(2, 0, 0), false);

  pixels.setPixelColor(0, pixels.Color(0, 2, 0));
  pixels.show();

  WiFiMulti.addAP(WIFI_SSID, WIFI_PASSWORD);
  while (WiFiMulti.run() != WL_CONNECTED) {
    delay(100);
  }

  pixels.setPixelColor(1, pixels.Color(0, 2, 0));
  pixels.show();

  configTime(3 * 3600, 0, "pool.ntp.org", "time.nist.gov");

  pixels.setPixelColor(2, pixels.Color(0, 2, 0));
  pixels.show();
}

unsigned long lastPing = 0;

/**
  Sends a ping every 5 seconds, and handles reconnections
*/
void loop() {
  webSocket.loop();

  if (connected) {
    // Send ping every 5 seconds, to keep the connection alive
    if (millis() - lastPing > 5000) {
      sendPing();
      lastPing = millis();
    }
  } else {
    // Try to connect / reconnect to slack
    connected = connectToSlack();
    if (!connected) {
      delay(500);
    }
  }
}

```

# Answer
@mach @Axel

I replaced use `rtm.start` with `rtm.connect` as per April 2017 Slack Recent Updates https://api.slack.com/changelog and this got rid of the error on my Wemos.

```
http.begin("https://slack.com/api/rtm.connect?token=" + SLACK_BOT_TOKEN, SLACK_SSL_FINGERPRINT);

```
> 1 votes

---
Tags: esp8266, adafruit
---


title: Arduino Simon Says with Midi Controller

text:
# Question
Title: Arduino Simon Says with Midi Controller
I altered code for the Simple Simon says to work with a Midi controller instead of push buttons. i am having trouble with the input of the song sequence with the Midi Controller. during the time where the code is waiting for input from the Midi controller **waitForButton(int delay)** the notes being inputted should sound but it dose not . i need help in figuring this out. any advice would be appreciated. Here's my code :https://pastebin.com/dV73eF9U

```
const int PLAY = 1;
const int TRYAGIN = 2;
long currentMillis = 0;
long previousMillis = 0;
int state;
void songlearn(int tune);
void showsequence();
void readsequnce();
void incorrect();
int tune;

void loop() {
  if (state == PLAY) {
    showsequence();
    readsequnce();
  }
  else if (state == TRYAGIN) {
    incorrect();
    state = PLAY;
  }
}

void MyHandleNoteOn(byte channel, byte pitch, byte velocity) {
  data1 = MIDI.getData1();
  if (data1 == 48) { //C3
    Status[0][0] = 1;
    noteOn(0, data1, 100);
    input[0] = data1;
  }
  if (data1 == 49) { //C3#
    Status[0][1] = 1;
    noteOn(0, data1, 100);
    input[1] = data1;
  }
  if (data1 == 50) { //D3
    Status[0][2] = 1;
    noteOn(0, data1, 100);
    input[2] = data1;
  }
  if (data1 == 51) { //D3#
    Status[0][3] = 1;
    noteOn(0, data1, 100);
    input[3] = data1;
  }
  if (data1 == 52) { //E3
    Status[0][4] = 1;
    noteOn(0, data1, 100);
    input[4] = data1;
  }
  if (data1 == 53) { //F3
    Status[1][0] = 1;
    noteOn(0, data1, 100);
    input[5] = data1;
  }
  if (data1 == 54) { //F3#
    Status[1][1] = 1;
    noteOn(0, data1, 100);
    input[6] = data1;
  }
  if (data1 == 55) { //G3
    Status[1][2] = 1;
    noteOn(0, data1, 100);
    input[7] = data1;
  }
  if (data1 == 56) { //G3#
    Status[1][3] = 1;
    noteOn(0, data1, 100);
    input[8] = data1;
  }
  if (data1 == 57) { //A3
    Status[1][4] = 1;
    noteOn(0, data1, 100);
    input[9] = data1;
  }
  if (data1 == 58) { //A3#
    Status[2][0] = 1;
    noteOn(0, data1, 100);
    input[10] = data1;
  }
  if (data1 == 59) { //B3
    Status[2][1] = 1;
    noteOn(0, data1, 100);
    input[11] = data1;
  }
  if (data1 == 60) { //C4
    Status[2][2] = 1;
    noteOn(0, data1, 100);
    input[12] = data1;
  }
  if (data1 == 61) { //C4#
    Status[2][3] = 1;
    noteOn(0, data1, 100);
    input[13] = data1;
  }
  if (data1 == 62) { //D4
    Status[2][4] = 1;
    noteOn(0, data1, 100);
    input[14] = data1;
  }
  if (data1 == 63) { //D4#
    Status[3][0] = 1;
    noteOn(0, data1, 100);
    input[15] = data1;
  }
  if (data1 == 64) { //E4
    Status[3][1] = 1;
    noteOn(0, data1, 100);
    input[16] = data1;
  }
  if (data1 == 65) { //F4
    Status[3][2] = 1;
    noteOn(0, data1, 100);
    input[17] = data1;
  }
  if (data1 == 66) { //F4#
    Status[3][3] = 1;
    noteOn(0, data1, 100);
    input[18] = data1;
  }
  if (data1 == 67) { //G4
    Status[3][4] = 1;
    noteOn(0, data1, 100);
    input[19] = data1;
  }
  if (data1 == 68) { //G4#
    Status[4][0] = 1;
    noteOn(0, data1, 100);
    input[20] = data1;
  }
  if (data1 == 69) { //A4
    Status[4][1] = 1;
    noteOn(0, data1, 100);
    input[21] = data1;
  }
  if (data1 == 70) { //A4#
    Status[4][2] = 1;
    noteOn(0, data1, 100);
    input[22] = data1;
  }
  if (data1 == 71) { //B4
    Status[4][3] = 1;
    noteOn(0, data1, 100);
    input[23] = data1;
  }
  if (data1 == 72) { //C5
    Status[4][4] = 1;
    noteOn(0, data1, 100);
    input[24] = data1;
  }
}

void MyHandleNoteOff(byte channel, byte pitch, byte velocity) {
  data1 = MIDI.getData1();
  if (data1 == 48) { //C3
    Status[0][0] = 0;
    noteOff(0, data1, 100);
    input[0] = 0;
  }
  if (data1 == 49) { //C3#
    Status[0][1] = 0;
    noteOff(0, data1, 100);
    input[1] = 0;
  }
  if (data1 == 50) { //D3
    Status[0][2] = 0;
    noteOff(0, data1, 100);
    input[2] = 0;
  }
  if (data1 == 51) { //D3#
    Status[0][3] = 0;
    noteOff(0, data1, 100);
    input[3] = 0;
  }
  if (data1 == 52) { //E3
    Status[0][4] = 0;
    noteOff(0, data1, 100);
    input[4] = 0;
  }
  if (data1 == 53) { //F3
    Status[1][0] = 0;
    noteOff(0, data1, 100);
    input[5] = 0;
  }
  if (data1 == 54) { //F3#
    Status[1][1] = 0;
    noteOff(0, data1, 100);
    input[6] = 0;
  }
  if (data1 == 55) { //G3
    Status[1][2] = 0;
    noteOff(0, data1, 100);
    input[7] = 0;
  }
  if (data1 == 56) { //G3#
    Status[1][3] = 0;
    noteOff(0, data1, 100);
    input[8] = 0;
  }
  if (data1 == 57) { //A3
    Status[1][4] = 0;
    noteOff(0, data1, 100);
    input[9] = 0;
  }
  if (data1 == 58) { //A3#
    Status[2][0] = 0;
    noteOff(0, data1, 100);
    input[10] = 0;
  }
  if (data1 == 59) { //B3
    Status[2][1] = 0;
    noteOff(0, data1, 100);
    input[11] = 0;
  }
  if (data1 == 60) { //C4
    Status[2][2] = 0;
    noteOff(0, data1, 100);
    input[12] = 0;
  }
  if (data1 == 61) { //C4#
    Status[2][3] = 0;
    noteOff(0, data1, 100);
    input[13] = 0;
  }
  if (data1 == 62) { //D4
    Status[2][4] = 0;
    noteOff(0, data1, 100);
    input[14] = 0;
  }
  if (data1 == 63) { //D4#
    Status[3][0] = 0;
    noteOff(0, data1, 100);
    input[15] = 0;
  }
  if (data1 == 64) { //E4
    Status[3][1] = 0;
    noteOff(0, data1, 100);
    input[16] = 0;
  }
  if (data1 == 65) { //F4
    Status[3][2] = 0;
    noteOff(0, data1, 100);
    input[17] = 0;
  }
  if (data1 == 66) { //F4#
    Status[3][3] = 0;
    noteOff(0, data1, 100);
    input[18] = 0;
  }
  if (data1 == 67) { //G4
    Status[3][4] = 0;
    noteOff(0, data1, 100);
    input[19] = 0;
  }
  if (data1 == 68) { //G4#
    Status[4][0] = 0;
    noteOff(0, data1, 100);
    input[20] = 0;
  }
  if (data1 == 69) { //A4
    Status[4][1] = 0;
    noteOff(0, data1, 100);
    input[21] = 0;
  }
  if (data1 == 70) { //A4#
    Status[4][2] = 0;
    noteOff(0, data1, 100);
    input[22] = 0;
  }
  if (data1 == 71) { //B4
    Status[4][3] = 0;
    noteOff(0, data1, 100);
    input[23] = 0;
  }
  if (data1 == 72) { //C5
    Status[4][4] = 0;
    noteOff(0, data1, 100);
    input[24] = 0;
  }
}

//Send a MIDI note-on message.  Like Pressing a piano key
void noteOn(byte channel, byte note, byte attack_velocity) {
  talkMIDI( (0x90 | channel), note, attack_velocity);
}

//Send a MIDI note-off message.  Like releasing a piano key
void noteOff(byte channel, byte note, byte release_velocity) {
  talkMIDI( (0x80 | channel), note, release_velocity);
}

//Plays a MIDI note. Doesn't check to see that cmd is greater than 127, or that data values are less than 127
void talkMIDI(byte cmd, byte data1, byte data2) {
  mySerial.write(cmd);
  mySerial.write(data1);
  //Some commands only have one data byte. All cmds less than 0xBn have 2 data bytes
  //(sort of: http://253.ccarh.org/handout/midiprotocol/)
  if ( (cmd & 0xF0) <= 0xB0)
    mySerial.write(data2);
}

void playNote(int midi, int row, int col, int len, bool short_led = false)
{
  int len1, len2;
  if (short_led) {
    len1 = len * 3 / 4;
    len2 = len * 1 / 4;
  } else {
    len1 = len;
    len2 = 0;
  }
  noteOn(0x90, midi, 100);
  digitalWrite(LedR[row], HIGH);
  digitalWrite(LedC[col], LOW);
  delay(len1);
  digitalWrite(LedR[row], LOW);
  digitalWrite(LedC[col], HIGH);
  delay(len2);
  noteOff(0x90, midi, 0);
}

void songlearn (int tune) {
  if (tune == 1) {

    lcd.clear();
    lcd.setCursor(4, 0);
    lcd.print("Learning Song :");// Print a message to the LCD.
    lcd.setCursor(1, 1);
    lcd.print(menuP1);

    //Plays Mary Had a Little Lamb on a loop at 145 BPM

    //Bar 1
    note[0] = 0x40;
    note[1] = 0x3e;
    note[2] = 0x3c;
    note[3] = 0x3e;
    //Bar 2
    note[4] = 0x40;
    note[5] = 0x40;
    note[6] = 0x40;
    //Bar 3
    note[7] = 0x3e;
    note[8] = 0x3e;
    note[9] = 0x3e;
    //Bar 4
    note[10] = 0x40;
    note[11] = 0x43;
    note[12] = 0x43;
    //Bar 5
    note[13] = 0x40;
    note[14] = 0x3e;
    note[15] = 0x3c;
    note[16] = 0x3e;
    //Bar 6
    note[17] = 0x40;
    note[18] = 0x40;
    note[19] = 0x40;
    note[20] = 0x40;
    //Bar 7
    note[21] = 0x3e;
    note[22] = 0x3e;
    note[23] = 0x40;
    note[24] = 0x3e;
    //Bar 8
    note[25] = 0x3c;
    //End song
  }
}

void (*SongSeq[x])() =
{ //Bar 1
  [] { playNote(0x40, 3, 1, 414); } ,//Quarter note: E
  [] { playNote(0x3e, 2, 4, 414); } ,//Quarter note: D
  [] { playNote(0x3c, 2, 2, 414); } ,//Quarter note: C
  [] { playNote(0x3e, 2, 4, 414); } ,//Quarter note: D
  //Bar 2
  [] {playNote(0x40, 3, 1, 414, 1);} , //Quarter note: E
  [] {playNote(0x40, 3, 1, 414, 1); }, //Quarter note: E
  [] {playNote(0x40, 3, 1, 828, 1); }, //Half note: E
  //Bar 3
  []{playNote(0x3e, 2, 4, 414, 1);}, //Quarter note: D
  []{playNote(0x3e, 2, 4, 414, 1);}, //Quarter note: D
  []{playNote(0x3e, 2, 4, 828, 1);}, //Half note: D
  //Bar 4
  []{playNote(0x40, 3, 1, 414);}, //Quarter note: E
  []{playNote(0x43, 3, 4, 414, 1);}, //Quarter note: G
  []{playNote(0x43, 3, 4, 828, 1);}, //Half note: G
  //Bar 5
  []{playNote(0x40, 3, 1, 414);}, //Quarter note: E
  []{playNote(0x3e, 2, 4, 414);}, //Quarter note: D
  []{playNote(0x3c, 2, 2, 414);}, //Quarter note: C
  []{playNote(0x3e, 2, 4, 414);}, //Quarter note: D
  //Bar 6
  []{playNote(0x40, 3, 1, 414, 1);}, //Quarter note: E
  []{playNote(0x40, 3, 1, 414, 1);}, //Quarter note: E
  []{playNote(0x40, 3, 1, 414, 1);}, //Quarter note: E
  []{playNote(0x40, 3, 1, 414, 1);}, //Quarter note: E
  //Bar 7
  []{playNote(0x3e, 2, 4, 414, 1);}, //Quarter note: D
  []{playNote(0x3e, 2, 4, 414, 1);}, //Quarter note: D
  []{playNote(0x40, 3, 1, 414);}, //Quarter note: E
  []{playNote(0x3e, 2, 4, 414);}, //Quarter note: D
  //Bar 8
  []{playNote(0x3c, 2, 2, 1656);}, //Whole note: C
  //End song

};

void showsequence() {
  //Add a new index to the end of the songseq
  SongSeq[largestindex];
  largestindex++;
  //loop through the songseq
  for (int index = 0; index < largestindex; index++) {
    SongSeq[index]();
  }
}

void readsequnce() {
  bool mademistake = false;
  int key;
  for (int index = 0; index < largestindex & mademistake == false; index++) {
    key = waitForButton(5000);
    if (key == -1 | key != note[index]) {
      mademistake = true;
      SongSeq[index]();
      SongSeq[index]();
      state = 2;
    }
  }
}

int waitForButton(int delay)
{
  int keyPressed = -1;
  int check;
  boolean keyBackUp = false;

  currentMillis = millis();      // The number of ms since the program started running
  previousMillis = currentMillis;   // Records the point when we start spinning the loop.

  // Keep spinning the loop until "delay" seconds have passed.
  while (currentMillis - previousMillis < delay & keyBackUp == false)
  {
    // Read the button and record when it has been pushed down.
    for (int i = 0; i < 25 & keyBackUp == false; i++)
    {
      if (input[i] != 0)
      {
        keyPressed = input[i];

        // Show the LED pushed.
        noteOn(0, keyPressed, 100);
        //  digitalWrite(leds[pin], HIGH);

        // It is possible the button is still being pushed.
        // This loop spins until the button is let up.
        while (currentMillis - previousMillis < delay & keyBackUp == false)
        {
          check = input[i];
          if (check == 0)
          {
            keyBackUp = true;
          }
          currentMillis = millis();
        }

        // Turn the LED pushed off.
        noteOff(0, keyPressed, 0);
        // digitalWrite(leds[pin], LOW);

        // See if they took to long.
        if (currentMillis - previousMillis > delay)
        {
          keyPressed = -1; // They took to long to let the button up so they lose.
        }
      }
    }

    currentMillis = millis();

  }

  return keyPressed;
}

```

# Answer
> 1 votes
I notice that nothing in the code you posted calls the `MyHandleNoteOn()` function, which is the only thing that reads MIDI data in the code you posted.

The `waitForButton()` function where you say you're having the problem never does any input or output, it simply checks to see if something else has changed the `input` array. `MyHandleNoteOn()` above does change it.

This leads me to believe that code you haven't posted sets up an interrupt handler that calls `MyHandleNoteOn()` (and probably `MyHandleNodeOff()`). If that doesn't mean anything to you, the main problem here is that the program is a bit beyond your abilities and you need to start learning on something simpler. If it does mean something to you, the problem here is that the program is rather badly written and you need to write something simpler to practice using interrupts and shared memory communication.

Have you written simpler programs before that read MIDI events, do a bit of processing, and play back things based on that? Building a Simon Says game on top of that would be a good learning project.

---
Tags: arduino-mega, programming, sketch, midi
---


# Question
Title: Store data in flash/EEPROM and process it in parallel
I want to store incoming data in flash or EEPROM and then apply FFT or some other method to detect frequency and intensity.

I am taking sound through microphone amplifying it with an LM741 and giving this amplified signal as input to an Arduino and then processing it at the same time.

But the problem is that the time taken in running the code is interfering with the sampling rate. I want to store say 50 inputs in flash and then process these 50 numbers, while at the same time the next set of 50 numbers is being stored, so that I can have data stored at a constant sampling rate.

Also how can I store data continuously? Because if I do this in `loop()` won't it again have time lag due to rest of the code?

I am new to Arduino, so please give details or some link to help me understand.

Thanks.

# Answer
> 2 votes
A common method of overlapping data input with data processing uses double (or multiple) buffering. For example, one of two buffers is processed in the foreground (that is, in the `loop()` routine) while another buffer is filled in background (via interrupt handlers). Each time a buffer fills, the usage of the two buffers swaps: that which was being processed now refills, while the recently-filled buffer gets processed. To make this work, buffer processing must take less time than buffer filling.

For recording conversion times, because free-running ADC conversions each take the same amount of time, you can just save fill-start and fill-end times with each buffer, and interpolate to find out reading times.

If you plan to process audio data at near-normal speeds, it's likely most Arduinos won't be fast enough to keep up. However, using an Arduino Due probably is feasible. The Due is based on an ARM Cortex M3 processor with 72 MHz operating frequency, 32-bit arithmetic, large RAM (for an Arduino), etc.

An alternative method of processing audio data is to use a frequency analysis chip. Here is a low-end example: The MSGEQ7 Graphic Equalizer Display Filter is about $5 in an 8-pin DIP package from sparkfun.com. Apparently, it continuously measures peak spectral intensity in each of seven frequency bands, and can read the peaks out perhaps a thousand times per second. Audio goes in on the "Audio in" pin. A Reset pin resets an output-multiplexor counter to zero. Each time after you clock a strobe line, a band's reading is presented as an analog voltage on a "DC out" output line; the band's peak reading is decayed about 10%; and the multiplexor advances one band upward in frequency, rolling over from highest to lowest every seven strobes.

# Answer
> 1 votes
> What I want to do is store incoming data from in flash or eeprom

No, for your application you absolutely do not want to do that. You want to use RAM instead.

The Arduino has three kinds of memory:

1. Bytes in RAM (also called SRAM) can be written an unlimited times and written very quickly. RAM is designed for short-term storage of information while a sketch is running. The contents vanish when the Arduino is turned off, but this isn't a problem for you unless you need to process previously read information later on after the Arduino is turned back on. An Arduino Uno has 2048 bytes of RAM and all your C/C++ variables must fit in that.
2. An EEPROM byte can be written around 100,000 times; writing it is much, much slower than writing a RAM location. This makes it very bad for doing intensive processing, as opposed to, e.g., just storing configuration variables that are rarely read. EEPROM is designed for storage of information across power cycles of the microcontroller; unlike RAM, previously written data are still there to be read when the Arduino is powered on. An Arduino Uno has 1024 bytes of EEPROM; this is only used when your code or library code explicitly requests data be written to or read from it.
3. Each block of flash memory can be written around 10,000 times; writing it is much slower than RAM, though it can be read very quickly. Flash storage is designed for storing programs, not data; it's the memory from which instructions are read, though you can with care store "constant" data in it too. It's only changed when you upload a sketch via USB.\* An Arduino Uno has 32768 bytes of Flash memory and your program and any constants you store in Flash must fit in it.

* Not technically true, but if you know how to use Flash for runtime data storage, this answer isn't providing you any useful information. :-)

---
Tags: arduino-mega, eeprom, flash
---


# Question
Title: Arduino Uno - ESP 8266: sending AT commands via Code
I bought a ESP 8266 & I am able to send AT commands and receive response via serial monitor when I upload a empty sketch. I changed the baud rate from 115200 to 9600 by using `AT+CIOBAUD=9600` and am able to run AT commands at 9600 baud rate.

**Empty Sketch:**

```
void setup()
{

}
void loop()
{

}

```

Here is how my circuit looks:

**Problem**

The problem is when I create a custom sketch to run AT commands it doesn't work. Here is how my sketch looks:

```
#include <SoftwareSerial.h>
SoftwareSerial esp8266(0,1); //RX,TX

void setup()
{

  Serial.begin(9600);
  esp8266.begin(9600);

  Serial.println("Run AT Command");

   esp8266.print("AT\r\n");

}

void loop(){
   String response = "";
   while(esp8266.available())     {
        char c = esp8266.read();
        response+=c;
        Serial.print(c);
      }

      if(response != ""){
        Serial.println(response);
      }

}

```

ESP8266 is receiving 3.3V but I have read TX and RX sends 5V, and they also need to be 3.3V. Don't know if thats what is causing it, but I am able to run AT commands on empty sketch, so this is a bit weird.

> UPDATE:

**My sketch is:**

```
#include <SoftwareSerial.h>
SoftwareSerial esp8266(2, 3); //RX,TX

void setup()
{

  Serial.begin(9600);
  esp8266.begin(9600);

  esp8266.print("AT\r\n");

}

void loop() {
  String response = "";
  while (esp8266.available())     {
    char c = esp8266.read();
    response += c;
  }

    if (response != "") {
      Serial.println("Response: " + response);
    }

}

```

**Serial Monitor shows this:**

```
Response: A
Response: T

OK
Response:

```

**OUTPUT when I run AT+CIFSR command:**

```
Response: A
Response: T+CIFSR

Response:
+CIFSR:APIP
Response: ,"192.168.4.1
Response: "
+CIFSR:APMA
Response: C,"5e:cf:7f:80
Response: :f7:74"

OK

```

**Question now is:** How do I store the string being returned from the esp8266. I thought my response string was suppose to store the "OK" but that did not happen.

# Answer
> 2 votes
Of course you cannot use the same pins for both hardware and software serial, but that part seems to have been solved in comments.

> Question now is: How do I store the string being returned from the esp8266. I thought my response string was suppose to store the "OK" but that did not happen.

```
 while (esp8266.available())     {
    char c = esp8266.read();
    response += c;
 }

```

This will only read as long as characters are available, but the ATmega is able to run this loop much more quickly than characters are received, so unless the entire message was previously transferred it will likely only get a character or two before the receive buffer is found (temporarily) empty and it terminates.

You should instead read until a terminating condition is found, such as a newline character. For safety you might also put in a "give up and try again" timeout, but make it long.

Some would try to solve this problem by inserting short delays before trying to read, but that is unwise - depending on delays creates unreliability as the necessary delay can easily change due to conditions that may on the surface seem to have little relevance, for example the esp866 might respond more slowly if it is seeing a lot of broadcast traffic on a network, or if the firmware version changes.

# Answer
> 2 votes
There is another technique that you can use, instead of hanging around waiting for more characters from the ESP8266. Your code starts:

```
void loop() {
    String response = "";
    while (esp8266.available())     {
        char c = esp8266.read();
        response += c;
    } // while

```

This has the effect of creating a new `String` every time `loop()` is entered, and you accumulate the data from the ESP8266 in that - but it's lost if you leave `loop()`. So it may be better to do it differently:

```
const char EOL = '\n'; // End of line
String response = ""; // Create String once, outside loop()

void loop() {
    char c = '\0'; // Initialise to NUL
    while (esp8266.available() && c!=EOL) { // Wait for End of Line
        c = esp8266.read();
        response += c;
    } // while
    if (c==EOL) {
        Serial.print("Response: "); // Don't use '+' if you can help it!!!
        Serial.println(response);
        // Do other processing
        response = ""; // Clear response for next string
    } // if

```

This has three effects:

1. It keeps an incomplete `response` between calls to `loop()`.
2. It only processes `response` once the end-of-line is read.
3. It keeps `loop()` running nicely (important on other Arduino), rather than hanging around

# Answer
> 1 votes
Just check if this answer helps. Here is the thing, For AT commands from serial monitor, RX or arduino should be connected to RX of ESP and TX of arduino to TX of ESP. That is the reason you are able to enter AT commands with your circuit when empty program is uploaded.

Now for arduino to communicate with ESP using program, you have to connect RX of arduino to TX of ESP and TX of Arduino to RX of ESP. In your case if using software serial 2 & 3, then pin2 to TX of Esp and pin3 to RX of ESP.

To read "OK" from ESP, try below code:

```
if(esp8266.find("OK"))

```

Also you may try this code to read:

```
esp8266.find("pin="); //this acts like a pointer.
int value = esp8266.read(); //returns ASCII Code. this will read value which comes after pin=

```

Refer : https://www.arduino.cc/en/Serial/read

---
Tags: arduino-uno, esp8266
---


# Question
Title: Using Lego temperature sensor with Arduino
I have Arduino mega and Lego temperature sensor which I would like to connect to the Arduino. I'm trying to use a I2C connection between them, with no luck. I connected the sensor and Arduino referring to the picture below: I'm using the Wire library for transmitting data. This is my code currently:

```
#include < Wire.h >
byte ADDRESS=0x98;
byte CONFIG=0x01;
void setup(){
  Serial.begin(9600);
  Wire.begin();
  Wire.beginTransmission(ADDRESS);
  Wire.write(CONFIG);
  Wire.endTransmission();
  delay(100);
}
void loop(){
  Wire.beginTransmission(ADDRESS);
  Wire.write(CONFIG);
 Wire.endTransmission();
  Wire.requestFrom(ADDRESS,2);
  delay(100);
  int avail=Wire.available();
  Serial.println(avail);
  delay(100);
}

```

I found the config and address values from RobotC drivers for the same sensor. But all I get is zeros. Is there any way i could check for a defect sensor? Is my code correct?

# Answer
I managed to get it work with the following code:

```
float getTemp(){
    #define ADDRESS 0x4C
    #define CONFIG 0x00
    float temp;
    Wire.beginTransmission(ADDRESS);
    Wire.write(CONFIG);
    Wire.endTransmission();
    delay(50);
    Wire.requestFrom(ADDRESS,2);
    temp=Wire.read();
    if(Wire.read()==128){
        temp+=0.5;
    }
    return temp;
}

```

And connect the green wire to 3.3V, not to the 5V.
> 1 votes

---
Tags: arduino-mega, i2c
---


title: Capacitor Questions

text:
# Question
Title: Capacitor Questions
I've designed a board (HAT) that uses the ATmega328P microcontroller, and I think I might have made some mistakes in the board design. The design is most like the Arduino Pro mini, but with a 5A dual channel H-bridge, running at 3.3V 16MHz, and using the Raspberry Pi as the power source.

My Board: https://github.com/cescalemodels/BaseStationHAT/tree/master/Hardware

Arduino Pro Mini: https://www.arduino.cc/en/uploads/Main/Arduino-Pro-Mini-schematic.pdf

1) Do I have to have C3? I think it's for power stability and needs to be put next to the microcontroller, but I'm really not sure and want to eliminate it as a possibility as to which part made the board fail.

2) Do I need C2 if I'm not using the DTR Pin?

3) I assume that I don't need C13 and C10 because I'm getting power from the Pi, but can someone confirm?

If it helps, when I boot the raspberry pi, the serial port comes up, but I am totally incapable of communicating. Are there other components that I'm missing?

# Answer
> 3 votes
Every active chip should have adequate decoupling. That is the point of C3, to provide decoupling for the MCU. It is required.

While you don't need capacitors on the output of a non-existent regulator you do need a reservoir capacitor on the power input to your board. 10uF should be adequate.

No, you don't need the DTR capacitor if DTR is not connected to anything.

All that aside, there are two fundamental flaws I can see:

* The raspberry pi can only provide something like 50mA on the 3.3v supply. (Or originally anyway, it may have improved with newer versions)
* The ATMega chip cannot run reliability at 16MHz from just 3.3v. 10MHz is your top limit IIRC.

---
Tags: atmega328, uart, raspberrypi
---


title: Arduino pins always reading HIGH (1)

text:
# Question
Title: Arduino pins always reading HIGH (1)
I have tried changing pinModes and I/O declarations but still getting erratic or unexpected pin readings (HIGH), even though, I think, that I have set them LOW during setup. I read elsewhere that this is not uncommon, but I have not found a similar situation or a suitable explanation/solution. I can only believe that it is a basic misunderstanding (still learning). Thanks for any support. By the way, I had deleted the use of the keypad for trial purposes. My code is below:

```
//////////////////////////// Initialize & Includes //////////////////////////
#include "SIM900.h"
#include "sms.h"
#include "Keypad.h"
#include <GSM.h>
SMSGSM sms;
boolean pir_SensorPin = 2;
int led_OutPin = 11; // green
int alarm_OutPin = 12; // red
int alarm_count = 0;
boolean switchPin = 4; // alarm on test
boolean keypadPIN;
int z = 0;
int i = 0;
int waitTime = 5000;

//////////////////////////// Setup Keypad //////////////////////////
const byte ROWS = 4; // four rows
const byte COLS = 4; // four columns
char keys[ROWS][COLS] =
{
  {
    '1', '2', '3', 'A'
  }
  ,
  {
    '4', '5', '6', 'B'
  }
  ,
  {
    '7', '8', '9', 'C'
  }
  ,
  {
    '*', '0', '#', 'D'
  }
};
byte rowPins[ROWS] = {
  6, 7, A2, A3 // row pin# on keypad to Arduino pin#, ie Row Pin #1 goes to Arduino Pin #6, etc.
}; // connect to the row pinouts of the keypad
byte colPins[COLS] = {
  3, A0, A1, A4
}; // connect to the column pinouts of the keypad
Keypad keypad = Keypad(makeKeymap(keys), rowPins, colPins, ROWS, COLS );
const char PIN[5] = {
  '9', '6', '7', '9', '#'
}; // PIN number
char key_input[5] = {
  0, 0, 0, 0, 0
}; // used for comparison

//////////////////////////////// Setup ///////////////////////////////////
void setup() {
  Serial.begin (9600);  // Establish Serial connection;
  pinMode (switchPin, INPUT);       // Set pinMode.
  pinMode (led_OutPin, OUTPUT);     // Set pinMode.
  pinMode (alarm_OutPin, OUTPUT);   // Set pinMode.
  pinMode (pir_SensorPin, INPUT);   // Set pinMode.
  digitalWrite (led_OutPin, LOW);   // Set output pins to LOW for start.
  digitalWrite (alarm_OutPin, LOW); // Set output pins to LOW for start.
  digitalWrite (switchPin, LOW);
  digitalWrite (pir_SensorPin, LOW);
  Serial.println ("Studio Alarm starting up."); // Serial message that GSM shield is starting up
  if (gsm.begin(4800)) {    // Set GSM shield to recommended 4800 baud rate.
    Serial.println ("Status = Network READY");
    digitalWrite (led_OutPin, HIGH);
  }
  //  attachInterrupt (digitalPinToInterrupt (2), trigger, CHANGE); // PIR as interrupt
  Serial.println ("System Ready");

}

//////////////////////////// State Setup //////////////////////////
enum STATE {
  armed, // system acknowledges trigger
  unarmed, // system unarmed via keypad entry setting keypadPIN = LOW
  justActivated, // PIR-triggered
  alarm // confirm system unarmed then goto unarmed state else start alarm
};

STATE systemState = unarmed;
long timeGettingArmed;

/////////////////////////// Trigger ///////////////////////////////
//void trigger() {
//  systemState = alarm;

//////////////////////////// State Machine //////////////////////////
void loop() {
  check(); Serial.print ("switchPin = "); Serial.println (switchPin);
  Serial.print ("pir_SensorPin ="); Serial.println (pir_SensorPin);
  switch (systemState) {
    case armed:
      Serial.println ("armed");
      if (digitalRead (pir_SensorPin == HIGH)) {
        systemState = alarm;
      } else if (digitalRead (keypadPIN == LOW)) {
        systemState = unarmed;
      }
      break;
    case unarmed:
      if (digitalRead (pir_SensorPin == HIGH)) {
        Serial.println ("unarmed");
        timeGettingArmed = millis(); // Or just do a delay here.
        systemState = justActivated;
      }
      break;
    case justActivated:
      Serial.println ("juatActivated");
      if (timeGettingArmed + waitTime < millis()) {
        systemState = armed;
      }
      break;
    case alarm:
      Serial.println ("alarm");
      if (digitalRead (keypadPIN == LOW)) {
        systemState = unarmed;
      } else {
        beep();
      }
      break;
  }
}

//////////////////////////// Alarm //////////////////////////
void beep() {
  Serial.println("at beep");
  // (sms.SendSMS("**********", "*** Motion Detected in Studio! ***"));
  Serial.println ("MOTION detected: SMS Sent");
  for (alarm_count = 0; alarm_count <= 5; alarm_count++) { // Cycle outputs if triggered
    digitalWrite (alarm_OutPin, HIGH); delay (1000); // On/Off/On/Off/Off
    digitalWrite (alarm_OutPin, LOW); delay (500);
    digitalWrite (led_OutPin, HIGH); // delay (1000);
    Serial.println (alarm_count);
  }
  systemState = armed;
}

void check() {
  if (digitalRead (switchPin == HIGH)) { // manual test in lieu of keypad attached
    (keypadPIN = LOW); // unarmed
  }
  else {
    (keypadPIN = HIGH); // armed
  }
  Serial.print ("switchPin = "); Serial.println (switchPin);
  Serial.print ("keypadPIN = "); Serial.println (keypadPIN);
}

Serial output shows:
pir_SensorPin =1
switchPin = 1
keypadPIN = 1
switchPin = 1

```

# Answer
Your code to read from the pins is incorrect. You write

```
if (digitalRead (pir_SensorPin == HIGH)) {

```

However, this compares `pir_SensorPin == HIGH`, (which is `2 == HIGH`), producing a true or false that it then passes as the argument to `digitalRead`, which will try to interpret that as a pin number. Fix your parentheses:

```
if (digitalRead(pir_SensorPin) == HIGH)  {

```

(This problem occurs throughout your code.)

You also are writing an input pin in your setup, which is not necessarily wrong (it is one way of enabling or disabling the pullup resistor), but you should understand why you're doing it:

```
pinMode (pir_SensorPin, INPUT);   // Set pinMode.
...
digitalWrite (pir_SensorPin, LOW);

```
> 3 votes

---
Tags: arduino-uno
---


title: Life span of arduino

text:
# Question
Title: Life span of arduino
We are students of Pragati Engineering College -AP. We are currently working on Automatic Street Light project selected in Smart India Hackathon 2017 under ministry of steel. For this project We are using Arduino nano to control street lights in industries. Now we are requiring some general following information about arduino nano.

What is the life span of Arduino nano? We need a micro-controller with on analog input pin to read analog voltage and four digital pins for output. The program that we are dumping include serial communication with Java UI in PC. The program occupies 6750 bytes, 318 bytes for global variables and 1730 bytes for local variables. We would like to know which arduino board is best suitable for our project?

# Answer
> 1 votes
Atmel chips (the ones used in the Arduino) have been used in all sorts of industrial appilications way before Arduino came along. Same for other micro controllers like the still popular 8051. What you want to focus on might be the enclosure, seal it against the outside.

Rather than using a (chunky) pre-manufactured Arduino board, you'll have to pick the right chip for your application and design a board around it. http://www.atmel.com/products/microcontrollers/avr/

# Answer
> 1 votes
> What is the life span of Arduino nano ?

Many years.

Flash memory can degrade with time and the program can become corrupted or lost - however:

> Reliability Qualification results show that the projected data retention failure rate is much less than 1 PPM over 20 years at 85°C or 100 years at 25°C.

Wet electrolytic capacitors dry out over time. When resurrecting old hardware the first thing you do is replace all the electrolytic capacitors. Depending on how much you de-rate them they could last a few years, or tens of years, before they need replacing. If possible avoid them and use MLCC and tantalum instead since they never dry out.

The biggest problem of any kind of industrial installation is that of the environment. Corrosion from airborne contaminates (water, etc) will destroy the PCB (oxidise the copper of the tracks, etc) long before the components have worn out. Proper sealing, and even "potting" in extreme environments, is essential for longevity.

Another important thing to remember is to factor in a certain number of failures over the intended lifetime of the product. If you find you will be needing to replace portions of a unit on a semi-regular basis then make those portions easy to replace. For instance, it may be more cost effective to routinely replace a board after 5 years rather than have to replace the entire unit every 8 years because the board that has failed is impossible to replace (e.g., it's potted).

As others have mentioned you shouldn't be using an Arduino of any form in a product. Instead you will be designing (or paying someone to design) a dedicated PCB. During that design phase extra steps can be taken to make the board more rugged - such as wider tracks and thicker copper that will take longer to corrode; increased clearances that will take longer for corroded copper to bridge; components chosen to have a suitable MTBF, etc.

Many components have a "service life" or "lifetime" quoted. This is especially important for components such as electrolytic capacitors. For instance, the EEUFR1C471 from Panasonic (to pick one at random) is quoted as 6000 hours at 105°C. 105°C is the maximum temperature you can run it at, so the quoted service life is a *minimum* at *worst case* parameters. 6000 hours is, of course, just 250 days (about 8 months or so) - but of course that is *worst case*, and the *minimum guaranteed* time (they *guarantee* that it will run for *at least* 6000 hours at 105°C). Run it at a lower temperature and you get longer life out of it.

# Answer
> 0 votes
> What is the life span of Arduino nano ?

Electronics doesn't really "die". Treated well, it should last for years. I have a RFID security system that I made in 2011 (six years ago, as I write this) and it is still working perfectly.

> We would like to know which arduino board is best suitable for our project ?

These sorts of questions are hard to answer. What is "best"? Price? Size? Weight? Ease of use?

# Answer
> 0 votes
> What is the life span of Arduino nano ?

the answer is use dependent. Just like you don't know for sure what's the life span of a particular individual, it is hard to know the life span of a product in a particular application, as it depends on the environment, design, and operations of that application.

> We would like to know which arduino board is best suitable for our project ?

hard to tell, and likely none. street lighting is exposed all sorts of elements, from high / low temperatures to moistures and lightening for example, and demands high reliability in all conditions, particularly in failure. Arduino wouldn't be great in that environment.

if you have to go down that path, develop the code in arduino and burn the hex into bare chips so you have the choice of the chip and other components going into your application.

---
Tags: serial
---


title: Design vehicle tracking device

text:
# Question
Title: Design vehicle tracking device
I want to create an Arduino based vehicle tracking device which will be moved into a production board without Arduino later. Right now I have a few questions:

* What GPS module should I use for a best result (little time to fix from a cold start and high accuracy locations)? It will be good if support GLONASS. I want to detect when the car is turning (using HMC5983). I've bought Ublox NEO-6M GPS module and tested it into the car, but it cannot find a location.
* What MCU I should buy? I also want to communicate with OBD II port of vehicle over the CAN protocol (using MCP2551 + MCP2515). For now i choose ATMega328.
* How to power all elements ?

PS: Data from the vehicle and the GPS locations will be send over GPRS with SIM800l module.

Cheers

# Answer
There are some SIMCOM modules with GPRS + GPS, for example: SIM968

In addition to GPS, it also supports GLONASS/Galileo/QZSS.

As for the MCU, you will need something more powerful than ATMega328, because 2KB RAM is not enough for multi-threading + GPS code + GSM/GPRS code + CAN + etc. Also it hasn't CAN peripheral. You will need MCU with ARM core. From Arduino line, Arduino Due looks suitable: has 96KB RAM, multiple HW serials, CAN. There is also compatible CAN library here. Also worth looking on STM32F103 (or STM32F407 with Cortex M4) which also can used be with Arduino IDE with some extra effort (STM32 MCUs usually more cost effective than Atmel counterparts, and have higher performance).
> 1 votes

---
Tags: arduino-uno, gsm, atmega328, gps, can-bus
---


# Question
Title: (SOLVED) Fast HW check: (18 digital + 4 analog to I2C ) Arduino Mini Pro + MCP23017 or STM32?
**Arduino Mini Pro+MCP23017** or **STM32**

I want make device, which reads 17 digital buttons and 4 analog, process it somehow and send the result to I2C bus. Also there is a LED to be managed. I may want to attach some wireless too later, but I am not really sure, if I woud do it (which would need 5-6 mor digital pins). I need to update the firmware often, as it is under heavy developement just now. I should make the PCB as soon as possible, but programming can wait some time.

The PCB would have buttons and analogs on it (and `MCP` in the arduino case). Also lot of connectors, like I2C, programming interface and some power regulators, the LED (or maybe more of them, if there was few free pins, but it is not mandatory). The processor will be connected via wires for space reasons (and maintainability and the board may be redesined later), so only long row of soldering pads on PCB for it.

**Main decision:** If I opt to Arduino, then `MCP` will be part of the PCB and connected to `I2C` bus, if I use STM32, no `MPC` will be present and buttons would go directly to output connector.

Making the HW is no problem for me, the logic inside is also easy (basically read all inputs, normalize analogs to some range, make some simple tests and if desired, send result over I2C. Reply to some simple I2C too.)

I have a lot of Arduino Mini Pro, but it is few legs short for the task, so I would use MCP23017 expander for 16 of that digital buttons.

I also got some these STM32 https://www.aliexpress.com/item/STM32F103C8T6-ARM-STM32-Minimum-System-Development-Board-Module-For-Arduino/32279776568.html but did not open the package yet. Anyway I want to learn to use them "sometimes soon".

Maybe it is just the kind of starter project, which I would like to do.

Now I am just not sure about the number of available pins on the STM32, on first look it have more pins, but each description I found yet states too much details about additional functions, but I got confused about the basics here. So my question is:

**Can mentioned STM be easilly programed as Arduino, manage I2C communication, and still have comfortable 18+4 I/O pins free? And 23+4 I/O free?**

# Answer
> 1 votes
> Can mentioned STM be easilly programed as Arduino, manage I2C communication, and still have comfortable 18+4 I/O pins free? And 23+4 I/O free?

it can be programed as Arduino, manage I2C communication, and still have 18+4 I/O pins free or 23+4 I/O free.

it is only knowable to the person programming it whether it can be done easily or comfortably.

---
Tags: i2c, pins, hardware
---


# Question
Title: Gravity fan does not work when powered by 3.3V ESP8266
The gravity fan has 3 pins. I connected one pin to the ground, one pin to the digital pin numbered 2 on ESP8266. I uploaded this code but the fan doesn't run at all. The fan supposedly uses a 5V power supply but the ESP8266 only supplies 3.3V. Could this be the problem?

```
void setup() {
  pinMode(2, OUTPUT);
}

void loop() {
  digitalWrite(2, HIGH);
}

```

# Answer
The ESP can only supply 12 milliamperes of current. The fan most likely uses a whole lot more. You could for example uses a transistor to turn on the fan.
> 1 votes

---
Tags: esp8266
---


# Question
Title: ESP8266 + Slack (ssl->need_bytes=16432 > 6859)
I'm trying to connect an Adafruit Huzzah ESP8266 with Slack.

I'm facing an issue with the connection I'd like some help or tips on. I'm able to get a connection *sometimes*, but sometimes during the initial step where I'm making the first connection, I get errors and it completely fails, repeating the connect/disconnect over and over again.

The error I get is usually this:

```
ssl->need_bytes=16432 > 6859

```

# My Troubleshooting So Far

As per this github issue: https://github.com/esp8266/Arduino/issues/1375

My understanding is that the error is caused by Slack's SSL certificate being too large. This makes sense, but sometimes my code (see below) actually works which is why I'm confused.

When it *does work*, it usually fails a couple times at first, before maintaining a consistent ping with Slack. At that point, it works as expected, and I can send commands from Slack to the board without fail.

Does anyone have an idea why this sometimes works, and sometimes doesn't?

I'm assuming it has something to do with the SSL certificate size being too large, but if that was the case why wouldn't it fail each time, but work sometimes?

Any help is greatly appreciated.

---

# Errors in Serial Monitor

Here's what I see in the Serial Monitor log:

```
⸮scandone
f r0, scandone
f r0, scandone
state: 0 -> 2 (b0)
state: 2 -> 3 (0)
state: 3 -> 5 (10)
add 0
aid 7
cnt

connected with 2WIRE952, channel 3
dhcp client start...
ip:192.168.1.73,mask:255.255.255.0,gw:192.168.1.254

Waiting for time sync
please start sntp first !
.please start sntp first !
.Sun Apr 16 06:57:35 2017

Time is synced
ssl->need_bytes=16432 > 6859
WebSocket Host=mpmulti-4pcb.slack-msgs.com Path=/websocket/Z5ZDermv9h2Q7HL88ukG5ddIvY--zrBAVCN4423KOy5t_6wN3AW859grAYCYr6L-0l0leeXA3AhlO1VmIxcCopS1pJ-IkrVOdmel50tgcA7hBJwEIkpI-biYnraTFc88K4F6wqL3TE_gi1jU0SJHhR6_aD5435yE8FRALEflTkY=
[WebSocket] Connected to: /websocket/Z5ZDermv9h2Q7HL88ukG5ddIvY--zrBAVCN4423KOy5t_6wN3AW859grAYCYr6L-0l0leeXA3AhlO1VmIxcCopS1pJ-IkrVOdmel50tgcA7hBJwEIkpI-biYnraTFc88K4F6wqL3TE_gi1jU0SJHhR6_aD5435yE8FRALEflTkY=
[WebSocket] Disconnected :-(
ssl->need_bytes=16432 > 6859
WebSocket Host=mpmulti-eavp.slack-msgs.com Path=/websocket/HjuUTJUL4ghmBCthwdFxOYNWD0wGjWbCgQZwnum546F5Nj8rrJ7LJgeyVOLqSv9sBHtkZBrCBLyxdM2oMB85-GXGwtIgg9anVYFL66vMB8yEN9Xout7OMmqlEewZsL7n2vqJyvx_qAnQ9M8UwOnZwETkNYJ51XrUvR6EjIAvAQE=
[WebSocket] Connected to: /websocket/HjuUTJUL4ghmBCthwdFxOYNWD0wGjWbCgQZwnum546F5Nj8rrJ7LJgeyVOLqSv9sBHtkZBrCBLyxdM2oMB85-GXGwtIgg9anVYFL66vMB8yEN9Xout7OMmqlEewZsL7n2vqJyvx_qAnQ9M8UwOnZwETkNYJ51XrUvR6EjIAvAQE=
[WebSocket] Disconnected :-(
ssl->need_bytes=8496 > 6859

```

# My Sketch Code

The Sketch file I'm compiling using the Arduino IDE.
**Note:** be sure to update Wifi + Slack Bot Token if testing 8-)

```
#include <Arduino.h>

#include <ESP8266WiFi.h>
#include <time.h>
#include <ESP8266WiFiMulti.h>
#include <ESP8266HTTPClient.h>

#include <WebSocketsClient.h>
#include <ArduinoJson.h>

#define SLACK_SSL_FINGERPRINT "AC 95 5A 58 B8 4E 0B CD B3 97 D2 88 68 F5 CA C1 0A 81 E3 6E" // If Slack changes their SSL fingerprint, you would need to update this

#define WIFI_SSID       ""
#define WIFI_PASSWORD   ""

String SLACK_BOT_TOKEN = ""; // Get token by creating new bot integration at https://my.slack.com/services/new/bot

#define WORD_SEPERATORS "., \"'()[]<>;:-+&?!\n\t"

ESP8266WiFiMulti WiFiMulti;
WebSocketsClient webSocket;

long nextCmdId = 1;
bool connected = false;

//Timezone Settings
const int timezone = 9;
const int dst = 0; //daylight savings

/**
  Sends a ping message to Slack. Call this function immediately after establishing
  the WebSocket connection, and then every 5 seconds to keep the connection alive.
*/
void sendPing() {
  DynamicJsonBuffer jsonBuffer;
  JsonObject& root = jsonBuffer.createObject();
  root["type"] = "ping";
  root["id"] = nextCmdId++;
  String json;
  root.printTo(json);
  webSocket.sendTXT(json);
}

/**
  Looks for color names in the incoming slack messages and
  animates the ring accordingly. You can include several
  colors in a single message, e.g. `red blue zebra black yellow rainbow`
*/
void processSlackMessage(char *payload) {
  char *nextWord = NULL;
  bool zebra = false;
  for (nextWord = strtok(payload, WORD_SEPERATORS); nextWord; nextWord = strtok(NULL, WORD_SEPERATORS)) {
    if (strcasecmp(nextWord, "red") == 0) {
      Serial.printf("Yay! Its red.");
    }

  }
}

/**
  Called on each web socket event. Handles disconnection, and also
  incoming messages from slack.
*/
void webSocketEvent(WStype_t type, uint8_t *payload, size_t len) {
  switch (type) {
    case WStype_DISCONNECTED:
      Serial.printf("[WebSocket] Disconnected :-( \n");
      connected = false;
      break;

    case WStype_CONNECTED:
      Serial.printf("[WebSocket] Connected to: %s\n", payload);
      sendPing();
      break;

    case WStype_TEXT:
      Serial.printf("[WebSocket] Message: %s\n", payload);
      processSlackMessage((char*)payload);
      break;
  }
}

/**
  Establishes a bot connection to Slack:
  1. Performs a REST call to get the WebSocket URL
  2. Conencts the WebSocket
  Returns true if the connection was established successfully.
*/
bool connectToSlack() {
  // Step 1: Find WebSocket address via RTM API (https://api.slack.com/methods/rtm.start)
  HTTPClient http;
  http.begin("https://slack.com/api/rtm.start?token=" + SLACK_BOT_TOKEN, SLACK_SSL_FINGERPRINT);
  int httpCode = http.GET();

  if (httpCode != HTTP_CODE_OK) {
    Serial.printf("HTTP GET failed with code %d\n", httpCode);
    return false;
  }

  WiFiClient *client = http.getStreamPtr();
  client->find("wss:\\/\\/");
  String host = client->readStringUntil('\\');
  String path = client->readStringUntil('"');
  path.replace("\\/", "/");

  // Step 2: Open WebSocket connection and register event handler
  Serial.println("WebSocket Host=" + host + " Path=" + path);
  webSocket.beginSSL(host, 443, path, "", "");
  webSocket.onEvent(webSocketEvent);
  return true;
}

void setup() {
  Serial.begin(115200);
  Serial.setDebugOutput(true);

  WiFiMulti.addAP(WIFI_SSID, WIFI_PASSWORD);
  while (WiFiMulti.run() != WL_CONNECTED) {
    delay(500);
  }

  //setup network time protocol (ntp)
  configTime(timezone * 3600, dst, "pool.ntp.org", "time.nist.gov"); //configtime is esp8266 function

  Serial.println("\nWaiting for time sync");
  while (!time(nullptr)) {
    Serial.print(".");
    delay(1000);
  }
  Serial.println("Time is synced");

  delay(500);
}

unsigned long lastPing = 0;

/**
  Sends a ping every 5 seconds, and handles reconnections
*/
void loop() {
  webSocket.loop();

  if (connected) {
    // Send ping every 5 seconds, to keep the connection alive
    if (millis() - lastPing > 5000) {
      sendPing();
      lastPing = millis();
    }
  } else {
    // Try to connect / reconnect to slack
    connected = connectToSlack();
    if (!connected) {
      delay(500);
    }
  }
}

```

# Answer
replace `rtm.start` with `rtm.connect` as per April 2017 Recent Updates log
> 2 votes

---
Tags: esp8266, web
---


# Question
Title: What if I detach AVR micro controller from the Arduino Board after uploading program?
What if I detach AVR microcontroller from the Arduino Board after uploading program? Does the microcontroller still have the program on it? Or the program will be deleted?

On the board where does Arduino store hex file?

I am very beginner in Embedded Programming. I am learning about microcontroller and Arduino. While learning about programming Arduino-Uno I got these question in my mind.

# Answer
The AVR µC got a flash memory that can store the code loaded in. That mean you can load the code with the arduino board, detach the avr and put it on another circuit. If the µC is powered well, it will behave just like the arduino.

Don't forget to set the /reset pin to high, if you do, the µC will be stuck to the 1st line of code ;)
> 1 votes

---
Tags: avr
---


# Question
Title: Using a potentiometer to control number of lit pixels on an NeoPixel strip
I'm working on controlling an Adafruit NeoPixel strip with an Arduino and a potentiometer. Specifically, I'm trying to use the potentiometer to control how many pixels are lit up on the strip. As I turn the potentiometer "up" (i.e., increasing the value), the number of lit-up pixels increases.

However, if I try to turn the potentiometer the other way and decrease the number of lit-up pixels, then the strip will stay at whatever the last value was.

I have a method below that's called during the 'void loop()' method that read in the potentiometer data:

```
void readAndSendPotentiometerDataIfChanged(void) {
 //Read data from analog pin 2, and scale it
 int newPotentiometerValue = analogRead(A2) / 5.68;
  if (newPotentiometerValue != lastPotentiometerValue) {
      Serial.print("POT. value");
      Serial.print(newPotentiometerValue);
      lastPotentiometerValue = newPotentiometerValue;

      /* The value of "colorVal" is determined by a switch, and seems to be
         working properly */
      if (colorVal == "RED") {
        //If the value is 0, we want to clear the pixel values to white
        if (lastPotentiometerValue == 0) {
          clearPixels();
        } else {
          colorWipe(strip.Color(255, 0, 0)); // Red
        }
      } else if (colorVal == "BLUE") {
        if (lastPotentiometerValue == 0) {
          clearPixels();
        } else {
          colorWipe(strip.Color(0, 0, 255)); // Blue
        }
      }
   }
}

```

The method below will clear out all 180 pixels on my strip to no color (clear).

```
void clearPixels() {
   uint16_t clearColor = (127, 127, 127);
   strip.setPixelColor(180, clearColor);
   strip.show();
}

```

Here's where the pixels on the strip get set...I'm sure the problem is in the for loop below, but I haven't been able to come up with a better way to set the pixels on the strip and then turn them on:

```
void colorWipe(uint32_t c) {

  /* Use the value of 'lastPotentiometerValue' to determine how many pixels
   on the strip should be lit up */
  for(uint16_t i=0; i<lastPotentiometerValue; i++) {
    strip.setPixelColor(i, c);
    delay(0.5);
  }
   strip.show();
}

```

Anyone have a pointer to how I could refactor my code so that the potentiometer works in both directions, and will light up or turn off the pixels on the strip as appropriate? Thank you!

**EDIT** Based on Ignacio's answer, I changed my `colorWipe` method to this:

```
void colorWipe(uint32_t c) {

  for (uint16_t i = lastPotentiometerValue; lastPotentiometerValue<180; i++){
      uint16_t clearColor = (127, 127, 127);
      strip.setPixelColor(i, clearColor);
  }

  for(uint16_t i=0; i<lastPotentiometerValue; i++) {
    strip.setPixelColor(i, c);
    delay(0.5);
  }

   strip.show();
}

```

However, now no strips are lit up.

**EDIT 2**

The condition was wrong; below is the code that works:

```
void colorWipe(uint32_t c) {

  for(uint16_t i = lastPotentiometerValue; i<180; i++){
      uint16_t clearColor = (0, 0, 0);
      strip.setPixelColor(i, clearColor);
  }

  for(uint16_t i=0; i<lastPotentiometerValue; i++) {
    strip.setPixelColor(i, c);
    delay(0.5);
  }

   strip.show();
}

```

# Answer
You forgot to clear every *other* pixel in `colorWipe()`. Pixels that aren't sent a color retain their previous color.
> 1 votes

---
Tags: arduino-uno, potentiometer, neopixel
---


# Question
Title: List of Arduino board preprocessor #defines
When one selects a board within Arduino IDE, a preprocessor definition is added to one of the behind-the-scenes files.

After a lot of hunting and some good fortune I found that the format of this definition is:

```
#define ARDUINO_<PROCESSOR-DESCRIPTOR>_<BOARDNAME>

```

Some are easy to guess (`ARDUINO_AVR_UNO`, for example), but others are less so. The Pro Micro has '16' or '8' appended to the definition depending on the speed. I do not know if the definition is different for 5V or 3.3V. I haven't managed to guess the definition for the Mega2560, but it isn't anything obvious.

**Question 1**: Is there a list in existence of the possible definitions?

**Question 2**: Is there any distinction, as far as compilation and preprocessor involvement is concerned, between *BoardX*-5V and *BoardX*-3.3V, and how is this distinction defined?

# Answer
> 15 votes
The list of board symbols can be generated by this shell command:

```
$ grep board= boards.txt | cut -f2 -d= | sort -u
AVR_ADK
AVR_BT
AVR_DUEMILANOVE
AVR_ESPLORA
AVR_ETHERNET
AVR_FIO
AVR_GEMMA
AVR_LEONARDO
AVR_LILYPAD
AVR_LILYPAD_USB
AVR_MEGA
AVR_MEGA2560
AVR_MICRO
AVR_MINI
AVR_NANO
AVR_NG
AVR_PRO
AVR_ROBOT_CONTROL
AVR_ROBOT_MOTOR
AVR_UNO
AVR_YUN

```

The boards are defined by the "build.board" property in the boards.txt file.

```
mini.build.board=AVR_MINI

```

This property is used by the build recipe together with ARDUINO\_-prefix.

```
-DARDUINO_{build.board}

```

Cheers!

# Answer
> 7 votes
Mikael has the right answer, but there are multiple boards.txt files depending on the installed boards with board manager, modifying the command to:

```
grep board= `find . -name boards.txt` | cut -f2 -d= | sort -u

```

and running it from your base Arduino directory collects the whole set.

# Answer
> 3 votes
The first blank is the *platform*. This is "AVR" for AVRs, "SAM" for SAM-based Arduinos, etc. This is derived from the platform directory containing the core.

The second blank is the *board*. This comes from the entry in `boards.txt` in the core itself, and is the identifier before the first period.

There is no difference between compilation processes with regards to voltages; any speed difference is given in `F_CPU` and the board itself should not be checked for this.

So there is no definitive list, since the list is of arbitrary size due to its source.

---
Tags: ide, c-preprocessor
---


# Question
Title: LCD display and ultrasonic sensor not functioning
I am doing fish feeder project with level detection for the feeds but lcd display and ultrasonic sensor did not function.

```
#include <LiquidCrystal.h>
#define trigPin 12              // the trig pin to digital pin 12
#define echoPin 13              // the Echo pin to digital pin 13
#define L 8
#define M 9
#define H 10
// #define trigmotor 1 //closelid
int led = A1;           // LED indicator to digital pin A1
#include <Servo.h>
Servo MyServo;

LiquidCrystal lcd(7, 6, 5, 4, 3, 2);

const int thresholdH = 0;
const int thresholdM = 70;
const int thresholdL = 90;
// defines variables
long duration;
int distance;
float percentLV;

void setup()
{
  pinMode(trigPin, OUTPUT);
  pinMode(echoPin, INPUT);
  Serial.begin(9600); // Starts the serial communication
  pinMode(led,OUTPUT);
  digitalWrite(led,LOW);            //set the led off(initial condition)
  lcd.begin(16, 2);
}
void loop()
{

int degreesOfRotation = 8;
int servoPinNumber = 11;
float hoursBetweenMeals = 12;
float mealDelayTime = 0;

{
    MyServo.attach(11);
    MyServo.write(degreesOfRotation);
    mealDelayTime = hoursBetweenMeals * 1800000;
    delay(20);

    while(degreesOfRotation < 152) {
        MyServo.write(degreesOfRotation);
        delay(10);
        degreesOfRotation += 1;
    }
    while(degreesOfRotation > 8) {
        MyServo.write(degreesOfRotation);
        delay(10);
        degreesOfRotation -= 1;
    }
    delay(mealDelayTime);
}

{
  // Clears the trigPin
  digitalWrite(trigPin, LOW);
  delayMicroseconds(2);
  // Sets the trigPin on HIGH state for 10 micro seconds
  digitalWrite(trigPin, HIGH);
  delayMicroseconds(10);
  digitalWrite(trigPin, LOW);
  // Reads the echoPin, returns the sound wave travel time in microseconds
  duration = pulseIn(echoPin, HIGH);
  // Calculating the distance
  distance = (duration * 0.034 / 2);
  float percentLV = (40 - ( distance - 16 )) * 100 / 40;

  if (percentLV > thresholdL && percentLV < 100) {

    lcd.clear();
    lcd.setCursor(0, 0);
    lcd.print("PLEASE REFILL!");
    lcd.setCursor(0, 1);
    //lcd.print(distance);
    lcd.print(percentLV);
    lcd.print(" %");
    digitalWrite(H, HIGH);
    digitalWrite(M, LOW);
    digitalWrite(L, LOW);
    //digitalWrite(trigmotor, HIGH);
    //delay(3000);
    //digitalWrite(trigmotor, LOW);
    //delay(1000);
    digitalWrite (led, HIGH);      // Turn on the led indicator
    delay(20);
  } else if (percentLV <= thresholdL && percentLV > thresholdM) {
    lcd.clear();
    lcd.setCursor(0, 0);
    lcd.print("U May Refill Now");
    lcd.setCursor(0, 1);
    //lcd.print(distance);
    lcd.print(percentLV);
    lcd.print(" %");
    digitalWrite(H, LOW);
    digitalWrite(M, HIGH);
    digitalWrite(L, LOW);
    //digitalWrite(trigmotor, LOW);
    digitalWrite (led, HIGH);      // Turn on the led indicator
    delay(20);
  } else if (percentLV <= thresholdM && percentLV > thresholdH) {
    lcd.clear();
    lcd.setCursor(0, 0);
    lcd.print("Take it easy");
    lcd.setCursor(0, 1);
    //lcd.print(distance);
    lcd.print(percentLV);
    lcd.print(" %");
    digitalWrite(H, LOW);
    digitalWrite(M, LOW);
    digitalWrite(L, HIGH);
    //digitalWrite(trigmotor, LOW);
    digitalWrite (led, LOW);      // Turn off the led indicator
    delay(20);

  } else {
    lcd.clear();
    lcd.setCursor(0, 0);
    lcd.print("FULL!!");
    lcd.setCursor(0, 1);
    //lcd.print(distance);
    lcd.print(percentLV);
    lcd.print(" %");
    //digitalWrite(trigmotor, LOW);
    digitalWrite (led, LOW);      // Turn off the led indicator
    delay(20);

    Serial.print("PercentLV: ");
    Serial.print(percentLV);
    Serial.println("%");
  }
  delay(1000);

}

}

```

# Answer
There doesn't appear to be anything wrong from a quick glance. Have you got the right library for the LCD?

The chances are there is something wrong with your LCD. So check your connections again. Now create a new sketch that just prints hello world on the LCD, or better still use an example. If that works, then the problem is an interaction between components.

So write a sketch that spins the servo back and forth while printing a message on the LCD.

Did that work, now add in the ultrasonic sensor and the code.

Now the other bits, and if that works, then you could look at what you have done differently, or just thank your lucky stars :)
> 1 votes

---
Tags: sensors, lcd
---


title: Arduino Zero: Enable RTTI

text:
# Question
Title: Arduino Zero: Enable RTTI
I need dynamic casts for my project, I'm getting:

```
error: 'dynamic_cast' not permitted with -fno-rtti

```

It appears that RTTI (run-time type information) is disabled with the `fno-rtti` compiler flag.

How do I change this?

# Answer
> 1 votes
It apparently is true that “RTTI (run-time type information) is disabled with the `fno-rtti` compiler flag”; however, looking at `compiler.c.flags` and `compiler.cpp.flags` in `platform.txt`, no `fno-rtti` compiler flag is set, suggesting that gcc sets it by default.

One way to turn off `fno-rtti` is adding a `-frtti` flag into the appropriate flags string in `platform.txt`. As a side effect, this will affect all sketches subsequently compiled, rather than only those that need dynamic casts.

Note, on a microcontroller, a more-appropriate way to deal with the problem is getting rid of the need for dynamic casts, via function overloading.

*Edit 1:* On Linux, typical file paths to `platform.txt` are like `/opt/arduino-1.6.3/hardware/arduino/avr/platform.txt` or `/opt/arduino-1.8.0/hardware/arduino/avr/platform.txt`. I don't know the location on OSX. However, a command like `locate *avr/platform.txt` should reveal its location. (If `locate` is a new install on your system, first run `updatedb`, which may take a while.)

---
Tags: arduino-zero
---


title: POE with Arduino Leonardo Eth

text:
# Question
Title: POE with Arduino Leonardo Eth
I recently purchased a Leonardo Eth and a 5v POE module in an attempt to have a POE micro-controller. I installed the module in the holes closest to the Ethernet jack side of the board, but when I apply power, the green power light turns on every second or so, but never fully turns on.

What am I doing wrong? Did I install the module wrong? Is it the wrong module?

# Answer
From the arduino.cc website.

"The optional PoE module is designed to extract power from a conventional twisted pair Category 5 Ethernet cable. PoE module features are as follows: IEEE802.3af compliant Input voltage range 36V to 57V Overload and short-circuit protection 12V Output High efficiency DC/DC converter: typ 85% @ 80% load 1500V isolation (input to output)"

It sounds like you need the 12V PoE module
> 2 votes

---
Tags: power, ethernet, arduino-leonardo
---


# Question
Title: Why is my boards.txt file not being found?
I'm using the `ino` command line tool for the first time. When attempting to build my first sketch I run: `ino build` in the project directory.

I get the following error:

```
Searching for Board description file (boards.txt) ... FAILED
Board description file (boards.txt) not found. Searched in following places:
  - /Applications/Arduino.app/Contents/Resources/Java/hardware/arduino
  - /usr/local/share/arduino/hardware/arduino
  - /usr/share/arduino/hardware/arduino

```

What's going wrong here?

I've found an open issue here: https://github.com/amperka/ino/issues/240 But I'm wondering if anyone has a workaround.

# Answer
I got a hack to work (macOS) by symlinking the files to where `ino` expected them to be. But now I'm running into this issue: https://github.com/amperka/ino/issues/149

FWIW:

```
cd /Applications/Arduino.app/Contents/Resources;
ln -s Java ../Java;
cd /Applications/Arduino.app/Contents/Resources/Java/hardware/arduino;
ln -s boards.txt avr/boards.txt;

```

Did it for me as far as finding boards.txt goes.

Still Broken otherwise. (Not marking as answer)
> 2 votes

---
Tags: arduino-uno, ino
---


# Question
Title: How do I sense that the serial monitor is started?
When starting the serial monitor in IDE I want to save important data to EEPROM before the Arduino Uno restarts. I do not have physical access to the Arduino so a "press button" solution does not work here.

# Answer
You can't. There is no way of detecting if the serial monitor is open or not.

However, you can disable the automatic reset and provide some functionality in your code for saving data to EEPROM when prompted through a command entered on the serial monitor (if you now need to even save the data).
> 3 votes

# Answer
What you really want to do is to store the data before the computer shuts down.

Here is what I did. I am running a Mega in a car and using it for a lot of things. The Mega receives its power from the ignition switch. When the ignition switch it turned on, the Mega boots up. In the "setup" section of the program, I set a digital output HIGH. The digital output is tied to the coil of a relay. One side of the relay is tied directly to the battery. Once the relay is energized, the relay supplies power to the Mega. I have a digital input tied to the power coming from the ignition switch through a resistor and a zener diode to clamp the voltage at 5 volts. In the main program I monitor the input power digital input. When I see the power go down,(ignition switch is turned off), I run a Shutdown program that stores all of the data I need stored to the EEProm. Once that is done, I set the digital output LOW. This de-energizes the relay and removes the power from the Mega. If you push the reset button, that is a hardware reset and you lose your data. If I want to reset the computer, I simply run the "Shutdown" routine. I can do that using a remote switch that drives a digital input.
> 0 votes

---
Tags: arduino-uno, eeprom, reset
---


title: Robot beeping when power set to 0

text:
# Question
Title: Robot beeping when power set to 0
I am working on an Arduino Uno robot project for college, I have modified my robot to beep and light up when he bumps into a wall or reverses, my robot works fine except for one very annoying problem, when my robots power is switched to 0 to turn him off he starts to beep as though he is bumping and I have no idea why!

My code:

```
#include <Servo.h>                           // Include servo library

Servo servoLeft;                             // Declare left and right servos
Servo servoRight;

byte wLeftOld;                               // Previous loop whisker values
byte wRightOld;
byte counter;                                // For counting alternate corners

void setup()                                 // Built-in initialization block
{
  pinMode(7, INPUT);                         // Set right whisker pin to input
  pinMode(5, INPUT);                         // Set left whisker pin to input
  pinMode(8, OUTPUT);                        // Left LED indicator -> output
  pinMode(2, OUTPUT);                        // Right LED indicator -> output

  tone(4, 3000, 1000);                       // Play tone for 1 second
  delay(1000);                               // Delay to finish tone

  servoLeft.attach(13);                      // Attach left signal to pin 13
  servoRight.attach(12);                     // Attach right signal to pin 12

  wLeftOld = 0;                              // Init. previous whisker states
  wRightOld = 1;
  counter = 0;                               // Initialize counter to 0
}

void loop()                                  // Main loop auto-repeats
{

  // Corner Escape

  byte wLeft = digitalRead(5);               // Copy right result to wLeft
  byte wRight = digitalRead(7);              // Copy left result to wRight

  if(wLeft != wRight)                        // One whisker pressed? (Output on the left is not the same as the right)
  {                                          // Alternate from last time?
  tone(4, 3000, 1000);                       // Beep for 1 second as we hit the wall (BK)
    if ((wLeft != wLeftOld) && (wRight != wRightOld))
    {
      counter++;                             // Increase count by one
      wLeftOld = wLeft;                      // Record current for next rep
      wRightOld = wRight;
      if(counter == 4)                       // Stuck in a corner?
      {
        wLeft = 0;                           // Set up for U-turn
        wRight = 0;
        counter = 0;                         // Clear alternate corner count
      }
    }
    else                                     // Not alternate from last time
    {
      counter = 0;                           // Clear alternate corner count
    }
  }

  // Whisker Navigation
  if((wLeft == 0) && (wRight == 0))          // If both whiskers contact
  {
    bump();                                  // Call bump function
    backward(1000);                          // Back up 1 second
    reverseBeep();                           // Call reverseBeep function
    turnLeft(800);                           // Turn left about 120 degrees
  }
  else if(wLeft == 0)                        // If only left whisker contact
  {
    bump();                                  // Call bump function
    backward(1000);                          // Back up 1 second
    reverseBeep();                           // Call reverseBeep function
    turnRight(400);                          // Turn right about 60 degrees
  }
  else if(wRight == 0)                       // If only right whisker contact
  {
    bump();                                  // Call bump function
    backward(1000);                          // Back up 1 second
    reverseBeep();                           // Call reverseBeep function
    turnLeft(400);                           // Turn left about 60 degrees
  }
  else                                       // Otherwise, no whisker contact
  {
    forward(20);                             // Forward 1/50 of a second
  }
}

void forward(int time)                       // Forward function
{
  servoLeft.writeMicroseconds(1700);         // Left wheel counterclockwise
  servoRight.writeMicroseconds(1300);        // Right wheel clockwise
  delay(time);                               // Maneuver for time ms
}

void turnLeft(int time)                      // Left turn function
{
  servoLeft.writeMicroseconds(1300);         // Left wheel clockwise
  servoRight.writeMicroseconds(1300);        // Right wheel clockwise
  delay(time);                               // Maneuver for time ms
}

void turnRight(int time)                     // Right turn function
{
  servoLeft.writeMicroseconds(1700);         // Left wheel counterclockwise
  servoRight.writeMicroseconds(1700);        // Right wheel counterclockwise
  delay(time);                               // Maneuver for time ms
}

void backward(int time)                      // Backward function
{
  servoLeft.writeMicroseconds(1300);         // Left wheel clockwise
  servoRight.writeMicroseconds(1700);        // Right wheel counterclockwise
  delay(time);                               // Maneuver for time ms
}

void bump()                                  // Light and sound code for when the robot bumps a wall (BK)
{

  tone(4, 3000, 1000);                       // Play tone for 1 second
  digitalWrite(8, HIGH);                     // Left LED on
  digitalWrite(8, LOW);                      // Left LED off

}

void reverseBeep()                           // Light and sound code for when the robot reverses(BK)
{

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

        digitalWrite(8, HIGH); // Left LED on
        tone(4, 1600, 400);                     // Beep (Pin 4, 1600Khz tone for 400ms) (BK)
        digitalWrite(8, LOW); // Left LED off

      }

}

```

I am using this breadboard setup http://learn.parallax.com/tutorials/robot/shield-bot/robotics-board-education-shield-arduino/chapter-5-tactile-navigation-6

The custom functions `bump()` and `reverseBeep()`are my custom functions to control the bumping and reversing beep and LED light up.

Does anyone know why he beeps when the power switch is set to 0?

# Answer
> 0 votes
By beeping I assume you mean a 1 second been with no flash from the LED. The only place in you code that can happen is when the whiskers are not equal. I think the whiskers are powered by the shield you have turned off, in which case I suspect they are floating. Is it possible to power these direct from the board, bypassing the off switch?

The easiest way to fix it would be to allow the processor to know when the Off switch is on and off. Wire the 5V from the shield to the Arduino via a resistor of ???Ohms and read that pin before doing anything in loop().

---
Tags: arduino-uno
---


title: ESP8266 ESP-12 Connection

text:
# Question
Title: ESP8266 ESP-12 Connection
I am connected with my ESP-12 through a programmer and all the AT functions work correctly. However I do not get a connection when connecting to the ESP8266 module.

*I have done the following:*

Set the mode both: `AT+CWMODE=3`

Connect to an Access Point: `AT+CWJAP="<name>","<password>"` (Responds with WIFI Connected and WIFI Got IP)

Set the Access Point: `AT+CWSAP = "<other_name>","<password>",<channel>,<password_security>`

So at this time it should be connected to my local network and I can connect to it through wifi on my laptop. However when I connect to it, it says 'Connected, No Internet' (The network the esp8266 module is connected to, has internet).

When I troubleshoot problems it says DNS is not responding.

Does anyone have a clue what to do next? Or what I might do wrong?

# Answer
> 0 votes
You can make the ESP8266 behave as a router, see Google for details. By default it won't do this.

You need to create two separate WIFI networks and then tell the ESP to 'route' traffic between them.

Your ESP needs to form one network (STA mode?). Your laptop needs to be on one network with the ESP. The laptop needs to be configured to use the ESP as the gateway and unless your ESP has a DHCP server the laptop needs a static address.

Your ESP also needs to be a client to you router's network, and needs to take an address from the Router's DHCP server.

---
Tags: esp8266, wifi
---


# Question
Title: Arduino powered car not running when touching ground
I hacked a cheap car I connected both motors to L298N Dual H-Bridge Motor Controller and all things are working good. Motors are running fast. But when I put the car on the ground to run. It runs so slow. I am using 4.5V for L298N. What can I do to run it fast on ground?

I have tried PWM but it does not work.

What can be the causes of this?

# Answer
> 5 votes
It cannot draw enough current I suppose. When wheels are free-spinning, the load on motor is very small. When you put it on ground, the load increases, and it is slow because there is not enough current to drive the load

---
Tags: arduino-uno, h-bridge, l298n
---


# Question
Title: Can you pass the entries of a strut array to a int array? if so how?
```
typedef struct {
  uint8_t  pitch;
}LearnNote;

#define  MAX_NOTE  500

LearnNote  Noteseq[MAX_NOTE];

int learnindex=0;
void loop() {
 MIDI.read();
}

void MyHandleNoteOn(byte channel, byte pitch, byte velocity){
Noteseq[learnindex].pitch=pitch;
learnindex++;
}

```

# Answer
Its not very clear what you are asking, but I think you are saying can you do this

```
uint8_t anArray[MAX_NOTE];
anArray = Noteseq.pitch;

```

In general the answer is no. However in this **specific** case off the top of my head I think you probably can (maybe). You have a struct which only contains bytes. The compiler will probably pack the sequentially so you will effectively have a contiguous sequence of bytes which you would be able to copy to the byte array by doing:

```
memcpy (anArray, Noteseq, MAX_NOTE);  // THIS IS BAD PRACTICE!

```

You can only do this in this case because the types are both 8bit numbers. Its not a good idea to do this copy between an array of structs and a POD type array is just asking for trouble.

Instead use a function to do it.

```
int* CopyPitch (LearnNote* source, int* destination, int count)
{
    for (int i = 0; i < count; ++i)
    {
        destination[i] = source[i].pitch;
    }
}

```

(You should really check for null pointers and stuff, but its just an example)
> 1 votes

---
Tags: arduino-mega, programming, array, struct
---


# Question
Title: How to connect arduino with local network
I am trying to connect Arduino with local network. This will act as a web server, client would be android mobile app or web browser. These are on same local network.

Do I need Ethernet Shield or ESP8266 to make Arduino accessible with local network IP ? Is there any way to connect without Ethernet Shield ?

# Answer
> 3 votes
To connect to a network you need a network interface. This could be an Ethernet interface, a Wifi interface or something that supports TCP/IP. The easiest way of doing this is with ether an Ethernet 'shield' of a WIFI 'shield'.

In either case there are a range of options, from full shields to smaller boards that connect via jumper wires. One important consideration is the longer the wires the more chance for signal degradation and loss of comms. So direct plug in boards are probably better.

Probably the easiest way to do it is to use a ESP8266-??, but using an ESP as a network interface is like only using your PC for email. The ESP is faster and has more memory than the Arduino, so it would be better to program that as the web-server and get the Arduino to feed it the data.

You could use Bluetooth, radio, etc, but that's just making life hard for yourself.

You could also look at the Arduinos that have networking built in.

# Answer
> 1 votes
If you get yourself a board with an ESP8266 (say, Wemos D1, NodeMCU etc) this will allow you to do what you require and connect wirelessly to a local network. You can do this either with the Arduino using the ESP8266 as a shield or alternatively you can use the 8266 board on its own (it's a more powerful MCU than the Arduino!!)

Hope this helps.

---
Tags: arduino-uno, esp8266, ethernet
---