body:
For the conductivity meter shown in the photo below, it is a non-NPN sensor for measuring conductivity / impedance.

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

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

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

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

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

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

  [1]: https://i.stack.imgur.com/Qzm8T.png
  [2]: https://i.stack.imgur.com/9O9Qz.jpg
  [3]: https://i.stack.imgur.com/ymrN2.jpg

title: Two-wire Conductivity Sensor and Arduino Hook-up?

Answers: 1

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

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

Cheers!


body:
I am working on a project when I have to enroll and Submit the attendance of the fingerprints.

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

> R305 FingerPrint Sensor having 1000 fingerPrint storage and
> Arduino Uno

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

title: Enroll more than one finger on Unique Id in R305 FingerPrint Module Working With Arduino

Answers: 1

body:
Each fingerprint must have a unique ID that refers to that fingerprint.

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

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

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

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


body:
I have a very simple ISR:

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

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

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

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

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

What is happening here?

title: Why my ISR is giving impossible values?

Answers: 1

body:
The problem is a combination of several causes.

**Assignments are not atomic**

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

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

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

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

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

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

And at machine level you get

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

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

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

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

**You must use volatile**

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

**Critical section**

The rule for using values changed by ISR is simple:

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

**Demo**

This little demo shows you all of this in action.

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

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

    #include "TimerOne.h"

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

    volatile uint32_t toggle = PATTERN_A;

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

    #define PRINT_INTERVAL 60000L

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

     while(!Serial);

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

**Other CPU**

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


body:
I have an Amica ESP8266 NodeMCU I want to send some commands to. I have tried sending some commands like 'AT' and 'AT+CWLAP' but I do not get any sort of output for any command I send to it.

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

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

title: Is an Arduino Uno required to send any sort of command to a NodeMCU?

Answers: 1

body:
With erase_flash you deleted the AT firmware from flash. You can load it back with esptool or with [Flash Download Tool (Windows only)][1].

[AT firmware download page][2]

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

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

  [1]: http://espressif.com/en/support/download/other-tools
  [2]: http://espressif.com/en/support/download/at?keys=&field_type_tid[]=14


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

title: Arduino MQTT Bluetooth

Answers: 1

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

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

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

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

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

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

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

  [1]: https://i.stack.imgur.com/zTSX3.jpg
  [2]: https://i.stack.imgur.com/zCduc.png


body:
I'm new to arduino's and am currently working on a project which requires a lot of different sensors. I was just wondering if its possible to use all the following sensors on a single Arduino Uno:

- 2 Separate Load sensors (i.e giving different readings) controlled with an load cell amplifier
- a Gyro Sensor
- an Accelerometer
- and an ESC

If its not possible, could someone please tell me what hardware I would need to run all these sensors together. Thanks :).

title: Can I support all these sensors?

Answers: 2

body:
It really depends on how many pins each sensor uses. The signal pins of all the sensors used would have to be equal to or less than the total number of I/O pins on the arduino, which would be 20. So you can control 20 sensors if they each have one signal pin.

However, to control more sensors (or use a lower pin count on arduino) you can use multiplexing. See [Two sensors on one input][1] or [MULTIPLEXING WITH ARDUINO AND THE 74HC595][2].

Theoretically, you can control an infinite number of sensors with the use of multiplexing.

  [1]: https://arduino.stackexchange.com/questions/14489/two-sensors-on-one-input
  [2]: http://www.instructables.com/id/Multiplexing-with-Arduino-and-the-74HC595/

body:
Yes, it should work. The HX711 need two pins each (one for clock and one for shifting out the data). The MPU6050 seems to have an I2C interface, which needs two lines (SCL and SDA). And lastly an ESC uses a PWM pin.

All in all this needs 7 pins, way less than an Arduino UNO has.

Note that having enough pins doesn't mean, that you can usw all the sensors at the same time. You might habe to disable one for a short time to do something else.


body:
I'm trying to connect SD card reader to my Arduino. For testing i'm running [CardInfo][1] example.

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

This is my pinout:

    CardReader       Arduino

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

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

Does anyone have any suggestions?

  [1]: https://www.arduino.cc/en/Tutorial/CardInfo

title: Failed to initialise SD card on Leonardo

Answers: 1

body:
A Leonardo has the SPI pins on the ICSP header, not on pins 11, 12, 13.

[![Leonardo pinout][img_l]][link_l]

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

[![Pro Micro pinout][img_pm]][link_pm]

  [img_l]: https://i.stack.imgur.com/c9i7U.png
  [link_l]: http://www.pighixxx.com/test/portfolio-items/leonardo/
  [img_pm]: https://i.stack.imgur.com/uAqD5.png
  [link_pm]: http://www.pighixxx.com/test/2016/07/pro-micro-pinout/
  [pin_def]: https://github.com/arduino/Arduino/blob/1.8.5/hardware/arduino/avr/variants/leonardo/pins_arduino.h#L111-L114


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

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

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

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

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

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

Digital outputs:

CONVST  = Port B, bit 2

SS ADC  = Port B, bit 1

SS SRAM = Port B, bit 0

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

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

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

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

[![Data that I have measured][1]][1]

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

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

Learning points for me were:

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

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

    void loop(){

    switch (statemachine){

    // other cases, including reading serial data from PC

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

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

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

title: Uniform timing when using Arduino for data acquisition

Answers: 2

body:
I did a project [generating VGA signals](http://www.gammon.com.au/forum/?id=11608) that required highly precise timing for the sync pulses.

The technique that worked for me was:

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

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

    EMPTY_INTERRUPT (TIMER1_COMPA_vect);

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

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

See [my page about the ADC](http://www.gammon.com.au/adc) and [my page about interrupts](http://www.gammon.com.au/interrupts).

---

## Automatic mode

Another possibility is to use the automatic ADC conversion, as in this example from [my page about the ADC](http://www.gammon.com.au/adc):

    const byte adcPin = 0;  // A0

    const int MAX_RESULTS = 256;

    volatile int results [MAX_RESULTS];
    volatile int resultNumber;

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

    EMPTY_INTERRUPT (TIMER1_COMPB_vect);

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

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

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

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

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

      }  // end of setup

    void loop () { }

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

---

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

No, I don't think so.

body:
> the ADC is LTC1859 and triggers on the slave select falling edge.

No, it doesn't. Here is a link to [its datasheet][]. It has a pin
labeled CONVST, for “_conversion start_”. According to the section _Pin
functions_, “This active high signal starts a conversion on its rising
edge.”

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

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

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

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

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

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

    // Now transfer the data.
    ...

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

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

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

[its datasheet]: http://cds.linear.com/docs/en/datasheet/185789fb.pdf

[jorisvr]: http://jorisvr.nl/article/arduino-frequency


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

    import processing.serial.*;

    Serial myPort;  // Create object from Serial class

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

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

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

    PFont font;

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

      font = createFont("Courier", 32);

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

       hq = quatAxisAngle(axis, angle);

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

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

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

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

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

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

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

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

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

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

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

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

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

      endShape();
    }

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

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

      buildBoxShape();

      popMatrix();
    }

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

      readQ();

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

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

      drawCube();
    }

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

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

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

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

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

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

      return q;
    }

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

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

      return q;
    }

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

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

      return conj;
    }

title: 'import' does not name type ERROR

Answers: 1

