title: Reducing Memory Usage lots of Floats

text:
# Question
Title: Reducing Memory Usage lots of Floats
Im using an Arduino Uno - All code at github.com/robbrad/AirQuality

Current sketch usage:

```
Sketch uses 23186 bytes (71%) of program storage space. Maximum is 32256 bytes.
Global variables use 1428 bytes (69%) of dynamic memory, leaving 620 bytes for local variables. Maximum is 2048 bytes.

```

I wouldn't normally just spam code for a optimisation - but im looking to get about 10% memory back from this sketch

It basically checks a bunch of sensors sets the values to floats, build a string and posts that to a php page where some more processing happens.

I have tried everything to my knowledge but I just cant think of a smarter way to use less memory.

I tried an array, a function to build the data string, using one float and concatenating it to the string when it set

I even thought of reducing the Math.h include to just the math functions I was using

Maybe im just reaching the little boards limits (which are pretty good anyway :) ! )

```
#include <SPI.h>
#include <Ethernet.h>
#include "DHT.h"
#include <math.h>
#include <Wire.h>
#include "MutichannelGasSensor.h"
#include "HP20x_dev.h"
#include "KalmanFilter.h"

unsigned char ret = 0;

/* Instance */
KalmanFilter t_filter;    //temperature filter
KalmanFilter p_filter;    //pressure filter
KalmanFilter a_filter;    //altitude filter

// Enter a MAC address for your controller below.
// Newer Ethernet shields have a MAC address printed on a sticker on the shield
byte mac[] = { 0xDE, 0xAD, 0xBE, 0xEF, 0xFE, 0xED };
// if you don't want to use DNS (and reduce your sketch size)
// use the numeric IP instead of the name for the server:
IPAddress server(192, 168, 0, 30); // numeric IP for Google (no DNS)
//char server[] = "www.google.com";    // name address for Google (using DNS)

// Set the static IP address to use if the DHCP fails to assign
IPAddress ip(192, 168, 0, 40);

// Initialize the Ethernet client library
// with the IP address and port of the server
// that you want to connect to (port 80 is default for HTTP):
EthernetClient client;

#define Vc 4.95
//the number of R0 you detected just now
#define R0 35.54
#define DHTPIN A1     // what pin we're connected to

// Uncomment whatever type you're using!
//#define DHTTYPE DHT11   // DHT 11
#define DHTTYPE DHT22   // DHT 22  (AM2302)
//#define DHTTYPE DHT21   // DHT 21 (AM2301)

DHT dht(DHTPIN, DHTTYPE);

int pin = 8;
unsigned long duration;
unsigned long starttime;
unsigned long sampletime_ms = 2000;//sampe 30s ;
unsigned long lowpulseoccupancy = 0;
float ratio = 0;
float concentration = 0;
String data = "";

void setup() {
  Serial.begin(9600);
  while (!Serial) {
    ; // wait for serial port to connect. Needed for native USB port only
  }

  delay(150);
  HP20x.begin();
  delay(100);

  /* Determine HP20x_dev is available or not */
  ret = HP20x.isAvailable();

  pinMode(8, INPUT);
  starttime = millis();//get the current time;
  //Serial.println("power on!");

  pinMode(4, OUTPUT);
  digitalWrite(4, HIGH);

  //if (Ethernet.begin(mac) == 0) {
  //  Serial.println("Failed to configure Ethernet using DHCP");
  // try to congifure using IP address instead of DHCP:
  Ethernet.begin(mac, ip);

  // give the Ethernet shield a second to initialize:
  delay(10000);
  // Serial.println("connecting...");
  //}
  // give the Ethernet shield a second to initialize:
  //delay(1000);
  //Serial.println("connecting...");

  // Serial.println(Ethernet.localIP());

  gas.begin(0x04);//the default I2C address of the slave is 0x04
  gas.powerOn();
  //Serial.print("Firmware Version = ");
  //Serial.println(gas.getVersion());
  //Serial.println("Particles\tRS\tHCHO (PPM)\tNH3 (PPM)\tCO (PPM)\tNO2     (PPM)\tC3H8 (PPM)\tC4H10 (PPM)\tCH4 (PPM)\tH2 (PPM)\tC2H5OH (PPM)");
  dht.begin();
  delay(10000);

}

void loop() {

  if (client.available()) {
    char c = client.read();
    //  Serial.print(c);
  }

  float HATemp2;
  float HAPres2;
  float HAAlt2;
  float d;

  if (OK_HP20X_DEV == ret)
  {
    unsigned long HATemp = HP20x.ReadTemperature();
    d = HATemp / 100.0;
    HATemp2 = t_filter.Filter(d);

    unsigned long HAPres = HP20x.ReadPressure();
    d = HAPres / 100.0;
    HAPres2 = p_filter.Filter(d);

    unsigned long HAAlt = HP20x.ReadAltitude();
    d = HAAlt / 100.0;
    HAAlt2 = a_filter.Filter(d);

  }

  duration = pulseIn(pin, LOW);
  lowpulseoccupancy = lowpulseoccupancy + duration;

  if ((millis() - starttime) >= sampletime_ms) //if the sampel time = = 30s
  {
    ratio = lowpulseoccupancy / (sampletime_ms * 10.0); // Integer percentage 0=>100

    d = 1.1 * pow(ratio, 3) - 3.8 * pow(ratio, 2) + 520 * ratio + 0.62; // using spec sheet curve
    //Serial.print("concentration = ");

   lowpulseoccupancy = 0;
    starttime = millis();
  }

 //Serial.print("\t");
  //HCHO

  int sensorValue = analogRead(A0);
  double Rs = (1023.0 / sensorValue) - 1;

  double ppm = pow(10.0, ((log10(Rs / R0) - 0.0827) / (-0.4807)));
  //Serial.print("HCHO ppm = ");

  //MultiChannel Gas
  float NH3 = gas.measure_NH3();
  float CO = gas.measure_CO();
  float NO2 = gas.measure_NO2();
  float C3H8 = gas.measure_C3H8();
  float C4H10 = gas.measure_C4H10();
  float CH4 = gas.measure_CH4();
  float H2 = gas.measure_H2();
  float C2H5OH = gas.measure_C2H5OH();

  // Reading temperature or humidity takes about 250 milliseconds!
  // Sensor readings may also be up to 2 seconds 'old' (its a very slow sensor)
  float h = dht.readHumidity();
  float t = dht.readTemperature();

  data = String("dust=") + d + "&rs=" + Rs + "&hcho=" + ppm + "&nh3=" + NH3 + "&co=" + CO + "&no2=" + NO2 + "&c3h8=" + C3H8 + "&c4h10=" + C4H10 + "&ch4=" + CH4 + "&h2=" + H2 + "&c2h5oh=" + C2H5OH + "&temp=" + t + "&hum=" + h + "&HATemp=" + HATemp2 + "&HAPres=" + HAPres2 + "&HAAlt=" + HAAlt2;

  //Serial.println(data);

  if (client.connect(server, 80)) {
    Serial.println(F("connected"));
    client.println(F("POST /air_add.php HTTP/1.1"));
    client.println(F("Host:  192.168.0.30"));
    client.println(F("User-Agent: Arduino/1.0"));
    client.println(F("Connection: close"));
    client.println(F("Content-Type: application/x-www-form-urlencoded;"));
    client.print(F("Content-Length: "));
    client.println(data.length());
    client.println();
    client.println(data);
  }
  else
  {
    Serial.println(F("could not connect"));
  }

  Serial.println(data);

  if (client.connected()) {
    client.stop();
  }

  delay(300000);
}

```

# Answer
> 5 votes
I counted the floats in the sketch:

```
Global: 2
setup: 0
loop: 14
Total: 16 floats -> 64 bytes.

```

If you want to reduce that, don't wait to have all your values before preparing your answer. You will use less memory if you do

```
  data = String("dust=") + dht.readHumidity();
  data+= "&rs=" + (1023.0 / sensorValue) - 1;
  data+= "&hch0=" + pow(10.0, ((log10(Rs / R0) - 0.0827) / (-0.4807)));
  ... and the rest ...

```

Your `data` String and concat's take way more space than the floats. Use char\[\] instead of string.

As last resort, you don't need to construct the complete POST before sending it to the server. Send it line by line, value by value. Use a fixed, big enough `Content-Length:`, padding with spaces after you send the values and know the actual lenght.

Or you can switch your technology: MQTT need way less memory than HTTP.

# Answer
> 2 votes
Two basic approaches:

1) use fixed point math. or

1) use int16\_t or int32\_t in lieu of the floating types. for example, you can use x10 or x100 to designate variables with some decimal points. use x16 or x128 or even x256 for speed gains as well. you will need to make sure that it doesn't overflow.

edit: here is an example that hopefully will help you get it going.

```
void setup() {
    Serial.begin(9600);
    var1=100;               //var1=1.00
    var2=123;               //var2=1.23
}

void loop() {
    var1+=var2;             //increment var1
    Serial.print("var1 = "); Serial.print(var1 / 100); Serial.print("."); Serial.print(var1 - (var1 / 100) * 100); Serial.println(".");
    delay(100);
}

```

var1 (1.00 initially) is incremented by var2 (1.23), both are int32\_t types.

here is the printout.

# Answer
> 1 votes
I second the advice that has already been given to you about avoiding `String`. Other than that, using fixed-point math could be a big win, but given the math you do it won't be any easy.

Assuming you stick with floating point, I just found a couple of easy optimization opportunities:

* Do not use `pow` to evaluate a polynomial. Use the Horner's method which is way cheaper: `d = ((1.1*ratio - 3.8)*ratio + 520)*ratio + 0.62`.
* The expression of ppm can be simplified: `ppm = 2500.33 * pow(Rs, -2.0803)`.

---

**Edit**: You could also try to implement chunked transfer encoding. This way you could send the data to the server on the fly, as you collet it, instead of storing everything in memory and sending it in one go.

Example:

```
void send_chunk(Print &connection, const String &chunk)
{
    connection.println(chunk.length, 16);
    connection.println(chunk);
}

void loop() {
    // ...

    // last header sent to the client:
    client.println(F("Transfer-Encoding: chunked"));
    client.println();

    // Now the data:
    String chunk;
    chunk = "dust=";
    chunk += ((1.1*ratio - 3.8)*ratio + 520)*ratio + 0.62;
    send_chunk(client, chunk);
    chunk = "&rs=";
    chunk += Rs;
    send_chunk(client, chunk);
    chunk = "&hcho=";
    chunk += 2500.33 * pow(Rs, -2.0803);
    send_chunk(client, chunk);
    chunk = "&nh3=";
    chunk += gas.measure_NH3();
    send_chunk(client, chunk);
    // and so on...
    chunk = "";
    send_chunk(client, chunk);  // Empty chunk means end of message.

    // ...
}

```

Notice that there is no "Content-Length" header. Instead, each chunk is preceded by its size in hex. And, most importantly, notice that this way you can get rid of lots of variables.

---

**Edit 2**: I came out with a better (more generic) way to implement chunked encoding, which involves sending the data through a “chunker” filter that does the encoding and outputs to the client. Here is my `Chunker` class:

```
/*
 * Transfer a message using the HTTP/1.1 "Chunked Transfer Coding".
 * C.f. https://tools.ietf.org/html/rfc7230#section-4.1
 */
class Chunker : public Print
{
public:
    Chunker(Print &downstream) : downstream(downstream), pos(0) {}

    virtual size_t write(uint8_t c)
    {
        buffer[pos++] = c;
        if (pos == BUFFER_SIZE)
            send();
        return 1;
    }

    void end()
    {
        if (pos) send();
        send();  // empty chunk means end of message
    }

private:
    static const uint8_t BUFFER_SIZE = 32;
    Print &downstream;
    uint8_t buffer[BUFFER_SIZE];
    uint8_t pos;

    // Send the buffer as a chunk.
    void send()
    {
        downstream.println(pos, HEX);
        if (pos) {
            downstream.write(buffer, pos);
            downstream.println();
            pos = 0;
        }
    }
};

```

