body:
I have this code, which puts the Arduino into CTC mode with interrupts, and outputs a square wave on `PD6` (`OC0A`):

    void setup_timer(double p_ms, double duty){
      DDRD |= (1 << 6);  // set pin 3 as output
      TCCR0A = _BV(COM0A0); // toggle OC0A on Compare Match
      TCCR0B = _BV(WGM01); // set CTC mode WGM0[2,1,0] = 0b010
      TIMSK0 |= _BV(OCIE0A); // Enable CTC interrupt
      OCR0A = 128;  // set on and off time
      TCCR0B |= ( (0 << CS02) | (0 << CS01) | ( 1 << CS00)); // CS02:0 - No prescaling
      sei();
    }

In the `ISR` (which is not shown) I want to be able to see whether `OC0A` (i.e. `PD6`) is `HIGH` or `LOW`.

I assumed that I could do a `digitalRead()`, but this post, [Re: How to read the state of an output pin ?][1] says:

> Looking at the code the digitalRead() function just does a read of the appropriate bit in the appropriate PINx register without modifying anything, so it should work.
>
>One catch, if it's a PWM pin the PWM will be stopped.

So, will the toggling of `OCR0A` be stopped?

[This answer][2] to [How can I digitalRead a pin that is in pinMode OUTPUT?][3] suggests reading PORTD directly, with

    bitRead(PORTD,6);

However, will that work for PWM output or will PWM also be stopped by reading `PORTD`?

-------

### Addendum

I plan to use this code either as (primarily) a stand alone AVR µController (48/88/168/328 IC), but maybe in a Nano/Uno (if it will work) for *testing purposes*. I understand that using `Timer0` will affect the operation of `millis()`, `delay()` etc., but the rest of the code will not rely on any of those functions... so I presume (maybe incorrectly) that the code will work as expected. Is that correct?

In addition, I don't intend on using a `setup()` & `loop()` program structure but rather `main()`. Just out of interest, would `loop()` work (i.e. is it reliant on `Timer0`)? I don't believe that it is.

  [1]: https://forum.arduino.cc/index.php?topic=102716.0
  [2]: https://stackoverflow.com/questions/6160963/how-can-i-digitalread-a-pin-that-is-in-pinmode-output#answer-6171551
  [3]: https://stackoverflow.com/questions/6160963/how-can-i-digitalread-a-pin-that-is-in-pinmode-output

title: How to read OC0A when in CTC (toggle) mode?

Answers: 2

body:
If you look into the Arduino Core, you'll find this code for the digital read:

<!-- language: c++ -->

    int digitalRead(uint8_t pin)
    {
     uint8_t timer = digitalPinToTimer(pin);
     uint8_t bit = digitalPinToBitMask(pin);
     uint8_t port = digitalPinToPort(pin);

     if (port == NOT_A_PIN) return LOW;

     // If the pin that support PWM output, we need to turn it off
     // before getting a digital reading.
     if (timer != NOT_ON_TIMER) turnOffPWM(timer);

     if (*portInputRegister(port) & bit) return HIGH;
     return LOW;
    }

That means, disabling PWM is just weird feature in `digitalRead`.

For reading `bitRead(PORTB,3);` I'm not so sure if you'll get output value of `OC0A`, it might be different signal line internally. However you'll get logical level on the port pin by reading `bitRead(PINB,3);`.

body:
**Preliminary note**: If you are using any of the ATmega48/88/168/328,
then the OC0A pin is PD6, not PB3.

As four your idea of reading the PORT register (`PORTD`, not `PORTB`),
it won't work either, as that will only tell you what was the last value
that was written to the port with `digitalWrite()`. Here is a schematic
showing how the timer controls the output pin. It's taken from the
ATmega328P datasheet, but the other AVRs of that family behave
identically in this respect:

[![Compare match output unit][1]][1]

As shown in the schematic, the value written to the port comes from a
multiplexer and is controlled either:

- by the PORT flip-flop when the timer is _not_ generating a PWM output
- or the OC0A flip-flop when it is.

Quite importantly, the timer does _not_ write to the PORT register, it
only overrides it.

Thus, it would look like you want to read the OC0A flip-flop in your
ISR. Alas, this schematic also shows that, contrary to the PORT
flip-flop, the OC0A flip-flop is _not_ connected to the data bus. Thus
you cannot read it, and it doesn't even have an address.

What I would recommend is to read the PIN register instead. This won't
tell you what the timer is writing to the port, but what you can read
back. However, unless the pin is loaded well beyond its absolute maximum
rating, what you read back what has been written. There is a small delay
between the write operation and the value been available to read back (a
couple of CPU cycles IIRC), but this is way shorter than the execution
time of an ISR prologue.

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


body:
I happened to be looking through the HardwareSerial.cpp file that contains the functions used for Serial communication for Arduino.  While looking through the HardwareSerial::begin(baud, config) function, I noticed that the ucsra register has its U2X0 bit set.  When I looked through the datasheet, it says that the U2X0 bit is set to start Double Speed Operation.  From what I'm reading, this means that the baud rate is doubled.
I've been using this Arduino on this computer for a while now with no complaints for the baud rate being at an incorrect speed. What is Double Speed Operation?  Why does it seem to be set in the code by default? I attached the code and section in the manual below.

    void HardwareSerial::begin(unsigned long baud, byte config)
    {
      // Try u2x mode first
      uint16_t baud_setting = (F_CPU / 4 / baud - 1) / 2;
      *_ucsra = 1 << U2X0;

      // hardcoded exception for 57600 for compatibility with the bootloader
      // shipped with the Duemilanove and previous boards and the firmware
      // on the 8U2 on the Uno and Mega 2560. Also, The baud_setting cannot
      // be > 4095, so switch back to non-u2x mode if the baud rate is too
      // low.
      if (((F_CPU == 16000000UL) && (baud == 57600)) || (baud_setting >4095))
      {
        *_ucsra = 0;
        baud_setting = (F_CPU / 8 / baud - 1) / 2;
      }

      // assign the baud_setting, a.k.a. ubrr (USART Baud Rate Register)
      *_ubrrh = baud_setting >> 8;
      *_ubrrl = baud_setting;

      _written = false;

      //set the data bits, parity, and stop bits
      #if defined(__AVR_ATmega8__)
        config |= 0x80; // select UCSRC register (shared with UBRRH)
      #endif
      *_ucsrc = config;

      sbi(*_ucsrb, RXEN0);
      sbi(*_ucsrb, TXEN0);
      sbi(*_ucsrb, RXCIE0);
      cbi(*_ucsrb, UDRIE0);
    }

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

  [2]: https://i.stack.imgur.com/W6OUo.png

title: Double Speed Operation for USART on Arduino Mega 2560

Answers: 2

body:
When in double-speed mode, as noted in the manual, fewer samples are used. In Asynchronous serial communication, there is no clock signal, so the clock that keeps the two devices in sync is extrapolated from the data signal. Each end of the communication has it's own clock source (crystal oscillator, ceramic resonator, R-C oscillator, etc.), and you'll rarely find two that are calibrated identically.

The receiver samples the signal at a higher rate than the actual baud rate so that it can better determine where, relative to it's own clock, the data-signal edges go up or down and continually adjusts its offset to compensate for clock drift.

By operating in double-speed mode, the receiver has fewer samples to work with, and so if your transmitter has a clock source that is different enough than the receiver, or is not stable, or you have long or noisy wires or fluctuating temperatures (etc.) then you may experience less stable communication.

If your particular use-case works fine, then stick with it. But if you start to notice errors in communication, the first troubleshooting step would be to disable this mode, since the clock recover is less robust in this mode.

body:
As explained in jose can u c’s answer, in double speed mode the UART has
fewer samples for doing clock and data recovery. But this doesn't help
answering the second question:

> Why does it seem to be set in the code by default?

Double speed mode has also an advantage: it enables higher resolution in
setting the baud rate. In normal mode, the bit duration is constrained
to be a multiple of 16 CPU clock cycles, whereas in double speed
mode it is only constrained to a multiple of 8 cycles.

As an example, let's say you want 57600 bps on a 16 MHz
Arduino. Then,

F\_CPU ÷ desired\_baud\_rate = 277.78 = 8 × 34.72 = 16 × 17.36

In single speed mode, this would be rounded to 16 × 17, and the rounding
error would make the baud rate 2.1% too fast. In double speed mode, it
is rounded to 8 × 35, and the baud rate is only 0.8% too slow. Thus you
get better baud rate accuracy in double speed mode. Note that for some
baud rates, like 9600 bps, single speed and double speed yield the
exact same rate.

This is presumably the reason the Arduino core uses double speed mode,
except for a documented compatibility exception and for extremely low
baud rates (double speed cannot work below 488 bps).

It should be noted that this is not the only possible strategy. The
avr-libc, for example, provides some [helper macros for baud rate
calculations][setbaud]. These macros give preference to single speed
mode and revert to double speed only if the rounding error exceeds a
specified tolerance, which defaults to 2%.

[setbaud]: http://www.nongnu.org/avr-libc/user-manual/group__util__setbaud.html


body:
<!-- language: c++ -->

    #include <ESP8266WiFi.h>

    const char* ssid     =  "Tonosh";
    const char* password =  "a43056043";

    const char* host     =  "192.168.8.107";

    void setup()
    {
      Serial.begin(115200);
      delay(10);

      Serial.println();
      Serial.println();
      Serial.print("Connecting to ");
      Serial.println(ssid);

      WiFi.begin(ssid,password);

      while(WiFi.status() != WL_CONNECTED)
      {
        delay(500);
        Serial.print(".");
      }

      Serial.println("");
      Serial.println("WiFi connected");
      Serial.println("IP Address: ");
      Serial.println(WiFi.localIP());

    }

    int value = 0;

    void loop()
    {
      delay(2000);
      ++value;

      Serial.print("Connecting to ");
      Serial.println(host);

      WiFiClient client;
      const int httpPort = 80;
      if(!client.connect(host,httpPort))
      {
        Serial.println("Connection failed");
        return;
      }

      String url = "http://192.168.8.107/prueba.php";

      String data = "serie=777&temp=33";

      Serial.print("Requesting URL:  ");
      Serial.println(url);

      client.print(String("POST ") + url + "HTTP/1.0 \r\n" +
                   "Host: " + host + "\r\n" +
                   "Accept: *" + "/" + "*\r\n" +
                   "Content-Length: " + data.length() + "\r\n" +
                   "Content-Type: aplication/x-www-form-urlencoded\r\n" +
                   "\r\n" + data
                  );
      delay(10);

      Serial.println("Respond:");

      while(client.available())
      {
        String line = client.readStringUntil('\r');
        Serial.print(line);

        Serial.println("Closing connection");
      }
    }

Any idea? I tried different post here and nothing works.

title: ESP8266 Bad request error 400

Answers: 1

body:
HTTP status code 400 means that your request syntax is invalid.

Here's a good way to debug it: store the request in a string, print that, and then transmit it. You'd see very quickly at least one of the problems your code has.

    String request = String("POST ") + url + "HTTP/1.0 \r\n" +
                     "Host: " + host + "\r\n" +
                     "Accept: *" + "/" + "*\r\n" +
                     "Content-Length: " + data.length() + "\r\n" +
                     "Content-Type: aplication/x-www-form-urlencoded\r\n" +
                     "\r\n" + data;
    Serial.print(request);
    client.print(request);

The request in the POST line needs to be just the pathname and any arguments. You also need a space before `HTTP/1.0`.

