body:
I made a sketch like this:

    void setup() {
      // put your setup code here, to run once:
      Serial.begin(9600);

      char str1[64] = "test with spaces";
      char str2[32] = "test with spaces";

      Serial.println(str1);
      Serial.println(str2);

      if (str1 == str2) Serial.println("Equals");
      else Serial.println("Different");

      if (strcmp(str1, str2)) Serial.println("Equals");
      else Serial.println("Different");

    //  if (strcoll(str1, str2)) Serial.println("Equals"); // <-- this won't compile for Arduino UNO { why ??? }
    //  else Serial.println("Different");

      if (memcmp(str1, str2, sizeof(str2))) Serial.println("Equals");
      else Serial.println("Different");

      if (areEqual(str1, str2)) Serial.println("Equals");
      else Serial.println("Different");

      strcpy(str1, "test+with+spaces");
      strcpy(str2, "test with spaces");

      Serial.println();
      Serial.println(str1);
      Serial.println(str2);

      if (str1 == str2) Serial.println("Equals");
      else Serial.println("Different");

      if (strcmp(str1, str2)) Serial.println("Equals");
      else Serial.println("Different");

      if (memcmp(str1, str2, sizeof(str2))) Serial.println("Equals");
      else Serial.println("Different");

      if (areEqual(str1, str2)) Serial.println("Equals");
      else Serial.println("Different");

      strcpy(str1, "test+with++++++++++++++++++++++++++++++++++++spaces");
      strcpy(str2, "test with spaces");

      Serial.println();
      Serial.println(str1);
      Serial.println(str2);

      if (str1 == str2) Serial.println("Equals");
      else Serial.println("Different");

      if (strcmp(str1, str2)) Serial.println("Equals");
      else Serial.println("Different");

      if (memcmp(str1, str2, sizeof(str2))) Serial.println("Equals");
      else Serial.println("Different");

      if (areEqual(str1, str2)) Serial.println("Equals");
      else Serial.println("Different");

    }

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

    }

    bool areEqual(char* string1, char* string2) {
      return ((strlen(string1) == strlen(string2)) && (strstr(string1, string2)));
    }

Which produces this:

    test with spaces
    test with spaces
    Different
    Different
    Different
    Equals

    test+with+spaces
    test with spaces
    Different
    Equals
    Equals
    Different

    test+with++++++++++++++++++++++++++++++++++++spaces
    test with spaces
    Different
    Equals
    Equals
    Different

The first comparisson is silly (==), I know. It compares the address of the pointer, not of the string itself. I just put it there to show how hard it is for a programmer who comes from another language to understand such a thing.

The second comparison (strcmp), as the reference says "Compares the C string str1 to the C string str2.", NO, it doesn't. They are exactly the same, except for their pre-specified size. But the strings are equal to my eyes.

The third comparison (strcoll) uses locale to compare the two strings, but how come it says different when they are equal?

The fourth comparison (memcmp), given two pointers to the exact same sequence of characters, why does it say "different"?

The mind blowing part is the comparison "works" when you add as many "+" as you wish to only one of the strings. Isn't a "+" sign also a character?

It's obvious I must be missing something really basic about c++ style strings, but I dare to ask: what is it?

Thanks.

title: Yet another basic and silly question about C++ strings

Answers: 1

body:
The return value of `strcmp` does not have boolean semantics, as you seem to incorrectly assume.

`strcmp` is a *tri-state comparator*, which returns negative, zero or positive value. For equal strings it returns *zero*, which means that an equality comparison with `strcmp` should normally look as follows

    if (strcmp(str1, str2) == 0) Serial.println("Equals");
    else Serial.println("Different");

while your original code actually does the opposite.

There's a moderately widespread ugly habit of writing such comparisons as

    if (!strcmp(str1, str2)) Serial.println("Equals");
    else Serial.println("Different");

(note the application of `!` operator). It works properly, but it has poor readability. Avoid it. For tri-state comparators is a much better idea to spell out the comparison with `0` explicitly.

And you made exactly the same mistake with `memcmp`. `memcmp` is also a tri-state comparator, so it should be

    if (memcmp(str1, str2, sizeof str2) == 0) Serial.println("Equals");
    else Serial.println("Different");

The same applies to `strcoll`.

P.S. And in fact such zero-terminated strings represented by `char[]` arrays are called *C-style strings*, not C++-style strings.


body:
12bit ADC will give us about 1.2mV per step:

    5 / 4096 = 0.00122

But if we give Arduino a 1.2V voltage reference we get 1.1mV per step:

    1.2 / 1024 = 0.00117

Does that means Arduino can be more accurate than a 12 bit ADC?

title: Arduino vs 12bit ADC

Answers: 1

body:
In a word, no.

The Arduino uses a rather crude 10-bit ADC. If you feed it a small voltage reference, you can divide that small voltage into 1024 steps. (as you say, about 1.1mV/step)

If you feed the same small 1.2V reference voltage into a 12-bit ADC, you'll get 4 times as many steps for the same range. (about 293μV/step)

And, as mentioned before, the ADC's in Arduinos are not very good. They're slow, and not very accurate.

(To be technical, precision is how exactly you DESCRIBE your answer. A decimal reading using more decimal places is more precise than a reading with less decimal places. Accuracy is how close the measured value is to the actual value. If you're sloppy with your measurements but use lots of decimal places to write it down, and the answer is very far off, you have a precise but inaccurate answer. (e.g you measure something as 1.0000001 millimeters, but it's really 2.5 mm.

A 12-bit ADC is more precise than a 10-bit ADC, but it may or may not be more accurate. Given the crude nature of the ADCs in Arduinos, a dedicated 12-bit ADC is likely to be more accurate than built-in one.)


body: Hi I have an Arduino UNO and a AT28c64B and a single shift register, is it possible to make an EEPROM programmer with it? I’m not too good with the Arduino to do a lot of trial and error... I would just like to know if it’s possible or not, not how to...

title: Can you use an Arduino UNO as an EEPROM programmer

Answers: 1

body:
You need 24 GPIO pins to control that EEPROM chip. The Arduino has 19, and a typical shift register has 8 outputs. It takes 3 or 4 (depending on the shift register) to drive the shift register.

That's `19 + 8 - 4 = 23` for a shift register that needs 4 pins, or `19 + 8 - 3 = 24` for one that needs 3 pins.

However I would assume that you want to communicate with your computer as well, and that means that pins 0 and 1 of the Arduino are out of bounds, since they are used for the PC communication.

That means, at best, you have 22 pins when you need 24.

So, no, with that combination you can't, due to a lack of pins.

However an IO expander, such as the MCP23017, would give you enough pins and need fewer pins to drive. They also work in both directions, so can be used for pins that want to be read as well as written (data pins).

Alternatively an SPI or I2C connected EEPROM would be the better option, since those are designed to be driven by a small microcontroller like an Arduino uses.


body:
I am trying to design a circuit that wakes my ESP8266 (Wemos D1 Mini) from deep sleep using a shock sensor. I can achieve this using the reset pin but I need
it to ignore further requests to reset to give it time to run the code in my sketch. Provided there is still motion it will just continue to reset meaning the code only gets run after the 'shock' stops. I have tried all kinds of things with capacitors and transistors to delay subsequent resets but with very limited success. Can someone please point me in the right direction or suggest an easier way to do this? Many thanks in advance.

title: Deep Sleep Reset with Shock Sensor

Answers: 1

body:
This is actually somewhat more tricky than you would at first thing.

First off, the "shock sensor" is merely a spring inside a tube.  This will create *lots* of triggers while it's being "shocked", which really is messy.

Secondly, you only want those shocks to make it through to the ESP when you are in deep sleep.

Thirdly, you don't want whatever you connect to adversely affect, or be affected by, other circuitry that is connected to the reset pin.

So you first really need to "condition" the output of your sensor so that it gives a clean pulse that can reset the ESP8266. Then you need to "gate" that signal so it can only get through while the board is asleep.