And here is how you would use it:

```
Chunker message(client);  // instantiate the filter
message.print(F("dust="));
message.print(((1.1*ratio - 3.8)*ratio + 520)*ratio + 0.62);
message.print("&rs=");
message.print(Rs);
message.print(F("&hcho="));
message.print(2500.33 * pow(Rs, -2.0803));
message.print(F("&nh3="));
message.print(gas.measure_NH3());
// and so on...
message.end();  // terminate the chunked message

```

The main advantage of this method is that you completely avoid using the `String` class, which means no dynamic memory allocation (a very desirable thing). Also you can choose your buffer size. I've set it to 32 bytes, but you can make it smaller if needed.

---
Tags: sensors, code-optimization, memory-usage
---


# Question
Title: Arduino Serial data communication with NodeJS
I am using an Arduino Uno and a DTH11 temperature sensor to read temperature and then send that value to a computer via the serial port.

A NodeJS application is running on the computer and captures that value and writes to a log file.

When I try to get values from my NodeJS application, sometimes the value is broken into two values. `Eg: 25 -> 2 and 5`

This is my Arduino code:

```
dht DHT;

#define DHT11_PIN 7
float tem [4];

void setup() {
  Serial.begin(9600);
  pinMode(12, OUTPUT);
}

void loop() {
  int chk = DHT.read11(DHT11_PIN);
  int val = (int)(DHT.temperature);
  Serial.println(val);
  delay(600000);
}

```

This is my NodeJS program.

```
var fs = require('fs')
var logger = fs.createWriteStream('/data/Temperature/temperature.csv', {
  flags: 'a' // 'a' means appending (old data will be preserved)
})

var SerialPort = require("serialport")
var serialPort = new SerialPort("/dev/ttyACM0", {
  baudRate: 9600,
});

serialPort.on("open", function () {
  serialPort.on('data', function(data) {
    var moment = require('moment');
    var dayTime = moment().format('YYYY-MM-DD,hh:mm');
    var val1 = data.toString();
    var val = val1.trim();
    if (val == '') {
      console.log('no data');
    else {
      console.log(val);
      logger.write(dayTime + ',' + val + '\n');
    }
  });
});

```

Is it a problem with my code?

Thanks in advance.

# Answer
As Look Alterno wrote in a comment, you need to parse the incoming data on the receiving side. In this instance, you have to look for the line terminators. The Node.js serialport module provides a parser for this called Readline. Read that doc and use it.
> 1 votes

---
Tags: arduino-uno, serial, temperature-sensor, serial-data, node.js
---


# Question
Title: Is it possible to increase the Arduino's input and output pins?
I am undergoing a BSc (Hons) Degree in Computer Science and working on an Arduino project.

I am using the Arduino Mega and even though this microprocessor has plenty of input and output pins I am running out.

In the event that there are no more I/O pins available for me to make use of, and I am also referring to both analog and digital pins, is it possible to increase them?

I did some research, however the solutions are too vague... One of the suggestions was to use one or more of the following: 74HC595 8-Bit Shift Register DIP-16.

I am good at coding however when it comes to hardware sometimes I'll need some push.

Thanks a lot.

# Answer
> 3 votes
You could use an MCP23017 port expander to get 16 more pins. It communicates via I2C. The pins can be set as inputs, outputs, or inputs with pullups.

Adafruit has a library for the expander: https://github.com/adafruit/Adafruit-MCP23017-Arduino-Library

This is the datasheet: http://ww1.microchip.com/downloads/en/DeviceDoc/21952b.pdf

