title: How avoid TCP packet fragmentation?

text:
# Question
Title: How avoid TCP packet fragmentation?
I'm using an Arduino Uno with an Ethernet Shield and the arduino.cc Ethernet library for a custom TCP-based message-exchanging chat-like protocol. Specifically I'm using the Client class with its `print()` and `println()` methods. It works.

But on each single `print()` or `println()` call a whole TCP packet is sent. Also if just one byte is printed, a whole TCP packet is sent over the IP layer. I mean there's a lot of TCP packets with very few data inside. In other words there's a big overhead.

For example take this message that my Arduino successfully sends and my server successfully receives:

```
i-am EEEEEEEE-EEEEEEEE-EEEEEEEE-EEEEEEEE\r\n

```

The code is the following:

```
stream.print("i-am");
stream.print(' ');
for (byte i = 0 ; i < SERIAL_CODE_LENGTH ; i++){
  if (  i % 4 == 0 && i != 0 ){
    stream.print('-');
  }
  if (serialCode[i] < 16){
    stream.print('0');
  }
  stream.print(serialCode[i], HEX);
}
stream.println();

```

All that `EE` are hexadecimal byte values from an array and they are fine. But I can see from Wireshark that **those 42 bytes** (that could be fit in a single packet) **are sent in 22 TCP packets** (one for each `print` call in my code)!

