title: Arithmetic mean for sensor

text:
# Question
Title: Arithmetic mean for sensor
This is the code I am currently using, but I want to add an arithmetic mean to it. My goal is: when the pin A0 reads 5 values, I get the average on which the fan and led will depend to be turned on and off, instead of 5 separate measurements.

```
int tempPin = A0;
int fan = 3;
int led = 8;
int temp;
int tempreal;
int tempMin = 20;
int tempMax = 30;

void setup()
{
  Serial.begin(9600);
  pinMode(fan, OUTPUT);
  pinMode(led, OUTPUT);
  pinMode(tempPin, INPUT);
}

void loop()
{
  temp = analogRead(tempPin);
  tempreal = temp * 0.48828125;
  delay(1);
  if(tempreal > tempMax)
  {
    digitalWrite(fan,HIGH);
    digitalWrite(led,LOW);
    delay(1);
  }
  else if (tempreal < tempMin)
  {
    digitalWrite(fan,LOW);
    digitalWrite(led,HIGH);
    delay(1);
  }
  else if (tempreal >  tempMin && tempreal <  tempMax)
  {
    digitalWrite(fan,LOW);
    digitalWrite(led,LOW);
    delay(1);
  }
}

```

**Edit** by Edgar Bonet – The OP added in a comment to my answer:

“I tried \[averaging consecutive readings\]. It worked as you would expect but it still does not solves my problem. My sensor is only getting right values in the beginning of the scanning and then it varies. That is why I wanted to make average value but it still does not work. Sadly I think I wont be able to change sensor, but is there any other way to camouflage this problem?”

Below is a screenshot showing both correct (✓) and incorrect (✗) readings:

# Answer
> 1 votes
A fixed sampling window can be hard to manage, especially if you want the calculation to be recursive, for space and speed considerations.

You can achieve similar results via exponential smoothing.

Yn = (1−α) Yn−1 \+ α Xn

Where Yn is the smoothed outcome, Xn is the current measurement, and α is the weight.

With some thoughts, it can be done with integers and without loss of precision.

edit: i ran a comparison of exponential smoothing vs. (fixed window) moving average. The moving average algorithm was written to be recursive for maximal speed.

the sampled data is a simulated sine wave:

1000 * sin(2pi\*n/100) + 100 * noise. n = 0..19999, and noise = -0.5...+0.5.

So snr = 1000 / 50 = 20:1, or about 5 digits. far worse than what you would encounter in a 10-bit adc.

the window I picked is 4.

As you can see, both approaches closely resemble each other. exponential smoothing uses much less ram and is also much faster. older data has lower weight on the output, something generally desirable in most applications.

# Answer
> 1 votes
See Arduino Tutorials Smoothing https://www.arduino.cc/en/tutorial/smoothing

Create an array to hold a series of readings. And a variable to hold the sum.

Incrementally cycle through the array, subtracting the oldest value from the sum and replacing it in the array with the current reading. Divide by the number of readings for the average.

Remember to allow for a delay in each reading as is appropriate for the sensor.

# Answer
> 1 votes
You could use a moving average. It will update at each cycle whenever you take a new reading. Suppose you want to average over N readings:

```
double moving_average(double old_average, double new_value) {
    double new_average = old_average;
    new_average -= old_average/N;
    new_average += new_value/N;
    return new_average;
}

```

I edited the function above. I had typed one of arguments incorrectly.

# Answer
> 1 votes
> My sensor is only getting right values in the beginning of the scanning and then it varies. That is why I wanted to make average value but it still does not work.

I had a similar problem. It turned out that I was reading writing and transmitting too fast. It means that since it seems that reading and writing can be interrupted during "their job", when you read a variable and in the same time someone is writing on that you're reading garbage. In my opinion this can be fixed by the application of "semaphores" or mutex or reducing the call of the reading. Randomly it would happen again but less frequently.

An idea can be found here https://forum.arduino.cc/index.php?topic=132813.0

Best

Gian Maria

# Answer
> 0 votes
Seems too simple. am I missing something?

```
--- arithmetic-mean.ino.orig    2017-04-27 19:37:01.386458500 +0200
+++ arithmetic-mean.ino 2017-04-27 19:38:14.458114972 +0200
@@ -16,8 +16,11 @@

 void loop()
 {
-  temp = analogRead(tempPin);
-  tempreal=temp * 0.48828125;
+  temp = 0;
+  for (int i = 0; i < 5; i++) {
+    temp += analogRead(tempPin);
+  }
+  tempreal = temp * 0.48828125 / 5;
   delay(1);
   if(tempreal > tempMax)
   {

```

---
Tags: temperature-sensor
---


# Question
Title: Rc receiver giving wrong values when controlling servo
So I'm building a helicopter. That why I need a receiver (tgy 9x) to read the values from my controller. Those values get passed to my Arduino due where some calculation happen and then get sent to the servos.

Now the problem is the moment I move my servo all the value I get from my receiver immediately become gibberish.

The values I should get and get when I am not sending anything to my servos. These values are in microseconds.

```
Channel1 Channel2 Channel3 Channel4
1486     1484     1482     1472
1486     1484     1482     1472
1486     1484     1482     1472
1486     1484     1482     1472

```

What I get after moving the servo. These should be between 1000 and 2000.

```
Channel1 Channel2 Channel3 Channel4
1495     18660    1105     17182
1495     2337     5667     3070
8828     7674     8795     6198
10289    7674     8795     11404

```

The Arduino gets power from the USB (at the moment) and the servo from the ESC of my motor. All the grounds are connected. There is only one servo hooked up and all wires from the receiver are not anywhere near any power lines or servos.

So the question is why is the receiver giving me gibberish and how do I fix it.

Right now I have commented everything out except this:

**RC\_controller.h**

```
#ifndef RC_controller
#define RC_controller

#include <Arduino.h>
#include "eeprom.h"

void RC_init();
void calc_input0();
void calc_input1();
void calc_input2();
void calc_input3();
void calc_input4();
void calc_input5();
#endif

```

---

**RC\_controller.cpp**

```
#define RC_NUM_CHANNELS  8
uint32_t volatile rc_start[RC_NUM_CHANNELS];
uint32_t volatile rc_shared[RC_NUM_CHANNELS];
uint32_t volatile rc_raw[RC_NUM_CHANNELS];

int rc_channels_pin[8] = {2, 3, 4, 5, 6, 7, 8, 9};

void calc_input0() {
 int identifyer = 0;
   if (digitalRead(rc_channels_pin[identifyer]) == HIGH) {
     rc_start[identifyer] = micros();
   } else {
     rc_raw[identifyer] = (uint16_t)(micros() - rc_start[identifyer]);
   }
}

...

void RC_init()
{

 for (byte i = 0; i > RC_NUM_CHANNELS; i++)
   pinMode(rc_channels_pin, INPUT);

 attachInterrupt(digitalPinToInterrupt(rc_channels_pin[0]), calc_input0, CHANGE);
 attachInterrupt(digitalPinToInterrupt(rc_channels_pin[1]), calc_input1, CHANGE);
 attachInterrupt(digitalPinToInterrupt(rc_channels_pin[2]), calc_input2, CHANGE);
 attachInterrupt(digitalPinToInterrupt(rc_channels_pin[3]), calc_input3, CHANGE);
 attachInterrupt(digitalPinToInterrupt(rc_channels_pin[4]), calc_input4, CHANGE);
 attachInterrupt(digitalPinToInterrupt(rc_channels_pin[5]), calc_input5, CHANGE);
}

```

---

**main.cpp**

```
...
void setup()
{
Serial.begin(115200);
  Wire.begin();
#if I2CDEV_IMPLEMENTATION == I2CDEV_BUILTIN_FASTWIRE
    Fastwire::setup(400, true);
#endif
for (int a = 0; a < 3; a++)
  swashplate[a].attach(10+a, 1200, 1800);
RC_init();
}

void loop()
{
if (rc_raw[0] < 2000)
  {
    swasplate[0].write(rc_raw[0]);
  }

  Serial.print(rc_raw[0]);
  Serial.print("    ");
  Serial.print(rc_raw[1]);
  Serial.print("    ");
  Serial.print(rc_raw[2]);
  Serial.print("    ");
  Serial.print(rc_raw[3]);
  Serial.print("    ");
  Serial.print(rc_raw[4]);
  Serial.print("    ");
  Serial.print(rc_raw[5]);
  Serial.print("    ");
  Serial.println();
}

```

# Answer
I found the problem. The problem was with the interrupts when the program was running and doing calculations at that moment the Arduino would be interrupted and stop in the middle of it, and change the value it was doing calculations with. This somehow caused the Arduino to sent interference over the signal wires. Reading the signals with a reading guard fixed the problem.

```
void read_inputs()
{
  noInterrupts();

  byte identifyer = 0;
  rc_shared[identifyer] = rc_raw[identifyer];

  ...

  interrupts();
}

```
> 0 votes

---
Tags: programming, arduino-due, electronics
---


# Question
Title: What is the minimal possible latency between arduino and PC
Case specifications:

* PC OS: Debian 9, x64 arch
* Starting time point: i have a 1kb buffer on arduino that i want to send to host PC
* Ending time point: i have recieved the buffer in a custom written C\C++ app running on a host PC
* I want to send such a buffer once a second

What is the minimal possible latency - time passed between starting and ending points? and with what communication type? (serial?)

# Answer
> 4 votes
There is more to low-latency communication than just squirting data as fast as you can (though that is an important part of it).

One thing people often forget is that the Arduino can only (easily) do one thing at a time. While you're sending your buffer to the PC it can't be sampling and filling your buffer. If you have a buffer which fills up over the period of 1 second and you want to send that buffer to the PC when full, what happens during the subsequent second while you're sending the buffer? The buffer can't be being filled while it's being sent.

Using a normal UART to USB connection as most of the normal Arduino boards (Uno, Mega, etc) use the fastest you can reasonably expect is around 1MBaud. That's about 100kB/s. Less if you use a cheap Chinese clone with a CH340G. Even at 100kB/s your 1kB buffer, if sent completely raw and in binary, would take around 10ms to transfer. But getting the computer to make any sense of that raw data would be hard. So you'd need to wrap it in some form of protocol (up to you to design that...) so you may get half that speed (or worse depending on your protocol design).

And during that time not much else can happen.

For smooth low-latency communication of data it is much more preferable to use "ping-pong" buffers and interrupt- or DMA-driven sampling of your data. That means that one buffer is receiving your data from whatever source, and the other is being sent to the PC. Once the first buffer is filled up they reverse roles. However, the little 8-bit Arduinos aren't really suited for that kind of thing:

* They don't have much RAM to waste on two buffers
* They don't have interrupts with priorities to allow samples to occur while sending
* They don't have DMA to do background transfers of data to/from peripherals

If latency is really that critical you would be better using one of the ARM-based Arduinos, such as the Due, where you can also then take advantage of a high-speed native USB interface which can give much higher throughput than a UART connection. Your choice of USB endpoint can also influence the latency of your design:

* Isochronous - Lowest latency, small packets, not guaranteed to be delivered
* Interrupt - Medium latency, small packets, delivery guaranteed
* Bulk - High latency, large packets, delivery guaranteed

Isochronous is used mainly for audio where you would notice the slightest delay in sound, but wouldn't necessarily notice or worry about a slight glitch in the quality. Interrupt is used for things like HID where you need it to respond to you pressing the keys on your keyboard nice and fast, but you're never sending much data (64 byte packet limit on interrupt transfers). Bulk is used for things like CDC/ACM (Serial over USB) where you may want to tranfer lots of data but wouldn't notice if it's pausing for a few ms every now and then (HS USB has a 512 byte packet limit on bulk transfers, FS USB has a 64 byte limit).

One of the great things with a direct USB connection is that underneath it is all packet-based, so you can use that as your transfer protocol if you know what you're doing. Don't just rely on the CDC/ACM "pipe", but instead make use of the underlying USB protocol to send individual packets which the receiving program can then understand and break apart into the right data without adding any extra protocol overheads.

For more advanced USB programming the Teensy and chipKIT cores have far more sophisticated USB support than the Arduino core, so you may fancy taking a look at their offerings in the way of boards that may suit your needs better.