As an alternate solution, you could just add another Arduino Mega to your project, and have them both communicate via serial. You could set up state machines on each one (like in Mr. Gammon's tutorials: http://www.gammon.com.au/statemachine) for fast communication. That way you could easily add an extra 52 pins to your project.

# Answer
> 1 votes
You can either use external hardware or communicate to a 2nd Arduino and control the 2nd Arduino's digital and analog ports. Being good at coding would suggest you would prefer communicating to a 2nd Arduino. Also, most hardware solutions only add digital pins, not analog pins.

# Answer
> -1 votes
You can use a CD74HC4067 Mux multiplexer to increase the number of inputs/outputs. This IC will convert 4 analog or 4 digital pins to 16 inputs and outputs.

---
Tags: arduino-mega, pins
---


title: Integer array definitions: Length

text:
# Question
Title: Integer array definitions: Length
I'm defining a variable as integer and want to use thati

```
int specLength = 17;
int spec[specLength-1];

```

When I do this, I get the following error message:

```
 TestProgram:34: error: array bound is not an integer constant before  ']' token
 int spec[specLength-1];

```

But when I set it up as

```
int specLength = 17;
int spec[16];

```

it all works fine.

What is the magic here?

Many thanks

# Answer
> 1 votes
You have to use a constant expression, one that produce always the same value.

```
const int specLength = 17;
int spec[specLength - 1];

```

Otherwise, the compiler won't know how much space reserve for the array.

The problem with C/C++ is that the compiler doesn't really know if a variable is modified somewhere or not (thru pointers, for example). You have to tell the compiler that something is `static`, not changing.

You can also use a #define for the same porpuse:

```
#define SPEC_LENGTH 17
int spec[SPEC_LENGTH]

```

Why both? `const int val=17` means that `val` has a type (`int`). Using `#define` is just a text search-and-replace before compiling. So, SPEC\_LENGTH has no type at all. If needed, you have to use a cast, like `(int) SPEC_LENGTH`.

---
Tags: arduino-uno, arduino-ide, c, code-review
---


# Question
Title: Arduino IDE: Board nodemcuv2 (platform esp8266, package esp8266) is unknown
I am receiving this error after reinstalling Arduino IDE (everything was working fine \[same components, same code\]):

> Board nodemcuv2 (platform esp8266, package esp8266) is unknown

I have recently reinstalled ESP8266 libraries. Could that have caused this issue?

# Answer
Did some digging and found a solution that worked for me:

Uninstall (by logically deleting folders) and reinstall ESP Libraries.

Open Arduino IDE Go to FILE -\> PREFERENCES

Open the preferences folder (this works in Linux, Mac and Windows) Go to PACKAGES \> ESP8266 \> HARDWARE \> ESP8266

Delete all libraries (if your issue is similar to mine and to others', you should have 2 or more folders, with different versions).

Restart Arduino IDE. Go to SKETCH \> INCLUDE LIBRARY \> MANAGE LIBRARIES Install ESP8266 Community Go to TOOLS \> BOARD and scroll down to your model of NODEMCU

Run compile and your problem should be fixed.
> 1 votes

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


title: Programming standalone 328P in circuit

text:
# Question
Title: Programming standalone 328P in circuit
I am designing a PCB using a 328P. As I understand it, I can either flash the chip via the ICSP header (without bootloader) or via Serial (if it has a bootloader already). But how does programming actually work?

1. According to my program running on the chip, it acts as master for SPI peripherals. If using ICSP, how does the chip know that it is supposed to act as SPI slave and receive a program?
2. Is there anything I must take into account with regards to what is connected to the SPI pins? i.e. does it harm in any way if I have other SPI slaves on the board connected to these same pins?
3. Same for serial programming: how does the chip know that it's supposed to receive a program on the serial interface, when my application uses this port for a different purpose?

# Answer
> According to my program running on the chip, it acts as master for SPI peripherals. If using ICSP, how does the chip know that it is supposed to act as SPI slave and receive a program?

A special signal is sent using the RESET pin. From the datasheet (p361):

> 1. Power-up sequence: Apply power between VCC and GND while RESET and SCK are set to “0”. In some systems, the programmer can not guarantee that SCK is held low during power-up. In this case, RESET must be given a positive pulse of at least two CPU clock cycles duration after SCK has been set to “0”.
> 2. Wait for at least 20ms and enable serial programming by sending the Programming Enable serial instruction to pin MOSI.
> 3. The serial programming instructions will not work if the communication is out of synchronization. When in sync. the second byte (0x53), will echo back when issuing the third byte of the Programming Enable instruction. Whether the echo is correct or not, all four bytes of the instruction must be transmitted. If the 0x53 did not echo back, give RESET a positive pulse and issue a new Programming Enable command.

---

> Is there anything I must take into account with regards to what is connected to the SPI pins? i.e. does it harm in any way if I have other SPI slaves on the board connected to these same pins?

Yes. It is possible that a chip may respond to the ICSP signals. You should have pullup resistors on all your CS (or SS if you prefer to call it that) pins on all your slave chips so that while the ATMega328P is in programming mode (and all the GPIO pins are in INPUT mode by default) the CS pins of your slaves aren't floating.

---

> Same for serial programming: how does the chip know that it's supposed to receive a program on the serial interface, when my application uses this port for a different purpose?

Simple: it listens for 2 seconds after power-on or reset for a special sequence of bytes arriving on the serial port. If they arrive within that 2-second window (8 seconds for ATMega32U4 based boards, to allow time for USB enumeration) the bootloader keeps running and looking for programming instructions. If it doesn't see that start sequence within the timeout period it exits the bootloader and runs your sketch.

The STK500 protocol (which the Arduino bootloader is based around) is detailed here. The trigger sequence is the "CMD\_SIGN\_ON" command detailed on page 4.
> 1 votes

# Answer
1. You pull the reset pin LOW.

> Both the Flash and EEPROM memory arrays can be programmed using the serial SPI bus while RESET is pulled to GND. The serial interface consists of pins SCK, MOSI (input) and MISO (output). After RESET is set low, the Programming Enable instruction needs to be executed first before program/erase operations can be executed.

2. Most SPI devices have a Chip Select pin. Unless this pin reads LOW, the device isn't listening. That way you can have multiple devices sharing a single SPI bus.
3. You pull the reset pin LOW for a moment. That makes the chip reset itself. When the chip resets, it first runs the bootloader program. The Arduino bootloader waits 3 seconds for any programming instructions coming in via the serial connection. If these 3 seconds have past, it will exit the bootloader and run your main sketch.
> 1 votes

# Answer
Simply follow the hardware design guide from Atmel AVR042
> 0 votes

---
Tags: programming, icsp
---


# Question
Title: #Ardunio Send Float values with bluetooth.print in arduino
I have been creating the example for bluetooth communication with arduino with hc\_05 Problem I am facing are below.

```
String statuss= "1.00,2.00,3.00";
bluetooth.print(statuss);
Serial.print(statuss);

```

This is the code where is get only last 2 digits i.e 00 in android while its showing me complete string in serial monitor.

```
String statuss= "Hello";
bluetooth.print(statuss);
Serial.print(statuss);

```

Then I get the output as **ello** in Android n in Serial monitor it show **Hello**

Can Anybody suggest the whats the problem

# Answer
I suspect (at first sight) a speed problem. Android runs Bluetooth at 115200 Bauds. So you must set your HC-05 o HC-06 at this speed to get proper result.

But as you perform "bluetooth.print(statuss);" and also "Serial.print(statuss);" this mean you have created a virtual port, probably using the Software Serial lib. Unfortunatly, this lib is not very efective. At speed higher than 19200 Bauds, you lost data (I've had a lot of problem with that before understanding!!) The only right way is to use directly the RX and TX port of the Arduino (pin 0 and 1) and use (eg) a LCD Display to display data and help you debugging your Arduino code (as when you plug the HC on Pin 0 and 1 you lost the access to the serial monitor).

A trick: with the HC on pin 0 and 1, each time you send the sketck to the Ardino, you must unplug RX as it's used for sending the code.

Hope this will help.
> 0 votes

# Answer
It is difficult to know your exact problem since you have not provided your code. However, I believe that you don't have a clear starting bit and a clear end bit, so that the modules don't know when to Start and End.
> -1 votes

---
Tags: arduino-uno, bluetooth, android
---


# Question
Title: How to use a coma as the decimal separator?
I have a LCD that displays a float variable. I would like to show a comma instead of a dot as the decimal separator.

```
float temp = 23.50;
lcd.setCursor(0, 0);
lcd.print(temp);

```

I want to show **23,50** instead of **23.50**.

Is there any function to convert or format it?

# Answer
Print the integer part, print a comma, then print the value minus the integer part.

```
float value = 123.45;
int ival = (int)value;
int frac = (value - ival) * 100;

Serial.print(ival);
Serial.print(",");
if (frac < 10) Serial.print("0");
Serial.println(frac);

```
> 3 votes

# Answer
Due to some performance reasons %f is not included in the Arduino's implementation of sprintf(). A better option would be to use dtostrf() - you convert the floating point value to a C-style string, Method signature looks like:

```
char *dtostrf(double val, signed char width, unsigned char prec, char *s)

```

**Demo**

```
void setup() {
  Serial.begin(9600);
  while(!Serial);

  float a = 12.34;
  char buffer[] = "9999.99";
  dtostrf(a, 4, 2, buffer);
  char* p  = strchr(buffer, '.');
  *p = ',';
  Serial.println(buffer);
}

void loop() {

}

```

The `strchr` search for the first ocurrence of second arg ('.' in this case) and return a pointer to that char. You then use that pointer to sustitute '.' with ','.

You have the final string in buffer, where you can use it for whatever purpose you fancy.

Caution: You have to reserve space (buffer) to hold your biggest value.
> 1 votes

# Answer
May be overkill for this simple usage but, if you are printing numbers in more than one place in your program, it may be convenient to implement a filter that replaces all dots with commas.

Here is one such filter:

```
// Replace dots with commas.
class CommaForDot : public Print
{
public:
    CommaForDot(Print &downstream) : downstream(downstream) {}
    virtual size_t write(uint8_t c) {
        return downstream.write(c=='.' ? ',' : c);  // replacement
    }
private:
    Print &downstream;
};

```

And here is a simple test:

```
void setup()
{
    Serial.begin(9600);
    float a = 12.34;

    Serial.print("Through Serial:      ");
    Serial.println(a);

    CommaForDot filteredSerial(Serial);
    Serial.print("Through CommaForDot: ");
    filteredSerial.println(a);
}

void loop(){}

```

The output is:

```
Through Serial:      12.34
Through CommaForDot: 12,34

```
> 1 votes

---
Tags: lcd, variables, float, convert
---


title: How to import my own library or file?

text:
# Question
Title: How to import my own library or file?
I have some small functions to format numbers. I move them to a new file and I would like to import it to my proyect.

I can't find how to do it without defining a class (maybe it's the only way). I would like to import like JavaScript, PHP or other languages: just using the import word or something similar.

I know how to import libraries. Example:

```
#include <OneWire.h>
#include <DallasTemperature.h>

```

# Answer
If the file is in your sketch folder then you use this syntax:

```
#include "foo.h"

```

All source files in the root of the sketch folder are shown as tabs in the Arduino IDE. In some cases that might not be desirable. If so, you can put the file in the `src` subfolder of your sketch folder and use this syntax:

```
#include "src/foo.h"

```

Or you might want to group files together into separate subfolders:

```
#include "src/foo/foo.h"

```

If you want to access the file from multiple sketches then you should turn it into a library and use this syntax:

```
#include <foo.h>

```
> 1 votes

---
Tags: library, class
---


# Question
Title: Oil Pressure / Water Pressure / Boost Pressure ( Turbo Engine )
I'm an automotive enthusiast and I want to build some gauges by myself using Arduino.

I was taking a look at this pressure transducer or sender, 100 psi, stainless steel, for oil, fuel, air, water and I was thinking if I can use this sensor to do all of the these tasks: Water, Boost and Oil Pressure.

Look at the Signal output vs read PSI chart of the sensor

I came out with this equation for the PSI calculation:

Since it is a `Y = bx + a`, where:

```
a = 0.5
b = y2 - y1 / x2 - x1 = (4.5 - 0.5 ) / (100 - 0) = 4/100 = 0.04
x = PSI
y = Signal's Voltage

```

This means that

Voltage Reading = 0.04PSI + 0.5

So we have :

PSI = (Voltage Reading - 0.5 ) / 0.04

Am I correct? Can I use this sensor?

# Answer
You math checks you to me.

When you code it, You will probably read a voltage using an analog pin (or external ADC) that will return an integer between 0 being 0 volts, and 1024 = vin volts. vin will be 5 if you don't wire up the vin pin, and 1024 could be different if you use an external ADC.

Anyway you should be aware that the raw readings will probably not be 0-5, and they dont have decimal points. You will need to first convert the reading into the voltage with something like this:

```
float voltage = ((float)reading)/1024.f;

```

notice that the datatype float is used (enables decimal points) and that the constant being divided by is also a float so that the calculations will definitly happen between floating point numbers.
> 3 votes

# Answer
I'd add code to test for voltage between 0.0 to less than or near 0.5 volts. Disconnected pressure transducer won't present 0.5v, 0 PSI transducer voltage; not output 0.5 v @0 PSI shows a lower voltage indicated a fault or open circuit in transducer wiring. My experiences, too many times other engineers "borrowed" hardware and I wound up troubleshooting a non-fault but theft ;} Only a few lines of code to ensure connections are correct. The floating point vs integer arithmetic compute time is outweighed by settling time of A/D converter and transducer. The auto part was my solution to show HOA board stats for my wildly varying water pressure at Condo Assn, very cost effective too.
> 1 votes

---
Tags: sensors
---


# Question
Title: How to convert the 0-5V to a 4-20mA current loop?
I'm pretty clueless about electronics so everything has to be explained in simple terms to me.

I have an Arduino with a program which provides a value via the Analog output, so that is anything from 0-5V.

On the other side I have a PLC (programmable logic controller) with an IO card which allows to connect to a (4-20mA) current loop.

How do I convert from lets say 1-5V to the 4-20mA in a somewhat cheap and safe way (I don't want to destroy the PLC \[and possibly the Arduino\])?

Of course the Arduino and the PLC have separate power sources.

# Answer
> 1 votes
If all you need is analog 4-20mA loop transmitter, then you need an op-amp, the transistors that its output drives, a sense resistor, and a few other resistors. Note that these are at least 1% resistors. **This needs to be built on a printed circuit board, not a solderless breadboard.** Two of my coworkers at Maxim Integrated wrote an applications note about a 4-20mA current-loop transmitter: http://www.maximintegrated.com/en/app-notes/index.mvp/id/5610 see this figure:

Since you are already using a PWM (hopefully with an RC low-pass filter), you just need everything after the DAC output. (*Performance will not be as good with an Arduino PWM as it would be with a 16-bit voltage-output DAC, but the general idea would still work.*) For your purpose, you can also ignore all of the stuff about the HART modem -- that's an extra feature for sending digital information along the same loop. Only relevant if your PLC receiver was expecting it.

There are also numerous prebuilt 4-20mA transmitter boards available, this has been around many decades in the industrial control market. Since Maxim Integrated makes precision DAC chips, we don't make reference designs that take 0-5V (especially from a PWM!) and convert to 4-20mA -- but we do sell reference design boards that include the DAC. Such as our Monterey system board (MAXREFDES15#). http://www.maximintegrated.com/en/app-notes/index.mvp/id/5683

There's also a `4-20mA Current-Loop Transmitter` from ti.com, XTR117: http://www.ti.com/lit/ds/symlink/xtr117.pdf

There's also a board from mikroElektronika, MIKROE-1296 (available through mouser.com) that uses an Analog Devices DAC (through SPI interface) to drive the 4-20mA transmit circuit. Again, this is an idea that's been around many decades, so a search for `4-20mA transmitter` should yield lots of useful information.

So your best bet is probably to purchase one of these prebuilt 4-20mA transmitter boards, which most likely will include its own precision DAC. You'll have to modify your Arduino code to drive the SPI interface, specific to whichever DAC you end up using. Or, if you really want to use the PWM to drive 4-20mA (at reduced performance), be sure to at least use an RC low-pass filter to get it as close as possible to a stable DC level.

# Answer
> 0 votes
Here is an article which explain how you can use arduino and a 4-20mA current loop transmitter to generate 4-20mA signal. Its using a DAC and 4-20mA current generator. https://ncd.io/interfacing-isolated-4-20ma-current-loop-transmitter-arduino/ So this is how it works in this article they are using a 4-20mA current transmitter board with arduino, You can build it by yourself as well as you can get it from it from https://store.ncd.io/shop/?fwp\_product\_type=4-20ma-transmitter. it has a DAC and a XTR ( its a TI part which is used to generate 4-20mA signal) and signal and power isolator. In these application it is very important that you use isolation between device and your arduino or any other master device. Once you have all the hardware setup, you can send i2c commands and it will generate 4-20mA current loop signal. Lets say you have a device which provides 0-5V and you want to control a different device which needs 4-20mA signal in that case you can use arduino analog input to read the 0-5V and you can use this 4-20mA transmitter to convert that 0-5V into 4-20mA. For more info checkout the above mentioned article.

---
Tags: voltage-level, current
---


# Question
Title: Arduino Uno board works but Arduino Uno + Wifi is not being detected
When I connect my Arduino Uno board it instantly detects the board and shows it in the list. But when I connect my new Uno + Wifi board it doesn't detect it. I also manually selected Arduino Uno Wifi but it still gives me the message

`Error uploading check if the selected board is currently available`

How can I fix this?

This is the one that's not working:

Arduino Uno + Wifi

While this one I got does work:

Arduino Uno

# Answer
What you have there is a cheap Chinese clone. It uses the cheap CH340G USB chip instead of the proper ATMega16u2 that real Arduinos use.

Install the right drivers and it should start working.
> 2 votes

---
Tags: arduino-uno, wifi
---


# Question
Title: How to use Ultrasonic Sensor's trig pin, and why it is needed?
I have HC-SR04 Ultrasonic Sensor with me. I couldn't understand the "Trig" pin's working structure and the working technic. Do we really need it while we use?

(With Arduino examples, I generally use Echo pin more than trig pin.)

# Answer
Yes, you do need it.

The purpose of the TRIG pin is to cause the module to send out a "Ping". It's what makes the whole thing work. As soon as the TRIG pin goes HIGH then LOW (for a period of not less than 10µs) the internal clocks start ticking. 8 cycles of 40KHz audio are sent out of the transmitter and it starts counting how long it takes for the echo to arrive.

If you don't use the TRIG pin the module won't be able to do anything at all.
> 3 votes

# Answer
There are two versions of this device. In the threepin version you trigger the measurement and receive the echo pulse on the same pin. In the four pin version trigger and echo are on separate pins.

Possibly your Arduino example is written for the three pin version.
> 1 votes

# Answer
I stumbled across your topic while working in a personal project. As people said earlier, your doubts must be related to the different versions of this board.

Keep in mind that, when using the 4-pin you can keep the ECHO full online as an input, while in the 3-pin version, you need to cancel the ECHO to use it as Output for the TRIG.

This is particularly useful when you need to make a environmental analysis to different responses to different actions.
> 0 votes

---
Tags: sensors
---


# Question
Title: Do multiple ultrasonic sensors need an external power source?
So maybe it's a very low class form of question, but please bear with me. I'm working on a project with 7 HC-SR04 ultrasonic sensors connected to one Arduino. I tried to unify the trigger and echo pin, but the sensing isn't good enough, so I dropped the Uno and convert it to Mega. My question is, do I need external power source for those 7 Sensors? And how do I connect all of them? Thanks

# Answer
> 4 votes
Well, according to the datasheet the "working current" is 15mA. Even if you had all 7 working at once, which I doubt you will - you'll be working through them in sequence I guess - that would be just 105mA - way below the 800mA the Arduino's on-board regulator can supply, and only a fifth of what a USB port can provide.

The datasheet doesn't mention the quiescent (idle) current, but it will be a tiny fraction of that 15mA and so can mostly be ignored. Running the sensors in sequence, which is the most likely scenario, would use about the same amount of current as if you had 1 sensor - or 20 sensors. Most of the current consumption would be while you are actively producing an ultrasonic chirp.

So no, you don't need an external power supply to run them all - just take them all from the Arduino's 5V pin.

# Answer
> 0 votes
You will probably not have any kind of problem with the Arduino power source, while in the test bench. When using it for the Drone/Bot you seem to be working, make sure to have a stable power source to the Arduino, and, if possible, let your sensors have their own energy input.

I had previous experiences with the sensors not working properly because the Arduino was not getting enough energy through the Arduino's pins when mounted.

---
Tags: arduino-mega, sensors, power
---


# Question
Title: Calculate power requirement for 64 rgb led ws2812b
Hi I am working on small project where I want to run ws2812b module via arduino and lipo battery. I have purchased 64 matrix for ws2812b from eBay and lipo battery with 500mah.

I am looking to find how I can calculate how much power does WS2818b modules will consume with all leds running and will the battery be sufficient for it. How long will it run on full charge.

Can someone please point me to the formula how I can calculate this. Also to note I am using a power up converter from 3.7 to 5v.

# Answer
> 0 votes
If all LEDs are in full bright white, assume 60mA per LED. 64 would mean a maximum current draw of 64\*60mA=3840mA. This figured would not include the Arduino itself.

a 500mAh battery could power this for no more than 7.8 minutes (500mAh / 3840mA = 0.17 hours = 7.8 minutes)

If your usage will not be full bright 100% if the time, then you could run longer.

You didn’t say how long you want it to run. Perhaps start with the design goal before specifying parts.

For a more realistic view of how much power it takes, measure with a multimeter the current draw from the battery or bench power supply to your boost converter while displaying a typical usage on the matrix. Use calculations as above to determine the expected battery lifespan.

---
Tags: power, arduino-nano, lipo
---


# Question
Title: After burning bootloader, Windows 10 doesn't recognize the USB device
I just built my own version of an Arduino Micro, using the ATMEGA32u4 chip. I burned the bootloader to it via another Arduino (Arduino Nano from banggood.com).

The Arduino Nano uses an ATMEGA328 chip, so it *should* work as an ISP programmer. None the less, I hooked up the Nano to my custom board, according to Sparkfun's Guide, and proceeded to burn the bootloader. The Arduino IDE says that I have successfully burned the bootloader.

However, when I plug in the newly burned custom board, Windows 10 throws the error, saying, `USB Device Not Recognized` followed by `The last USB device you connected to this computer malfunctioned and Windows does not recognize it`.

I have searched for a solution, but none seem to come up. My question is, what do I need to do in order to get this custom board working as an Arduino? Thanks!

# Answer
You need a number of things to be true before the (new) bootloader will work:

* The hardware needs to be wired correctly
* You have used an appropriate crystal as the clock
* You have installed the correct bootloader (ie. one for the Atmega32U4)
* The fuses are set to boot into the bootloader
* The fuses are set for the correct bootloader size
* The fuses are set correctly for the clock type and the clock speed (for example, don't have the "divide clock by 8" bit set)

I have a sketch that analyses your chip signature and fuses which will also report on what bootloader it detected (assuming it is one from a recognized list). You could run that and amend your question to post the resulting display from the serial monitor.

I also have a sketch that programs a bootloader for various chips including the Atmega32U4. This sketch also sets the appropriate fuses.
> 2 votes

# Answer
I figured out my own problem. After further testing, I found that my ATMEGA32u4 from DIGIKEY was damaged. Most likely I damaged it by accident, but I can't be sure. Oh man, wouldn't it be nice if life had a CTRL+Z on it?
> 0 votes

---
Tags: usb, atmega32u4, windows
---


title: ESP8266 wifi mesh

text:
# Question
Title: ESP8266 wifi mesh
I'm using 3 ESP8266 for my project: one ESP8266 is a server and controls any action.

I want to be able to connect to any ESP8266 with a phone and if that ESP8266 is a client, send data to the server.

I'm using TCP/IP for communication between ESP8266 models and ESP8266 with PC or phone.

My problem is with the number of clients. In ESP8266, a maximum of 5 TCP clients can connect to a server, and my master ESP8266 is using 2 (to connect to the other ESP8266), so that just leaves 3 clients (PC or phone) that can connect to the master ESP8266.

Is there any way to increase the number of clients?

Is there any alternative for communicating between ESP8266 models other than TCP/IP and leave 5 clients in ESP8266 for the user to connect?

# Answer
> 1 votes
If I understand correctly the problem is only 5 clients can connect to an ESP8266 at any one time. This is an early morning solution to the problem and to be honest I haven't though it through that much, but hopefully its a starting point.

Rather than having all the clients in the mesh connect to the Master node, run an aggregation service on the slaves. One slave will accept connections fro up to 4 other slaves and it will forward the data to the master. If you ever wanted more than 5 slave nodes you would need to have the aggregator nodes feeding into another aggregator (like a tree structure). Its quite easy to do statically, but could be tricky if you wanted to do it dynamically. These aggregators might need to be dedicated nodes, it depends on traffic.

That leaves the master 4 connections for clients. If that isn't enough then you could send the data from the master to additional ESP8266s acting as dedicated webservers and get the clients to connect to them instead. There may even be a method of sharing the load between these two web servers in the same way as proper servers do.

# Answer
> 0 votes
You don't need a separate socket for every client. A client connects to server, sends data or gets data and disconnects. Then the next client connects. One server and one client at the time plus one client connection to PC.

---
Tags: esp8266, wifi
---


# Question
Title: Is it possible to power up Arduino upon serial transmission without dropping data?
I have radiator valves that send readings about the temperature and valve opening to the serial output: Honeywell HR-25.

I want to collect those readings in a central server at home without flashing the thermostat with a custom firmware.

To do that, I need an Arduino (very bare one) that can receive the serial data, but at the same time I need it to be powered down most of the time, or it would kill the battery life of the thermostat.

Can I wake up an Arduino from power down using the serial transmission, and immediately capture the serial data without dropping bits? how?

# Answer
> 0 votes
I never tried myself, but afaik you can define an wake up/interrupt from USART, meaning that if you get a receiving byte from the UART it will wakeup the Arduino.

When powered up, you can read continuous data. I would be surprised if they make an UART wakeup signal, that bytes would be lost (i.e. that powering up would take too long to miss more UART bytes).

# Answer
> 0 votes
You can build a circuit using an electronic counter to only start supplying power to the Arduino at a specific given time. You would still need to supply the circuit, but the energy need would be a small fraction of the Arduino's needs.

On the other hand, can't you use a second power source for the Arduino? Li-On batteries are pretty cheap nowadays, and you can always savage something from an old Notebook's battery.

# Answer
> -1 votes
I don't think you can use the HW peripheral, so IF you really want/need low power you will need something like this (note: this may be very overkill for your application)

simulate this circuit – Schematic created using CircuitLab

NOTE: I assume the "serial" is a UART and its "rest" voltage is 5V. Choose the PMOS so that it is turned on with about 3V.

In this case, the circuit is normally powered off. When you receive a START, the PMOS start conducting. The ATMEL will then pull pin B to 5V, thus keeping the circuit powered. Through pin A it can sense the UART.

In this case, since you miss the start bit, you won't be able to use the usual libraries or peripherals. You can, however, implement a software uart which can avoid the first start bit to overcome this.

Just a suggestion, however. If your thermostat is transmitting frequently, maybe a more useful approach can be to listen to one transmission, then put everything to sleep for let's say 30 seconds, then turn on again and wait for the first serial transmission. This can be simpler than this solution and more effective

---
Tags: serial, sleep
---


# Question
Title: Control LED strip IR controller using Arduino
Is it possible to connect to one of these, which run at 12v, to turn on the LED strip using an ESP8266? It doesn't matter if it's an Arduino or the ESP8266, both should be able to do this. The board looks like this:

If I turn on the red light, the "R" gets grounded and therefore applies 12v to the rail. The 3 MOSFETs on the images are P0903BDG MOSFETs.

Alternatively, I can hook into the IR signal and send an IR signal using the ESP8266. That would be really awesome, as it only requires 3 wires. How that is possible, I'm not really sure, though.

I know it's possible to make your own circuit using IRLZ44N MOSFETs, which I have done before, but I want to try and use as much as this circuit as possible.

# Answer
> 1 votes
I tried to do the same thing with hooking up an IR LED on a Raspberry Pi. It worked pretty well but the chip on the receiver board could not take fast switchings. I ended up doing my own PCB.

The problem is that the chips run at voltages higher than you would use for an ESP8266 or Arduino. This will be the biggest problem if you want to supply it with the voltages available on the board.

I think the safest thing is to see if you can simulate IR input by just connecting to GND and OUT of the IR receiver port.

---
Tags: esp8266, led, rgb-led, led-strip
---


# Question
Title: I am having trouble with fading two LEDs
I've tried to modify this code, but everything I tried failed.
Where am I going wrong?

All I want to happen is when button 1 is pressed LED 1 fades up and when released LED 1 fades out and the same again with the 2nd LED when button 2 is pressed LED 2 fades up and when released it fades out.

```
int ledpin = 10;
int ledpin1 = 11;
int pushbutton = 7;
int pushbutton1 = 8;

int brightness = 255;
int fadeamount = 1;

void setup ()
{
  pinMode (ledpin,OUTPUT);
  pinMode (ledpin1,OUTPUT);
  pinMode (pushbutton,INPUT);
  pinMode (pushbutton1,INPUT);
}

void loop ()
{
  if( digitalRead(pushbutton)==HIGH && brightness<255 )
  {
    // fade in ledpin
    brightness = brightness + fadeamount;// increase brightness
    if( brightness>255 ) // check that brightness doesn't exceed 255
      brightness = 255;
    analogWrite(ledpin,brightness);
    delay (1);
  }
  else if( digitalRead(pushbutton)==LOW && brightness>0 )
  {
    // fade out ledpin
    brightness = brightness - fadeamount;// decrease brightness
    if( brightness<0 ) // check that brightness doesn't go below 0
      brightness = 0;
    analogWrite(ledpin,brightness);
    delay (1);

  }

  if( digitalRead(pushbutton1)==HIGH && brightness<255 )
  {
    // fade in ledpin1
    brightness = brightness + fadeamount;// increase brightness
    if( brightness>255 ) // check that brightness doesn't exceed 255
      brightness = 255;
    analogWrite(ledpin1,brightness);
    delay (1);
  }
  else if( digitalRead(pushbutton1)==LOW && brightness>0 )
  {
    // fade out ledpin1
    brightness = brightness - fadeamount;// decrease brightness
    if( brightness<0 ) // check that brightness doesn't go below 0
      brightness = 0;
    analogWrite(ledpin1,brightness);
    delay (1);

  }

}

```

# Answer
> 1 votes
Create 2 sets of brightness, fadeamount variables, one for each button/LED. You can put them in a struct to make things simpler:

```
struct brightness {
    int brightness;
    int fadeamount;
    int ledpin;
    int pushbutton;
};

struct brightness set1;
struct brightness set2;

```

Then initialize them in init.

The LED goes from full brightness to off in 0.255 seconds. That is pretty quick.

You can add a `millis()` based timer on the brightness change:

```
struct brightness {
    int brightness;
    int fadeamount;
    int ledpin;
    int pushbutton;

    //add the following
    unsigned long timeChanged;
    unsigned long timeBetweenChanges;
};

void handleButtonFade(struct brightness* set){
      if( millis() - set.timeChanged < set.timeBetweenChanges)
          return;

      if(digitalRead(set1.pushbutton)==HIGH && set.brightness<255 )
      {
        // fade in ledpin
        set.brightness = set.brightness + set.fadeamount;// increase brightness
        if( set.brightness>255 ) // check that brightness doesn't exceed 255
          set.brightness = 255;
        analogWrite(set.ledpin,set.brightness);
      }
      else if( digitalRead(set.pushbutton)==LOW && set.brightness>0 )
      {
        // fade out ledpin
        set.brightness = set.brightness - set.fadeamount;// decrease brightness
        if( set.brightness<0 ) // check that brightness doesn't go below 0
          set.brightness = 0;
        analogWrite(set.ledpin,set.brightness);

      }

}

void loop(){
    handleButtonFade(&set1);
    handleButtonFade(&set2);
}

```

# Answer
> 0 votes
Small Change in these lines :

* if( digitalRead(pushbutton)==HIGH && **brightness\<=255** )
* else if( digitalRead(pushbutton)==LOW && **brightness\>=0** )

Also change delay to delay(10) something, instead of delay(1). Only then, human eye can observe that change in brightness from 0-255 :-)

Also adding a capacitor to reduce the debounce in your pushbutton would be a thing to do.

---
Tags: led
---


# Question
Title: Arduino I2C communication between Raspberry Pi
We are trying to communicate between multiple Arduino's (in this example a Nano and a Mega) and a Raspberry Pi. The Raspberry pi is defined as master and the Arduino's as slaves. We would also like that the Arduino's communicate between each other. For example: The Mega requests from the Nano and at some point, the Mega also communicates with the Raspberry Pi. This is the short version of what we are trying to accomplish but we ran into the problem that the i2c communication failed between the Nano and Mega upon the request from the Mega to the Nano.

**Schematic**

**Problem**

After some time the i2c bus 'fills' up...

**Code Nano**

(We send RFID data to Mega)

```
#include <Wire.h>
#include "SPI.h"
#include "MFRC522.h"

#define SS_PIN 10
#define RST_PIN 9
#define SP_PIN 8

MFRC522 rfid(SS_PIN, RST_PIN);

MFRC522::MIFARE_Key key;

void setup() {
  Serial.begin(9600);
  SPI.begin();
  rfid.PCD_Init();

  Wire.begin(0x10);
  Wire.onRequest(requestEvent);
}

void loop() {

}

void requestEvent() {
  if (!rfid.PICC_IsNewCardPresent() || !rfid.PICC_ReadCardSerial())
    return;

  // Serial.print(F("PICC type: "));
  MFRC522::PICC_Type piccType = rfid.PICC_GetType(rfid.uid.sak);
  // Serial.println(rfid.PICC_GetTypeName(piccType));

  // Check is the PICC of Classic MIFARE type
  if (piccType != MFRC522::PICC_TYPE_MIFARE_MINI &&
      piccType != MFRC522::PICC_TYPE_MIFARE_1K &&
      piccType != MFRC522::PICC_TYPE_MIFARE_4K) {
    Serial.println(F("Your tag is not of type MIFARE Classic."));
    return;
  }

  String strID = "";
  for (byte i = 0; i < 4; i++) {
    strID +=
      (rfid.uid.uidByte[i] < 0x10 ? "0" : "") +
      String(rfid.uid.uidByte[i], HEX) +
      (i != 3 ? ":" : "");
  }
  strID.toUpperCase();
  //81:AE:1D:29
  Serial.print("Send to Mega: ");
  Serial.println(strID);

  Wire.write(strID.c_str());

  rfid.PICC_HaltA();
  rfid.PCD_StopCrypto1();

}

```

**Code Mega**

```
#include <Wire.h>

void setup() {
  Wire.begin(0x03);
}

void loop() {
  Wire.requestFrom(0x10, 11);

  String uid = "";

  while (Wire.available()) {
    char c = "";
    c = Wire.read();
    uid += c;
  }

  if (uid.indexOf(':') != 2) {
    return;
  }

  Serial.println(uid);

  delay(500);
}

```

We would like to communicate between the Arduino's when the Raspberry Pi is master.

# Answer
Pi and arduino works at different logic level bro. Also you gotta check if pull up resistors are needed in the SDA lines of I2C bus. I suspect internal pullups of UNO are not really useful. Use 2.2K pull-ups externally.
> 1 votes

# Answer
Its a long time since I used a Pi, but isn't it a 3.3V device and the Arduinos are 5V devices. I think you may need a logic level shifter (not a resistor divider). I suspect that's the reason I2Cdetect isn't working and without that working, nothing else will.
> 1 votes

---
Tags: arduino-mega, arduino-nano, i2c, communication, raspberrypi
---


# Question
Title: Detect and stream if a chair is occupied
I am planning to build a device able to detect and tell a server via Wi-Fi if a chair is occupied. How would you do it? And how cheap do you think the device could be?

# Answer
Oh wow, so many ways you could do this. To start, get an arduino with a wifi shield to transmit and read data. Familiarize yourself with how the arduino works with the shield, and how to read it on the other end. Then it's time to look at sensors you could use. Here's a couple ideas, I would recommend using more than one and cross-checking:

1. Force sensor on base of chair: Can tell you how much weight is on a chair (Sparkfun SEN-09376)
2. IR or sonic sensor on back of chair to detect distance (example)
3. Vibration/shock sensor to detect if someone has sit down (example)
4. Load sensor: literally a scale in a sensor. (Sparkfun SEN-10245)

The optimal solution if you had the cash would be to put all of them on the chair and use the arduino to compute all of the sensor values into one boolean. However, if you only could have one sensor I would recommend the load sensor which would definitely be the most reliable of all the examples I gave.
> 6 votes

# Answer
For a soft seat you could sense occupancy with an LED and photo-sensor at opposite ends of a short somewhat flexible tube that gets flexed when the cushion compresses, interrupting the light. That or a microswitch would have to be the cheapest means of sensing.

Getting from there to the server depends a little on how much work you're willing to do, from rolling your own micro-controller+WiFi PCB to purchasing off the shelf parts, which may in turn, depend on whether you need to monitor one chair or a whole auditorium.
> 6 votes

# Answer
I'm not going to answer this directly, because then you wouldn't learn anything! However, here are a few suggestions:

* Use a pressure sensor on the seat of the chair or
* Put a distance sensor (IR or ultrasonic) pointing at the chair.
* Use the official Arduino WiFi shield.
> 5 votes

# Answer
You could use the awesome CapSense-Library. Additionally to the Library you only need a thin piece of conducting material e.g. aluminium foil and two pins on your arduino. The only thing you have to do is experiment with different resistors to reliably distinguish between someone sitting on the chair or not. Advantages of this method are:

* virtually no costs at all
* easy to implement
* not subject to wear and tear
* should work with any kind of chair independent of material e.g.
hard or soft surface
* consumes next to no power (I assume the whole device runs on battery since it's attached to a movable chair)
* could even sense a person in the process of seating her-/himself and enable you to start the music faster (my stereo for example takes a second or so to start up)
> 4 votes

# Answer
You could use Electric Field Sensing, it allows you to detect the presence and position of conductive objects even if the sensor is covered by an opaque object. The technology is used in cars to detect if someone is sitting in a seat so the car can beep at you to put your seat-belt on. However, if all you want to do is detect presence then this is no better than using CapSense.

http://web.media.mit.edu/~jrs/efs.html

https://en.wikipedia.org/wiki/Electric\_field\_proximity\_sensing

To communicate with a server over WiFi you could use the Arduino WiFi shield, the Arduino Yun (which has on-board WiFi) or buy a ethernet WiFi adapter and use it with an Arduino board which has ethernet.

http://arduino.cc/en/Main/ArduinoWiFiShield

http://arduino.cc/en/Main/ArduinoBoardYun (Arduino board with on-board WiFi)

http://arduino.cc/en/Main/ArduinoBoardEthernet
> 2 votes

# Answer
conductive foam as sensor. it chg resistance when compressed.

or use image from camera to determine if seat is occupied. only one source for all data.
> 0 votes

---
Tags: sensors, wifi
---


# Question
Title: exit status 1 expected primary-expression before 'int'
```
int temp=A0;
#include<stdlib.h>
#include <SoftwareSerial.h>

#define SSID "rab"
#define PASSWORD "rakesh1234"
#define IP "184.106.153.149" // thingspeak.com
String GET = "GET /update?key=B8B8E4FC1K541QZQ&field1=";
SoftwareSerial monitor(0, 1); // RX, TX
SoftwareSerial mySerial(5, 6); // RX, TX
int p1=0,p2=0,p3=0;
int i=0;
int j=0;

void setup() {
  pinMode(A0,INPUT);
  Serial.begin(115200);
  monitor.begin(115200);
  mySerial.begin(9600);
  sendDebug("AT");
  delay(2000);
  if(Serial.find("OK")) {
    monitor.println("RECEIVED: OK");
    Serial.println("RECEIVED: OK");
  }
  connectWiFi();
}

unsigned char buf[50];

void loop() {
   while(!mySerial.available());
   if(mySerial.read() == '#') {
     for(int i=0;i<12;i++) {
       while(!mySerial.available());
       buf[i] = mySerial.read();
     }
     buf[3] =0;
     buf[7]=0;
     buf[11]=0;
     p1 = atoi((const char *)&buf[0]);
     p2 = atoi((const char *)&buf[4]);
     p3 = atoi((const char *)&buf[8]);
     delay(1000);
   }

   long int SensorValue=analogRead(temp);
   SensorValue=SensorValue*5000;
   SensorValue=SensorValue/1024;
   SensorValue=SensorValue/10;
   SensorValue=SensorValue*9;
   SensorValue=SensorValue/5;
   SensorValue=SensorValue+32;
   String tempF=String(p1);
   String tempFF=String(p2);
   String tempFFF=String(p3);
   String tempFFFF=String(SensorValue);

   for(int j=0;j>-1;j++) {
     **j= Serial.read(int p1, int p2, int p3);**
   }
   while(Serial.available()==j)
     updateTemp(tempF,tempFF,tempFFF,tempFFFF);
   while(1) {}
 }

 void updateTemp(String tempF1 ,String tempF2, String tempF3,  String tempF4) {
   String cmd = "AT+CIPSTART=\"TCP\",\"";
   cmd += "api.thingspeak.com";
   cmd += "\",80";
   sendDebug(cmd);
   delay(1000);
   if(Serial.find("Error")) {
     monitor.print("RECEIVED: Error");
     Serial.print("RECEIVED: ERROR");
     return;
   }
   cmd = GET;
   cmd += tempF1;
   cmd += "&field2=";
   cmd += tempF2;
   cmd +="&field3=";
   cmd +=tempF3;
   cmd +="&field4=";
   cmd +=tempF4;
   cmd += "\r\n";
   Serial.print("AT+CIPSEND=");
   Serial.println(cmd.length());
   if(Serial.find(">")) {
     monitor.print(">");
     monitor.print(cmd);
     Serial.print(cmd);
   } else {
     sendDebug("AT+CIPCLOSE");
   }
   if(Serial.find("OK")) {
     monitor.println("RECEIVED: OK");
   } else {
     monitor.println("RECEIVED: Error");
   }
 }

 void sendDebug(String cmd) {
   monitor.print("SEND: ");
   monitor.println(cmd);
   Serial.println(cmd);
 }

 boolean connectWiFi() {
   Serial.println("AT+CWMODE=1");
   delay(2000);
   String cmd="AT+CWJAP=\"";
   cmd+=SSID;
   cmd+="\",\"";
   cmd+=PASSWORD;
   cmd+="\"";
   sendDebug(cmd);
   delay(1000);
   if(Serial.find("OK")) {
     monitor.println("RECEIVED: OK");
     return true;
   } else {
     monitor.println("RECEIVED: Error");
     return false;
   }
 }

```

This is my code. I am getting an error as "exit status 1 expected primary-expression before 'int'"

Please help me.

Thank you.

# Answer
> 1 votes
You are doing Serial.read() wrong with:

```
Serial.read(int p1, int p2, int p3);

```

`Serial.read()` takes no parameters per https://www.arduino.cc/en/Serial/read

Maybe you want to try `parseInt()` instead?

# Answer
> 1 votes
Your problem is that your are using asterisks ("\*")

```
   for(int j=0;j>-1;j++) {
     **j= Serial.read(int p1, int p2, int p3);**
   }

```

The asterisk in C/C++ is the **pointer operator**. You use to get the value pointed by a pointer.

The expression `**j` means that `j` is a pointer to a pointer that points something. That's is meaningless here.

Then, the last `**` is readed as another pointer to a pointer, and the compiler is expecting a variable or expression that give the value for the pointer, but found "}", which is an error.

You probably tried to comment out that line of code after the compiler barks at the `Serial.read()`, which, as Dave X pointed out, is illegal, because `Serial.read()` takes no arguments.

And, the syntax `function(int x)` is only use for declaring a function, not for calling one.

---
Tags: programming, code-review
---


# Question
Title: Why using static volatile for variables and only static for arrays in TWI library?
I want to know why to declare variables with static volatile and arrays with only static in TWI library?

For example;

```
static uint8_t twi_masterBuffer[TWI_BUFFER_LENGTH];
static volatile uint8_t twi_masterBufferIndex;
static volatile uint8_t twi_masterBufferLength;

```

# Answer
> 4 votes
You use `volatile` to mark variables that are going to change at any moment, in a ISR (Interrupt Service Routine) typically.

You mark them so the compiler doesn't optimize, and always go and pick its actual value. If you don't do that, then an ISR may update a variable while the main "thread" of execution keeps using its old value. That's is a nasty situation to debug.

You only need to mark variables that are used both in the ISR and in the main sketch. If `twi_masterBuffer` is not changed inside an ISR, you don't need to mark it with `volatile`.

`static` is used inside function to mark variables that need to be permanent, i.e., keep their values between calls, but not accessible from outside that function.

---
Tags: i2c, c, array, variables
---


# Question
Title: Good book/reference for AVR coding in pure C/C++?
Can someone recommend a good book/reference for going vanilla (i.e. not using arduino simplified language) on e.g. ATtiny85? I will need to use the equivalents of analogRead() and digitalRead() quite a bit. And is softwareserial the best method for debug output? I have less than 8KB of flash, so any advice on that (and reduction of binary for upload) would also be greatly appreciated.

# Answer
> 5 votes
First, let's make this clear: The Arduino environment does not provide a “simplified language”: it provides a simple hardware abstraction layer through its core library. The language is plain C++.

Like Talk2, I don't have good book recommendations. The basics of low-level programming are covered in the Arduino tutorial on port manipulation\[\]. Past this you will have to dig into the datasheet of your MCU. Look also at the doc of the avr-libc and the tutorials in Nick Gammon's microprocessors pages.

I would suggest you try to develop your program like this:

1. Do the initial prototype of your idea on an Arduino Uno (or similar) using the Arduino libraries. It just makes things easier, and you are more likely to get a working prototype pretty fast.
2. Once the initial idea works, optimize it for the limited resources of the ATtiny85. This may involve replacing some call to the Arduino libs with avr-libc and/or direct port access.
3. You may then want to remove all references to Arduino core, but you don't have to: there are some ATtiny cores available that you can use if you want.
4. If it now fits in less than 8 K, port to the ATtiny.

The thing I love about the Arduino environment is that you can very easily mix and match abstraction levels: you can have, in the same program, calls to Arduino core, to avr-libc, direct port access, and even inline assembly if want to. You don't even need to stick to the `setup()` and `loop()` method: you can write your own `main()` if you prefer, just remember to call `init()` to initialize the Arduino core if you are going to use it. Oh, and you don't have to use the Arduino IDE either if you don't like it (I don't).

As for the optimization tips, I would recommend :

* Use direct port access instead of `digitalRead()`, because that function is pretty big and slow.
* `analogRead()` may not be that bad, size wise, but it has a serious shortcoming: it's a blocking function which spends 104 µs in a spin loop, just waiting for the ADC result. If your CPU has better things to do, you may want to implement a non-blocking read instead.
* For debugging output, the most efficient option is likely to be the USI port. You will have to search for a driver or implement your own based on the Atmel application note AVR307: Half Duplex UART Using the USI Module. Alternatively, you could use something like AltSoftSerial. Do not use SoftwareSerial: it blocks interrupts for insanely long amounts of time.
* Use the command `avr-nm --size-sort -Crtd my_program.elf` to get a listing of the functions of your program sorted by flash usage. This will help you choose good targets for size optimization.

# Answer
> 3 votes
I can recommend the book "**Make: AVR Programming**", which uses **avr-gcc** directly. The Arduino IDE *is* mentioned at one point, but just in order to "place" it, and to explain how to use its libraries in your own code. You can study all the code used in the book right here (github link).

(late answer, I know, I was searching for other books that don't use the Arduino IDE and stumbled upon this question)

# Answer
> 0 votes
If you abandon the Arduino paradigm you will be pushed into dealing with setting up all the hardware that makes today's embedded processor so flexible. This usually takes an experienced embedded programmer days if not weeks to get through on a new processor. You will also need a dedicated Atmel programmer as you will no longer be using the Arduino boot loader.

Once you get past these obstacles, you can start studying C and C++. The "grand dad" C reference book would be by the "first guys" that did C, Kernighan & Ritchie. The equivalent C++ book (if you are up to it) would be by Bjarne Stroustrup.

However...

What have you gained by abandoning the Arduino paradigm?

Some would say, not much.

Most of why programming in the Arduino paradigm is easy has to do with Arduino libraries. They "abstract" the hardware down to a couple simple function calls. For example, with one function call you can set up the pulse train that can position a servo motor using a familiar term: degrees.

It should also be pointed out that the compiler Arduino uses is a C / C++ compiler. And that most Arduino libraries are purposely written in C++.

Perhaps writing a C++ Arduino library is a good way to learn C++. Start by finding the code to libraries that you already use. Then reviewing how the C++ code is put together. Finally write you own C++ Arduino library.

# Answer
> 0 votes
Sorry, I don't have any book recommendation apart from the AVR Datasheet.

You could try to use AVR-LIBC as a abstraction layer instead of playing directly with individual registers: http://www.nongnu.org/avr-libc/.

That might help you saving some Ks on your code which the Arduino layer might be adding. Just make sure you have a proper IDE to assist you with code-completion and navigation.

Also Atmel has a good link how to optimize your C code: http://www.atmel.com/images/doc8453.pdf, which I had a look when doing some bootloader coding.

Finally, you could explore the Arduino libraries, and see the overhead added to each function, like "analogRead()" from your example. Most of the Arduino funcions will be a layer on top of the AVR-GCC, so it'll be a good learning exercise - again, get a proper IDE that helps with auto-completion and navigation.

Cheers

# Answer
> 0 votes
The Arduino implements a subset of c++. I am not sure what you expect to achieve by not using it.

If you are really after optimum code, there is no obligation to use any inbuilt function and you can code your own.

Most conventional compilers use a standard runtime library. The reason Arduino does not is because of the limited memory. It is necessary to omit many standard functions to save space.

By not using a library only functionality you need is actually linked in.

---
Tags: serial, programming, c++, avr
---


# Question
Title: How can I change the speed of a stepper motor?
I am new to Arduino and am trying to implement different rotational speeds for a stepper motor. I am using a Nema 17 bipolar stepper motor, a Big Easy Driver, and an Arduino Uno.

I've been trying to modify a tutorial code such that it will run at variable speeds:

```
//Declare pin functions on Arduino
#define stp 2
#define dir 3
#define MS1 4
#define MS2 5
#define MS3 6
#define EN  7

//Declare variables for functions
char user_input;
int x;
int y;
int state;

#include <AccelStepper.h>
#include <Stepper.h>
Stepper stepper1 (1,stp,dir);

void setup() {

  pinMode(stp, OUTPUT);
  pinMode(dir, OUTPUT);
  pinMode(MS1, OUTPUT);
  pinMode(MS2, OUTPUT);
  pinMode(MS3, OUTPUT);
  pinMode(EN, OUTPUT);
  resetBEDPins(); //Set step, direction, microstep and enable pins to default states
  Serial.begin(9600); //Open Serial connection for debugging
  stepper1.setSpeed(1);
  Serial.println("Begin motor control");
  Serial.println();
  //Print function list for user selection
  Serial.println("Enter number for control option:");
  Serial.println("1. Turn at default microstep mode.");
  Serial.println("2. Reverse direction at default microstep mode.");
  Serial.println();

}

//Main loop
void loop() {
  while(Serial.available()){
      user_input = Serial.read(); //Read user input and trigger appropriate
function
      digitalWrite(EN, LOW); //Pull enable pin low to set FETs active and allow motor control
      if (user_input =='1')
      {
         StepForwardDefault();
      }
      else if(user_input =='2')
      {
        ReverseStepDefault();
      }
      else
      {
        Serial.println("Invalid option entered.");
      }
      resetBEDPins();
  }
}

//Reset Big Easy Driver pins to default states
void resetBEDPins()
{
  digitalWrite(stp, LOW);
  digitalWrite(dir, LOW);
  digitalWrite(MS1, LOW);
  digitalWrite(MS2, LOW);
  digitalWrite(MS3, LOW);
  digitalWrite(EN, HIGH);
}

//Default microstep mode function
void StepForwardDefault()
{
  Serial.println("Moving forward at default step mode.");
  digitalWrite(dir, LOW); //Pull direction pin low to move "forward"
  for(x= 1; x<4000; x++)  //Loop the forward stepping enough times for motion to be visible
  {
    digitalWrite(stp,HIGH); //Trigger one step forward
    delay(1);
    digitalWrite(stp,LOW); //Pull step pin low so it can be triggered again
    delay(1);
  }
  Serial.println("Enter new option");
  Serial.println();
}

//Reverse default microstep mode function
void ReverseStepDefault()
{
  Serial.println("Moving in reverse at default step mode.");
  digitalWrite(dir, HIGH); //Pull direction pin high to move in "reverse"
  for(x= 1; x<4000; x++)  //Loop the stepping enough times for motion to be visible
  {
    digitalWrite(stp,HIGH); //Trigger one step
    delay(1);
    digitalWrite(stp,LOW); //Pull step pin low so it can be triggered again
    delay(1);
  }
  Serial.println("Enter new option");
  Serial.println();
}

```

Adjusting the potentiometer on the Big Easy Driver will either stop the motor turning completely or run at a constant speed regardless of further adjustment.

Do you have any suggestions for debugging my code, or are there other functions I should be using in addition to/instead of those I have?

# Answer
> 1 votes
Do you understand how a stepper works? You send it pulses and it steps for each pulse you send it. The faster you send the pulses the faster it will run. The slower you send the pulses the slower it will run. You have lines in your code like this:

```
void StepForwardDefault()
{
  Serial.println("Moving forward at default step mode.");
  digitalWrite(dir, LOW); //Pull direction pin low to move "forward"
  for(x= 1; x<4000; x++)  //Loop the forward stepping enough times for motion to be visible
  {
    digitalWrite(stp,HIGH); //Trigger one step forward
    delay(1);
    digitalWrite(stp,LOW); //Pull step pin low so it can be triggered again
    delay(1);
  }
  Serial.println("Enter new option");
  Serial.println();
}

```

Can you see the part that is sending HIGH and LOW to your step pin? See the delay that is determining how fast those pulses go out? Can you imagine how you might change that delay so that the pulses go out faster or slower? Here's a hint, delay works in milliseconds, but if you want to go faster than this then you'll need to work in microseconds. Can you find the version of delay that works in microseconds in the Arduino reference?

---
Tags: arduino-uno, stepper
---


title: Alternatives to Wire library for I2C

text:
# Question
Title: Alternatives to Wire library for I2C
I am looking for (reasonably easy to use and well tested) alternatives to the `Wire` library. `Wire` works very well, but: I only need the Arduino to act as I2C master and the `Wire` library seems to be a real waste of resources:

My goal is to send out data en bloc (e.g. 32 or 64 bytes). This data is already sitting in an array in SRAM. Now when you use the `Wire` library, you call the `TwoWire::write` function which copies your data into a 2nd buffer. Afterwards, `Wire` makes use of the `TWI` library where `twi_writeTo` copies the data again into a 3rd buffer. That's a bit clunky, isn't it?

I have seen the DSSCircuits / I2C-Master-Library but I am not sure how mature it is because there hasn't been any commit after the initial commit which is 3 years old now.

# Answer
I don't see any objection to using DSS Circuits I2C Master Library.

It may not have been updated for a couple of years, but if it works it doesn't need to be. It's not as if libraries for micro-controllers have to support new printer drivers, video drivers, etc.

If it works, it works.

The chip hasn't changed, and the only real reason for updates these days is if the IDE changes (or the compiler changes) in such a way that it introduces compile errors. Such things have happened fairly recently with things like PROGMEM having tighter rules, for example.
> 4 votes

# Answer
Also Procyon AVR library worth be checking. It is a bit old now but very professional and kinda minimalistic. Not much dependencies, should be fine to use just I2C module only. There is hardly anything new in AVR I2C part since.
> 4 votes

# Answer
Cosa TWI class is a very different approach to I2C device driver support. It does not use any extra SRAM for buffers at all. If a device driver is non-blocking it must handle the necessary buffering. Also the Cosa TWI class supports typical interaction with I2C devices such as master/slave, "write register-read data"-patterns, and transactions when using multi-threading.

A software and hardware Arduino-TWI library is available. It uses the Arduino-GPIO library and can be used on AVR and SAM based boards.

Some examples: TWI Scanner, DS3231 Real-Time Clock/Calender, I2C LCD Adapter with PCF8574.
> 3 votes

# Answer
You can use completely different approach to the top question. Asking for alternatives you have given reason to this: getting rid of unused code in the binary. You can achieve removal of unused code without actually using alternative library. Please keep in mind, that you can instruct the compiler and linker to exclude unused code from the compiled binary. Just use compilation flags:

```
CFLAGS += -Wl,-static
CFLAGS += -ffunction-sections
CFLAGS += -Wl,--gc-sections

```

Rach function will be in its own section.

```
LDFLAGS += -Wl,-gc-sections

```

This tells GCC to send the -gc-sections flag to the linker which will remove unused sections. And voilla! Unused sections are removed.
> 2 votes

# Answer
I made 2 libs myself for easier use and consistant calls:

one for AVR targets:
cI2C

another using the same functions for all other targets (which basically is a wrapper for Wire library):
WireWrapper

Both are available within the IDE library manager.
They both work as master without using interrupt and are tested on different targets with different slaves:
\- UNO, Nano for cI2C
\- Zero, Due & ESP8266 for WireWrapper
> 1 votes

---
Tags: i2c, library, wire-library
---


# Question
Title: Why it's not possible to manipulate the TWSR directly?
I think I forgot the reason for this SFR manipulation in microcontrollers; like, checking the TWSR in twi.

The technique for checking the values of the TWSR is by masking it with another variable or a value.

So, why not checking the TWSR directly in; for example, switch function for checking the values of TWSR?

Like, `switch (TWSR)`

instead of

`uint8_t Status;
 Status = TWSR & 0xF8;
 switch(Status)`

Or, substitute it in any function; like, `Serial.println(TWSR);` or `digitalRead(TWSR);`. DO I have to mask it? If so then why?

# Answer
> 1 votes
> Why it's not possible to manipulate the TWSR directly? i2c c switch

Because your premise is wrong: it is routinely done to manipulate twsr directly.

As to the use of masks, well, because sometimes you only care about certain bits but not others. So you mask away those that you don't want.

Just that simple.

# Answer
> 0 votes
The mask is a must, because bit 0 and bit 1 are I2C clock speed bits and they are changeable between different I2C clock speed configurations.

---
Tags: i2c, c, switch
---


# Question
Title: ESP8266 - AT Command for Network Requiring Username AND Password
I have been using my ESP8266 module with my Arduino on my university's Wi-Fi network, which only requires a password to log on to.

The university will soon terminate that Wi-Fi network and replace it with one that requires a username and password to log on.

What would that AT command be to connect to such a network?

Edit: I have since found out that the university has changed the network so that a user can "connect" to the network and then enter their university id/password in a captive portal to gain internet access (and perhaps other features of the network). Also, I have since learned how to overwrite the firmware on my esp-01 so that I no longer need to use the AT commands -- in fact, I can program it in the Arduino IDE just as I would with another esp8266-based device, such as the NodeMCU.

# Answer
We can't tell without more information but it sounds rather like you will need a \[WiFi\_SSID, WiFi\_PASSWORD\] pair for the ESP to connect to the WiFi, and a \[Network\_USERNAME, Network\_USERPASSWORD\] pair for their network to let you use the network (as if you were logging onto it by hand from a terminal).

If so, you'd provide the first pair as you do now, with the AT+CWJAP... command, to get your device connected to the WiFi. For the second pair, your Arduino will probably need to interact with a user logon screen to provide the second pair. You'll need to get those details from the school's IT department, and possibly mimic a terminal.

Update: As above, you need to find out whether the network requires 2 sets of credentials - the SSID and WPA2 key and network username and password. If it requires the latter, then your ESP can get you onto the WiFi but your Arduino will then have to mimic a user sitting at a terminal - read the network ID and Password challenges and provide the appropriate responses. Without know that, you can't know how to write the login code, nor can we. It sounds as if there are people on site who have already done what you're trying to do. They and their experience can be far more helpful than we, who have no knowledge of the school network.
> 2 votes

# Answer
If you are using Arduino+ESP8266 version 1(ESP-01)module. You can connect ESP module to the internet, using AT commands as follows:

Normally, AT+CWJAP="ssid","password"

If your Internet requires ssid, username and passowrd(usually in universities- eduroam) then

1) Connect to eduroam or university wifi using ssid, username and password from your laptop.

2) Install Connectify Hotspot software in your laptop.

3) Open "Connectify Hotspot" application and open settings tab, then create wifi-hotspot.