For conditioning the shock sensor signal I would be inclined to use a 55 timer in monostable mode.  You can find a good circuit and description [here](https://www.element14.com/community/community/project14/diytestequipment/blog/2017/08/12/vintage-555-a-general-purpose-button-debouncer) which looks like this:

[![enter image description here][1]][1]

Now to gate that signal (which is active high) you need a signal to gate it with.  Since all the GPIOs of the ESP8266 are "dead" while it's asleep you need it to be in a "default on" state and have the ESP8266 drive an "I am awake" signal to disable the output.  So you'd have a pullup resistor on a GPIO to make it default HIGH (to match the trigger pulse for simplicity) and then use `pinMode()` and `digitalWrite()` as the first things after waking up (and at the start of `setup()`) to indicate it's awake by driving it LOW.  Then you combine those two signals:

* If the trigger is HIGH and
* If the gate signal is HIGH
* Then pull reset LOW
* Otherwise don't affect reset

So you make a truth table:

    Trig | Gate | Res
    -----------------
      L  |  L   |  HiZ
      L  |  H   |  HiZ
      H  |  L   |  HiZ
      H  |  H   |  L

The tricky one here is the "HiZ" - This means "High Impedance" - or in effect "Don't affect the reset pin at all".

Apart from that the truth table is that for a NAND gate - if both inputs are HIGH then the output is LOW - otherwise the output is HIGH.  Except we want HiZ not HIGH.

To make that HiZ there's two things you can do:

1. Use a NAND gate that has an "Open Collector" (or "Open Drain") output, or
2. Use an AND gate and create your own "Open Collector" that inverts the output by adding a transistor.

For option 1 you can use the 74AC01 which is a "Quad 2 input NAND gate Open Collector".  For option 2 you can use the 74AC08 and any NPN transistor (or N-channel MOSFET with a suitable threshold).

<!-- Begin schematic: In order to preserve an editable schematic, please
     don't edit this section directly.
     Click the "edit" link below the image in the preview instead. -->

![schematic](https://i.stack.imgur.com/fHFxE.png)

<!-- End schematic -->

  [1]: https://i.stack.imgur.com/zXhqb.png


body:
I have the following code;

    #include <Ethernet.h>
    #include <SPI.h>
    #include <LiquidCrystal.h>

    LiquidCrystal lcd(31, 30, 29, 28, 27, 26, 25, 24, 23, 22);
    byte mac[] = { 0xDE, 0xAD, 0xBE, 0xEF, 0xFE, 0xED };
    EthernetClient client;

    void setup()
    {
      Serial.begin(9600);
      //client.begin(mac);
      //Init Ethernet Comms
      Serial.println(F("Start."));
      while (!Ethernet.begin(mac) == 0) {
        Serial.println(F("Network Error"));
        delay(200);
      };
      Serial.println(F("Connected"));

    }

    void loop() {}

As it is above it gets out of the while loop. However, if i remove the line `LiquidCrystal lcd(31, 30, 29, 28, 27, 26, 25, 24, 23, 22);`It will then fail to connect, and stay in the loop. Im at a complete loss here as the Ethernet shield and 2x16 LCD are unrelated devices, and if anything id expect the addition of used pins to cause issue, not the removal.

Edit: I should note this is occurring on two devices, one Mega one Uno.

2nd Edit: As pointed out by Juraj in the comments, this can be resolved using Ethernet.Init(CS_Pin) where CS_Pin is an unused pin, in my case D9.

title: Ethernet.h Ethernet.Begin(mac) only connects if i have a LiquidCrystal object from LiquidCrystal.H

Answers: 0


body:
    unsigned long Htime;
    unsigned long Ltime;
    unsigned long Ttime;
    unsigned long f;
    int N;

    void setup() {
      // put your setup code here, to run once:
    cli();
      TCNT2 = 0;
      TCCR2A = 0;
      TCCR2B = 0;
      Serial.begin(9600);
      pinMode(5,INPUT);
      pinMode(3,OUTPUT);
      pinMode(11,OUTPUT);
      TCCR2A = (1 << COM0A1) | (1 << COM0B1) | (1 << WGM21) | (1 << WGM20);
      TCCR2B = (1 << WGM22) | (1 << CS22) | (1 << CS21) | (1 << CS20);
      TIMSK2 = (1 << OCIE2A);
    }

    void loop() {
      // put your main code here, to run repeatedly:
      Htime = pulseIn(5, HIGH);
      Ltime = pulseIn(5, LOW);
      Ttime = Htime + Ltime;
      f = 1000000 / Ttime;
      Serial.println(f);
      N = (16000000 / 1024 / f ) - 1;
      OCR2A = N;
      OCR2B = N/2;

    }

Hi this is what i have written. and i need output a square wave with timer, its frequency is measured from input signal in pin 5. After connecting the oscilloscope, i see the problem, there is phase shift between 2 signals. [![enter image description here][1]][1]How could i synchronize this 2 signals?(rising edge to rising edge, falling edge to falling edge) Thank u so much for your help!

  [1]: https://i.stack.imgur.com/4gL4Q.jpg

title: How could i synchronize 2 signals

Answers: 1

body:
Given that only the falling edge of your input is sharp and well
defined, I suggest the following approach:

* Use the input-capture feature of Timer 1 to get a timestamp on the
  falling edge and trigger an interrupt.

* In the ISR, start by toggling the output in order to set it low. Then
  compute the period of the signal (timestamp of this falling edge minus
  timestamp of the previous one) and program a compare register to
  trigger a compare match event after half a period.

* The compare match would automatically toggle the output pin again, by
  using the “toggle on compare match” timer output mode.

The following program attempts to implement this approach. Note that it
is completely untested. Input is on pin 8 (i.e. PB0 and ICP1). Output is
on pin 9 (i.e. PB1 and OC1A). The timer is set to run at `F_CPU/8` in
order to accommodate frequencies as low as about 30.1 Hz. A
different prescaler should be used if lower frequencies are needed. The
program does not rely on the Arduino core, and thus defines its own
`main()` instead of `setup()` and `loop()`.

```c++
ISR(TIMER1_CAPT_vect)
{
    TCCR1C = _BV(FOC1A);  // force output compare -> toggle output
    static uint16_t last_capture;
    uint16_t capture = ICR1;
    uint16_t period = capture - last_capture;
    last_capture = capture;
    OCR1A = capture + period/2;  // compare match after 1/2 period

    // If output is high, toggle again.
    if (bit_is_set(PINB, PB0))
        TCCR1C = _BV(FOC1A);
}

int main()
{
    // Set OC1A = PB1 = digital 9 as output.
    DDRB = _BV(PB1);

    // Configure Timer 1.
    TCCR1A = _BV(COM1A0);  // toggle OC1A on compare match
    TCCR1B = _BV(CS11);    // clock at F_CPU/8
    TCCR1C = _BV(FOC1A);   // force output compare -> toggle output
    TIFR1  = _BV(ICF1);    // clear capture flag
    TIMSK1 = _BV(ICIE1);   // enable capture interrupt
    sei();

    for (;;) {}
}
```


body:
What should be done to solve it?
I have edited the `board.txt` file and none of my codes are getting verified
it shows this error:

> "Error reading file (C:\Program Files
> (x86)\Arduino\hardware\arduino\avr\boards.txt:0): Invalid line format,
> should be 'key=value' "

title: Error reading file

Answers: 1

body:
You can either reinstall the Arduino IDE (it will replace the file), or copy the original code back in the file (if you have a copy somewhere).

See the link: https://code.google.com/archive/p/arduino/wikis/Platforms.wiki for more background in case you are interested.

(note: I cannot copy the content of the file in the answer since it is more than 30000 characters.)


body:
Firstly, I'm not sure if this is the right SE to ask this question. Please feel free to direct me somewhere else if needed.

I am observing large spikes in CO2 and TVOC measurements using the CJMCU-811 sensor. When plotted it looks like this:

[![enter image description here][1]][1]

Nothing particular is happening around the sensor at those moments of spikes, I'm not breathing on the sensor etc.

I use Arduino Uno with the following code:

```cpp
/******************************************************************************
  Read CO2 and TVOCs from CJMCU-811 sensor

  Arduino connection:
  3.3V to 3.3V
  ACC to 3.3V
  GND to GND
  WAK to GND
  SDA to A4
  SCL to A5

******************************************************************************/
#include <Wire.h>

#include "SparkFunCCS811.h"
#define CCS811_ADDR 0x5B

CCS811 mySensor(CCS811_ADDR);

void setup()
{
  Serial.begin(9600);
  Serial.println("CCS811 Basic Example");

  Wire.begin();

  CCS811Core::status returnCode = mySensor.begin();
  if (returnCode != CCS811Core::SENSOR_SUCCESS)
  {
    Serial.println(".begin() returned with an error.");
    while (1);
  }
}

void loop()
{

  if (mySensor.dataAvailable())
  {

    mySensor.readAlgorithmResults();

    delay(1);

    Serial.print("CO2 ");
    Serial.print(mySensor.getCO2());

    Serial.print(", tVOC ");
    Serial.print(mySensor.getTVOC());

    Serial.println();
  }

  delay(2000);
}
```

Of course I can filter and not worry about them, but I'm nevertheless curious what is causing it. Any suggestions what could be the reason for that?

  [1]: https://i.stack.imgur.com/P4Qo0.png

title: Spikes in CO2 and TVOC measurements with CJMCU-811 sensor

Answers: 3

body:
I have two of those sensors in a long term setup and I know those spikes very well. I once put lots of effort in debugging and I personally gave up on the ccs811 and use a different sensor now.

Back then I have already tried what Jaromanda suggests in his comment.
Both of my sensos showed the same behaviour while the spikes on both sensors did **not correlate** in any form.
Also, if I remember it right, those erronous readings appeared to be at dedicated values.
I tried several pullups, which also didn't make any difference and on the oscilloscope everything looked fine.
Printing the output of the I2C related functions revealed that communication was always stable. If it was I2C related I would expect those erronous readings to be completely random anyway (which they aren't from my experience).

My final (vague) theory was that maybe there exist race conditions between the computation and the I2C interface or maybe the adc and the approximation algorithm (that's all "inside" of the sensor). I once produced such a bug myself which resulted in a similar behaviour.

At least I'm pretty sure that there is nothing you can do in your sketch to fix this problem, because for the mentioned reasons it is very unlikely related to communication problems. You might want to work-around it or look for an updated firmware.
Or (my prefered solution) choose a sensor which does a **true CO2 measurement** (the ccs811 only returns a pseudo, calculated CO2-equivalent approximation).
Those higher-class sensors use NDIR technique and are only a bit more expensive (still under 50$) but you'll probably have much more reliable readings, less problems and a wider measurement range (up to 0-40000ppm vs 400-8192ppm).

Ps: did you follow the guidelines concerning the "burn-in time"? Because honestly, that was a mistake I did: I simply plugged it in of curiosity to test communication and read about this step afterwards. But I don't believe it has something to do with this problem, because there are physical reasons why one should do so, but those artifacts seem to be of digital nature.

body:
I saw similar behavior from 3 CJMCU-811 sensors that I bought (in one order, so probably the same manufacturing lot) in mid 2019. Two gave readings with steady, spikey, but uncorrelated upward growth. The third periodically spiked into the 2000-3000 ppm zone and then popped back to ~450 ppm (in an empty room with decent airflow). A logic analyzer on the I2C lines didn't show issues (or I missed them).

I went as far as adding a line to reset the sensors every few minutes. Replacing the sensors with what I assume was a different manufacturing lot resolved the issue.

I'm using the AdaFruit ccs811 library on ESP8266s (Wemos D1 minis).

**Months later:** The replacements have gone haywire, occasionally giving readings in the 3000ppm range until reset, at which point they're back to the 400-600ppm range for a while until drifting higher. I recommend avoiding the ccs811.

body:
There is a [CCS811 library](https://github.com/maarten-pennings/CCS811) which supports querying the internal firmware version of the sensor, and flashing a new firmware (latest is 2.0.1). Older firmware versions used to have burn-in compensation which apparently caused more harm than good (instead, new firmware requires sensors to be burned-in during 48 hours), and also relied on an external sensor for temperature compensation, which is simply missing on most cheap breakout boards. Ironically many cheap boards come with CCS811 flashed with an older firmware, which periodically samples the voltage on a floating pin and uses that value to correct CO2/TVOC calculations.

Unless your board features a thermistor, consider upgrading the sensor firmware to 2.0.1. Even or boards with a thermistor (e.g. original Adafruit), new firmware might give better results.


body:
I recently inherited some firmware with weird problems in regards to the duration of reading sensor values. The board is based on the ESP32 Wrover MCU and has multiple sensors connected via the I2C bus. The firmware makes use of the port of the FreeRTOS task library and uses the main loop to read two sensors as well as an extra task on the same core to read some more sensor via a DS2482 I2C to OneWire bridge. Usually I would expect the reading of the sensors to take at most one second (assuming the 'worst' case under normal conditions) via the bridge, but it takes a multitude of that, usually around 30 or more seconds for one sensor. Not only the reading but any communication over the bridge takes a very long time. One more detail: The sensors behind the bridge are connected one per channel of the bridge and the one wire channel is reset each time before a sensor is read.

My current suspicion is that using multiple tasks on the same I2C bus may screw up the timings of the communication and thus cause communication errors leading to the increased read times.

Does that suspicion sound reasonable at all or what would you suggest to investigate on the described system (knowing well, that I didn't provide too many details)?

Any ideas are welcome.

Thanks!

title: ESP32: Share I2C bus among multiple freeRTOS tasks - do I have to expect synchronization issues?

Answers: 0


body:
I'm am completing a project of mine that uses an MCP3424 i2c 18bit ADC and an arduino nano to measure temperature with an NTC thermistor but am having trouble with the arduino wire library. This is my first project using i2c so I'm not very knowledgeable about the subject but I have rigorously read the datasheet of the MCP3424 that can be found at (http://ww1.microchip.com/downloads/en/devicedoc/22088b.pdf) and tried many different ways to get it working. Also I'm new to posting on this stackexchange so pardon me if my syntax and what not is not right(I'm doing my best). Here is the code I have so far that is on my arduino.

    #include<Wire.h>
    //#include<LiquidCrystal.h>
    //LiquidCrystal lcd(12, 11, 5, 4, 3, 2);

    #define MCP 0x6E //Device will output conversion data (7 bits, device address. 1 bit, Read/Write mode)
    #define CH1 0x8c //PGA = 1, SPS = 3.75, One-Shot mode, channel 1, initiate new conversion.
    #define CH2 0xac //channel 2
    #define CH3 0xcc //channel 3
    #define CH4 0xec //channel 4

    void setup() {
      Serial.begin(9600);//Initiate Connection to computer
      //lcd.begin(16, 2); not used yet
      Wire.begin();//Initiate Wire library
    }

    void loop() {
      // Read data from
      int pins[] = {CH1, CH2, CH3, CH4};
      long results[] = {0, 0, 0, 0};
      for (int i = 0; i < 4 ; i++) {
        results[i] = ReadMCP(pins[i]);
        Serial.print(i+1);
        Serial.print(": ");
        Serial.print(ReadMCP(pins[i]));
        Serial.print(" ");
        delay(500);
      }
      Serial.print("\n");

    }
    long ReadMCP(int channel){
      //conversion takes the three bytes and converts to number between 0 and 131071
      int x, y, z;
      long result = 0;

      Wire.beginTransmission(MCP);//begin transmission with ADC in Write mode
      Wire.write(channel);//configure the ADC with settings found in either CH1, 2, 3 or 4
      Wire.endTransmission();
      //delay(500);
      Wire.requestFrom(MCP, 3);//request 6 Bytes of information from MCP3424
      x = Wire.read();//read bytes
      y = Wire.read();
      z = Wire.read();

      if (x>1) {
        if (x%2){
          result += (1 * 65536L);//x * 65536 = x * 2^16
          result += (y * 256L);//y * 256 = y * 2^8
          result += z;
          result = -131072 + result;
        }else{
          result += (y * 256L);//y * 256 = y * 2^8
          result += z;
          result = -131072 + result;
        }

      } else {
        result += (x * 65536L);//x * 65536 = x * 2^16
        result += (y * 256L);//y * 256 = y * 2^8
        result += z;
      }
      return result;
    }

My program reads the measurements from each of the 4 channels of the ADC and prints them in the serial monitor.

The issue I am having is that when this code is run without the "delay(500);" function in the ReadMCP() function my measurements from each channel of the MCP3424 are in the wrong place. It prints the measurement from channel 1 as channel 2, the measurement from channel 4 as channel 1 and etc. However, with the delay between endTransmission() and requestFrom() the values are in the correct place. I have looked all over the datasheet and experimented a lot with the issue but cannot see what is causing it. Does anyone know why?

For reference when I have something to measure attached to channel 2 the output without the delay is

1: 131071 2: 131071 3: 66891 4: 131071

and with the delay is

1: 131071 2: 66843 3: 131071 4: 131071

title: Communication between arduino nano and MCP3424 over I2c pt. 2

Answers: 0


body: I have an rs232 to TTL converter and I want to read something in the Arduino serial monitor by using the converter instead of using Arduino serial cable. I have connected the correct wiring in my opinion such as tx, Rx, Vcc and GND of the converter to Arduino pin 0 (Rx), pin 1 (Tx), 3.3 V and GND. But when I write something in the serial monitor of Arduino, I am getting nothing. But when I use only the arduino serial cable then I receive what I am writing in the serial monitor. Kindly can anyone tell me what am i doing wrong?

title: RS232 to ttl communication of arduino

Answers: 0


body:
I need a program to count days, from day 1 to day 21 for my project.

I'm making an artificial incubator and I need to show the days on an LCD.

title: Program for counting days

Answers: 1

body:
You can do that easily using Real Time Clock IC. ds1307/ds3231 ic will do the job. Adafruit has Arduino library for that. easy to interface.

I don't supprt using millis() function. you will lose your time if the system power downs or mcu resets. Using RTC chip is safe option as it has backup battery for time keeping.


body:
**Here’s the code:**
```
void setup()
{
 Serial.begin(9600);
 delay(300);

 double lat = 1111.11;
 double lon = 4444.44;

 const byte len{10};

 char sLat[len];
 char sLon[len];

 dtostrf(lat, len, 2, sLat);
 Serial.println(sLat);

 Serial.println("---");

 dtostrf(lon, len, 2, sLon);
 Serial.println(sLon);
 Serial.println(sLat); // <-- prints nothing!

 Serial.println("---");

 dtostrf(lat, len, 2, sLat);
 Serial.println(sLat);
 Serial.println(sLon); // <-- prints nothing!
}

void loop()
{
}
```

**Here’s the output:**
```
   1111.11
---
   4444.44

---
   1111.11
   4444.44   1111.11
```

As you see. Every next call for `dtostrf` ruins the previous results, in a weird way.

What’s the problem?

title: double to char* conversion. Weird results from dtostrf

Answers: 1

body:
If `len` is the text array size, you need space there for the terminating '\0'.
So the second paramater to `dtostrf` has to be smaller than `len`.


body:
I am trying to power my Arduino Mega 2560 from a benchtop power supply. I plan to essentially feed in a 9V supply directly on the Vin pin and connect the GND pin to the floating ground pin on the power supply. I noticed on the schematic that the UGND is connected to GND through this jumper. On the Arduino that I have these two pins are tied together. Does this mean that even with the external power supply the Arduino will be connected to the UGND, and in effect the protective earth?

What is the best way to float the Arduino? Would it be ok to remove the jumper connection between UGND and GND? Or should I try something like a linear USB isolator like [this][1]?

[![enter image description here][2]][2]

  [1]: https://www.analog.com/media/en/dsp-documentation/evaluation-kit-manuals/DC2092A_LTP2884FA.PDF
  [2]: https://i.stack.imgur.com/fpRxy.png

title: Floating power supply for Arduino - Is it still connected to the USB ground?

Answers: 1

body:
> Does this mean that even with the external power supply the Arduino will be connected to the UGND, and in effect the protective earth?

Yes.

> Would it be ok to remove the jumper connection between UGND and GND?

No. I don't know quite why they provided that jumper. I can see no scenario in the datasheet where it suggests the two can be separate.

> Or should I try something like a linear USB isolator like this?

If you want it to float then you need galvanic isolation on *all* USB pins. The device you link to will do that for you. There are others as well.

Personally in these situations I prefer to use a wireless communication system so there is no worry about grounds and isolation - it's naturally isolated.


body:
I want to read a [quadrature rotary encoders][1] at full resolution with only one interrupt on Arduino Nano (ATmega328). So I [found out][2] that we can use [XOR][3] to reach a full resolution:

Where pin `3` is interruptable but `4` and `5` are not.

Our requirements are:

 1. Full resolution: for example, the solution offered in [this answer][4] works at a half-resolution only, not detecting all the edges.
 2. Real-time: being as fast as possible up to the level that this hardware allows and safe in terms of not missing any of the signal edges.
 3. using only one interrupt. We need the other one for other purposes.

So far, I have developed two different codes, one aiming for safety and the other for performance:

#Preamble:

~~~c++
#include "digitalWriteFast.h"

#define pinT 3 // trigger pin comming from XOR

#define pinA 4 // channel A
#define pinB 5 // channel B

volatile long counter = 0;
long counter_ = counter;
~~~

where the `digitalWriteFast` library can be downloaded from [here][5].

#Performant:

~~~c++
volatile short int increment = 0;
volatile bool tmpA;
volatile bool tmpB;
volatile bool lastA;

ISR(trigger) {
  tmpA = digitalReadFast(pinA);
  tmpB = digitalReadFast(pinB);
  counter += (1 - 2 * tmpA) * (1 - 2 * tmpB) * (1 - 2 * (lastA != tmpA));
  lastA = tmpA;
}

void setup() {
  pinMode(pinA, INPUT_PULLUP);
  pinMode(pinB, INPUT_PULLUP);
  pinMode(pinT, INPUT_PULLUP);
  attachInterrupt(digitalPinToInterrupt(pinT), trigger, CHANGE);
  lastA = digitalReadFast(pinA);
  Serial.begin(9600);
}

void loop() {
  if (counter != counter_) {
    Serial.println(counter);
    counter_ = counter;
  }
}
~~~

#Safe:

~~~c++
volatile unsigned long error = 0;
unsigned long error_ = 0;

volatile bool inputA;
volatile bool inputB;

volatile short state; // 100 110 101 111
volatile short state_;

void detectState() {
  inputA = digitalReadFast(pinA);
  inputB = digitalReadFast(pinB);

  if (inputA) {
    if (inputB) {
      state = 111;
    } else {
      state = 110;
    }
  } else {
    if (inputB) {
      state = 101;
    } else {
      state = 100;
    }
  }
}

ISR(trigger) {

  detectState();

  if (state_ != state) {
    switch (state_) {
      case 100:
        if (state == 110) {
          counter++;
        } else if (state == 101) {
          counter--;
        } else {
          error++;
        }
        break;
      case 110:
        if (state == 100) {
          counter--;
        } else if (state == 111) {
          counter++;
        } else {
          error++;
        }
        break;
      case 101:
        if (state == 100) {
          counter++;
        } else if (state == 111) {
          counter--;
        } else {
          error++;
        }
        break;
      case 111:
        if (state == 110) {
          counter--;
        } else if (state == 101) {
          counter++;
        } else {
          error++;
        }
        break;
      default:
        error++;
        break;
    }

    state_ = state;
  } else {
    error++;
  }
}

void setup() {
  pinMode(pinT, INPUT_PULLUP);
  attachInterrupt(digitalPinToInterrupt(pinT), trigger, CHANGE);

  pinMode(pinA, INPUT_PULLUP);
  pinMode(pinB, INPUT_PULLUP);

  detectState();
  state_ = state;

  Serial.begin(9600);
}

void loop() {
  if (counter != counter_) {
    Serial.print("counter: ");
    Serial.println(counter);
    counter_ = counter;
  }

  if (error != error_) {
    Serial.print(error);
    Serial.println(" errors");
    error_ = error;
  }
}
~~~

Now my questions are:

 1. Is there any way to improve the speed/safety of the performant/safe code? Any way to improve this code is appreciated.
 2. Is it possible to have maximum speed and safety together or some trade-off in between?
 3. What is the maximum frequency we can get out of this configuration?

Thanks for your help in advance.

  [1]: https://electronics.stackexchange.com/questions/459715/how-to-check-if-my-quadrature-encoder-is-broken-or-not
  [2]: https://electronics.stackexchange.com/a/459185/124243
  [3]: https://electronics.stackexchange.com/q/459852/124243
  [4]: https://arduino.stackexchange.com/a/12064/35432
  [5]: https://github.com/NicksonYap/digitalWriteFast

title: real-time reading of a quadrature encoder at full resolution with only one interrupt on ATmega328

Answers: 1

body:
This is just a partial, rushed answer.

You should be able to get a significant speed-up if you define your own
ISR for handling the interrupt, as in:

```c++
ISR(INT1_vect) { ... }
```

The Arduino way of using interrupts is instead

```c++
void trigger() { ...}

void setup() {
    attachInterrupt(int_number, trigger, CHANGE);
    ...
}
```

but this is slow, as it involves the ISR provided by the Arduino core,
which has to locate and call your interrupt handler. The way you wrote
the handler is wrong: either you define a regular function, without the
`ISR` macro, and go the Arduino way, or you go the plain AVR path and
define the ISR yourself, which should be named `INTERRUPT_NAME_vect`, in
which case you don't use `attachInterrupt()`. The way you did it is
probably the slowest you can get, as the compiler will needlessly add an
ISR-type prologue and epilogue to your handler.

As for the maximum frequency, that's hard to assess without testing, but
you may get some idea by reading [this answer on interrupt
latency](https://arduino.stackexchange.com/a/8926/7508).

------------------------------------------------------------------------

**Edit**: As I stated in my first comment to the question, a pin change
interrupt can be used instead of an external logic gate. Here is how to
do it.

First, one should look at the Arduino Uno pinout and see that:

* digital 4 = PD4 = PCINT20
* digital 5 = PD5 = PCINT21

Both pins are tied to the pin change interrupt request 2 (PCINT2\_vect).
This interrupt can be configured in `setup()` as follows:

```c++
PCMSK2 = _BV(PCINT20)   // enable interrupt on pin PCINT20 = PD4
       | _BV(PCINT21);  // enable interrupt on pin PCINT21 = PD5
PCIFR  = _BV(PCIF2);    // clear interrupt flag
PCICR  = _BV(PCIE2);    // enable pin change interrupt request 2
```

Now, the interrupt will fire on every change of the logic levels of
inputs 4 and 5.

Then, in the ISR, the whole port D can be read in a single cycle by
just evaluating the corresponding pin input register, i.e. `PIND`. With
some shifting and masking, one can get a phase between 0 and 3
(the count is in Gray code: 0, 1, 3, 2, 0...). From the previous and the
current phase, one can compute the change that needs to be applied to
the counter:

```c++
// Handle pin change interrupt request 2.
ISR(PCINT2_vect) {
    static uint8_t previous_phase;
    uint8_t phase = (PIND >> 4) & 0x03;  // read input pins
    counter += encoder_delta(previous_phase, phase);
    previous_phase = phase;
}
```

The implementation of `encoder_delta()` is left as an exercise to the
reader. ;-)


body:
I have a basic circuit, where I'm reading analog values from 14 infrared receivers.

I set the bit resolution to 16 but specific ports are returning 10 bit values (from 0 - 1024) instead of 16 bit values (from 0 - 65536).

I can confirm this is not a problem with my circuitry because when I've tested reading each individual sensor with a port that "works" and the correct range is returned every time.

____
Here is my code:

    #include <ADC.h>

    ADC *adc = new ADC();
    const int* RECIEVERS = (int[14])
    {
        A15, A16, A17, A19, A20, A21, A22, A1, A2, A3, A6, A7, A8, A9
    };

    void setup() {
        Serial.begin(4608000);
        adc->setAveraging(16); // set number of averages
        adc->setResolution(16); // set bits of resolution
        adc->setConversionSpeed(ADC_CONVERSION_SPEED::HIGH_SPEED_16BITS);
        adc->setSamplingSpeed(ADC_SAMPLING_SPEED::VERY_HIGH_SPEED);
        for (int i = 0; i < 14; i++) pinMode(RECIEVERS[i], INPUT);
    }

    void loop() {
        for (int i = 0; i < 14; i++) {
            Serial.print(adc->analogRead(RECIEVERS[i]));
            Serial.print(" | ");
            delay(1);
        }
        Serial.println("");
    }

____

**Is there a problem with my code or is my Teensy damaged?**

title: Specific ports on Teensy 3.6 not reading correct bit resolution using ADC library?

Answers: 1

body:
The Kinesis 66 (the chip on the Teensy 3.6) has *two* ADC modules. Each one talks to different pins.

By default the configuration functions in that library configure ADC0, so unless you tell it otherwise, you will only be configuring half the ADC pins.

You should call each of the configuration functions twice, once for ADC0 and once for ADC1:

    adc->setAveraging(16, 0); // set number of averages
    adc->setResolution(16, 0); // set bits of resolution
    adc->setConversionSpeed(ADC_CONVERSION_SPEED::HIGH_SPEED_16BITS, 0);
    adc->setSamplingSpeed(ADC_SAMPLING_SPEED::VERY_HIGH_SPEED, 0);

    adc->setAveraging(16, 1); // set number of averages
    adc->setResolution(16, 1); // set bits of resolution
    adc->setConversionSpeed(ADC_CONVERSION_SPEED::HIGH_SPEED_16BITS, 1);
    adc->setSamplingSpeed(ADC_SAMPLING_SPEED::VERY_HIGH_SPEED, 1);


body:
Can I program an Arduino and then remove the micro-controller from it and use it on a breadboard without reprogramming the micro-controller again?

My steps would be:

 1. create my Arduino code.
 2. I upload the compiled code to the board.
 3. I remove the Ic and use it alone without the whole board.

Will the code be preserved on the microcontroller?

title: Program Arduino then Remove Atmega?

Answers: 4

body:
Yes. The programming of the arduino microcontroller sets the values inside the [FLASH][1]. This is [non volatile memory][2] and as such won't be erased by taking out the IC.

Please note that this is assuming a [DIP package][3] IC as these can be removed without force, heat and stress. A [TQFP][4], and [SMT packages][5] like that, IC might get damaged by moving them in such a way. This doesn't mean it has to be erased, it is still non volatile storage, but the moving process is much more dangerous for the chip.

I would recommend connecting the whole arduino or if you really need the whole chip: designing your own board/circuit which allows you to program the chip without moving it around as this is really tedious and not worth the effort. Also moving the chip around is a [ESD hazard][6].

Also please note that you'll need to add a clock source for the chip to work (most of the time). Or you'll need to enable an internal PLL. It will in any case require more effort on your part to make sure that the MCU can work. Therefore using the whole arduino board is preferable.

  [1]: https://en.wikipedia.org/wiki/Flash_memory
  [2]: https://en.wikipedia.org/wiki/Non-volatile_memory
  [3]: https://en.wikipedia.org/wiki/Dual_in-line_package
  [4]: https://en.wikipedia.org/wiki/Quad_Flat_Package
  [5]: https://en.wikipedia.org/wiki/Surface-mount_technology#/media/File:Photo-SMDchips.jpg
  [6]: https://en.wikipedia.org/wiki/Electrostatic_discharge

body:
Yes you can do it (as said by Tarick).

Note about clock:

Be sure to program it correctly:

- Do not add a bootloader if you don't need one
- Do not use an external oscillator if you don't have one on your new board! This is important, since if you remove it you will not be able to start or programming it again!

So, before you remove the IC, set this on your Arduino (I assume it is an ATMega328):

- 8MHz internal (leave external only if you have an oscillator in the new board!)
- Bootloader: no

You will see that you do not have this options if you select a normal Arduino, since it already has an oscillator.

So you should use the board manager and add this:
https://github.com/MCUdude/MiniCore

body:
As code is stored in the flash memory, your code won't erase until some unexpected happens. But the question might comes in whether your code will work properly or not when you remove microcontroller from arduino board and connect with breadboard.

As you are planning to remove the microcontroller, I am guessing you are using Arduino Uno atmega328 DIP package.

You need to do two things for the proper function of the microcontroller in the breadboard. There are other solutions exist. I always prefer this one as easy.

 1. connect 16MHz crystal with 22p(two) capacitor with the corresponding crystal pin(pin 9 &10). The crystal circuit is straightforward. Searching google might help.
 2. Pull the Reset Pin with VCC using a 10k resistor.

body: Don't forget 0.1uF caps on the VCC and AVCC pins to Gnd. AVCC must also have power on it, either direct to the VCC pin, or thru a filter (small inductor)


body:
I have a seemingly simple problem that seems to be popular, but after searching several forums I still have not found the answer: How do you use a class inside of another class?

I have simplified my problem:

    class A {
      const int pin;
      public:
      A(int attachPin) : pin(attachPin) {
      }

      void setup() {
        pinMode(pin, INPUT_PULLUP);
      }
    };

    class B {
      A myA;
      public:
      B(int a_attach) : myA(a_attach) {
      }

      void setup() {
        myA.setup();
      }
    };

    B test;

    void setup() {
       test.setup();
    }

    void loop() {
    }

title: Using a class inside of another class

Answers: 1

body: I think, the problem in that line B test. You are define a variable, but you forget to define default constructor ( B() ). You try to setup an A class with unknown pin! To avoid this you may define test variable in that way B test(2); or in that way const int test_pin = 2; B test(test_pin);. Also to avoid this problem you may to set default value to the constructor sucha as  B(int attach=2) : myA(attach) {} and define test variable, as you do in your code B test;.


body:
I am using a MCP3002 to convert an analog signal to digital data. It works fine actually, sends good data. However; After a while, when the power is turned off and on again a few times, it only returns zeros. If I Power it on the next day, it works for a while again.

I am just beginning with SPI, so I do not know 'all' the basics. Is there something I should reset when powering on or something? (Clock, Timing, etc.)

This is the code I am using (pretty straightforward):

 #include <SPI.h>
 SPISettings spiSettings(7280000, MSBFIRST, SPI_MODE0);
 const int SPI_CS = 2;

 void setup() {
  pinMode (SPI_CS, OUTPUT);
  SPI.begin();
  SPI.setBitOrder(MSBFIRST);
  SPI.setFrequency(7280000);
 }

 void loop() {
  SPI.beginTransaction(spiSettings);
  digitalWrite (SPI_CS, LOW);

  uint8_t cmd = 0b11000000;
  byte msb, lsb;
  word assembled;

  msb = SPI.transfer(cmd);
  lsb = SPI.transfer(0);

  assembled = word(msb, lsb);
  Serial.println(assembled);

  digitalWrite (SPI_CS, HIGH);
  SPI.endTransaction();
 }

Is there something wrong, or should something be added to this?

title: Reading data from the MCP3002

Answers: 1

body:
I thin the following is happening:

The MCP transmits 1 measurement per SPI transaction, which consists of activating chip select, reading data and deactivating chip select. To distinguish between different transactions, the time between deactivation and reactivation of chip select need to have a bit delay between them. Currently your code runs really fast, a few microseconds between the transactions at max.

This may also be connected to the MCP needing time to measure the analog signal.

I think there is some kind of race condition, so that the MCP does not have a new value to transmit, either because the MCP hasn't finished measurement yet, or because the delay between the transactions were just a bit too short, maybe a combination of both.

When the MCP is once in this situation, it will only send zeros at that point  (read chapter 5.1 in the datasheet. Last sentence in the left column).

You need to give the MCP more time between the transactions. I suggest using a small delay at the end of the `loop()` function. You can experiment with the actual value, I would guess, that you can go down to the microseconds range.


body:
I'm trying to achieve RS485 communication between Arduino Mega and Arduino UNO as specified in following link:

https://www.engineersgarage.com/arduino/rs485-communication-between-arduino-mega-and-arduino-pro-mini

But now my problem is The master i.e. Arduino Mega doesn't print anything on Serial Monitor.

Please help me out to solve this issue, trying from week still no success.

---

Sir Peter Paul Kiefer,

Im attaching my circuit setup

[![enter image description here][1]][1]

  [1]: https://i.stack.imgur.com/yNCfc.jpg

Master Code/Mega code

    void setup()
    {
      //Using Serial1 Port
      Serial1.begin(9600);
      Serial.begin(9600);

      //DE/RE Controling pin of RS-485
      pinMode(8, OUTPUT);
    }

    void loop()
    {
      char getdata='m';

      //DE/RE=HIGH Transmit Enabled M1
      digitalWrite(8,HIGH);

      //Write '9' and Fetch Data From Pro Mini
      Serial1.print('9');

      //DE/RE=LOW Receive Enabled M1
      digitalWrite(8,LOW);
      delay(1000);

      //If Serial Data is available
      if(Serial1.available())
      {
        while( Serial1.available() && getdata!='d' )
        {
          getdata=Serial1.read();
          Serial.print(getdata);
        }

        Serial.println("");
      }
    }

Slave code

    void setup()
    {
      //Serial1.begin(9600);//Uncomment for Arduino Lenardo
      Serial.begin(9600);
      //while(!Serial1);//Uncomment for Arduino Lenardo

      //Led Connected
      pinMode(13, OUTPUT);

      //DE/RE Controling pin of RS-485
      pinMode(8, OUTPUT);
    }

    void loop()
    {
      // put your main code here, to run repeatedly:
      char getdata='c';

      //Led OFF
      digitalWrite(13,LOW);
      //DE/RE=LOW Receive Enabled
      digitalWrite(8,LOW);

      if(Serial.available())
      {
        getdata=Serial.read();
      }

      if(getdata=='9')
      {
         //DE/RE=HIGH Transmit Enabled
         digitalWrite(8,HIGH);

         Serial.print("AcruxTek");
         Serial.print("Isld");
      }

      delay(2000);
      //Led ON
      digitalWrite(13,HIGH);
      delay(2000);
    }

---

I connected gnd of RS485 converter to arduino gnd and also i did common gnd between circuits but still no output. I used same code nothing changed.. except one thing the example uses arduino pro mini but i used arduino uno as slave

title: RS485 communication problem

Answers: 2

body:
I think there might be two issues in the engineering garage code. delay() function parameter in both codes is not matched. And another thing might cause problem is"Arduino Serial monitor hardware serial is already connected with another usb-serial converter ic which you are using for code uploading, so you cannot use this serial port for rs-485. So using software serial of Arduino pro-mini is a safe option. Finally you have to connect the software Serial pins with rs-485 converter. I have modified the code a little bit and attached the code herewith.

**Arduino Mega code**

    void setup()
    {
      Serial1.begin(9600);//Using Serial1 Port
      Serial.begin(9600);
      pinMode(8, OUTPUT);//DE/RE Controling pin of RS-485
    }

    void loop()
    {
      digitalWrite(8,HIGH);//DE/RE=HIGH Transmit Enabled M1
      Serial1.print('9');//Write '9' and Fetch Data From Pro Mini

      int timeOut = 0;
      digitalWrite(8,LOW);//DE/RE=LOW Receive Enable
      while(!Serial1.available() && timeOut < 5000)
      {
       delay(1);
       timeOut++; // wait 5s to get response from slave
      }
      String response = Serial1.readString();
      Serial.println(response);
    }

**Arduino Pro-Mini Code**

    #include <SoftwareSerial.h>
    #define RS485_RX 2
    #define RS485_TX 3
    SoftwareSerial mySerial(RS485_RX,RS485_TX);//Creating object

    void setup()
    {
      //Serial1.begin(9600);//Uncomment for Arduino Lenardo
      Serial.begin(9600);
      mySerial.begin(9600);
      //while(!Serial1);//Uncomment for Arduino Lenardo

      pinMode(13, OUTPUT);//Led Connected
      pinMode(8, OUTPUT);//DE/RE Controling pin of RS-485
    }

    void loop()
    {
      digitalWrite(13,LOW);//Led OFF
      digitalWrite(8,LOW);//DE/RE=LOW Receive Enable

      while(!mySerial.available())
      {
       delay(1);
      }

      String res = mySerial.readString();
      if (res == "9")
      {
        digitalWrite(8,HIGH);//DE/RE=HIGH Transmit Enabled
         mySerial.print("AcruxTek");
         mySerial.print("Isld");
      }
      digitalWrite(13,HIGH);//Led OFF
    }

body:
It's not really clear from the picture, but it seems that, the two adapter have no common ground. i.e you have to connect the ground (GND) pin of one the adapter to the GND pin of the other one. But do *not* remove the connection between the GND pins and the arduino GND pins.

I also assume that the mega-adapter is powered with 3.3 V and the UNO-adapter is powered with 5 V (or 3.3V I can not see). This might cause a problem, because the MAX485 chip needs a 5V power supply.

EDIT:

Sorry by a second view a saw, the mega delivers 5 V. So possibly you only have to connect the GNDs of the adapters to solve your problem.

EDIT 2:

I guess the little yellow wire in front of of both adapters connects the DE pins of them. The DE pin of each adapter is also connected to the respective Arduino PIN 8. So it doesn't matter which Arduino is requesting to switch the adapter into the send mode. Both adapters are sending. As far as I know, the adapter only work in Half Duplex you mus define the direction of the data flow. If one adapter is in send mode the other must be in receive mode.

It might also be possible that the DE and RE PIN of each adapter is connected.
But this seams strange to me also. With that I would say you setup up one adapter in both receive and send mode and the other in none of them.

EDIT 3:

By looking into the MAX485 Spec. I saw that RE is LOW active but labeled as RE (which I understood as HIGH active), so sorry the last paragraph of my EDIT 2 is nonsense. So, perhaps it's a matter of timing or (more likely) there is still something wrong with the wiring.

EDIT 4:

In the picture I see that you connect the hardware tx and rx pins to the adapter. But Software Serial needs its own pins. Pin0 and Pin1 are connected with the PC Serial Terminal over the built in USB to Serial adapter of the arduino UNO. That's the reason why you need the software serial solution on an arduino. You need a second serial interface and UNO has only one of them which is already used for the connection to the PC (Programming and serial monitor).

In the code I don't see the initialization of the software serial port.
This is also necessary:

    #include <SoftwareSerial.h>

    const byte rxPin = 2;
    const byte txPin = 3;

    // set up a new serial object
    SoftwareSerial mySerial (rxPin, txPin);


body:
First of all: my board used to work fine.

Now my Nano 33 IoT turns ON (green light) when connected to USB on Mac but:

1. doesn't enter in upload mode after pressing twice on board button.
2. doesn't shows up in any serial port: nor `/dev/cu.usbmodem14*01`, neither `/dev/tty.usbmodem14*01`

For reasons too long to explain, I want to connect via ANY pins to the SAMD21 and force the burning of a new bootloader.

Is that possible in any way? Any idea is welcome!

Tx

title: Nano 33 IoT rescue from the dead: No USB. No upload mode

Answers: 1

body:
Use the SWD interface and a programmer to burn the bootloader to SAMD.

[![enter image description here][1]][1]

source of the picture https://medium.com/@manuel.bl/arduino-in-circuit-debugging-with-platformio-9f699da57ddc

I had luck with [Adafruit DAP library][2] using an Arduino M0 to burn a bootloader to MKR Zero.

  [1]: https://i.stack.imgur.com/ZFNM6.png
  [2]: https://learn.adafruit.com/programming-an-m0-using-an-arduino


body:
I made a mistake connecting SD0 (GPIO7) and SD1 (GPIO8) with the SDA and SCL on my arduino nano. I got confused with GPIO21 and pin21 and GPIO22 and pin 22!

Since I made a PCB prototype, I would avoid to add some wires and cut the traces, so I would ask if I could use these pins (GPIO7 and GPIO8) as SDA and SCL.

If the answer is affirmative, using Arduino library how could I assign them?

Wire.begin (7,8)?

Another question, I would use a dedicate 2x4.7K pull up resistors. On the arduino side I wrote:

digitalWrite(SDA, 0);
digitalWrite(SCL, 0);

It is correct to do the same thing on the ESP32 side?

Update November 01:
After the question from Majenco I think I need more help for the I2c setup.

I designed the PCB having in mind that the esp32 was 5V tolerant, so at the moment I pull-up the SDA, SCL from the 5V that I input in the esp power pin. Note that this 5V doesn't come from the Nano due to the high current required by the esp. I take my 12V power supply input and regulate it to 5V with a 7805, only dedicated to the esp (I know, a lot of dissipation! In the next PCB version I have to change the things, having in mind that I need both 12V and 5V in my circuit).

Now, I read that the esp32 is not 5V tolerant. In order to avoid level shifter can I pull up the SDA and SCL from the 3.3V line (the arduino 3.3V or esp32 one?)?

I would use the esp32 as master.

Thanks.

title: Connect arduino nano and ESP32 with I2C on the GPIO7 and GPIO8?

Answers: 1

body:
> Since I made a PCB prototype, I would avoid to add some wires and cut the traces, so I would ask if I could use these pins (GPIO7 and GPIO8) as SDA and SCL.

No, you can't. Those pins are used by the internal flash chip. If you connect things to them you will end up not being able to read the flash and thus won't be able to run any code.  In other words, the chip will not boot. So you will have to bite the bullet and cut traces and add bodge wires.

> Wire.begin (7,8)?

Yes. That will control the bus matrix to route the I2C through different pins - but of course you can't use those pins, as noted above.

> On the arduino side I wrote:
>
> digitalWrite(SDA, 0); digitalWrite(SCL, 0);
>
> It is correct to do the same thing on the ESP32 side?

No. That exploits a quirk in the AVR GPIO system that doesn't exist in the ESP32. In the ESP32 the pins are configured with:

    pinMode(sda, OPEN_DRAIN | PULLUP | INPUT | OUTPUT );

and

    pinMode(scl, INPUT | PULLUP);

so you could *try* replicating that in your code but without the `PULLUP` flag. However the effect of this is unknown, so YMMV.

However, if your external pullups are pulling up to 3.3V then you really don't need to do anything on the ESP32. All you end up with is a large resistance in parallel with your 4.7kΩ, which will just cause your resistance to drop slightly (and since 4.7kΩ is arguably too high any way that's a good thing).


body:
When does the ISR mapped to SPI_STC_vect (SPI transmission complete) get fired? Does it fire after a byte has been received (eight clock cycles) of when the slave select changes back to high to deselect the slave?
Or: does "transmission" mean the transmission of a byte or the whole bunch of bytes that belong to the command sequence?

title: When does interrupt get fired

Answers: 1

body: It fires after a single byte has been sent or received (the two are one and the same). This is because there is only room for one byte in the buffer, so you need to get it out of that buffer (or put a new one in) after each 8-bit transfer.


body:
Being clear I'm **not talking about** **How to flash ESP8266 using arduino**.
I want to ask **how can I use atmega328p as flash with esp8266** (instead of that 8 pin small chip on ESP-01) so that I can burn Webserver code on Atmega328p and it simply works with esp8266?

Thanks in advance.

title: Esp8266 + Atmega328p as flash

Answers: 1

body:
It can't be done (also, why would you think that would ever be a good idea?!)

The 8 pin chip on the ESP-01 is a 512kB SPI flash that runs at (at least) 40MHz.  So to emulate that you would need:

* More than 512kB of flash,
* A slave SPI interface that can operate at a minimum of 40MHz, and
* The knowledge, time and energy to write the firmware to emulate an SPI flash chip

The first two are certainly beyond an ATMega328P with 32kB flash and an 8MHz maximum speed SPI interface. The third is probably beyond you since you have to ask the question in the first place (which shows a certain lack of knowledge on what it is you are proposing).

There are plenty of examples for creating a web server using an ESP8266 using either the standard AT firmware or by directly programming the ESP8266's flash chip through the ESP8266's built-in UART bootloader.  Personally I find the use of AT firmware clumsy at best and prefer to always program my ESP8266's directly.  If you feel the need to also add an ATMega328P into the mix for some reason then the communication protocol that you use between them is entirely up to you.


body:
I have NodeMCU v3 with ESP8266 and I am running small project where I am measuring the input from IR phototransistor via ADC pin (A0) and everything is working flawlessly.
But now I want to transfer it to battery source (powerbank -> microUSB) and I want to be able to tell the remaining battery capacity, but all tutorials I found were going through switching ADC(A0) to internal, thus disabling it.
Is there any other way I can either measure the battery OR input from phototransistor?
Thanks!

title: Measuring Battery level with ADC already in use

Answers: 1

body:
As @dandavis rightly says in the comments, you can't measure the battery voltage from a power bank.  This is because the power bank typically includes a step-up converter to turn the batter voltage (3.2 to 4V) into a stable 5V.  That 5V will alwaye be 5V (or thereabouts) until the battery runs out and the power bank shuts itself off.

To measure the battery state you will have to directly interface with the batteries (disassemble the power bank) and tap into the battery terminals themselves.

Some power banks also have LEDs in them to display the power remaining. It could be possible to interface directly with these as well.

One thing to note, though, is that using a power bank for an ESP8266 board is pretty silly.  You are taking nominal 3.6V, stepping it up to 5V, then linearly dropping it back down to 3.3V again.  Both stages involve power wastage - the 5V to 3.3V most of all (a linear regulator turns the waste voltage into heat).

You would be better removing the batteries from the power bank and wiring them directly to the power input - or better still, feed them through a high efficiency switching regulator to get a stable 3.3V and feed that directly into the 3.3V pin.  be sure to include some way of monitoring the battery voltage and shutting off the power when it gets too low. Since your ADC input is already in use the simplest way is to add an external ADC chip to your design.


body:
I am trying to play a song using arduino while at the same time display time using a rtc board using the tmrpcm library. However, if the rtc board is connected no sound is played.

I do understand that the tmrpcm may be interfering with the wire.h library but even commenting the same doesn't resolve the problem.

I am using the following code:

~~~
// Date and time functions using a DS1307 RTC connected via I2C and Wire lib
#include <RTClib.h>
#include<Wire.h>
#include <Arduino.h>
#include "SevenSegmentTM1637.h"
#include "SevenSegmentExtended.h"
#include "SevenSegmentFun.h"
#include "SD.h"
#define SD_ChipSelectPin 4
#include "TMRpcm.h"
#include "SPI.h"

TMRpcm tmrpcm;

const int ProxSensor=3;
int inputVal = 0;
#define CLK 8
#define DIO 7

// The amount of time (in milliseconds) between tests
#define TEST_DELAY   2000

SevenSegmentFun    display(CLK, DIO);

RTC_DS1307 rtc;

char daysOfTheWeek[7][12] = {"Sunday", "Monday", "Tuesday", "Wednesday", "Thursday", "Friday", "Saturday"};

void setup () {
  Serial.begin(9600);
  if(!SD.begin(SD_ChipSelectPin))
  {
    Serial.println("SD fail");
    return;
  }
  while (!Serial); // for Leonardo/Micro/Zero
  tmrpcm.speakerPin=9;
  Serial.begin(57600);
  if (! rtc.begin()) {
    Serial.println("Couldn't find RTC");
    while (1);
  }

  if (! rtc.isrunning()) {
    Serial.println("RTC is NOT running!");
    // following line sets the RTC to the date & time this sketch was compiled
    rtc.adjust(DateTime(2019, 10, 19, 01,41,00));
    // This line sets the RTC with an explicit date & time, for example to set
    // January 21, 2014 at 3am you would call:
    // rtc.adjust(DateTime(2014, 1, 21, 3, 0, 0));
  }
  pinMode(ProxSensor,INPUT);    //Pin 2 is connected to the output of proximity sensor
  display.begin();
}

void loop(){
  DateTime now = rtc.now();
  display.print((now.unixtime() / 86400L )-17963);
  Serial.print((now.unixtime() / 86400L )-17963);
  while(digitalRead(ProxSensor)==LOW)      //Check the sensor output
  {
    tmrpcm.setVolume(5);
    tmrpcm.play("test.wav");
      repeat:
    if(digitalRead(ProxSensor==LOW))
      goto repeat;
  }
}
~~~

Can anyone please help me?

title: Audio stops playing after rtc is connected

Answers: 2

body: The TMRpcm and one of your other libraries might use the same timer on Uno which causes one of them to break. Either get a Arduino Mega which can run TMRpcm on TIMER3,4 or 5 or use libraries that don't require a timer.

body:
The problem is

    repeat:
    if(digitalRead(ProxSensor==LOW))
      goto repeat;

`ProxSensor==LOW` is false so 0. **you read the pin 0** and the outcome is random. The surrounding wiring can affect that. If digitalRead(0) is zero the wav starts playing immediately again. At least use

    while (digitalRead(ProxSensor) == LOW);


body:
---> I am trying to create a controller using Arduino Uno that simply detects pulses from a waveform generator mimicking a Laser Machine and then switches between 4 state machines states at the output of a Pre-amp, it is a built on of this [previous post][1] so the connections are the same except for the waveform generator settings. The new waveform generator settings are :

**Type: Pulse, Freq:20Hz (50ms), Amp:5.0 Vpp, Offset:0V, Width = 100ns**

---> I am trying to add 5 things in the project so any input is greatly appreciated:

  1) **Initialize** all the **4 state machine states** into an **Array** so user can define as many states as they want from the declarations.

  2) **ADD a digital** de-bounce to the input pin, **LASER_PIN**.

  3)(requires item #5 to be done first)  **ADD a reset** to the system which moves the program back to **STATE_00**  from whatever it is doing.

  4) Better code to wait until a pulse from Laser arrives before going to the state machine in **void loop()**.

  5) (item #2 depends on this) Completely **Remove** delay from the **CountPulses()** function and replace with **millis()** function to allow the use of reset button

---> Here is what i have so far, i started off by adding 4 state machine states and using the **delay()** function in the **CountPulses()** function just like in the previous post and it works fine and i am able to switch states while counting pulses, however, when i added the **millis() to replace delay()** function as shown below in the code, **i only get** **0s** in pulse count and the state machine is **stuck** in **STATE_00** so i used a couple of print statements to debug  and it turns out currentmillis() - startmillis() is actually less than period = 1000ms so i am stuck on how to set this up and without this i cannot move forward, any help would be appreciated. My code and serial monitor results are shown below:

--> **UPDATE**: items #3 and #5 work perfectly fine , please see updated code. for item #4 i have not figured this one out yet. for item #2 ,there are a lot of libraries for debounce but not sure which libraries (Button, Bounce and etc) are most trusted by arduino community, any suggestions would help.

-->**UPDATE 2:** The code has been update with the following changes, external interrupts are used to reset the system if switch is LOW, Polling with interrupts is used to wait for pulses.

**THE UPDATE TO QUESTION**: items#3, 4 and 5 were solved and now only 2 items remain to be added to the project with modifications to item #1 and item #2 based on comments:

1) I require the state machine to do the following:

 a) Declared in an array where user can easily change the order of execution of states. (eg: state_2--> state_1 -->state_3--> state_0).

  b) User can easily decrease the number of states from MAX_VALUE = 4 to only 1 state. (eg with MAX_VALUE = 3: state_0--> state_1--> state_2)  .