# Answer
> 0 votes
it is not exactly what you ask, but yesterday I tested the speed with this sketch:

```
void setup() {
  Serial.begin(460800);
  delay(5000);
}

void loop() {
  Serial.println();
  unsigned long start = millis();
  for (unsigned long i = 0; i < 1000000L; i++) {
    Serial.write('A');
  }
  Serial.flush();
  Serial.println();
  Serial.println(millis() - start);
  while(true);
}

```

to receive on linux to file:

```
stty -F /dev/ttyACM0 460800
(stty raw; cat > received.txt) < /dev/ttyACM0

```

the sketch measured 20000 ms to push that 1MB over Serial. the Arduino is Mega 2560. at 921600 baud not all data were transfered.

EDIT: Nano 328p clone with CH340 complete only at 230400 baud in 45000 ms

---
Tags: buffer, latency
---


# Question
Title: ESP8266(01) doesn't work when servo connected to GPIO-2
the wiki here says http://www.esp8266.com/wiki/doku.php?id=esp8266\_gpio\_pin\_allocations

```
0 Low
1 High
x floating
MODE                   GPIO15   GPIO0   GPIO2
SDIO (BootSDCard)       1       x        x
UART (UploadCode)       0       0        x or 1
FLASH (NormalRunning)   0       1        x or 1

```

Can connecting my GPIO 2 to a servo Signal Wire cause it to go LOW? because some how my ESP8266 doen't boot when I have a servo hooked up to it. I tried to change it to RX (which is GPIO3 on ESP8266) and everything seems to work fine. But I wanna know the reason why GPIO2 didn't work.

Thank you.

p/s:http://www.goodluckbuy.com/ld-1501mg-metal-gear-digital-servo-17kg-for-rc-robot.html this is the servo, if it matters. Also GPIO-2 works when I use another servo of different type instead (I don't know its name though)

# Answer
It's what Juraj said.

> add external pull-up to io 2 -Juraj

sovled it
> 0 votes

---
Tags: esp8266, servo
---


# Question
Title: How to prevent shoot-through when swiching a motor with a bridge?
Ideally, when wiring a motor with an H-Bridge one would ensure that all "open" operations are performed before and "close" operations in order to prevent a short circuit. **How does one ensure that these operations are performed in order when using a bridge?**

I see on some forums that the L298 IC is a recommended bridge for controlling motors with the Arduino, but this condition is seemingly never discussed. It is not an issue with the speed of modern ICs or are the common tutorials overlooking shoot-through in the interest of simplicity?

# Answer
> 4 votes
You only get this kind of problem when you are manually controlling the high- and low-side switches manually. Bridge chips seldom make you do that and include the logic and drive circuitry within them so that you just control a HIGH or LOW to a "leg" and it switches the two transistors properly for you.

You normally get an "enable" and a "direction" input.

For instance, take the L298 internal circuit:

If we look at the left-most transistor pair you can see they are driven by a pair of gates. One has an inversion on the input. The gates are mainly there to AND the *enable* signal in, but the inversion on the upper input of the lower gate is the vital thing. That makes sure that one transistor is on when another is off. You can't turn both on, or both off - you only have a single signal that indicates which should be on.

Of course, that circuit is very simplified, and there is additional circuitry that ensures that during the switching period one transistor switches off before the other switches on. Matched transistors with known switching characteristics, adding offsets to the base voltages with diodes, etc are all methods that are used internally.

With MOSFET based bridges it's less of an issue since gate threshold (*VGS*) come into play and choosing and matching the transistors correctly automatically creates a "dead zone" in the switching input voltage range.

---
Tags: motor, wires
---


title: Arduino and Python

text:
# Question
Title: Arduino and Python
Does anyone know how do I get Arduino and Python talking to each other? I would essentially like to write my code and export it somehow to the arduino-uno.

# Answer
You can not run python on an UNO. If you want to use python on a microcontoller you should look into boards supported by MicroPython or Circuit Python
> 2 votes

# Answer
The Arduino communicates with the PC (and vice-versa) normally using Serial. You can use the PySerial module in your python code to open the Arduino's serial port and read and write data, and the `Serial` object in your Arduino code likewise.

What that data is, and what it means, though is up to you to decide upon and program.
> -1 votes

---
Tags: arduino-uno, python
---