4) Give eduroam(or your wifi)--\>"Internet to share" field , Give your own Hotspot name and password. Then click on "start Hotspot" button.

5) Now your esp01 module can detect this new hotspot using AT+CWLAP. Connect to
it using AT+CWJAP="HOtspot ssid","HOtspot password".

This way you can overcome the problem of extra Authentication.

Hope it helped. Enjoy Programming.
> 0 votes

---
Tags: esp8266
---


title: 'TCCR0B' undeclared

text:
# Question
Title: 'TCCR0B' undeclared
I am trying to compile the function in http://playground.arduino.cc/Code/PwmFrequency

This produces a couple of errors

```
sketch/setPwmFrequency.c:34:3: error: unknown type name 'byte'
   byte mode;
   ^
sketch/setPwmFrequency.c:45:7: error: 'TCCR0B' undeclared (first use in this function)
       TCCR0B = TCCR0B & 0b11111000 | mode;

```

`byte` is trivial, but I can't seem to find `TCCR0B` et al I assume it should be defined somewhere.

# Answer
> 1 votes
Both errors can be solved by adding the following line to your setPwmFrequency.c:

```
#include <Arduino.h>

```

This will include the files that contain the `byte` typedef and also the register definitions.

You may notice that is not necessary in an .ino file. The reason is that the Arduino IDE automatically adds the Arduino.h include to .ino files during sketch preprocessing before compilation.