So right now you're transmitting:

    POST http://192.168.8.107/prueba.phpHTTP/1.0

when you need to transmit

    POST /prueba.php HTTP/1.0


body:
I have a ESP8266-01 and am trying to get it to work. I am using the example [WiFiScan][1] code shown below.

    #include "ESP8266WiFi.h"

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

      WiFi.mode(WIFI_STA);
      WiFi.disconnect();
      delay(100);

      Serial.println("Setup done");
    }

    void loop() {
      Serial.println("scan start");

      // WiFi.scanNetworks will return the number of networks found
      int n = WiFi.scanNetworks();
      Serial.println("scan done");
      if (n == 0) {
        Serial.println("no networks found");
      } else {
        Serial.print(n);
        Serial.println(" networks found");
        for (int i = 0; i < n; ++i) {
          // Print SSID and RSSI for each network found
          Serial.print(i + 1);
          Serial.print(": ");
          Serial.print(WiFi.SSID(i));
          Serial.print(" (");
          Serial.print(WiFi.RSSI(i));
          Serial.print(")");
          Serial.println((WiFi.encryptionType(i) == ENC_TYPE_NONE) ? " " : "*");
          delay(10);
        }
      }
      Serial.println("");

      // Wait a bit before scanning again
      delay(5000);
    }

I have a voltage regulator producing 3.3 V connected to `CH_PD` and the Arduino powers the ESP's VCC via the 3.3 V pin. `TX` is connected to `TX` and `RX` is connected to `RX`. `GPIO0` is connected to ground. I can upload, but it cannot find any networks. It always states no networks found. Now I'm not even sure how to proceed... Any help would be appreciated.

  [1]: https://github.com/esp8266/Arduino/blob/master/libraries/ESP8266WiFi/examples/WiFiScan/WiFiScan.ino

title: ESP8266-01 WifiScan not working

Answers: 1

body:
You should provide a good power source for the VCC. One that can supply 170 mA for WiFi operations of esp8266. You should use the power regulator to supply 3.3 V to VCC and there is no reason to use other power source for the CH_PD pin. CH_PD pin is "enable" pin, it doesn't need a strong power supply.

IO 0 should be connected to ground only for upload, not for normal operation.


body:
I'm reading on the DFRobot website to implement this Voltage divider: [Analog Voltage Divider SKU: DFR0051][1]

    void setup()
    {
      Serial.begin(9600);
    }
    void loop()
    {
          float val;
          float temp;
          val=analogRead(2);//This divider module will divide the measured voltage by 5, the maximum voltage it can measure is 25V.
          temp= val/40.92;
          val=(float)temp;
          Serial.println(val);
          delay(1000);
    }

Where does `40.92` come from? And even when printing only `VAL` it's something like `210` and I'm not sure what this is supposed to be. I don't get how to get the *actual* voltage of the battery etc. being measured? If it's divided by 5, why do you not multiply by 5 anywhere?

  [1]: https://www.dfrobot.com/wiki/index.php/Analog_Voltage_Divider_SKU:_DFR0051

title: Using a DFRobot Voltage Divider

Answers: 1

body: The unit measures a maximum voltage of 25v. When the measured voltage is 25v it divides it by 5 to present a maximum of 5v to the Arduino.  That is measured as a value of 1023 by analogRead(). If you divide 1023 by 40.92 you get 25.


body:
I am trying to send ADS 1115 data which is connected with Arduino mega_1 over I2C and arduino Mega_1 is connected with arduino Mega_0 over SPI.
Arduino Mega_1 is act as a slave and send ADS 1115 data to master device..
I think my whole setup is working but i want to received actual data of ADS 1115 on master Arduino
Here is screenshots of results of my code[![enter image description here][1]][1]

**master**

    #include <SPI.h>

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

      digitalWrite(SS, HIGH);  // ensure SS stays high for now

      // Put SCK, MOSI, SS pins into output mode
      // also put SCK, MOSI into LOW state, and SS into HIGH state.
      // Then put SPI hardware into Master mode and turn SPI on
      SPI.begin ();

      // Slow down the master a bit
      SPI.setClockDivider(SPI_CLOCK_DIV8);

    }  // end of setup

    byte transferAndWait (const byte what)
    {
      byte a = SPI.transfer (what);
      delayMicroseconds (20);
      return a;
    } // end of transferAndWait

    void loop (void)
    {
    byte a;

      // enable Slave Select
      digitalWrite(SS, LOW);

      transferAndWait ('a');  // add command
    a=transferAndWait (0);

      // disable Slave Select
      digitalWrite(SS, HIGH);

      Serial.println ("results:");
      Serial.println (a);

      delay (1000);  // 1 second delay
    }  // end of loop
**slave**

    #include <Wire.h>
    #include <Adafruit_ADS1015.h>
    int out_buf;
    int adc0;

    // Adafruit_ADS1115 ads;  /* Use this for the 16-bit version */
    Adafruit_ADS1015 ads;
    // what to do with incoming data
    volatile byte command = 0;
    void ss_falling ()
    {
      command = 0;
    }
    void setup (void)
    {
     ads.begin();
     Serial.begin(9600);
     //ads.startComparator_SingleEnded(0, 1000);
    // have to send on master in, *slave out*
     pinMode(MISO, OUTPUT);

    // turn on SPI in slave mode
     SPCR |= _BV(SPE);

     // turn on interrupts
     SPCR |= _BV(SPIE);
     attachInterrupt (0, ss_falling, FALLING);

    }

    // SPI interrupt routine
    ISR (SPI_STC_vect)
    {
     byte c = SPDR;

      switch (command)
      {
      // no command? then this is the command
      case 0:
        command = c;
        SPDR = 0;
        break;

      // add to incoming byte, return result
      case 'a':
        SPDR = out_buf; // add 15
        break;

      } // end of switch

    }  // end of interrupt service routine (ISR) SPI_STC_vect

    void loop (void)
    {
    adc0 = ads.readADC_SingleEnded(0);
    Serial.print("AIN0: "); Serial.println(adc0);

    out_buf=adc0;
    //int buff = atoi(out_buf);
    Serial.print("AIN1: "); Serial.println(out_buf);
    delay(1000);
     }

i am sending 1570 but on Master side i received 35 i think ADS data is of 16 bits i.e 2 bytes and SPI received only 1 byte at a time i am stuck here please help me.
Thank you in Advance

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

  [1]: https://i.stack.imgur.com/XXIGu.png
  [2]: https://i.stack.imgur.com/fgUDZ.png
  [3]: https://i.stack.imgur.com/MfnQp.png

title: How do i send ads1115 data over spi to master arduino

Answers: 2

body:
Implementing SPI slave mode is a little more tricky than you may think.  The most important thing to remember is that it's not a "Give me X" -> "Ok, here is X" kind of protocol.  It's actually a "Here's X" <=> "Here's Y" protocol.

That is, at the same time that the master sends X to the slave, the slave sends "Y" to the master.

The way you have it is that the master sends "a" as a command and discards what it receives.  The slave remembers that "a" as the "command". Then the master sends 0, and remembers what it receives. The slave receives that 0 and thinks "Ah, I got the command last time, so it must want the value" and queues up the value to be sent the next time a transaction occurs.  That then gets thrown away, since that occurs when the next "command" is sent.

You need to be a little more cunning, and implement a finite state machine to work out where in the stream you are.

* When SS falls set a "byte counter" to 0.
* When a byte is received examine the "byte counter":
  * Byte 0: If it's an "a" then place the first byte of the value in SPDR.
  * Byte 1: Place the second byte of the value in SPDR
  * Byte 3: Do nothing (or place 0 in SPDR)
* Increment the byte counter

So the transaction goes something like this (1570 is 0x622 in hex, and I choose "little endian" since the AVR is naturally little endian):

    Master Sends        Slave Queues          Master Receives
    'a'                 0x22                  Rubbish
    0                   0x06                  0x22
    0                   0x00                  0x06

    'a'                 0x22                  0x00
    0                   0x06                  0x22
    0                   0x00                  0x06

The important thing to remember is that the master receives what the slave queued *on the next transfer*.

body:
My Problem is solved now, thanks to the almighty. I did few changed in code as:
1. Converted the received int type data from ADS to Char.
2. Stored it in an Array, to form a string.

Here is my Modified Slave Code:

    #include <Wire.h>
    #include <Adafruit_ADS1015.h>
    Adafruit_ADS1015 ads;
    void setup (void)
    {
    ads.begin();
     Serial.begin(9600);
      // have to send on master in, *slave out*
      pinMode(MISO, OUTPUT);

      // turn on SPI in slave mode
      SPCR |= bit(SPE);

      // turn on interrupts
      SPCR |= bit(SPIE);
    }  // end of setup

    char buf[20];
    volatile int pos;
    volatile bool active;

    // SPI interrupt routine
    ISR (SPI_STC_vect)
    {
      byte c = SPDR;

      if (c == 1)  // starting new sequence?
        {
        active = true;
        pos = 0;
        SPDR = buf [pos++];   // send first byte
        return;
        }

      if (!active)
        {
        SPDR = 0;
        return;
        }

      SPDR = buf [pos];
      if (buf [pos] == 0 || ++pos >= sizeof (buf))
        active = false;
    }  // end of interrupt service routine (ISR) SPI_STC_vect

    void loop (void)
    {
    int adc0=0;
    adc0 = ads.readADC_SingleEnded(0);
    itoa(adc0,buf,10);
    Serial.print("AIN1: "); Serial.println(buf);
    delay(500);
    }  // end of loop

**On Master side**

We are receiving string by sending one dummy value at a time.
Here is modified master code:

    #include <SPI.h>

    void setup (void)
    {
      Serial.begin (9600);
      Serial.println ("Starting");

      digitalWrite(SS, HIGH);  // ensure SS stays high for now

      // Put SCK, MOSI, SS pins into output mode
      // also put SCK, MOSI into LOW state, and SS into HIGH state.
      // Then put SPI hardware into Master mode and turn SPI on
      SPI.begin ();

      // Slow down the master a bit
      SPI.setClockDivider(SPI_CLOCK_DIV8);

    }  // end of setup

    void loop (void)
    {
      char buf [20];

      // enable Slave Select
      digitalWrite(SS, LOW);
      SPI.transfer (1);   // initiate transmission
      for (int pos = 0; pos < sizeof (buf) - 1; pos++)
        {
        delayMicroseconds (15);
        buf [pos] = SPI.transfer (0);
        if (buf [pos] == 0)
          {
          break;
          }
        }

      buf [sizeof (buf) - 1] = 0;  // ensure terminating null

      // disable Slave Select
      digitalWrite(SS, HIGH);

      Serial.print ("We received: ");
      Serial.println (buf);

      delay (500);
    }  // end of loop


body:
Can we write a analog voltage to analog pins `A0`-`A7` of the Arduino Nano (for example)?

As in:

    pinMode(A3, OUTPUT);
    analogWrite(A3, 200);

title: Writing analog voltages on analog pins of Arduino

Answers: 4

body: analogWrite are PWM digital pins. Analog pins on Nano are ADC read/input only (or digital I/O except A6 and A7).

body:
No. The `analogWrite(pin, val)` function is reserved to PWM pins (`D3`, `D5`, `D6`, `D9`, `D10`, and `D11` in Arduino Nano). Pins marked as "ANALOG IN" on the board can work either as analog input (to the **A**nalog to **D**igital **C**onverter), digital input, or digital output.