# Question
Title: Arduino String: use a non-null-terminated char array?
I'm using a library that takes a `String` as it's parameter (https://github.com/gmag11/painlessMesh)

I want to pass char arrays that is binary (UTF-8) data that also contains null-bytes (`0x00`). Right now, the resulting String is cut off at the first null-byte as expected. I know the full length of the char array, is it possible to construct an Arduino String while passing the arbitrary length, so that the full String also contains the null-bytes including the data that follows after, up until the pre-set length?

I had this problem before and then I solved it by converting the UTF-8 data to hex and then add a null-byte. I was hoping there is a more elegant way, since this forces me to double the data-size.

Thanks!

# Answer
Assuming you are talking about the function

```
bool painlessMesh::sendBroadcast( String &msg, bool includeSelf = false)

```

Then you'll see that ultimately, the library passes `msg` into the function `buildMeshPackage` where it constructs a JSON message (see here)

```
String ICACHE_FLASH_ATTR painlessMesh::buildMeshPackage(uint32_t destId, uint32_t fromId, meshPackageType type, String &msg) {
    debugMsg(GENERAL, "In buildMeshPackage(): msg=%s\n", msg.c_str());

    DynamicJsonBuffer jsonBuffer;
    JsonObject& root = jsonBuffer.createObject();
    root["dest"] = destId;
    //root["from"] = _nodeId;
    root["from"] = fromId;
    root["type"] = (uint8_t)type;

    switch (type) {
    case NODE_SYNC_REQUEST:
    case NODE_SYNC_REPLY:
    {
        JsonArray& subs = jsonBuffer.parseArray(msg);
        if (!subs.success()) {
            debugMsg(GENERAL, "buildMeshPackage(): subs = jsonBuffer.parseArray( msg ) failed!");
        }
        root["subs"] = subs;
        break;
    }
    case TIME_SYNC:
        root["msg"] = jsonBuffer.parseObject(msg);
        break;
    default:
        root["msg"] = msg;
    }

    String ret;
    root.printTo(ret);
    return ret;
}

```

Even if you did construct a `String` with null terminators in it, the moment it gets put into the JSON string it destroys everything. JSON by default doesn't support binary data strings (reference).

So, the library is a problem because it happily passes data as JSON messages, and that's bad if you want binary data transported. You could use Base64 or the more efficient http://base91.sourceforge.net/ encoding though to mitigate this a little bit, or search for a different lib.
> 3 votes

---
Tags: string, convert, data
---


# Question
Title: ESP8266 check if TCP client disconnected...informally
Hi with ESP8266WiFi library, I usually check for connection of a TCP client with client.connected().

But it seems to still return **true** if my TCP client in an unexpected way (like disconnect to WiFi/ Power loss/...). Which leaves my program stuck in a infinite loop.

Is there a more reliable to check for connection status?

# Answer
> 2 votes
You have the inherent problem that a TCP connection is terminated by an explicit "FIN" message from the terminating party, followed by a FIN-ACK and ACK.

Refer to here.

If your client (or server) just powers off without closing the connection properly, that's it. The connection hangs up and no data will be transfered if it is not explicitly handled.

If you must know whether the client is still there, you must use a heartbeat meachanism. That is, after some period time without a response has passed, query the connection party with a "heartbeat" message and see if it responds after a given maximum time. The other way around would be to make the client send a periodic "Keep Alive" message which holds up the connection as long as it is sent repeadetly.

Refer to here and here.

---
Tags: esp8266, tcpip
---


# Question
Title: ZS-040 (HC-05) blueetooth module Arduino Mega
I followed this tutorial http://www.martyncurrey.com/using-an-arduino-mega-with-a-hc-05-zs-040-at-mode/ and it seems that the AT mode is on. (the LED is blinking like it's supposed)

I connected my pins like this:

> BT VCC to Arduino 5V out. Disconnect before running the sketch
>
> BT GND to Arduino GND
>
> BT RX (through a voltage divider) to Arduino TX1 (pin 18)
>
> BT TX to Arduino RX1 (no need voltage divider) (pin 19)

This is the code I run: (from the tutorial)

```
// Basic Bluetooth test sketch 5a for the Arduino Mega.
// AT mode using button switch
// HC-05 with EN pin and button switch
//
// Uses serial with the host computer and serial1 for communication with the Bluetooth module
//
//  Pins
//  BT VCC to Arduino 5V out. Disconnect before running the sketch
//  BT GND to Arduino GND
//  BT RX (through a voltage divider) to Arduino TX1 (pin 18)
//  BT TX  to Arduino RX1 (no need voltage divider)   (pin 19)
//
// When a command is entered in to the serial monitor on the computer
// the Arduino will relay it to the Bluetooth module and display the result.
//

char serialByte = '0';
const byte  LEDPIN = 13;

void setup()
{
    pinMode(LEDPIN, OUTPUT);

    // communication with the host computer
    Serial.begin(9600);

    Serial.println("Do not power the BT module");
    Serial.println(" ");
    Serial.println("On the BT module, press the button switch (keep pressed, and at the same time power the BT module");
    Serial.println("The LED on the BT module should now flash on/off every 2 seconds");
    Serial.println("Can now release the button switch on the BT module");
    Serial.println(" ");
    Serial.println("After entering AT mode, type 1 and hit send");
    Serial.println(" ");

    // wait for the user to type "1" in the serial monitor
    while (serialByte !='1')
    {
        if ( Serial1.available() )   {  serialByte = Serial1.read();  }
    }

    // communication with the BT module on serial1
    Serial1.begin(38400);

    // LED to show we have started the serial channels
    digitalWrite(LEDPIN, HIGH);

    Serial.println(" ");
    Serial.println("AT mode.");
    Serial.println("Remember to to set Both NL & CR in the serial monitor.");
    Serial.println("The HC-05 accepts commands in both upper case and lower case");
    Serial.println(" ");
}

void loop()
{
    // listen for communication from the BT module and then write it to the serial monitor
    if ( Serial1.available() )   {  Serial.write( Serial1.read() );  }

    // listen for user input and send it to the HC-05
   if ( Serial.available() )   {  Serial1.write( Serial.read() );  }
}

```

I want to mention that the baud rate is set to **9600** and **Both NL & CR** is also set.

The problem is when I insert `1` in the Serial Monitor and nothing happens. How can I solve this problem?

# Answer
> 1 votes
**Solution**

Connection:

* Bluetooth RXD to Arduino Mega pin 11
* Bluetooth TXD to Arduino Mega pin 10
* Bluetooth VCC to Arduino Mega 5V
* Bluetooth GND to Arduino Mega GND

I used this code:

```
#include <SoftwareSerial.h>

#define RxD 10
#define TxD 11

SoftwareSerial BTSerial(RxD, TxD);

void setup(){
  // replace BAUDRATE as suggested
  BTSerial.begin(BAUDRATE);
  Serial.begin(9600);
  BTSerial.print("AT\r\n");
}

void loop(){

  if (BTSerial.available())
    Serial.write(BTSerial.read());

  if (Serial.available())
    BTSerial.write(Serial.read());

}

```

after setting AT mode as described in the tutorial above.

I tried running the code with `BAUDRATE` starting from 9600 to 460800:

---
Tags: arduino-mega, bluetooth
---


title: Best method of detecting peg in hole

text:
# Question
Title: Best method of detecting peg in hole
I’ve got a large wall with 1” holes scattered about. I’ve got some wooden pegs that fit perfectly into these holes. Now I’m thinking of creating a light installation based on the pegs, but i’m Struggling to find a way of detecting when a peg has been inserted into any hole.

What’s the best method of detecting them? I was thinking a stop switch that’s just placed on the edge of the hole to the peg activates it, but i’m Not sure how well that can be detected or if it would bend with use

# Answer
> 2 votes
We can't tell you the "best" method. It depends on too many details we don't have.

Here are some options:

* A reed switch at the bottom of the hole and a magnet on the peg.
* A photo sensor at the back of the hole -- the peg blocks the light.
* As you suggest, a switch at the side of hole.
* Use contrasting colors on the wall and the pegs and detect the pegs using a camera and some sort of image processing (not an Arduino solution)

I think you are going to need to build some prototypes and experiment to find the best option for you.

---
Tags: sensors, button, installation
---


title: When to use PROGMEM?

text:
# Question
Title: When to use PROGMEM?
I believe PROGMEM is used to store large data (e.g. strings) that don't change. So it frees up the SRAM.

in the Ardunio Reference it is mentioned that.

"Using PROGMEM is also a two-step procedure. After getting the data into Flash memory, it requires special methods (functions), also defined in the pgmspace.h library, to read the data from program memory back into SRAM, so we can do something useful with it."

If I have to load the data into SRAM before using it then how is it efficient than directly stroing into SRAM by defining vaiable normally

# Answer
Say you have a string of 1000 characters in Flash, and you want to print it to Serial. Yes, you need to load it into RAM in order to pass that data around the place for printing. But, do you need to put *all* of it in RAM at once? No. You only need one character at a time. So instead of taking 1000 characters and allocating 1000 bytes of RAM and copying the whole shebang into RAM then printing it, you just need to allocate 1 byte of RAM\* and copy each character in turn and print it.

Since you can only read one character at a time from flash there's no advantage in reading the whole lot anyway.

---

\*Actually, because of compiler optimizations, this probably never even touches RAM and just stays in a CPU register.
> 12 votes

# Answer
If you have a constant c-string (char array) in your code without F macro or progmem, then the string is copied into RAM at start an stays there.

If in a function you use the F macro or you create a char buffer of some size and copy the progmem string into the buffer, on function return the variables are deleted from stack and the memory is released.

In case of some big array, if you put it into progmem and then in the code when you need to lookup a value in that array, you need to copy to RAM only one array item at time not the whole array.
> 4 votes

# Answer
Like Majenko said, you do not need to put everything you have in flash storage into RAM at once. You can move items into SRAM as necessary, and reuse the memory once you're done.

However, you are not limited to moving one byte at a time. There are functions defined in `avr/pgmspace.h` that can handle moving data for you.

For instance, you could do something like:

```
const struct mystruct_s my_value PROGMEM = { value = 1234 };

// ...

struct mystruct_s working_copy;
memcpy_P(&working_copy, &my_value, sizeof(struct mystruct_s));
int foo = working_copy.value / 2;

```
> 1 votes

---
Tags: memory-usage, memory
---


title: TMP36 not working with arduino uno?

text:
# Question
Title: TMP36 not working with arduino uno?
I have an Arduino Uno hooked up with a TMP36 and an ESP8266 to send the temperature reading to a PHP file which receives the post request and stores it in a text file.

The ESP8266 and PHP works fine and I'm positive of that. But the temperature my code gets are ridiculous and change a lot. I'll include my code and a Fritzing sketch and the URL to the data.txt (you can see the results real time). It might be a problem with my code or something else I'm not sure I've fiddled around to no success and hopefully some fresh eyes will help.

Most of the code is copypasta as I've never used ESP8266 before.

```
#include "SoftwareSerial.h"

String ssid ="correctssid";
String password="correctpwd";

float val=0;
int temppin = 2;
float volts=0.0;
float tempC=0.0;

SoftwareSerial esp(6, 7);

String data;
String server = "www.elijahdur.co.uk";
String url = "/arduino/esp8266/file.php"; //I've changed this just well because

void setup() {
  esp.begin(9600);
  Serial.begin(9600);
  reset();
  connectWifi();
}

void reset() {
  esp.println("AT+RST");
  delay(1000);
  if(esp.find("OK") ){
    Serial.println("Module Reset");
  }
}

void connectWifi() {
  String cmd = "AT+CWJAP=\"" +ssid+"\",\"" + password + "\"";
  esp.println(cmd);
  delay(4000);

  if(esp.find("OK")) {
    Serial.println("Connected!");
  }

  else {
    connectWifi();
    Serial.println("Cannot connect to wifi");
  }
}

void loop () {
  val = analogRead(temppin);
  volts = val * 5.0;
  volts /= 1024.0;
  tempC = (volts - 0.5) * 100;

  String string = (String) tempC;
  data = "data=" + string;
  httppost();

  delay(30000);
}

void httppost () {
  esp.println("AT+CIPSTART=\"TCP\",\"" + server + "\",80");//start a TCP connection.

  if( esp.find("OK")) {
    Serial.println("TCP connection ready");
  }

  delay(1000);

  String postRequest =
  "POST " + url + " HTTP/1.0\r\n" +
  "Host: " + server + "\r\n" +
  "Accept: *" + "/" + "*\r\n" +
  "Content-Length: " + data.length() + "\r\n" +
  "Content-Type: application/x-www-form-urlencoded\r\n" +
  "\r\n" + data;

  String sendCmd = "AT+CIPSEND=";//determine the number of caracters to be sent.

  esp.print(sendCmd);
  esp.println(postRequest.length());

  delay(500);

  if(esp.find(">")) {
    Serial.println("Sending..");
    esp.print(postRequest);
  }

  if( esp.find("SEND OK")) {
    Serial.println("Packet sent");
  }

  while (esp.available()) {
    String tmpResp = esp.readString();
    Serial.println(tmpResp);
  }

  esp.println("AT+CIPCLOSE");

}

```

The txt file is located at http://elijahdur.co.uk/arduino/esp8266/data.txt

Sometimes is will straight up give -50 and it's because it reads 0 and takes away the 5V from the analog.

Any help is greatly appreciated thank you!

**EDIT:** Apologies, but I had mixed up my sensors and was using an LM35, it still does not work however so I'm still stuck :/

# Answer
First off, as a general debugging tip: Always use a minimal example to only test one component to make sure it works. You should have tested the temperature sensor on its own, then the ESP8266 WiFi connection.

Second, regarding this code:

```
  /* as global variable */
  float val=0;

void loop () {
  val = analogRead(temppin);
  volts = val * 5.0;
  volts /= 1024.0;
  tempC = (volts - 0.5) * 100;

  String string = (String) tempC;
  data = "data=" + string;
  httppost();

  delay(30000);
}

```

The line `String string = (String) tempC;` looks very suspicious to me. You are casting a `float` to a `String` object, i.e., you re-interpret it with a cast operator. That should not work because a `float` is not a `String` object.

What should work is creating a new `String` object using its constructor, i.e., write

```
 String string(tempC);

```

If this is does not work, use the sketch at https://learn.adafruit.com/tmp36-temperature-sensor/using-a-temp-sensor, change sensorPin to `2`, double check your wiring and remove the ESP8266.

And as 3rd note: You are hooking up your Arduino's TX directly to the ESP8266's RX pin, according to your schematic. This will damage the ESP8266 module, because it is a 3.3V device and should only receive 3.3V signals -- your Arduino Uno outputs 5V as a logic 'high'. You need a voltage divider or a logic level shifter between them.
> 2 votes

# Answer
This instructables does the TMP36 part very similar using tempPin=0 instead 2 ,
I'd try that code because there shouldn't be a negative value as long you are measuring room temperate and the TMP36 is not defective.

According to these curves

and table from the TMP35/36/37 data sheet

you should measure 700-750mV (with VS 3V)
> 1 votes

---
Tags: arduino-uno, esp8266, temperature-sensor
---


title: USB upload to Pro Micro (32u4)

text:
# Question
Title: USB upload to Pro Micro (32u4)
My project is based around the ATMEGA32u4 microcontroller.

I followed the Arduino Pro Micro schematic to design my own board layout and build a custom PCB, soldered on the components. Then I used the Arduino IDE to successfully upload the Arduino bootloader with SPI.

Currently I can also upload programs to my \`32u4 over SPI (using "in-serial programming"). Tested that with Blink.

But I cannot upload programs with the USB, like you would normally be able to do with a Pro Micro. What things should I look for to debug this?

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

     System wide configuration file is "C:\Users\Myname\AppData\Local\Arduino15\packages\arduino\tools\avrdude\6.3.0-arduino9/etc/avrdude.conf"

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

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

     Programmer Type : butterfly
     Description     : Atmel AppNote AVR109 Boot Loader

Connecting to programmer: .avrdude: butterfly_recv(): programmer is not responding

```

# Answer
> 1 votes
The answer, as kindly pointed out by Gerben, is that ISP program upload overwrites the bootloader.

Only upload the bootloader via ISP, then switch to USB for uploading Arduino sketches.

---
Tags: arduino-ide, usb, arduino-leonardo, arduino-pro-micro, atmega32u4
---


title: How do string pointers work in Arduino?

text:
# Question
Title: How do string pointers work in Arduino?
To the best of my understanding, when I declare

```
String s = "This is a string.";

```

what happens is that space is allocated on the stack for a pointer which points to some String object which internally contains a char array. My confusion stems from the fact that this pointer seems(I could be wrong) to behave differently than any other type of pointer. For example, if I write

```
int a = 1;
int* x = &a;
int* y = x;

```

what happens is that the pointer saved in y now points to the same location in memory as the pointer saved at x. So if I write

```
String s1 = "This is a string.";
String s2 = "Hello World!";
s1 = s2;

```

does the pointer saved at s1 now point to the same memory location as s2? Or does s1 copy the char array from s2 into its own separate memory? Further, If I write

```
String s1 = "This is a string.";
s1 = "Hello World!";

```

does s1 now point to whatever arbitrary memory location was created for the string literal "Hello World!"? Will this memory location be freed later, or is some sort of smart garbage collector in place which knows that I am using that memory in the heap? Finally, should I never assign a string declared on the stack to a global variable, as this will be referencing a memory location which will be freed soon?

Thank you in advance for your help!

# Answer
String is not a simple type like an `int` or a `char`. It is a class with many member functions and, more importantly, operators. When you create the object it allocates room for that object either on the stack (for a local variable) or in the global data area if it's a global variable. However that object doesn't contain the memory used to store the actual string data - it only has a pointer. The memory for the string data is allocated on the *heap* using `malloc()` and `realloc()`.

Assigning string data to the String object is done through the `=` operator defined in the class, of which there are a number of overloaded varieties:

```
String & String::operator = (const String &rhs)
{
    if (this == &rhs) return *this;

    if (rhs.buffer) copy(rhs.buffer, rhs.len);
    else invalidate();

    return *this;
}

#if __cplusplus >= 201103L || defined(__GXX_EXPERIMENTAL_CXX0X__)
String & String::operator = (String &&rval)
{
    if (this != &rval) move(rval);
    return *this;
}

String & String::operator = (StringSumHelper &&rval)
{
    if (this != &rval) move(rval);
    return *this;
}
#endif

String & String::operator = (const char *cstr)
{
    if (cstr) copy(cstr, strlen(cstr));
    else invalidate();

    return *this;
}

String & String::operator = (const __FlashStringHelper *pstr)
{
    if (pstr) copy(pstr, strlen_P((PGM_P)pstr));
    else invalidate();

    return *this;
}

```

They all, ultimately, call the `copy()` or `move()` functions which copy the data from the source into the memory allocated on the heap (increasing the allocation if needed).

Using:

```
String s1 = "Foo";
String s2 = s1;

```

`s1` has memory allocated on the heap, then `Foo\0` copied into it. `s2` then also has memory allocated on the heap, and the data from `s1` is copied into it. So you have two separate objects with separate memory allocated for their content. So then doing:

```
s2 += "bar";

```

you end up with:

```
s1: "Foo\0"
s2: "Foobar\0"

```

Since it's an object that's allocated on the stack (or in global space) and not a pointer to the object you can get a pointer to it like with an `int`:

```
String s1 = "Foo";
String *s2 = &s1;
(*s2) += "bar";

```

Which gives you just one object and one memory space, but two names for it, and the result is:

```
s1: "Foobar\0"
s2: "Foobar\0"

```

This is why it's important to use either pointers or references when passing String objects as parameters to functions, and the constant allocation and reallocation on the heap why String objects are frowned upon in microcontrollers with very limited RAM.
> 8 votes

---
Tags: string, memory, pointer, object-oriented
---


# Question
Title: Why call a USB connection a serial connection?
Does anyone know why Arduino calls a USB connection a serial? When I hear a serial connection I automatically think of a male pin connection and not a USB connection. Also not sure if this a Linux term or just an Arduino thing.

# Answer
> 2 votes
As @ratchetfreak answered, USB is a **Serial** bus. But there is more.

The microcontroller on Arduino boards has one or more built-in peripherals called `UART`s, which stands for **Universal Asynchronous Receiver-Transmitter**.

This is what the Arduino core calls a Serial port. It uses the same kind of protocol as the old DB-9 serial ports on PCs and such, but at 5V or 3.3V logic levels. Contrast this 0V to 5V voltage swing to indicate Logic LOW and Logic HIGH with the RS-232 standard for the old PC serial ports, which use a +12V to -12V swing to indicate such.

But PCs today don't often have the old RS-232 serial port. They instead have the new USB - Universal Serial Bus - port. On the Arduino board is chip that communicates on one side via USB with the PC and tells the PC that it provides the equivalent of the old COMPORT or /dev/ttyS\* serial device; and on the other side via UART with the microcontroller on the Arduino board.

It's like we are "emulating" the old PC serial ports in software over the new USB bus, which itself is a serial communication system, though much more complex than a plain UART.

# Answer
> 2 votes
On most Arduinos `Serial` is not a USB connection. It is a UART (real serial) connection which is used to communicate with a USB to UART adaptor (often made out of another small MCU, the ATMega16U2). It's only from that chip onwards that it is USB. Between the main MCU and that USB interface chip it is serial. The same serial you get from pins 0/1 (literally: it's hardwired together).