---
Tags: arduino-ide, arduino-nano, compilation-errors
---


# Question
Title: How do I create global pointers with low memory overhead?
# Problem

I have a few large objects in my code that need global visibility, but creating them seems to eat up memory significantly faster than simple math would dictate, and furthermore, using them differently in code seems to change how much RAM the compiler tells me I have left for local variables.

**How do I optimize the use of my RAM while still being able to use an object in both my `setup()` and my `loop()` functions?**

Note: Skim the **Pseudo-Code** section and then skip to the **Discussion** section if want to get to the meat of my question (I just wanted to provide plenty of background, if needed).

# Test Code

To demonstrate that reported global RAM usage changes due not only the number of variables I define globally, but **how those variables are used in code**, I created a test program. I compiled this code on the Arduino IDE on a Mac, and ran this on multiple Elegoo Nanos.

Please forgive the particularly long "minimal" complete verifiable code, but it has a bit going on. Here's the pseudo-code for it.

### Pseudo-Code

"T" (for tested) before a line means that I commented out a line or left it be depending on what test I was running:

```
Define a function to check how much memory remains, freeRam() (taken from https://playground.arduino.cc/Code/AvailableMemory, bottom of page)
Create a class that uses a ton of RAM, about 1024B (GinormousClass)
Create a wrapper for GinormousClass (GinormousClassWrapper) that may or may not construct the GinormousClass, based on how it is implemented

Global scope:
Run freeRAM() to see how much initial RAM is available before setup() is run.
T Create a global pointer to the wrapper class

Local scope (setup):
Report initial RAM
T Create a local pointer to the wrapper class
T Assign a newly constructed wrapper object to the pointer, which does NOT instantiate the huge class
    Report how much RAM remains after creation and after deletion
T Assign a newly constructed wrapper object to the pointer, which DOES instantiate the huge class
    Report how much RAM remains after creation and after deletion

```