body:
Processing code is intended to be run on a computer. You would use the [Processing IDE](https://processing.org/reference/environment/) to run this code.

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


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

title: Outputs/inputs to Multiple Arduinos in Arduino IDE at once

Answers: 1

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

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

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

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

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


body:
Fair warning: I'm an electronics n00b.

I'm trying to get an Arduino Uno R3 to send data over 9600 baud serial to a Wemos D1 Mini Pro.

What worked (mostly):

Powering (5V) Arduino off a 4 AA barrel jack battery pack.  Measured voltage between Vin and GND as ~4.5V (the batteries were somewhat old).  4.5V is low enough to be safe as 5V input for the (3.3V) Wemos, which can be powered off its 5V pin (it's the input to the board's 3.3V regulator).  I tied the Arduino's GND and Wemos's, took the Arduino's Vin pin to Wemos's 5V pin (providing it ~4.5V), and connected Arduino's TX to Wemos's RX via a voltage divider (a 2.2 kΩ resistor and a 4.7 kΩ; verified <3.3V with a multimeter).

And, everything worked, for a few brief, glorious minutes.  Arduino sent 1 byte over serial every 3 seconds, alternating the builtin LED each time.  Wemos read them and served up a web page showing the latest values.  But, after a few minutes, the Wemos started to read data the Arduino shouldn't be sending (0x00 bytes; the Arduino program was only sending uppercase ascii letters).  I noticed that the Arduino builtin LED, that's supposed to be alternating every 3s, was blinking rapidly.  I think I drained the batteries too far to provide both the Wemos and the Arduino with enough power, and the Arduino got stuck in a boot cycle (and I suppose it's sending 0x00 over its TX pin while booting).

What didn't work:

Since changing batteries frequently would be a pain, I tried plugging the Wemos into a micro USB wall adaptor, and the Arduino into a 12V 1A barrel jack wall wart, and unplugging Arduino's Vin from Wemos's 5V (leaving GND tied together).  Plugged both adaptors into a single power strip, and turned it on.  Both boards powered up, and were running their programs (I could connect to the Wemos over WiFi and it would serve me a page; the Arduino builtin LED was alternating every 3 seconds as expected).  A multimeter read the voltage between Wemos RX and GND as 3.34V, but the Wemos wasn't receiving any serial data.

After that experiment, I switched back to the battery pack, wired Arduino Vin to Wemos 5V again, swapped out 2 of the 4 batteries, and everything works.

TLDR:

I powered a 5V Arduino off 12V and a 3.3V Wemos off 5V, and the Wemos couldn't read serial data being transmitted by the Arduino.  When I powered them both off a 4.8V battery pack, everything worked.  Why didn't it work when they had separate supplies and a common ground?

Sorry for the wordy question; I'm confused enough to not know which details are relevant!

title: Serial communication between two microcontrollers w/ separate power supplies

Answers: 0


body:
I've recently started tinkering with Arduino, and I'm attempting to build a little 2WD robot based on an Arduino Nano.

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

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

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

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

title: Charge 14500 LiFePO4 lithium batteries from an Arduino Nano

Answers: 1

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

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


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

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

    Servo esc;

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

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

    int m = 1;
    int singleShot = 100;

    bool shot = false;

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

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

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

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

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

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

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

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

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

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

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

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

title: AnalogWrite only working for one pin of RGB LED

Answers: 1

body:
You are trying to combine the use of the Servo library and PWM on pins 9 and 10. You can't do both. PWM on pins 9 and 10 uses the same timer as the servo library.

As it states on the [Servo library web page](https://www.arduino.cc/en/Reference/Servo):

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


body:
I need to do a GET request in the form: `user:passw@ip:port/streaming/channels/1/picture`  to capture a still frame from an Ip camera.
Is there a way to do this with the `ESP8266HTTPClient.h` library?

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

title: How to download files from a user/password protected web server (user:passw@ip:port)

Answers: 2

body: use the `http.setAuthorization(user, passw)` method.

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

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


body:
I wanted to run the following code as something similar to Tone or pwm. However for some reason that I am unable to seek it doesn't work.

    #define WAIT 3200UL

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

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

        PORTB &= B11111110; // clear pin 8

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

        PORTB |= B00000001; // set pin 8

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

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

      }
    }

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

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

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

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

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

Appreciate your help.

title: What's wrong with infinite loops inside loop()?

Answers: 2

body:
First

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

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

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

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

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

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

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

you could write:

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

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

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

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

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

    #include <util/delay.h>

    ...
    _delay_us(1.375);

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

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

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


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

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

Greetings

title: UART communication, is it possible to use only the TX line?

Answers: 1

body:
Yes.

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

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

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


body:
I have connected a Bluetooth shield and LCD screen to an Arduino Uno. I have two active low push buttons to increase or decrease the variable `desiredTemp`. This value is meant to be displayed on the LCD screen, and on my smartphone over the Bluetooth serial connection.

This works as intended for my smartphone, however, when my transmission and receive pins are connected to the board the LCD screen is frozen until the pins are removed. Additionally, I'm not able to update the `desiredTemp` variable through the Bluetooth serial connection.

Attached is my code:

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

    #include <LiquidCrystal.h>
    #include <SoftwareSerial.h>

    LiquidCrystal LCD(10,9,3,2,1,0);
    double inIRPin = A0;
    double inThermPin = A1;

    int LED = 4;
    char recvChar;

    int increaseTemp = 7;
    int decreaseTemp = 6;
    int increaseTempState = 0;
    int decreaseTempState = 0;

    #define RxD         13
    #define TxD         12
    SoftwareSerial BTSerial(RxD,TxD);

    double valIR = 0;
    double valTherm = 0;
    double val = 0;
    double temp = 0;
    double const tempRatio = 0.125;
    double desiredTemp = 40; //Degrees Celcius

    void setup() {
     // put your setup code here, to run once:

     pinMode(increaseTemp,INPUT);
     pinMode(decreaseTemp,INPUT);

    pinMode(RxD, INPUT);
    pinMode(TxD, OUTPUT);
    pinMode(LED, OUTPUT);
    setupBlueToothConnection();

    pinMode(inIRPin, INPUT);
    pinMode(inThermPin, INPUT);
    LCD.begin(16,2);
    LCD.setCursor(0,0);

    }

    void loop() {
      // put your main code here, to run repeatedly:
       valIR = analogRead(inIRPin); //IR Sensor Output
      valTherm = analogRead(inThermPin);

       increaseTempState = digitalRead(increaseTemp);
       decreaseTempState = digitalRead(decreaseTemp);

       if(increaseTempState == LOW){
        desiredTemp++;
      }
       if(decreaseTempState == LOW){
         desiredTemp--;
       }
       if(BTSerial.available()){
          recvChar = BTSerial.read();
          Serial.print(recvChar);
          BTSerial.println(desiredTemp);
          if(increaseTempState == LOW){
             desiredTemp++;
             updateLCD();
           }
           if(decreaseTempState == LOW){
             desiredTemp--;
             updateLCD();
           }
           if(recvChar == '1'){
             BTSerial.println("Increasing Temp");
             desiredTemp++;
           }
           if(recvChar == '0'){
             BTSerial.println("Decreasing Temp");
             desiredTemp--;
           }
       }
        updateLCD();
      }

     void setupBlueToothConnection()
     {
        BTSerial.begin(9600);

        BTSerial.print("AT");
        delay(400);

        BTSerial.print("AT+DEFAULT");             // Restore all setup value to
        factory setup
        delay(2000);

        BTSerial.print("AT+NAMESmartCoaster");    // set the bluetooth name
        delay(400);

        BTSerial.print("AT+PIN0000");             // set the pair code to connect
        delay(400);

        BTSerial.print("AT+AUTH1");             //
        delay(400);

        BTSerial.flush();

      }

     void updateLCD(){
          LCD.setCursor(0,0);
          LCD.print("Current Temp:");
          LCD.println(temp);
          LCD.setCursor(0,1);
          LCD.print("Desired Temp:");
          LCD.println(desiredTemp);
          delay(100);
      }

title: When the TX and RX pins for Bluetooth are connected the LCD screen will not update. Why is that?

Answers: 1

body:
You connected the LCD module to serial hardware pins 0 (RX) and 1 (TX).

When you receive the data from the Bluetooth module, through the software serial, you send it to the hardware serial.

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

    if(BTSerial.available()){
          recvChar = BTSerial.read();
          Serial.print(recvChar);
    ...

This messes up the communication with the LCD module. Remove `Serial.print(recvChar);` and it should work.

---

A more sensible solution would be to use hardware serial for the Bluetooth module and the other pins for the LCD module.

Software serial should only be used, if you really can't use the hardware serial, e.g. you need the hardware serial to communicate with another device (a PC or some other module).


body:
Imagine i have a code, that loops, and at one point there is i2c request.

Is loop() paused right away when there is Wire.onReceive() or loop is finished then Wire.onReceive() is called?

title: I2C Interrupting Loop?

Answers: 1

body:
The onReceive callback is called from an interrupt service routine (ISR). As the name says, interrupts are "interrupting" the currently executing code almost immediately. And "almost immediately" means that it only will take a few clock cycles. (This is the reason why changing data in an ISR can corrupt data, since the ISR may change a variable, when the main code tries to read it)

So the Arduino will not wait for the `loop()` function to end. It will interrupt in the line, where it was when the interrupt occured, and return to it after the ISR returns.


body:
I want to transfer image to PC via Arduino leonardo.
OV7670 is non-FIFO, and no SD card connected.
[![enter image description here][1]][1]

I followed this [blog][2] and this [youtube video][3].using this [code][4].
when uplaod, I got errors below:

    Arduino: 1.8.5 (Windows 10), Board: "Arduino Leonardo"
    error: 'ASSR' was not declared in this scope
    error: 'EXCLK' was not declared in this scope
    error: 'AS2' was not declared in this scope
    error: 'TCCR2A' was not declared in this scope
    error: 'COM2A0' was not declared in this scope
    error: 'WGM21' was not declared in this scope
    error: 'WGM20' was not declared in this scope
    error: 'TCCR2B' was not declared in this scope
    error: 'WGM22' was not declared in this scope
    error: 'CS20' was not declared in this scope
    error: 'OCR2A' was not declared in this scope
    error: 'UBRR0H' was not declared in this scope
    error: 'UBRR0L' was not declared in this scope
    error: 'UCSR0A' was not declared in this scope
    error: 'UCSR0B' was not declared in this scope
    error: 'RXEN0' was not declared in this scope
    error: 'TXEN0' was not declared in this scope
    error: 'UCSR0C' was not declared in this scope
    error: 'UCSR0A' was not declared in this scope

I know that error occurred because this code is only for UNO. But mine is leonardo. Changing settings (Tool->board:uno board) was still compiling error.
I have search this [Topic][5] found nothing. I am so confusing, please help.

  [1]: https://i.stack.imgur.com/4O0J6.png
  [2]: http://privateblog.info/arduino-uno-i-kamera-ov7670-primer-ispolzovaniya/
  [3]: https://www.youtube.com/watch?v=8V-XBA2qAKY
  [4]: https://docs.google.com/document/d/1pHX-J7o86kvgr7zaC2tjA3JIkxs5vUgjcNxyGhLMabI/edit
  [5]: http://forum.arduino.cc/index.php?topic=159557.0

title: Arduino leonardo + OV7670 non-FIFO

Answers: 0


body:
I am working with a music shield, I have got my code from this site https://www.waveshare.com/Music-Shield.htm it works fine with arduino UNO but when I try to use it on MEGA it give me errors, Well I found that the problem is with this line

    card.init(SPI_FULL_SPEED,SD_CS_PIN)

in uno `SD_CS_PIN=10` I tried to change it to `53` based on this map

    SPI   Uno   Mega
    SS   10   53
    MOSI   11   51
    MISO   12   50
    SCK   13   52

which is available on https://forum.arduino.cc/index.php?topic=165170.30 but still it returns false. What other options do I have to make it work on `MEGA`?

Thing that I am trying

    #define SD_CS_PIN=10
    #define VS_XRESET A0
    #define VS_DREQ   A1
    #define VS_XDCS   A2
    #define VS_XCS    A3
    void VS10XX::init(void)
    {
      SPI.begin();
      SPI.setClockDivider(SPI_CLOCK_DIV2);
      pinMode(53, OUTPUT);

      pinMode(VS_XRESET, OUTPUT);
      pinMode(VS_DREQ, INPUT);
      pinMode(VS_XDCS, OUTPUT);
      pinMode(VS_XCS, OUTPUT);
      digitalWrite(VS_XDCS, HIGH);
      digitalWrite(VS_XCS, HIGH);

      reset();
    }

In setup I added used this code but still does not work

    void setup()
    {
      Serial.begin(115200);
      pinMode(53, OUTPUT);//setting pin 53 to input
      player.begin();
    }

the error code when I attempt to `init` sd card is `0` which says

    /** timeout error for command CMD0 */

title: card.init(SPI_FULL_SPEED,SD_CS_PIN) returns false for Arduino Mega

Answers: 1

body:
53 is a SS pin if the Mega is SPI slave. Pin 10 is connected to shield to select it as a listening slave. So let the parameter set to pin 10. Additionally on Mega set pin 53 to output, otherwise the Mega can 'fall' into SPI slave mode.

SPI pins 50, 51 and 52 are connected to the ICSP header too. The 6 pin ICSP header is on the same place relative to Uno an Mega common pin headers.

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

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


body:
Hello i am new to NodeMCU (ESP8266) i am building a small program to connect with WIFI (with internet) and if internet is not available i want to process request over IP address.

I am using firebase as a database / server to fetch the status. And process command through a URL like http://192.168.1.223/on?pin=04 if internet is connected then no problem i can update firebase entry, but with same network (LAN) connection over wifi i want to process i need to have static IP. But the concern is i am not able to make this IP address static, and if i make it static then my NodeMCU is not able to connect with firebase.

Here is how my code looks like:

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

    #define FIREBASE_HOST "pushst-56f2c.firebaseio.com"
    #define FIREBASE_AUTH "mhBpzrNyhhwEGwmFxkVFTIEylwrXMw0gm"
    #define PATH "/clients/devicename/watermotor"

    IPAddress ip(192, 168, 1, 223);  //Node static IP
    IPAddress dns(192, 168, 1, 223);
    IPAddress gateway(192,168,1,1);
    IPAddress subnet(255,255,255,0);

    char ssid[] = "MyNetwork";
    char password[] = "Qwert98!!";

    int wifiStatus = WL_IDLE_STATUS;

    ESP8266WebServer server(80);

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

          delay(100);
          Serial.println();
          Serial.println();
          Serial.print("Your are connecting to;");
          Serial.println(ssid);

          WiFi.begin(ssid, password);
          WiFi.config(ip, dns, gateway, subnet);

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

          wifiStatus = WiFi.status();

          if(wifiStatus == WL_CONNECTED){
              digitalWrite(WIFI_CONNECT_LED, LOW);

             Serial.println("Your IP address is: ");
             Serial.println(WiFi.localIP());

             Firebase.begin(FIREBASE_HOST, FIREBASE_AUTH);
             Firebase.set("/clients/devicename/watermotor/name", "Motor");
             Firebase.set("/clients/devicename/watermotor/relay_status", "off");
             Firebase.set("/clients/devicename/watermotor/device_status", "online");
             Firebase.stream(PATH);

             server.on("/on", handleOnRequest); //Associate the handler function
             server.on("/off", handleOffRequest); //Associate the handler function

             server.begin(); //Start the server
          }
          else{
            Serial.println("");
            Serial.println("WiFi not connected");
          }

    }

    void loop() {
        server.handleClient();
        if (Firebase.failed()) {
          Serial.println("streaming error");
          Serial.println(Firebase.error());
          delay(1000);
          return;
        }

        if (Firebase.available()) {
            Serial.println();
            Serial.print("Firebase available");
            Serial.println();
            FirebaseObject event = Firebase.readEvent();
        }
    }

I am not sure if its there is some problem with FirebaseLibrary or its just the ESP8266!

Any suggestions will be helpful, thanks in advance! :)

