# Question
Title: Can't read JSON data from client (webpage) with Arduino Leonardo ETH
I'm reading a digital pin and count how many times that pin is enable, after that the data is sent in JSON format. All is working well till here. But I want to introduce a value from webpage to arduino, so the arduino will know from what number it should count. I modified the webpage, I'm converting the value in JSON format, everything. But I can't get it on arduino. I see the value on Serial Monitor right before client disconnect. But I just cannot figure what I'm doing wrong, maybe you guys have a suggestion ?

Here is my Arduino code ( is a bit messy, and I haven't did the part were I tell to arduino the number where it should start to count, I will do that after i can get my numbers from webpage ). If needed i can also add the webpage code.

```
#include <SD.h>
#include <SPI.h>
#include <Ethernet2.h>
#include <ArduinoJson.h>

int pin = 3;
int state = 0;
//==========================
int push = 0;
//==========================
int laststate = 0;
const int chipS = 4;

byte mac[] = {0x00, 0x08, 0xDC, 0x1C, 0xB8, 0x4C}; // Enter the MAC address that is on your Ethernet shield (sticker) - eg. 00-08-DC-1C-B8-4C  (but use hexidecimal format eg. 0x00)
IPAddress ip(192, 168, 0, 88);                     // The IP address that you will give the Server - will depend on your local network range
EthernetServer server(8880);                       // The port to listen for Web Browsers - the default is 80, but some routers will block this port.. so change to 8081.

//*************************************************************************************************
// setup function
//=================================================================================================
void setup()
{
    Serial.begin(9600); // Begin Serial communication (baud rate = 9600).
    while (!Serial)
    {
        ; // wait for serial port to connect. Needed for Leonardo only
    }

    Ethernet.begin(mac, ip); // Initialise the ethernet library and network settings: https://www.arduino.cc/en/Reference/EthernetBegin
    server.begin();          // Tell the server to begin listening for incoming connections (on port 8081 in this example)
    Serial.print("Server IP address : ");
    Serial.println(Ethernet.localIP()); // If you see the IP address within the Serial monitor - you know that the server started successfully
    Serial.println(" ");

    // cardlaif  -  SD CARD INITALIZATION
    Serial.println("Initializare card...");
    if (!SD.begin(chipS))
    {
        Serial.println(" Initializarea cardului a esuat sau cardul lipseste ");
        while (1)
            ;
    }
    Serial.println(" Card initializat ");
    Serial.println(" ");
    pinMode(3, INPUT);
}

//*************************************************************************************************
// loop function
//=================================================================================================
void loop()
{
    //=====================================================================================================
    // contor  PIN 3 COUNTER
    //======================================================================================================
    state = digitalRead(pin);

    if (state != laststate)
    {
        if (state == HIGH)
        {
            push++;
        }
        delay(50);
    }
    laststate = state;

    Serial.print(" nr. citiri: ");
    Serial.println(push);
    //====================================================================================================
    // card SD CARD WRITE CODE
    //====================================================================================================
    String dataString = " ";
    dataString += String("nr. citiri: ");
    dataString += String(push);

    File dataFile = SD.open("datalog.txt", FILE_WRITE);
    if (dataFile)
    {
        dataFile.println(dataString);
        dataFile.close();
    }
    else
    {
        Serial.println("error opening datalog.txt");
    }
    //========================================================================================================
    //    net
    //========================================================================================================
    EthernetClient client = server.available(); // assign any newly connected Web Browsers to the "client" variable.

    if (client.connected())
    {
        Serial.println("Client Connected");
        // char c = client.read();
        // Serial.print(c);
        while (client.available())
        {
            Serial.write(client.read()); // Uncomment if you want to write the request from the Browser (CLIENT) to the SERIAL MONITOR (and comment out the next line)
            // client.read();                               // This line will clear the communication buffer between the client and the server.
        }

        // Send the Server response header back to the browser.
        client.println(F("HTTP/1.1 200 OK"));                                                                                // This tells the browser that the request to provide data was accepted
                                                                                //    client.println("GET");
        client.println(F("Access-Control-Allow-Origin: *"));                                                                            // Tells the browser it has accepted its request for data from a different domain (origin).
        client.println(F("Access-Control-Allow-Methods:  GET,POST,PUT,DELETE,OPTIONS"));                                                // The arduino will accept JSON format data using this
        client.println(F("Access-Control-Allow-Headers: Content-Type, Access-Control-Allow-Headers, Authorization, X-Requested-With")); // The arduino will accept JSON format data using this
        client.println(F("Content-Type: application/json;charset=utf-8"));                                                              // Lets the browser know that the data will be in a JSON format
        client.println(F("Server: Arduino"));                                                                                // The data is coming from an Arduino Web Server (this line can be omitted)
        client.println(F("Connection: close"));                                                                                // Will close the connection at the end of data transmission.
        client.println();                                                                                // You need to include this blank line - it tells the browser that it has reached the end of the Server reponse header.

        // Example Transmission: [{"key":0, "value":300},{"key":1, "value":320},{"key":2, "value":143},{"key":3, "value":24},{"key":4, "value":760},{"key":5, "value":470}]
        client.print("[");            // This is tha starting bracket of the JSON data
        client.print("{\"value\": "); // The value I read on pin 3 and send in JSON format to webpage
        client.print(push);           //  The value I read on pin 3 and send in JSON format to webpage
        client.print("}");            //  JSON things
        client.println("]");          // This is the final bracket of the JSON data
    }

    //=================================================================================================
    // trying to print on serial json data
    //=================================================================================================
    char json[] = "{\"index\" }";
    StaticJsonBuffer<300> jsonBuffer;
    JsonObject &root = jsonBuffer.createObject();
    if (!root.success())
    {
        Serial.println("Parsing failed");
    }
    int index = root["index"];
    Serial.print(" index: ");
    Serial.print(index);
    Serial.println(" ");

    client.stop();                       // This method terminates the connection to the client
    Serial.println("Client has closed"); // Print the message to the Serial monitor to indicate that the client connection has closed.
} // VOID LOOP END

```

And this is what I get on serial monitor:

```
Client Connected
POST / HTTP/1.1
Host: 192.168.0.88:8880
Connection: keep-alive
Content-Length: 1
Accept: application/json, text/javascript, */*; q=0.01
Origin: null
User-Agent: Mozilla/5.0 (Windows NT 10.0; Win64; x64)     AppleWebKit/537.36 (KHTML, like Gecko) Chrome/65.0.3325.181 Safari/537.36
Content-Type: application/json; charset=UTF-8
Accept-Encoding: gzip, deflate
Accept-Language: en-US,en;q=0.9,ro;q=0.8,es;q=0.7

5 index: 0

```

At the end, that 5 before the " index " word should be where the 0 is. The 5 it's my JSON data. The reason why I see it it's because I enabled to see the reqest from the browser.

Someone have any idea ?

P.S Sorry for my bad english ^\_^

# Answer
Below, you create a static string, which is never used again.

```
char json[] = "{\"index\" }";

```

Here you create a buffer and instantiate an empty JsonObject.

```
StaticJsonBuffer jsonBuffer;
JsonObject& root = jsonBuffer.createObject();

```

Here you check if `root` (your newly created JsonObject) is valid. Because it's empty and fresh, it is valid.

```
if (!root.success())
{
  Serial.println("Parsing failed");
}

```

Here, you try to ask for the value of `index` from your empty object.

```
int index = root["index"];
Serial.print(" index: ");
Serial.print(index);

```

If you never provide the `JsonObject` with any structure or content to parse, how can it give you anything back besides nothing?

The examples from the ArduinoJSON library prove to be helpful:

Documentation on `parseObject`

> ```
> char json[] = "{\"hello\":\"world\"}";
> StaticJsonBuffer<200> jsonBuffer;
> JsonObject& object = jsonBuffer.parseObject(json);
> const char* world = object["hello"];
>
> ```

Note the differences from what you are doing:

1. The initial JSON string to parse has both a key and a value.
2. The `StaticJsonBuffer` declaration includes a buffer size
3. The `JsonObject` declaration uses `parseObject` and passes in the `json` string, instead of creating a blank/empty object.
> 2 votes

---
Tags: arduino-leonardo, json
---


title: Arduino reduces the laser power

text:
# Question
Title: Arduino reduces the laser power
Its important to mention that I'm noob. I bought 500mw 405nm TTL module laser(5-12 volt) driver circuit. When I supplied laser with 12 volt, it turns on with max power. but when i connects laser TTL module to arduino (pin 11) in order to control turning on & off of laser through GRBL(CNC machine language) command with full power, the output of laser reduces.

"M05 S0" turns off the laser while "M03 S255" should turns on the laser with full power as it is turning on with direct 12 volt supply, but its not happening.

so how can I make laser turn on with full power with arduino control?

Laser I,m using https://www.amazon.in/gp/product/B071J2W7V8/ref=oh\_aui\_detailpage\_o00\_s00?ie=UTF8&psc=1

Laser driver circuit

# Answer
> 1 votes
The first thing I would recommend is to log into your Amazon account and contact the seller. Ask them to send you product documentation.

If the seller is not able to provide any, then you could return the product for a refund or try to figure it out how it works.

According to this document: TTL Laser

TTL modulators emit 100% of their power when a TTL "0" (0 VDC) is input and less than 5% of their power when a TTL "1" (5 VDC) is input.

gre\_gor's comment about trying a simple PWM sketch sounds like an excellent place to start.

---
Tags: arduino-uno
---


# Question
Title: On a motor after a continuous input of a certain amount of time
I would like to produce an output after a constant input is detected for a certain amount of time. Below is a simple code of what I am trying to do minus the time factor. Can someone help me on how to code out the duration of an input occurrence? i.e.

```
if (sensorValue > threshold);
    //if this occurs for more than 4 hours, then
    digitalWrite (3, HIGH);

```

# Answer
> 0 votes
You must store the state of the last readings and do something like this:

```
    //Off-loop:
    bool state_changed = false;
    unsigned long time_in_state = 0;
    unsigned long last_reading = 0;

    //On-loop:
    if (sensorValue > treshold && !state_changed) {
        time_in_state += millis() - last_reading;
        last_reading = millis();
    }
    else {
        state_changed = true;
        time_in_state = 0;
    }

    if (time_in_state > TIME_REQUIRED) {
      digitalWrite (3, HIGH);
    }

```

---
Tags: arduino-mega
---


title: ESP8266 MQTT client error

text:
# Question
Title: ESP8266 MQTT client error
```
#include <PubSubClient.h>
#include <ESP8266WiFi.h>

//EDIT THESE LINES TO MATCH YOUR SETUP
#define MQTT_SERVER "YOUR.MQTT.SERVER.IP"
const char* ssid = "YOUR_SSID";
const char* password = "YOUR_PASSWORD";

//LED on ESP8266 GPIO2
const int lightPin = 2;

char* lightTopic = "/test/light1";

WiFiClient wifiClient;
PubSubClient client(MQTT_SERVER, 1883, callback, wifiClient);

void setup() {
    //initialize the light as an output and set to LOW (off)
    pinMode(lightPin, OUTPUT);
    digitalWrite(lightPin, LOW);

    //start the serial line for debugging
    Serial.begin(115200);
    delay(100);

    //start wifi subsystem
    WiFi.begin(ssid, password);
    //attempt to connect to the WIFI network and then connect to the MQTT server
    reconnect();

    //wait a bit before starting the main loop
        delay(2000);
}

void loop(){

    //reconnect if connection is lost
    if (!client.connected() && WiFi.status() == 3) {reconnect();}

    //maintain MQTT connection
    client.loop();

    //MUST delay to allow ESP8266 WIFI functions to run
    delay(10);
}

void callback(char* topic, byte* payload, unsigned int length) {

    //convert topic to string to make it easier to work with
    String topicStr = topic;

    //Print out some debugging info
    Serial.println("Callback update.");
    Serial.print("Topic: ");
    Serial.println(topicStr);

    //turn the light on if the payload is '1' and publish to the MQTT server a confirmation message
    if(payload[0] == '1'){
        digitalWrite(lightPin, HIGH);
        client.publish("/test/confirm", "Light On");

    }

    //turn the light off if the payload is '0' and publish to the MQTT server a confirmation message
    else if (payload[0] == '0'){
        digitalWrite(lightPin, LOW);
        client.publish("/test/confirm", "Light Off");
    }

}

void reconnect() {

    //attempt to connect to the wifi if connection is lost
    if(WiFi.status() != WL_CONNECTED){
        //debug printing
        Serial.print("Connecting to ");
        Serial.println(ssid);

        //loop while we wait for connection
        while (WiFi.status() != WL_CONNECTED) {
            delay(500);
            Serial.print(".");
        }

        //print out some more debug once connected
        Serial.println("");
        Serial.println("WiFi connected");
        Serial.println("IP address: ");
        Serial.println(WiFi.localIP());
    }

    //make sure we are connected to WIFI before attemping to reconnect to MQTT
    if(WiFi.status() == WL_CONNECTED){
    // Loop until we're reconnected to the MQTT server
        while (!client.connected()) {
            Serial.print("Attempting MQTT connection...");

            // Generate client name based on MAC address and last 8 bits of microsecond counter
            String clientName;
            clientName += "esp8266-";
            uint8_t mac[6];
            WiFi.macAddress(mac);
            clientName += macToStr(mac);

            //if connected, subscribe to the topic(s) we want to be notified about
            if (client.connect((char*) clientName.c_str())) {
                Serial.print("\tMTQQ Connected");
                client.subscribe(lightTopic);
            }

            //otherwise print failed for debugging
            else{Serial.println("\tFailed."); abort();}
        }
    }
}

//generate unique name from MAC addr
String macToStr(const uint8_t* mac){

  String result;

  for (int i = 0; i < 6; ++i) {
    result += String(mac[i], 16);

    if (i < 5){
      result += ':';
    }
  }

  return result;
}

```

The error is 'callback' was not declared in this scope

# Answer
In C++, you can't use or reference a function before it is declared, that's not Arduino specific, it's how C++ "works"

Moving the `callback` function above the `client` declaration won't help, because the `callback` function references `client`

The only solution is to declare the `callback` function before it is referenced in `client` initialisation, but have the definition of `callback` after

i.e. add one line

```
WiFiClient wifiClient;
void callback(char* topic, byte* payload, unsigned int length); // add this in your code
PubSubClient client(MQTT_SERVER, 1883, callback, wifiClient);

```

Nothing else needs to be changed

Please excuse some terminology mistakes above - it's been a long time since I learned C/C++, while I know how to use it, I don't always know how to describe it :p

> apprently there's some bug in the toolchain - see the comments in the question. However, this is still a valid solution, I guess it works around the bug
> 3 votes

---
Tags: esp8266, mqtt
---


# Question
Title: How much can I recurse? How much can I recurse? How much ca!@#QFSD@$RFW
The Arduino Uno board has limited RAM which means it has a limited call stack available. Sometimes, recursion is the only quick option to implement a certain algorithm. So, given that the call stack is severely limited, what would be a way to find out that given a certain program running on the board, exactly how many recursive calls can you afford before there is a stack overflow (and bad things happen)?

# Answer
If you really want to recurse (and as @jippie said it is a bad idea; subliminal message: **don't do it**) and want to know how much you can recurse, then you will have to perform some calculation and experiments; also you generally will have only an approximation of it as it depends a lot on the memory state at the time your recursive function will be called.

For this, you should first know how SRAM is organized inside AVR-based Arduino (it won't apply to e.g. the Arduino Galileo by Intel). The following diagram from Adafruit shows it clearly:

Then you need to know the total size of your SRAM (depends on Atmel MCU, hence what kind of Arduino board you have).

On this diagram, it is easy to find out ths size of **Static Data** block as it is known at compile-time and won't change later on.

The **Heap** size can be more difficult to know as it can vary at runtime, depending on dynamic memory allocations (`malloc` or `new`) performed by your sketch or the libraries it uses. Using dynamic memory is quite rare on Arduino, but some standard functions do it (type `String` uses it, I think).

For the **Stack** size, it will also vary during runtime, based on the current depth of function calls (each function call takes 2 bytes on the Stack to store the address of the caller) and the number and size of local variables including passed arguments (that are also stored on the **Stack**) for all the functions called until now.

So let's suppose your `recurse()` function uses 12 bytes for its local variables and arguments, then each call to this function (the first one from an external caller and the recursive ones) will use `12+2` bytes.

If we suppose that:

* you are on Arduino UNO (SRAM = 2K)
* your sketch does not use dynamic memory allocation (no **Heap**)
* you know the size of your **Static Data** (let's say 132 bytes)
* when your `recurse()` function is called from your sketch, the current **Stack** is 128 bytes long

Then you are left with `2048 - 132 - 128 = 1788` available bytes on the **Stack**. The number of recursive calls to your function is thus `1788 / 14 = 127`, including the initial call (which is not a recursive one).

As you can see, this is very difficult, but not impossible to find what you want.

A simpler way to get the stack size available before `recurse()` is called would be to use the following function (found on Adafruit learning center; I have not tested it myself):

```
int freeRam ()
{
  extern int __heap_start, *__brkval;
  int v;
  return (int) &v - (__brkval == 0 ? (int) &__heap_start : (int) __brkval);
}

```

I strongly encourage you to read this article at Adafruit learning center.
> 15 votes

# Answer
Recursion is bad practice on a microcontroller as you already stated yourself and you probably want to avoid it whenever possible. On the Arduino site there are some examples and libraries available for checking free RAM size. You can for example use this to figure out when to break recursion or a bit trickier/riskier to profile your sketch and hard code the limit in it. This profile would be required for every change in your program and for every change in Arduino tool chain.
> 9 votes

# Answer
It depends on the function.

Every time a function is called, a new frame is pushed onto the stack. It will usually contain various critical items, potentially including:

* Return address (the point in the code from which the function was called).
* The local instance pointer (`this`) if calling a member function.
* Parameters passed into the function.
* Register values which need to be restored when the function ends.
* Space for local variables inside the called function.

As you can see, the stack space required for a given call depends on the function. For example, if you write a recursive function which only takes an `int` parameter and uses no local variables, it won't need much more than a few bytes on the stack. That means you can recursively call it far more than a function which takes several parameters and uses a lot of local variables (which will eat up the stack much quicker).

Obviously the state of the stack depends on what else is going on in the code. If you start a recursion directly within the standard `loop()` function, then there probably won't be a lot on the stack already. However, if you start it nested several levels deep in other functions, then there won't be as much room. That will affect how many times you can recurse without exhausting the stack.

It's worth noting that tail recursion optimisation exists on some compilers (although I'm not sure if avr-gcc supports it). If the recursive call is the very last thing in a function, it means it is sometimes possible to avoid altering the stack frame at all. The compiler can just re-use the existing frame, since the 'parent' call (so to speak) is finished using it. That will mean you can theoretically keep recursing as much as you like, so long as your function doesn't call anything else.
> 6 votes

# Answer
I had this exact same question as I was reading Jumping into C++ by Alex Allain, Ch 16: Recursion, p.230, so I ran some tests.

# TLDR;

**My Arduino Nano (ATmega328 mcu) can do 211 recursive function calls (for the code given below) before it has a stack overflow and crashes.**

# First off, let me address this claim:

> Sometimes, recursion is the only quick option to implement a certain algorithm.

\[Update: ah, I skimmed the word "quick". In that case you have some validity. Nevertheless, I think it's worth saying the following.\]

No, I don't think that is a true statement. I'm pretty certain **all** algorithms have both a recursive and a non-recursive solution, without exception. It's just that sometimes it is significantly *easier* to use a recursive algorithm. Having said that, recursion is very much frowned upon for use on microcontrollers and would probably never be allowed in safety-critical code. Nevertheless, it is possible of course to do it on microcontrollers. To know how "deep" you can go into any given recursive function, just test it! Run it in your real-life application in a real-life test case, and remove your base condition so that it will infinitely recurse. Print out a counter and see for yourself how "deep" you can go so you know whether or not your recursive algorithm is pushing the limits of your RAM too close to be used practially. Here's an example below to force stack overflow on an Arduino.

# Now, a few notes:

How many recursive calls, or "stack frames" you can get is determined by a number of factors, including:

* The size of your RAM
* How much stuff is already on your stack or taken up in your heap (ie: your free RAM matters; `free_RAM = total_RAM - stack_used - heap_used`, or you might say `free_RAM = stack_size_allocated - stack_size_used`)
* The size of each new "stack frame" which will be placed onto the stack for every new recursive function call. This will depend upon the function being called and its variables and memory requirements, etc.

# My results:

* 20171106-2054hrs - Toshiba Satellite w/16 GB RAM; quad-core, Windows 8.1: final value printed before crash: **43166**
    + took several seconds to crash--maybe 5~10?
* 20180306-1913hrs Dell high-end laptop w/64 GB RAM; 8-core, Linux Ubuntu 14.04 LTS: final value printed before crash: **261752**
    + followed by the phrase `Segmentation fault (core dumped)`
    + took only ~4~5 sec or so to crash
* 20180306-1930hrs Arduino Nano: TBD---is at ~250000 and still counting---the Arduino optimization settings must have caused it to optimize out the recursion...??? Yes, that is the case.
    + Add `#pragma GCC optimize ("-O0")` to the top of the file and redo:
* 20180307-0910hrs Arduino Nano: 32 kB flash, 2 kB SRAM, 16 MHz processsor: final value printed before crash: **211** `Here are the final print results:
209
210
211 ⸮ 9⸮ 3⸮`
    + took only a fraction of a second once it started printing at 115200 serial baud-rate--maybe 1/10 sec
    + 2 kiB = 2048 bytes / 211 stack frames = 9.7 bytes/frame (assuming ALL of your RAM is being used by the stack--which actually isn't the case) --but this seems very reasonable nonetheless.

# The code:

## The PC application:

```
/*
stack_overflow
 - a quick program to force a stack overflow in order to see how many stack frames in a small function can be loaded onto the stack before the overflow occurs

By Gabriel Staples
www.ElectricRCAircraftGuy.com
Written: 6 Nov 2017
Updated: 6 Nov 2017

References:
 - Jumping into C++, by Alex Allain, pg. 230 - sample code here in the chapter on recursion

To compile and run:
Compile: g++ -Wall -std=c++11 stack_overflow_1.cpp -o stack_overflow_1
Run in Linux: ./stack_overflow_1
*/

#include <iostream>

void recurse(int count)
{
  std::cout << count << "\n";
  recurse(count + 1);
}

int main()
{
  recurse(1);
}

```

## The Arduino "Sketch" program:

```
/*
recursion_until_stack_overflow
- do a quick recursion test to see how many times I can make the call before the stack overflows

Gabriel Staples
Written: 6 Mar. 2018
Updated: 7 Mar. 2018

References:
- Jumping Into C++, by Alex Allain, Ch. 16: Recursion, p.230
*/

// Force the compiler to NOT optimize! Otherwise this recursive function below just gets optimized into a count++ type
// incrementer instead of doing actual recursion with new frames on the stack each time. This is required since we are
// trying to force stack overflow.
// - See here for all optimization levels: https://gcc.gnu.org/onlinedocs/gcc/Optimize-Options.html
//   - They include: -O1, -O2, -O3, -O0, -Os (Arduino's default I believe), -Ofast, & -Og.

// I mention `#pragma GCC optimize` in my article here: http://www.electricrcaircraftguy.com/2014/01/the-power-of-arduino.html
#pragma GCC optimize ("-O0")

void recurse(unsigned long count) // each call gets its own "count" variable in a new stack frame
{
  // delay(1000);
  Serial.println(count);

  // It is not necessary to increment count since each function's variables are separate (so the count in each stack
  // frame will be initialized one greater than the last count)
  recurse (count + 1);

  // GS: notice that there is no base condition; ie: this recursive function, once called, will never finish and return!
}

void setup()
{
  Serial.begin(115200);
  Serial.println(F("\nbegin"));
  // First function call, so it starts at 1
  recurse (1);
}

void loop()
{
}

```

# References:

1. Jumping into C++ by Alex Allain, Ch 16: Recursion, p.230
2. http://www.electricrcaircraftguy.com/2014/01/the-power-of-arduino.html \- literally: I referenced my own website during this "project" to remind myself how to change Arduino compiler optimization levels for a given file with the `#pragma GCC optimize` command since I knew I had it documented there.
> 2 votes

# Answer
I wrote this simple test program:

```
void setup() {
  // put your setup code here, to run once:
  Serial.begin(115200);
  recurse(1);
}

void loop() {
  // put your main code here, to run repeatedly:

}

void recurse(long i) {
  Serial.println(i);
  recurse(i+1);
}

```

I compiled it for the Uno, and as i write it has recursed over 1 million times! I don't know, but the compiler may have optimized this program
> 1 votes

---
Tags: programming, sram
---


title: LED Strip Effect without delay

text:
# Question
Title: LED Strip Effect without delay
so a brief introduction about the project which I am working on before I go onto my issue.

I am working on a love-o-meter project (Not similar to the arduino example), whereby 2 people place 1 of their hands on a pad and with their other hand holding each other. Making use of a pulse sensor, I measure the BPM for 10s and then indicate the score on a LED strip. Apart from indicating the compatibility score, I also plan to use the LED strip (cylon/fire effect) to indicate that the arduino is in the progress of calculating (when it is measuring the BPM for 10s) and also to indicate idling (rainbow cycle effect, when there is no one is using the love-o-meter).

However, here comes my issue: Performing the BPM measurement and displaying the cylon/fire effect function at the same time. I know that I cannot use the delay function and instead use millis(). However, the functions in the NeoPixel library already uses the delay effect and it seems like a tough job to edit the function to it using millis(). Is there another way to do so?

# Answer
> 1 votes
If you can find another way of calculating the BMP during displaying an effect on the strip depends highly on your BMP sensor. If you can do the measurement with interrupts, it should work. In this case you should make sure, that the interrupt cannot be fired during the execution of the `Adafruit_NeoPixel.show()` function, since it is quite timing sensitive.

But since I recently worked on a project with a NeoPixel LED strip, I have already edited functions from the `strandtest` example for use with the `millis()` function. So you will not have to reinvent the wheel again :D I will try to strip away my custom code, so that you can easily use it.

```
float brightness = 1.0;
uint32_t strip_state=0;

uint32_t Wheel(Adafruit_NeoPixel *strip, byte WheelPos) {
  WheelPos = 255 - WheelPos;
  if(WheelPos < 85) {
    return strip->Color((255 - WheelPos * 3)*brightness, 0, WheelPos * 3*brightness);
  }
  if(WheelPos < 170) {
    WheelPos -= 85;
    return strip->Color(0, WheelPos * 3 * brightness, (255 - WheelPos * 3)*brightness);
  }
  WheelPos -= 170;
  return strip->Color(WheelPos * 3 * brightness, (255 - WheelPos * 3)*brightness, 0);
}

void fill_color(uint32_t color){
  byte r= ((color & 0xFF0000) >> 16) * brightness;
  byte g= ((color & 0xFF00) >> 8) *brightness;
  byte b= (color & 0xFF) * brightness;
  color = strip.Color(r,g,b);
  for(unsigned int i=0; i < strip.numPixels(); i++) {
    strip.setPixelColor(i, color);
  }
  strip.show();
}

void fade_color(){
  for(unsigned int i=0;i<strip.numPixels();i++){
    strip.setPixelColor(i,Wheel(&strip,strip_state));
  }
  strip.show();
  strip_state++;
  if(strip_state>255) strip_state = 0;
}

void moving_rainbow(){
  for(unsigned int i=0; i<strip.numPixels(); i++) {
    strip.setPixelColor(i, Wheel(&strip,((i * 256 / strip.numPixels()) + strip_state) & 255));
  }
  strip.show();
  strip_state++;
}

void colorWipe(uint32_t color) {
  byte r= ((color & 0xFF0000) >> 16) * brightness;
  byte g= ((color & 0xFF00) >> 8) *brightness;
  byte b= (color & 0xFF) * brightness;
  color = strip.Color(r,g,b);

  strip.setPixelColor(strip_state, color);
  strip.show();
  strip_state++;
}

//Theatre-style crawling lights.
void theaterChase(uint32_t c) {
  byte r= ((c & 0xFF0000) >> 16) * brightness;
  byte g= ((c & 0xFF00) >> 8) *brightness;
  byte b= (c & 0xFF) * brightness;
  c = strip.Color(r,g,b);
  for (uint16_t i=0; i < strip.numPixels(); i=i+3) {
    strip.setPixelColor(i + strip_state % 3, c);    //turn every third pixel on
    strip.setPixelColor(i + (strip_state +1) % 3, 0); // turn others off
    strip.setPixelColor(i + (strip_state +2) % 3, 0);
  }
  strip.show();
  strip_state++;
}

//Theatre-style crawling lights with rainbow effect
void theaterChaseRainbow() {
  for (uint16_t i=0; i < strip.numPixels(); i=i+3) {
    strip.setPixelColor(i + strip_state % 3, Wheel(&strip, (i+strip_state) % 255));    //turn every third pixel on
    strip.setPixelColor(i + (strip_state +1) % 3, 0); // turn others off
    strip.setPixelColor(i + (strip_state +2) % 3, 0);
  }
  strip.show();
  strip_state++;
}

```

The functions use the float variable `brigthness` to modulate the overall brightness of all LEDs. You can set it to every value between `0.0` and `1.0`.

The variable `strip_state` holds the current state of the effect on the strip. It is incremented everytime one of the functions is executed. Reset it to `0` if you want to restart an effect.

You yourself have to declare the variable `strip` as from the type `Adafruit_NeoPixel`.

So now you only have to call these function from the typical `millis()` code (like from the `BlinkWithoutDelay` example) in an interval, that you chose.

---
Tags: programming, millis
---


# Question
Title: Why doesn't the Ethernet W5100 shield work on Gigabit switch?
I have an Arduino Uno with an Ethernet Shield based on the Wiznet W5100 chipset :

It worked like a charm until I had to move it to another location and plugged it to a Gigabit switch. I had no link, the plug LEDs were off, or just on for a fraction of a second then off again.

I tried several switches, router and Internet boxes (french Freebox), and I ended up with the conclusion that it doesn't work when plugged onto a Gigabit switch. On every 10/100 switches, it works.

BUT

I also have a W5100 small module not designed like the shield :

This one is working on Gigabit switches !!!

I did see another post here : WizNet W5100 not connecting to modern switches and routers, where someone told the lower bits of the first MAC Address byte should be 00. So I changed the MAC address to 08:af:01:00:00:03 with no more luck, the shield still doesn't get connectivity.

I googled for this but didn't find any resources. I'm surprised this hasn't come over, knowing that so much ethernet shields are out on the market!

I tried a second shield (like the first picture), same issue : no connectivity on Gigabit switches.

I know other old NICs or laptops that don't support Gigabit are working correctly with Gigabit switches that should "pull down" the port to 100 instead of 1000.

Does anyone have an answer about why it doesn't work and how we can have an Arduino work when connected to a Gigabit switch? (other shields?)

# Answer
The fix for this is to solder a 120 Ohm resistor between pins 1-2 and 3-6 of the RJ45 socket (where pin 1 is closest to the left side of the socket when looking at the top of the board. (Credit to keithsw1111 for the fix)

See https://forum.arduino.cc/index.php?topic=372779.0 for full details.

I know this was asked a long time ago however this post comes up quite high on a google search of the issue so its good to have reference to the fix.
> 2 votes

---
Tags: arduino-uno, shields, ethernet, networking
---


title: ESP8266, Arduino IDE vs Lua?

text:
# Question
Title: ESP8266, Arduino IDE vs Lua?
I'm planning to buy an ESP8266. Do I really need to learn Lua to play with it? I have seen some people using it with the standard Arduino IDE.

Do you need a custom firmware to use the Arduino IDE instead of Lua?

The Arduino IDE seems better for me because I already know the syntax. Is there any downside to using the Arduino IDE instead of NodeMCU with Lua?

# Answer
Using the Arduino IDE *is* custom firmware. That's what you're writing. You don't *need* any new firmware because the new firmware is what you are writing.

I can't think of any downsides to using C++ to program the ESP8266 instead of Lua - in fact it can only be a benefit since you are not using an interpreted language which is going to be slower than natively compiled code.
> 13 votes

# Answer
Lua, like many scripting languages, tends to make you a lot more productive as a programmer: things become far easier as you work at a higher abstraction level and do not worry about trivial things like memory management. You achieve the same goals with far less lines of code. On the other hand, whereas it makes development faster, it also makes program execution slower. Whether this is a good trade-off or not is very dependent on the particular application you want to write.

In your particular case, you also have to consider the fact that you do not know Lua, and you already know both the C++ language and the Arduino API. Then you may not rip the benefits of Lua on a single project, because of the time needed to learn the language. You may consider learning the language as an investment, probably worth it if you are going to program a lot on this platform, probably *not* worth it if it's only for a single, simple enough project. If unsure, I suggest you take a look at the API provided with Lua on this platform: how well does it fit your project? Is it a significantly better fit than the Arduino API?
> 15 votes

# Answer
I STRONGLY RECOMMEND TO STAY WITH THE ARDUINO IDE!

Despite programming in C++ not being as friendly and versatile as Lua (working with Esplorer is really a dream come true!), Lua is VERY UNSTABLE AND UNPREDICTABLE!!!

You can run a simple program of ten lines and it works ok for a day... two... and suddenly, on the 3rd day the chip hangs unexpectedly, and with no reason! If you are lucky, the chip will reboot and program will start running again... that WAS NOT the case with me. I had to reload the program again! After 3 cycles like this, I decided to abandon Lua... FOREVER.
> 5 votes

# Answer
Sorry for bumping, but this thread helped me to decide for Arduino IDE.

I started with Arduino IDE but couldn't get it to work with ESP-07. Moved on to NodeMCU and Lua with Esplorer. Took me a while to get it working there also due to the odd bootloader baud rate. First it seemed so easy to set up a WEB-server, but problem was that all the examples found were based on an ancient FW 0.96, and trying with the latest 2.1 didn't work at all. So realising that people hadn't done much with newer FW gave me second thoughts.

Now with Arduino IDE things start to work the way they should! :)
> 0 votes

---
Tags: arduino-ide, esp8266, nodemcu
---


# Question
Title: Arduino IDE : 'tansig' was not declared in this scope
I am working on a simple NN sketch, everything looks fine and also i have added #include math.h .but when i try to compile it gives an error i-e **'tansig' is not defined in this scope**

I am trying to implement neural networks on obstacle avoiding robot. Weights(Constants) are extracted from matlab training file. How to make **tansig** work with arduino IDE

```
#include <math.h>
byte p1,p2,p3;
float n1,n2,n3,n4,n5,n6,n7,n8,n9,n10,n11,n12,s1,s2,s3,s4,s5,s6,s7,s8;

int Echo1 = A4; //LEFT_SENSOR ECHO
int Trig1 = A5; //LEFT_SENSOR TRIG
int Echo2 = A2; //MID_SENSOR ECHO
int Trig2 = A3; //MID_SENSOR TRIG
int Echo3 = A0; //RIGHT_SENSOR ECHO
int Trig3 = A1; //RIGHT_SENSOR TRIG

//Motor driver outputs

#define m11 3
#define m12 4
#define m21 5
#define m22 6

int Left_Distance = 0,Right_Distance = 0,Middle_Distance = 0 ;

/*Ultrasonic distance measurement Sub function*/
int Left_Distance_test()
{
digitalWrite(Trig1, LOW);
delayMicroseconds(2);
digitalWrite(Trig1, HIGH);
delayMicroseconds(20);
digitalWrite(Trig1, LOW);
float Fdistance = pulseIn(Echo1, HIGH);
delay(10);

Fdistance= Fdistance/ 29 / 2;
return (int)Fdistance;
}

int Middle_Distance_test()
{
digitalWrite(Trig2, LOW);
delayMicroseconds(2);
digitalWrite(Trig2, HIGH);
delayMicroseconds(20);
digitalWrite(Trig2, LOW);
float Fdistance = pulseIn(Echo2, HIGH);
delay(10);

Fdistance= Fdistance/ 29 / 2;
return (int)Fdistance;
}

int Right_Distance_test()
{
digitalWrite(Trig3, LOW);
delayMicroseconds(2);
digitalWrite(Trig3, HIGH);
delayMicroseconds(20);
digitalWrite(Trig3, LOW);
float Fdistance = pulseIn(Echo3, HIGH);
delay(10);

Fdistance= Fdistance/ 29 / 2;
return (int)Fdistance;
}

void setup()
{

pinMode(Echo1, INPUT);
pinMode(Trig1, OUTPUT);
pinMode(Echo2, INPUT);
pinMode(Trig2, OUTPUT);
pinMode(Echo3, INPUT);
pinMode(Trig3, OUTPUT);

  pinMode(m11, OUTPUT);
  pinMode(m12, OUTPUT);
  pinMode(m21, OUTPUT);
  pinMode(m22, OUTPUT);

}

void loop()
{
  Left_Distance = Left_Distance_test();
delay(10);
Middle_Distance = Middle_Distance_test();
delay(10);
Right_Distance = Right_Distance_test();
delay(10);

p1=Left_Distance;
p2=Middle_Distance;
p3=Right_Distance;

n1=(0.0588*p1)+(-2.7382*p2)+(-2.2898*p3)+(5.2586);
n2=(-3.1601*p1)+(-2.2137*p2)+(1.7397*p3)+(1.4386);
n3=(2.2931*p1)+(0.3145*p2)+(3.5053*p3)+(-1.0167);
s1=tansig(n1);
s2=tansig(n2);
s3=tansig(n3);

n4=(1.1021*s1)+(1.2825*s2)+(-1.9864*s3)+(-2.3891);
n5=(-0.5501*s1)+(1.8527*s2)+(-2.0468*s3)+(1.4314);
n6=(0.4322*s1)+(-0.2474*s2)+(-2.5017*s3)+(-0.5222);
n7=(-0.2658*s1)+(-2.0624*s2)+(-2.2511*s3)+(1.0958);
n8=(1.7401*s1)+(1.1111*s2)+(1.2254*s3)+(2.4701);
s4=tansig(n4);
s5=tansig(n5);
s6=tansig(n6);
s7=tansig(n7);
s8=tansig(n8);

n9=(1.0819*s4)+(-1.0897*s5)+(0.0658*s6)+(-0.1232*s7)+(0.3510*s8)+(1.2990);
n10=(-1.0865*s4)+(1.0899*s5)+(-0.062*s6)+(0.1241*s7)+(0.5818*s8)+(-0.7316);
n11=(-0.2292*s4)+(-0.0606*s5)+(1.0508*s6)+(-0.9711*s7)+(1.1635*s8)+(0.2269);
n12=(0.2262*s4)+(0.0607*s5)+(-1.0482*s6)+(0.9717*s7)+(-0.5215*s8)+(0.6312);

digitalWrite(m11,n9);
digitalWrite(m12,n10);
digitalWrite(m11,n11);
digitalWrite(m11,n12);

}

```

**error**: 'tansig' was not declared in this scope

# Answer
> -1 votes
According to: http://au.mathworks.com/help/nnet/ref/tansig.html

> **Algorithms**
>
> ```
> a = tansig(n) = 2/(1+exp(-2*n))-1
>
> ```
>
> This is mathematically equivalent to tanh(N).

So, replace calls to `tansig` by `tanh`. Or, make a define to do it:

```
#define tansig(n) tanh(n)

```

---

> But output of tanh are not suitable to write for motor inputs. They are \[ -0.xxx or 1.xxx or 0.xxx\].

...

> How to translate those outputs to some other which suits motor driver

There is a map function in the IDE which lets you translate from one range to another.

---

> map() works only on long integers (comment by Edgar Bonet)

```
long map(long x, long in_min, long in_max, long out_min, long out_max)
{
  return (x - in_min) * (out_max - out_min) / (in_max - in_min) + out_min;
}

```

OK, well write your own function that does the same thing to floats. Example:

```
float fmap(float x, float in_min, float in_max, float out_min, float out_max)
{
  return (x - in_min) * (out_max - out_min) / (in_max - in_min) + out_min;
}

```

---
Tags: arduino-mega, arduino-ide, c++
---


# Question
Title: How to determine the SPIFFS size on an esp8266-01?
I'm confused about my esp8266-01 if they have SPIFFS or not. Is there a way to find it out? If they have, how to get their size?

I've got the following flash id: `0x1440e0`.

Example SPIFFS apps keep crashing with `wdt reset` and lots of dumped hexes.

# Answer
First you need to know the size of the flash memory attached to esp8266 on your module. Common sizes are 512 kB (4Mbit), 1 MB (8Mbit) and 4 MB. Espressif Flash Download Tool (Windows) or esptool can determine it.

You can choose the size of the SPIFFS in your flash 'layout' by selecting the option in IDE Tools menu. Take one according to for you flash size and size of the files you want to put into SPIFFS.

If you have 1 MB flash on your module and you want to use OTA upload, let flash space for twice a space taken by the sketch.
> 2 votes

---
Tags: esp8266
---


# Question
Title: RFID reader code to identify more than one tag
I'm new to using Arduino and I have managed a few changes to this sketch. But I want to check for a second tag if the first one is not correct. I just can't seem to get it to work. I think it would be good if the tag is not a match to ask it to check the next tag and carry on, but I'm not sure how to make this happen.

```
//RFID Password Typer
//If a matching tag is found, the keyboard types
//CTRL-ALT-DEL, then types the password and presses enter
//Which should log you on to a Windows computer
//Or Lock the computer if you're already logged in

#include <SPI.h>
#include <MFRC522.h>
#include "Keyboard.h"
#include <Mouse.h>

#define RST_PIN 9
#define SS_PIN 10

byte tag[10]={0x64,0xAE,0xDD,0xFC,};
char pswd[]="********\n";      //password, end with just \n
MFRC522 mfrc522(SS_PIN, RST_PIN);  // Create MFRC522 instance

void setup() {
  SPI.begin();              //start SPI
  mfrc522.PCD_Init();       //start RC522 module
  Keyboard.begin();         //start USB keyboard
  pinMode(13, OUTPUT);
  digitalWrite(13, LOW);     //LED off
}

void loop() {
  if (!mfrc522.PICC_IsNewCardPresent()){ return; }
  if (!mfrc522.PICC_ReadCardSerial()){ return; }
  for(byte i = 0; i < mfrc522.uid.size; i++) {
    if(mfrc522.uid.uidByte[i]!=tag[i]){ return; }
  }
  mfrc522.PICC_HaltA(); //stop tag so we don't get repeats
  digitalWrite(13, HIGH); //LED on so we know we've got tag match
  Mouse.click();
  delay(1000);
  Keyboard.press(KEY_LEFT_CTRL);
  delay(1000);
  Keyboard.releaseAll();
  Keyboard.press(KEY_LEFT_CTRL);
  Keyboard.press(KEY_LEFT_ALT);
  Keyboard.press(KEY_DELETE);
  delay(100);
  Keyboard.releaseAll();
  delay(300);
  Keyboard.print(pswd);
  delay(100);
  digitalWrite(13, LOW); //LED off
}

```

# Answer
> 1 votes
here's how I'd do it ... allowing for 4, 7 and 10 byte uid's (which are all possible apparently)

```
struct tagInfo {
  byte len;
  byte uid[10];
};
struct tagInfo tag[] = { // add your tags here
  // the len is 1, 2 or 3, for lengths 4, 7, and 10
  // you could just use 4, 7, 10 here and not bother
  // with the len * 3 + 1 calculation later
  // the choice is yours, really
  {1, {0x01, 0x02, 0x03, 0x04}},
  {1, {0x02, 0x03, 0x04, 0x05}},
  {2, {0x01, 0x02, 0x03, 0x04, 0x05, 0x06, 0x07}},
  {1, {0x02, 0x02, 0x02, 0x02}}
};
const int numtags = sizeof(tag)/sizeof(struct tagInfo);

```

Then, your loop

```
void loop() {
  if (!mfrc522.PICC_IsNewCardPresent()) { return; }
  if (!mfrc522.PICC_ReadCardSerial()) { return; }
  int i; // declare before the loop because we want to check the value after the loop ends
  for (i = 0; i < numtags; i++) {
    byte len = tag[i].len * 3 + 1;
    if(len == mfrc522.uid.size) { // 4, 7, 10?
      if(!memcmp(mfrc522.uid.uidByte, tag[i].uid, len)) {
        break; // found an exact match so stop the loop
      }
    }
  }
  if (i == NUMTAGS) { return; } // no matches
  // all good here - run the rest of your code
}

```

# Answer
> 0 votes
Got it. Not sure if it's the best way but it works. Thanks for your help.

```
//RFID Password Typer
//If a matching tag is found, the keyboard types
//CTRL-ALT-DEL, then types the password and presses enter
//Which should log you on to a Windows computer
//Or Lock the computer if you're already logged in

#include <SPI.h>
#include <MFRC522.h>
#include "Keyboard.h"

#define RST_PIN 9
#define SS_PIN 10

byte tag[10]={****,****,****,****,};
byte tag1[10]={****,****,****,***^,};
byte tag2[10]={****,****,****,**^^,};
byte tag3[10]={****,****,****,*^^^,};
char pswd[]="*********\n";      //password, end with just \n
MFRC522 mfrc522(SS_PIN, RST_PIN);  // Create MFRC522 instance

void setup() {
  SPI.begin();              //start SPI
  mfrc522.PCD_Init();       //start RC522 module
  Keyboard.begin();         //start USB keyboard
  pinMode(13,OUTPUT);
  digitalWrite(13,LOW);     //LED off
}

void loop() {
  if (!mfrc522.PICC_IsNewCardPresent()) { return; }
  if (!mfrc522.PICC_ReadCardSerial()) { return; }
  for(byte i = 0; i < mfrc522.uid.size; i++) {
    if(mfrc522.uid.uidByte[i]!=tag[i]) {
    } else if(mfrc522.uid.uidByte[i]!=tag1[i]) {
    } else if(mfrc522.uid.uidByte[i]!=tag2[i]) {
    } else if(mfrc522.uid.uidByte[i]!=tag3[i]) { return; }
  }
  mfrc522.PICC_HaltA(); //stop tag so we don't get repeats
  digitalWrite(13, HIGH); //LED on so we know we've got tag match
  Keyboard.press(KEY_LEFT_CTRL);
  Keyboard.press(KEY_LEFT_ALT);
  Keyboard.press(KEY_DELETE);
  delay(100);
  Keyboard.releaseAll();
  delay(300);
  Keyboard.print(pswd);
  delay(100);
  digitalWrite(13,LOW); //LED off
}

```

---
Tags: arduino-leonardo
---


# Question
Title: Error array value after passed to a function
I would like to ask about a weirdness in my program. This is my program:

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

void loop() {
   workout_Text();
}

void workout_Text() {
  int woT_x[] = {1, 4, 8, 12, 16};
  int woT_y[] = {1, 4, 8, 12, 16};
  int n = sizeof(woT_y);
  on_led(woT_x, woT_y, n);
}

void on_led(int a_mat[], int b_mat[], int m) {
  for (int i = 0; i < m; i++) {
    Serial.print(a_mat[i]);
    Serial.print(" : ");
    Serial.println(b_mat[i]);
    delay(100);
  }
}

```

This is the part of my program for a LED matrix. The `on_led purpose` function is for printing the value of `a_mat` and `b_mat`. Instead of printing:

```
1 : 1
4 : 4
8 : 8
12 : 12
16 : 16
1 : 1
4 : 4
8 : 8
16 : 16

```

It prints:

```
1 : 1
4 : 4
8 : 8
12 : 12
16 : 16
13312 : 1
23296 : 4
1 : 8
4 : 12
8 : 16
1 : 1
4 : 4
8 : 8

```

Where does the big number come from? I am sure that my code is right to just print the `a_mat` and `b_mat`.

Thank you.

# Answer
> 3 votes
`sizeof()` returns the total number of bytes. If you have an array of 5 ints, where each int is 2 bytes long, sizeof will return 10.

If you want the number of elements in the array, you need to divide by the size of a single element:

```
int n = sizeof(woT_y) / sizeof(woT_y[0]);

```

# Answer
> 3 votes
`sizeof` counts bytes. the type of your array is int. sizeof of the int array of length 5 is 10 bytes. your `for` loop goes to i \< 10 and reads after the 5th item of the array.

---
Tags: programming, c, array
---


# Question
Title: Using an accelerometer with an Arduino as a shock sensor
I really need some help. I have absolutely no experience with accelerometers and have a project that would work great if I could integrate one into it. I am not hinting to have some write me a code, just get me looking in the right direction.

My code (below) was written to work with 2 buttons and an LED. Basically, its nothing but a reaction timer using an RGB liquid crystal display.

Sequence of events...

1. power on
2. displays “push button to start”
3. when panel button is pushed, the loop begins by randomly selecting a “FIRE” time when “fire” button is pressed, it echoes the time it took
4. my FOR statement, allows it to loop three times before returning to the begin.

This was all what I set out to accomplish, originally. My sister has been using it at a retirement home for some of the patients to play with. Lately she asked if instead of a “fire” button it could be programmed to simply, tap the whole unit, push the unit, or even use a tether of some sort. I figured an accelerometer was the ticket.

I purchased an ADXL345, I tried playing with several sketches from GitHub. What I find is the accelerometer is ALWAYS giving out information. I thought it would actually “rest” when not being physically moved.

How can I use my ADXL345 to be at complete standstill, until it is “moved,” that it would activate a WHILE statement???

```
#include <Wire.h>
#include <LiquidCrystal.h>
#include <SparkFun_ADXL345.h>

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

int lcdRedPWMPin = 17;
int lcdGreenPWMPin = 16;
int lcdBluePWMPin = 15;

void setDisplayRGB(int r, int g, int b)

{
  analogWrite(lcdRedPWMPin,   r);
  analogWrite(lcdGreenPWMPin, g);
  analogWrite(lcdBluePWMPin,  b);
}

void setup()
{
  lcd.begin(16, 2);
  lcd.clear();
  pinMode(13, OUTPUT);
  Serial.begin(115200);
  adxl.powerOn();
  adxl.setRangeSetting(2);    // Accepted values are 2g, 4g, 8g or 16g
  //adxl.setSpiBit(0);
  adxl.setActivityXYZ(1, 1, 1);
  adxl.setActivityThreshold(70);
  adxl.ActivityINT(1);
  pinMode(13, INPUT);
  digitalWrite(13, LOW);

  pinMode(9, INPUT); //panel button
  digitalWrite(9, HIGH);

  pinMode(8, INPUT); //FIRE button
  digitalWrite(8, HIGH);

  pinMode(10, OUTPUT); //FIRE led
  digitalWrite(10, LOW);

  // int    fireButton = digitalRead(8);
  int    panelButton = digitalRead(9);
  lcd.clear();
  setDisplayRGB(100, 100, 75);
  lcd.setCursor(1, 0);
  lcd.print("Let's see what");
  lcd.setCursor(1, 1);
  lcd.print("what you got!");
  delay(2000);
}
double timeToFire = 0; //time it took to (fire-trigger)
double fireTimerStarts = millis(); //fire (timer starts)
double triggerTimerStops ; //trigger (timer stops)
int ran; //random

void loop()
{

  int x, y, z;
  adxl.readAccel(&x, &y, &z);
  // byte interrupts = adxl.getInterruptSource();
  int average = (x + y + z);

  while (digitalRead(9) == HIGH)
  {
    lcd.clear();
    setDisplayRGB(40, 200, 75); //purple 40,200,75
    lcd.setCursor(0, 0);
    lcd.print("Press Button");
    lcd.setCursor(0, 1);
    lcd.print("to Start ...");
    delay(50);
  }
  for (int panelButton = 0; panelButton < 3; panelButton++)

  {
    lcd.clear();
    lcd.setCursor(0, 0);
    setDisplayRGB(255, 255, 0); //blue
    lcd.print("  ---READY---");
    delay((int)random(1000, 5000));
    {
      ran = random(1, 3);
      Serial.println(ran);
      if ( ran == 1)
        lcd.clear();
      lcd.setCursor(0, 0);
      setDisplayRGB( 0, 155, 155 );  //red
      lcd.print("     <FIRE>   ");
      lcd.setCursor(0, 1);
      lcd.print(average);
      fireTimerStarts = millis();
      digitalWrite(10, HIGH);

      // if(adxl.triggered>activityThreshold)

      while (adxl.triggered(13, HIGH))

        //while (digitalRead(8) == HIGH)
      {
        triggerTimerStops = millis();
      }
      digitalWrite (13, LOW);
      digitalWrite(10, LOW);

      setDisplayRGB(100, 100, 225); //green
    }
    timeToFire = (triggerTimerStops - fireTimerStarts) / 1000;

    delay(500);
    {
      lcd.clear();
      setDisplayRGB(0, 255, 0);
      lcd.setCursor(0, 1);
      lcd.print(timeToFire);
      lcd.setCursor(11, 1);
      lcd.print("Sec's");
      lcd.setCursor(0, 0);
      lcd.print("Your time was ...");
      delay(1500);
    }
  }

}

```

# Answer
> 1 votes
An alternative to using an accelerometer is a simple Vibration Sensor Switch. Adafruit has a Fast Vibration Sensor Switch: https://www.adafruit.com/product/1766, Medium Vibration Sensor Switch: https://www.adafruit.com/product/2384 and a Slow Vibration Sensor Switch: https://www.adafruit.com/product/1767, each costing 1 USD.

**Edit 1:**

If you look for "ADXL345\_ACTIVITY" in the SparkFun\_ADXL345\_Example.ino sketch, there is a comment that says "add code here to do when activity is sensed".

My suggestion is to get the ADXL345 working with this sketch first, then start removing the excess code from it that you don't need. Once you have the bare minimum code required to accomplish your goal, try to integrate that with you current sketch.

There are several "sensitivity adjustments" you can make under the "Configure ADXL345 Settings" section of the code.

# Answer
> 0 votes
> I purchased an ADXL345, I tried playing with several sketches from GitHub. What I find is the accelerometer is ALWAYS giving out information. I thought it would actually “rest” when not being physically moved.

The accelerometer reports its current acceleration on each axis at all times, whether that acceleration is changing or not. When at rest and upright, it will report close to 1.0 g on the Z axis; when rotated to some other direction and held steady, the *vector magnitude* of the accelerations on the three axes will be close to 1.0. The vector magnitude is computed as the square root of the sum of the squares of the elements, so rather than averaging, you'll want to do this:

```
int x, y, z;
adxl.readAccel(&x, &y, &z);

float mag = sqrt( x*x + y*y + z*z );

```

This `mag` value should change only slightly if you gently rotate the accelerometer. That baseline value represents 1.0g of acceleration from Earth's gravity.

A rapid motion of the accelerometer will produce some higher or lower value, briefly. Figure out what threshold makes sense for your application and do something like:

```
if (mag > (BASELINE_GRAVITY * 1.2f))
{
    lcd.setCursor(0, 0);
    lcd.print("You moved!");
}

```

# Answer
> 0 votes
According to the datasheet of adxl345, this chip (so the module) has single-tap, double-tap functionality. As described in the datasheet, you can configure the chip as you want it to operate. The chip has 2 interrupt pins. When it is configured to operate one of the tap modes and senses the tap, it gives an interrupt signal. You can check that signal and process the information.

---
Tags: programming
---


# Question
Title: Arduino(s) not resetting on Serial connection lost / re-established - why?
it seems that I accidentally found a way to make my two Arduino nano clones run without resetting on serial connection close/reconnect. On one hand, this behavior is much closer to the desired behavior and on the other hand it feels hackish, because I don't know the cause yet.

The devices are still able to be flashed with new firmware

I assume that it has to do with the usage of `socat` as proxy for the devices in question. The described behavior was first observed after playing with `socat`. The command that finally worked for me:

```
/usr/bin/socat -s -d /dev/ttyACM3,b115200,cs8,parenb=0,cstopb=0,clocal=0,raw,echo=0,setlk,flock-ex-nb,nonblock=1 PTY,link=~/.pyduin/ttyACM3.tty,b115200,cs8,parenb=0,cstopb=0,clocal=0,raw,echo=0,setlk,flock-ex-nb,nonblock=1

```

An Arduino Uno with the exact same firmware/treatment does not show the same bahavior.

Any ideas what had gone wrong? And how to restore the default FTDI behavior?

# Answer
What you have done is to disable the "HUPCL" signal that is sent when the port is opened/closed.

You can turn the signal back on with:

```
$ stty -F /dev/ttyACM3 hupcl

```

And you can turn it off again with:

```
$ stty -F /dev/ttyACM3 -hupcl

```

HUPCL means "HangUP on CLose".
> 3 votes

---
Tags: ftdi, reset
---


title: What is wrong with this code?

text:
# Question
Title: What is wrong with this code?
So I am writing code to control a servo with an RC radio. I am using an Arduino Mega. I get this error whenever I compile. I am not that experienced with Arduino so I am probably not doing something right. Thanks for the help!

> Arduino: 1.8.5 (Windows 10), Board: "Arduino/Genuino Mega or Mega 2560, ATmega2560 (Mega 2560)"
>
> C:\Users\ethan\Desktop\Periferals\_control\Periferals\_control.ino: In function 'void loop()':
>
> Periferals\_control:46: error: expected ';' before '{' token
>
> {
>
> ^
>
> exit status 1 expected ';' before '{' token
>
> This report would have more information with "Show verbose output during compilation" option enabled in File -\> Preferences.

```
#include <Servo.h>
Servo servo1;
Servo servo2;
//the following are all ~PWM capable ports
int servoElevator_PwmIn = 6; //Elevator Servo
int servoGrabber_PwmIn = 7; //Grabber Servo

//Channels on AT9
int leftStickVertical = 2; //Channel 3
int rightStickVertical = 3; //Channel 7

int elevatorServoStop = 50;

void setup() {

  //pinMode(servoGrabber_PwmIn, OUTPUT);
  //pinMode(servoElevator_PwmIn, OUTPUT);
  pinMode(leftStickVertical, INPUT);
  pinMode(rightStickVertical, INPUT);
  Serial.begin(9600);

  servo1.attach(6);
  servo2.attach(servoGrabber_PwmIn);
}

void loop() {

  int leftStickVerticalPwm = pulseIn(leftStickVertical, HIGH, 25000);
  int rightStickVerticalPwm = pulseIn(rightStickVertical, HIGH, 25000);
  Serial.print(leftStickVerticalPwm);
  Serial.print("\t");
  Serial.print(rightStickVerticalPwm);
  Serial.print("\n");

  if (rightStickVerticalPwm == 0)
  {
    servo1.write(elevatorServoStop);
  }
  else if (rightStickVerticalPwm > 1500)
  {
    servo1.write(100);
  }
  else (rightStickVerticalPwm < 1400)
  {
    servo1.write(30);
  }
}

```

# Answer
```
  if (rightStickVerticalPwm == 0)
  {
    servo1.write(elevatorServoStop);
  }
  else if (rightStickVerticalPwm > 1500)
  {
    servo1.write(100);
  }
  else (rightStickVerticalPwm < 1400)
  {
    servo1.write(30);
  }

```

You cannot have another comparison in an `else` statement. You might have meant `else if` in the last clause.

Clarification if you're not well familiar with C/C++: If you have an `if` statement, it can be followed by arbitrary many `else if` clauses and at maximum one `else` clause which will execute when all other conditions fail. For example:

```
 int a = 10;
 if( a == 9 ) {
       //Executed if a = 9
 } else if( a < 20 ) {
   //If above not executed, this will be executed if a < 20
 } else {
   //This is executed if none of the conditions above hold.
   //A pure "else" does not have a condition and only one may
   //exist in an `if` statement.
 }

```
> 4 votes

# Answer
you should not provide conditions for " else " statement because it focuses on what action should happen if all " if and else if " conditions are not fulfiiled.
> 1 votes

---
Tags: arduino-mega, pwm, remote-control, compilation-errors
---


# Question
Title: Unexpected value change of 2nd Potentiometer
I'm trying to connect 2 potentiometer (10k) and pass their value to Hairless Midi software (For Serial to Midi Bridge) the first pot is working fine but the second pot's value keep on changing and when i move around the knob of pot1 the value of pot 2 also changes.

I have tried reading the value twice but no luck....

My code:

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

void loop()
{
  analogRead(0);
   val = analogRead(0)/8;   // Divide by 8 to get range of 0-127 for midi
   if (val > lastVal+1 or val < lastVal+1 )
   {
   MIDImessage(176,1,val);}
   lastVal = val;

  analogRead(2);
   val2 = analogRead(2)/8;   // Divide by 8 to get range of 0-127 for midi
   if (val2 > lastVal2 + 1 or val2 < lastVal2 + 1 )
   {
   MIDImessage(176,2,val2);}         // 176 = CC command, 2 = Which Control, val = value read from Potentionmeter 2
   lastVal2 = val2;

   //val3 = analogRead(2)/8;   // Divide by 8 to get range of 0-127 for midi
   //if (val3 != lastVal3)
   //{
   //MIDImessage(176,3,val3);}         // 176 = CC command, 3 = Which Control, val = value read from Potentionmeter 3
   //lastVal3 = val3;

delay(100);
}

void MIDImessage(byte command, byte data1, byte data2) //pass values out through standard Midi Command
{
   Serial.write(command);
   Serial.write(data1);
   Serial.write(data2);
}

```

# Answer
As I was having chat with @Maxmilian Gerhardt he suggested to check the voltage of pot 2 so when I checked I was getting 0 volt So he Suggested me there may be a loose connection or something with the beadboard.

So This was a workaround :

Thnx for the help @Maxmilian Gerhardt
> 1 votes

---
Tags: potentiometer, midi, arduino-duemilanove
---


# Question
Title: Using Due (SAM3X8E) native USB port for programming?
I would like to make my own version of the Arduino Due.

What I can't find the answer to is; Can I program a blank SAM3X8E using the native USB port from within the Arduino IDE, or do I first need to program some bootloader or similar?

My board will not have the Mega16U2 which is normally used for programming.

# Answer
The SAM3X8E comes with a bootloader in ROM.

* Memories
    + 256 to 512 Kbytes embedded Flash, 128-bit wide access, memory accelerator, dual bank
    + 32 to 100 Kbytes embedded SRAM with dual banks
    + **16 Kbytes ROM with embedded bootloader routines (UART, USB) and IAP routines**
    + Static Memory Controller (SMC): SRAM, NOR, NAND support. NFC with 4 Kbyte RAM buffer and ECC

Since this bootloader does all that the Arduino IDE asks of it, and has a freely available cross-platform command-line upload tool (`bossac`) the IDE just uses that. No need to invent the wheel when the wheel does everything you need and even comes with a tin of axel grease.

While technically it is possible to use your own bootloader in conjunction with the existing one (use the existing one to install yours, and then use yours to upload sketches) it requires in-depth knowledge of both the chip and GCC linker ("ld") scripts to set aside a block of memory for your bootloader to reside in and relocate the compiled code around it properly. Too much work when the bootloader that already exists does what you want.

However other chips either don't have a bootloader (like the M0 in the Feather) or don't have one that works as desired (like the DFU bootloader in the ATMega32U4) so a custom bootloader is used on those.

The IDE itself is pretty dumb. It just has a configuration file that says "Execute this command with these parameters to upload the HEX file". It neither knows, nor cares, what the bootloader at the other end of the connection is, nor how it works. As long as there is a command-line executable to do the work it just hands over to it.
> 1 votes

# Answer
Microchips needs some kind of bootloader to be able programmed over USB. Arduino boards cames with default bootloader loaded (from Arduino company at least, net necesarry from Chine, probably without, if you byu just the chip from manufacturer), so on official boards it is all done for you to have aesy life.

Being able to properly communicate over USB is not exactly easy task and there are many different protocols for sending program to bootloader, which is then resposible to put the program at flash memory at proper place and give it controll later.

Also keep in mind, that there are other ways, how to put program in memory and that not all devices using some microcontroler are even meant to be programable by user over it. (For example they may idetyfy themself as keybords, mouses, joysticks and such to computer and be closed to reprogramming by manufactor of such device. Arduino community is only small part of industry, which uses the same chips for totally different tasks).
> -1 votes

---
Tags: arduino-due, bootloader, icsp
---


# Question
Title: Not getting proper readings on Arduino from MAP Sensor
In recent project, I have to take reading from MAP sensor. So basically, we used analog pin for this. But in my case, I don't get proper result which actually I want.

When I'm taking readings through multi-meter then I got proper readings. Means when I start the vehicle then it's show 0.99 V. When I provide full throttle then voltage also increase and it's reach to 1.66 V. And finally when suddenly come back to normal throttle then also voltage decrease around like 0.48 V and then within a second again show normal 0.99 V.

Here, when I'm taking readings from MAP sensor through multi-meter then I'm providing ground to multi-meter. And when I taking readings from MAP sensor through Arduino then I'm not providing any ground to Arduino. Because I think it may be damage my Arduino.

So, I think this is also one possibility and may be possible that's why I'm not getting that type of voltage output through Arduino.

Here, the ground which I provide to multi-meter is from 12V DC battery which is used in CNG Auto rickshaw. So, that's why I'm not providing ground to Arduino. So, give me some suggestions about this. What should I do for this. Providing ground to Arduino or not.

Here, it's my code.

```
int kMAP1 = 0;
float kMAP2 = 0;

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

void loop()
{
  kMAP1 = analogRead(A0);
  kMAP2 =  kMAP1 * (5.0 / 1023.0);

  Serial.print("MAP1: ");
  Serial.print(kMAP1);

  Serial.print("\t");

  Serial.print("      MAP2: ");
  Serial.println(kMAP2);

  delay(1000);
}

```

And it's my serial monitor output.

```
MAP1: 490         MAP2: 2.39
MAP1: 433         MAP2: 2.12
MAP1: 270         MAP2: 1.32
MAP1: 0           MAP2: 0.00
MAP1: 447         MAP2: 2.18
MAP1: 401         MAP2: 1.96
MAP1: 518         MAP2: 2.53
MAP1: 487         MAP2: 2.38
MAP1: 344         MAP2: 1.68
MAP1: 374         MAP2: 1.83
MAP1: 611         MAP2: 2.99
MAP1: 429         MAP2: 2.10
MAP1: 647         MAP2: 3.16
MAP1: 668         MAP2: 3.26
MAP1: 460         MAP2: 2.25
MAP1: 489         MAP2: 2.39
MAP1: 278         MAP2: 1.36
MAP1: 277         MAP2: 1.35
MAP1: 318         MAP2: 1.55
MAP1: 383         MAP2: 1.87
MAP1: 238         MAP2: 1.16
MAP1: 237         MAP2: 1.16
MAP1: 134         MAP2: 0.65
MAP1: 191         MAP2: 0.93
MAP1: 230         MAP2: 1.12
MAP1: 308         MAP2: 1.51
MAP1: 479         MAP2: 2.34
MAP1: 388         MAP2: 1.90
MAP1: 544         MAP2: 2.66
MAP1: 518         MAP2: 2.53
MAP1: 419         MAP2: 2.05
MAP1: 544         MAP2: 2.66
MAP1: 586         MAP2: 2.86
MAP1: 544         MAP2: 2.66
MAP1: 575         MAP2: 2.81
MAP1: 184         MAP2: 0.90
MAP1: 202         MAP2: 0.99
MAP1: 883         MAP2: 4.32
MAP1: 671         MAP2: 3.28
MAP1: 884         MAP2: 4.32
MAP1: 487         MAP2: 2.38
MAP1: 403         MAP2: 1.97
MAP1: 184         MAP2: 0.90
MAP1: 426         MAP2: 2.08
MAP1: 412         MAP2: 2.01
MAP1: 428         MAP2: 2.09
MAP1: 434         MAP2: 2.12
MAP1: 420         MAP2: 2.05
MAP1: 312         MAP2: 1.52
MAP1: 414         MAP2: 2.02
MAP1: 435         MAP2: 2.13
MAP1: 405         MAP2: 1.98
MAP1: 418         MAP2: 2.04
MAP1: 515         MAP2: 2.52
MAP1: 462         MAP2: 2.26
MAP1: 578         MAP2: 2.83
MAP1: 332         MAP2: 1.62
MAP1: 330         MAP2: 1.61
MAP1: 164         MAP2: 0.80
MAP1: 425         MAP2: 2.08
MAP1: 345         MAP2: 1.69
MAP1: 226         MAP2: 1.10
MAP1: 0           MAP2: 0.00
MAP1: 97          MAP2: 0.47
MAP1: 872         MAP2: 4.26
MAP1: 55          MAP2: 0.27
MAP1: 492         MAP2: 2.40
MAP1: 531         MAP2: 2.60
MAP1: 1023        MAP2: 5.00
MAP1: 43          MAP2: 0.21
MAP1: 6           MAP2: 0.03

```

# Answer
> 4 votes
The ground does need to be connected. I have also added a RC filter to stabilize the sensor reading.

Connection :

> Arduino 5V ----\> MAP Vcc
>
> Arduino GND ----\> MAP GND
>
> Arduino Analog Pin A0 \<---- RC Filter \<---- MAP Output pin

Using this connection, I get the proper readings.

Readings on Serial Monitor :

```
// When Vehicle not start //
MAP1: 376         MAP2: 1.84
MAP1: 376         MAP2: 1.84
MAP1: 376         MAP2: 1.84
MAP1: 376         MAP2: 1.84
MAP1: 376         MAP2: 1.84
MAP1: 376         MAP2: 1.84
MAP1: 376         MAP2: 1.84
MAP1: 376         MAP2: 1.84
MAP1: 376         MAP2: 1.84
MAP1: 376         MAP2: 1.84
MAP1: 376         MAP2: 1.84
MAP1: 376         MAP2: 1.84
MAP1: 376         MAP2: 1.84
MAP1: 376         MAP2: 1.84

//When start vehicle//
MAP1: 343         MAP2: 1.68
MAP1: 332         MAP2: 1.62
MAP1: 341         MAP2: 1.67
MAP1: 255         MAP2: 1.25
MAP1: 215         MAP2: 1.05
MAP1: 336         MAP2: 1.64
MAP1: 320         MAP2: 1.56
MAP1: 321         MAP2: 1.57
MAP1: 308         MAP2: 1.51
MAP1: 316         MAP2: 1.54
MAP1: 326         MAP2: 1.59
MAP1: 326         MAP2: 1.59
MAP1: 325         MAP2: 1.59
MAP1: 177         MAP2: 0.87
MAP1: 219         MAP2: 1.07
MAP1: 216         MAP2: 1.06
MAP1: 220         MAP2: 1.08
MAP1: 208         MAP2: 1.02
MAP1: 211         MAP2: 1.03

//Provide full throttle//
MAP1: 319         MAP2: 1.56
MAP1: 324         MAP2: 1.58
MAP1: 341         MAP2: 1.67
MAP1: 349         MAP2: 1.71
MAP1: 353         MAP2: 1.73
MAP1: 352         MAP2: 1.72
MAP1: 352         MAP2: 1.72
MAP1: 356         MAP2: 1.74
MAP1: 357         MAP2: 1.74
MAP1: 359         MAP2: 1.75
MAP1: 355         MAP2: 1.74
MAP1: 354         MAP2: 1.73
MAP1: 327         MAP2: 1.60

//Suddenly come back to normal throttle//
MAP1: 181         MAP2: 0.88
MAP1: 181         MAP2: 0.88
MAP1: 192         MAP2: 0.94
MAP1: 205         MAP2: 1.00
MAP1: 201         MAP2: 0.98
MAP1: 210         MAP2: 1.03
MAP1: 218         MAP2: 1.07
MAP1: 222         MAP2: 1.09

//Provide full throttle again//
MAP1: 309         MAP2: 1.51
MAP1: 375         MAP2: 1.83
MAP1: 395         MAP2: 1.93
MAP1: 376         MAP2: 1.84
MAP1: 261         MAP2: 1.28
MAP1: 360         MAP2: 1.76
MAP1: 307         MAP2: 1.50
MAP1: 361         MAP2: 1.76
MAP1: 259         MAP2: 1.27

//Suddenly back again normal throttle//
MAP1: 156         MAP2: 0.76

//Again provide full throttle//
MAP1: 295         MAP2: 1.44
MAP1: 267         MAP2: 1.30
MAP1: 287         MAP2: 1.40
MAP1: 372         MAP2: 1.82
MAP1: 380         MAP2: 1.86
MAP1: 375         MAP2: 1.83
MAP1: 229         MAP2: 1.12
MAP1: 359         MAP2: 1.75
MAP1: 339         MAP2: 1.66
MAP1: 337         MAP2: 1.65
MAP1: 359         MAP2: 1.75
MAP1: 344         MAP2: 1.68

//Again suddenly back to normal throttle//
MAP1: 121         MAP2: 0.59
MAP1: 164         MAP2: 0.80
MAP1: 202         MAP2: 0.99

//Again provide full throttle//
MAP1: 310         MAP2: 1.52
MAP1: 339         MAP2: 1.66
MAP1: 356         MAP2: 1.74
MAP1: 361         MAP2: 1.76
MAP1: 274         MAP2: 1.34

//Again suddenly back to normal throttle//
MAP1: 127         MAP2: 0.62
MAP1: 178         MAP2: 0.87
MAP1: 221         MAP2: 1.08
MAP1: 247         MAP2: 1.21
MAP1: 224         MAP2: 1.09

//Again provide full throttle//
MAP1: 292         MAP2: 1.43
MAP1: 278         MAP2: 1.36
MAP1: 265         MAP2: 1.30
MAP1: 367         MAP2: 1.79
MAP1: 328         MAP2: 1.60
MAP1: 358         MAP2: 1.75

//Again suddenly back to normal throttle//
MAP1: 182         MAP2: 0.89
MAP1: 174         MAP2: 0.85
MAP1: 242         MAP2: 1.18
MAP1: 253         MAP2: 1.24
MAP1: 261         MAP2: 1.28

//Vehicle stop//
MAP1: 307         MAP2: 1.50
MAP1: 360         MAP2: 1.76
MAP1: 375         MAP2: 1.83
MAP1: 375         MAP2: 1.83
MAP1: 375         MAP2: 1.83
MAP1: 376         MAP2: 1.84
MAP1: 375         MAP2: 1.83
MAP1: 375         MAP2: 1.83
MAP1: 376         MAP2: 1.84
MAP1: 376         MAP2: 1.84
MAP1: 377         MAP2: 1.84
MAP1: 377         MAP2: 1.84
MAP1: 377         MAP2: 1.84
MAP1: 377         MAP2: 1.84

```

# Answer
> 1 votes
Although the circuit isn't shown and description isn't perfectly clear, evidently there is some question about how to connect up the various grounds.

Voltage, being “the difference in electric potential energy between two points per unit electric charge” \[ref Voltage article in Wikipedia\], is measured between two points in an electric circuit. If the two points are in unrelated and isolated circuits meaningful measurements can't be taken.

In typical MAP sensor circuits, the sensor output is relative to automotive ground, so your Uno's analog ground should be connected to automotive ground. Whether this is electrically safe depends on several things:
• Sensor output voltage range – The multimeter readings showed a safe range. The range is narrow compared to the Uno ADC's default +5V range; if you want a bit or two more resolution, you could either set up a 2 V external ADC reference, or could amplify the sensor output up to a range of about 5 V, or could use a unity gain op amp circuit followed by a voltage divider to get into a 0-to-1.1 V range, and use the internal 1.1 V bandgap reference.
• Uno power supply ground voltage – If the Uno's supply is isolated, its ground can be connected to automotive ground with no problem. Or, if its supply ground already connects to automotive ground, no problem. Where a problem might occur is if you measure a large voltage between automotive ground and Uno ground. If so, connect a 100 Ω resistor between the two grounds and measure the voltage across it. If the voltage is near zero, you can connect the grounds or could leave them connected by a small resistor like that. If, on the other hand, some appreciable voltage appears across the resistor, or if it disappears in a puff of smoke, then they can't connect safely and you would need to use a different power supply for the Uno that doesn't have such a problem.
• Ground wire topology – The wiring path from Uno ground to automotive ground should not share any segments with high current devices. In normal operation, or in case of a load dump, several volts difference can arise between the ends of a piece of ground wire to a high current device.

# Answer
> 0 votes
I once used an arduino to check the map sensor on my ford f150. As an FYI, I will state that the ford map gave a digital pulse as output for the engine computer and was not analogue as the one you seem to be using. I'm only commenting here for others who might be having trouble with a MAP sensor, so that they realize that some give pulse outputs and not voltage outputs. So, I'm not sure about your map sensor, or turning the pulses into an average reading, but I simply used the interrupt to count pulses over a second and then recorded those readings over several minutes of drive time. (I was having intermittent engine stumbling and I was ruling out the various sensors as causing the trouble.) I was checking to make sure the MAP sensor didn't completely drop out from time to time. In the end, it was my ignition module giving out due to heat fatigue that was the problem. But, I can say that with a handful of resistors and a probe I was able to check all the sensors in the vehicle in short time...except for the oxygen sensor which I was afraid to damage due to its sensitivity.

---
Tags: arduino-uno, programming, arduino-ide, analogread
---


title: Arduino ISP external power

text:
# Question
Title: Arduino ISP external power
I want to program an atmega328p-pu via my arduino uno as ISP in a circuit.

I omitted my connected sensors, LCD, etc in the schematic to keep it simple.

When I power the circuit via a 5V power supply (left) I get

```
avrdude: AVR device initialized and ready to accept instructions

Reading | ################################################## | 100% 0.02s

avrdude: Device signature = 0x000000 (retrying)

Reading | ################################################## | 100% 0.02s

avrdude: Device signature = 0x000000 (retrying)

An error occurred while uploading the sketch
Reading | ################################################## | 100% 0.02s

avrdude: Device signature = 0x000000
avrdude: Yikes!  Invalid device signature.
         Double check connections and try again, or use -F to override
         this check.

avrdude done.  Thank you.

```

When powering off the circuit and connecting 5V and GND from the arduino to the power and gnd lines in my circuit everything works fine.

I connect 5V and GND from the arduino via pin headers I added to the 5V and GND rails in my circuit to power external sensors etc.

Is there a reason I apparently **have to** use power from the arduino?

# Answer
Even with an external supply, you must still have a common ground reference between the ATmega being programmed, and the Arduino/ATmega doing the programming. According to your comment this was the critical issue.

Also keep in mind that the specifications of most ICs including the ATmega prohibit applying signal voltages when the chip itself is unpowered. To stay within that specification, you would need to turn on the external supply first, and insure that all of the pins were in their high impedance state and not driving the programmer's ATmega when it is unpowered.

Your pullup resistor on the target's reset would weakly drive pin 10 on the programmer, but a 10K resistor should limit the current to within what the protection diode on the corresponding ATmega pin can tolerate (even such a weak current can however cause problems with clean startup, though the ATmega is less sensitive than some other devices).

If you can't be sure power is going to be applied correctly, putting 1K (maybe even 2.2K) series resistors between the two chips can help a little, but there's a balance between keeping the signals strong enough to work well, and keeping illicit currents weak enough to avoid stress.
> 2 votes

---
Tags: arduino-uno, atmega328, isp
---


# Question
Title: Measuring high frequencies (300kHz) with arduino
I'm designing a frequency generator with ICL8038, which would output sine, square and triangle waves, which would reach frequency such as 300kHz.

I've already designed a circuit around the ICL8038, but I'm unsure how to measure the frequency, to show on LCD display.

I'm leaving down a schematics I've drawn. A.Duty is going to the analog input of arduino, which will show the duty cycle between 2% and 98%. This will be going to a voltage divider to make a proportional input for the arduino analog input.

The "frequency pin" would be connected directly from the BNC connector from the casing, which means, that the input can be triangular, sine or square.

Just to mension, in case it makes any kind of difference, I'm planning to use just Atmega328 with 16MHz quartz and 2 capacitors, not exactly as Arduino UNO or NANO. But the Atmega will have a arduino bootloader on it.

By the time asking about ICL8038, I've got also few questions about the IC:

1. You connect the FM Bias(pin 7) and SWEEP (pin 8) together to create sweep on the output of any kind of signal, whichever it is? This is fixed time constant or should I add some kinda coapacitor there?
2. What exactly does Tcap (pin 10) does? I've read through the datasheet but couldn't understand it's meaning.
3. How would I get proper voltage range every time, when I would change the input voltage of the ICL8038? (it has wide range of output signal, proportionall to the input; it goes from 36V to input, 28V max output)
4. For power supply would be proper LM317 as adjustable power supply (since it has low power consumption) and just use a potentiometer to adjust input of the ICL8038 and monitor the OUTPUT levels?
5. PIn 13 and PIn 14 are NC (not connected). Can I just connect them together and connect them to GND?

As if anybody knows for any "better" IC as this one is, please let me know. I'm already going to have to buy it from China (this gives me doubts about the capabilities), I'd rather just order one from Europe or US.

# Answer
> -1 votes
To sample a 300kHz signal you need to sample at *at least* 600,000 samples per second (see Nyquist-Shannon Theorem).

The Arduino can sample at an absolute maximum of 125,000 samples per second.

A normal Arduino will not be able to sample the analog input fast enough to even remotely have a clue what the frequency is - let alone what shape the signal is (for that you would have to be sampling in the millions of samples per second).

You will need a much more powerful board than an Arduino to do it.

The other option is to feed the signal through a comparator (an op-amp with infinite gain) to convert the signal into a square wave. You can then use simple frequency counting to get the frequency (count the pulses within a given time frame - maybe 1 second).

As for the rest of your questions, you would be better off asking those on Electrical Engineering.

---
Tags: frequency
---


# Question
Title: I can't control my DC motors speed with analogWrite()
I have Arduino Uno and I attached it to 2 DC motors with L298N bridge. I want to control the speed of the motors so they don't move at maximum speed. I use `analogWrite()` but it does nothing,and the motors move at maximum speed

Here is my code:

```
//motor A
int enA = 9;
int in1 = 8;
int in2 = 7;

//motor B
int enB = 3;
int in3 = 5;
int in4 = 4;

void setup() {
  Serial.begin(9600);
  pinMode(enA, OUTPUT);
  pinMode(in1, OUTPUT);
  pinMode(in2, OUTPUT);
  pinMode(enB, OUTPUT);
  pinMode(in3, OUTPUT);
  pinMode(in4, OUTPUT);
}

void loop() {

  analogWrite(enA, 0);

  analogWrite(enB, 0);

  digitalWrite (in1, HIGH);
  digitalWrite (in3, HIGH);
  digitalWrite (in2, LOW);
  digitalWrite (in4, LOW);

  delay(50);
}

```

# Answer
> 2 votes
I did find solutions for the problem. It turned out that the bridge does not work as it should be and the pins of en(A,B) is replaced with the in pins ..now I can control the speed but can't reverse the direction of the motors

# Answer
> 1 votes
analogWrite() can take values between **0** and **255** as its second parameter. Where 255 will give you the maximum motor speed and 0 will give you the lowest (motor will not run).

For example, below code will give you almost the half of max speed.

```
analogWrite(enA, 128);
analogWrite(enB, 128);

```

---
Tags: arduino-uno, motor, pwm, analogwrite
---


# Question
Title: Crosses Initialization in switch case with different size of array per case
```
void setup()  {
 Serial.begin(9600);
}

void loop()
{
 time_Text(2);
}

void time_Text(int PastTo_val) {
  switch (PastTo_val) {
   case 1:
   {
    int tPTT_y[] = {11, 11, 11, 11};
    int tPTT_x[] = {6, 7, 8, 9};
  }
  break;
case 2:
  {
    int tPTT_y[] = {11, 11};
    int tPTT_x[] = {10, 11};
  }
  break;
 }

 int n_tPTT = sizeof(tPTT_x) / sizeof(tPTT_x[0]);

 Serial.print(tPPT_y);
 Serial.print(" : ");
 Serial.print(tPPT_x);
 Serial.print(" : ");
 Serial.println(n_tPPT);

}

```

I have a case that I need to assign different kind of array value (with different size per case), and then find the size of the array, and print it. The problem is that the `tPTT_y` and `tPTT_x` is a local variable which cannot be accessed outside of the case function. I have tried to declare it before the switch function but I cannot give a size number because the size is different per case, how could I solve this?

# Answer
> 1 votes
Create two global arrays that contain the maximum amount of number you ever need, e.g.

```
int tPTT_x[4];
int tPTT_y[4];

```

Than create one global int that contains how much x and y are filled, e.g.

```
int filled;

```

Than you can change your cases to

```
void time_Text(int PastTo_val) {
  switch (PastTo_val) {
   case 1:
   {
    tPTT_y[0] = 11;
    tPTT_y[1] = 11;
    tPTT_y[2] = 11;
    tPTT_y[3] = 11;
    tPTT_x[0] = 6;
    tPTT_x[1] = 7;
    tPTT_x[2] = 8;
    tPTT_x[3] = 9;
    filled = 4;
  }
  break;
case 2:
  {
    tPTT_y[0] = 11;
    tPTT_y[1] = 11;
    tPTT_x[0] = 10;
    tPTT_x[1] = 11;
    filled = 2;
  }
  break;
 }

```

Than you can use the 'filled' variable to see how many items in the array are 'valid' (0 \<= item \< filled).

# Answer
> 1 votes
Just create a buffer of a maximum value and copy in the value you want while remembering the length of the array.

```
#define MAX_ARR_LENGTH (4)

void time_Text(int PastTo_val) {
    int tPTT_x[MAX_ARR_LENGTH];
    int tPTT_y[MAX_ARR_LENGTH];

    const int tptt_y_case_1[] = {11, 11, 11, 11};
    const int tptt_x_case_1[] = {6, 7, 8, 9};
    const int tptt_y_case_2[] = {11, 11};
    const int tptt_x_case_2[] = {10, 11};

    int filled = 0;

    switch (PastTo_val) {
    case 1:
    {
        memcpy(tPTT_x, tptt_x_case_1, sizeof(tptt_x_case_1));
        memcpy(tPTT_y, tptt_y_case_1, sizeof(tptt_y_case_1));
        filled = 4;
    }
    break;
    case 2:
    {
        memcpy(tPTT_x, tptt_x_case_2, sizeof(tptt_x_case_2));
        memcpy(tPTT_y, tptt_y_case_2, sizeof(tptt_y_case_2));
        filled = 2;
    }
    break;
    }

    Serial.println("Printing array values");
    for(int i=0; i < filled; i++) {
        Serial.println("tPPT_x["+ String(i) +"] = " + String(tPTT_x[i]));
        Serial.println("tPPT_y["+ String(i) +"] = " + String(tPTT_y[i]));
    }
}

```

Depending on whether you need to modify the memory you can also just point to constant memory and remember the length.

```
void time_Text(int PastTo_val) {
    const int* tPTT_x;  //Pointers to the values
    const int* tPTT_y;

    //You make also add "static" if you want to reference this
    //data beyond the scope of the function
    const int tptt_y_case_1[] = {11, 11, 11, 11};
    const int tptt_x_case_1[] = {6, 7, 8, 9};
    const int tptt_y_case_2[] = {11, 11};
    const int tptt_x_case_2[] = {10, 11};

    int filled = 0; //number of elements

    switch (PastTo_val) {
    case 1:
    {
        tPTT_x = (const int*) tptt_x_case_1;
        tPTT_y = (const int*) tptt_y_case_1;
        filled = 4;
    }
    break;
    case 2:
    {
        tPTT_x = (const int*) tptt_x_case_2;
        tPTT_y = (const int*) tptt_y_case_2;
        filled = 2;
    }
    break;
    }

    Serial.println("Printing array values");
    for(int i=0; i < filled; i++) {
        Serial.println("tPPT_x["+ String(i) +"] = " + String(tPTT_x[i]));
        Serial.println("tPPT_y["+ String(i) +"] = " + String(tPTT_y[i]));
    }
}

```

---
Tags: programming, array, switch
---


title: Encoders for precise robot turns

text:
# Question
Title: Encoders for precise robot turns
So I recently purchased:

DFRobot Wheel Encoders

DFRobot 3PA and 4WD Rovers (2pk)

Romeo V2 Arduino Controller

I was doing a bit of research online and I'm trying to figure out how to use the encoders to control the PWM applied to the motors which will make precise turns. This seems like a popular method to use. Here is some of my code. I have nothing for the encoders yet. I only have the sensors working the PWM control for the motors. All my code does is stop the motors when the front sensor detects a wall. My next step is to implement the encoders to give the robot a 90 degree turn. Does anyone have some sample code or tips on how to do this? Thanks in advanced!

```
  void stop(void)
    {
      digitalWrite(5,LOW);
      digitalWrite(6,LOW);

    }
    void forward(char a,char b)
    {
      analogWrite(5,a);
      digitalWrite(4,HIGH);
      analogWrite(6,b);
      digitalWrite(7,HIGH);

    }
    void back(char a,char b)
    {
      analogWrite(5,a);
      digitalWrite(4,LOW);
      analogWrite(6,b);
      digitalWrite(7,LOW);

    }
    void Left(char a,char b)
    {
      analogWrite (5,a);
      digitalWrite(4,LOW);
      analogWrite (6,b);
      digitalWrite(7,HIGH);

    }
    void Right(char a,char b)
    {
      analogWrite (5,a);
      digitalWrite(4,HIGH);
      analogWrite (6,b);
      digitalWrite(7,LOW);

    }
    void setup(void)
    {

      pinMode(buttonPin2, INPUT);
      pinMode(buttonPin3, INPUT);
      for(int i =4;i<=7;i++)
        pinMode(i, OUTPUT);
      pinMode(LED_BUILTIN, OUTPUT);
     forward(100,100);

      Serial.begin(9600);

    }
void GetSensor()
{

  Sen_Val_B = SenAvg(Sensor_Back);
  Sen_Val_F = SenAvg(Sensor_Front);
  Sen_Val_R = SenAvg(Sensor_Right);
  Sen_Val_L = SenAvg(Sensor_Left);

}

int SenAvg(int SensorNumber)
{

  Arr[100]= 0;
  avg = 0;

  for(int i = 0; i<100; i++)
  {
    Arr[i] = analogRead(SensorNumber);
    avg = avg + Arr[i];
  }
    avg = avg/100;
    return avg;
}
void loop(void)
{

   GetSensor();
  if(Sen_Val_F > 200)
  {
   stop();
  }

}

```

# Answer
What encoders do is give you clocked feedback on motor rotation, which you can count to get an idea of position and speed. So in order to turn by a specified amount, you will need to know how much your wheel has to turn for the given angle. You can then turn the wheel precisely by dividing your wheel circumference with the maximum encoder ticks per revolution.

Say we get 600 ticks per revolution and our wheel has a circumference of 10cm. We would then turn the wheel by `100mm / 600 = 0,16mm` per encoder tick!

You could even write a function taking more parameters into account (robot diameter/distance between wheels) that calculates these values. A faster/more empirical approach than gathering all these values is to just drive your robot for x (i.e. 100) ticks and measure the angle it drove to get a direct relation between encoder ticks and robot angle.

Another, much more precise solution would be to utilize a compass or gyroscope to measure the robot's orientation and rely on that instead of the encoders.
> 1 votes

# Answer
> All my code does is stop the motors when the front sensor detects a wall. My next step is to implement the encoders to give the robot a 90 degree turn.

would this work?

```
  if (wall_sensed()) turn_90right(); //if wall is sensed, turn 90 degrees to the right

```

You may also consider change

```
  digitalWrite(5,LOW);
  digitalWrite(6,LOW);

```

to:

```
  digitalWrite(MOTOR_LF,STOP);   //stop left front motor
  digitalWrite(MOTOR_LR,STOP);   //stop left right motor

```

so that

1. it is a lot more readable; and
2. if you were to change pin assignment, it is done consistently throughout your code.
> 0 votes

---
Tags: pwm, arduino-leonardo, rotary-encoder
---


# Question
Title: Why does this array have stored values in it even though I have not put any values in it?
```
void alarm() {
  char keypressed4;
  char keypressed5;
  char keypressed6;
  char keypressed7;
  char disarmcode1[5];
  Serial.println("hi2");
  Serial.println(disarmcode1);

```

The array gets declared here and I print the values in the empty array. In the serial monitor I read this:

```
hi2
"c

```

I don't know why or how these values get put into the array. I have code later on that puts values into the array, but from where that point in the code is, no values should be in the array

Also I have an LCD screen hooked up too, and it prints a value of 0 at (2, 0).

# Answer
> 5 votes
The values haven't been "put" in the array. The array has been located in memory where those values (left over from some earlier operation, possibly as part of a function's stack frame) happen to be.

The simple fact that you *haven't* put anything in there means that what was there before hasn't been changed.

# Answer
> 2 votes
local arrays are not initialized. Reading uninitialized values is Undefined Behavior.

Practically this means that when read they will interpret the bytes at their memory location as values which can result in anything.

# Answer
> 1 votes
Ad to existing answers, while the default behavior of reading unassigned non-instance and non-static memory (e.g. local array) is *undefined*, you can use slightly different C++ declaration which is *defined* as initialized to all zeroes:

```
char disarmcode1[5] = {};

```

or in pure C

```
char disarmcode1[5] = {0};

```

---
Tags: array
---


# Question
Title: Have I fried the voltage input on my Arduino Nano?
I tried using my Arduino Nano in a circuit, switched on power to the circuit and heard a crack and smelt a bit of burning - something shorted.

I have plugged my Arduino into my PC with a USB, the light comes on - it's detected by my PC, so it's not fried completely.

However, when I try powering the Arduino with a 12V 2A wall adaptor (it was working with that before) no lights. Is it possible I somehow fried the voltage input or ground pins - or the voltage regulator (if it has one)?

# Answer
> 0 votes
12V, 2A through a shorted LDO? Yes. It's toast, or something else in the power path (diode?) is toast.

If you are good at soldering you could maybe replace the component, but probably easier to just use a 5v supply instead.

---
Tags: pins, voltage
---