Note: Remaining RAM before creation and after deletion were always the same.

### Actual Code

```
#define ARRAY_SIZE 256

// Method to determine how much memory is left (https://playground.arduino.cc/Code/AvailableMemory, bottom of page)
int freeRam() {
  extern int __heap_start, *__brkval;
  int v;
  return (int) &v - (__brkval == 0 ? (int) &__heap_start : (int) __brkval);
};

// Define a class that uses a ton of RAM
class GinormousClass {
  public:
    GinormousClass() { // Fill array with (kind of) random numbers
      for (int i = 0; i < ARRAY_SIZE; i++) {
        BIG[i] = random(1000);
      }
    };

    long BIG[ARRAY_SIZE]; // Have this class control a huge array
};

// Define a class that has the potential to use a ton of RAM
class GinormousClassWrapper {
  public:
    GinormousClassWrapper(bool createGiantObject) { // Constructor
      if (createGiantObject) {
        // Create a GinormousClass object (use a ton of RAM)
        gPointer = new GinormousClass();
      } else {
        // Do not create GinormousClass object
      }
    };

    ~GinormousClassWrapper() { // Delete the Ginormous Class, if it exists
      if (gPointer) {
        delete gPointer;
      }
    }

    GinormousClass *gPointer = NULL; // Initialize pointer to NULL
};

int initialFreeRam = freeRam(); // Figure out how much RAM is available before the fun begins
GinormousClassWrapper *ginny; // Declare a GLOBAL pointer to the potentially enormous class

void setup() {
  // Start the Serial connection, and get the initial amount of RAM
  Serial.begin(9600);
  Serial.print("Initial free RAM: ");
  Serial.println(initialFreeRam);

  //  GinormousClassWrapper *ginny; // Declare a LOCAL pointer to the potentially enormous class

  // Try making the class, without defining the array
  Serial.println("Making Ginormous Class (do nothing constructor)...");
  ginny = new GinormousClassWrapper(false);

  Serial.print("Current free RAM: ");
  Serial.println(freeRam());
  Serial.println();

  // Delete the class
  Serial.println("Deleting first class...");
  delete ginny;

  Serial.print("Current free RAM: ");
  Serial.println(freeRam());
  Serial.println();

  // Try making the class, WITH defining the array
  Serial.println("Making Ginormous Class (use a ton of RAM constructor)...");
  ginny = new GinormousClassWrapper(true);

  Serial.print("Current free RAM: ");
  Serial.println(freeRam());
  Serial.println();

  //  Delete the class
  Serial.println("Deleting second class...");
  delete ginny;

  Serial.print("Current free RAM: ");
  Serial.println(freeRam());
  Serial.println();
};

void loop() {

};

```