title: NodeMCU (ESP8266) Defining static IP, stops Firebase processing

Answers: 2

body:
You have wrong DNS server IP address. In your sketch it is the same as the static IP address you assign to esp. Then the name of the firebase host can't be resolved by DNS.

The DNS server is usually the router/gateway.

    IPAddress dns(192,168,1,1)

body:
I also placed the same problem(If I set the static IP means it's not getting internet)But Then I added the DNS "IPAddress dns(192,168,1,1)" for that also it didn't connect to the Internet. But I connected to the Internet after adding the "IPAddress dns(8,8,8,8)".

   This is my Code
```
#include <ESP8266WiFi.h>
const char* ssid = "Varaprasad";
const char* password = "varara";
int red = D6; int green = D7; int blue = D8;
const char* host = "18.221.215.201";
IPAddress staticIP(192,168,1,78);
IPAddress gateway(192,168,1,254);
IPAddress dns(8, 8, 8, 8);
IPAddress subnet(255,255,255,0);
void setup()

{
 pinMode(red,OUTPUT); pinMode(green,OUTPUT); pinMode(blue,OUTPUT);
Serial.begin(9600);
Serial.println();
Serial.printf("Connecting to %s\n", ssid);
WiFi.begin(ssid, password);
WiFi.config(staticIP,dns, gateway, subnet);
while (WiFi.status() != WL_CONNECTED)
{
delay(500);
Serial.print(".");
}
Serial.println();
Serial.print("Connected, IP address: ");
Serial.println(WiFi.localIP());
}
void loop() {
  if(WiFi.status() == WL_CONNECTED){
  WiFiClient client1;
    if (client1.connect(host,80))
      {
         client1.stop();
      analogWrite(red,0); analogWrite(green,1023); analogWrite(blue,0);
      }
      else{
      analogWrite(red,1023); analogWrite(green,0); analogWrite(blue,0);
      client1.stop();
      }
    }
  }
```


body:
I want to give a pause to case 0xFF02FD or at least to break from that case by entering the case 0xFFA25D even if the 1st case not finished, when I press power button wich has hexa code ( 0xFFA25D) I turn On the led and when I press playButton(0xFFA25D ) I turn on the piezoo and turn off the led (as you can see in my code) but I can't get out from that case by pressing powerButton again I should wait till it ends .

    void loop() {
      if (irrecv.decode(&results)) {
        // If it's been at least 1/4 second since the last
        // IR received, toggle the relay
        Serial.println(results.value,HEX);
        irrecv.resume();
      }

      switch(results.value){
        case 0xFFA25D:
          digitalWrite(redPin,HIGH);
          break;

        case 0xFF02FD:
          digitalWrite(redPin,LOW);
          firstSection();

          //Play second section
          secondSection();

          //Variant 1
          beep(f, 250);
          beep(gS, 500);
          beep(f, 350);
          beep(a, 125);
          beep(cH, 500);
          beep(a, 375);
          beep(cH, 125);
          beep(eH, 650);

          delay(500);

          //Repeat second section
          secondSection();

          //Variant 2
          beep(f, 250);
          beep(gS, 500);
          beep(f, 375);
          beep(cH, 125);
          beep(a, 500);
          beep(f, 375);
          beep(cH, 125);
          beep(a, 650);
          delay(500);
          break;
      }
    }

title: how can I break from this case by IRremote even if it's not finished yet?

Answers: 2

body:
Because you only check `if (irrecv.decode(&results))` at the top of `loop()`, that is the only point in your code that you can change your action based on a new IR input.

While not an ideal solution, you could just insert `if (irrecv.decode(&results)) {return;} `in between all `beep()` calls.

    //Variant 1
    beep(f, 250);
    if (irrecv.decode(&results)) {return;}
    beep(gS, 500);
    if (irrecv.decode(&results)) {return;}
    beep(f, 350);
    if (irrecv.decode(&results)) {return;}

and so on.

A better solution would be to avoid re-typing the same code by using loops and functions. You call `beep()` repeatedly with only the note and duration changing. You could put your sequence of notes and durations in an array and writing a new function that calls `beep()` for one element in the array and then increments a pointer to the next note to play. Your `loop()` calls this function and checks to see if there is any IR code ready also.

An even better solution would be to set up a hardware timer to produce regular interrupts and the ISR would check if there is IR data ready and set a global flag that is checked in the program.

body:
You are not asking to simply exit a switch-case statement, but to react to your IR remote button press during the execution of other code. With a normal push button directly connected to the Arduino you would normally do this through an interrupt routine. Maybe the library, that you are using, supports decoding IR signals trough interrupts.

If not, you have one more option:
From your code it seems, that the IR receiving part is non-blocking. This means, that it only executes, if there is really something to receive, else it would let the program execute the rest of the code, not blocking the execution. Then you have to program your piezo code (the code in the `case 0xFF02FD:`) as non-blocking code (maybe using PWM hardware or timer interrupts to output the right frequency and just setting trigger variables in your switch-case statement).

When the piezo code is non-blocking, the decode function of the IR library is executed also during your beep sequence, so your program can react to the results of it.


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

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

This is project 2 of their official arduino projects book called "Spaceship interface". I understand resistors normally reduce voltage so the LEDs don't burnout but here 5v is coming from either digital 3, 4, or 5 and it seems like it goes right into the LED before going through a resistor as it goes back to ground. This makes no sense to me.

title: Why would the resistor be after the LED in this project?

Answers: 4

body:
It does not matter if a resistor is before or after a component, see the circuits below.

The resistor reduces the current, and this is true for the path where the resistor is in (until the interconnections before/after the resistor). In the examples there is only one path.

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

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

<!-- End schematic -->

body:
The resistor is to limit the *current flow* through the LED. A LED *will* burn itself out if given too much current and the maximum Arduino output current is 40 mA per leg (output). A quick calculation of V=I*R where V is 5 Volts, I = 40 mA leaves R = 5/.04 or 125 Ohms. You don't want to pull that much current from the Arduino so using 220 resistors is a safe bet at 22mA current draw per leg.

That 10K resistor keeps pin #2 at the ground potential until the button is pushed. Then the input to pin #2 is 5 Volts.

FWIW - that is an ugly drawing.

body:
Most single or RGB LEDs can't take more than 20mA without risking overheating/burning up. Modern LEDs need as little as 5mA to be really bright.  I use 1K resistors on boards where the LED is being used as an indicator (like Power, or Rx or Tx active, or for the L (SCK activity) LED.  Sometimes 2.2K when 1K seems too bright still.  Depends on the LED. Test first before soldering thinks up.

To calculate a resistor value for a desired current, use Ohms Law, V=IR,
Voltage = current x resistance.  Rearranged, Voltage/current = resistance.

If you know the Voltage, Vf, of the LED when it is on, and you are driving from an Arduino pin that outputs 5V, then:
(5V - Vf)/current = resistor.
With 5mA and say a Vf of 2.5V: (5V - 2.5)/.005A = 500 ohm.

You can determine Vf of an LED by using a 5V source and a 1K resistor. Connect the LED and resistor in series between 5V and Gnd. Measure the voltage across the LED, that is Vf.  5V - Vf = voltage across the resistor, Vr.  5V = Vf + Vr.

If you know the voltage across the resistor, Vr, you can calculate current flow:
Vr/resistor ohms = current Amps.
Say you measured Vr of 2.7V and used a 1K resistor. Then current = 2.7V/1000ohm = .0027A, or 2.7mA.

body:
It doesn't matter where the resistor is located (before and after are meaningless concepts). What is important is that the resistor is in **series** with the LED.

This produces an approximation to a constant current source (I = V/R). The actual current is lower due to the voltage drop across the LED, so is actually I = (V- VLED)/R. VLED varies; red LED is lower ~1.2V  blue significantly higher.

The resistor serves 2 functions; to limit the current from the Arduino and to limit the current through the LED (either to limit brightness or protect the LED)


body:
I made simple 3 red buttons like this:

    #include <SPI.h>

    #include "Adafruit_GFX.h"
    #include "Adafruit_ILI9341.h"
    #include "URTouch.h"

    #define TFT_DC 9
    #define TFT_CS 10
    #define TFT_RST 8
    #define TFT_MOSI 11
    #define TFT_CLK 13
    #define TFT_IRQ  7

    Adafruit_ILI9341 tft = Adafruit_ILI9341(TFT_CS, TFT_DC, TFT_MOSI, TFT_CLK,

    #define t_SCK 3
    #define t_CS 4
    #define t_MOSI 5
    #define t_MISO 6
    #define t_IRQ 7

    URTouch ts(t_SCK, t_CS, t_MOSI, t_MISO, t_IRQ);

    void setup() {

      tft.begin();
      tft.fillScreen(BLACK);

      tft.fillRoundRect (12,15,30,80,5,RED);//50,100,30,80,5,RED
      tft.fillRoundRect (50,15,30,80,5,RED);
      tft.fillRoundRect (88,15,30,80,5,RED);

      delay(500);
    }

And this the part where I need help:

    void loop()
    {
      int x, y;

      while(ts.dataAvailable())
      {
        ts.read();                //-----------> this is the whole thing
        x = ts.getX();
        y = ts.getY();

      }

What I need is, to know how to detect and read the pressure of the button area, so that I can run different tasks.

title: How to detect an read buttons pressure on touchscreen

Answers: 2

body:
I'm not 100% sure what you ask, but I assume you want to perform a task depending on what button has been pressed.

You can do this by checking x and y, e.g.

    switch (x)
    {
    case 0:
       switch (y)
       {
       case 0: // Button (0,0) is pressed)
          perform_task_A();
          break;
       case 1:
          perform_task_B();
          break;
       ... // etc.
       }
       break;
    case 1:
       switch(x)
           // Etc. as above but use different tasks.

Than create for each task a function

    void perform_task_A()
    {
       // Do your code
    }

If you want to change 'functionality' depending on a button press, e.g. assume perform_task_A should read a digit, than create a new switch statement there to read a digit key.

If you want more complicated menu structures/input entering, check into state diagrams to keep track where you are in the UI-flow and act on the current state AND the pressed button.

body:
The `fillRoundRect` function format is `(initial_Xpoint,initial_Ypoint,length,width,corner_radius,color)`

Therefore, you already have the information about the location of the button itself. Next, check if the `x` and `y` value is within the button area.

    void setup() {

      tft.begin();
      tft.fillScreen(BLACK);

      tft.fillRoundRect (12,15,30,80,5,RED);  //button1
      tft.fillRoundRect (50,15,30,80,5,RED);  //button2
      tft.fillRoundRect (88,15,30,80,5,RED);  //button3

      delay(500);
    }

    void loop()
    {
      int x, y, pressedbutton=0;

      if(ts.dataAvailable())
      {
        ts.read();                //-----------> this is the whole thing
        x = ts.getX();
        y = ts.getY();

     if ((x>=12) && (x<=12+30) && (y>=15) && (y<=15+80)) pressedbutton = 1; else
     if ((x>=50) && (x<=50+30) && (y>=15) && (y<=15+80)) pressedbutton = 2; else
     if ((x>=88) && (x<=88+30) && (y>=15) && (y<=15+80)) pressedbutton = 3;
      }

      ...
      ...
      ...
     }


body:
I bought a bunch of the common RC522 boards from some Aliexpress vendor. They (I tried multiple) seem to work at the register read-write level, but they don't seem to execute commands, much less recognise any RFID card.

But the realy weird thing is that the version returns 0X12, which matches neither the rc522 1.0, nor the 2.0, nor the clone that should return 0x88.

I verfied with my scope that the chip indeed answers to the SPI byte 1110_1110 (read register 0x37) with the value 0001_0010. The signal is crips, no clock skew, nice sharp edges.

I tried this with and Arduino Uno, an Arduino Due, using a recent version of the miguelbalboa library. But as I see this on my scope, it can't see how it can be a software problem.

Has anyone seen this, or better: found a solution?

title: rf522 version 0x12

Answers: 1

body: Put a `delay(5)` right after `init()` in `setup()` and firmware readout will work.


body:
I've been struggling in this issue for a long time, I know there are people who have done it.

But, I don't have much experience in C to have the skills to design or develop such complicated functions.

I want to scroll data, e.g. text, chars or numbers just like the nice projects in YouTube about the dot matrix.

Like this one: [How to Make a SCROLLING TEXT Display at Home
][1]

  [1]: https://www.youtube.com/watch?v=e_pY-uGkDFA&t=17s

I know how to display a char, but I don't know how to scroll it. If I try I don't get the results I want.

This is my function for displaying chars:

    void draw(void)
    {
      s=0;
      uint8_t data_shift_buf;
      for (l=0;l<26;l++)            // to print 26 letters
      {
        for (row=1;row<9;row++)     // for 8 matrix rows
        {

            SPI_TX_m16(data = (row<<8) | (Alphabet[s]),4);// trying set data by column
            s++;_delay_ms(300);
        }
      }
    }

title: How to scroll data in LED dot matrix through multiple modules?

Answers: 1

body:
This is the function for my problem.

    void draw(void)
    {
    uint32_t map_buffer=0;int8_t i,k;
    uint8_t data_reg[4] = {0xaa,0xbb,0xff,0xff};      // random data to write
    uint8_t dis_buf[4],no_device,no_col;s=0;l=3;

    for (i=0;i<4;i++)
    map_buffer |= data_reg[i] << i*8;                 // loading data into map_buffer

    for (col=0;col<32;col++)                          // for 8 matrix columns
    {
        map_buffer >>= 1;                            // start shifting the data by 1 pixel
        for (i=0;i<4;i++)
        dis_buf[i] = map_buffer >> i*8;              // loading shifted data into display buffers
        for (i=0;i<4;i++)
        {
            for (row=1;row<9;row++)                 // for 8 matrix rows
            {
                SPI_TX_m(data = (row<<8) | (dis_buf[i]),i);
            }
        }_delay_ms(1000);
    }
}


body:
While this board (listed on ebay as *D1 Mini NodeMcu Lua WIFI ESP-12F ESP8266 WeMos 4M Bytes Development Board Kit*) was powered by usb, I accidentially shorted between the gnd (G) and 5v pins on the left, and some magical smoke escaped.

I can no longer power the device from usb, but it works nicely if I supply it with the right voltage on either the 5V on the left or the 3V3 on the right.

So something has burned between the 5V on the usb and the 5V on the regulator.
I have tried measuring the components with an ohmmeter, and compared it to a working board, but I can measure no difference.

Is one of these tiny components a fuse, or a diode to prevent backwards voltage from board to pc, if the board is powered on the pins?

Or could the short between 5V and GND have caused a track to burn?

[![D1 Mini][1]][1]

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

title: D1 Mini; is there a fuse?

Answers: 3

body: Try measuring with a voltmeter to compare the good board to the bad one. If it is the diode as mentioned in the comments under the question, you should get a different reading on the bad board. It should be fairly easy to replace if you have a soldering iron and a steady hand.

body:
I came here because of a dead Wemos D1 Mini Pro. One which I managed to kill in exactly the same way (shorting out something while trying to measure a voltage - most likely I shorted the 5V and GND as well :) ).

The symptoms were identical - could power the board via 5V or 3V3, but not via USB. And they were solved after replacing the diode - or, more accurately, bypassing it, since I was unable to find an SMD Schottky to replace it with.

I won't tell you the rest of the story (where I first blamed it on the voltage regulator and replaced that), to save myself the embarassment :)

body: I can confirm that the component, which on my Mini clones (which have an almost identical layout) is the tiny black component pictured at the upper left corner of the USB shielding, is a diode and can be blown pretty easily by shorting +5 to Gnd. I did as you Lenne proposed and jumpered it with a tiny wire and recovered the device.


body:
I'm kind of new on the field of Arduino. Although I have a question concerning multiple fan connection on 1 arduino PWM pin. The goal is to connect around 8 to 16 fans on 1 arduino  pwm header pin and control their speeds separately using a potentiometer. As I seen it can be achieved by using transistors. The question is are there any limitations on how many fans can I connect and control seperatly using tranzistors? Can I for example use 16 transistors and control 16 fans seperatly ?

Thank you for your answers in advance

title: Controlling multiple fans using arduino uno

Answers: 2

body:
One PWM pin can control only one fan (or one group of fans). You can't have one PWM pin outputting different values to different fans, since one pin can only have one value. (Yes, there are ways of multiplexing it through time slicing but that is both hard and not a good idea).

You need one PWM per fan if you want individual control of each fan's speed. That means a maximum of 6 fans on an Arduino.

To get more you would either have to use software PWM (which can introduce jitter which may not be a problem with simple fans), or an external PWM controller.  Or add more Arduinos.

If all you want is potentiometer control of the fans you can do it without using an Arduino. A pair of op-amps (it can be a single dual op-amp chip), one acting as a triangle wave oscillator, and the other as a comparator, will generate PWM for you.  Here's an example:

> [![enter image description here][1]][1]
>
> [Image by ElectroBOOM](https://electroboom.com) (watch his videos sometime, they're hilarious)

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

body:
One option for controlling multiple PWM output is to use a I2C PWM Driver (e.g. PCA9685).  It has 16 PWM outputs and is controlled from the arduino with I2C which only requires 2 pins on the arduino.

Tutorial: https://learn.adafruit.com/16-channel-pwm-servo-driver


body:
I am developing a multi-master scenario sketch with the https://github.com/rambo/I2C library, because this library will handle multi-master data collisions.

I created a setup with two Arduino nano's which act both as master and slave.
My sketch works as long as I use only one master. Sending data from one Arduino to the other works fine. The other receives the data.

But when I sequentially try to send data from the second Arduino to the first, I get an error (32). After that even sending data from the initial Arduino results in error 32.

This is the used sketch for both the Arduino's.
The only difference is that I switch the values of rel_address and own_address when programming the seconds Arduino.

Sending data is done by pressing a button on pin 2 (switchPin)

    /**
       atme328 = ATmega328
       SDA --> Pin A4
       SCL --> Pin A5
    */
    #include <I2C.h>
    #include <Wire.h>

    int switchPin = 2;
    int relayOnPin = 3;
    int relayOffPin = 4;

    uint8_t broadcast_address = 0;
    uint8_t own_address = 11; // CHANGE FOR EVERY MODULE!!
    // rel_address = address of relay to switch; SET to own_address if relay is connected to this chip!
    uint8_t rel_address = 10; // CHANGE FOR EVERY MODULE!! SET to own_address if relay is connected to this chip!
    uint8_t rpi_address = 1;

    unsigned long counter = 0;

    void setup() {

       Serial.begin(9600);
       pinMode(switchPin, INPUT_PULLUP);

       pinMode(relayOnPin, OUTPUT);
       pinMode(relayOffPin, OUTPUT);
       // start condition
       digitalWrite(relayOnPin, HIGH);
       digitalWrite(relayOffPin, LOW);

       I2c.begin();
       I2c.timeOut(50);
       // I2c.pullup(true); // done by external 4.7kOhm resistors

       // config Wire library for I2C slave functionality
       Wire.begin( own_address );

       TWAR = (own_address << 1) | 1;  // enable broadcasts to be received!

       // set slave receive callback
       Wire.onReceive( onI2CReceive );

    }

    void loop() {
       counter = counter + 1;
       if (counter == 20000) {
          digitalWrite(relayOnPin, LOW);
          digitalWrite(relayOffPin, LOW);
       }
       if ( digitalRead(switchPin) == LOW ) {
          sendCmd('d', rel_address); // send command to remote relay
       }
    }

    void sendCmd(uint8_t cmd, uint8_t address) {
       uint8_t status = I2c.write(address, cmd); //configure device for continuous mode
       if (status > 0) {
          // error codes at https://github.com/rambo/I2C/blob/master/I2C.cpp
          Serial.print(status, DEC);
          Serial.print('!');
          digitalWrite(relayOffPin, HIGH);
          delay(50);
       } else {
          digitalWrite(relayOnPin, HIGH);
          Serial.print('.');
       }
       counter = 0;
    }

    void onI2CReceive(int howMany) {
       // loops, until all received bytes are read
       while (Wire.available() > 0) {
          digitalWrite(relayOffPin, HIGH);
          Serial.write(Wire.read());
       }
       counter = 0;
    }

What do I need to do to be able to send from two units using this library?
Thanks!

title: Getting error 32 in multi-master I2C sketch with library https://github.com/rambo/I2C

Answers: 2

body:
You cannot use the I2C library and the Wire library at the same time. From the code I guess you wanted the Wire library to do the slaves job and the I2C library to implement the master. But since both libraries use the same hardware, this cannot be divided between them. Combining two libraries for the same hardware isn't that trivial. The I2C library only provides master functionality. So, to reach your goal, you would have to find a library, that provides both master and slave functionality while doing correct bus arbitration (which is the term for correctly handling master data collisions). Or you have to change one of the two libraries yourself, to provide the missing functionality.

And the error you get is defined in `#define MT_SLA_NACK 0x20` in I2C.h (0x20 is equal to 32). This means, that you haven't got an acknowledgement from the slave you have addressed. This suggests, that in your current code only the master functionality is working. (But it may have another meaning considering the interaction of the two libraries on the same hardware)

body:
I ended up removing the I2C library and using a modified version of Wire.
I replaced the twi.h and twi.c libraries in C:\Program Files (x86)\Arduino\hardware\arduino\avr\libraries\Wire\src\utility with those from http://liken.otsoa.net/pub/ntwi/. This implementation adds timeouts to the operations, which prevents a hang-up.


body:
I started to learn Arduino and I want to get an input from user to blink LEDs. I wrote under the void loop() section input codes. After i compiled it and Arduino IDE gave me this: "Arduino:1.8.5 (Windows 10), Kart:"Arduino/Genuino Mega or Mega 2560, ATmega2560 (Mega 2560)"

    C:\Users\Yunus Emre ERYILMAZ\Documents\Arduino\sketch_feb17a\sketch_feb19a\sketch_feb19a.ino: In function 'void loop()':

    sketch_feb19a:27: error: cannot resolve overloaded function 'parseInt' based on conversion to type 'int'

     numBlueBlink=Serial.parseInt;

                 ^

    sketch_feb19a:31: error: cannot resolve overloaded function 'parseInt' based on conversion to type 'int'

     numYellowBlink=Serial.parseInt;

                   ^

    exit status 1
    cannot resolve overloaded function 'parseInt' based on conversion to type 'int'

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

What should i do, how can solve this problem? Thanks.

The code that i wrote:

    int blueLEDPin=9;  // Declaring blue led's pin is 9.
    int yellowLEDPin=10;  //Decllaring yellow led's pin is 10.
    int blueOnTime=250;  // Bue led ontime
    int blueOffTime=250; // Blue led offtime
    int yellowOnTime=250; // Yellow led ontime
    int yellowOffTime=250; // Yellow led offtime
    int numBlueBlink=0;
    int numYellowBlink=5;
    String blueMessage="The blue LED is blinking...";
    String yellowMessage="The yellow LED is blinking...";

    void setup() {
      String wm1 = "Welcome to";
      String wm2 = " My Program";
      String wm3;
      wm3 = wm1+wm2;
      Serial.begin(115200);
      Serial.println (wm3);
      pinMode (blueLEDPin,OUTPUT);
      pinMode (yellowLEDPin, OUTPUT);

    }

    void loop() {
    Serial.println ("How many times do you want the blue LED to blink? ");
    while (Serial.available()==0){ }
    numBlueBlink=Serial.parseInt;

    Serial.println ("How many times do you want the yellow LED to blink? ");
    while (Serial.available()==0){ }
    numYellowBlink=Serial.parseInt;

    Serial.println (blueMessage);
    for (int j=1; j<=numBlueBlink; j=j+1) {
      Serial.print ("   You are on Blink #: ");
      Serial.println(j);
      digitalWrite (blueLEDPin,HIGH);  // Turn first led on
      delay (blueOnTime);  // Wait
      digitalWrite (blueLEDPin,LOW); // Turn first led off
      delay (blueOffTime); // Wait
    }

    Serial.println (" ");

    Serial.println (yellowMessage);
    for (int k=1; k<=numYellowBlink; k=k+1){
      Serial.print ("   You are on Blink #: ");
      Serial.println (k);
      digitalWrite (yellowLEDPin,HIGH); // Turn second led on
      delay (yellowOnTime); // Wait
      digitalWrite (yellowLEDPin,LOW);  // Turn second led off
      delay (yellowOffTime);  // Wait
    }
    Serial.println (" ");
    }

title: cannot resolve overloaded function... error

Answers: 1

body:
The function parseInt is a function and you have to add parameters with ( and ), even when it has no parameters, thus instead of

     numBlueBlink = Serial.parseInt;

you have to write

     numBlueBlink = Serial.parseInt();

See [Serial.parseInt][1] for a reference.

  [1]: https://www.arduino.cc/en/Reference/ParseInt


body:
I am absolutely new at arduino but ok with writing code. I am trying to upload 20 points of interest lat/long as a static file that sits on my arduino. Then I want to use my GPS sensor and a function which uses the haversine formula to constantly measure distance between all 20 points and the GPS data from the arduino and output the distance to the nearest point on an LCD screen.

I cannot figure out how to store and reference that list of GPS points of interest.

title: Is it possible to upload a file with GPS values onto my arduino?

Answers: 1

body:
The Arduino does not have a file system per-se, to which you could upload files, unless you create the code that does that. There is "EEPROM" space on the Arduino processor that can hold 1024 bytes of data and survives power-cycles. That should be sufficient to hold 20 lon/lat pairs of sufficient precision.

As for how to get the waypoint data onto the Arduino, you could transfer them over the serial port from your computer, either by manual entry from your computer over the serial monitor of the Arduino IDE or by writing a script in Python or some other language to read the waypoint file and transmit the data according to the protocol you invented.

There are are also SD Card peripherals you can add to an Arduino, so you could potentially just load the waypoint file onto the SD Card from your computer, and then insert the card into the SD Card reader on the Arduino and have it read the data from there.


body:
I have been working for a while with the **ESP8266** I have a question:

According to the online documentation of GitHub from the [esp8266wifi library][1] I can initialize the WiFi in *Station* mode to (obviously) connect to a nearby AP, I can initialize the station mode in 3 "different ways":

- `WiFi.begin ()`: The module initializes the *Station* mode and connects to the last network that is connected, because the credentials (SSID and Password) are stored in its internal memory (flash?).

- `WiFi.begin (ssid, password)`: The module initializes the *Station* mode and connects to the network with "ssid" and "password".

- `WiFi.begin (ssid, password, channel, bssid, connect)`: The same as the previous one, only that you pass more parameters: the one that interests me is the bssid, which is the **MAC address** of the AP to which I am going to connect.

Now comes the question: if I wanted to use the *last* mode, because I want to make sure that the **ESP** connects **ONLY** to an AP (a kind of MAC filtering), I also have to specify the channel and set the connect parameter? Or I can simply use something like this:

    WiFi.begin ("MyOwnNetwork", "123456789", "00: 1B: 44: 11: 3A: B7")

I can not prove it right now, I do not have the module in my hands.

  [1]: https://github.com/esp8266/Arduino/blob/master/doc/esp8266wifi/station-class.rst

title: Doubt with the library esp8266wifi and Station Mode

Answers: 1

body:
This is the function prototype:

[![Function][1]][1]

Per C++ rules, in order to supply an argument for `bssid`, you have to pass an argument for `channel` as well, but `connect` is optional since it's positioned after your target argument. This should not be a problem though since you can just pass the default value of `channel` (i.e. 0) into the function; the `channel` argument is only relevant if you enter a value between 1 and 13 inclusive.

So your call should basically look like:

    char ssid[] = "ssid";
    char pwd[] = "pwd";
    uint8_t bssid[] = {0x00, 0x1b, 0x44, 0x11, 0x3a, 0xb7};
    WiFi.begin(ssid, pwd, 0, bssid);

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


body:
I am new to Arduino and electronics in general.

I am working on a project where I would ultimately like to power the project from 220V AC (Wall light switch) (I want to replace the light switch with one of my own design).

I will want to feed power to the arduino directly from the 220V connecting wires in the light switch cavity.

This power source is 5V (I know the Arduino needs 9-12V), but I will use a USB connector, wired onto my AC/DC power source, to power the Arduino.

[Power Source][1]

**Ratings:**

    AC85 - 264V or  DC110 - 370V wide voltage input
    DC 5V(+/ -0.2V) 600mA isolated output
    Input Current: 0.0273A/115VAC  0.014A/230VAC
    Input surge current: 20A (230VAC)
    Frequency range: 50/60 Hz
    Operating Temperature: -30 - 70 ℃
    Relative humidity: 20%- 90%
    Rated power: 3W
    Output efficiency: 80%

I don't really know why yet (this is part of figuring that out), but I have the feeling that the arduino would want a linear power source, rather than a switching power source. (Because linear is cleaner power?)

Regardless, I am asking the question as if this power source will do the job, and if not, why not? (Why not a switching PSU) ?

  [1]: https://www.banggood.com/AC-DC-Isolated-AC-110V-220V-To-DC-5V-600mA-Constant-Voltage-Switch-Power-Supply-Converter-Module-p-1088877.html

title: Can I use this power supply with my Arduino?

Answers: 1

body:
Yes, that power supply is ideal for powering an Arduino (an Arduino doesn't care if it's linear or switching, and a linear regulator that goes from 220V to 5V is called a *furnace*, and you don't want one of those...)

**HOWEVER** unless you have a very strange wiring setup in your house, under normal circumstances *there is no 220V supply in the switch*.  You normally have *live in*, *switched live out* and ***NO*** neutral connection.

That means you don't have the connections you need to wire your power supply up to.

By the way: *if you didn't already know that then you are not qualified to mess around with home wiring and you should leave it to the professionals.*


body:
exit status 1
invalid operands of types 'const char [5]' and 'const char [2]' to binary 'operator+'

      String message = "Page not found\n\n";
      message += "URI: " + HTTP.uri() + "\n";
      message += "Method: " + (HTTP.method() == HTTP_GET)? "GET": "POST" + "\n";
      message += "Arguments: " + HTTP.args() + "\n";

title: Why I get error on string concatination?

Answers: 2

body: The operators of the class String apply only for an instance of String. In your expression you concatenate two c-strings "POST" + "\n"

body:
A simple fix is to just move the (const char *)s around a little:

This should compile

      String message = "Page not found\n\n";
      message += "URI: " + HTTP.uri() + "\n";
      message += "Method: " + (HTTP.method() == HTTP_GET)? "GET\n": "POST\n";
      message += "Arguments: " + HTTP.args();
      message += "\n";


body:
Though I've written C/C++ code for a long time, the unseen limitations on how memory was consumed on various MCU and SOC programming platforms have often tripped me up. As I'm about to build up code for my first large project for my NANO boards, which will likely use a fair amount of its resources, I'd like to be better prepared for any surprising and unexpected "gotchas" to look out for.

For example, on another SOC I recently worked on extensively (The Pololu.com wixel) I was very surprised to learn that function/method arguments and auto variables, which I'd normally expect to be stack allocated and recovered when a function returns were in fact permanently allocated for the life of the program! Wow! so on that platform, where I'd normally hate to "overwork" variables or reuse variables after their names no longer make sense, I had to adjust my coding to what I'd normally consider BAD for readability. Not to mention realizing that simple loop variables were better off allocated globally. Yecch!

Can those of you who have run into such unexpected coding issues in the Arduino environment share some "special" guidelines about things like this?

title: memory usage "dos and don'ts"

Answers: 2

body:
As you have noticed yourself, this can be somewhat platform-dependent.
Since you are working on a Nano, my answer will be for the AVR
architecture, when compiled with gcc, the avr-libc, and the Arduino core
library.

First, let me reassure you: this weird behavior you saw of the Wixel
doesn't happen on this platform. Local variables get allocated mostly in
CPU registers, then on the stack.

Now, the first general rule may sound obvious: think twice about what
your program _really_ needs to remember. Also, use each time the
smallest possible data type. The C99 types `int8_t`, `uint16_t` and co.
are useful for this.

Another rule you will often hear on this platform: avoid dynamic
allocation, i.e. `malloc()` and `new`, as quite often you cannot afford
heap fragmentation. Avoid also the `String` class, as it relies on
dynamic allocation. Prefer when possible static allocation, or stack
allocation for small things.

Don't forget to use `const` for constants: with this qualifier the
compiler can often optimize the constants out as immediate operands. For
arrays of constants, use [`PROGMEM`][PROGMEM]. Yes, it's not comfortable
to use, but it can save you lots of RAM. The `F()` macro for printing
constant messages is a special case of `PROGMEM`.

Lastly, be very careful with recursion.

[PROGMEM]: https://www.arduino.cc/reference/en/language/variables/utilities/progmem/

body:
Edgar's got some great tips, and I'll reiterate one before giving a few more:

**avoid dynamic memory allocation**

Don't use malloc. When you're designing a system, budget out your RAM like you do your monthly budget. Make sure you're able to do everything at once.

And a couple other tips:

**global statics**

Make full use of the BSS block; try to block out space for as much as possible in global `static` arrays. You may shudder or scoff at the idea of putting everything at a global level, but embedded is a paradigm shift, with its own set of rules.

Since you'll have so many variables at a global level, `static` helps you to avoid polluting your namespace too much.

**avoid fancy C++ features**

In fact, try to not use C++ at all. C++ takes you "farther from the metal," with its RAII and its constructors and its implicit type conversion... It's much harder to keep a tight inventory of all of your resources when your language does so much behind the scenes. If you really want to use a certain C++ language feature, try to keep the tone of your code more like "C with bits of C++" rather than "C++ shoehorned into an embedded system." That never goes well.

Especially avoid generics/templates, which will eat up lots of your memory. Every time you use a new type with a template in your code, another copy of the template class is compiled into your program, just for that one type. Ever wonder why C++ binaries can balloon to 20, 50, even 100 MB? Templates, man. Templates.

**const**

This keyword should go on as many variables as it can. Keeping this habit will save on both execution time and space consumption. Learn the difference between `const T* foo`, `T* const foo`, and `const T* const foo`.