Indeed, the first Arduino prototype (that grew out of the Wiring project) had no USB at all - only Serial. The USB to UART adaptor was added later. But it still remains a Serial interface.

# Answer
> 0 votes
Almost all the ways protocols used to communicate on arduino are Serial. USB,UART, I2C, SPI. Serial means one bit at a time, then the other way is Parallel communication which is what printers used to use. This allowed a whole byte to sent at one time(there were 8 data lines). As clock speeds increased there was no longer a need to have these big bulky,expensive cables and connectors. So away went parallel connections from common computer/electronics applications.

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


title: Arduino +CCLK at command parsing

text:
# Question
Title: Arduino +CCLK at command parsing
I have arduino leonardo and sim800h module. I don't seem to find the problem in my program, this is probably the 5th time I'm rewriting it. Please someone tell me what should I change to work normally. I decodes the answers, but some chars seem to disappear and sometimes appear again. With time only +CCLK stays everything else is gone. Also the time should update all the time, but the seconds stay the same for 5-10 seconds.

This is the code:

```
const long interval = 200;
static long currentMillis;

byte searchcharpos = 0; //To determine where is the + in +CCLK in the char array

char serialdata[256]; //Array to store the chars before parsing

char rtcy1[3]; //Current year  Format: yy\0
char rtcm1[3]; //Current month  Format: mm\0
char rtcd1[3]; //Current day  Format: dd\0
char rtch1[3]; //Current hour  Format: hh\0
char rtcmm1[3]; //Current minute  Format: mm\0
char rtcs1[3]; //Current second  Format: ss\0

byte pointingfinger = 0;

char enabledtime = 0;

char readenabl = 0;

char foundchar[6];

void setup() {
  Serial.begin(9600); //USB to Computer
  Serial1.begin(9600); //UART to Modem
  Serial1.print("ATE0\r"); //Disable echo
}

void loop() {
  if (millis() - currentMillis >= interval) //This is done every second
  {
    Serial1.print("AT+CCLK?\r");

    Serial.println("=========");
    Serial.print(serialdata[searchcharpos]);
    Serial.print(serialdata[searchcharpos + 1]);
    Serial.print(serialdata[searchcharpos + 2]);
    Serial.print(serialdata[searchcharpos + 3]);
    Serial.print(serialdata[searchcharpos + 4]);
    Serial.print(serialdata[searchcharpos + 5]);
    Serial.print(serialdata[searchcharpos + 6]);
    Serial.print(serialdata[searchcharpos + 7]);
    Serial.print(serialdata[searchcharpos + 8]);
    Serial.print(serialdata[searchcharpos + 9]);
    Serial.print(serialdata[searchcharpos + 10]);
    Serial.print(serialdata[searchcharpos + 11]);
    Serial.print(serialdata[searchcharpos + 12]);
    Serial.print(serialdata[searchcharpos + 13]);
    Serial.print(serialdata[searchcharpos + 14]);
    Serial.print(serialdata[searchcharpos + 15]);
    Serial.print(serialdata[searchcharpos + 16]);
    Serial.print(serialdata[searchcharpos + 17]);
    Serial.print(serialdata[searchcharpos + 18]);
    Serial.print(serialdata[searchcharpos + 19]);
    Serial.print(serialdata[searchcharpos + 20]);
    Serial.print(serialdata[searchcharpos + 21]);
    Serial.print(serialdata[searchcharpos + 22]);
    Serial.print(serialdata[searchcharpos + 23]);
    Serial.print(serialdata[searchcharpos + 24]);
    Serial.print(serialdata[searchcharpos + 25]);
    Serial.print(serialdata[searchcharpos + 26]);
    Serial.print(serialdata[searchcharpos + 27]);
    Serial.print(serialdata[searchcharpos + 28]);
    Serial.print(serialdata[searchcharpos + 29]);
    Serial.print(serialdata[searchcharpos + 30]);
    Serial.print ("=========");
    //Serial1.print("AT+CCLK?\r"); //ask for the time
    //delay(50);
    Serial.println("");
    Serial.println("=====");
    Serial.println(millis());

    Serial.println("YEAR: ");
    Serial.print(rtcy1[0]);
    Serial.println(rtcy1[1]);
    Serial.println("MONTH: ");
    Serial.print(rtcm1[0]);
    Serial.println(rtcm1[1]);
    Serial.println("DAY: ");
    Serial.print(rtcd1[0]);
    Serial.println(rtcd1[1]);
    Serial.println("HOUR: ");
    Serial.print(rtch1[0]);
    Serial.println(rtch1[1]);
    Serial.println("MINUTE: ");
    Serial.print(rtcmm1[0]);
    Serial.println(rtcmm1[1]);
    Serial.println("SECOND: ");
    Serial.print(rtcs1[0]);
    Serial.println(rtcs1[1]);

    enabledtime = 1;

    currentMillis = millis();
  }

  if (enabledtime == 1) {
  if (Serial1.available () > 0) {
    if (foundchar[0] == '\n') {
      /*for (byte a = 0; a < 255; a = a + 1 ) {
        serialdata[a] = 0;
        }*/
        readenabl = 0;
      //pointingfinger = 0;
      enabledtime = 0;
      rtcy1[0] = serialdata[searchcharpos + 8]; //getting first char with its offset
    rtcy1[1] = serialdata[searchcharpos + 9];
    rtcy1[2] = '\0';
    rtcm1[0] = serialdata[searchcharpos + 11];
    rtcm1[1] = serialdata[searchcharpos + 12];
    rtcm1[2] = '\0';
    rtcd1[0] = serialdata[searchcharpos + 14];
    rtcd1[1] = serialdata[searchcharpos + 15];
    rtcd1[2] = '\0';
    rtch1[0] = serialdata[searchcharpos + 17];
    rtch1[1] = serialdata[searchcharpos + 18];
    rtch1[2] = '\0';
    rtcmm1[0] = serialdata[searchcharpos + 20];
    rtcmm1[1] = serialdata[searchcharpos + 21];
    rtcmm1[2] = '\0';
    rtcs1[0] = serialdata[searchcharpos + 23];
    rtcs1[1] = serialdata[searchcharpos + 24];
    rtcs1[2] = '\0';
    }

    if (foundchar[0] == '\r') {
      readenabl = 0;
      //pointingfinger = 0;
      enabledtime = 0;
      rtcy1[0] = serialdata[searchcharpos + 8]; //getting first char with its offset
    rtcy1[1] = serialdata[searchcharpos + 9];
    rtcy1[2] = '\0';
    rtcm1[0] = serialdata[searchcharpos + 11];
    rtcm1[1] = serialdata[searchcharpos + 12];
    rtcm1[2] = '\0';
    rtcd1[0] = serialdata[searchcharpos + 14];
    rtcd1[1] = serialdata[searchcharpos + 15];
    rtcd1[2] = '\0';
    rtch1[0] = serialdata[searchcharpos + 17];
    rtch1[1] = serialdata[searchcharpos + 18];
    rtch1[2] = '\0';
    rtcmm1[0] = serialdata[searchcharpos + 20];
    rtcmm1[1] = serialdata[searchcharpos + 21];
    rtcmm1[2] = '\0';
    rtcs1[0] = serialdata[searchcharpos + 23];
    rtcs1[1] = serialdata[searchcharpos + 24];
    rtcs1[2] = '\0';
    }
    foundchar[0] = foundchar[1];
    foundchar[1] = foundchar[2];
    foundchar[2] = foundchar[3];
    foundchar[3] = foundchar[4];
    foundchar[4] = foundchar[5];
    foundchar[5] = Serial1.read();

    if (foundchar[0] == '+' && foundchar[1] == 'C' && foundchar[2] == 'C' && foundchar[3] == 'L' && foundchar[4] == 'K') {
      readenabl = 1;
      pointingfinger = 0;
    }
    if (readenabl == 1) {
      serialdata[pointingfinger] = foundchar[0];
      serialdata[pointingfinger + 1] = 0;
      pointingfinger++;
    }
  }
  }
}

```

This is the output:

Thanks!

# Answer
> 1 votes
This is the final working program that requests the time and parses the answer:

```
const long interval = 1000;
static long currentMillis;

byte searchcharpos = 0; //To determine where is the + in +CCLK in the char array

char serialdata[256]; //Array to store the chars before parsing

char rtcy1[3]; //Current year  Format: yy\0
char rtcm1[3]; //Current month  Format: mm\0
char rtcd1[3]; //Current day  Format: dd\0
char rtch1[3]; //Current hour  Format: hh\0
char rtcmm1[3]; //Current minute  Format: mm\0
char rtcs1[3]; //Current second  Format: ss\0

byte pointingfinger = 0; //index of the array

char enabledtime = 0; //this variable is set to 1 every second and set to 0 after parsing is done

char readenabl = 0; //this is set to 1 when is finished reading from serial

char foundchar[6]; //small buffer that works as a shift register to hold only the command for comparison

void setup() {
  Serial.begin(9600); //USB to Computer
  Serial1.begin(9600); //UART to Modem
  Serial1.print("ATE0\r"); //Disable echo
}

void loop() {
  if (millis() - currentMillis >= interval) //This is done every second
  {
    Serial1.print("AT+CCLK?\r");

    Serial.println("=========");
    Serial.print(serialdata[searchcharpos]);
    Serial.print(serialdata[searchcharpos + 1]);
    Serial.print(serialdata[searchcharpos + 2]);
    Serial.print(serialdata[searchcharpos + 3]);
    Serial.print(serialdata[searchcharpos + 4]);
    Serial.print(serialdata[searchcharpos + 5]);
    Serial.print(serialdata[searchcharpos + 6]);
    Serial.print(serialdata[searchcharpos + 7]);
    Serial.print(serialdata[searchcharpos + 8]);
    Serial.print(serialdata[searchcharpos + 9]);
    Serial.print(serialdata[searchcharpos + 10]);
    Serial.print(serialdata[searchcharpos + 11]);
    Serial.print(serialdata[searchcharpos + 12]);
    Serial.print(serialdata[searchcharpos + 13]);
    Serial.print(serialdata[searchcharpos + 14]);
    Serial.print(serialdata[searchcharpos + 15]);
    Serial.print(serialdata[searchcharpos + 16]);
    Serial.print(serialdata[searchcharpos + 17]);
    Serial.print(serialdata[searchcharpos + 18]);
    Serial.print(serialdata[searchcharpos + 19]);
    Serial.print(serialdata[searchcharpos + 20]);
    Serial.print(serialdata[searchcharpos + 21]);
    Serial.print(serialdata[searchcharpos + 22]);
    Serial.print(serialdata[searchcharpos + 23]);
    Serial.print(serialdata[searchcharpos + 24]);
    Serial.print(serialdata[searchcharpos + 25]);
    Serial.print(serialdata[searchcharpos + 26]);
    Serial.print(serialdata[searchcharpos + 27]);
    Serial.print(serialdata[searchcharpos + 28]);
    Serial.print(serialdata[searchcharpos + 29]);
    Serial.print(serialdata[searchcharpos + 30]);
    Serial.print ("=========");
    //Serial1.print("AT+CCLK?\r"); //ask for the time
    //delay(50);
    Serial.println("");
    Serial.println("=====");
    Serial.println(millis());

    Serial.println("YEAR: ");
    Serial.print(rtcy1[0]);
    Serial.println(rtcy1[1]);
    Serial.println("MONTH: ");
    Serial.print(rtcm1[0]);
    Serial.println(rtcm1[1]);
    Serial.println("DAY: ");
    Serial.print(rtcd1[0]);
    Serial.println(rtcd1[1]);
    Serial.println("HOUR: ");
    Serial.print(rtch1[0]);
    Serial.println(rtch1[1]);
    Serial.println("MINUTE: ");
    Serial.print(rtcmm1[0]);
    Serial.println(rtcmm1[1]);
    Serial.println("SECOND: ");
    Serial.print(rtcs1[0]);
    Serial.println(rtcs1[1]);

    enabledtime = 1;

    currentMillis = millis();
  }

  if (enabledtime == 1) {
    if (Serial1.available () > 0) {
      /*
        if (foundchar[0] == '\n') {
          readenabl = 0;
        //pointingfinger = 0;
        enabledtime = 0;
        rtcy1[0] = serialdata[searchcharpos + 8]; //getting first char with its offset
        rtcy1[1] = serialdata[searchcharpos + 9];
        rtcy1[2] = '\0';
        rtcm1[0] = serialdata[searchcharpos + 11];
        rtcm1[1] = serialdata[searchcharpos + 12];
        rtcm1[2] = '\0';
        rtcd1[0] = serialdata[searchcharpos + 14];
        rtcd1[1] = serialdata[searchcharpos + 15];
        rtcd1[2] = '\0';
        rtch1[0] = serialdata[searchcharpos + 17];
        rtch1[1] = serialdata[searchcharpos + 18];
        rtch1[2] = '\0';
        rtcmm1[0] = serialdata[searchcharpos + 20];
        rtcmm1[1] = serialdata[searchcharpos + 21];
        rtcmm1[2] = '\0';
        rtcs1[0] = serialdata[searchcharpos + 23];
        rtcs1[1] = serialdata[searchcharpos + 24];
        rtcs1[2] = '\0';
        }
        if (foundchar[0] == '\r') {
        readenabl = 0;
        //pointingfinger = 0;
        enabledtime = 0;
        rtcy1[0] = serialdata[searchcharpos + 8]; //getting first char with its offset
        rtcy1[1] = serialdata[searchcharpos + 9];
        rtcy1[2] = '\0';
        rtcm1[0] = serialdata[searchcharpos + 11];
        rtcm1[1] = serialdata[searchcharpos + 12];
        rtcm1[2] = '\0';
        rtcd1[0] = serialdata[searchcharpos + 14];
        rtcd1[1] = serialdata[searchcharpos + 15];
        rtcd1[2] = '\0';
        rtch1[0] = serialdata[searchcharpos + 17];
        rtch1[1] = serialdata[searchcharpos + 18];
        rtch1[2] = '\0';
        rtcmm1[0] = serialdata[searchcharpos + 20];
        rtcmm1[1] = serialdata[searchcharpos + 21];
        rtcmm1[2] = '\0';
        rtcs1[0] = serialdata[searchcharpos + 23];
        rtcs1[1] = serialdata[searchcharpos + 24];
        rtcs1[2] = '\0';
        }

        if (foundchar[0] == '\r') {
        readenabl = 0;
        //pointingfinger = 0;
        enabledtime = 0;
        rtcy1[0] = serialdata[searchcharpos + 8]; //getting first char with its offset
        rtcy1[1] = serialdata[searchcharpos + 9];
        rtcy1[2] = '\0';
        rtcm1[0] = serialdata[searchcharpos + 11];
        rtcm1[1] = serialdata[searchcharpos + 12];
        rtcm1[2] = '\0';
        rtcd1[0] = serialdata[searchcharpos + 14];
        rtcd1[1] = serialdata[searchcharpos + 15];
        rtcd1[2] = '\0';
        rtch1[0] = serialdata[searchcharpos + 17];
        rtch1[1] = serialdata[searchcharpos + 18];
        rtch1[2] = '\0';
        rtcmm1[0] = serialdata[searchcharpos + 20];
        rtcmm1[1] = serialdata[searchcharpos + 21];
        rtcmm1[2] = '\0';
        rtcs1[0] = serialdata[searchcharpos + 23];
        rtcs1[1] = serialdata[searchcharpos + 24];
        rtcs1[2] = '\0';
        }
      */
      foundchar[0] = foundchar[1];
      foundchar[1] = foundchar[2];
      foundchar[2] = foundchar[3];
      foundchar[3] = foundchar[4];
      foundchar[4] = foundchar[5];
      foundchar[5] = Serial1.read();

      if (foundchar[0] == '+' && foundchar[1] == 'C' && foundchar[2] == 'C' && foundchar[3] == 'L' && foundchar[4] == 'K' && foundchar[5] == ':') {
        readenabl = 1;
        pointingfinger = 0;
      }
      if (readenabl == 1) {
        while (foundchar[0] != '\n') {
          if (Serial1.available() > 0) {
            serialdata[pointingfinger] = foundchar[0];
            serialdata[pointingfinger + 1] = 0;
            pointingfinger++;
            foundchar[0] = foundchar[1];
            foundchar[1] = foundchar[2];
            foundchar[2] = foundchar[3];
            foundchar[3] = foundchar[4];
            foundchar[4] = foundchar[5];
            foundchar[5] = Serial1.read();

          }
        }
        readenabl = 0;
        //pointingfinger = 0;
        enabledtime = 0;
        rtcy1[0] = serialdata[searchcharpos + 8]; //getting first char with its offset
        rtcy1[1] = serialdata[searchcharpos + 9];
        rtcy1[2] = '\0';
        rtcm1[0] = serialdata[searchcharpos + 11];
        rtcm1[1] = serialdata[searchcharpos + 12];
        rtcm1[2] = '\0';
        rtcd1[0] = serialdata[searchcharpos + 14];
        rtcd1[1] = serialdata[searchcharpos + 15];
        rtcd1[2] = '\0';
        rtch1[0] = serialdata[searchcharpos + 17];
        rtch1[1] = serialdata[searchcharpos + 18];
        rtch1[2] = '\0';
        rtcmm1[0] = serialdata[searchcharpos + 20];
        rtcmm1[1] = serialdata[searchcharpos + 21];
        rtcmm1[2] = '\0';
        rtcs1[0] = serialdata[searchcharpos + 23];
        rtcs1[1] = serialdata[searchcharpos + 24];
        rtcs1[2] = '\0';
      }
    }
  }
}

```

---
Tags: serial
---


# Question
Title: How to read main code inside main code in Arduino?
How can I read the hex code of the main programme stored inside flash memory inside my running Arduino programme?

So far I am able to read the Flash at any given address by using PROGMEM

```
unsigned int displayInt;
int k;    // counter variable

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

  for(k = 0; k < 5; k++) {
    displayInt = pgm_read_word_near(k);
    Serial.println(displayInt);
  }
}

void loop() {
}

```

The output is

```
37900
13716
53
3072
37900

```

But this not hex code.

I am implementing the OTA (over the air) feature. I will get the new version of a code from GPRS. It will be huge code so I will write it to flash by using the custom bootloader mentioned in this thread. I am able to write to the flash memory. Now I would like to read the data from flash. To begin with I would like to read the main programme inside my main programme.

# Answer
> 5 votes
Interesting. If you want hex you have to tell it to print in hex. If I change your display line to:

```
Serial.println(displayInt, HEX);

```

Then I get:

```
940C
3594
35
C00
940C

```

Compare this to what the decompiled file looks like:

```
   0:   0c 94 35 00     jmp 0x6a    ; 0x6a <__ctors_end>
   4:   0c 94 5d 00     jmp 0xba    ; 0xba <__bad_interrupt>
   8:   0c 94 5d 00     jmp 0xba    ; 0xba <__bad_interrupt>

```

If you take the endianness into account (you are reading words, not bytes) then it is the same.

---

If you change it to read bytes it looks better:

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

  for(int k = 0; k < 12; k++) {
    byte c = pgm_read_byte(k);
    char buf [3];
    sprintf (buf, "%02X", c);
    Serial.println(buf);
  }
}

void loop() {
}

```

I increased the baud rate to 115200. I'm always puzzled when people use 9600 baud. Do you hanker for the olden days, when 9600 baud modems were the fastest you could get?

That gives this result:

```
0C
94
35
00
0C
94
5D
00
0C
94
5D
00

```

As you can see, it is exactly correct.

---
Tags: memory-usage, memory
---


# Question
Title: RFID-RC522 Can't read from MIFARE Ultralight
I tried many ways to get and print UID and other data from a MIFARE Ultralight, but it always ends with an error. I am using the RFID-RC522 reader with an Arduino UNO and thr MFRC522 Library.

I can normally get and print the PICC type of the chip, but that's the only thing that works.

This is how I have connected my RC522 reader:

<sub>(source: ytimg.com)</sub>

This is my code:

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

#define RST_PIN 9
#define SS_PIN 10

MFRC522 rfid(SS_PIN, RST_PIN);

unsigned long noSignal = 0;

bool lastState = true;
bool read = true;

void setup()
{
    pinMode(2, OUTPUT); //Red led
    pinMode(3, OUTPUT); //Green led

    Serial.begin(9600);
    SPI.begin();
    while (!Serial);

    rfid.PCD_Init();
    Serial.println("RFID ctecka byla uspesne spustena."); //Prints "RFID Reader succesfully started"
    Serial.println();

    changeLed(true);
}

void changeLed(bool red)
{
    digitalWrite(2, red);
    digitalWrite(3, !red);
}

void loop()
{
    if (millis() - noSignal >= 300)
    {
        changeLed(true);
        read = true;
    }

    bool state = !rfid.PICC_IsNewCardPresent() && !rfid.PICC_ReadCardSerial();

    if (state != lastState)
        if (state)
            noSignal = millis();
        else if (read)
        {
            read = false;

            changeLed(false);
            noSignal = millis();

            Serial.println("---------Cip detekovan----------"); //Prints "Chip detected"
            Serial.println();

            MFRC522::PICC_Type piccType = rfid.PICC_GetType(rfid.uid.sak);

            Serial.print("Znacka cipu: ");//Prints chip type
            Serial.println(rfid.PICC_GetTypeName(piccType));

            rfid.PICC_DumpToSerial(&rfid.uid); //Here is the error

            Serial.println();
            Serial.println("---------Cteni skoncilo----------");//prints "Read ended"
            Serial.println();

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

    lastState = state;
}

```

Serial monitor snapshot:

Maybe an important thing is that when I call `PCD_DumpVersionToSerial()` I get:

```
Firmware Version: 0x12 = (unknown)

```

Somewere I read that my Arduino isn't compatibile with MIFARE Ultralight and I need MIFARE Classic cards. Is that true? Can I solve this problem by using another library or is it a hardware problem?

**EDIT:** I asked my friend, who has an Arduino too from the same shop as me, if he can read MIFARE Ultralight cards. He said that it's working for him. So my problem will be probably on the hardware side. We both have unofficial Arduinos from AliExpress.

# Answer
> 3 votes
In the first lines of code there are two lines that say:

```
#define RST_PIN 9
#define SS_PIN 10

```

They define the RESET pin to be on the D9 pin and the SDA on the D10 pin. So you have an connection error try connecting like shown and you should be good to go.

---
Tags: arduino-uno, rfid
---