# Results

I've collected the RAM reported at 4 different times:

1. after compilation
2. before `setup()`
3. after the "do-nothing" construction of the wrapper
4. after the "use-space" construction of the wrapper

5 different scenarios were tested:

1. no pointer declared/wrapper not constructed
2. pointer declared but object not constructed
3. do-nothing constructor used
4. use-space constructor used
5. do-nothing constructor used, object deleted, and use-space constructor used

### Raw Results:

Numbers are amount of RAM left, in bytes

```
0 Not declared:
    Compiler: 1836
    Initial: 1830
    Do-nothing constructed: N/A
    Use-space constructed: N/A

1 Declared global, not constructed:
    Compiler: 1836
    Initial: 1830
    Do-nothing constructed: N/A
    Use-space constructed: N/A

2 Declared global, constructed do-nothing:
    Compiler: 1734
    Initial: 1728
    Do-nothing constructed: 1724
    Use-space constructed: N/A

3 Declared global, constructed use-space:
    Compiler: 1722
    Initial: 1716
    Do-nothing constructed: N/A
    Use-space constructed: 686

4 Declared global, constructed both:
    Compiler: 1648
    Initial: 1640
    Do-nothing constructed: 1636
    Use-space constructed: 610

```

Note: Local pointer instead of global pointer had no change except increase all reported RAM by 2 bytes.