2) **ADD a digital** de-bounce to the input pin, **RESET_PIN**.
Note: The debounce to LASER_PIN was a mistake in understanding based on the comments, so i have updated this.

Updated code with current serial monitor results is shown below:

           //Objectives: Use input from laser to control pre-amp on adc. Multiplex the inputs on Pre-Amp
    //Date:10/21/2019
    //Type: Pulse, Freq:20Hz (50ms), Amp:5.0 Vpp, Offset:500mV, Width = 100ns

    //-----------------------PROJECT LIBRARIES----------------------------------
    #include <Bounce2.h>
    #include <Arduino.h>
    #include <avr/io.h>
    #include <avr/wdt.h>
    #include <avr/interrupt.h>
    //-----------------------DEFINES------------------------------------------
    //Declare Laser Input Pin
    #define LASER_PIN 2

    //Declare Reset Pin
    #define RESET_PIN 3

    //Define the states of the machine
    typedef enum {STATE_00, STATE_01, STATE_10, STATE_11} fsm_state_type;
    fsm_state_type fsm_state = STATE_00;

    // -------------------------CONSTANTS (won't change)-------------------------------------
    const unsigned long period = 1000;  //the value is a number of milliseconds

    //-------------------------VARIABLES (will change)-------------------------------------
    bool only_for_print = false;//used only for print state ments

    int reset_switch = 1;//Start HIGH to avoid reset
    int PulseCount = 0; //Pulse count from X-RAY
    int Output = 0;//Switch state on the Pre-Amp
    int wait = 0;//wait for pulses count
    int N = 20;//no. of pulses to count before switching states
    volatile int IRQcount = 0;
    volatile boolean reset_flag = false;

    unsigned long start_time = 0;
    unsigned long current_time = 0;

    //----------------------------USER DEFINED FUNCTIONS---------------------------------
    void fsm();
    void loop();
    void setup();
    void WDT_RESET();
    void IRQcounter();
    void CountPulses();
    //-----------------------------DEBOUNCE FUNCTIONS---------------------------------------

    //--------------------------------MAIN SETUP--------------------------------------

    void setup()
    {

      Serial.begin(115200);

      //Pin Setup
      pinMode(LASER_PIN, INPUT_PULLUP);
      pinMode(RESET_PIN, INPUT_PULLUP);
      attachInterrupt(digitalPinToInterrupt(LASER_PIN), IRQcounter, RISING);//attach interrupt handler to laser input
      attachInterrupt (digitalPinToInterrupt (RESET_PIN), RESET_ISR, FALLING);  // attach interrupt handler to reset, wait for user press button or switch
      start_time = millis();   //initial start time
      sei();//Turn on Interrupts

        WaitForPulses();//Waits to detect 20 pulses
    }

    //--------------------------------MAIN LOOP----------------------------------
    void loop()
    {

     current_time = millis();
     fsm();//State machine
    }

    //--------------------------------PULSE COUNT FUNCTION--------------------------------------------

    void CountPulses()
    {
      //  current_time = millis();
      if ((current_time - start_time) >= period)
      {
        start_time = current_time;
        cli();//disable interrupts
        PulseCount = IRQcount;
        IRQcount = 0;
        Serial.print(F("Pulse Count is = "));
        Serial.println(PulseCount);
        sei();//enable interrupts
      }
    }

    //--------------------------------STATE MACHINE FUNCTION--------------------------------------------
    void fsm()
    {
      switch (fsm_state)
      {

        case STATE_00:

    /////////Print Statement only for debugging//////////
            while (only_for_print == false)
            {
                Serial.println("The state is 00");
                only_for_print = true;
            }

    ///////// Count Pulses Setup /////////////////
                current_time = millis();
                CountPulses();
                Output = 0;
                if (PulseCount == N)
                {
                  PulseCount = 0;//Reset Pulse Count
                  only_for_print = false; //used only for print statments
                  fsm_state = STATE_01;//switch to next state
                }
          break;

        case STATE_01:
    /////////Print Statement only for debugging//////////
          while (only_for_print == false)
          {
              Serial.println("The state is 01");
              only_for_print = true;
          }

    ///////// Count Pulses Setup /////////////////
              current_time = millis();
              CountPulses();
              Output = 2;
              if (PulseCount == N)
              {
                PulseCount = 0;//Reset Pulse Count
                only_for_print = false; //used only for print statments
                fsm_state = STATE_10;//switch to next state
              }
          break;

        case STATE_10:
    /////////Print Statement only for debugging//////////
          while (only_for_print == false)
          {
              Serial.println("The state is 10");
              only_for_print = true;
          }

    ///////// Count Pulses Setup /////////////////
              current_time = millis();
              CountPulses();
              Output = 3;
              if (PulseCount == N)
              {
                PulseCount = 0;//Reset Pulse Count
                only_for_print = false; //used only for print statments
                fsm_state = STATE_11;//switch to next state
              }

          break;

        case STATE_11:
    /////////Print Statement only for debugging//////////
          while (only_for_print == false)
          {
              Serial.println("The state is 11");
              only_for_print = true;
          }
    ///////// Count Pulses Setup /////////////////
              current_time = millis();
              CountPulses();
              Output = 4;
              if (PulseCount == N)
              {
                PulseCount = 0;//Reset Pulse Count
                only_for_print = false; //used only for print statments
                fsm_state = STATE_00;//switch to next state
              }

          break;

        default:
          fsm_state = STATE_00;
          break;
      }

    }

    //----------------------------------RESET SWITCH ISR-------------------------------------

    void RESET_ISR()
    {
      reset_flag = true;
      if(reset_flag == true)
        {
         // Serial.println("System will now Reset");// Only for debugging
          reset_flag = false;//Reset reset switch flag
          wdt_enable(WDTO_500MS);//Reset after 0.5 seconds
          while (1)
           {
             // wdt_reset();          // uncomment to avoid reboot
           }
        }
    }

    //-----------------------PULSE COUNT ISR---------------------------------------

    void IRQcounter()
    {
      IRQcount++;
    }
    //-----------------------WAIT FOR PULSES---------------------------------------
    void WaitForPulses()
    {
      while(wait<20)
     {
        if (bit_is_set(EIFR, INTF0))
        {
          Serial.println("Pulse is detected ");
          wait++;
        }
     }
     wait = 0;//reset
    }
    */