title: GPS not display

text:
# Question
Title: GPS not display
so im currently trying to do a a project whereby if my sensor is active, it will display my location. but, it seems that when the sensor is active, it only display location of lat: 0.00 , long: 0.00 on my LCD display. help me to solve this problem.

```
#include <LiquidCrystal.h>
#include <TinyGPS++.h>
#include <SoftwareSerial.h>

SoftwareSerial mySerial(9,10);
char msg;

int knockPin = 7;                   // Use Pin 7 as our Input
int knockVal = HIGH;                // This is where we record our shock measurement
boolean bAlarm = false;
int knockValue = digitalRead(6);
unsigned long lastKnockTime;        // Record the time that we measured a shock
int knockAlarmTime = 500;           // Number of milli seconds to keep the knock alarm high

static const int RXPin = 13, TXPin = 8;
static const int GPSBaud = 9600;
TinyGPSPlus gps;
SoftwareSerial ss(RXPin, TXPin);

const int rs = 12, en = 11, d4 = 5, d5 = 4, d6 = 3, d7 = 2;
LiquidCrystal lcd(rs, en, d4, d5, d6, d7);

void setup ()
{
  mySerial.begin(19200);   // Setting the baud rate of GSM Module
  delay(20000);
  ss.begin(GPSBaud);
  Serial.begin(115200);
  Serial.println("GSM SIM900A BEGIN");
  pinMode (knockPin, INPUT) ;       // input from the KY-031
  pinMode (6, OUTPUT);
  lcd.begin(16, 2);
  String latitude = String(gps.location.lat(),6);
  String longitude = String(gps.location.lng(),6);
      lcd.clear();
      lcd.setCursor(2,0);
      lcd.print("VeCAS System");
      lcd.setCursor(3,1);
      lcd.print(">>Begin>>");
      delay (5000);

}

void loop ()
{
  knockVal = digitalRead (knockPin) ; // read KY-031 Value

  if (knockVal == LOW)                // If we see a knock
  {

    lastKnockTime = millis();         // record the time of the shock
                                      // The following is so you don't scroll on the output screen
    if (!bAlarm)
    {

      Serial.println("KNOCK, KNOCK");
      bAlarm = true;
      digitalWrite (6, HIGH);
      Serial.println(knockVal);
      delay(100);

      while (ss.available() > 0)
    gps.encode(ss.read());
    if (gps.location.isUpdated())
       lcd.clear();
      lcd.setCursor(4,0);
      lcd.print("KNOCK!");
      lcd.setCursor(3,1);
      lcd.print("Detected");
      delay (5000);

          lcd.clear();
          Serial.print("Latitude= ");
          Serial.print(gps.location.lat(), 6);
          Serial.print(" Longitude= ");
          Serial.println(gps.location.lng(), 6);

          lcd.setCursor(0,0);
          lcd.print("LAT:");
          lcd.setCursor(5,0);
          lcd.print(gps.location.lat());
          lcd.setCursor(0,1);
          lcd.print("LON:");
          lcd.setCursor(5,1);
          lcd.print(gps.location.lng());
          delay(1000);
          lcd.clear();

    }
   }

 else
  {
    if( (millis()-lastKnockTime) > knockAlarmTime  &&  bAlarm)
    {
      Serial.println("no knocks");
      bAlarm = false;
      digitalWrite (6, LOW);
      delay(100);
    }
   }
  }

void gpsTrack()
{
      lcd.clear();
      lcd.setCursor(4,0);
      lcd.print("KNOCK!");
      lcd.setCursor(3,1);
      lcd.print("Detected");
      delay (5000);

          lcd.clear();
          Serial.print("Latitude= ");
          Serial.print(gps.location.lat(), 6);
          Serial.print(" Longitude= ");
          Serial.println(gps.location.lng(), 6);

          lcd.setCursor(0,0);
          lcd.print("LAT:");
          lcd.setCursor(5,0);
          lcd.print(gps.location.lat());
          lcd.setCursor(0,1);
          lcd.print("LON:");
          lcd.setCursor(5,1);
          lcd.print(gps.location.lng());
          delay(1000);
          lcd.clear();
}

```

# Answer
> 1 votes
If you put the GPS on `Serial` (pins 0 & 1) and the GSM on `AltSoftSerial` (pins 8 & 9), it could work. You will have to disconnect pin 0 to upload new sketches over USB. I *assume* that you have an UNO or Nano, because you didn't say which Arduino you are using.

Like Majenko said, this will never work with two `SoftwareSerial` ports. `SoftwareSerial` is very inefficient, because it disables interrupts for long periods of time. This can interfere with other parts of your sketch or with other libraries. And it cannot send and receive at the same time. This answer provides complete details.

You may also want to take a look at my NeoGPS library. It is smaller, faster, more reliable and more accurate than all other GPS libraries. Even if you don't use it, you should read the page about choosing a serial port. There are also many tips on the Troubleshooting page.

NeoGPS, AltSoftSerial and NeoSWSerial are available from the IDE Library Manager, under the menu **Sketch -\> Include Library -\> Manage Libraries**.

BTW, you can't use `delay` like that. You must constantly read and decode the GPS characters. The sketch will lose many, many GPS characters, preventing it from ever getting complete GPS information. You have to do something like this:

```
#include <LiquidCrystal.h>
#include <NMEAGPS.h>
#include <AltSoftSerial.h>

AltSoftSerial gsmPort; // receive pin 8 to GSM TX, transmit pin 9 to GSM RX

char msg;

int knockPin = 7;                   // Use Pin 7 as our Input
int knockVal = HIGH;                // This is where we record our shock measurement
boolean bAlarm = false;
int knockValue = digitalRead(6);
unsigned long lastKnockTime;        // Record the time that we measured a shock
int knockAlarmTime = 500;           // Number of milli seconds to keep the knock alarm high

static const int GPSBaud = 9600;
NMEAGPS gps;
gps_fix fix;
#define gpsPort Serial // RX pin 0 to GPS TX, TX pin 1 to GPS RX

const int rs = 12, en = 11, d4 = 5, d5 = 4, d6 = 3, d7 = 2;
LiquidCrystal lcd(rs, en, d4, d5, d6, d7);

void setup ()
{
  gsmPort.begin(19200);   // Setting the baud rate of GSM Module

  gpsPort.begin(GPSBaud);
  //Serial.begin(115200);  // gpsPort *is* serial
  //  Serial Monitor has to be set at 9600 (lower right
  //    corner of Serial Monitor window)
  Serial.println("GSM SIM900A BEGIN");
  pinMode (knockPin, INPUT) ;       // input from the KY-031
  pinMode (6, OUTPUT);

  lcd.begin(16, 2);
  lcd.clear();
  lcd.setCursor(2,0);
  lcd.print("VeCAS System");
  lcd.setCursor(3,1);
  lcd.print(">>Begin>>");
  delay( 1000 );
}

void loop ()
{
  // Check for GPS characters (always!)
  if (gps.available( gpsPort )) {
    fix = gps.read(); // save the latest GPS fields in one structure
    gpsTrack();       // show the latest GPS fields
  }

  // Check for knocks

  knockVal = digitalRead (knockPin) ; // read KY-031 Value

  if (knockVal == LOW)                // If we see a knock
  {

    lastKnockTime = millis();         // record the time of the shock
                                      // The following is so you don't scroll on the output screen
    if (!bAlarm)
    {

      bAlarm = true;
      digitalWrite (6, HIGH);

      Serial.println("KNOCK, KNOCK");
      Serial.println(knockVal);

      lcd.clear();
      lcd.setCursor(4,0);
      lcd.print("KNOCK!");
      lcd.setCursor(3,1);
      lcd.print("Detected");
    }
  }
  else
  {
    if( (millis()-lastKnockTime) > knockAlarmTime  &&  bAlarm)
    {
      Serial.println("no knocks");
      bAlarm = false;
      digitalWrite (6, LOW);
    }
  }
}

void gpsTrack()
{
  Serial.print("Latitude= ");
  if (fix.valid.location)
    Serial.print( fix.latitude(), 6);
  Serial.print(" Longitude= ");
  if (fix.valid.location)
    Serial.println( fix.longitude(), 6);

  lcd.clear();
  lcd.setCursor(0,0);
  lcd.print("LAT:");
  lcd.setCursor(5,0);
  if (fix.valid.location)
    lcd.print( fix.latitude() );
  lcd.setCursor(0,1);
  lcd.print("LON:");
  lcd.setCursor(5,1);
  if (fix.valid.location)
    lcd.print( fix.longitude() );
}

```

Notice that it also checks the location validity flag *before* using the lat/lon values. Your GPS may not know the location, perhaps due to bad satellite reception.

# Answer
> 0 votes
You have two SoftwareSerial ports. You can't reliably use two of them at once. Only one can be set to receive data, and that one is the first one you define. You can switch between them with the `listen()` function, but it's not recommended. If you never want to receive on one of them then it's (almost) fine, but when sending on any of them nothing can be received anywhere (not even on the hardware Serial port).

Adding to `setup()` after `ss.begin(GPSBaud)`:

```
ss.listen();

```

may make it work for the time being, but as soon as you start doing anything more with `mySerial` you could run into trouble.

If you need more than one serial port in your design then you really should be looking at using a more capable board with more hardware UART ports.

---
Tags: arduino-uno, gps
---


# Question
Title: Error to make a request using Arduino Uno and ESP8266
I'm using Arduino Uno and ESP8266 in a project.

I'm using AT Commands to connect to wi-fi and make a request. I'm using the monitor serial to test the code before compile it in arduino.

It is connecting to wi-fi and I can make a request to a server in my network but when i try to make a request to my web-service in cloud it doesn't work well.

The return is an HTML with an 404 page instead of what I am expecting:

```
<h1>Hello Versa</h1>

```

Here is my code:

```
AT+CIPSTART="TCP","ternary.com.br",80
AT+CIPSEND=18
GET /webservice/

```

Can someone help me telling me what I am doing wrong?

---

After see the answer of Maximilian Gerhardt, I solved it writing the following sequence in the monitor serialize:

```
AT+CIPSTART="TCP","ternary.com.br",80
AT+CIPSEND=70
GET /webservice/ HTTP/1.1
Host: ternary.com.br
Connection: Close
[Just press enter and send a new line]

```

# Answer
A HTTP requests is comprised of more than just `GET /webservice/`. Take a look at what `curl` (console-line HTTP client) does.

```
C:\>curl -v "http://ternary.com.br/webservice/"
*   Trying 187.84.237.200...
* Connected to ternary.com.br (187.84.237.200) port 80 (#0)
> GET /webservice/ HTTP/1.1
> Host: ternary.com.br
> User-Agent: curl/7.46.0
> Accept: */*
>
< HTTP/1.1 200 OK
< Date: Fri, 11 May 2018 15:04:16 GMT
< Server: Apache
< X-Powered-By: PHP/5.6.30
< Vary: Accept-Encoding
< Cache-Control: max-age=0, no-cache, no-store, must-revalidate
< Expires: Wed, 11 Jan 1984 05:00:00 GMT
< X-UA-Compatible: IE=Edge,chrome=1
< Pragma: no-cache
< Transfer-Encoding: chunked
< Content-Type: text/html; charset=UTF-8
<
<h1>Hello Versa</h1>* Connection #0 to host ternary.com.br left intact

```

You will have to at least transfer the minimal correct HTTP Headers of the form

```
GET /webservice/ HTTP/1.1
Host: ternary.com.br
Connection: Close

```

To get an answer. Also mind the ending `\r\n\r\n`. Refer to this website for more headers.

When I only send `GET /webservice/` I also get 404 page.

```
C:\>cat test
GET /webservice/

C:\>cat test | ncat ternary.com.br 80
[...]
        <title data-i18n="[html]404_page.title">404 ÔÇô P├ígina n├úo encontrada</title>

```
> 1 votes

---
Tags: esp8266, http
---


# Question
Title: Arduino Mega Pins for SoftwareSerial (vs. AltSoftSerial)
I am currently looking at using an Arduino Mega to build a MIDI Receive box that will then pump the data over USB, but am having design issues/uncertainties with the Arduino's receiving end.