**How can I avoid this fragmentation? Is there a way to use an hardware or software buffer to group data before to send (Nagle's algorithm)?**

With other SDKs the data are buffered by default and they're sent when the buffer is full or when an explicit "push" or "flush" call occurs. I checked Client `flush` method and it looks to be a different beast...

# Answer
Finally I managed to derive the EthernetClient class to override the write method and to add a sendNow method. In this way I still can:

1. Use any print method version simply by inheritance;
2. Pass the BufferedEthernetClient objects to function taking generalized Stream references (functions that can be used also with Serial, Wire, SD...).

---

## Code

```
#define BUFFER_SIZE 64

class BufferedEthernetClient : public EthernetClient {
  public:
    BufferedEthernetClient();
    virtual size_t write(const uint8_t *buf, size_t size);
    virtual void sendNow();
  private:
    byte buffer[BUFFER_SIZE];
    byte bufferCount;
};

BufferedEthernetClient::BufferedEthernetClient(){
  bufferCount = 0;
}

size_t BufferedEthernetClient::write(const uint8_t *buf, size_t size){
  for (size_t i = 0; i < size; i++){
    buffer[bufferCount] = *(buf + i);
    bufferCount++;
    if (bufferCount >= BUFFER_SIZE){
      sendNow();
    }
  }
  return size;
}

void BufferedEthernetClient::sendNow(){
  if (bufferCount){
    bufferCount -= EthernetClient::write(buffer, bufferCount);
  }
}

```

## Example

I use it in this way:

```
void printSerialCode(Stream & stream){
  for (byte i = 0 ; i < SERIAL_CODE_LENGTH ; i++){
    if (  i % 4 == 0 && i != 0 ){
      stream.print('-');
    }
    if (serialCode[i] < 16){
      stream.print("0");
    }
    stream.print(serialCode[i], HEX);
  }
}

BufferedEthernetClient client;
...
client.print("i-am");
client.print(' ');
printSerialCode(client);
client.println();
client.sendNow();

```
> 0 votes

# Answer
I suspect its `stream.print()` that is causing the problem. Write the data into a string and then use a SINGLE call to `stream.print()` to send the data. It looks like it is trying to send it as soon as possible to prevent delays and this is what is causing fragmentation..
> 0 votes

# Answer
Instead of this, you can join strings into one string by separating with a sign (i.e."-") and then split it into array elements
> 0 votes

---
Tags: tcpip
---


title: Resistor pull-ups for ESP8266

text:
# Question
Title: Resistor pull-ups for ESP8266
I'm using 4.7kOhm resistor as pullups for GPIOs 2,0,2,16, CH\_PD and RESET, and also 4.7kOhm pulldown for GPIO 15. The ESP8266 boots and works fine. Would it be okay for a long shot? Should I use 10kOhm instead of 4.7kOhm?

# Answer
> 12 votes
In general it makes little or no difference what the value of resistor you use is.

The only things it can affect are:

* The current consumption while a button is pressed - a lower value resistor will cause more current to flow while for the time the button is pressed (it makes no difference at other times).
* The LOW voltage (VIL) read at the IO pin if the button has a high resistance (for example if it's on the end of a 500m length of cable).
* Noise immunity - a lower value resistor will pull the pin up "harder" making it more difficult for noise induced in a long wire (see the previous point, too) from causing a false button press (although this is less of a concern with modern digital inputs that tend to all have Schmitt triggers).

10k is often chosen not because it's "better" than any other value, but purely because it's more common that many other values, and it's in the right kind of ball-park for most setups. It's low enough to give good noise immunity while being high enough to not cause undue current flow while the button is pressed. But more importantly, it's a resistor that everyone has in their kit, and is most likely the most common resistor used in a number of other places in the circuit as well. It's a good all-rounder as far as resistors go.

To take a closer look at the current flow aspect - if you are running (as with an ESP8266) at 3.3V and you have a 10k resistor the current flow, when the button is pressed and the resistor connected directly to ground, though the resistor would be (I=V/R) 3.3/10,000 = 330uA. If you used a 4.7k resistor (as you are doing at the moment) the current rises to 3.3/4,700 = 702uA. Yes, that's just over double the current, but twice peantus is still peanuts. So 4.7k, under most general circumstances, is perfectly fine.

However if power consumption is a real concern and you want to keep all consumption to an absolute minimum switching to 100k (as you often see in low-power circuits) would be beneficial, since 3.3/100,000 is 33uA.

If your input is connected to a momentary button which will be pressed for fractions of a second at a time it's not that much of an issue. But if the input is connected to a switch that could be activated for days or weeks at a time it obviously becomes of greater interest.

So in short: when running on batteries higher value pullup resistors are better, but when running off a power supply it really makes no difference.

---
Tags: esp8266, resistor, pull-up
---


title: Read from serial monitor till timeout

text:
# Question
Title: Read from serial monitor till timeout
Is is possible to read from serial window till timeout?

Actually, what I am looking for is a function that reads from serial monitor, and if no data is available in serial monitor, then it should wait for some time and if still no data is arrived it should return.

Something like,

```
Serial.read(int timeout);

```

# Answer
> 2 votes
Use this:

```
byte x;
if (Serial.available() > 0) {
  x = Serial.read();
  }

```

This doesn't block, because you only read when there is something available in the input buffer.

Now, if you want to read an integer with time-out the serial input, this is a short demo:

```
#define TIME_OUT 10000L
void setup()
{
    Serial.begin(9600);

    while(!Serial);

    Serial.println();

    Serial.println("Input an int (waiting for 60 seconds");
}

void loop()
{
    static unsigned long timeLastInput = 0;
    unsigned long now = millis();
    static char buffer[10];
    static int index = 0;
    int value;

    if(Serial.available() > 0) {
        char x = Serial.read();
        timeLastInput = now;

        if(isDigit(x)) {
            buffer[index++] = x;
        } else {
            if(index > 0) {
                buffer[index] = 0;
                value = atoi(buffer);
                Serial.print("Integer=");
                Serial.println(value);
                index = 0;
            }
        }
    }

    if(now - timeLastInput > TIME_OUT) {
        Serial.println("Time out");
        index = 0;
        timeLastInput = now;
    }
}

```

It works by reading all digits into buffer. A non digit input signal the end of the integer. We use `atoi` to convert the integer ascii representation in his binary value. The result you wants is stored in the `value` variable.

Note that we read only one char at the time in each loop pass.

And this how the output looks:

And remember: code doesn't manage any error condition; is up to you.

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


title: RX/TX not working as intended

text:
# Question
Title: RX/TX not working as intended
I am currently working on a project with a HC-06 module. I hooked it up accordingly like so:

```
Arduino -> HC-06
5V -> VCC
GND -> GND
TX -> RX
RX -> TX

```

and I ran this code:

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

void loop() {
   Serial.print("test");
   Serial.print("\n");

}

```

Strangely enough that does not work at all. When I am using neither with or without PC as the power source. When I am using SoftwareSerial like this it works like a charm:

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

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

void loop() {

   mySerial.print("test");
   mySerial.print("\n");

}

```

Can someone please explain why and of course how to fix that?

# Answer
You are using a Leonardo. Pins 0/1 aren't `Serial`, they're `Serial1`. `Serial` is the built-in USB connection.

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

void loop() {
   Serial1.print("test");
   Serial1.print("\n");

}

```
> 1 votes

---
Tags: serial, bluetooth, arduino-leonardo
---


title: ArduinoJson buffer gets overwritten

text:
# Question
Title: ArduinoJson buffer gets overwritten
I have not that much experience with native languages like c/c++ and I'm facing a strange issue, which drives me crazy. So I'm using an Wemos D1 mini (ESP8266) which uses a class calles `ConfigManager` to read a configuration file from eeprom. The config file is formatted as json, so I'm using ArduinoJson to parse the content. I have declared a `StaticJsonBuffer` and pointer to a `JsonObject` in the header, like you can see in the code example:

```
//FILE: ConfigManager.h
#ifndef ConfigManager_H
#define ConfigManager_H

#include <Arduino.h>
#include <ArduinoJson.h>
#include <FS.h>
#include "Logger.h"

class ConfigManager {
public:

    Settings *settings;

    ConfigManager();

    void read_from_eeprom();

private:

    File configFile;
    JsonObject *json;
    StaticJsonBuffer<200> jsonBuffer;

    void open_file(const char *permission);

    void read_json();

    void recreate_file();

    void create_json();

    void check_success();

    void populate_settings();

    void clean_up();
};

#endif

```

When the function `read_from_eeprom` is invoked, it opens the file and invokes the function`read_json`:

```
void ConfigManager::read_json() {
    size_t size = configFile.size();
    Log.verbose("[ConfigManager] Config file size: %d", size);

    std::unique_ptr<char[]> buf(new char[size]);
    configFile.readBytes(buf.get(), size);
    Log.verbose("[ConfigManager] File content: %s", buf.get());

    Log.verbose("[ConfigManager] Parsing json");
    json = &jsonBuffer.parseObject(buf.get());

    Log.notice("[ConfigManager] Json is:");
    json->printTo(Serial);
    Serial.println();
}

```

Which is followed by a call to `check_success()`

```
void ConfigManager::check_success() {
    Log.notice("[ConfigManager] Json is:");
    json->printTo(Serial);
    Serial.println();

    bool should_recreate = true;
    if (json->success()) {
        Log.notice("[ConfigManager] Parsed json successfully");

        auto version = json->get<const char*>("version");
        if (version) {
            if (strcmp(version, Settings::current_version) == 0) {
                Log.notice("[ConfigManager] Config version is up2date");
                should_recreate = false;
            } else {
                Log.warning("[ConfigManager] Config version outdated");
            }
        } else {
            Log.warning("[ConfigManager] Invalid config file");
        }
    } else {
        Log.warning("[ConfigManager] Config file is not valid json");
    }

    if (should_recreate) {
        Log.notice("[ConfigManager] Recreating config file");
        recreate_file();
        create_json();
    }

    Log.notice("JSON IS: ");
    json->prettyPrintTo(Serial);

    Log.notice("[ConfigManager] Sucessfully read json");
}

```

So what I noticed is that the file content is fine. E.g. `{"version":"0.2","led_count":"64"}`.

Then the json is parsed, which succeeds and logs the json object, which is again `{"version":"0.2","led_count":"64"}`.

Afterwards the function returns, and calls `check_success`, which again prints the content of the json object to the log, but this time it seems that something has overwritten the JsonBuffer, which causes the json object to be corrupted. This time the logged content is `{"v␂":"0.2","led_count":"64"}` (with some strange unicorn characters that change as the source code changes). I'm trying to figure out whats going on for many hours now, but I'm stuck. Can someone please point me in the right direction to solve this problem? Thank you!

# Answer
> 2 votes
the ArduinoJson library doesn't copy the strings, it only stores pointers and writes terminating zeros into input buffer. And your buffer buf is disposed by std::unique\_ptr at the end of read\_json() function

---
Tags: esp8266, c++, eeprom
---


title: ATtiny84 vs ATtiny85 consumption

text:
# Question
Title: ATtiny84 vs ATtiny85 consumption
I'm doing a comparative study between ATtiny84 and ATtiny85, and I found from the datasheet that ATtiny84 consumes less current, is that normal even if it is bigger in terms of size and number of pins? Am i wrong?

# Answer
There are wide differences in power usage in AVR parts. Typically the "P" variants (for "picopower") are more optimized for low power usage, but there are also differences between different revs of the same part (for example the ATMEGA168PB uses slightly more power than the ATMEGA168PA during sleep) presumably becuase of different processes used to make the chips.

If you are looking for the lowest power possible, it will depend on how your application. Do you spend most time running at full speed? Power down? Do you need a realtime-clock?

Don't forget about the ATXMEGA parts- they have some that have very low power when running a real-time clock from the internal "ultra-low power" oscillator.
> 0 votes

---
Tags: arduino-uno, serial, programming, attiny, data
---


# Question
Title: Is it possible to add an additional board on Arduino Web Editor (create.arduino.cc)?
I'm using a board that can be programmed via Arduino IDE (a NodeMCU with ESP8266) and I've configured the Windows client successfully. I've added an additional board through "Preferences" menu by specifying its configuration url, following manufacturer's directions.

Now, I'm quite happy with the web editor, the one at create.arduino.cc, and I'd like to use it with this board too. Is there any way to configure additional boards?

# Answer
> 1 votes
No, there isn't.

The web editor is completely closed. It's a service run by Arduino, and as such it will only support Arduino's own boards.

Two reasons:

1. Why should they spend the time, effort and money adding support for other people's products?
2. It adds value to their products to encourage you to use real Ardiuno hardware.

Business is business, after all.

---
Tags: arduino-ide
---


# Question
Title: At dimming = 128, suddenly voltage goes up to 240 volt and then back to 0 volt
**While using dimmer circuit with esp8266, at dimming = 128, suddenly voltage goes up to 240 volt and then back to 0 volt. at the output inductive load is connected like TABLE FAN** , it has not any type of adapter, its AC line device.

where, the dimming range is 0-128 . 0=ON (no power clipping) means load should be ON. 128=OFF means load should be OFF.

1. Is this happens with dimmer circuit normally while load connected \[TABLE FAN\] or I am doing something wrong?
2. Also , can we use this value(128) for switching purpose? --means whenever we put the dimming=128 the load will be stay OFF,and power consumption stops towards load, as switch works.

i am newbie and trying esp8266 dimmer for first time.

here , the line voltage is 230-240 volts AC, 50Hz power supply .

I am referring this circuit as it is and code also, only the change is dimming value taken using serial communication

here i am using inductive load (TABLE FAN).

\`

```
  const int interruptPin = 14;
int AC_LOAD = 4;    // Output to Opto Triac pin
int dimming = 128;  // Dimming level (0-128)  0 = ON, 128 = OFF

void setup()
{
  Serial.begin(115200);
  pinMode(AC_LOAD, OUTPUT);// Set AC Load pin as output
  pinMode(interruptPin, INPUT_PULLUP);
  attachInterrupt(digitalPinToInterrupt(interruptPin), zero_crosss_int, RISING);  // Choose the zero cross interrupt # from the table above
}

//the interrupt function must take no parameters and return nothing
void zero_crosss_int()  //function to be fired at the zero crossing to dim the light
{
  // Firing angle calculation : 1 full 50Hz wave =1/50=20ms
  // Every zerocrossing thus: (50Hz)-> 10ms (1/2 Cycle)
  // 10ms=10000us
  // (10000us - 10us) / 128 = 75 (Approx)

  int dimtime = (75 * dimming);  // For 60Hz =>65
  delayMicroseconds(dimtime);    // Wait till firing the TRIAC
  digitalWrite(AC_LOAD, HIGH);   // Fire the TRIAC
  delayMicroseconds(10);         // triac On propogation delay
  // (for 60Hz use 8.33) Some Triacs need a longer period
  digitalWrite(AC_LOAD, LOW);    // No longer trigger the TRIAC (the next zero crossing will swith it off) TRIAC
}

void loop()  {

   dimming = Serial.read(); // dimming value is taken from serial for
                               dimming the load

}`

```

# Answer
```
int dimming = 128;  // Dimming level (0-128)  0 = ON, 128 = OFF

```

The code comments explicitly tell you that the range is 0-128; while non-trivial to do safely, digging out a scope to understand what exactly happens on overflow could be interesting (for example, it may skip alternate half cycles), but the obvious solution is to never command values outside that range, and *clamp* any out-of-range values which might be requested over the serial port to the limits.

Given that the timing is done unreliably in software, the precise phase behavior of your zero cross detector may be different than the original author's and the line frequency and pulse width constants may or may not be correct for your location, it's not really surprising that you are seeing 128 fall outside the limit of proper behavior rather than just within it. Likely you want to be conservative in what you allow.

To avoid inconcistency, even better than clamping the maximum value, you may simply want to treat everything above a chosen delay limit as an absolute "off" by simply finishing the ISR immediately without firing the triac at all. This may prove a lot simpler than trying to reliably find a delay limit that is "almost entirely" off without sometimes slipping over to firing right at the start of the next half cycle - and who really uses the "barely even on" range anyway?

Technically, depending on what the actual memory access width and alignment rules of the ESP8266 are, the sharing of a potentially non-atomic variable between the main and interrupt contexts could cause a **one time** glitch when it is changed (though even that is unlikely for your expected range of values, especially if you do the limiting before assignment to the shared variable). However, the atomicity concern can be simply remedied by using a `volatile unsigned char` (or more portably including `stdint.h` and using a `volatile uint8_t`) as the shared variable. The `volatile` keyword is used to require that the compiler actually calculate a variable that may not appear to be used, and actually store it in memory rather than merely cache it in a register.

It's worth noting that the software timed dimming, while somewhat portable is not particularly reliable, and may at high degrees of delay mean the processor spends almost all of its time in the ISR. For this reason it is generally better to use a hardware timer for this purpose, however that then becomes more chip-specific. If you are hoping to have things life WiFi running on your ESP8266 at the same time, you'll almost certainly want to move to a hardware timer to avoid glitching.

Ultimately it seems that the tutorial your are following is a poor one, such that doing a complete from-scratch reimplementation would be wise. Additionally, mains-powered dimming circuits present many safety and reliability concerns even when driving a lightbulb - and it is by no means clear that your triac and snubber circuit are safe to use with an inductive load. This is a challenging project, and not necessarily an *appropriate* one to attempt without deep experience. You might want to consider using a DC fan PWM-controlled from a well-engineered low-voltage power supply instead.
> 1 votes

---
Tags: esp8266
---


title: Why my ISR is giving impossible values?

text:
# Question
Title: Why my ISR is giving impossible values?
I have a very simple ISR:

```
const uint32_t PATTERN_A = 0xFF00FF00;
const uint32_t PATTERN_B = 0x00FF00FF;
volatile uint32_t count = 0;
volatile uint32_t toggle = PATTERN_A;

// My ISR
void callback()
{
    count++;
    toggle = (count % 2) ? PATTERN_A : PATTERN_B;
}

```

The idea is that the `toggle` variable takes values 0xFF00FF00 or 0xFF00FF00 depending on the evenness of the `count` variable. This is the only place where `toggle` is changed, but it's used (read-only) in the sketch.

I don't know why, but `toggle` gets all sort of random values during execution.

What is happening here?

# Answer
The problem is a combination of several causes.

**Assignments are not atomic**

An *atomic* operation is something that is completely done or not. The opposite is some operation that can be disrupted while executing, leaving thing in a inconsistent state.

This is how the `count++` works at machine level in Arduino:

```
void callback()
{
    count++;
  fa:   80 91 0a 02     lds r24, 0x020A
  fe:   90 91 0b 02     lds r25, 0x020B
 102:   a0 91 0c 02     lds r26, 0x020C
 106:   b0 91 0d 02     lds r27, 0x020D
 10a:   01 96           adiw    r24, 0x01   ; 1
 10c:   a1 1d           adc r26, r1
 10e:   b1 1d           adc r27, r1
 110:   80 93 0a 02     sts 0x020A, r24
 114:   90 93 0b 02     sts 0x020B, r25
 118:   a0 93 0c 02     sts 0x020C, r26
 11c:   b0 93 0d 02     sts 0x020D, r27

```

The first four instruction loads the four `count` bytes into four separate register, the laboriously increment it by one and then store it back in RAM.

Now, `toggle` is a variable of interest and you want to use it inside `loop`, like this:

```
void loop()
{
    uint32_t x = toggle;
    ...
}

```

And at machine level you get

```
    uint32_t x = toggle;
 414:   60 91 04 01     lds r22, 0x0104
 418:   70 91 05 01     lds r23, 0x0105
 41c:   80 91 06 01     lds r24, 0x0106
 420:   90 91 07 01     lds r25, 0x0107

```

Here we are simply copying the `toggle` variable into our `x` variable. As you can see, the copy takes four machine instructions to get completed.

Now, what happens if an interrupt comes while you are copying (or using) `toggle`?

An interrupt suspend the assignment, go to the ISR (`callback` in this case and change `toggle` value. Upon return, copying continues, mixing bytes from the old and new value.

**You must use volatile**

Any global variable used inside an ISR must be declared `volatile`. This is an hint to the compiler that the variable could change unexpectedly. Therefore, the volatile variable must be always read afresh, discarding any cached value.

**Critical section**

The rule for using values changed by ISR is simple:

1. Always copy the ISR's global variables to your own temporary variable.
2. Before coping, disable interrupts and reenable it after the copy is done. This prevent the ISR from executing while your are copy the values.

**Demo**

This little demo shows you all of this in action.

The sketch collect all the values from `toggle` (not disabling interrupts) during one minute and after that print a table showing what it got.

```
/*
 * This sketch show how to deal with variables shared between ISR and main thread.
 *
 * By Look Alterno 2018
 */

#include "TimerOne.h"

volatile uint32_t count = 0;
const uint32_t PATTERN_A = 0xFF00FF00;
const uint32_t PATTERN_B = 0x00FF00FF;

volatile uint32_t toggle = PATTERN_A;

#define MAX_CASES 16
struct {
    unsigned long value;
    int count;
} found[MAX_CASES];
int freeFound = 0;

#define PRINT_INTERVAL 60000L

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

    while(!Serial);

    Serial.println("");
    Serial.println("Test assignment under interrupts");
    Serial.println("");

    Serial.print("Value A=");
    Serial.println(PATTERN_A, HEX);
    Serial.print("Value B=");
    Serial.println(PATTERN_B, HEX);

    Timer1.initialize(500);
    Timer1.pwm(9, 512);
    Timer1.attachInterrupt(callback);

    pinMode(A0, INPUT);
    randomSeed(analogRead(A0));
}

void callback()
{
    count++;
    toggle = (count % 2) ? PATTERN_A : PATTERN_B;
}

void loop()
{
  static unsigned long prev = 0;

  //  A random delay to simulate some real, variable work being done.
    delayMicroseconds(random(250));

  // This is the critical section.
//  noInterrupts();
    uint32_t x = toggle;
//  interrupts();

  // Now, let's see what value we got.
    if(x != PATTERN_A && x != PATTERN_B) {
        insert(x);
    }

  // Print values found
  unsigned long now = millis();
  if (now - prev > PRINT_INTERVAL) {
    printFound();
    prev = now;
  }
}

/*
 * Add a value to a table for counting.
 */
void insert(unsigned long x)
{
    int index = 0;

    while(index < freeFound && found[index].value != x) {
        index++;
    }

    if(index < MAX_CASES) {
        if(index == freeFound) {
            found[index].value = x;
            found[index].count = 1;
            freeFound++;
      Serial.print(freeFound);
      Serial.print(". Add=");
      Serial.println(x, HEX);
        } else {
            found[index].count++;
        }
    } else {
        Serial.print("*** Table overflow. value=");
        Serial.print(x, HEX);
        Serial.println(" ***");
    }
}

/*
 * Print the table of found values so far.
 */
void printFound() {
  Serial.println("");
  Serial.println("Values found");
  Serial.println("");
  Serial.println("Value - Count");
  for (int i=0; i < freeFound; i++) {
    Serial.print(found[i].value, HEX); Serial.print(" - "); Serial.println(found[i].count);
  }
}

```

If you uncomment `noInterrupts` and `interrupts`, every thing works just fine.

**Other CPU**

More powerful CPUs have atomic assignments, but following this practices makes your code portable across platforms, no matter what. Think of *defensive programming*
> 4 votes

---
Tags: programming, interrupt, faq
---


# Question
Title: Enroll more than one finger on Unique Id in R305 FingerPrint Module Working With Arduino
I am working on a project when I have to enroll and Submit the attendance of the fingerprints.

What I have : I am able to enroll single fingerprint on a different unique ID. Using AdaFruit FingerPrint Sensor Library. I have :

> R305 FingerPrint Sensor having 1000 fingerPrint storage and Arduino Uno

What I want : I want to enroll more than one finger Prints on same Unique Id. How to do it, Please anyone Help me with this. Help will be appreciated. Thanks

# Answer
> 1 votes
Each fingerprint must have a unique ID that refers to that fingerprint.

What you need next is a table to associate multiple fingerprint IDs with "persons" so that you can find out which person belongs to a particular print scan.

You didn't say if you were holding fingerprint and person data within the Arduino or on some network-based storage system, but if we assume that this is entirely self-contained in the Arduino you would need to write the association table to some kind of storage that won't reset when the Arduino loses power, such as an EEPROM. The Uno has a "built in" EEPROM on the ATMega328p chip, but it only holds 1024 bytes. There are external EEPROMs that communicate via SPI or I2C that can hold more data.

As to the actual data structure -- it can be as simple as a 2-dimensional array, with one dimension holding the fingerprint ID, and the other holding a person ID. For multiple fingerprints of the same person, the table would have multiple rows with the same person ID, but different fingerprint IDs.

You could also make an array of `struct` datatypes, or create class, etc. But the point is that the "Unique ID" matching only ONE print from the fingerprint sensor is a limitation you have to work with.

---
Tags: arduino-uno
---


# Question
Title: Can I change this code to use a potentiometer instead of a push button
The following code is for a pyrograph power supply that uses an ATtiny85. I want to change it, so instead of a push button I have a potentiometer being the control of the temperature. Can anyone guide me on how to accomplish this with this code?

```
//Written by Tyler Gerritsen
//2017-10-21
//Pyrography Pen Power Supply Controller
//Written for ATTiny85 w/ Internal 1MHZ Clock

const byte btn = 2;
const byte led = 1;
const byte pwr = 0;
byte rate = 0;
unsigned long nextChange = 0;
boolean onOff = false;
unsigned long blinkyCount = 2000000000;
unsigned long nextBlink = 0;
unsigned long debounceTimer = 2000000000;
const unsigned int debounceDelay = 400;
const unsigned int onDelay[5] = {6800, 6300, 5800, 6300, 4800};
const unsigned int offDelay = 5000;

void setup() {
  pinMode(btn, INPUT_PULLUP);
  digitalWrite(btn, HIGH);
  pinMode(led, OUTPUT);
  pinMode(pwr, OUTPUT);
  digitalWrite(pwr, LOW);
  debounceTimer = 60000000;
  while (digitalRead(btn)) {
    checkButton();
  }
  analogWrite(led, 0);
  nextChange = micros();
  debounceTimer = millis() + debounceDelay;
  blinkyCount = 1;

}

void loop() {
  runBurner();
  checkButton();
}

void runBurner() {
  if (micros() > nextChange) {
    if (onOff) {
      digitalWrite(pwr, LOW);
      onOff = false;
      nextChange += onDelay[rate];
    } else {
      digitalWrite(pwr, HIGH);
      onOff = true;
      nextChange += offDelay;
    }
  }
}

void checkButton() {
  if (!digitalRead(btn) && millis() > debounceTimer) {
    debounceTimer = millis() + debounceDelay;
    rate++;
    rate %= 5;
    blinkyCount = (rate) * 2 + 5;
    nextBlink = millis();
  }
  if (blinkyCount > 1 && millis() > nextBlink) {
    if (blinkyCount % 2) {
      digitalWrite(led, LOW);
      blinkyCount--;
      nextBlink += 150;
    } else {
      analogWrite(led, 10);
      nextBlink += 150;
      blinkyCount--;
    }
  } else if (blinkyCount == 1) {
    analogWrite(led, 10);
    blinkyCount = 0;
  }
}

```

# Answer
> 2 votes
This is a simple sketch that shows how to read a potentiometer and do something with the value, namely, adjust the delay of the blinking led.

\[Source: https://www.arduino.cc/en/tutorial/potentiometer\]

```
/* Analog Read to LED
 * ------------------
 *
 * turns on and off a light emitting diode(LED) connected to digital
 * pin 13. The amount of time the LED will be on and off depends on
 * the value obtained by analogRead(). In the easiest case we connect
 * a potentiometer to analog pin 2.
 *
 * Created 1 December 2005
 * copyleft 2005 DojoDave <http://www.0j0.org>
 * http://arduino.berlios.de
 *
 */

int potPin = 2;    // select the input pin for the potentiometer
int ledPin = 13;   // select the pin for the LED
int val = 0;       // variable to store the value coming from the sensor

void setup() {
  pinMode(ledPin, OUTPUT);  // declare the ledPin as an OUTPUT
}

void loop() {
  val = analogRead(potPin);    // read the value from the sensor
  digitalWrite(ledPin, HIGH);  // turn the ledPin on
  delay(val);                  // stop the program for some time
  digitalWrite(ledPin, LOW);   // turn the ledPin off
  delay(val);                  // stop the program for some time
}

```

So, in every loop iteration you read the potPin and using that value for delay.

AnalogRead gives you a value between 0-1023, which you have to adjust to give the desired value for temperature control. That is all you need.

Use `map` function to adjust the value. Look at https://www.arduino.cc/reference/en/language/functions/math/map/

# Answer
> 1 votes
This bit of code from you is the key part:

```
if (!digitalRead(btn) && millis() > debounceTimer) {
  debounceTimer = millis() + debounceDelay;
  rate++;
  rate %= 5;
  blinkyCount = (rate)*2+5;
  nextBlink = millis();
}

```

Specifically, the `rate++` and `rate %= 5` lines.

You have a 5-step temp setting. The `analogRead()` function returns a value from 0 to 1023, which you have to map to 0 to 4 (5 steps). Also, you can read the Potentiometer without worry about debouncing; thus:

```
if (true) {
  rate = map(analogRead(A0), 0, 1023, 0, 4);
  blinkyCount = (rate)*2+5;
  nextBlink = millis();
}

```

If you desire to have more than 5 "settings" for temperature, you could get a continuous range by eliminating the table `onDelay[]` and mapping the analog value between the high and low range of the acceptable `onDelay` values, so you get a finer control of the "on" delay time.

```
// No longer needs to be an array or a const
unsigned int onDelay = 6800;

```

Within `checkButton()`:

```
if (true) {

  // Key Change here
  onDelay = map(analogRead(A0), 0, 1023, 6800, 4800);

  blinkyCount = (rate)*2+5;
  nextBlink = millis();
}

```

Update to `runBurner()`:

```
void runBurner(){
  if (micros() > nextChange){
    if (onOff){
      digitalWrite(pwr, LOW);
      onOff = false;

      // Key Change here:
      nextChange += onDelay;

    }
    else {
      digitalWrite(pwr, HIGH);
      onOff = true;
      nextChange += offDelay;
    }
  }
}

```

---
Tags: arduino-uno, button, potentiometer
---


# Question
Title: Is an Arduino Uno required to send any sort of command to a NodeMCU?
I have an Amica ESP8266 NodeMCU I want to send some commands to. I have tried sending some commands like 'AT' and 'AT+CWLAP' but I do not get any sort of output for any command I send to it.

Actually I did not send commands the first time I bought it. I flashed it with a `deauther` program made by spacehuhn then I erased the chip using the `esptool.py --port /dev/tty.SLAB_USBtoUART erase_flash` command multiple times. Then I heard that you can send commands to the NodeMCU using the Serial Monitor using Arduino. So I tried it but no output. So my question is whether I need an Arduino Uno or has the command which I used to erase the factory code of the NodeMCU broken something?

PS. I am a newbie so I don't know much of this stuff.

# Answer
With erase\_flash you deleted the AT firmware from flash. You can load it back with esptool or with Flash Download Tool (Windows only).

AT firmware download page

Addresses for 4 megabyte flash (more in readme.md of AT firmware):

```
esptool.py -p /dev/tty.SLAB_USBtoUART write_flash 0x0 boot_v1.7.bin 0x01000 at/512+512/user1.1024.new.2.bin 0x3fc000 esp_init_data_default.bin 0xfe000 blank.bin 0x3fe000 blank.bin

```
> 3 votes

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


title: Arduino MQTT Bluetooth

text:
# Question
Title: Arduino MQTT Bluetooth
Is there a library to use MQTT with a bluetooth module (HC-06) instead of WiFi? If not is there a similar ready for use implementation of a publisher subscriber pattern available?

# Answer
> 1 votes
MQTT is TCP/IP native. If you want to access it via Bluetooth, you need a gateway; a device that translate protocols. You need one for the specific protocols involved: MQTT, TCP/IP and Bluetooth.

Google "MQTT Bluetooth gateway" to find alternatives like this one:

> The iGS01 gateway listens for beacons, gets their advertising data and forwards it on to your server or an IoT server via TCP, HTTP(S) or MQTT. It can be used to feed back-end systems that report on the presence or absence of iBeacon or Eddystone beacons or act on beacon sensor (e.g. accelerometer, temperature, light, humidity) data.

> The gateway connects to your local 2.4GHz frequency band WiFi access point and is managed via a web browser interface. It can be connected via WPS (press button on both the gateway and the WiFi access point). It can also be managed via Telnet commands from other hardware (or a human).
>
> For MQTT/MQTTS, the host, port, username, password and a root CA cert can be provided.

There are also software only solutions available, but I didn't found a generic one, only specific for certain vendors.

---
Tags: bluetooth, mqtt
---


# Question
Title: Atmega328P-PU: Programmer is not responding
Few days ago, I built my own custom Arduino on the breadboard. It is built according to tutorial on http://www.crash-bang.com/resource/breadboard-arduino/. The Atmega328P-PU is already burned with the Arduino bootloader with simple blink sketch.

For the programmer, I decided to use the Arduino USB2Serial. Again, it is connected as shown on crash-bang site. Problem is I get this error when uploading a different sketch:

```
avrdude -Cavrdude.conf -v -patmega328p -carduino -PCOM3 -b115200 -D -Uflash:w:build244630154737317489.tmp/sketch_may23a.cpp.hex:i

avrdude: Version 6.0.1, compiled on Apr 15 2015 at 19:59:58
     Copyright (c) 2000-2005 Brian Dean, http://www.bdmicro.com/
     Copyright (c) 2007-2009 Joerg Wunsch

     System wide configuration file is "avrdude.conf"

     Using Port                    : COM3
     Using Programmer              : arduino
     Overriding Baud Rate          : 115200
     AVR Part                      : ATmega328P
     Chip Erase delay              : 9000 us
     PAGEL                         : PD7
     BS2                           : PC2
     RESET disposition             : dedicated
     RETRY pulse                   : SCK
     serial program mode           : yes
     parallel program mode         : yes
     Timeout                       : 200
     StabDelay                     : 100
     CmdexeDelay                   : 25
     SyncLoops                     : 32
     ByteDelay                     : 0
     PollIndex                     : 3
     PollValue                     : 0x53
     Memory Detail                 :

                              Block Poll               Page                       Polled
       Memory Type Mode Delay Size  Indx Paged  Size   Size #Pages MinW  MaxW   ReadBack
       ----------- ---- ----- ----- ---- ------ ------ ---- ------ ----- ----- ---------
       eeprom        65    20     4    0 no       1024    4      0  3600  3600 0xff 0xff
       flash         65     6   128    0 yes     32768  128    256  4500  4500 0xff 0xff
       lfuse          0     0     0    0 no          1    0      0  4500  4500 0x00 0x00
       hfuse          0     0     0    0 no          1    0      0  4500  4500 0x00 0x00
       efuse          0     0     0    0 no          1    0      0  4500  4500 0x00 0x00
       lock           0     0     0    0 no          1    0      0  4500  4500 0x00 0x00
       calibration    0     0     0    0 no          1    0      0     0     0 0x00 0x00
       signature      0     0     0    0 no          3    0      0     0     0 0x00 0x00

     Programmer Type : Arduino
     Description     : Arduino
     Hardware Version: 3
     Firmware Version: 4.4
     Vtarget         : 0.3 V
     Varef           : 0.3 V
     Oscillator      : 28.800 kHz
     SCK period      : 3.3 us

avrdude: AVR device initialized and ready to accept instructions

Reading | ################################################## | 100% 0.00s

avrdude: Device signature = 0x1e950f
avrdude: reading input file "build244630154737317489.tmp/sketch_may23a.cpp.hex"
avrdude: writing flash (450 bytes):

Writing | avrdude: stk500_recv(): programmer is not responding

```

Most of the time I do not even get to this point and just end up with something like:

```
avrdude: stk500_recv(): programmer is not responding
avrdude: stk500_getsync() attempt 1 of 10: not in sync: resp=0xf5

```

What I have done so far:

* I already tried to reset Arduino just before uploading the sketch.
* According to the avrdude, bootloader is fine.
* Reinstalled drivers, Arduino IDE
* Changed the USB cable and connected it to another USB slot
* Burned new bootloader using ArduinoISP

Thank you for help.

# Answer
"Step 3 says to connect +ve rail –\> AVCC (pin 20) and +ve rail –\> AREF (pin 21). You can leave those pins not connected. "

+ve rail should not be connected to Aref. The +ve rail will connect via the internal operation of the ADC mux.

AVCC and both Gnds should be connected per the datasheet: 5.2.7. AVCC AVCC is the supply voltage pin for the A/D Converter, PC\[3:0\], and PE\[3:2\]. It should be externally connected to VCC, even if the ADC is not used.

28.2. AVCC must not differ more than ±0.3V from VCC.... Optionally, AVCC or an internal 1.1V reference voltage may be connected to the AREF pin by writing to the REFSn bits in the ADMUX Register. The internal voltage reference must be decoupled by an external capacitor at the AREF pin to improve noise immunity.

If you connect Aref to the +ve rail externally, and then select the internal reference, things can go bad.

FTDT thru 0.1uF cap to Reset, with 10K pullup, and reverse biased diode to VCC, works for me in plenty of designs. Not sure why it does not work in all cases. The diode dissipates any spike on the Reset line to keep the chip from thinking high voltage programming mode is being started.
> -1 votes

---
Tags: arduino-uno, serial, atmega328, programmer
---


# Question
Title: Error while uploading the sketch for Arduino Mini
I'm having a problem while uploading the program.

```
Arduino: 1.8.4 (Windows 10), Board: "Arduino Mini, ATmega328P"

Archiving built core (caching) in: C:\Users\UMME-K~1\AppData\Local\Temp\arduino_cache_566019\core\core_arduino_avr_mini_cpu_atmega328_3f323efdab4276426e9d8710d5d73f64.a
Sketch uses 3932 bytes (13%) of program storage space. Maximum is 28672 bytes.
Global variables use 250 bytes (12%) of dynamic memory, leaving 1798 bytes for local variables. Maximum is 2048 bytes.
D:\Amna\arduino-1.8.4\hardware\tools\avr/bin/avrdude -CD:\Amna\arduino-1.8.4\hardware\tools\avr/etc/avrdude.conf -v -patmega328p -carduino -PCOM4 -b115200 -D -Uflash:w:C:\Users\UMME-K~1\AppData\Local\Temp\arduino_build_808790/buzzer.ino.hex:i

avrdude: Version 6.3, compiled on Jan 17 2017 at 12:00:53
         Copyright (c) 2000-2005 Brian Dean, http://www.bdmicro.com/
         Copyright (c) 2007-2014 Joerg Wunsch

         System wide configuration file is "D:\Amna\arduino-1.8.4\hardware\tools\avr/etc/avrdude.conf"

         Using Port                    : COM4
         Using Programmer              : arduino
         Overriding Baud Rate          : 115200
avrdude: stk500_getsync() attempt 1 of 10: not in sync: resp=0x00
avrdude: stk500_getsync() attempt 2 of 10: not in sync: resp=0x00
avrdude: stk500_getsync() attempt 3 of 10: not in sync: resp=0x00
avrdude: stk500_getsync() attempt 4 of 10: not in sync: resp=0x00
avrdude: stk500_getsync() attempt 5 of 10: not in sync: resp=0x00
avrdude: stk500_getsync() attempt 6 of 10: not in sync: resp=0x00
avrdude: stk500_getsync() attempt 7 of 10: not in sync: resp=0x00
avrdude: stk500_getsync() attempt 8 of 10: not in sync: resp=0x00
avrdude: stk500_getsync() attempt 9 of 10: not in sync: resp=0x00
avrdude: stk500_getsync() attempt 10 of 10: not in sync: resp=0x00

avrdude done.  Thank you.

An error occurred while uploading the sketch

This report would have more information with
"Show verbose output during compilation"
option enabled in File -> Preferences.

```

What should I do?

# Answer
> 2 votes
On Uno and other boards with USB on board, for flashing the IDE resets the Atmega to bootloader, sending signal over USB. Mini has not an build in USB and you connected it with an USB to TTL cable. Has this cable a Reset signal line? If yes, did you connect this line to Reset pin?

If not, then you need to do a manual reset in the right moment when avrdude sends the hex file. I count to 9 after the first attempt and then I push the reset button.

# Answer
> 0 votes
"If not, then you need to do a manual reset in the right moment when avrdude sends the hex file. I count to 9 after the first attempt and then I push the reset button."

In the IDE, if you select File:Preferences and turn on Verbose outputs, you can see when the IDE is about to download, there will appear "compiled xxx of 32xxx bytes), then3 attempts to download. If you press Reset when you see that message, or press & hold reset then release when you see that message, it is much easier to get the bootloader started at the right time (assuming one is actually loaded and there is nothing interfering with the signals on the D0/D1 pins).

---
Tags: arduino-mini
---


# Question
Title: Sending over a number from Arduino to Attiny85
I recently started my first arduino project, displaying a number on a 4x 7 segment display. I want to keep this code and use the display in other projects to display 4 digit numbers (creating a library and using segmentdisplay.write(number) maybe?).

Just displaying the number went really well, but I wanted to drive it with less I/O pins. Then I discovered shift registers, which reduced the number of necessary I/O pins to 3. But, the code needs to execute constantly to keep the 4 digits on the display via multiplexing. My solution to this was to run the sketch on attiny85, on which I programmed the code below. The only thing left to do is to change the value of 'getal' to a value that I read or calculate on the arduino. But I have no idea on how to achieve this, can I shift out data from the arduino to attiny85, which then updates 'getal's value? Any help is appreciated!

```
const int dataPin = 0;
const int latchPin = 1;
const int clockPin = 2;

const int Db = B00001111;
const int D1 = B00000111;
const int D2 = B00001011;
const int D3 = B00001101;
const int D4 = B00001110;
const int num0 = B11111100;
const int num1 = B01100000;
const int num2 = B11011010;
const int num3 = B11110010;
const int num4 = B01100110;
const int num5 = B10110110;
const int num6 = B10111110;
const int num7 = B11100000;
const int num8 = B11111110;
const int num9 = B11110110;

int D_4[4] = {D1, D2, D3, D4};
int D_3[4] = {Db, D2, D3, D4};
int D_2[4] = {Db, Db, D3, D4};
int D_1[4] = {Db, Db, Db, D4};
const int num[10] = {num0, num1, num2, num3, num4, num5, num6, num7, num8, num9};

const int tallen[4] = {1000, 100, 10, 1};

int getal = 185;

void setup() {
  pinMode(latchPin, OUTPUT);
  pinMode(clockPin, OUTPUT);
  pinMode(dataPin, OUTPUT);
}

void loop() {
  int lengte = findn(getal);
  switch (lengte) {
    case 1:
      displaynum(D_1);
      break;
    case 2:
      displaynum(D_2);
      break;
    case 3:
      displaynum(D_3);
      break;
    case 4:
      displaynum(D_4);
      break;
  }
}

int findn(int num) {
  int n = 0;
  while (num) {
    num /= 10;
    n++;
  }
  return n;
}

void displaynum(int *D_x) {
  for (int i = 0; i <= 3; i++) {

    digitalWrite(clockPin, LOW);
    digitalWrite(latchPin, LOW);

    shiftOut(dataPin, clockPin, LSBFIRST, D_x[i]);
    shiftOut(dataPin, clockPin, LSBFIRST, num[(getal / tallen[i]) % 10]);
    digitalWrite(latchPin, HIGH);
    delay(1);
  }
}

```

# Answer
> 1 votes
As Look Alterno stated it would be easier to directly use an LCD display. But if you really want to use the 7 segment display and the ATTiny85 you can use I2C to send the number to the ATTiny. There are libraries, that can use the USI hardware ot emulate a (nearly) full I2C bus. For example my TinyWire library, that I composed from the previous TinyWireM and TinyWireS libraries. I2C needs only 2 pins (pin 0 as SDA and pin 2 as SCL I think), so you still have your 3 pins left for the display.

Then you would make the Arduino master and the ATTiny slave. Use the examples, that come with the library to learn it's usage. Note, that currently you can use the `write()` function only with one byte, so if you need bigger datatypes you need to split them to byte-level on your own.

# Answer
> 1 votes
Could also use a chip with better resources, such as Attiny2313. 20 Pins, so a little larger than the '85, but you get a real serial port and SPI port.

---
Tags: arduino-uno, communication, attiny85
---


# Question
Title: ATtiny85 serial communication, bootloader and setting up fuses
I have been reading some articles about ATtiny and how to burn the bootloader. And I have two questions which I can't figure out.

1. Do I need to manually setup fuses to run 8 MHz on my ATtiny when I'm using my Arduino board as my ISP (there we can select the internal clock and that confuses me)?
2. For the SoftwareSerial.h library, do I need to setup my ATtiny to 8 Mhz in order to work?

# Answer
> 0 votes
If you load this into the IDE https://github.com/SpenceKonde/ATTinyCore the fuses will be set correctly for the different selectable clock speeds.

# Answer
> 0 votes
1. If you search the internet, you mostly find statements, that the fuses will be set right, if you burn the bootloader from the IDE. However I had to set the fuses in an extra call to avr-dude, because the clock divider was still active, setting the clock effectivly to 1MHz, instead of the intended 8MHz. With a command like

avrdude -P /dev/ttyUSB1 -b 19200 -c avrisp -p attiny85 -v

you can read the current fuses. Note that you have to set the parameters according to your setup (I used an ArduinoAsISP on the serial port ttyUSB1). You can write the fuses with a command like this:

```
avrdude -P /dev/ttyUSB1 -b 19200 -c avrisp -p attiny85 -v -U lfuse:w:0xE2:m

```

depending on which fuse you want to set, you have to replace `lfuse` with `hfuse` or `efuse`.

2. SoftwareSerial should also work with other clock frequencies, but I don't know the limitations. Keep in mind, that lower clock frequency means you can only reach lower baudrates. It is crucial, that the fuses are set correctly for the intended speed, because the library takes the speed defined in the IDE. In my case this was 8MHz, but the ATTiny still run at 1MHz, which confused the serial communication.

---
Tags: softwareserial, bootloader, attiny85, fuses
---


# Question
Title: How many transistors can be connected to Arduino pins?
How many TIP122 transistors can I connect to the Arduino digital pins? The Atmega328p datasheet states that the pins can source a total of 200 mA, while other documents state 40 mA per pin.

In the following circuit layout, I connected six TIP122 transistors with 2.2 kΩ base resistors. I used an LM338 regulator to power the Arduino IC and other functions.

# Answer
I would use a N-channel MOSFET instead of the TIPwhatever. AOD514 from Digikey has really low Rds, somewhere around 0.01 ohm, and can be driven from an Arduino pin, say thru a 150 ohm resistor to protect against the gate input capacitance of the MOSFET. A 10K pulldown resistor on the gate will hold the MOSFET off until the Arduino sketch starts up and controls the pin. AOD514 is surface mount, but tab and pins are pretty good size and can be manually soldered. AOD508 and AOD510 are even lower Rds, but cost a bit more at Digikey.
> 1 votes

# Answer
The TIP122 is a 100V, 5A, Hfe at least 1000, darlington NPN transistor. With the base resistor of 2k2, that is about 1 or 2 mA per pin. You don't have to worry about a few mA.

To answer your question: "How many transistor can be connected to arduino pins?", that will be about 100.

Why do you use TIP122 ? They have a voltage drop. Logic level mosfets have a very little voltage drop and thus they stay a lot cooler. Mosfets leak at a higher voltage. If you need to operate near 100V, there are IGBT transistors for that.

Make sure that the high current through the TIP122 at the emitter does not disturb the GND of the ATmega chip. You have to design your circuit board to avoid such troubles.
> 0 votes

# Answer
"In datasheet atmega 328p total arduino pin can source 200 ma of current or some saying 40ma current per pin."

Datasheet says 200mA per VCC and GND pin. I personally confirmed that with Atmel Tech Support (before they were bought by MicroChip).

Absolute max per IO pin is 40mA, more than that and you risk damaging the pin. Further, above 20mA a High output will begin outputting lower voltage, and a Low output will begin outputting a higher voltage. See Section 32 of the latest datasheet:

"Note: Stresses beyond those listed under “Absolute Maximum Ratings” may cause permanent damage to the device. This is a stress rating only and functional operation of the device at these or other conditions beyond those indicated in the operational sections of this specification is not implied. Exposure to absolute maximum rating conditions for extended periods may affect device reliability."

and notes 3 and 4 under table 32.2:

"If IIOH exceeds the test condition (20mA at VCC = 5V, 10mA at VCC = 3V), VOH may exceed the related specification. Pins are not guaranteed to source current greater than the listed test condition."

"If IOL exceeds the test condition (20mA at VCC = 5V, 10mA at VCC = 3V), VOL may exceed the related specification. Pins are not guaranteed to sink current greater than the listed test condition."
> 0 votes

---
Tags: arduino-uno, transistor
---


# Question
Title: Build a timer that starts and stops timing when 2 wires are broken
I need to build a timer that uses the breaking of copper strips to trigger its starting and stopping. The intention is to measure the speed of a rocket with this - it will break the first wire, starting the timer, and then break the second, stopping it.

I am using an **Arduino Uno**, and a couple of lengths of wire for now.

I can plug one wire into the 1st 5V power supply on the board, and the other end into one of the analog pins (AO), (and then the second wire into the 2nd 5v supply and A1) so that when it is pulled out of the pin socket, it is 'broken'. Is this the correct method to go about this, and if so, how do I tell the Arduino to look for those signals as its 'start' and 'stop' and then record the time difference accordingly?

So far, I have managed to read a signal from the wire using the Analog Read Signal tutorial on Arduino.cc (*https://www.arduino.cc/en/Tutorial/AnalogReadSerial*). I noted whilst watching the printed data that once the wire is removed from the pin, the voltage value slowly decreased, and held at around 290 (starting at 1023, as per the tutorial). Is this simply a side effect of not using a grounded potentiometer, but a wire?

```
void setup() {
  // set up comms:
  Serial.begin(9600);
}

void loop() {
  // check and read value of input:
  int sensorValue = analogRead(A0);
  Serial.println(sensorValue);
  delay(1);
}

```

I am new to Arduino, so please explain in detail, or point me to a thread that will! *Thanks in advance for help!*

**UPDATE** Having played around with analogWrite some more, I have managed to get a situation where I can output the relative value from both A0 and A1. However, I am still struggling to make it operate as a timer.

```
// declare variables
unsigned long startTime, stopTime;
unsigned long totalTime = (stopTime - startTime);

void setup() {
  Serial.begin(9600);   // set up comms
}

void loop() {
  // check and read value of input:
  int sensorValue1 = analogRead(A0);
  int sensorValue2 = analogRead(A1);

  if (sensorValue1 < 1023) {
    startTime = micros();
    Serial.println(sensorValue1);
  }
  if (sensorValue2 < 1023) {
    stopTime = micros();
    Serial.println(sensorValue2);
  }

  Serial.println("Time: ");   // prints "Time: "
  Serial.println(totalTime);  // prints time value
    delay(1000);
}

```

I have also tried to convert this to use **digitalRead** rather than **analogRead** but have not had much success - I am still failing to get a time. I know my method is wrong, but have struggled to find guidance on how to correct it.

```
    // declare variables
boolean timingFinished = false;
unsigned long startTime, stopTime;

String strTime = "Time:";

void setup() {
  Serial.begin(9600);   // set up comms
  pinMode(7, INPUT);   // set up pin 7
  pinMode(6, INPUT);   // set up pin 6
}

void loop() {
  // check and read value of input:
  int sensorValue1 = digitalRead(7);
  int sensorValue2 = digitalRead(6);
  Serial.println(sensorValue1);
  Serial.println(sensorValue2);

  if (sensorValue1 = HIGH) {
    startTime = micros();
    Serial.println(sensorValue1);
  }
  if (sensorValue2 = HIGH) {
    stopTime = micros();
    Serial.println(sensorValue2);
  }
  unsigned long totalTime = (sensorValue1 - sensorValue2);
  String strPrint = strTime + totalTime;
  Serial.println(strPrint);      // prints "Time"

}

```

# Answer
You have a number of problems in your code. For one thing, you are doing a lot of printing:

```
void loop() {
  // check and read value of input:
  int sensorValue1 = digitalRead(7);
  int sensorValue2 = digitalRead(6);
  Serial.println(sensorValue1);
  Serial.println(sensorValue2);

  if (sensorValue1 = HIGH) {
    startTime = micros();
    Serial.println(sensorValue1);
  }
  if (sensorValue2 = HIGH) {
    stopTime = micros();
    Serial.println(sensorValue2);
  }
  unsigned long totalTime = (sensorValue1 - sensorValue2);
  String strPrint = strTime + totalTime;
  Serial.println(strPrint);      // prints "Time"

}

```

At 9600 baud each byte output takes 1/960 seconds (about 1 ms). A `println` adds a carriage-return/linefeed to what you are printing so I estimate:

```
3 + 3 + 7 + 7 = 20 bytes (20 ms)

```

That is **every time around the loop**! You will soon find the output buffer filling up, and thus are limiting the rate at which you can test times to be the nearest 20 ms which makes using `micros()` a bit redundant. You won't get that accuracy.

---

Plus, the `String` class does dynamic memory allocation which will slow things down. Why use `String` at all? For example, you can print "Time" like this:

```
Serial.println ("Time:");

```

---

Next, this **assigns** not compares:

```
  if (sensorValue1 = HIGH) {

```

That statement makes sensorValue1 HIGH (always) and then tests if it is true, which it always will be. You want:

```
  if (sensorValue1 == HIGH) {

```

---

Finally, as mentioned by Majenko, make the inputs INPUT\_PULLUP and wire the other end to ground, like this:

```
  pinMode(7, INPUT_PULLUP);   // set up pin 7
  pinMode(6, INPUT_PULLUP);   // set up pin 6

```

---

**Edit** \- after amended question.

```
// declare variables
unsigned long startTime, stopTime;
unsigned long totalTime = (stopTime - startTime);

```

You don't declare totalTime like that. It appears you want totalTime to **eventually** subtract startTime from stopTime.

Just declare totalTime without any calculations, and do the calculation when it is needed. eg.

```
// declare variables
unsigned long startTime, stopTime;
unsigned long totalTime;

...

  if (sensorValue2 == HIGH) {
    stopTime = micros();
    totalTime = stopTime - startTime;
    Serial.print ("Time: ");
    Serial.println (totalTime);
    }  // end of second sensor tripped

```

Note the "==" there, without it the code thinks *both sensors tripped immediately*.
> 3 votes

# Answer
A broken wire is just a button that's held in until you release it. Just treat it like any other button.

simulate this circuit – Schematic created using CircuitLab

Just like a button, when it's all connected (button is pressed), it reads LOW, and when it's disconnected / broken (button is released) it reads HIGH. No need for messing around with analog inputs - you only care about two states, OPEN (HIGH) and CLOSED (LOW).

You can even use interrupts to make it respond even faster.

Here is an example using a simple state machine for how you could code it (untested):

```
const uint8_t startPin = 4;
const uint8_t stopPin = 5;

uint32_t startTime;
uint32_t stopTime;

#define ARMED = 0
#define STARTED = 1
#define STOPPED = 2

uint8_t state = ARMED;

void setup() {
    Serial.begin(115200);
    pinMode(startPin, INPUT_PULLUP);
    pinMode(stopPin, INPUT_PULLUP);
}

void loop() {

    switch (state) {
        case ARMED:  // If first wire disconnects then start.
            if (digitalRead(startPin) == HIGH) {
                startTime = micros();
                state = STARTED;
            }
            break;

        case STARTED:  // If second wire disconnects then stop
            if (digitalRead(stopPin) == HIGH) {
                stopTime = micros();
                state = STOPPED;
                Serial.print(F("Duration: "));
                Serial.print(stopTime - startTime);
                Serial.println("us");
            }
            break;

        case STOPPED:  // If both wires reconnected then start over
            if ((digitalRead(startPin) == LOW) &&
                (digitalRead(stopPin) == LOW)) {
                    state = ARMED;
            }
            break;

        default:
            break;
    }
}

```
> 1 votes

# Answer
A better approach for your problem which was to measure the speed of a rocket (i am assuming at launch) would be to use non touch style sensors. Rather then the rocket having to hit two wires which would interrupt the flight path. You could use IR sensors Like in this article.

It would use much of the same logic you are working on now, but would use the IR sensors rather then wires (buttons)
> 0 votes

# Answer
Regardless of what you use as the sensors, wires or photo detectors, you should use interrupts. Each sensor should go to an interrupt and that interrupt routine should be as short as possible, basically just saving the processor time micros(), into a storage location and returning. Your main loop can then look at the storage and see if a calculation or printout is necessary. That way your result will not be dependent on where in your loop the event was detected. The inputs should be digital, high or low as described above. If you are using photo detectors that are analog, build some external circuits to turn their outputs into digital signals. I would say this isn't rocket science, but apparently it is. I just hope I am not helping a terrorists :-)
> 0 votes

---
Tags: arduino-uno, timers, analogread
---


# Question
Title: Two-wire Conductivity Sensor and Arduino Hook-up?
For the conductivity meter shown in the photo below, it is a non-NPN sensor for measuring conductivity / impedance.

I am trying to figure out the best method for measuring the output of the sensor using an Arduino.

I am told from the supplier that there is no polarity. I was planning to connect one of the leads through a 10k resistor to an analog input (A0) on my Arduino; and the other lead to 5V?

Without much other information on the sensor, is a 10k resistor a good place to start?

# Answer
It depends on the conductivity of the liquid which it is going to be placed/submerged to. For example if the liquid is highly conductive(ex. saltwater), then a 10k Ohms resistor should be fine. But if the liquid conductivity is low(ex. tap water), then its best to measure the output voltage of one lead with respect to the Arduino's ground to be sure what value of resistor to apply to or if there is no resistor needed at all.

But generally if you are going to supply it with 5 Volts, it should be fine to connect it with the Arduino's Analog inputs directly as the operating voltage of the Arduino itself is also 5 Volts.

Cheers!
> 1 votes

---
Tags: analogread
---


# Question
Title: Failed to initialise SD card on Leonardo
I'm trying to connect SD card reader to my Arduino. For testing i'm running CardInfo example.

It seems like it runs ok when I'm running it on my Arduino UNO, but it fails to initialise SD Card while i'm running it on any Arduino with Atmega32U4 chip. I tried on two Leonardo's and Micro Pro.

This is my pinout:

```
CardReader       Arduino

CS          <->     4
SCK         <->    13
MISO        <->    12
MOSI        <->    11
VCC         <->    5V
GND         <->    GND

```

I'm using Library in version 1.2.1 if that's make difference.

Does anyone have any suggestions?

# Answer
> 3 votes
A Leonardo has the SPI pins on the ICSP header, not on pins 11, 12, 13.

And a Pro Micro has the SPI pins on 14, 15, 16.

---
Tags: arduino-leonardo, sd-card, arduino-pro-micro
---


title: 'import' does not name type ERROR

text:
# Question
Title: 'import' does not name type ERROR
I am working with a group of people on an arduino controlled BB8 robot. We are using an IMU unit (accelerometer+gyroscope). I found a processing example for the IMU unit we are using. The code is shown below. I am getting an error "'import' does not name type". I know programming but I am not very familiar with arduino. Can anyone help me?

```
import processing.serial.*;

Serial myPort;  // Create object from Serial class

final String serialPort = "/dev/tty.usbmodem621"; // replace this with your serial port. On windows you will need something like "COM1".

float [] q = new float [4];
float [] hq = null;
float [] Euler = new float [3]; // psi, theta, phi

int lf = 10; // 10 is '\n' in ASCII
byte[] inBuffer = new byte[22]; // this is the number of chars on each line from the Arduino (including /r/n)

PFont font;

void setup()
{
  size(800, 600, P3D);
  myPort = new Serial(this, serialPort, 115200);

  font = createFont("Courier", 32);

  /*
  float [] axis = new float[3];
   axis[0] = 0.0;
   axis[1] = 0.0;
   axis[2] = 1.0;
   float angle = PI/2.0;

   hq = quatAxisAngle(axis, angle);

   hq = new float[4];
   hq[0] = 0.0;
   hq[1] = 0.0;
   hq[2] = 0.0;
   hq[3] = 1.0;
   */

  delay(100);
  myPort.clear();
  myPort.write("1");
}

float decodeFloat(String inString) {
  byte [] inData = new byte[4];

  if (inString.length() == 8) {
    inData[0] = (byte) unhex(inString.substring(0, 2));
    inData[1] = (byte) unhex(inString.substring(2, 4));
    inData[2] = (byte) unhex(inString.substring(4, 6));
    inData[3] = (byte) unhex(inString.substring(6, 8));
  }

  int intbits = (inData[3] << 24) | ((inData[2] & 0xff) << 16) | ((inData[1] & 0xff) << 8) | (inData[0] & 0xff);
  return Float.intBitsToFloat(intbits);
}

void readQ() {
  if (myPort.available() >= 18) {
    String inputString = myPort.readStringUntil(lf);
    //print(inputString);
    if (inputString != null && inputString.length() > 0) {
      String [] inputStringArr = split(inputString, ",");
      if (inputStringArr.length >= 5) { // q1,q2,q3,q4,\r\n so we have 5 elements
        q[0] = decodeFloat(inputStringArr[0]);
        q[1] = decodeFloat(inputStringArr[1]);
        q[2] = decodeFloat(inputStringArr[2]);
        q[3] = decodeFloat(inputStringArr[3]);
      }
    }
  }
}

void buildBoxShape() {
  //box(60, 10, 40);
  noStroke();
  beginShape(QUADS);

  //Z+ (to the drawing area)
  fill(0,255,0);
  vertex(-30, -5, 20);
  vertex(30, -5, 20);
  vertex(30, 5, 20);
  vertex(-30, 5, 20);

  //Z-
  fill(0,0,255);
  vertex(-30, -5, -20);
  vertex(30, -5, -20);
  vertex(30, 5, -20);
  vertex(-30, 5, -20);

  //X-
  fill(255,0,0);
  vertex(-30, -5, -20);
  vertex(-30, -5, 20);
  vertex(-30, 5, 20);
  vertex(-30, 5, -20);

  //X+
  fill(255,255,0);
  vertex(30, -5, -20);
  vertex(30, -5, 20);
  vertex(30, 5, 20);
  vertex(30, 5, -20);

  //Y-
  fill(255,0,255);
  vertex(-30, -5, -20);
  vertex(30, -5, -20);
  vertex(30, -5, 20);
  vertex(-30, -5, 20);

  //Y+
  fill(0,255,255);
  vertex(-30, 5, -20);
  vertex(30, 5, -20);
  vertex(30, 5, 20);
  vertex(-30, 5, 20);

  endShape();
}

void drawCube() {
  pushMatrix();
  translate(800/2, 600/2 + 50, 0);
  scale(5, 5, 5);

  // a demonstration of the following is at
  // http://www.varesano.net/blog/fabio/ahrs-sensor-fusion-orientation-filter-3d-graphical-rotating-cube
  rotateZ(-Euler[2]);
  rotateX(-Euler[1]);
  rotateY(-Euler[0]);

  buildBoxShape();

  popMatrix();
}

void draw() {
  background(0,0,0);
  fill(255,255,255);

  readQ();

  if (hq != null) { // use home quaternion
    quaternionToEuler(quatProd(hq, q), Euler);
    text("Disable home position by pressing \"n\"", 20, 600 - 30);
  }
  else {
    quaternionToEuler(q, Euler);
    text("Point FreeIMU's X axis to your monitor then press \"h\"", 20, 600 - 30);
  }

  textFont(font, 20);
  textAlign(LEFT, TOP);
  text("Q:\n" + q[0] + "\n" + q[1] + "\n" + q[2] + "\n" + q[3], 20, 20);
  text("Euler Angles:\nYaw (psi)  : " + degrees(Euler[0]) + "\nPitch (theta): " + degrees(Euler[1]) + "\nRoll (phi)  : " + degrees(Euler[2]), 200, 20);

  drawCube();
}

void keyPressed() {
  if (key == 'h') {
    println("pressed h");

    // set hq the home quaternion as the quatnion conjugate coming from the sensor fusion
    hq = quatConjugate(q);
  }
  else if (key == 'n') {
    println("pressed n");
    hq = null;
  }
}

// See Sebastian O.H. Madwick report
// "An efficient orientation filter for inertial and intertial/magnetic sensor arrays" Chapter 2 Quaternion representation

void quaternionToEuler(float [] q, float [] euler) {
  euler[0] = atan2(2 * q[1] * q[2] - 2 * q[0] * q[3], 2 * q[0]*q[0] + 2 * q[1] * q[1] - 1); // psi
  euler[1] = -asin(2 * q[1] * q[3] + 2 * q[0] * q[2]); // theta
  euler[2] = atan2(2 * q[2] * q[3] - 2 * q[0] * q[1], 2 * q[0] * q[0] + 2 * q[3] * q[3] - 1); // phi
}

float [] quatProd(float [] a, float [] b) {
  float [] q = new float[4];

  q[0] = a[0] * b[0] - a[1] * b[1] - a[2] * b[2] - a[3] * b[3];
  q[1] = a[0] * b[1] + a[1] * b[0] + a[2] * b[3] - a[3] * b[2];
  q[2] = a[0] * b[2] - a[1] * b[3] + a[2] * b[0] + a[3] * b[1];
  q[3] = a[0] * b[3] + a[1] * b[2] - a[2] * b[1] + a[3] * b[0];

  return q;
}

// returns a quaternion from an axis angle representation
float [] quatAxisAngle(float [] axis, float angle) {
  float [] q = new float[4];

  float halfAngle = angle / 2.0;
  float sinHalfAngle = sin(halfAngle);
  q[0] = cos(halfAngle);
  q[1] = -axis[0] * sinHalfAngle;
  q[2] = -axis[1] * sinHalfAngle;
  q[3] = -axis[2] * sinHalfAngle;

  return q;
}

// return the quaternion conjugate of quat
float [] quatConjugate(float [] quat) {
  float [] conj = new float[4];

  conj[0] = quat[0];
  conj[1] = -quat[1];
  conj[2] = -quat[2];
  conj[3] = -quat[3];

  return conj;
}

```

# Answer
> 2 votes
Processing code is intended to be run on a computer. You would use the Processing IDE to run this code.

The Arduino IDE is used to write, compile, and upload code to a microcontroller that you might have on an Arduino board. This is the cause of the error.

---
Tags: arduino-uno, accelerometer, gyroscope, compilation-errors, imu
---


# Question
Title: Outputs/inputs to Multiple Arduinos in Arduino IDE at once
I apologize if this information could be easily accessed, but I'm new to Arduino and did multiple searches. I'm currently able to write to one Arduino Trinket in Arduino IDE using digitalWrite. However, I'll have to be reading from two different Arduino Trinkets with analogRead. An important part of this is that I must be able to access both devices at the same time. I saw during research that other people were able to use two different Arduino IDE instances, but I don't think this will work for me. I'll more than likely soon be purchasing 2 Arduino ItsyBitsy's or nano's for the serial USB communication. Let me know if this would make the issue easier. I appreciate any help!

# Answer
> 1 votes
Arduino IDE is editor and builder. Your sketch runs on microcontroller and the microcotroller doesn't need the IDE to run it. The Serial prints from microcontroller go to com port from which any Terminal app can show them, not only the Serial Monitor build-in in IDE.

Connect both arduinos of same type to computer. They will have different ports. Upload your sketch to the first one, then change the port setting in IDE and upload to second arduino.

Serial Monitor can show you the output of arduino connected to the selected port. Switch port in Tools menu and reopen Serial Monitor to see the output of the second arduino.

To display booth at once, there are some options with different difficulty level:

1. use two instances of a terminal program like PuTTY Terminal Emulator to show the output
2. connect the TX pins of arduinos together
3. send data from one arduino to the second and let the second process them

---
Tags: arduino-ide
---


# Question
Title: Charge 14500 LiFePO4 lithium batteries from an Arduino Nano
I've recently started tinkering with Arduino, and I'm attempting to build a little 2WD robot based on an Arduino Nano.

I was thinking of powering the robot using two 14500 LiFePO4 batteries, which I understand will fit in a standard 2 x AA battery holder, and in series will give me about 6.4V, which should be ideal.

If I were instead going to use AA batteries, I think I'd need 4 of them, which will make my robot a fair bit bulkier.

I would like to be able to charge the batteries simply by plugging a standard USB cable into the Nano's USB socket.

Is there some easy way to safely do this? Do I need a separate charging module board, or is there some way to do it directly from the Nano?

# Answer
No, you cannot charge a Lithium-Ion battery (of any variant) directly from an Arduino. You require a Lithium-Ion battery charge controller.

The best source for these kinds of things at a small size is retailers of model vehicle parts.
> 1 votes

---
Tags: arduino-nano, robotics
---


# Question
Title: AnalogWrite only working for one pin of RGB LED
I'm working on some code for a Nerf blaster with an LED indicator light. When attempting to use analogWrite to PWM my LED pins, only one pin (blue) behaves as expected and dims down. The other two (red, green) don't light up at all. The LED is confirmed working and the Arduino.cc fade example works fine on each pin individually when testing. Here is the code:

```
#include <ClickButton.h>
#include <Servo.h>

Servo esc;

ClickButton rev(6, LOW, CLICKBTN_PULLUP);
ClickButton mode(7, LOW, CLICKBTN_PULLUP);
ClickButton trig(8, LOW, CLICKBTN_PULLUP);

int flyPin = 2;
int escPin = 3;
int pushPhasePin = 4;
int pushSpeedPin = 5;
int RED = 9;
int GREEN = 10;
int BLUE = 11;

int m = 1;
int singleShot = 100;

bool shot = false;

void setup() {
  pinMode(flyPin, OUTPUT);
  pinMode(pushPhasePin, OUTPUT);
  digitalWrite(pushPhasePin, HIGH);
  pinMode(pushSpeedPin, OUTPUT);

  pinMode(RED, OUTPUT);
  pinMode(GREEN, OUTPUT);
  pinMode(BLUE, OUTPUT);

  esc.attach(escPin, 1000, 2000);
  esc.write(0);

  digitalWrite(RED, HIGH);
  digitalWrite(BLUE, HIGH);
  digitalWrite(GREEN, HIGH);
  delay(500);
  digitalWrite(RED, LOW);
  digitalWrite(BLUE, LOW);
  digitalWrite(GREEN, LOW);
  delay(500);
  digitalWrite(RED, HIGH);
  digitalWrite(BLUE, HIGH);
  digitalWrite(GREEN, HIGH);
  delay(500);
  digitalWrite(RED, LOW);
  digitalWrite(BLUE, LOW);
  digitalWrite(GREEN, LOW);
  delay(1500);
}

void loop() {
  rev.Update();
  mode.Update();
  trig.Update();

  if (mode.clicks != 0) {
    m++;
    if (m > 3) {
      m = 1;
    }
  }

  if (m == 1) {
    digitalWrite(RED, LOW);
    digitalWrite(BLUE, LOW);
    analogWrite(GREEN, 120);
  }
  else if (m == 2) {
    digitalWrite(RED, LOW);
    analogWrite(BLUE, 120);
    digitalWrite(GREEN, LOW);
  }
  else if (m == 3) {
    analogWrite(RED, 120);
    digitalWrite(BLUE, LOW);
    digitalWrite(GREEN, LOW);
  }

  if (rev.depressed) {
    digitalWrite(flyPin, HIGH);
    esc.write(40);
  }
  else {
    digitalWrite(flyPin, LOW);
    esc.write(0);
  }

  if (trig.depressed) {
    if (m == 1) {
      if (!shot) {
        digitalWrite(pushSpeedPin, HIGH);
      }
      delay(singleShot);
      shot = true;
      digitalWrite(pushSpeedPin, LOW);
    }
    if (m == 2) {
      if (!shot) {
        digitalWrite(pushSpeedPin, HIGH);
      }
      delay(singleShot * 3);
      shot = true;
      digitalWrite(pushSpeedPin, LOW);
    }

    if (m == 3) {
      digitalWrite(pushSpeedPin, HIGH);
    }
  }

  else {
    digitalWrite(pushSpeedPin, LOW);
    shot = false;
  }
}

```

The relevant portion that is failing is under the "if m == 1,2,3" blocks. Where m \[for mode\] == 2, the blue light works but the other leds do not light when cycling through the modes. Note the leds are on PWM pins (9,10,11). Thanks for any help!

# Answer
> 2 votes
You are trying to combine the use of the Servo library and PWM on pins 9 and 10. You can't do both. PWM on pins 9 and 10 uses the same timer as the servo library.

As it states on the Servo library web page:

> The Servo library supports up to 12 motors on most Arduino boards and 48 on the Arduino Mega. **On boards other than the Mega, use of the library disables analogWrite() (PWM) functionality on pins 9 and 10, whether or not there is a Servo on those pins.** On the Mega, up to 12 servos can be used without interfering with PWM functionality; use of 12 to 23 motors will disable PWM on pins 11 and 12.

---
Tags: arduino-uno, led, rgb-led, analogwrite
---


# Question
Title: Is there a constant for the Maximum Unsigned Long value in an Arduino compiler?
I am writing a timer function that uses the micros() function which generates a unsigned long value. To compensate for a roll over condition, I would like to use the maximum value for that variable type. I have a number, 4,294,967,295, but was expecting that to be a constant somewhere.

Is there a MAX\_UNSIGNED\_LONG constant in the Arduino compiler files somewhere?

I have tried that name and know it probably isn't that. Still poking around.

# Answer
Various `limits.h` files in the `avr-gcc` hierarchy define `ULONG_MAX`, which may be the value you want. For example, on my system such files have paths ending with `hardware/tools/avr/lib/gcc/avr/4.8.1/include-fixed/limits.h` or with `hardware/tools/avr/lib/gcc/avr/4.8.1/install-tools/include/limits.h` and contain definitions like the following.

```
/* Maximum value an `unsigned long int' can hold.  (Minimum is 0).  */
#undef ULONG_MAX
#define ULONG_MAX (LONG_MAX * 2UL + 1UL)

```

Note, `LONG_MAX` also is defined in `limits.h`.

Note, arithmetic done in a form like

```
timeDelta = micros() - prevTime;

```

will be correct (regardless of whether `micros()` overflowed) for elapsed times up to 2³² microseconds, or about 4295 seconds.
> 9 votes

# Answer
You don't need "to compensate for a roll over condition".

See my answer: https://arduino.stackexchange.com/a/33577/10794

---

> in an Arduino compiler?

The "Arduino" compiler is a C++ compiler. That is the starting point for most questions. If you Google for:

```
maximum unsigned long in c++

```

You will find the first link leads to:

http://www.cplusplus.com/reference/climits/

In that it says:

```
ULONG_MAX   Maximum value for an object of type unsigned long int

```
> 4 votes

# Answer
Did you try to do this?:

```
unsigned long maxUnsignedLong = 0UL - 1UL;

```

or:

```
const unsigned long ULONG_MAX = 0UL - 1UL;

```
> 3 votes

---
Tags: arduino-uno, compiler
---


# Question
Title: What's wrong with infinite loops inside loop()?
I wanted to run the following code as something similar to Tone or pwm. However for some reason that I am unable to seek it doesn't work.

```
#define WAIT 3200UL

void setup() {
  DDRB |= B00000001;  // set pin8 as output
}

void loop() {
  unsigned long t;
  while (1) {

    PORTB &= B11111110; // clear pin 8

    for (t = 0 ; t < WAIT; t++);

    PORTB |= B00000001; // set pin 8

    for (t = 0; t < WAIT; t++);

    //            PORTB &= B11111110;
    //            delayMicroseconds(WAIT);
    //            PORTB |= B00000001;
    //            delayMicroseconds(WAIT);

  }
}

```

the code is pretty simple, just toggling a pin. If I use the commented section, it works fine but as is, it doesn't work.

I removed the "while(1)" statement since it was unnecessary for now, it started to work improperly, (changing the WAIT didn't have any effect and I'm not sure I'm getting a full swing).

Pin 8 is connected to an LED + R to ground and a piezzo in parallel to them. the LED seems to be steady on yet the buzzer makes a low noise. I measured a voltage of 3.8v DC and arround 9v AC on the pin, other pins I ran the code for were similar.

As another attempt I put a Serial.print in the beginning of the while(1) but it printed out only once.

Also looked at the assembly code generated for a clue to find out what does delayMicroseconds() do but couldn't figure out what's wrong.

Appreciate your help.

# Answer
First, I will give you some unsolicited advise about your coding style. Instead of writing:

```
PORTB &= B11111110;
...
PORTB |= B00000001;

```

you could write:

```
PORTB &= ~_BV(PB0);
...
PORTB |= _BV(PB0);

```

These are standard AVR idioms, and they make it clearer that you are toggling the pin PB0.

Then, to answer your actual question, your delay loop does not work because it got optimized-out by the compiler. This has already been said in Michel Keijzers' answer, but let me elaborate.

All modern compilers are *optimizing* compilers. This means they can change your code in whatever way they see fit, as long as the *visible effects* remain the same. The effects considered *visible* are usually I/O and access to variables declared `volatile`. Quite importantly, the *slowness* of the program is *not* considered a visible effect for the purpose of optimization. And if you think about it, it makes good sense: if the slowness of the program were to be preserved, then any form of optimization would be impossible. Thus, a loop that has no effect other than slowing your program down can legitimately be optimized-out.

The solution to your problem is quite simple: if you want a delay, then call `delayMicroseconds()`. Or maybe even `delay()` if you are OK with its low resolution. On the other hand, if you need sub-microsecond resolution, you can call `_delay_us()`, from the avr-libc. This function (or rather, macro) provides single-cycle resolution. If you write

```
#include <util/delay.h>

...
_delay_us(1.375);

```

you get *exactly* what you ask for, i.e. a delay of 22 CPU cycles (on an Arduino Uno clocked at 16 MHz). The issues with this function are that it is AVR-specific, and its argument must be a compile-time constant.

It has been suggested to you to write your delay loop using a `volatile` loop counter. I strongly advise you *against* doing that, for three reasons:

1. Doing so will force the counter to be allocated to RAM, thus consuming a scarce and valuable resource for no good reason.
2. Incrementing a RAM-based 32-bit counter takes 20 CPU cycles. Add to this the time required to test the end-of-loop condition and you will realize that your delay resolution is way worse than that of `delayMicroseconds()`.
3. Your actual delay will depend on the clock frequency, and probably also on the compiler's version, making your code pretty fragile.
> 4 votes

# Answer
First

```
t = WAIT;
for (t = 0; t < WAIT; t++);

```

The first statement is not useful, since t will be assigned to 0 in the for loop.

However, since t is not used, probably it is optimized and removed by the compiler, meaning it will not perform a delay.

You should make t volatile. This prevents the compiler from optimizing it (out).

The only difference with or without the infinite loop is that variable t does not need to be allocated for (and keeps its value from the previous loop), but since the value is overwritten it does not make a difference.
> 1 votes

---
Tags: arduino-uno, loop
---


title: Beetle ble with SD card reader

text:
# Question
Title: Beetle ble with SD card reader
I just started working on a project involving bluno beetle ble. For now, i'm sending the data from beetle to a android app i made.

But, for a fail safe mechanism in case the mobile is not in range or has disconnected from the device, i want to add a SD card reader to the device so i can save the data.

Is it really possible to add SD card reader to beetle ble? If yes, can someone provide any hint on what connections need to be made?

Thanks

# Answer
Eventually I got it working. The connections that i made are as follows:

* SDA pin on beetle -\> SDA pin on SD card module
* SCL pin on beetle -\> SCL pin on SD card module
* GND pin on beetle -\> GND pin on SD card module
* VCC pin on beetle -\> VIN pin on SD card module

Then upload the sample code present on arduino IDE, or you can find it here as well: https://www.arduino.cc/en/Tutorial/ReadWrite

There we go!

EDIT: The soldering is tricky for bluno beetle. Detailed instructions can be found here :
> 0 votes

---
Tags: sd-card, bluno
---


# Question
Title: How to download files from a user/password protected web server (user:passw@ip:port)
I need to do a GET request in the form: `user:passw@ip:port/streaming/channels/1/picture` to capture a still frame from an Ip camera. Is there a way to do this with the `ESP8266HTTPClient.h` library?

The samples show a GET request as: `http.begin(host,port,url);`
What I need to do is get the `user:passw@` put in before the `host:url`

# Answer
use the `http.setAuthorization(user, passw)` method.
> 1 votes

# Answer
It would depend whether it's digest or basic authentication. If former, you have a nice example here: https://github.com/esp8266/Arduino/blob/master/libraries/ESP8266HTTPClient/examples/DigestAuthorization/DigestAuthorization.ino

and if it's the latter, you can just do something like this: `http.begin("http://user:password@example.com/test.html");`
> 0 votes

---
Tags: esp8266
---


# Question
Title: UART communication, is it possible to use only the TX line?
I am trying to connect an *ESP-01* with an *ArduinoMega* through the **serial** port of both, as they use different voltage levels I would need a voltage divider between the TX pin of the Mega (pin 1) and the pin RX of the ESP-01 (pin 4) , it is not difficult to do, but I just need to *"send data"* from *ESP-01* to *Mega*, then I have a question and it is as follows:

If I just need to **send** data from one device to the other, could I just connect the **TX** pin of the *ESP-01* to the **RX** of the *Mega*? If I do so, will I receive data in the Mega?

Greetings

# Answer
> 2 votes
Yes.

You can connect only the the line with which the ESP-01 *transmits* to the Arduino's receiver, and accomplish one-way data transfer.

*However*, the ESP will have to be willing to transmit without prompting, and you will not be able to use the Arduino to setup or configure it. Further, you will not be able to use any in-band signalling to ask the ESP to refrain from sending, so you will have to be sure that your Arduino sketch is generally ready to claim any input which may arrive, and that if there are periods when it is not, the behind-the-scenes serial buffer is large enough.

There's also the question if it is safe to connect the ESP transmit pin directly to the Arduino receive. In the intended direction of operation, it is. But should you ever load code on the Arduino which uses that pin as a GPIO output, there is some risk of damage to the ESP. It's up to you to decide if careful usage will be enough to prevent that; if not, you may want to try something like a 1K series resistor and a schottky diode to clamp the line to the ESP's 3.3v supply, in a way that diverts the current from any accidental 5v output around any internal protection diode that may have more limited power handling.

---
Tags: arduino-mega, esp8266, uart
---


# Question
Title: Uniform timing when using Arduino for data acquisition
I am using Arduino UNO together with a SPI ADC (LTC1859) and SRAM (23CL1024) to record a series of data points at approx 2 kHz sampling rate (let's say a few thousand data points).

I have some questions about how to ensure the data points are sampled at uniform time intervals, down to the precision of a clock cycle.

What are the limitations of Arduino macros in respect to this? Can I replace SPI.transfer() with some lower-level code that will make an improvement?

Even if my code is precise, is the relatively low CPU speed of 16 MHz something to worry about for data sampling rates up to a few kHz?

The time-critical part of my code is as follows, and I'd appreciate suggestions:

\**RE-EDIT. As has been requested, the ADC is LTC1859 and triggers on ~~the slave select falling edge~~ active high of input on the CONVST pin, which is the same time that I make ADC SS low (first line inside the for loop).

Digital outputs:
CONVST = Port B, bit 2
SS ADC = Port B, bit 1
SS SRAM = Port B, bit 0

```
      for(unsigned int i=0;i<DATA_LENGTH;i++){
        PORTB=B11000101;                     // ADC Slave select
        __builtin_avr_delay_cycles(112);     // ADC conversion time
        DATA_MSB=SPI.transfer(ADCbyte1);     // Get 16-bit ADC value as 2 bytes
        DATA_LSB=SPI.transfer(ADCbyte2);
        PORTB=B11000010;                     // SRAM Slave select
        SPI.transfer(WRITE);                 // Write data value to SRAM as 2 bytes
        SPI.transfer((uint8_t)(DATA_ADDRESS >> 16)&0xFF);
        SPI.transfer((uint8_t)(DATA_ADDRESS >> 8)&0xFF);
        SPI.transfer((uint8_t)(DATA_ADDRESS));
        SPI.transfer(DATA_MSB);
        SPI.transfer(DATA_LSB);
        PORTB=B11000011;                     // Deselect both ADC and SRAM slaves
        DATA_ADDRESS++;
        DATA_ADDRESS++;
        __builtin_avr_delay_cycles(7600);    // Delay makes 1/sampling rate.  7600 = 2 kHz
      }                                      // Repeat for number of data points

```

\**EDIT. Also, I have done some further tests and replaced occurrences of `SPI.transfer(data);` with `SPDR = data;` followed by waiting a constant number of clock cycles to ensure the data clears. I checked out the timing accuracy by measuring a sine wave voltage input and analyzing the FFT of the recorded data. Overall timing accuracy was improved but I do not see evidence that this part of code limits how uniformly the data are sampled. I have not tried Nick Gammon's suggestion yet to use timer interrupts.

Below is an example of the real-world data that I am recording. The ADC is digitizing data at 16 bit, 2 KHz from a magnetometer with around 10-15 T/Hz1/2 sensitivity, then passing to a PC running Qt where I plot the time-domain data and frequency-domain data after FFT.

The signal is laboratory magnetic background and contains harmonics of the 50 Hz line frequency from mains cables etc. The point of showing the data is that I am not stuck getting the data acquisition to work. I want to improve the data acquisition code as far as possible within the limits of Arduino.

SOLUTION: I modified Edgar Bonet's code in the accepted answer to use timer1 for PWM control of ADC trigger (CONVST, OC1B = Arduino pin 10). This worked successfully.

Learning points for me were:

(1) much greater accuracy in ADC sampling rate. The resonator frequency is accurate enough for my purposes at kHz sampling that I don't need fiddly calibrations of `for` loop duration;

(2) much better way of programming a DAQ. Using the state machine concept, I can run other processes in parallel with the DAQ without penalties in timing accuracy.

```
void loop(){

switch (statemachine){

// other cases, including reading serial data from PC

case 2: // Initialize data acquisition
cli();
data_address=0;
data_counter=0;
statemachine=3;
TCCR1A=0;
TCCR1B=0;
OCR1A=124; // 16 MHz / (64 * 125) = 2000 Hz
OCR1B=1;
TCCR1A = _BV(COM1B1)  // Clear pin OC1B on compare match, set at BOTTOM, noninverting
| _BV(WGM10)          // fast PWM mode 15, TOP = OCR1A
| _BV(WGM11) ;        // fast PWM mode 15.
TCCR1B = _BV(WGM12)   // fast PWM mode 15
| _BV(WGM13)          // fast PWM mode 15
| _BV(CS11)           // Set timer prescaler to 64.
| _BV(CS10) ;         // Set timer prescaler to 64.
TCNT1=0x03;
TIFR1 |= _BV(OCF1A); // Clear match flag
break;

case 3: // Acquire data and store.
loop_until_bit_is_set(TIFR1,OCF1A);
TIFR1 |= _BV(OCF1A);              // Clear match flag
PORTB=B11000101;                  // ADC SS
__builtin_avr_delay_cycles(160);  // 10 us
msb=SPI.transfer(ADCbyte1);
lsb=SPI.transfer(ADCbyte2);
PORTB=B11000010;                  // SRAM SS
SPI.transfer(WRITE);
SPI.transfer((uint8_t)(data_address >> 16) & 0xFF);
SPI.transfer((uint8_t)(data_address >> 8)  & 0xFF);
SPI.transfer((uint8_t)(data_address));
SPI.transfer(msb);
SPI.transfer(lsb);
PORTB=B11000011;
data_address++;
data_address++;
data_counter++;
if(data_counter==data_length){statemachine=4;} // Data capture complete
break;

// other cases, including data transfer to PC
}
}

```

# Answer
> the ADC is LTC1859 and triggers on the slave select falling edge.

No, it doesn't. Here is a link to its datasheet. It has a pin labeled CONVST, for “*conversion start*”. According to the section *Pin functions*, “This active high signal starts a conversion on its rising edge.”

If you want your sampling to be at 2 kHz with cycle-accurate timings, you have to send to this pin a train of pulses which are at least 40 ns wide and have a period of 500 µs, i.e. 8,000 CPU cycles. This can be done with any of the three timers of the Uno. For example, you can set Timer 2 to repeatedly count from 0 to 124 with a prescaler of 64. Your initialization would have something like this:

```
// Initial transfer to configure the ADC.
PORTB &= ~_BV(SS_ADC);
SPI.transfer(ADCbyte1);
SPI.transfer(ADCbyte2);
PORTB |= _BV(SS_ADC);

// Configure Timer 2 for PWM on pin OC2B = PD3 = digital 3.
DDRD  |= _BV(PD3);    // pin PD3 as output
TCCR2A = 0;           // undo the Arduino core's configuration
TCCR2B = 0;           // ditto
OCR2A  = 125 - 1;     // period = 64 * 125 CPU cycles = 500 us
OCR2B  =   2 - 1;     // high for 64 *   2 CPU cycles =   8 us
TCNT2  = 122;         // first pulse in 8 to 12 us
TIFR2 |= _BV(OCF2B);  // clear the output compare flag
TCCR2A = _BV(COM2B1)  // non-inverting PWM on pin OC2B
       | _BV(WGM20)   // mode 7: fast PWM, TOP = OCR2A
       | _BV(WGM21);  // ditto
TCCR2B = _BV(WGM22)   // ditto
       | _BV(CS22);   // clock at F_CPU/64

```

Note that the timer will also set a flag when the pulse is done, at which time you can start the data transfer. You would then start your data-taking loop with:

```
// Wait for the output compare flag.
loop_until_bit_is_set(TIFR2, OCF2B);

// Clear the flag.
TIFR2 |= _BV(OCF2B);

// Now transfer the data.
...

```

**Edit 1**: I would just want to add that *cycle accurate* timing does not mean *perfectly uniform* timing. The Arduino Uno is clocked off a ceramic resonator. This kind of resonator, in addition to having bad accuracy, has poor frequency stability. To get an idea of how bad it can be, see the Allan deviation plots on the article Arduino clock frequency accuracy, by Joris van Rantwijk.

**Edit 2**: After some tests, I wrote a more complete initialization:

* An initial SPI transaction is used to prime the ADC, as suggested by Chris Stratton
* the PWM pin is configured as an output
* the Arduino core's Timer setup is undone before applying the new configuration
* the very first pulse on CONVST is scheduled to happen not too long after the initialization, yet after tACQ
* the output compare flag is cleared during the initialization.
> 2 votes

# Answer
I did a project generating VGA signals that required highly precise timing for the sync pulses.

The technique that worked for me was:

* Use the hardware timers to generate the required pulse interval
* Put the processor to sleep (`set_sleep_mode (SLEEP_MODE_IDLE);`) to remove jitter caused by whether the interrupt occurred while an instruction was executing (interrupts can't interrupt half-way through a multi-cycle instruction).

So in your case I would set up the timer (eg. Timer 1) to generate the appropriate interrupts. Then go to sleep waiting for the interrupt. The ISR doesn't have to do anything in particular, you just want to pause until the interrupt happens. For example you could do this:

```
EMPTY_INTERRUPT (TIMER1_COMPA_vect);

```

That will generate a "do nothing" interrupt handler for Timer 1 compare-A vector.

Once the interrupt happens you will pass the sleep instruction and then you can do your ADC sample and send the results. You may want to scale back the ADC clock a bit (eg. a prescaler of 64) to speed up the ADC sample a bit.

See my page about the ADC and my page about interrupts.

---

## Automatic mode

Another possibility is to use the automatic ADC conversion, as in this example from my page about the ADC:

```
const byte adcPin = 0;  // A0

const int MAX_RESULTS = 256;

volatile int results [MAX_RESULTS];
volatile int resultNumber;

// ADC complete ISR
ISR (ADC_vect)
  {
  if (resultNumber >= MAX_RESULTS)
    ADCSRA = 0;  // turn off ADC
  else
    results [resultNumber++] = ADC;
  }  // end of ADC_vect

EMPTY_INTERRUPT (TIMER1_COMPB_vect);

void setup ()
  {
  Serial.begin (115200);
  Serial.println ();

  // reset Timer 1
  TCCR1A = 0;
  TCCR1B = 0;
  TCNT1 = 0;
  TCCR1B = bit (CS11) | bit (WGM12);  // CTC, prescaler of 8
  TIMSK1 = bit (OCIE1B);  // WTF?
  OCR1A = 39;
  OCR1B = 39;   // 20 uS - sampling frequency 50 kHz

  ADCSRA =  bit (ADEN) | bit (ADIE) | bit (ADIF);   // turn ADC on, want interrupt on completion
  ADCSRA |= bit (ADPS2);  // Prescaler of 16
  ADMUX = bit (REFS0) | (adcPin & 7);
  ADCSRB = bit (ADTS0) | bit (ADTS2);  // Timer/Counter1 Compare Match B
  ADCSRA |= bit (ADATE);   // turn on automatic triggering

  // wait for buffer to fill
  while (resultNumber < MAX_RESULTS)
    { }

  for (int i = 0; i < MAX_RESULTS; i++)
    Serial.println (results [i]);

  }  // end of setup

void loop () { }

```

The code above will take 256 samples at 50 kHz frequency. You could modify the ISR to send the results by SPI (SPI transfers should be OK inside an ISR) if you needed to take more samples and save them elsewhere.

---

> Even if my code is precise, is the relatively low CPU speed of 16 MHz something to worry about for data sampling rates up to a few kHz?

No, I don't think so.
> 1 votes

---
Tags: arduino-uno, spi, datalogging, speed
---