[![edited image][3]][3]

  [1]: https://electronics.stackexchange.com/questions/464324/counting-pulses-using-arduino-uno/464357?noredirect=1#comment1171115_464357
The serial monitor is shown below with added reset switch on pin 3 using watch dog timer library .

     Pulse is detected
    Pulse is detected
    Pulse is detected
    Pulse is detected
    Pulse is detected
    Pulse is detected
    Pulse is detected
    Pulse is detected
    Pulse is detected
    Pulse is detected
    Pulse is detected
    Pulse is detected
    Pulse is detected
    Pulse is detected
    Pulse is detected
    Pulse is detected
    Pulse is detected
    Pulse is detected
    Pulse is detected
    Pulse is detected
    The state is 00
    Pulse Count is = 112
    Pulse Count is = 20
    The state is 01
    Pulse Count is = 20
    The state is 10
    Pulse Count is = 20
    The state is 11
    Pulse Count is = 20
    The state is 00
    Pulse Count is = 20
    The state is 01
    Pulse Count is = 20
    The state is 10
    Pulse Count is = 20
    The state is 11
    Pulse Count is = 20
    The state is 00
    Pulse Count is = 20
    The state is 01
    Pulse Count is = 20
    The state is 10
    Pulse Count is = 20
    The state is 11
    Pulse Count is = 20
    The state is 00
    Pulse Count is = 20
    The state is 01
    Pulse Count is = 20
    The state is 10
    Pulse Count is = 20
    The state is 11
    Pulse Count is = 20