I am looking to having (hopefully) 16 MIDI (as 5-pin DINs) inputs on this build, with no outputs other than the USB. The Mega has the 4 Rx pins, which still leaves me with 12 to create in software. From what I've read it appears that SoftwareSerial will not support simultaneous reads from different inputs, while AlftSofSerial does. However, it also appears (at least from what I've gathered) that AltSoftSerial is not supported on as many pins as I would need to make this work.

With my setup up, not all 16 MIDI devices would be sending data into the Arduino at once, but only 2 - 4; these would be operating at the same time though (i.e. a Keyboard note along with a volume fader), so I don't believe SoftwareSerial would work well for what I need.

Is it possible to work out what I need with SoftwareSerial/AltSoftSerial and the physical UARTs? If there's any necessary info that seems to be missing or I seem to be misunderstanding something, please let me know. Thanks!

# Answer
> 0 votes
> From what I've read it appears that SoftwareSerial will not support simultaneous reads from different inputs

Correct. You can only `listen()` on one instance at a time.

AltSoftSerial can only support 1 instance, but allows simultaneous transmit and receive, and doesn't block the whole system while either transmitting or receiving.

So the best you can hope for is 4 hardware UART and one AltSoftSerial for 5 ports.

I would suggest looking into the possibility of using multiple Arduino Mega boards with 4 ports on each (4 boards would give 16 ports in total) and have them communicate with each other through some other protocol (SPI or I2C for instance).

---
Tags: softwareserial, uart, midi, atmega2560, rx-pin
---


# Question
Title: 2 buttons, 1 servo, turn when pressed only
I have a code problem. I need to turn a servo clockwise or counter clockwise using 2 microswitches.

The problem is that my code is fine on startup, but when i press the button the servo continues to spin.

How do i make this so it only spins while the buttons are pressed and turn off when they are not pressed?

```
#include <Servo.h>

Servo myservo; // create servo object to control a servo

// CONSTANTS

// PINS
const int crServo = 12; // sets pin 12 as servo
const int buttonPinCW = 2; // sets pin 2 as button; CW => clockwise => FOCUS FAR
const int buttonPinCC = 3; // sets pin 3 as button; CC => counterclockwise => FOCUS NEAR

// SERVO PROPERTIES
const int crSpeedDefault = 0; // is the stay still position, motor should not turn
const int crSpeedCW = 110; // turns the motor full speed clockwise
const int crSpeedCC = 70; // turns the motor full speed counter-clockwise

// SET BUTTON STATES
int buttonStateCW = 0; //sets button 1 as off
int buttonStateCC = 0; // sets button 2 as off

void setup()
{
  myservo.attach(crServo); // attaches the servo on pin 12 to the servo object
  pinMode (crServo, OUTPUT);
  pinMode (buttonPinCW, INPUT); // sets button as input
  pinMode (buttonPinCC, INPUT); // sets button as input
  myservo.write(crSpeedDefault); // default servo to crSpeedDefault
}

void loop()
{
  crServo = digitalRead(crSpeedDefault);
  buttonStateCW = digitalRead(buttonPinCW);
  buttonStateCC = digitalRead(buttonPinCC);
  // clockwise rotation
  if (buttonStateCW == HIGH) {
    myservo.write(crSpeedCW);
    // counterclockwise rotation
  }
  if (buttonStateCC == HIGH) {
    myservo.write(crSpeedCC);
  }
}

```

# Answer
If you want the logic "if none of the two buttons are pressed, stop the servo immediately", then you'd express this in your `loop` as a `if` expression where you check if both buttons read `LOW`:

```
void loop()
{
  buttonStateCW = digitalRead(buttonPinCW);
  buttonStateCC = digitalRead(buttonPinCC);
  // clockwise rotation
  if (buttonStateCW == HIGH) {
    myservo.write(crSpeedCW);
    // counterclockwise rotation
  }
  if (buttonStateCC == HIGH) {
    myservo.write(crSpeedCC);
  }

  //Are both buttons not pressed?
  if(buttonStateCC == LOW && buttonStateCW == LOW) {
    //Stop the servo.
    myservo.write(0);
  }
}

```

This assumes your buttons are with pull-down resistors to GND on one side and with +5V on the other side, as detailed in the Arduino tutorial. In short this means that an unpressed button reads as `0` and a pressed on reads as `1` (`HIGH`). This is unusual because we usually use the internal pullup resistors via the `INPUT_PULLUP` `pinMode` parameter with a switched logic (`1` = unpressed, `0` = pressed).

I've also removed the line `crServo = digitalRead(crSpeedDefault);` because that doesn't make sense in my opinion, as I've detailed in my comment.
> 2 votes

# Answer
This solution is similar to @Maximilian Gerhardt's solution. So his comments on the pull-up/down resistors apply.

I assume that you only want to turn either CW or CC and not oscillate between the two.

Then you should cater for 4 button conditions:
None pressed, CW only press, CC only press, both pressed.

We only need to worry about the "only pressed" conditions and a default state when coding.

Here is my solution:

```
void loop()
{
  buttonStateCW = digitalRead(buttonPinCW);
  buttonStateCC = digitalRead(buttonPinCC);

  // CW button pressed only
  if (buttonStateCW == HIGH && buttonStateCC == LOW) {
    myservo.write(crSpeedCW); // clockwise rotation
  }
  // CC button pressed only
  else if (buttonStateCW == LOW && buttonStateCC == HIGH) {
    myservo.write(crSpeedCC); // counterclockwise rotation
  }
  // Default condition
  else {
    myservo.write(crSpeedDefault);
  }
}

```
> 1 votes

---
Tags: programming
---


# Question
Title: Arduino ESP8266 - wifi evt: 3 and wifi evt: 7 meaning?
I'm getting these in my serial port, but what does wifi evt 3 and 7 mean? I am trying to complete this tutorial. https://youtu.be/4Z0gBG8dkqw

The PHP file is on my hosting, and the ESP reads out the temperature and humidity from the sensor so that's fine.

**The serial code:**

```
Connecting
wifi evt: 3
Connected
Temperature:
24.10
Humidity:
39.70
[hostByName] request IP for: lucasdebelder.be
[hostByName] Host: lucasdebelder.be IP: 185.182.57.81
connected
HTTP/1.1 200 OK
Date: Fri, 11 May 2018 13:14:17 GMT
Server: Apache/2
Upgrade: h2,h2c
Connection: Upgrade, close
Vary: User-Agent
Content-Length: 0
Content-Type: text/html; charset=UTF-8

�
wifi evt: 7
wifi evt: 7
wifi evt: 7
wifi evt: 7
wifi evt: 7
wifi evt: 7
wifi evt: 7
wifi evt: 7
wifi evt: 7
wifi evt: 7
wifi evt: 7
wifi evt: 7
wifi evt: 7
wifi evt: 7
wifi evt: 7
wifi evt: 7
wifi evt: 7
wifi evt: 7
wifi evt: 7
wifi evt: 7
wifi evt: 7
wifi evt: 7
wifi evt: 7
wifi evt: 7
wifi evt: 7
wifi evt: 7
wifi evt: 7
wifi evt: 7
wifi evt: 7
wifi evt: 7
wifi evt: 7
wifi evt: 7
wifi evt: 7
wifi evt: 7
wifi evt: 7
wifi evt: 7
wifi evt: 7
wifi evt: 7
wifi evt: 7

```

**The code that I am running in Arduino.**

```
#include <ESP8266WiFi.h>
#include "DHT.h"

const char* ssid     = "bbox2";      // SSID of local network
const char* password = "azerty";   // Password on network

WiFiClient client;
char servername[]="lucasdebelder.be";  // remote server we will connect to
String result;

float temperature;
float humidity;

#define DHTPIN 14

#define DHTTYPE DHT22
DHT dht(DHTPIN, DHTTYPE);

void setup() {
  dht.begin();
  delay(2000);
  Serial.begin(115200);
  Serial.println("Connecting");
  WiFi.begin(ssid, password);

  while (WiFi.status() != WL_CONNECTED) {
    delay(100);
  }
  Serial.println("Connected");
  delay(1000);
  readSensor();
  String temperatureString = String(temperature,1);
  String humidityString = String(humidity,1);
  sendDataToServer(temperatureString,humidityString);
}

void loop() {

}

void sendDataToServer(String temperature, String humidity)
{
  if (client.connect(servername, 80)) {  //starts client connection, checks for connection
    Serial.println("connected");
    client.println("GET /send_email.php?temperature="+temperature+"&humidity="+humidity+" HTTP/1.1"); //Send data
    client.println("Host: lucasdebelder.be");
    client.println("Connection: close");  //close 1.1 persistent connection
    client.println(); //end of get request
  }
  else {
    Serial.println("connection failed"); //error message if no client connect
    Serial.println();
  }

 while(client.connected() && !client.available()) delay(1); //waits for data
  while (client.connected() || client.available()) { //connected or data available
    char c = client.read(); //gets byte from ethernet buffer
      result = result+c;
    }

  client.stop(); //stop client
  Serial.println(result);

}

void readSensor()
{

  humidity = dht.readHumidity();
  temperature = dht.readTemperature();
  Serial.println("Temperature:");
  Serial.println(temperature);
  Serial.println("Humidity:");
  Serial.println(humidity);

}

```

# Answer
The codes are explained in this forum thread. The wifi event types are described here (and also duplicated here, which are ultimately coming from the Espressif Non-RTOS SDK, chapter 6.2.4):

```
typedef enum WiFiEvent
{
    WIFI_EVENT_STAMODE_CONNECTED = 0,
    WIFI_EVENT_STAMODE_DISCONNECTED,
    WIFI_EVENT_STAMODE_AUTHMODE_CHANGE,
    WIFI_EVENT_STAMODE_GOT_IP,
    WIFI_EVENT_STAMODE_DHCP_TIMEOUT,
    WIFI_EVENT_SOFTAPMODE_STACONNECTED,
    WIFI_EVENT_SOFTAPMODE_STADISCONNECTED,
    WIFI_EVENT_SOFTAPMODE_PROBEREQRECVED,
    WIFI_EVENT_MAX,
    WIFI_EVENT_ANY = WIFI_EVENT_MAX,
    WIFI_EVENT_MODE_CHANGE
} WiFiEvent_t;

```

The enum's values are increasing downwards, meaning that 7 is `WIFI_EVENT_SOFTAPMODE_PROBEREQRECVED`. Receiving a probe request means that some other device has scanned the surrounding WiFi networks and your ESP answered. This indicates that your ESP is in the Software Access Point (AP) + Station (SoftAP + STA) mode. But you only want to be a station in your own WiFi network, not an access point yourself.

The output is triggered by this function.

This comment on an issue suggests that you add `WiFi.mode(WIFI_STA);` to your `setup`, like

```
void setup() {
  WiFi.mode(WIFI_STA);
  dht.begin();
  delay(2000);
  Serial.begin(115200);
  Serial.println("Connecting");
  WiFi.begin(ssid, password);

  while (WiFi.status() != WL_CONNECTED) {
    delay(100);
  }
  Serial.println("Connected");
  delay(1000);
  readSensor();
  String temperatureString = String(temperature,1);
  String humidityString = String(humidity,1);
  sendDataToServer(temperatureString,humidityString);
}

```

Subsequently, a WiFi event 3 indicates `WIFI_EVENT_STAMODE_GOT_IP`. Which also makes sense because you're telling the module to connect to the WiFi, it acquires an IP over DHCP and is then fully connected. This message is harmless since it doesn't indicate an error.

You should investigate on why these debug messages are thrown in the first place. The messages are only printed if two macros are set: `DEBUG_ESP_WIFI` and `DEBUG_ESP_PORT` (see here). So *something* must do `#define DEBUG_ESP_WIFI` and `#define DEBUG_ESP_PORT Serial` somewhere.

This is either done in some compiler settings which you are not aware of or because you modified a header file to include this change. Either way, you can try to use the `#undef` pre-processor macro to remove these definitions again before including the library. Change your first line to the following:

```
//Try to kill the DEBUG defines
#undef DEBUG_ESP_WIFI
#undef DEBUG_ESP_PORT
#undef DEBUG_WIFI
#include <ESP8266WiFi.h>

```
> 4 votes

# Answer
You see the "wifi" debug messages because you set in Tools menu `Debug Level "WiFi"`. Set`Debug Level "None"`
> 1 votes

---
Tags: esp8266, wifi
---


title: Heads Up Display Helmet With arduino

text:
# Question
Title: Heads Up Display Helmet With arduino
I want to make a HUD Helmet similar to the one shown in Ironman movies. Please suggest me some links and parts needed for this type of project

# Answer
There is a fairly inexpensive solution, but it's not Arduino based.

All you need is:

* the Google Cardboard sdk
* a fairly modern and powerful Android phone (I have a OnePlusOne and it works well with Cardboard apps) - assuming you already own something similar, this is where the big saving happens :-)
* a compatible head unit: there are many available on ebay (on some you might have to drill a hole where the camera of the phone is located.) price got from about $5 to $25
* some high level programming skills to write your augmented reality application, but there's no way around it :-) - you might even find some demo on the net.

Here the basic of the solution I'm proposing is to take the video stream from the front camera on the phone, use the CardBoard API to create a view for each eye (yes, you will loose stereoscopy, since each eye will see the same image from the camera) and overlay it with whatever info you would like to show. The simpler case could be a compass, where you show N-W-S-E at the top of the field of view. Or you could even add a map, like in a FPS :-)

The part where the arduino might come useful is if you want to create some (bluetooth, for example) sensor and/or controller (using the usb port from the phone requires both a phone with HW that supports host mode and a rooted device).
> 3 votes

# Answer
You will need Electroluminescent Transparent display, something like this display from Beneq

But these displays are segmented displays...The problem with these displays is these displays are very expensive :( other problem is Focusing the display, You need to keep the display at your Focal distance..

Good thing is : You can use "CUSTOM ARDUINO" board to control this display, "IF" size is consideration :)

Happy Learning..
> 1 votes

# Answer
You can't. You can't even simulate it or even begin to approach that style of display.

Try it. Print something out then hold it in front of your face the distance the visor is away from you. Now try and focus on it. You can't. The human eyes are unable to focus that closely.

You would need to focus the vision through lenses (which is what VR headsets do) or directly project through prisms and lenses into the eye (which is what Google Glass does) in order for you to be able to see the images you generate.

You could do it if you required the user to wear special glasses to focus their vision, however they then wouldn't be able to focus on anything else much and would keep walking into things and tripping over their own feet. The rest of the world would just be a complete blur.

The whole depiction of those kind of HUD displays are impractical. In military HUD systems the image is either fed via a single eyepiece (and it takes lots of practice and brain training to get the brain to superimpose the two images), or it's projected on to the cockpit window. The only way it could be done as they depict it would be to directly project the images into both eyes (to create a 3D effect) superimposing it over the natural light entering the eyes. That would then of course mean that it would be invisible to anyone except the user, so still wouldn't be quite the same.
> 0 votes

# Answer
Luckily the concept of an Ironman helmet has more options then one would think and can be broken down as if any form of helmet. First theres the question of dimensions and proportion - this has more options than I realized since the Ironman helmet has undergone many transformations over more than 50 years both in print and film. An image search of "Ironman mask" and "Ironman comic" shows that there are a lot of options to choose from. Additionally I haven't found a consensus to exactly how Ironman was able to see outside the helmet which leaves your options open as well.

The "Ironman Mask" has what some could argue are two covered openings for the user to look through. Call them windows, eye holes - what ever - but they are openings to allow the user a direct field of vision through the helmet. If this is the case you are asking for a system that projects an overlay of some type into the users natural line of sight. Others could argue that these "eyes" on the outside of the mask are just for looks and that the users vision is completely enclosed in the helmet and that their entire view of the outside world is somehow projected into their view within the helmet.

If we're speaking of the first case, an Arduino can be used for a simple head mounted display (there are multiple examples if you Google it - include terms "glass", "hmd", and "hud") but Uno and other atmel based Arduinos are limited to simple 8 bit animations and text, nothing truly impressive or emersive. You will also have the issue of image correction in cases where your trying to create a large overlay - the viewable image will warp and fade since not projected onto surface strait on. Lenses can be used to correct but this is costly and not realistic for most diy/makers which only leaves software based solutions which Uno cannot handle running. It is possible however with other boards like the pi zero which is comparable in size and price and has enough power for higher resolution graphics and image correction. Note this approach will still require a single lens for focusing the projected image, but these are basic and cheap lenses as opposed to prisms or multi-lens solutions.

The second case would functionally be more like a VR headset and could be a challenge with some designs of Ironman helmets due to limited space within the helmet. If willing to stretch the proportion of the helmet a generic low definition version could be created using cheap lenses and at least two unos. it will require at least one FPV camera module and two display modules as well as whatever sensors you would be using. this would be more in line with Igor Stoppa's answer.
> 0 votes

---
Tags: arduino-uno
---


# Question
Title: Android phone can't get ESP8266WebServer page if Content-Length > 1460
I uploaded the following sketch to my ESP8266:

```
#include <ESP8266WiFi.h>
#include <ESP8266WebServer.h>

ESP8266WebServer server(80);
String toServe;

void serveShortString() {
    server.send(200, "text/plain", "short string!");
}

void serveLongString() {
    server.send(200, "text/plain", toServe);
}

void setup() {
    WiFi.softAP("test");

    // fill string to serve:
    toServe.reserve(3000);
    for(int i=0; i<150; i++) toServe += "1234567890123456789\n";

    server.on("/long", serveLongString);
    server.on("/short", serveShortString);
    server.begin();
}

void loop() {
    server.handleClient();
}

```

It serves a short message on `/short` and a long message (3000 chars) on `/long`.

The `/short` page works everywhere: Windows, Desktop Linux (Fedora) and Android. The `/long` page, on the other hand, only works on Windows and most of the time on desktop Linux. It *never* works on Android. I tried two phones.

I captured the network traffic on my Android phone using tPacketCapture. This is the result:

When trying to get `/short`, everything works fine. When trying to get `/long`, only the header comes through but the content never arrives. As I said, everything works fine on Windows and (most of the time) on Desktop Linux. Any idea what's going wrong?

# Answer
The solution is to add the following line to `platformio.ini`:

```
build_flags = -D PIO_FRAMEWORK_ARDUINO_LWIP2_LOW_MEMORY

```

---

I noticed that the same sketch works without a problem when building with the Arduino IDE, so I checked the differences in building with platformio and the Arduino IDE.

Turns out the relevant difference is that the Arduino IDE uses lwIP 2 by default, while platformio uses 1.4, which seems to have this bug (the same bug appears when using the Arduino IDE with lwIP 1.4).

The build flag above tells platformio to use lwIP v2.
> 1 votes

---
Tags: esp8266, http
---


# Question
Title: How do you convert a formatted print statement into a string variable?
I'm using the following routine to print the current time on the com port. I would like to capture this as a string so I can display it using ePaper.

```
    void printLocalTime()
    {
      time_t rawtime;
      struct tm timeinfo;
      if(!getLocalTime(&timeinfo))
      {
        Serial.println("Failed to obtain time");
       return;
      }
     Serial.println(&timeinfo, "%A, %B %d %Y %H:%M:%S");
    }

```

produces -

> Saturday, May 12 2018 12:18:27

# Answer
> 8 votes
To achieve what you want you probably want to use the "string format time" function `strftime` (docs). You would write the result in a character buffer, which you can also print directly without having to convert it to `String` object.

So, the following code should work:

```
void printLocalTime()
{
  time_t rawtime;
  struct tm timeinfo;
  if(!getLocalTime(&timeinfo))
  {
    Serial.println("Failed to obtain time");
   return;
  }
  char timeStringBuff[50]; //50 chars should be enough
  strftime(timeStringBuff, sizeof(timeStringBuff), "%A, %B %d %Y %H:%M:%S", &timeinfo);
  //print like "const char*"
  Serial.println(timeStringBuff);

  //Optional: Construct String object
  String asString(timeStringBuff);
}

```

The overload for `Serial.print` also does this exact same thing:

```
size_t Print::print(struct tm * timeinfo, const char * format)
{
    const char * f = format;
    if(!f){
        f = "%c";
    }
    char buf[64];
    size_t written = strftime(buf, 64, f, timeinfo);
    print(buf);
    return written;
}

```

---
Tags: string, esp32
---


title: Capacitors, Arduinos and Saving Data

text:
# Question
Title: Capacitors, Arduinos and Saving Data
In short, I have programmed and wired a speed/odometer and all is working well. However, I need to save data from the components/sensors once a power button is pressed, which has led me down the road of capacitors which seem to be the solution to my problem. Reading online about capacitors has dropped me in the deep end where I would like some help to see if I am thinking right.

I have attached a clearly very crude circuit which I need someone to confirm if I have it correct. If it's important, the whole system ran on 5v, powered by a 9v battery. Is a 5v Capacitor even the right one to use, considering that most components will not be active at the point of powering down?

OLD IMAGE: https://i.stack.imgur.com/aXhRi.jpg NEW IMAGE: https://imgur.com/a/aHRpzE4

Just tried to download the app and it's not happening for some reason, so the link(edited) will have to do, I'm sorry.

# Answer
> 1 votes
Just slapping a random capacitor across your supply is not going to work. It's far more complex than that.

Yes, a capacitor is used to store a charge, but you have to manage that charge properly or you won't get much of a chance to do anything with it.

You need to:

1. Ensure that the discharge voltage remains high enough to run the chip for long enough to save your data (Note: writing to EEPROM causes an increase in current)
2. Isolate the capacitor from the rest of the circuit so it only powers the main chip
3. Monitor the incoming power to know when to do the saving.

A block-diagram of your setup may look something like this:

simulate this circuit – Schematic created using CircuitLab

In that diagram R1 and R2 form a voltage divider so you can monitor the battery voltage. C1 is a *big* capacitor. We're talking super-cap teritory here. Rated at 9V *minimum*. The regulator on the Arduino is ignored. You don't want to use it. *Two* external regulators are now used to power your project - one direct from the battery to run the breadboard and other external components (which will lose power immediately the battery power is removed) and the other to run the main MCU and nothing else. The second regulator is isolated from the rest of the circuit by D1, and the capacitor's charge then can only go through that regulator to power the main MCU.

That regulator for the MCU should be a switching regulator (DC-DC, "buck" regulator). If you use a linear ("LDO") regulator you will waste power and your capacitor will have to be two or three times bigger than otherwise. Even better would be to have a "buck-boost" regulator that will boost the voltage up to 5V when the input voltage drops below 5V, thus giving you even more life from the capacitor.

An alternative to all this is to use the 47C16 chip (5V) or 47L16 chip (3.3V) to store your data. This is an "EERAM" chip - an EEPROM with RAM buffer and automatic saving to EEPROM at power failure. It works through I2C and needs a capacitor connected to it directly to provide the backup power while it stores the data to EEPROM.

---
Tags: arduino-uno, voltage-level, button, electronics, capacitors
---


# Question
Title: Cannot connect Mega to COM 9 but okay with other COM ports
I previously had issue updating code to Arduino Mega (clone). This is a continuation of this issue, but I think it should be made as separate thread.

After some time spending with it. Turns out if I change my USB port and connect it another USB port, the Mega is detected in port COM 6. I can upload code to the Mega using this COM port (COM6), although it shows an error sometimes. But if I change it back to the previous USB port (here the Mega detected as connected in COM9), I can't upload anything. You can see the error message in the above link.

I also have a Uno and tried uploading code to it through the same USB port (here it is detected as COM8), I can upload code.

I used the working COM (COM6) to upload Marlin FW to the Mega and I can connect my printer through the same COM port, but if I try it through COM9 I can't connect.

So why can't I use COM 9?

PS: I've been COM9 being used to communicate with the same Mega.

# Answer
> 0 votes
Check to see if you have !!! In your code. This will fail the upload.

More details here: http://net-forces.blogspot.ca/2017/08/arduino-upload-timeout-and-in-string.html?m=1

---
Tags: arduino-mega, communication
---