It is worth to note that the Arduino Nano (and any other Arduino board I'm aware of) actually doesn't have any 'true' analog output port. When you use `analogWrite(pin, val)` you are actually telling the Arduino to output a PWM signal with the duty cicle specified by `val` (100% for `val = 255` and 0% for `val = 0`). If you actually do need a true analog output, you should consider using any form of analog lowpass filter at the specified PWM output port. Depending on how *clean* you want your signal to be, you could use a single capacitor or any other (a little more complex) filter.

If you don't know anything about filters, this could be a good starting point: [ElectronicsTutorials - Passive Low Pass Filter][1]

More insight about PWM in Arduino, here: [EAS 199 - Basic Pulse Width Modulation][2]

  [1]: https://www.electronics-tutorials.ws/filter/filter_2.html
  [2]: http://web.cecs.pdx.edu/~gerry/class/EAS199A/topics/pdf/PWM_output_Arduino.pdf

body:
All microcontrollers including Arduino are digital, and rely on specific circuit hardware in order to interface with the analog world.  Two of these relate to your question:

 - Analog-to-digital converters (ADCs) sample an analog voltage and output a number representing the voltage relative to the measurement range - such as 0 to 1023 on a 10-bit ADC.
 - Digital-to-analog converters (DACs) do the reverse, where a digital number from the microcontroller is used to output an analog voltage, e.g. between ground and the supply voltage.

While ADCs and DACs convert analog-to-digital and vice versa, they need different circuits.  In the case of Arduino boards and other microcontrollers, analog input (read) and output (write) must use different pins.  Analog input pins cannot be used as outputs, and vice-versa.

The exception is where you want to produce an analog output via PWM (and a smoothing capacitor).  In that case the answer is yes, you can use pins A0-A7.  However, you will need to bit-bang and won't be able to use the timer hardware.  It's much easier to use the pins dedicated to DAC or `analogwrite` if that's an option for you.

body:
You can create your own PWM on non-PWM pins using Blink Without Delay techniques.  Use the micros() timer and check it every pass thru loop() to if it is time to change the state of the output.

This will create 50% duty cycle, with frequency = 1/(2 x halfPeriod)

<!-- language: lang-c++ -->

    void loop(){
      currentMicros = micros(); // capture the current 'time'
      elapsedMicros = currentMicros - previousMicros;
      if (elapsedMicros >= halfPeriod){
        previousMicros = previousMicros + halfPeriod; // set the 'time' of the next transition
      }
    }

all time related elements are of type unsigned long

Then filter with a RC Lowpass filter (Resistor and a capacitor) to smooth it out so it's more like an analog level.


body:
<!-- language: lang-c++ -->

    #include <Streaming.h>
    #include <StopWatch.h>
    #include <Albert.h>
    #include "avdweb_AnalogReadFast.h"
    const byte adcPin = A0;
    void setup(void)
    {
        Serial.begin(9600);
        while(!Serial);
        Serial << "\nanalogRead_10bit us1 analogRead_12bit us2 analogReadFast_10bit us3 analogReadFast_12bit us4";
        for(int i=0; i<10; i++)
            testAnalogRead();
    }
    void testAnalogRead()
    {
        static Stopwatch stopwatch(micros);
        //delay(1000);

        stopwatch.start();
        int adc1 = analogRead(adcPin); // default resolution 10bit 425us on SAMD21
        stopwatch.stop();
        int t1 = stopwatch.interval;

        analogReadResolution(12);
        stopwatch.start();
        int adc2 = analogRead(adcPin); // 425us on SAMD21
        stopwatch.stop();
        int t2 = stopwatch.interval;

        analogReadResolution(10);
        stopwatch.start();
        int adc3 = analogReadFast(adcPin); // 23us on SAMD21
        stopwatch.stop();
        int t3 = stopwatch.interval;

        analogReadResolution(12);
        stopwatch.start();
        int adc4 = analogReadFast(adcPin); // 24us on SAMD21
        stopwatch.stop();
        int t4 = stopwatch.interval;

        Serial << endl << adc1, t1, adc2, t2, adc3, t3, adc4, t4;
        analogReadResolution(10); // restore default
    }
    void loop()
    {
    }

This code does compile in the Arduino Zero, but does not produce the serial output on the serial monitor (serial plotter) at all.

What am I doing wrong?

title: The code does not produce the serial output

Answers: 0


body:
I have a class defined as below, it's basically a simple ring buffer, with some methods for getting useful statistics from the data held in the buffer.

    enum BalanceMsgType{
      BAL_MSG_NOT = 0,
      BAL_MSG_READING = 1,
      BAL_MSG_SPECIAL = 2,
      BAL_MSG_ERROR = 3
    };

    typedef struct MeasuredMass{
      float mg;
      unsigned long time;
      bool steady;
      BalanceMsgType type;
    };

    class RingBuffer{
      private:
      unsigned int _size = 0;
      unsigned int _pos = 0;
      MeasuredMass *_array;
      void LinearRegression(){
        //... left out for simplicity
      }
      public:
      float lin_reg_m = 0;
      float lin_reg_c = 0;
      float lin_reg_r = 0;
      float est_current_mg = 0;
      //methods
      RingBuffer(unsigned int size){
        _size = size; //forgetting to put this line ->div0-> >1hr debugging :(
        _array = new MeasuredMass[_size];
        for (int i = 0; i < _size; i++){
          _array[i].mg = 0.0;
        }
      }
      void Add(MeasuredMass in_element){
        _array[_pos] = in_element;
        _pos = (_pos + 1)%_size;
        LinearRegression();
        est_current_mg = lin_reg_m*(in_element.time+BALANCE_DELAY) + lin_reg_c;
      }
      void ReadInOrder(MeasuredMass *pdata){  //Call with
                                              //my_buffer.ReadInOrder(data)
        for(int i = 0; i < _size; i++){
          pdata[i]=_array[(_pos+i+1)%_size];
        }
      }
      float Sum(){
        //...
      }
      float Mean(){
        //...
      }
      float StdDev(){
        //...
      }
      bool SteadyEnough(float max_sd){
        //...
      }
    };

It compiles fine, and runs nicely in test programs. However, if I include it in larger programs (something like progmem 117404 of 122880 bytes, global vars 13604 of 32768) I get a "Board at COM8 not available" warning when using the Arduino Serial Monitor after uploading to my Fubarino Mini. (Even without actually interacting with those programs beyond creating an instance of the class.) Recent experience tells me this is some kind of crash due to a runtime error.

Fiddling around with the code, I've found that the issue doesn't occur in a version of the library which holds an array of floats instead of my `MeasuredMass`. That my `MeasuredMass` struct is obviously much larger than a float suggests to me that this is due to some pointer/array overflowy behaviour.

I've also managed to show that if I alter the class such that it uses a fixed length array rather than a pointer to one, the issue disappears.

i.e. RingBuffer's private member `MeasuredMass *_array;` becomes `MeasuredMass _array[25];`
and

    RingBuffer(unsigned int size){
      _size = size; //forgetting to put this line -> div0 -> >1hr bugtracking
      _array = new MeasuredMass[_size];
      for (int i = 0; i < _size; i++){
        _array[i].mg = 0.0;
      }
    }

becomes

    RingBuffer(){
      for (int i = 0; i < _size; i++){
        _array[i].mg = 0.0;
      }
    }

I'd rather maintain the ability to set the size of the ring buffer at runtime (in my case it's set based upon the number of seconds' worth of data requested), so can anyone help me in figuring out how I can achieve this without running into the overflow / memory problems I seem to be having?

Thanks

title: Runtime Error when using array of structs of unknown size as variable within class - some kind of overflow issue?

Answers: 1

body:
The problem is most likely here:

    _array = new MeasuredMass[_size];

You're allocating `_size * sizeof(MeasuredMass)` bytes in the heap. If `_size` is too big the amount of memory allocated becomes too great and it fails to allocate. You should check if `_array` is `NULL` or not after the `new`.  If it's `NULL` then it failed to allocate.

The problem is that heap allocation is limited to 2kB. This is regardless of the amount of memory you actually have in the chip. This is a limit imposed by the compiler (actually the libraries bundled with the compiler) and is set by a value in the linker script.  It's something I've been campaigning to have removed from the libraries for many years, but it's always fallen on deaf ears. So much so that I provide a "fixed" version of the compiler in UECIDE that removes this hard limit.

The best thing you can do is to not use dynamic allocation. Instead have a statically created array which you then pass to the constructor.

    MeasuredMass massBuffer[25];
    RingBuffer massRing(massBuffer, 25);

and:

    RingBuffer(MeasuredMass *buf, unsigned int size){
      _size = size; //forgetting to put this line ->div0-> >1hr debugging :(
      _array = buf;
      for (int i = 0; i < _size; i++){
        _array[i].mg = 0.0;
      }
    }


body:
I am sending data over USB Serial to my `Uno` in a specified format and printing the values after they are read

    void loop() {
        if(Serial.available()){
            while(Serial.available()){
                int pos = Serial.readStringUntil(':').toInt();
                Serial.println(pos);
                int r = Serial.readStringUntil(',').toInt();
                Serial.println(r);
                int g = Serial.readStringUntil(',').toInt();
                Serial.println(g);
                int b = Serial.readStringUntil(';').toInt();
                Serial.println(b);
            }
        }
    }

This is how the data is being sent

    0:255,255,255;1:255,255,255;2:255,255,255;3:255,255,255;4:255,255,255;5:255,255,255;6:255,255,255;7:255,255,255;8:255,255,255;9:255,255,255;10:255,255,255;

format is `{position}:{Red value},{Green value},{Blue value};`

When I send this string to the device through the serial monitor it prints wrong values

    0
    255
    255
    255
    1
    55 //should be 255
    255
    255
    2
    55 //should be 255
    255
    255
    3
    55 //should be 255
    255
    255
    4
    55 //should be 255
    255
    255
    5
    255
    255
    255
    6
    255
    255
    255
    7
    255
    255
    255
    8
    255
    255
    255
    9
    255
    255
    255
    10
    255
    255
    255

Why is the data wrong?

Is it just the serial monitor that isnt showing it right but the values are actually right?

title: Serial data showing incorrect values

Answers: 1

body:
It looks like you are parsing the incoming data for a string of 4 numbers, pos+r+g+b.  To avoid data loss as well as improve speed (if you need it), it may be better to send the data as bytes:

    : 0x01 0xFF 0xFF 0xFF : 0x02 0xFF 0xFF 0xFF : 0x03 0xFF 0xFF 0xFF ... etc

This can be done with Arduino serial monitor via a hex to ASCII converter.  For example https://www.branah.com/ascii-converter

Type in hex (missing 0x, where `0x3a=':'`): `3a01FFFFFF3a02FFFFFF3a03FFFFFF3a04FFFFFFFF`

Get ASCII: `:ÿÿÿ:ÿÿÿ:ÿÿÿ:ÿÿÿ`

Copy this into the Arduino serial monitor

Also, try to do all of the serial prints in one go, don't interleave reading and writing unless you absolutely have to.  Sometimes bytes get dropped that way, too.

    byte pos, r, g, b;

    void setup(){
    // serial begin
    }

    void loop() {
        if(Serial.available()){
            while(Serial.available()){
                Serial.readStringUntil(':');
                pos = Serial.read();
                r   = Serial.read();
                g   = Serial.read();
                b   = Serial.read();
                Serial.write(pos);
                Serial.write(r);
                Serial.write(g);
                Serial.write(b);
             }
        }
    }

If you need a more elegant way to do the serial write, you will find plenty of answers already on stack exchange (too many to suggest only one).


body:
I'm trying to use a remote control to control the red/green/blue values of an RGB LED using an Arduino Uno. Here's what I've got so far:

    #include <IRremote.h>
    #define IRPin 7
    #define bluePin 9
    #define greenPin 10
    #define redPin 11

    int blueValue = 0;
    int greenValue = 0;
    int redValue = 0;

    IRrecv irrecv(7);
    decode_results results;

    void RGBLED(int blue, int green, int red)
    {
      analogWrite(redPin, red);
      analogWrite(greenPin, green);
      analogWrite(bluePin, blue);
    }

    void setup(){
      irrecv.enableIRIn();
      pinMode(sensorPin, INPUT);
      Serial.begin(9600);
    }

    void loop(){
    if (irrecv.decode(&results)){
      switch(results.value)
      {
        case 0xFF6897:
          Serial.println("Red+16");
          redValue = redValue + 16;
          if(redValue >= 256)
          {
            redValue = 255;
          }
        break;
        case 0xFF9867:
          Serial.println("Green+16");
          greenValue = greenValue + 16;
          if(greenValue >= 256)
          {
            greenValue = 255;
          }
        break;
        case 0xFFB04F:
          Serial.println("Blue+16");
          blueValue = blueValue + 16;
          if(blueValue >= 256)
          {
            blueValue = 255;
          }
        break;
        case 0xFF30CF:
          Serial.println("Red-16");
          redValue = redValue - 16;
          if(redValue < 0)
          {
            redValue = 0;
          }
        break;
        case 0xFF18E7:
          Serial.println("Green-16");
          greenValue = greenValue - 16;
          if(greenValue < 0)
          {
            greenValue = 0;
          }
        break;
        case 0xFF7A85:
          Serial.println("Blue-16");
          blueValue = blueValue - 16;
          if(blueValue < 0)
          {
            blueValue = 0;
          }
        break;
      }
    irrecv.resume();
    RGBLED(blueValue, greenValue, redValue);
    }
Everything works fine, except the adding up to `redValue`. It's the same exact code that is used for `greenValue` and `blueValue`. The substraction from `redValue` works fine too. Everytime the problematic function gets called, the serial monitor prints `Re` and the whole thing just stops working.
I have tried rewriting that code from scratch, copying the other code, but nothing worked. I have switched up the codes from my IR remote but that had nothing to do with it either.
Can anyone spot the mistakes or tell me what I'm doing wrong?

Thanks in advance

title: Problem with incrementing values of an RGB LED

Answers: 0


body:
I am getting the following error message when compiling a program on my Arduino IDE. This does not happen when compiling the given example programs in the IDE.

The error message is as follows :

<!-- language: lang-none -->

    Arduino: 1.8.5 (Windows 10), Board: "Arduino/Genuino Uno"

    C:\Program Files\Arduino\arduino-builder -dump-prefs -logger=machine -hardware
    C:\Program Files\Arduino\hardware -tools
    C:\Program Files\Arduino\tools-builder -tools
    C:\Program Files\Arduino\hardware\tools\avr -built-in-libraries
    C:\Program Files\Arduino\libraries -libraries
    C:\Users\mahim\OneDrive\Documents\Arduino\libraries -fqbn=arduino:avr:uno -ide-version=10805 -build-path
    C:\Users\mahim\AppData\Local\Temp\arduino_build_361527 -warnings=none -build-cache
    C:\Users\mahim\AppData\Local\Temp\arduino_cache_227236 -prefs=build.warn_data_percentage=75 -prefs=runtime.tools.arduinoOTA.path=
    C:\Program Files\Arduino\hardware\tools\avr -prefs=runtime.tools.avr-gcc.path=
    C:\Program Files\Arduino\hardware\tools\avr -prefs=runtime.tools.avrdude.path=
    C:\Program Files\Arduino\hardware\tools\avr -verbose
    C:\Users\mahim\OneDrive\Documents\Arduino\3potpass\3potpass.ino
    readlink
    C:\Users\mahim\OneDrive\Documents\Arduino\3potpass\3potpass.ino: The system cannot find the file specified.

    Error compiling for board Arduino/Genuino Uno.

Answers: 2

body: [This is a known incompatibility between the Arduino IDE and Microsoft OneDrive](https://github.com/arduino/arduino-builder/issues/254). A fix should be available soon; in the meantime, move your Arduino sketches out of the OneDrive folder.

body:
Following on from [duskwuff's answer][1], the issue with OneDrive folders has been resolved as of version 1.8.6.

[https://www.arduino.cc/en/Main/ReleaseNotes][2]

> ARDUINO 1.8.6 2018.08.23
>
> [ide]
>
> * Updated arduino-builder to 1.4.0:
>  - parallel build (improve compile speed)
>  - better reuse of already compiled files
>  - **Windows: fixed build for sketch stored under OneDrive cloud folders**

Simply update to a newer version of the Arduino IDE and you will be able to compile and upload your sketch.

  [1]: https://arduino.stackexchange.com/a/53951/19409
  [2]: https://www.arduino.cc/en/Main/ReleaseNotes


body:
I have recebntly started a project where I need to connect an arduino and another device through serial. And I have setup a simple serial connection betwee python and arduino. I can setup the connection through the python terminal and it works just fine. When I type : `arduino.write("1")`, It receives the data only once. However, When I run this code:

    import serial

    arduino = serial.Serial('/dev/ttyACM0', 115200, timeout=.1)

    while True:
        arduino.write("1")
it writes properly, howver when I stop it using Ctrl-C, it doesn't stop sending and keeps sending to the arduino. Stops sending when I open a serial. connection using the python terminal again.

I have no idea what is causing this or how I can fiz it. Would reallly appreciate some help. Thanks in advance:

title: Arduino and Pyton Serial Communication, Pyton get stuck and keeps sending

Answers: 1

body: Your python code is sending "1"'s to the serial port at a blinding speed.  Way faster than they can go out over the serial line.  So when you stop your python code the serial port is still sending trying to get all the "1"'s out of its buffer.  When you open the connection again you clear that buffer and it stops sending.


body:
I've synced my Uno with the Arduino IDE and I'm using the following code to get the GPS coordinates:

    #include <TinyGPS.h>
    #include <SoftwareSerial.h>

    unsigned long fix_age;
    SoftwareSerial GPS(4,3);
    TinyGPS gps;
    void gpsdump(TinyGPS &gps);
    bool feedgps();
    void getGPS();
    long lat, lon;
    float LAT, LON;

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

    void loop(){
      long lat, lon;
      unsigned long fix_age, time, date, speed, course;
      unsigned long chars;
      unsigned short sentences, failed_checksum;
      // retrieves +/- lat/long in 100000ths of a degree
      gps.get_position(&lat, &lon, &fix_age);
      // time in hh:mm:ss, date in dd/mm/yy

      getGPS();
      Serial.print("Latitude : ");
      Serial.print(lat/100000,7); //#UPDATED
      Serial.print(" :: Longitude : ");
      Serial.println(lon/100000,7); //#UPDATED
    }

    void getGPS(){
      bool newdata = false;
      unsigned long start = millis();
      // Every 1 seconds we print an update
      while (millis() - start < 1000)
      {
        if (feedgps ()){
          newdata = true;
        }
      }
      if (newdata)
      {
        gpsdump(gps);
      }
    }

    bool feedgps(){
      while (GPS.available())
      {
        if (gps.encode(GPS.read()))
          return true;
      }
      return 0;
    }

    void gpsdump(TinyGPS &gps)
    {
      //byte month, day, hour, minute, second, hundredths;
      gps.get_position(&lat, &lon);
      Serial.print("Hello World : "); //#UPDATED (Test)
      LAT = lat;
      LON = lon;
      {
        feedgps(); // If we don't feed the gps during this long
      }
    }

When I compile, it uploads successfully and when I check the serial streams, it displays:

Latitude : 41103 :: Longitude : 41103

But my lat/lon (in the risk of disclosing location) is
(38.984898400, -76.957276900)

It doesn't seem to be the same.

title: Empty output with GPS module GTPA010

Answers: 0


body:
I've written a small sketch targeted at the Arduino Uno (ATmega328P) to debounce a mechanical pushbutton using the summing/integration technique:

    #include <IntegratingDebounce.h>
    #define PIN_BTN 4

    IntegratingDebounce *btn;

    ISR (TIMER2_OVF_vect) {
      ideb_poll(btn);
    } // end timer2 overflow ISR

    void set_debounce_timer() {
      TCNT2 = 0;                                  // Clear timer
      TCCR2A &= ~( bit( WGM21 ) | bit( WGM20 ) ); // Set waveform generation mode to normal
      TCCR2B &= ~bit( WGM22 );
      TIMSK2 |= bit( TOIE2 );                     // Enable interrupt on overflow
      TCCR2B |= 7;                                // Start clocking the timer
    } // set_debounce_timer()

    void setup() {
      Serial.begin(9600);
      pinMode(PIN_BTN, INPUT_PULLUP);

      ideb_init(&btn, PIN_BTN, 4);
      set_debounce_timer();
    } // setup()

    void loop() {
      while (ideb_read(btn) == HIGH);  // wait until the button pin goes low
      Serial.println("Pressed!");
      delay(100);
    } // loop()

An `IntegratingDebounce` structure stores the data needed to perform the debounce. I keep a pointer to the structure, `btn`, in the global memory space.

The timer2 overflow ISR periodically polls the state of the button pin, updates the internal integrator, and sets the (also internal) debounced output accordingly. The `ideb_read()` function reads the debounced output out of the structure.

I'm having trouble determining where the `volatile` keyword should be placed in the declaration for the `btn` structure pointer. First I declared it as:

`volatile IntegratingDebounce *btn;`

I thought this would make all of the fields in the structure pointed to by `btn` volatile, but button presses are not detected in loop(). Declaring `btn` as a volatile pointer rather than a pointer to a volatile structure generates the expected output:

`IntegratingDebounce *volatile btn;`

This seems backwards. Why does this work?

__IntegratingDebounce.h__

    #ifndef __INTEGRATING_DEBOUNCE_H__
    #define __INTEGRATING_DEBOUNCE_H__

    #include <Arduino.h>
    #include <stdint.h>

    extern "C" {

    typedef struct IntegratingDebounce_S IntegratingDebounce;
    typedef uint8_t ideb_size_t;

    // Create a debounce structure and initialize.
    void ideb_init(
      IntegratingDebounce **ideb,
      uint8_t pin,                  // I/O pin to debounce
      ideb_size_t clamp             // debounce clamp; the maximum value the
                                    //   internal sum is able to take on
    );

    // Poll the state of the pin, integrate, and update the debounced output.
    void ideb_poll(IntegratingDebounce *ideb);

    // Read the debounced state of the pin.
    uint8_t ideb_read(IntegratingDebounce *ideb);

    // Reset the internal integrator to either the LOW or HIGH state.
    void ideb_reset(IntegratingDebounce *ideb, uint8_t state);

    } // extern C

    #endif

__IntegratingDebounce.c__

    #include "IntegratingDebounce.h"

    struct IntegratingDebounce_S {
      uint8_t pin;              // pin to debounce
      uint8_t output;           // debounced output
      ideb_size_t clamp;        // debounce clamp
      ideb_size_t integrator;   // clamped running sum
    };

    void ideb_init(IntegratingDebounce **ideb, uint8_t pin, uint8_t clamp) {
      *ideb = (IntegratingDebounce *)malloc(sizeof(IntegratingDebounce));
      (*ideb)->pin = pin;
      (*ideb)->clamp = clamp;
      (*ideb)->output = 0;
      (*ideb)->integrator = 0;
    } // ideb_init()

    void ideb_poll(IntegratingDebounce *ideb) {
      // update the integrator based on the present state of the pin:
      // - if LOW, decrement the integerator; if HIGH, increment the integrator
      // - constrain the integrator to values between 0 and 'clamp'
      if (digitalRead(ideb->pin) == LOW) {
        if (ideb->integrator > 0) ideb->integrator--;
      } // if
      else {
        if (ideb->integrator < ideb->clamp) ideb->integrator++;
      } // else

      // update the output based on the value of the integrator; the output
      // will not change until the integrator reaches a limiting value
      if (ideb->integrator == 0 && ideb->output == HIGH) {
        ideb->output = LOW;
      } // if
      else if (ideb->integrator == ideb->clamp && ideb->output == LOW) {
        ideb->output = HIGH;
      } // else if
    } // ideb_poll()

    uint8_t ideb_read(IntegratingDebounce *ideb) {
      return ideb->output;
    } // ideb_read()

    void ideb_reset(IntegratingDebounce *ideb, uint8_t state) {
      if (state == LOW) {
        ideb->integrator = 0;
        ideb->output = LOW;
      } // if
      else {
        ideb->integrator = ideb->clamp;
        ideb->output = HIGH;
      } // else
    } // ideb_reset()

title: Interrupts: use of the "volatile" keyword with a structure pointer for button debounce

Answers: 2

body:
I think, that the problem is in `ideb_read`, which expects "a pointer to (non-volatile) structure" and so it does not care about re-reading `ideb->output` if it can it optimize out somehow (say putting it in free register).

IMHO the `ideb_read` should have parameter declared as `(volatile IntegratingDebounce *ideb)` (to know, that structure pointed by `ideb` is volatile) or use global variable `btn` (which is pointer to volatile structure) instead of pointer parametr to non-volatitle structure.

---

And why the second works would be because it forces re-read the parameter of `ideb_read` and so it cannot be saved out somewhere and the function is indirectly forced to expect changed pointer, so it have to use its 'new value' and read the structure (as it is simpler, than ensure, that the `ideb` have the same value as it had last call and so the whole structure there (which is declared as non-volatile in header of `ideb_read`) could be cached)

---

Another wording of the above:

Declaring `volatile IntegratingDebounce *btn;` the main program in `loop` simply takes the value of `btn` (which is non-volatile pointer to volatile structure) and copy that (non-volatile) value to `ideb` parametr od `ideb_read`, which is non-volatile pointer to non-volatile structure. `ideb_read` use it that way and compiler somehow was able to cache all of that and so not read `ideb->output` again, as it knows, that it is part of non-volatile struct. (So it does not work)

Declaring `IntegratingDebounce *volatile btn;` you made the `btn` volatile, so it gets read each time `ideb_read` is called and the 'new actual value' is passed to (non-volatile) `ideb` parametr (which is this way given 'new value' and so cannot be cached between calls) and it results to reading (non-volatile) date from "new" place pointed by `ideb`. So it works (by mistake).

Right solution would be declare correctly `volatile IntegratingDebounce *btn;` in main program AND declare correctly `uint8_t ideb_read(volatile IntegratingDebounce *ideb)` so the `ideb_read` function is forced read value pointed by `ideb` every time again (which is the right thing to do)

And it should be used for all other `ideb_**` functions too.

And I think, that it would be simpler to declare some typedef for this volatile structure (something like `typedef struct { ... } volatile ideb_t;` ) and use the new type everywhere.

body:
Getting pointer declarations right can be anything but obvious, especially where `const` and `volatile` are concerned (which are syntactically equivalent). Your problem stemmed from the confusion between "volatile pointer to struct" and "pointer to volatile struct". See the difference? In words it's fairly clear. In C, it has you - and me - running to your C manual's Table of Precedence.

I keep a copy of Dan Saks' article, ["Const T vs. T Const"][1] on hand for just exactly this case - it seems I always need to look it up.

And while you're there, check out some of [his other articles][2] as well. I learn something every time I read one.

  [1]: http://www.dansaks.com/articles/1999-02 const T vs T const.pdf
  [2]: http://dansaks.com/articles/


body:
have an esp8266.

i'm trying to create a DDNS updater.

it has to wait 5 min then do a GET request to a URL.

Here's my code:

    /* Code For DNS Updater.*/

    #include <ESP8266WiFi.h>
    #include <ESP8266HTTPClient.h>

    #define LOOP_TIME 300000

    const char* ssid = "SomeSSID";
    const char* password = "SomePSWD";

    const String address="http://dynamicdns.park-your-domain.com";
    const String path="update";
    const String pathHost="host";
    const String pathPassword="password";
    const String pathDomain="domain";

    const String dnsName="my-example-host.com";
    const String ddnsPassword="my-example-password";
    const String updateHosts[]={
        "@",
        "subdomain1",
        "subdomain2",
      };

    void setup() {
      Serial.begin(115200);
      connectWiFi();
    }

    long nextUpdate=0;

    void loop() {
      if(nextUpdate<millis()){
        if (WiFi.status() == WL_CONNECTED) {
        updateDNS();
        }else{
          connectWiFi();
        }
        nextUpdate=millis()+LOOP_TIME;
      }
    }

    void updateDNS(){
      Serial.println("Updating Hosts:");
      for(int host=0;host<(sizeof(updateHosts)/sizeof(String));host++){
        Serial.print(updateHosts[host]+": ");
        String assembledURL=address+"/"+path+"?"+pathHost+"="+updateHosts[host]+"&"+pathDomain+"="+dnsName+"&"+pathPassword+"="+ddnsPassword;
    //    Serial.println("Host: "+updateHosts[host]+" URL: "+assembledURL);
        HTTPClient http;
        http.begin(assembledURL);
        http.GET();
        http.end();
        Serial.println("Done");
      }
    }

    void connectWiFi(){
      WiFi.begin(ssid, password);

      Serial.print("Connecting To ");
      Serial.println(ssid);
      Serial.print("Password: ");
      Serial.println(password);
      Serial.print("Connecting");
      while (WiFi.status() != WL_CONNECTED) {

        delay(500);
        Serial.print(".");

      }
      Serial.println();
      Serial.print("Connected To ");
      Serial.println(ssid);
    }

and it stops after a couple of hours - which isnt good for a DDNS updater.

EDIT: maybe it has something to do with my timer. will try an unsigned long instead.

title: ESP8266 Stops Working After A While (Unknown Problem)

Answers: 1

body:
I have had the "stops after a while" too and it turned out to be heap memory consumption and fragmentation that caused not having enough stack and heap space any more.

My solution: check the heap from time to time (in loop) and reboot the node when it comes down to a practical limit.

Alternate: avoid using the String type and other Heap usages.


body:
The code below

    // include the library code:
    #include "LiquidCrystal.h"
    // initialize the library with the numbers of the interface pins
    LiquidCrystal lcd(2,4,5,6,7);

    void setup()
    {
    // set up the LCD’s number of columns and rows:
    lcd.begin(16,2);
    // Print a message to the LCD.
    lcd.print("hello");
    }
    void loop()
    {
    // set the cursor to column 0, line 1
    // (note: line 1 is the second row, since counting begins with 0):
    lcd.setCursor(0, 1);
    // print the number of seconds since reset:
    lcd.print(millis()/1000);
    }

Gives me the following error:

    exit status 1 no matching function for call to 'LiquidCrystal::LiquidCrystal(int, int, int, int, int)'

Answers: 1

body:
It seems as if you are missing a parameter in the `lcd()` call. It seem to take six arguments, not five.

From the `Blink` example in the `LiquidCrystal` library:

    // initialize the library by associating any needed LCD interface pin
    // with the arduino pin number it is connected to
    const int rs = 12, en = 11, d4 = 5, d5 = 4, d6 = 3, d7 = 2;
    LiquidCrystal lcd(rs, en, d4, d5, d6, d7);

Also, looking at the library definition, from `LiquidCrystal.cpp`:

    class LiquidCrystal : public Print {
    public:
      LiquidCrystal(uint8_t rs, uint8_t enable,
      uint8_t d0, uint8_t d1, uint8_t d2, uint8_t d3,
      uint8_t d4, uint8_t d5, uint8_t d6, uint8_t d7);
      LiquidCrystal(uint8_t rs, uint8_t rw, uint8_t enable,
      uint8_t d0, uint8_t d1, uint8_t d2, uint8_t d3,
      uint8_t d4, uint8_t d5, uint8_t d6, uint8_t d7);
      LiquidCrystal(uint8_t rs, uint8_t rw, uint8_t enable,
      uint8_t d0, uint8_t d1, uint8_t d2, uint8_t d3);
      LiquidCrystal(uint8_t rs, uint8_t enable,
      uint8_t d0, uint8_t d1, uint8_t d2, uint8_t d3);
    ...
    }

The number of arguments accepted by the various overloaded constructors are (respectively):

 - 10
 - 11
 - 7
 - 6

So, your statement:

    LiquidCrystal lcd(2,4,5,6,7);

is missing a parameter (or more) as it only has five.

This explains why the error that you are seeing has five `int`s listed in the parameter list:

    'LiquidCrystal::LiquidCrystal(int, int, int, int, int)'


body:
I have made a home automation project.

Description: Light on, off through HC-05 Bluetooth module and my Android app. The problem is when the power is gone, the system stops, that's OK. After that, when the power comes back, the system remains off, as because of no storage of the value.

Please any one help me, that how to store Bluetooth data on EEPROM on Arduino. My simple code looks like...

    #include <EEPROM.h>
    #define ledPin 7
    int state = 0;

    void setup() {
      pinMode(ledPin, OUTPUT);
      digitalWrite(ledPin, LOW);
      Serial.begin(9600); // Default communication rate of the Bluetooth module
    }

    void loop() {

      if(Serial.available() > 0){ // Checks whether data is comming from the serial port
        state = Serial.read(); // Reads the data from the serial port
      }

      if (state == '0') {
        digitalWrite(ledPin, LOW); // Turn LED OFF
        Serial.println("LED: OFF"); // Send back, to the phone, the String "LED: ON"
        state = 0;
      }
      else if (state == '1') {
        digitalWrite(ledPin, HIGH);
        Serial.println("LED: ON");;
        state = 0;
      }
    }

title: How does Arduino memorize the last bytes from Bluetooth HC-05?

Answers: 1

body:
Sir you didn't used EEPROM functions, you just initialized them. For example

- [`EEPROM.read();`][1]
- [`EEPROM.write();`][2]

if you use these function then your issue will be solved out..

  [1]: https://www.arduino.cc/en/Tutorial/EEPROMRead
  [2]: https://www.arduino.cc/en/Tutorial/EEPROMWrite


body:
I am trying, unsuccessfully to communicate, using my Arduino Nano, with a custom device at a baud rate of 800 kbit/s.

The Arduino code look like this:

    void setup() {
      // Put your setup code here, to run once:
      Serial.begin(800000);
    }

    void loop() {
      // Put your main code here, to run repeatedly:
      delay(5000);
      Serial.println(0x2be1);
    }

When I am trying to debug it with PuTTY the result is:

[![PuTTY output @ 800 kb/s][1]][1]

And when I change the baud rate to 400 kbit/s the result is (as it should be):

[![PuTTY output @ 400 kb/s][2]][2]

Any idea?

  [1]: https://i.stack.imgur.com/eSFhQ.png "PuTTY output @ 800 kb/s"
  [2]: https://i.stack.imgur.com/7qmLd.png "PuTTY output @ 400 kb/s"

title: How to work with non-traditional UART baud rates

Answers: 1

body:
The Arduino Nano cannot do 800 kb/s. As you can see in [the source
code][source], the bit duration is rounded to the nearest multiple of
8 CPU cycles. In your case, it is rounded to
3 × 8 CPU cycles, which yields a baud rate of
666.666 kb/s. That is 16% too slow, an error too large for any
communication to be possible.

At 400 kb/s there is no rounding error, so everything works fine.

**Edit**: Note that if you build your own [barebones
Arduino][barebones], then either a 12.8 MHz or a 19.2 MHz
crystal should allow you to get that exact baud rate. But then
`millis()`, `delay()` and co. would all be off.

[source]: https://github.com/arduino/Arduino/blob/1.8.5/hardware/arduino/avr/cores/arduino/HardwareSerial.cpp#L106
[barebones]: https://www.arduino.cc/en/Main/Standalone


body:
I am using the Arduino Uno.  I am attempting to only light a red LED when both a blue LED is on and the push button is pressed.  However, I keep receiving an error message stating too few arguments in my if statement.  I don't know whether I am simply overlooking something in my code.

The code is as follows:

    int redLEDPin=7;
    int blueLEDPin=3;
    int redLEDOn=2000;
    int redLEDOff=1000;
    int blueLEDOn=2000;
    int blueLEDOff=1000;
    int leverR=2;

    void setup() {
        pinMode(redLEDPin, OUTPUT);
        pinMode(blueLEDPin, OUTPUT);
        pinMode(leverR, INPUT);
        }

    void loop() {
        digitalWrite(blueLEDPin, HIGH);
        delay(blueLEDOn);
        digitalWrite(blueLEDPin, LOW);
        delay(blueLEDOff);
        }

      if ((digitalWrite(blueLEDPin) == HIGH) && (digitalRead(leverR) == HIGH)) {
        digitalWrite(redLEDPin, HIGH);
        delay(redLEDOn);
        digitalWrite(redLEDPin, LOW);
        delay(redLEDOff);
        }
      else
      {
        digitalWrite(redLEDPin, LOW);
      }
    }

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

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

title: Too few arguments for multiple if statement conditions

Answers: 3

body:
Your if statement is outside of the loop() function.

Remove the `}` after `delay(blueLEDOff);`

body:
The digitalWrite statement in the if statement needs a value to write. It looks like you meant digitalRead, since you're comparing the result to something and the other condition is a digitalRead.

     if ((digitalWrite(blueLEDPin) == HIGH) && (digitalRead(leverR) == HIGH)) {
vs

     if ((digitalRead(blueLEDPin) == HIGH)  && (digitalRead(leverR) == HIGH)) {

body:
This is your `loop()` function:

    void loop() {
        digitalWrite(blueLEDPin, HIGH);
        delay(blueLEDOn);
        digitalWrite(blueLEDPin, LOW);
        delay(blueLEDOff);
        }

Your `if()` statement is outside of your loop. Check your brackets. In the Arduino IDE, if you put your cursor to the right of a bracket, it will highlight which bracket corresponds to that one.

_Large Edit:_

To blink two LEDs concurrently, you need to get rid of the delays. Please read about using the millis() function: https://learn.adafruit.com/multi-tasking-the-arduino-part-1/using-millis-for-timing

I don't know how to explain this succinctly, so I am providing the code (note that the on and off times for the LEDs are equal -- if you want them on longer than they are off, you can work on that part of it):

    int redLEDPin=7;
    int blueLEDPin=3;
    int redLEDOn=2000;  //not used
    int redLEDOff=250;
    int blueLEDOn=2000;
    int blueLEDOff=1000;  //not used
    int leverR=2;

    // the following variables are needed for timing and tracking LED state:
    long previousMillisBlue = 0;
    long previousMillisRed = 0;
    bool ledStateBlue = LOW;
    bool ledStateRed = LOW;

    void setup() {
        pinMode(redLEDPin, OUTPUT);
        pinMode(blueLEDPin, OUTPUT);
        pinMode(leverR, INPUT_PULLUP); //I am using internal pullup resistor
    }

    void loop() {
        unsigned long currentMillis = millis();

        if(currentMillis - previousMillisBlue > blueLEDOn)
        {
          previousMillisBlue = currentMillis;

          if (ledStateBlue == LOW)
            {ledStateBlue = HIGH;}
          else
            {ledStateBlue = LOW;}

          digitalWrite(blueLEDPin, ledStateBlue);
        }

        //since we are tracking ledStateBlue above, we can reference it here
        if(digitalRead(leverR) == HIGH && ledStateBlue)
        {
          if(currentMillis - previousMillisRed > redLEDOff)
          {
            previousMillisRed = currentMillis;

            if (ledStateRed == LOW)
              {ledStateRed = HIGH;}
            else
              {ledStateRed = LOW;}

            digitalWrite(redLEDPin, ledStateRed);
          }
        }
        else
        {digitalWrite(redLEDPin, LOW);}

    }


body:
i've been working on a project using an Arduino UNO, Bluetooth Module HC-06 and NodeMCU esp8266, the project consists on turning leds on via bluetooth and telling the esp8266 that the leds were turned ON, so then we can display some particular webpage data, everything that is not related to the serial communication works perfectly fine.

    #include <NewPing.h>
    #include <Servo.h>
    #include <SoftwareSerial.h>
    #define TRIGGER_PIN 2
    #define ECHO_PIN 3
    #define MAX_DISTANCE 200

    NewPing sonar(TRIGGER_PIN, ECHO_PIN, MAX_DISTANCE);

    SoftwareSerial Serial1(5, 4);

    Servo myservo;

    int ledazul = 8; // LED RED
    int scLed1 = 9; // LED 1
    int scLed2 = 10; // LED 2
    int scLed3 = 11; // LED 3
    int scLed4 = 12; // LED 4
    int scLed5 = 13;
    int fan = 6;
    bool br = false;
    bool bra = false;
    bool porta = false;
    int pos = 0;

    char val;
    void setup() {

      Serial1.begin(115200);
      Serial.begin(9600);
      myservo.attach(7);
      pinMode(ledazul, OUTPUT);
      pinMode(scLed1, OUTPUT);
      pinMode(scLed2, OUTPUT);
      pinMode(scLed3, OUTPUT);
      pinMode(scLed4, OUTPUT);
      pinMode(scLed5, OUTPUT);
      pinMode(fan, OUTPUT);

    }
    void loop() {
      if (Serial.available() > 0)
      {
        val = Serial.read();

        Serial.print("Ping: ");
        int dist = sonar.ping();
        Serial.print(sonar.convert_cm(dist));
        Serial.println("cm");

      } else {
        //Serial.println("");
      }
      bool ledState = false;

      if (val == '1' && Serial1.available() > 0)
      {

        Serial1.print(val);
        Serial.print("SENT");
      }

      if (val == '0' && Serial1.available() > 0)
      {

        Serial1.print(val);
        Serial.print("SENT");
      }

      if (val == 'A')
      {
        digitalWrite(ledazul, !digitalRead(ledazul));
        ledState = true;
      }
      if (val == 'B')
      {
        Serial.print("Ping: ");
        int dist = sonar.ping();
        Serial.print(sonar.convert_cm(dist));
        Serial.println("cm");
      }
      if (val == 'C')
      {
        digitalWrite(scLed1, HIGH);
        ledState = true;
      }
      if (val == 'D')
      {
        digitalWrite(scLed2, HIGH);
        ledState = true;
      }
      if (val == 'E')
      {
        digitalWrite(scLed3, HIGH);
        ledState = true;
      }
      if (val == 'F')
      {
        digitalWrite(scLed4, HIGH);
        ledState = true;
      }

      if (val == 'G')
      {
        digitalWrite(scLed5, HIGH);
      }
      if (val == 'S')
      {
        digitalWrite(fan, HIGH);
      }
      if (val == 'O')
      {
        switch (porta)
        {
            if (pos < 90)
            {
            case false:
              porta = true;
              for (int x = 0; x < 90; x++)
              {
                myservo.write(x);
                delay(15);
              }
            }
            break;
        }
      }
      if (val == 'P')
      {
        switch (porta)
        {
            if (pos >= 90)
            {
            case true:
              porta = false;
              for (int y = 90; y > 0; y--)
              {
                myservo.write(y);
                delay(15);
              }
            }
            break;
        }
      }
    }

What happens is, i can toggle ESP led on or off as long as i dont use commands that uses bluetooth module, it works perfectly fine. Now, if i do use bluetooth commands and then esp commands, it'll lose connection with the bluetooth module.

What im looking for is a workaround for the baudrates, because i have a 9600baudrate for the HC-06 and 115200 for the nodemcu, how do i do to fix it?

title: Arduino loses communication with bluetooth when sending commands to nodemcu esp8266

Answers: 0


body:
[![enter image description here][1]][1]There is a mistake in the design implementation of the code probably in if statment - when using the serial monitor it repeatedly shows printf() statements from the code instead of "Sending SMS message".
-----------------

     // Include the GSM library
    #include <MKRGSM.h>
    #include<math.h>
    #include<stdio.h>
    int xp = A5;
    int yp = A4;
    int x,y;
    #include "arduino_secrets.h"
    // Please enter your sensitive data in the Secret tab or arduino_secrets.h
    // PIN Number
    const char PINNUMBER[] = SECRET_PINNUMBER;

    // initialize the library instance
    GSM gsmAccess;
    GSM_SMS sms;

    void setup() {
        x=analogRead(xp);delay(2);
        y=analogRead(yp);delay(2);

      // initialize serial communications and wait for port to open:
      Serial.begin(9600);
      while (!Serial) {
        ; // wait for serial port to connect. Needed for native USB port only
      }

      Serial.println("SMS Messages Sender");
      pinMode(xp,INPUT);
      pinMode(yp,INPUT);

      // connection state
      boolean connected = false;

      // Start GSM shield
      // If your SIM has PIN, pass it as a parameter of begin() in quotes
      while (!connected) {
        if (gsmAccess.begin(PINNUMBER) == GSM_READY) {
          connected = true;
        } else {
          Serial.println("Not connected");
          delay(1000);
        }
      }

      Serial.println("GSM initialized");
    }

    void loop() {
        if ((x>=0.60) & (y>=40))

     Serial.print("AT+CMGF=1\r");
        delay(1000);
        Serial.print("AT+CMGS=\"+491781234567\"\r");
        char remoteNum[20];

      // sms text
      Serial.print("your bike is in danger!");
      char txtMsg[200];

      Serial.println("SENDING");
      Serial.println();
      Serial.println("Message:");
      Serial.println(txtMsg);

      // send the message
      sms.beginSMS(remoteNum);
      sms.print(txtMsg);
      sms.endSMS();
      Serial.println("\nCOMPLETE!\n");
       delay(5000);
       if ((x<=0.30) & (y<=25))

     Serial.print("AT+CMGF=1\r");
        delay(1000);
        Serial.print("AT+CMGS=\"+491781234567\"\r");

      // sms text
      Serial.print("your bike is in danger");
      Serial.println("SENDING");
      Serial.println();
      Serial.println("Message:");
      Serial.println(txtMsg);

      // send the message
      sms.beginSMS(remoteNum);
      sms.print(txtMsg);
      sms.endSMS();
      Serial.println("\nCOMPLETE!\n");
       delay(5000);
    }

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

title: a code problem for arduino GSM 1400 to send a SMS when tilt movment is detected using accelerometer

Answers: 1

body:
Your if statement is broken!
==========================

    if(cond)
       statement; // this is conditional
    statment2; // this will always be executed!

You need to use a code block:

    if(cond)
    {
        statement; // both statments are now
        statement2; // conditional!
    }


body:
Our PCB uses an ATmega2560 chip and uses most of the pins, including some that are not defined in the standard `pins_arduino.h` module, since that module only provides for the pins that are brought out to headers on the Arduino Mega2560 PCB.

We have a modified `pins_arduino.h` module that has all pins defined, but it doesn't get included in the Arduino IDE compile.  It was cataloged in the same directory as the standard module (that we renamed `original`).  The path where the modified module is stored is `C:/Arduino/hardware/arduino/avr/variants/mega`, where the original was also located.

In the sketch, we added `#include "pins_arduino.h"` as well as `#include <pins_arduino.h>`, but neither seemed to have included the modified module, so the extra pins are not accessible.  Putting the module in the same library as the sketch didn't help either.

Any suggestions?

title: Where should a modified "pins_arduino.h" be stored for Arduino IDE compile?

Answers: 2

body:
Add another folder in the /variant folder, and put your modified pins_arduino.h in there.
Then in boards.txt, create another section of lines like the exsting Mega section, use a new board name, and add the path to your new folder.

Adding Megacore to the IDE in a similar manner pretty much does all that for you.

body:
Now have 2560 “full pin definition” working.  This is what I think I did:

1) Download IDE with "Windows ZIP file for non admin install " from https://www.arduino.cc/en/Main/Software

2) Download pins.arduino.h from https://forum.arduino.cc/index.php?action=dlattach;topic=200887.0;attach=60348

3) Open the IDE distribution zip file and extract all files into the location where you want the IDE files and your sketches to reside.  Could be anywhere.

4) Before starting arduino.exe from the extracted files, replace the pins.arduino.h file that came with the IDE, with the "all pins defined" version.  It is replaced in folder path: .../arduino-1.8.5/hardware/arduino/avr/variants/mega/pins.arduino.h

5) Place sketch within the same path as everything else (e.g. create a folder like “12.My_Sketches” inside “examples”). For example, I put my test sketch Blinky-2560 in folder path: .../arduino-1.8.5/examples/12.My_Sketches/Blinky-2560/Blinky-2560.ino

Why it worked this time?  The only difference I can see is I got the new pins file inserted in the right place before running the IDE.  It is also possible the sketch has to be in the same path as the rest of the IDE (saw that somewhere!?!?).  Otherwise I don’t think there was anything else different from what I was doing with the previously installed IDE.

Since the “all pins defined” file is a superset of the standard mega pins.arduino.h file, there is full compatibility with the Arduino ATmega2560 PCB.  It would be great if Arduino would make this fully defined pins file the standard that comes with the IDE.

Never did get MegaCore to upload the sketch after the compile.


body:
Going crazy here trying to connect a keypad to my Arduino. I followed this article [KeypadTutorial][1], but my guess is something is wrong/different because my keypad only has 9 pins and the far left (pin 1) and far right (pin 9) pins have no traces back to the keypad. I bought it years ago and just got around to finding a use for it. It looks just like this one [Arduino Keypad][2] but different with white keys with black font.

The issue is the wrong key shows up (i.e. press 0 and get 9). I used a multi-meter to test for continuity between pins when pressing each key and got results that are kind of stumping me. I would think there would be some kind of pattern (like the first pin would always be a 1, 2, or a 3), but obviously not (or I just have a bad keypad).

    KEY(pin1, pin2)
    1(2,3)
    2(1,2)
    3(2,5)
    4(3,7)
    5(1,7)
    6(5,7)
    8(1,6)
    9(5,6)
    0(1,4)
    #(4,5)
    *(3,4)

  [1]: https://playground.arduino.cc/Main/KeypadTutorial
  [2]: https://www.newegg.com/Product/Product.aspx?Item=9SIABKS5R53527&ignorebbr=1&nm_mc=KNC-GoogleMKP-PC&cm_mmc=KNC-GoogleMKP-PC-_-pla-_-Gadgets-_-9SIABKS5R53527&gclid=Cj0KCQjwjtLZBRDLARIsAKT6fXzKVorcg30K3QoEOKtgkOvHkN-NyKLSswJXBId_fWB205p-hRfRK2MaAqSJEALw_wcB&gclsrc=aw.ds

title: Arduino connected keypad printing wrong numbers

Answers: 1

body:
Transpose the pins for some of the keys and a pattern will emerge.

    KEY(pin1, pin2)      transposed pins
    1(2,3)        x        1(3,2)
    2(1,2)                 2(1,2)
    3(2,5)        x        3(5,2)
    4(3,7)                 4(3,7)
    5(1,7)                 5(1,7)
    6(5,7)                 6(5,7)
    8(1,6)                 8(1,6)
    9(5,6)                 9(5,6)
    0(1,4)                 0(1,4)
    #(4,5)        x        #(5,4)
    *(3,4)                 *(3,4)


body:
I have an Arduino Pro Mini along with a GPS Unit - ATGM336H. Below is the sketch I'm currently using:

    #include <SoftwareSerial.h>
    #include "Ublox.h"
    SoftwareSerial GPS(4,5);
    Ublox serial_gps;

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

    void loop(){
      while(GPS.available()){
      char c = GPS.read();
      if(serial_gps.encode(c)){
      Serial.println(serial_gps.longitude);
        }
      }
    }

I'm able to receive NMEA stream from the GPS Unit and parse (tried TinyGPS++, TinyGPS and Ublox) the stream but the data is not valid nor does it ever change. I've read that this GPS unit can take up to 32 seconds to get a fixed position and deliver valid co-ords but I cannot receive any.

[![Serial Monitor][1]][1]

Is there anything obviously wrong with my sketch or hardware setup?

Any and all help would be greatly appreciated!

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

title: GPS: Not receiving any valid output from ATGM336H

Answers: 1

body:
while(GPS.available() > 0) {....

Also is the GPS unit outside?


body: I received a Adafruit Feather 32u4 FONA as a gift and have read the great, comprehensive document Adafruit put have put together surrounding pinouts, examples etc for the board. I am having issue understanding the section on the KEY pin, I understand that it is used to put the cellular module to sleep, but in order to do this it is mentioned to “cut the trace and wire it to a micro controller pin”. Does this mean that in order to utilize the on/off functionality of the SIM module I have to slightly butcher my new shiny board instead of using the pin directly?

title: Adafruit Feather 32u4 FONA KEY Pin

Answers: 1

body:
Yes, you will need to physically cut the trace to use the on/off feature. This is common on development boards. It could be done with a jumper but that would add cost and/or require a larger board.

You will see on the back of the board there are 2 large pads connected by a thin trace. You can use an exacto knife to cut the trace. To repair the cut you use a blob of solder to bridge the gap between the pads.


body:
I connected my Arduino Uno to an external power supply, but did not noticed the power supply was on 30 V, I saw the part in the picture smoking and immediately pulled the cable out of the Arduino.
now, each time I connect it to some source of power his "ON and "L" light up ("TX" and "RX" are dark) and the ATmega heats up, and it can't receive sketches from my PC. It says just

> Problem uploading to board.

Is my board completely dead or I can somehow save it?

[![The part that smoked is circled][1]][1]

  [1]: https://i.stack.imgur.com/atF54.jpg "The part that smoked is circled"

title: Is my Arduino dead?

Answers: 2

body:
You could try to replace the SMD part, probably a capacitor (I may be wrong), if you can identify which part it is from the [schematic][1] (or any marking on the board).  However, you may have damaged something else as well. You will only know if and once you have replaced the smoking part.

You may be lucky and only that part has been damaged.

The ATmega appears to be socketed so you *could* try removing it and putting it in another undamaged board to see if it works still.

It looks like the smoking part is next to a regulator, `IC2` (I am not 100% sure about that), but that would make sense, seeing as it was a power supply issue that caused the smoking in the first place.  Maybe just the power supply part of the board is damaged (`D1`, `PC1`, `PC2`, `C2`, `IC1` or `IC2` - the two big black and white capacitors, with `47 25V` written on them in your photo are `PC1` and `PC2`), and you could slowly work your way through it, checking and replacing the sequential parts (again with the use of the [schematic][1]).

I wouldn't throw the board away, I have some partially damaged boards that only half function, but the part that still functions will probably suitable for some project or other in the future... or maybe not, depending on the damage.

It is hard to tell from just a photo which being able to check the parts using a multimeter.

Given that the power LED and `L` LED still work, there is some hope. Try using the USB input for power and see if that helps as the circuit is different from that of the power jack (no regulator). See `VIN` AND `PWRIN` versus `USBVCC`, on the [schematic][1].

Here is the power jack circuit:

[![Power jack circuit][2]][2]

Here is the USB input:

[![USB input][3]][3]

However, if, as you say, the PC can not see the Arduino to communicate with it, it will make programming it difficult.

If you *do* have another UNO board, with a removable ATmega IC, program `Blink.ino` on to the ATmega and place it in the damaged board to see if the `L` LED blinks. If it does then at least some of the board still works.

However, to sum up, your Arduino is probably not going to be as useful as it was prior to the over voltage having been applied - unless you are both lucky and replace a few SMD parts.

On the positive side, look at it as a learning experience on how to track down and repair faults on a PCB - a very useful skill to have.

  [1]: https://www.arduino.cc/en/uploads/Main/arduino-uno-schematic.pdf
  [2]: https://i.stack.imgur.com/rfRwC.png "Power jack circuit"
  [3]: https://i.stack.imgur.com/GX5pm.png "USB input"

body:
If the '328P gets hot, it is dead. But, it's replaceable, you can even buy one with a bootloader loaded in already.

The part you circles is a 100nF capacitor, a 10 cents part.

If the PC is not recognizing it when you plug in USB, then the Atmega16U2 that does the USB interfacing is dead. That one is a very small surface mount part that you cannot replace without a hot air rework station, and then you will need a Programmer to reload it with its USB interface program.

And if you killed the 2 regulators, those need replacing too.

Get another board, be more careful next time.
I'd get a 7.5V or 9V wallwart for power. I think you can get the wallwart and a bootloaded '328P from www.dipmicro.com, www.sparkfruit.com, www.adafruit.com, etc.


body:
I'm thinking to connect about 50 slave Arduinos on 1 master using TX/RX. I'm following recommendation of these links:

 - https://arduino.stackexchange.com/questions/14782/im-looking-for-a-way-to-serially-communicate-with-a-multi-mesh-arduino-slave-ne, and;
 -  [Tx/Rx UART communication between 2 MCU over 1 line][1]

using the cathode of diode connected to slaves TX pins and pulling up this line, like [this image][2]:

[![Async multi-drop diode isolation][3]][3]

In [Arduino - Digital Pins][4], when pin is set to input (high impedance), it is "equivalent to a series resistor of 100 MΩ in front of the pin". Slave RX line has input (RX pin) in parallel, then, if this 'equivalent resistor' is true, we have a low resistance (duo parallel configuration) that burn the master TX. Is it make sense?

I have not found either in the Arduino or the ATmega documentation, if TX port have the internal pullup on. In ATmega documentation, TX pin is set as output and RX pin as input. The TTL logic is high on idle, then 5 V must be sourced from somewhere, correct?

  [1]: https://electronics.stackexchange.com/questions/18762/tx-rx-uart-communication-between-2-mcu-over-1-line
  [2]: http://www.sampson-jeff.com/article/interface/as-mdd.gif
  [3]: https://i.stack.imgur.com/MV57T.gif "Async multi-drop diode isolation"
  [4]: https://www.arduino.cc/en/Tutorial/DigitalPins

title: Arduino UART (TX/RX) multidrop 1 master 50 slaves

Answers: 1

body:
An input pin draws 1uA or less input current, so more like 1 Megohm resistor, not 100 Megohm.

In an Uno, the USB interface chip typically is what is pulling the Tx and Rx lines high with 5mA drive (high output thru a 1K resistor to D0 or D1).

What you have drawn should work. The pullup resistor will ensure the Rx into the 1st Arduino sees a nice crisp high when the other two stop pulling the line low as they send a message out, and the diodes will prevent the one driving the line high while the other pulls it low.


body:
So basically I'm trying to create a device where when I push a button it starts a loop. When I push this button again, it stops the loop. Right now I have it logged to serial. It starts up correctly with no output. When I press the button the loop begins and it spits out "toggled on" continuously. When I press the button again... nothing happens. What should happen ideally is that it should stop spitting out "toggled on" and just go back to doing nothing.

    #include <Bounce2.h>

    Bounce bouncer = Bounce();
    const int W = 10;
    bool wOn = false;

    void setup() {
      Serial.begin(9600);
      pinMode(W, INPUT_PULLUP);
      bouncer.attach(W);
      bouncer.interval(5);
    }

    void loop() {
      bouncer.update();
      if (bouncer.read() == LOW) {
        wOn = !wOn;
      }

      if (wOn > 0) {
        Serial.println("toggled on");
      }
    }

title: Arduino - Button to start / stop loop

Answers: 2

body:
If you change your sketch to this one, you'll see the issue:

    const int W = 10;
    bool wOn = false;

    void setup() {
      Serial.begin(9600);
      pinMode(W, INPUT_PULLUP);
    }

    void loop() {
      if (digitalRead(W) == LOW) {
        wOn = !wOn;
      }

      if (wOn) {
        //Serial.println("toggled on");
      }
      Serial.println(wOn);
    }

The button's contacts "bounce" (Google "contact bounce"), sending multiple low to high signals. There are several software solutions that will eliminate this issue. Have a look at: [arduino.cc/en/Tutorial/Debounce][1]. There are a couple of libraries that simplify de-bouncing buttons: [playground.arduino.cc/Code/Debounce][2] and [playground.arduino.cc/Code/Bounce][3]

  [1]: https://www.arduino.cc/en/Tutorial/Debounce
  [2]: https://playground.arduino.cc/Code/Debounce
  [3]: https://playground.arduino.cc/Code/Bounce

body:
Fixed. The solution I used was to add state change checking using `.fell()` which you'll see reflected below. I added state change verification using `Bounce2.fell()`, like so:

      if (bouncer.read() == LOW && bouncer.fell()) {


body:
I am interested in measuring the voltage over an analog pin (`A6`). When I use the Arduino IDE to print the results through the serial I get values around `300`.

Here's the code

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

    void loop(){
       Serial.println(analogRead(A6));
       delay(50);
    }

When I try to run a equivalent program using Processing and interfacing it through Firmata and the corresponding library, I get values around `900`.

Here's the Processing code:

    import cc.arduino.*;
    import processing.serial.*;

    Arduino arduino;

    void setup(){
       arduino = new Arduino(this,Arduino.list()[0], 57600);
       delay(2000);
    }

    void draw(){
      System.out.println(arduino.analogRead(6));
      delay(50);
    }

Does anybody know what could be the issue? I should probably rather trust the values given directly by the Arduino without interfacing, right?

The pin is connected to a circuit with supply voltage.
I also tried reading the values directly using `Serial` in Processing (so without using the `cc.arduino.*` - library) and that showed me the values around `300`. So I guess the difference is caused by the `arduino.analogRead()` method. I am puzzled as to whether that's a bug in the library or something else.

The problem seems to be me not properly initialising the pins. But calling

    arduino.pinMode(6,Arduino.ANALOG);
in the setup method does nothing, as does Arduino.PWM, SERVO and any combination I tried. I thought, maybe Processing tried to assign D6 as analog instead of A6, but changing the value to 20 ([as it's the pin number according to this][1]) simply caused an OutOfBoundsException.

  [1]: https://www.arduino.cc/en/uploads/Main/ArduinoNanoManual23.pdf

title: Why does reading an analog pin give a different results when interfacing with Processing?

Answers: 1

body:
You have not provided a schematic of how the Arduino is wired up.

However, if *nothing* is connected to the pin, i.e. it is not connected to ground or a supply voltage, then the input will float. That means that just by placing your hand near the Arduino, then `analogRead()` will produce a different value than when your hand in not near it.

I would hazard a guess that if you ran *both* sets of code multiple times then you will get different answers each time, if you start waving your hand around the Arduino.

Try that first, and then tie the input to either `HIGH` or `LOW` and then repeat the previous experiment.

In the second case the results should be consistent, and equal in the Arduino and Processing alike.

-----

However, according to your comment, that is **not** your issue, as your inputs are not floating.

I think that issue is actually this:

> Even with Firmata installed, the Processing application needs to define the pin mode for ALL the pins being referenced, telling the Arduino instance that xPin, yPin, and zPin are ANALOG pins.

Source: [Re: Firmata problem with analogRead in Processing Library][1]

Looking at your Processing code the pins are **not** defined. You need to do so.

With the Arduino code, there is no need to define the analogue pins.

  [1]: https://forum.arduino.cc/index.php?topic=53733.msg393176#msg393176


body:
    // defines pins numbers
    const int trigPin = A0;
    const int echoPin = A1;
    // defines variables
    long duration;
    int distance;

    #include <moving.h>
    #include <Servo.h>

    Servo servo;

    moving car(6, 2, 3, 5, 4, 7, 11, 8, 9, 10, 12, 13); // setting up a new RC car with pins EN1, IN1, IN2, EN2, IN3, IN4, EN3, IN5, IN6, EN4, IN7, IN8

    void setup() {
    {
      for (int i=2; i<14; i++)
      {
        pinMode(i, OUTPUT);
      }
      servo.attach(10);
      servo.write(90);
    }
    {
    pinMode(trigPin, OUTPUT); // Sets the trigPin as an Output
    pinMode(echoPin, INPUT); // Sets the echoPin as an Input
    Serial.begin(9600); // Starts the serial communication
    }
    }

    void loop() {
      if (distance) > 10; // this is the problem
      car.set_speed(127);
      car.forward();
      delay(3000);
      if (distance) < 10; // and this
      car.set_speed(0);
      car.forward();
      delay(600);
      car.set_speed(127);
      car.right();
      delay(700);
      car.set_speed(127);
      car.forward();
      delay(700);
    }

title: How will I solve my problem : expected primary-expression before '>' token

Answers: 1

body:
You need curly brackets around your if block.

    if (distance > 10) { // this solves the problem
      car.set_speed(127);
      car.forward();
      delay(3000);
    }

etc
Edit: Thanks to the commenter.


body:
I have a [5 V 3-pin fan][1]. I want to be able to:

 1. power it from an Arduino Uno or a Seeeduino Lotus board, and, ideally;
 2. be able to change its speed.

Most resources I can find on the web explain how to connect a standard 12 V fan and moreover complicate the thing by explaining how to get the speed of a fan or to control multiple fans. This is way too complex for me.

If my understanding is correct, I can't just connect a fan to analog output pins, because the absolute max power per pin is 40 mA (recommended: 20 mA), while the fan uses 100 mA.

Instead, I have to somehow connect two of the three pins of the fan to an external power, and use the third pin to control the speed. Am I supposed to use the ground and 5 V pins situated on the left side of the board above ANALOG IN?

If not, what are my other options? The board is powered by an USB cable, and I see no way to split the power at this level between the board and another device without running a risk of damaging the board.

  [1]: https://noctua.at/en/products/fan/nf-a4x20-5v/specification

title: How do I (easily) power a 5 V 3-pin fan?

Answers: 2

body:
You are correct in your assumption that you can not power a fan from an Arduino directly.

Use a transistor, for example 2N2222 or BC548, which is switched by the Arduino, using a *single* pin, in order to provide sufficient current to the fan.

Such as this simple circuit (note that the 12V supply would be 5V in your case):

> [![Transistor powering a fan][1]][1]

Source: [Driving a PC fan - transistor with or without an optocoupler?][2]1

*However, as chrisl has pointed out, you fan has three pins and not two. The above circuit will only work for a two pin fan. In your case, for the reasons stated in Chrisl's answer, one pin goes to 5 V supply, one to `GND` and then third goes directly to the Arduino - let's say pin 3. Then you can use the code below.*

Assuming that the fan is connected to pin 3, then the code will look like this:

    const int fan = 3;

    void setup() {
      pinMode(fan, OUTPUT);
    }

    void loop() {
      int fanSpeed = 255;
      analogWrite(fan, fanSpeed);
    }

This will run the fan at full blast. However, you can thereafter modify your code to vary the value of `fanSpeed`.

Furthermore, by reading an analog input pin (let's assume that you have a potentiometer hanging off `A0`), using `analogRead()`, you can use the read value to modify the value of `fanSpeed` directly (by dividing the value returned from `analogRead()` by four2 and then sending to `analogWrite()`, like so:

      int potPin = A0;
      fanSpeed = analogRead(potPin)/4;
      analogWrite(fan, fanSpeed);

or even more succinctly, do away with `fanSpeed` completely and use:

      int potPin = A0;
      analogWrite(fan,analogRead(potPin)/4);

---

1 Note that the code in the link in incorrect as it attempts to write values greater than 255 using `analogWrite()`. As stated here, [Arduino reference - analogWrite()][3], `analogWrite()` takes values of `0-255`, whereas `analogRead()` returns values of `0-1023`

2 See the `loop()` function in [Arduino reference - analogWrite()][3] for another example.

  [1]: https://i.stack.imgur.com/M4k00.png "Transistor powering a fan"
  [2]: https://forum.arduino.cc/index.php?topic=90749.0
  [3]: https://www.arduino.cc/reference/en/language/functions/analog-io/analogwrite/

body:
EDIT:

As VE7JRO pointed out the fan you are using does not have a native PWM pin. The third pin is actually reporting back the RPMs of the fan. So you need to follow Greenonline's answer by using a MOSFET. For now I will leave my answer here for reference. If wanted I will delete it later.

---

A 3-pin fan is controlled like a servo. The current for actually driving the motor flows through the power pins (5V and Ground). The third pin takes a PWM (pulse width modulation) signal to determine the wanted fan speed. This is just a signal line, there is only very little current flow, so that the Arduinos pin will not be damaged. So the motor driver is already included.

From the programming side you can use `analogWrite()`, which outputs a PWM signal at one of the PWM-capable pins. The speed of the fan is controlled via the duty cycle of the signal. 100% (value of 255 for UNO) means full speed, 0% (value of 0) stops the motor.

About the power supply: Since your fan uses 100mA at full speed (I assume), it is still possible to power it over the 5V pin of the Arduino. You can source about 500mA over it (including the current for the Arduino itself). When sourcing higher currents over the USB plug, the polyfuse will be fried. This is the value for the UNO r3. A Nano can source only 200mA, because the diode will be fried.

So be carefull how much current you draw from the 5V pin of the Arduino. Or, if you have greater current requirements you have to supply an extra voltage to drive the fan.