title: Laser Controller using Arduino Uno

Answers: 1

body:
### Important note:

*After reading (again) your other question and its answers: **You are stressing the input of your Arduino with negative voltages!** Please set the offset of the signal to 2.5V (the middle between GND and VCC) and the amplitude to 5Vpp. **The signal must neither be lower than GND nor higher than VCC!** The input might withstand this for a while but given enough time and power it **will** get damaged.*

### Analysis of your problem:

**1. The measurement of the period**

Let's take a look at a "condensed" version of your time code:

    void setup()
    {
      startMillis = millis();
    }

    void loop()
    {
      currentMillis = millis();
      if (currentMillis - startMillis <= period)
      {
        startMillis = currentMillis;
      }
    }

I'm sure you see it now, too! Because right at the first call of `loop()` the time passed since `setup()` is short, the condition is `true` and `startMillis` is updated to the current time. This is repeated ever and ever again. The condition will always evaluate as `true`.

**2. The number of pulses**

In the function `CountPulses()` the counter is reset at the beginning. Then after some undefined very short duration (because your `if`-condition is always `true`) it is read. Chances are low for a pulse to be counted in that time span.

### Additional note:

Just one more tip. You can define and use your own data types to show your intentions. For example the states look so much better like shown below, and you'll get free error messages from code analyzers.

    typedef enum {
        STATE_00, STATE_01, STATE_10, STATE_11,
    } fsm_state_type;
    fsm_state_type fsm_state = STATE_00;