# Discussion

In the raw results, the GinormousClassWrapper takes 4B when constructed (the pointer it owns) and GinormousClass takes about 1024B when constructed (exactly 1030B, we can assume there's some overhead). However, one strange thing is of note:

The amount of room stated by the compiler to be available for local variables **decreases significantly** when the wrapper is constructed versus when it is not (1836B down to 1640B when both constructors are used). I would **expect** that the amount of RAM used by globals would not change, because technically only the pointer is in global scope. If it is SUPPOSED to change according to how the pointer is used, then why does it change by 196B, of all numbers?

I am assuming that the RAM given by the compiler is fact, and it's one that I would like to know because my project is running on tight memory restrictions. **So where is all of this valuable extra RAM going, and what can I do to reduce it?** Thank you for any help!

# Answer
> 0 votes
I compiled a slightly modified version of your code, with some `#define`s for selecting which objects get constructed or not. I also printed the available RAM right after entering `setup()`. I found that, at this point in the program, the version constructing both objects is using 178 bytes more RAM than the version that constructs none.

I then used the commands `avr-nm` and `avr-objdump` to try to figure out how the program is using its memory. I found the 178 bytes difference is as follows:

```
157 bytes of string data
  6 bytes of malloc data
  4 bytes of random state
  2 bytes for the ginny variable
  8 bytes of stack
  1 mystery byte

```

The difference in string data comes from messages such as “Making Ginormous Class (do nothing constructor)...”, “Deleting first class...”, etc., which are `#define`d out in the version that does not construct the objects. The `malloc()` data (heap\_start, heap\_end and margin) is not used in the version that does not use `new`, so it is not included in that version. For the same reason, the `random()` state is not included in the version that does not use `random()`. The `ginny` variable, although declared in both versions, is optimized-out by the compiler in the version where it remains unused. The 8 bytes of stack come from the fact that the largest version of `setup()` needs more CPU register to do its work, and hence pushes more registers to the stack. There is only one byte I could not account for, with value 0, sitting at the end of the .data section, with no associated symbol.

As you can see from this, the difference has little to do with the objects being constructed. It is mostly due to the string data. A smaller part of that difference comes from variables (`ginny`, random state and `malloc()` data) which are used only in one version of the program. The practical conclusions are:

1. If you want to save RAM, use the `F()` macro when printing constant strings.
2. If you want to benchmark memory consumption, beware your benchmarking method can have non-obvious effects on the consumption yo are trying to measure.

# Answer
> 1 votes
*I have to confess that I probably doesn't understand what you are asking ...*

Regarding the stats giving by the compiler (tested on a Uno, Arduino IDE 1.8.5), I got

**Global Wrapper (using global ginny)**

```
Sketch uses 3304 bytes (10%) of program storage space. Maximum is 32256 bytes.
Global variables use 400 bytes (19%) of dynamic memory, leaving 1648 bytes for local variables. Maximum is 2048 bytes.

```

**Execution**

```
Initial free RAM: 1640
Making Ginormous Class (do nothing constructor)...
Current free RAM: 1636

Deleting first class...
Current free RAM: 1640

Making Ginormous Class (use a ton of RAM constructor)...
Current free RAM: 610

Deleting second class...
Current free RAM: 1640

```

**Local Wrapper (using local ginny)**

```
Sketch uses 3258 bytes (10%) of program storage space. Maximum is 32256 bytes.
Global variables use 398 bytes (19%) of dynamic memory, leaving 1650 bytes for local variables. Maximum is 2048 bytes.

```

**Execution**

```
Initial free RAM: 1642
Making Ginormous Class (do nothing constructor)...
Current free RAM: 1638

Deleting first class...
Current free RAM: 1642

Making Ginormous Class (use a ton of RAM constructor)...
Current free RAM: 612

Deleting second class...
Current free RAM: 1642

```

Local Wrapper version uses 2 bytes less of global space. That's correct, because space for `local ginny` comes from the stack, while `global ginny` comes from the heap.

No compiler will give you how much space (for variables) will you need during execution. That's unsolvable (from Turing's Halting Problem). Just think what happens when you enter in a non-ending recursion.

Comparing execution results, both version show the same amount of memory, off by two bytes, which is due to `ginny` declared global vs local.

There is a differente between free space declared by compiler (1648, 1650 bytes) and space reported during program execution (1640, 1642 bytes). The difference is 8 bytes in both cases.

Now, `setup` is a function called from `main`. That's means you need stack space for the call (return address and whatever), which explains the 8 bytes difference.

# Answer
> 0 votes
> I am assuming that the RAM given by the compiler is fact ...

That's about the only thing I **wouldn't** assume. The compiler can't really know how much RAM your code is going to use, especially when you do dynamic memory allocation. The compiler can certainly report on how much space your global variables take, as it has to allocate addresses for them.

I have a post about what RAM is used in a minimal sketch, for example this:

```
#include "memdebug.h"

void setup ()
  {
  Serial.begin (115200);
  Serial.println ();
  Serial.print (F("Free memory = "));
  Serial.println (getFreeMemory ());
  }  // end of setup

void loop () { }

```

Perhaps surprisingly, that sketch already uses 346 bytes of RAM, and it hasn't got any (visible) variables in it.

---

> what can I do to reduce it?

```
  Serial.println("Making Ginormous Class (do nothing constructor)...");

```

You could start by using the `F` macro:

```
  Serial.println(F("Making Ginormous Class (do nothing constructor)..."));

```

---
Tags: programming, arduino-ide, c++, memory, pointer
---


# Question
Title: 4-20 milliamp to volts to pressure maths
I am measuring pressure in bars from OsiSense™ XMLP pressure sensor (4-20 milliamp) on a arduino uno. When the machine im measuring pressure on is switched off the reading is 0v as expected. When the machine is on (the sensor is on) the reading is 1v as expected.
When the machine is on and hydraulics are active the voltage fluctuates as expected.

The problem I have is I don't know the maths to translate the voltage to bar pressure.

From a previus question i've asked from 0v to 5v the equation is:

```
// This is for the DEFAULT 5V analog reference.
// v = the voltage at the pin in Volts.
// p = the pressure in bar.
// Note that 'bar' is the pressure relative to the
// normal atmospheric pressure at that moment.
float v = (float) analogRead(A0) / 1024.0 * 5.0;
float p = v / 5.0 * 100.0;"

```

Is it just a matter of changing the equation to take into account the 1v when the sensor has power and then dividing by 4 instead of 5:

```
RawVoltage = (float) analogRead(A0) - 1;
float v = RawVoltage / 1024.0 * 4.0;
float p = v / 5.0 * 100.0;"

```

# Answer
> 1 votes
If I understand your question correctly, when the sensor is on,

* 4 mA (1 V on the Arduino) means 0 bar
* 20 mA (5 V on the Arduino) means 100 bar.

Is that correct?

If that is correct, there you just have to linearly map the voltage range to the pressure range. The equation is

P = (v − 1 V) / 4 V × 100 bar

or, in C++:

```
float v = analogRead(A0) / 1024.0 * 5.0;  // in volts
float p = (v - 1) / 4 * 100;              // in bars

```

---
Tags: arduino-uno, sensors, resistor, pressure
---


title: Adafruit Huzzah espcomm_open failed

text:
# Question
Title: Adafruit Huzzah espcomm_open failed
I recently bought an adafruit huzzah as well as a serial to usb cable to connect it to my computer running windows 10. I was able to get the board set up in arduino following the directions found here. I copied and pasted this sketch:

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

void loop() {
  digitalWrite(0, HIGH);
  delay(500);
  digitalWrite(0, LOW);
  delay(500);
}

```

into the arduino 1.8.2 IDE, followed these instructions:

> Hold down the GPIO0 button, the red LED will be lit
>
> While holding down GPIO0, click the RESET button
>
> Release RESET, then release GPIO0
>
> When you release the RESET button, the red LED will be lit dimly, this means it's ready to bootload

and tried to upload only to get an error:

In versions 1.6.5 and 2.0.0 of the esp library I get these errors:

```
warning: espcomm_sync failed
error: espcomm_open failed
error: espcomm_open failed

```

In versions 2.1.0 - 2.3.0 of the esp library, I get these errors:

```
warning: espcomm_sync failed
error: espcomm_open failed
error: espcomm_upload_mem failed
error: espcomm_upload_mem failed

```

I've tried switching the tx and rx leads, I've tried versions 1.6.5-2.3.0 of the esp8266 library. I've also tried it on the other board that I ordered and got the same errors. Any ideas on what could be the problem?

EDIT: I've now tried it on a generic esp-01 board and am having the same issue

# Answer
> 1 votes
I had to install the SiLabs CP2104 drivers and reboot. Make sure you don't have 2 connection (Arduino IDEs, VS Code with PlatformIO, ...) open. Also, I kept pressing the reset button the first time.

https://learn.adafruit.com/adafruit-feather-huzzah-esp8266/using-arduino-ide

---
Tags: serial, esp8266, adafruit
---