**EDIT after you added new informations:**

### Item #2

Why do you think you need to debounce the laser pulse? Is it generated by a mechanical switch? Only those need debouncing. If the pulses are generated from some electronic circuit they should be clean.

### Item #4

You can reset the `IRQcount` and then wait for it to count up.

But as this involves disabling and enabling the interrupt and reading an `int` just for **1 event**, I'd rather set a flag if the interrupt occurs. Then the FSM could wait for the flag to be set.

Another alternative is to poll the input pin directly and to wait for the leading edge. But for this the pulse has to be wide enough.

As @EdgarBonet pointed out it will be even simpler to poll the interrupt flag. But IIRC the interrupt has to be disabled for this, else the call of the interrupt service routine will clear the flag with no chance for the main program to see it.

> A better alternative is to poll the interrupt flag (i.e. `if (bit_is_set(EIFR, INTF0)) { ... }`). Then you don't need a wide pulse: once the hardware detects the rising edge, the flag is set and remains set until you explicitly clear it (`EIFR = _BV(INTF0);`).


body:
I’m considering using `wifiManager` mostly to have the ability not to hard code WiFi creditntials.
But In my current code I use WiFi’s functions as `WiFi.setAutoReconnect(true)` and `WiFi.status() != WL_CONNECTED`

How can it be done using `WifiManager`?

title: WifiManager and WiFi functionally

Answers: 2

body:
You don't. WifiManager does all that for you. You don't need anything like that in your code. Just follow the examples and read the documentation.

But if you do want to then you just need to remember that WifiManager is merely a library that configures the WiFi for you. If you want to query or alter the WiFi settings you can - exactly as you are right now. The two aren't mutually exclusive.

body:
Here's a working example that's on my Wemos D1 Mini. It stands up an AP until you provide credentials for your local LAN, then displays it's DHCP IP address on a 16x2 LCD and stands up a webserver. Once the credentials are stored it won't stand up the AP, it will just reconnect and do the main loop() of the sketch. To force the AP to restart you need to call the `ESP.reset();` method to flush the stored credentials and reboot the Wemos.

    #include <LiquidCrystal_PCF8574.h>
    #include <ESP8266WiFi.h>

    #include <WiFiManager.h>
    #include <ESP8266WebServer.h>
    #include <Wire.h>

    WiFiClient wemosCL;

    ESP8266WebServer server(80);

    const int led = LED_BUILTIN;

    LiquidCrystal_PCF8574 lcd(0x38);

    void handleRoot() {
      digitalWrite(led, 1);
      server.send(200, "text/html", "<title>ESP8266 Demo</title>
Hello from ESP8266!

IP Addr: " +
              WiFi.localIP().toString() + "
");

      digitalWrite(led, 0);
    }

    void handleNotFound() {
      digitalWrite(led, 1);
      String message = "File Not Found\n\n";
      message += "URI: ";
      message += server.uri();
      message += "\nMethod: ";
      message += (server.method() == HTTP_GET) ? "GET" : "POST";
      message += "\nArguments: ";
      message += server.args();
      message += "\n";
      for (uint8_t i = 0; i < server.args(); i++) {
        message += " " + server.argName(i) + ": " + server.arg(i) + "\n";
      }
      server.send(404, "text/plain", message);
      digitalWrite(led, 0);
    }

    void setup(void) {
      Serial.begin(115200);
      WiFiManager wifiManager;
      wifiManager.autoConnect("Wemos", "configuration");
      pinMode(led, OUTPUT);
      digitalWrite(led, 0);

      lcd.begin(16, 2);
      lcd.setBacklight(255);
      lcd.print("I'm alive");

      // Wait for connection
      while (WiFi.status() != WL_CONNECTED) {
        delay(500);
        lcd.setCursor(0, 0);
        lcd.print(".");
      }

      lcd.clear();
      lcd.setCursor(0, 0);
      lcd.print("Status:Connected");
      lcd.setCursor(0, 1);
      lcd.print("IP:");
      lcd.print(WiFi.localIP());

      server.on("/", handleRoot);

      server.onNotFound(handleNotFound);

      server.begin();
    }

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


body:
![enter image description here](https://i.stack.imgur.com/5rqjG.jpg)![enter image description here](https://i.stack.imgur.com/zi6mJ.jpg)

Hello sir , so can i cut the switch from the picture and connect the wires to my relay module ? Im sorry because im still learning . Thank you !

title: 5v relay module and bulb holder

Answers: 2

body:
A relay is nothing more than a switch - but instead of your finger controlling it, it's controlled by an electromagnet.

The relay can perform the exact same function as the switch on that cable.  In the image you have posted you would use the right-hand two screw terminals (middle is "common", right is "normally open") to replace the switch.

body:
You can refer to this to cut the switch [![enter image description here][1]][1]

If you are a beginner, you can [get started with Relay here][2]

NOTE: It's dangerous and can cost your life. Please be careful when using Relay with 220 VAC

  [1]: https://i.stack.imgur.com/0vPDz.jpg
  [2]: https://arduinogetstarted.com/tutorials/arduino-relay


body: I am thinking about trying to make an Arduino synthesizer using the true analog output on the Due. However I would like to be able to play multiple notes at the same time on a single buzzer. Is this possible and how would I do it?

title: Creating and Arduino synthesizer without the tone library

Answers: 2

body:
Sound is nothing else than a multiple simple waves combined in to one. So, theoretically you can play as many sounds (tones) as you like on a single pin. If you want to go true analog than you probably want to use a sin wave to generate sound. However, in that case you can do the following:
Either make a function that would be capable of generating a sin wave of your desired frequency. In case of true analog this would probably be done by calculating actual sin values and using the [map()][1] function mapping 0 - 1 to 0 - 1024 and writing to the pin. The frequency can be adjusted by changing the delay between each step of changing the voltage or [DAC][2] value. However, this will not allow for multiple frequencies.
Alternatively for multiple frequencies to be played at the same time you would need to calculate the [Fourier inversion][3] of all the waves you want to play and send the results of that to the [DAC][2].

  [1]: https://www.arduino.cc/reference/en/language/functions/math/map/
  [2]: https://en.wikipedia.org/wiki/Digital-to-analog_converter
  [3]: https://en.wikipedia.org/wiki/Fourier_inversion_theorem

body:
You just have to add the waveforms. For example, if you want to play
pure tones (the simplest and most boring timbre), you generate a sine
wave for each of them and add them together:

```c++
struct Note {
    float frequency;
    float phase;
    bool is_active;
} notes[MAX_NOTES];

void output_sample()
{
    static uint32_t previous_time;
    uint32_t now = micros();
    uint32_t elapsed_time = now - previous_time;
    previous_time = now;
    float output = 0;
    for (int i = 0; i < MAX_NOTES; i++) {
        Note *note = &notes[i];
        if (note->is_active) {
            output += cos(note->phase);
            note->phase += 2*M_PI*note->frequency*1e-6*elapsed_time;
            if (note->phase >= 2*M_PI) {
                note->phase -= 2*M_PI;
            }
        }
    }
    analogWrite(DAC_PIN, 2048 + round(output * (2047.0 / MAX_NOTES)));
}
```

The function `output_sample()` should be called as frequently as
possible. You can change the `notes` array any time to add, remove or
change notes.

There is some room for optimization here, like:

* storing `2*M_PI*note->frequency*1e-6` as the “frequency” in order to
  save some calculations

* using a wave table instead of the `cos()` function (I don't know how
  good is the Due at transcendental math)

* replacing `elapsed_time` by a constant if you can manage to output the
  samples at a fixed rate.

------------------------------------------------------------------------

**Edit**: I wrote “You can change the `notes` array any time to add,
remove or change notes.” Here is how to start or stop a note, i.e. to
add or remove it from the list of active notes:

```c++
// Start a note. Returns an index to be used with stop_note(), or -1 if
// we couldn't start the note because we are already outputting the
// maximum number of simultaneous notes.
int start_note(float frequency)
{
    int i;  // index of the note in the notes[] array

    // Find a free slot in the array.
    for (i = 0; i < MAX_NOTES; i++)
        if (!notes[i].is_active) break;  // found

    // Couldn't find a free slot?
    if (i == MAX_NOTES) return -1;

    // Setup the note parameters.
    notes[i].frequency = frequency;
    notes[i].phase = 0;
    notes[i].is_active = true;
    return i;
}

// Stop the note with the given index.
void stop_note(int index)
{
    if (index >=0 && index < MAX_NOTES)
        notes[index].is_active = false;
}
```


body:
I want to take the GPS coordinates like **42.1234** per **22.1234** and merge them as a string, with a separator character:

`42.1234 x 22.1234`

But using this code:

`gps_string = (String)gps.location.lat()+' x '+(String)gps.location.lng();`

I lose the last decimals and I get:

`42.12 x 22.12`

The only way I could see full coordinates is by specifying an extra parameter to println, like this:

`Serial.println(gps.location.lat(), 6);`

How can I create a string containing both two coordinates without losing decimals ? e.g `42.1234 x 22.1234`

title: How to merge two GPS coordinates without losing decimals

Answers: 1

body:
If you want 4 decimal places, you may try something like this:

```c++
gps_string = String(gps.location.lat(), 4)
           + " x "
           + String(gps.location.lng(), 4);
```


body:
I'm really new to coding and Arduino so I would be eternally grateful for the help.

I'm trying to make a really basic flame sensor that beeps, lights up an LED and displays the distance from the sensor to the flame when activated. I keep getting a "'Serial' does not name a type" error message for the line that reads - Serial.println(analogRead(A0));

I’ve tried to figure it out from the information on this forum of similar questions to try to correct the issue but it seems like every time I fix one thing another 2 errors come up. I’ve been stuck on this one for a little while so I’m hoping I might be able to receive some kind of assistance from the Arduino community.

Below is the entire code - any help is appreciated, thanks :)

    int Led = 4;
    int Buzz = 7;
    int Sensor = 11;
    int Fire = HIGH;
    void setup()
    { Serial.begin(9600);
    pinMode(Buzz,OUTPUT);
    pinMode(Sensor,INPUT);
    pinMode(Led,OUTPUT);
    }
    void loop()
    {
    Fire = digitalRead(Sensor);
    if(Fire == HIGH);
    Serial.print("analog Read = ");
    Serial.print(analogRead);
    }
    Serial.println("HELP! A FIRE!");
    digitalWrite(Buzz,HIGH);
    digitalWrite(Led,HIGH);
    delay(200);
    digitalWrite(Led,LOW);
    delay(200);
    Serial.println(analogRead(A0));
    }
    else
    {
    Serial.println("No fire detected");
    digitalWrite(Buzz,LOW);
    digitalWrite(Led,LOW);
    }
    delay(500);
    }

title: Serial.println Issue with Flame Sensor

Answers: 1

body:
First things first; please INDENT YOUR CODE. The code you posted is a mess and I took at least double the time to fix that.

First, you have an extra closing curly bracket at line 17 and the `if (Fire == High);` should be changed to `if (Fire == High){`

Fixed code:
~~~
int Led = 4;
int Buzz = 7;
int Sensor = 11;
int Fire = HIGH;
void setup()
{
  Serial.begin(9600);
  pinMode(Buzz,OUTPUT);
  pinMode(Sensor,INPUT);
  pinMode(Led,OUTPUT);
}
void loop()
{
  Fire = digitalRead(Sensor);
  if(Fire == HIGH){
//Serial.print("analog Read = ");
//Serial.print(analogRead);
    Serial.println("HELP! A FIRE!");
    digitalWrite(Buzz,HIGH);
    digitalWrite(Led,HIGH);
    delay(200);
    digitalWrite(Led,LOW);
    delay(200);
    Serial.println(analogRead(A0));
 }
 else
 {
    Serial.println("No fire detected");
    digitalWrite(Buzz,LOW);
    digitalWrite(Led,LOW);
  }
  delay(500);
}
~~~


body:
Can anyone provide a sample code that would convert a human readable date like `2019-10-27 22:10:35` to a unix timestamp like `1572214235`?

I found many topics about it, but they eider refer to out of date libraries, or they seem to address more complex time functions, I find it hard to extract this functionality from them.

title: Converting human readable date to a unix timestamp

Answers: 2

body:
If you have a fixed format you can use `strtok()` to slice the string into individual segments, then convert those segments to integers. They can then be used with `TimeLib.h` with the `setTime()` function.  You can then query TimeLib for the unix timestamp with `now()`.

**Edit:** using [PaulStoffregen's TimeLib][1], this code sets current time and returns current unix timestamp.

```C++
#include <TimeLib.h>

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

  // hour, min, sec, day, month, year
  setTime(22, 30, 11, 29, 3, 2019);

  // 1553898611
  Serial.println(now());
}
void loop() {}
```

**Edit 2:** And to convert **any** given date to a unix timestamp (without setting current time):

```C++
#include "TimeLib.h"

tmElements_t my_time;  // time elements structure
time_t unix_timestamp; // a timestamp

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

  // convert a date and time into unix time, offset 1970
  my_time.Second = 0;
  my_time.Hour = 23;
  my_time.Minute = 0;
  my_time.Day = 25;
  my_time.Month = 3 - 1;      // months start from 0, so deduct 1
  my_time.Year = 2017 - 1970; // years since 1970, so deduct 1970

  unix_timestamp =  makeTime(my_time);
  Serial.println(unix_timestamp);
}

void loop() {}
```

  [1]: https://github.com/PaulStoffregen/Time

body:
After parsing the time into numbers, you can use the standard C time library `time.h`. More specifically, use the `mktime` [function][1] to convert a `struct tm` into a `time_t`, and use `difftime` to get the seconds since the start of the Unix expoch:

    #include <time.h>

    void loop() {
        struct tm ltm = {0};
        ltm.tm_year = 2019 - 1900;
        ltm.tm_mon  = 11 - 1;
        ltm.tm_mday = 5;

        int32_t epoch_seconds = difftime(mktime(&ltm), (time_t)0);
        Serial.print("Remember, remember, ");
        Serial.print(epoch_seconds);
    }

Note that in `struct tm`, the year starts at 1900 and the month starts at 0.

  [1]: https://en.cppreference.com/w/c/chrono/mktime

EDIT: In avr-libc, `difftime` returns an `int32_t`, not a `double`.


body:
I'm using the [FastLED][1] library to control a digital RGB LED strip.

While this library seems very comprehensive in capability and ease of use, I do not yet see a way to simply set the brightness value of a *individual* pixel on an *absolute scale*. In other words, I want to simply set the brightness of a pixel, without passing a hue or saturation, and without it effecting other pixels.

`FastLED.setBrightness()` scales down the brightness of all pixels.
`leds[i].fadeLightBy()` scales down an individual pixel, but if it's called again for the same pixel before updating the LEDs, then the pixel will be faded again from it's already-faded value.

Is there truly no built-in method for setting the brightness of individual pixels to a particular value?

  [1]: https://github.com/FastLED/FastLED/wiki/Pixel-reference

title: FastLED library: How can I adjust the brightness of a single pixel on an absolute scale?

Answers: 1

body:
There is no dedicated function to adjust brightness.

You can (however) do this by using the HSV color model.

**Breaking HSV (Anachronism) into Parts:**

**H** (Hue) Controls the Color itself.

**S** (Saturation) of the Color.

**V** is called Lightness or Value.

**'V'** is what you want to control.

Just set the LEDs color to a HSV value and change it's V value.

    leds[i] = HSV(color, saturation, brightness);

While 'Color' and Saturation' remain the same (to keep the same color), you can change the 'Brightness' directly on the third parameter.

Note that 'leds[i]' is still defined as 'CRGB', not as 'HSV'.

This assignment uses an implicit conversion, that is defined in the library.

You can see the 'HSV' usage example within the 'Cylon' example on the FastLED library.

There you will find the Hue value that gets changed; but it is the same principle as 'brightness'.

Now there is a problem to solve.

The FastLED library can convert 'HSV' Colors to 'RGB' Colors; but not the other way round.

So you cannot simply get the 'hue' and Saturation from an 'RGB' Color with this library.

**You have 2 Alternatives:**

**1.** You can just define an extra LEDs array with HSV colors and synchronize both arrays to contain the same data (everytime you want to change a color, you would set a 'HSV' color in the second array, convert that array to 'RGB' by using 'CRGB(hsv_leds[i])' and save that in the first array, which get's used by the FastLED library).

This is relatively easy, but you effectively need double the memory for storing the color values.

This is not an issue, if you have enough memory or few enough LEDs to control.

**2.** You can write your own function to convert 'RGB' values to 'HSV'; then use it to access the 'hue' and 'Saturation' values for the targeted 'RGB' Color, create a new 'HSV' Color with it and the new 'Brightness' and use it to set the 'RGB' values for the FastLED library.

In [this forum thread][1] there is a brief discussion about that, though it leaves you with the implementation yourself.

I think there are suitable implementations, that can be found on the web.

A quick search gave me [this code][2] from github gist.
I have not tested it, so I cannot say, if it really works correctly, but you should give it a try.
I'm sure there are also other implementations.

  [1]: https://forum.arduino.cc/index.php?topic=493488.0
  [2]: https://gist.github.com/fairlight1337/4935ae72bcbcc1ba5c72