body:
this is my code that stores the button sequence but it will be great if someone can help me blink the LED sequence an put the micro-controller in play or record mode when desired. Also this code faces some issue as some times it fails to take inputs or takes two inputs at a time:

    int arr[10];
    boolean previous = LOW;
    unsigned long time1 = 0;
    int debounce = 200;
    unsigned long time2 = 0;
    int index_state = 0;
    void setup()
    {
     for(int i = 3;i<6 ;i++)
      pinMode(i,INPUT);
     for(int n=0;n<10;n++) arr[n] = 0;//initialisition
     Serial.begin(9600);
    }

    void loop(){
     boolean mode = digitalRead(3) || digitalRead(4) || digitalRead(5);
     while(mode == LOW) mode = digitalRead(3) || digitalRead(4) || digitalRead(5);//wait here till one of the pushbutton goes high;
     //Serial.println("value");
     if( mode == HIGH && previous == LOW && millis() - time1 > debounce){
     //find out which one is high and store that value in array;
     if(digitalRead(3)) arr[index_state] = 3;
     else if(digitalRead(4)) arr[index_state] = 4;
     else if(digitalRead(5)) arr[index_state] = 5;
     else ;
     //print the value and the index;
     Serial.print(arr[index_state]);
     Serial.print(" Stored in index: ");
     Serial.println(index_state);
     index_state = (index_state + 1) % 10;
     //update value of time1 for button debouncing
     time1 =  millis();
    }

      //update the value of previous button state
      previous = digitalRead(3) || digitalRead(4) || digitalRead(5);

      }


sender: user

message:
How to program a BSFrance LoRA32u4 from Arduine IDE 8.5?

I've bought a BSFrance LoRA32u4 from DIYmall on eBay UK.

https://bsfrance.fr/lora-long-range/1311-BSFrance-LoRa32u4-1KM-Long-Range-Board-Based-Atmega32u4-433MHz-LoRA-RA02-Module.html

I've copied the "bsfrance" directory (from the ZIP) into Arduino/hardware (on 64-bit Ubuntu 16.04).

Staring the Arduino IDE, I've selected the correct board (Tools>>Board>>BSFrance>>LoRA32u4).

I've selected the correct port Tools>>Port>>/dev/ttyACM1 (LoRA32u4).

Verifying a trivial sketch looks fine:

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

    void loop() {
      digitalWrite(LED_BUILTIN, HIGH);   // turn the LED on (HIGH is the voltage level)
      delay(1000);                       // wait for a second
      digitalWrite(LED_BUILTIN, LOW);    // turn the LED off by making the voltage LOW
      delay(1000);                       // wait for a second
    }

Result:

    Sketch uses 4104 bytes (14%) of program storage space. Maximum is 28672 bytes.
    Global variables use 149 bytes of dynamic memory.

The USB device appears in `lsusb` as: `Bus 002 Device 077: ID 239a:800c`.

Clicking install causes a white LED to flicker for around ten seconds, but results in:

    avrdude: error: buffered memory access not supported. Maybe it isn't
    a butterfly/AVR109 but a AVR910 device?
    avrdude: initialization failed, rc=-1
             Double check connections and try again, or use -F to override
             this check.

or:

    Couldn't find a Board on the selected port. Check that you have the
    correct port selected.  If it is correct, try pressing the board's reset
    button after initiating the upload.

or:

    Found programmer: Id = "CATERIN"; type =

or:

    Device code: 0x0d

or:

    .   Software Version = 1.0; Hardware Version =

or:

    An error occurred while uploading the sketch

How do I transfer code onto this board?

(I am new to Arduino, so I may be missing something obvious.  I do have lots of experience programming vanilla ATMEGAs in C without the Arduino IDE.)

--

I have an AVRISP mkII - would burning a new boot-loader help, or just wreck the USB-serial on the device?

sender: assistant

body:
I emailed BSFrance and they were very helpful, coming back with a few suggestions which I could not get to work.

I then tried the Sketch>>Upload Using Programmer with my AVRISPmkII and it worked.  I'm guessing there is a bootloader/Linux issue with the board I bought, and bypassing it let me program the board.

It also works flawlessly with my Mac Mini.


body:
I've had the same problem, but couldn't fix it with the "Upload using programmer".
Instead i sound that the problem was that the serial connection kept dropping after a couple of seconds. My colleague, also on Ubuntu, had the same issue.

This fixed it for me: https://learn.adafruit.com/adafruit-arduino-ide-setup/linux-setup#udev-rules

The board registers as an Adafruit board on my system, and apparently the ModemManager is not too keen on that.

After running first command in the link and restarting, i could upload to the board from Arduino IDE with no errors.


message:
Atmega328P Prescaler to Microseconds

For a bitbanging project I'm working on, I need to measure microseconds as accurately as possible. The function micros() won't work for me here because of the unpredictable times at which it might roll over. I have been using this project by Louis Frigon as an example:

https://web.archive.org/web/20140627135927/http://www.sigmaobjects.com/toyota/

In this document he sets his Atmega8's prescaler value:

    // Timer 0 prescaler = 8 ( 1 count / us )
    TCCR0 = _BV(CS01);
Do I understand that after these instructions, TCNT0 counts up by nearly precise microseconds?
If so, what math could I use to set my prescaler for measuring microseconds? The 328P has a higher clock speed, does that mean I won't be able to do this?

body:
> The 328P has a higher clock speed

The 328P will run at whatever speed you clock it, up to a maximum that
depends on the supply voltage. Most 328P-based Arduinos are clocked at
16 MHz though.

> what math could I use to set my prescaler for measuring microseconds?

You can't. You would have to set the prescaler to 16 if you want the
timer to count microseconds. You can set it to 8 or to 64, but there is
no intermediate setting in between.

Maybe you could leave the prescaler at 8 and count half-microseconds
instead?

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

**Edit**: On the 328P, Timer 0 has _two_ control registers, named
`TCCR0A` and `TCCR0B`. To set it to normal counting mode at `F_CPU`/8,
you have to:

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

    TCCR0A = 0;
    TCCR0B = _BV(CS01);

If you are programming in plain C, the first line is not needed (but it
won't hurt either), as the initial value of `TCCR0A` is zero on reset.
If you are using the Arduino core library (and you write `setup()` and
`loop()` instead of `main()`), then you do need this first line, as the
Arduino core configures Timer 0 for PWM at 977 Hz. But note
that the Arduino core also uses Timer 0 for timekeeping
(`millis()`, `micros()` and `delay()`). Thus you may want to use another
timer.

You could switch to Timer 2 by replacing every “0” with a “2” on
the register and bit names of the two lines above. Then you would also
replace every occurrence of `TCNT0` in the code with `TCNT2`.


message:
Problem with action that should happen in loop(continuously)

I’m using WeMos D1 R2 and latest Blynk library and app. I am also using Arduino IDE 1.6.13. I am trying to read a button from the app, which works fine, but i want to read it continuously. Through the Serial Monitor I can see that the board changes modes as it should. However, even if sensors read values when we get through the first “if” states, the values do not continue to show up in Serial Monitor. I believe that’s happening because it is not working as a loop. Also, the relays are not working(they start as open as they should, but their state never changes), as I believe program freezes at some point.

Here is the code:

<!-- language: lang-cpp -->

    //Start of program
    #include <dht11.h>
    #define BLYNK_PRINT Serial//
    #include <ESP8266WiFi.h>
    #include <Blynk.h>
    #include <BlynkSimpleEsp8266.h>
    #include <NewPing.h>
    #include <SimpleTimer.h>

    #define TRIGGER_PIN2 D4 // Arduino pin tied to trigger pin on the ultrasonic sensor 2.
    #define ECHO_PIN2 D5     // Arduino pin tied to echo pin on the ultrasonic sensor 2.
    #define MAX_DISTANCE2  23// Height of the Water Tank 2 (in centimeters).
    #define DHT11_PIN D6

    char auth[] = "****";
    char ssid[] = "8888";
    char pass[] = "psw";

    int Relay1 = D1;
    int Relay2 = D2;
    int val2 = 0;
    int tankwater1 = 0; //water in tank 1 in liters
    int tankwater2 = 0; //water in tank 2 in liters
    int fieldsize1 = 0; //size of field1 in m^2
    int fieldsize2 = 0; //size of field2 in m^2
    int sensor_pin = D7;
    SimpleTimer timer;
    //NewPing sonar1(TRIGGER_PIN1, ECHO_PIN1, MAX_DISTANCE1); // NewPing setup
    of pins and maximum distance.
    NewPing sonar2(TRIGGER_PIN2, ECHO_PIN2, MAX_DISTANCE2); // NewPing setup of
    pins and maximum distance.

    void setup()
    {
      Serial.begin(9600); // opens serial port, sets data rate to 9600 bps
      Blynk.begin(auth, ssid, pass);
      pinMode(Relay1, OUTPUT); //Setup Relay pin as output pin
      pinMode(Relay2, OUTPUT); //Setup Relay pin as output pin
      //pinMode(led_pin, OUTPUT);
      pinMode(sensor_pin, INPUT);
      digitalWrite(Relay1, LOW);
      digitalWrite(Relay2, LOW);
    }

    void loop()
    {
      Blynk.run();
      timer.run();
    }

    BLYNK_READ(V8)
    {
      Blynk.virtualWrite(8, 23 - val2); // virtualpin 8 distance
    }

    BLYNK_WRITE(V1) {
      int pinValue = param.asInt();

      if (pinValue == 0)
      {
        val2 = sonar2.convert_cm(sonar2.ping_median());
        Serial.println("Irrigation mode is active");
        Serial.println("Water level is at:");
        Serial.println(23 - val2);

        if (digitalRead(sensor_pin) == HIGH)
        {
          if (val2 <= 15) //Water level reaches the Top of the Tank2
          {
            digitalWrite(Relay2, HIGH); //Pump2 off
            delay(500);
          }
          else if (val2 > 15) // Water is empty on the Tank2
          {
            digitalWrite(Relay2, LOW); // Pump2 ON
            delay(500);
            //delay(86400000); one day delay. not suitable for experiment
          }
          else if (digitalRead(sensor_pin) == LOW)
          {
            digitalWrite(Relay1, LOW);
          }
        }
      }
      else {
        Serial.println("Fertilize mode is active. This does nothing now");
        //val3 = sonar2.convert_cm(sonar2.ping_median());
        //tankwater2 = (10-val3)*fieldsize2; //calculation of water in tank2
      }
    }
    //End of program

body:
The `BLYNK_WRITE(V1)` function is only called when a Blynk app widget sends data to your hardware. It does not run in a loop. If you want something to run in a loop, put it in `loop()`.

The `WRITE` aspect is from the point of view of the App, not of your hardware, so your hardware uses `BLYNK_WRITE()` to **receive** information from the app. And it's only called when the app chooses to send that information. For example, when a button in the Blynk smartphone app is pushed.


message:
Why was the Atmega16U2 used on the Arduino UNO as a USB to Serial converter?

This is the first time that I realized that extra SMD IC near the USB port of the Arduino UNO is actually a fully fledged microcontroller, I thought that it was just a USB to Serial converter. Further research into this chip left me with more questions than answers.

First of all, why did Arduino decide to use the Atmega16U2 as a USB to Serial converter? Couldn't they have gone with an FTDI chip instead? I came across this phrase on Quora "The best part is that you can also program and create your own applications on the 16u2 if you have an In-circuit Serial Programmer". How exactly does this work?

What about the two other set of connectors on the board? (other than the two main rows of headers) The ones labeled ICSP and JP2? Is the JP2 for the 16U2? I read that these could be used for burning the code onto the Atmega328P so that it can be modified, but not overwritten. What are any other uses for the 16U2 on the Arduino UNO?

body:
First reason I'd guess is price:

 - [FT232 on octopart][1]: USD2.65 ~ 3
 - [Atmega16U2 on octopart][2]: USD2.12 ~ 2.2

They can probably get much better deals considering that the Atmega328 is also from Atmel (now Microchip).

About the programming:

There are some projects which make the Atmega16U2 into a MIDI device over USB or HID, for example some repos: [1][3], [2][4], [3][5]. I've used the second one I think, and it works fine.

You can program it with an ISP/ICSP programmer such as Atmel ICE(below) or [Arduino ISP][6].

[![enter image description here][7]][7]

Use the ISP pins by the Atmega16U2:

[![enter image description here][8]][8]

  [1]: https://octopart.com/search?q=FT232&start=0
  [2]: https://octopart.com/search?q=atmega16u2&start=0
  [3]: https://github.com/harlequin-tech/arduino-usb
  [4]: https://github.com/ddiakopoulos/hiduino
  [5]: https://github.com/kuwatay/mocolufa
  [6]: https://www.arduino.cc/en/Tutorial/ArduinoISP
  [7]: https://i.stack.imgur.com/rpxZF.jpg
  [8]: https://i.stack.imgur.com/DAqSF.png


message:
Measuring Lithium ion cell voltage used to power Arduino via a boost module

Can I measure lithium ion cell voltage with Arduino ADC which is used to power the same Arduino through a boost module (XL6009)? The output voltage of boost module is 9 volts.

body:
I'm the author of a library called [BatterySense][1] and you can use it to achieve your goal. In the repository Readme you can also find wiring diagrams and usage examples, but to give you a rough idea...

 1. Verify the negative side of your battery has continuity to the GND pin of your Arduino: you need to identify if the boost module is messing the common ground, but if you have continuity then you are fine
 2. Add a connection from the battery positive terminal going into one of the Arduino analog pins
 3. Use the BatterySense library to get the battery voltage and percentage level

  [1]: https://github.com/rlogiacco/BatterySense


message:
IR sensor not incrementing or decrementing inside the loop

My project is automatic room light controller with visitor counter using Arduino.

My project was running correct upto this, but the problem started when we connected GSM module to our project because we have given a limit to the room, so when after limit exceeded using GSM a msg must be sent to the admin.

Actual problem is when a limit exceeds,code is not coming out of loop and when we are trying to increment or decrement no. of persons using IR sensor but its not happening.

Help me which loop i sholud use to send msg automatically

    #include<LiquidCrystal.h>
    #include <SoftwareSerial.h>
    SoftwareSerial mySerial(3, 5);
    char msg;
    LiquidCrystal lcd(13, 12, 11, 10, 9, 8);
    #define in 14
    #define out 19
    #define relay 2
    int count = 0;
    void IN()
    {
      count++;
      lcd.clear();
      lcd.print("Person In Room:");
      lcd.setCursor(0, 1);
      lcd.print(count);
      delay(1000);
    }
    void OUT()
    {
      count--;
      lcd.clear();
      lcd.print("Person In Room:");
      lcd.setCursor(0, 1);
      lcd.print(count);
      delay(1000);
    }
    void setup()
    {
      lcd.begin(16, 2);
      lcd.print("Visitor Counter");
      delay(2000);
      pinMode(in, INPUT);
      pinMode(out, INPUT);
      pinMode(relay, OUTPUT);
      lcd.clear();
      lcd.print("Person In Room:");
      lcd.setCursor(0, 1);
      lcd.print(count);

      mySerial.begin(9600);   // Setting the baud rate of GSM Module
      Serial.begin(9600);    // Setting the baud rate of Serial Monitor (Arduino)
      Serial.println("GSM SIM900A BEGIN");
      Serial.println("Enter character for control option:");
      Serial.println("s : to send message");
      Serial.println();
      delay(100);
    }

    void loop()
    {
      if (digitalRead(in))
        IN();
      if (digitalRead(out))
        OUT();

      if (count <= 0)
      {
        lcd.clear();
        digitalWrite(relay, LOW);
        lcd.clear();
        lcd.print("Nobody In Room");
        lcd.setCursor(0, 1);
        lcd.print("Light Is Off");
        delay(200);
      }
      else
        digitalWrite(relay, HIGH);

      if (count >= 3)
      {
        SendMessage();

        digitalWrite(relay, HIGH);
        delay(100);
        lcd.clear();
        lcd.print("Limit exceeded");
        lcd.setCursor(0, 1);
        lcd.print(count);
        return;
      }
      //else
      //  digitalWrite(relay, LOW);

      if (Serial.available() > 0)
        switch (Serial.read())
        {
          case 's':
            SendMessage();
            break;
          case 'r':
            ReceiveMessage();
            break;
        }
      if (mySerial.available() > 0)
        Serial.write(mySerial.read());
    }

    void SendMessage()
    {
      mySerial.println("AT+CMGF=1");    //Sets the GSM Module in Text Mode
      delay(1000);  // Delay of 1000 milli seconds or 1 second
      mySerial.println("AT+CMGS=\"+918419906897\"\r"); // Replace x with mobile number
      delay(1000);
      mySerial.println("GSM TEST:Limit of the room exceeded");// The SMS text you want to send
      delay(100);
      mySerial.println((char)26);// ASCII code of CTRL+Z
      delay(1000);
      //Serial.end();
    }

    void ReceiveMessage()
    {
      mySerial.println("AT+CNMI=2,2,0,0,0"); // AT Command to recieve a live SMS
      delay(1000);
      if (mySerial.available() > 0)
      {
        msg = mySerial.read();
        Serial.print(msg);
      }
    }

    void Response()
    {
      int count = 0;
      Serial.println();
      while (1)
      {
        if (Serial.available())
        {
          char data = Serial.read();
          if (data == 'K') {
            Serial.println("OK");
            break;
          }
          if (data == 'R') {
            Serial.println("GSM Not Working");
            break;
          }
        }
        count++;
        delay(10);
        if (count == 1000) {
          Serial.println("GSM not Found");
          break;
        }
      }
    }

body:
Check that the GSM module is wired correctly, is setup correctly and that you get a ringing tone when you call that number from a different number.
If that is all okay, write / copy a sketch from one of the many online tutorials that sends an SMS taking all input from the serial monitor of the Arduino IDE. When that is working, transfer that code into the sketch above.
The *return* statement in your code will exit the loop() function within the sketch, but the C code running your sketch will just invoke your sketch again. Also, good practise says it's best not to include a function that is not actually used in the sketch - examples being the ReceiveMessage() and Response() functions.


message:
ATMEGA AVcc pin - low pass filter

I am a newby to the world of electronics and IC chips, and am looking to make an ATMEGA328 based board to monitor 12v batteries. The board will be powered from the batteries being monitored, with a regulated power supply taking 12v input and outputting 5v to the board.
The data sheet for the ATMEGA328 chip says that AVcc should be connected externally to Vcc via a low-pass filter. A bit of internetting tells me the low-pass filter will filter out noise above a specific frequency, and provides links to calculators that show the affect of different resistor / capacitor pairs.

My problem is that, I have no idea what frequencies I need to filter! All / any advice much appreciated.

Further info: voltage measurements will be via voltage divider circuits, amp hour consumption will be via sensors, all of which will be connected to analog pins for ADC conversion.

body:
The filter is only needed if low noise is important to your application.
For monitoring batteries, you probably don't need the accuracy level at
which you would want the filter. For what it's worth, the Arduino Uno
doesn't have such filter: it's AVCC is connected straight to VCC.

If you really want the filter, the exact characteristics are not
critical. The datasheet suggests 10 µH + 100 nF, so this
should be a safe choice.

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

**Edit**: To answer the question in the comment, yes, it is generally
advised to use decoupling capacitors, usually something like
100 nF, even when powered from a voltage regulator.

Notice that both the VCC and the AVCC pins are very close to a ground
pin. Best practice is to use one decoupling cap for each (A)VCC/GND
pair, and to place that cap as close as possible to the pins.


message:
Arduino uno audio output quality improvement

I am new to electronics. I am going to play a sound truck from SD card when user push a button, Well This is very easy and there are lots of methods and codes to play it. the problem is with sound quality. I want to output sound into an speaker using 2.5 mm jack. here the problem appears. Is there any module which outputs Arduinos to speakers?

To me more clear in this tutorial https://www.instructables.com/id/Audio-Player-Using-Arduino-With-Micro-SD-Card/ we can play sound using simple speakers, is it possible to connect it to a higher quality speaker? like those pc speakers using 2.5 mm jack?
In fact I want to get better sound quality than the above tutorial using adrino.
thanks

body:
If a beginner, it is always better to copy then invent.  That said, I would recommend using [this arduino.cc Simple Audio Player tutorial][1].  There are [many different types of Arduino boards][2].  The Arduino Due uses a [Microchip/Atmel SAM3X8E ARM Cortex-M3 CPU][3] which contains at least one [DAC][4].  It is assumed this will produce better sound than the [PWM][5] output of the slower [ATmega328P][6] processor found on an Arduino Uno.

  [1]: https://www.arduino.cc/en/Tutorial/SimpleAudioPlayer
  [2]: https://www.arduino.cc/en/Products/Compare
  [3]: http://ww1.microchip.com/downloads/en/devicedoc/atmel-11057-32-bit-cortex-m3-microcontroller-sam3x-sam3a_datasheet.pdf
  [4]: https://en.wikipedia.org/wiki/Digital-to-analog_converter
  [5]: https://en.wikipedia.org/wiki/Pulse-width_modulation
  [6]: http://www.microchip.com/wwwproducts/en/atmega328p


message:
Running python script using Arduino

I am trying to use Process.h library to run a shell command. Here is my code. I am using Arduino Uno.

    #include <Process.h>
    #include <Bridge.h>

    void setup() {
      // Initialize Bridge
      //Bridge.begin(115200);

      // Initialize Serial
      Serial.begin(115200);

      // Wait until a Serial Monitor is connected.
      while (!Serial);

      // run various example processes
      runPythonFunction();
    }

    void loop() {
      // Do nothing here.
    }

    void runPythonFunction() {

      Process p;        // Create a process and call it "p"
      //p.begin("/usr/bin/python /home/kairos/Arduino/codes/sketch_jan26a/tweet.py");
      p.runShellCommandAsynchronously("/usr/bin/python -U /path/to/tweet.py");      // Run the process and wait for its termination
      //p.run();
      // Print command output on the SerialUSB.
      // A process output can be read with the stream methods
      while(p.available() > 0) {
         char c = p.read();
        Serial.print(c);
      }
      // Ensure the last bit of data is sent.
      Serial.flush();
      delay(300000);
    }

If I do not comment the `Bridge.begin()` line, then in monitor display reverse question marks are displayed. And after commenting that, I am getting some garbage on the serial monitor. Also, my python script makes a new file in the same directory, which runs fine if I run it using a terminal. But if I run it using Arduino code, I am not able to see that new file being generated.

Even using `p.begin()` and `p.run()`it does not run. Nor using `p.runShellCommandAsynchronously()`.

So how can I run that python script?

body:
The Uno cannot run python.

The Bridge library is intended for communication either between the two MCUs of the Yun, or between an Arduino board and the MCU on a Yun shield.

It is literally a Bridge between the two systems - Arduino and the Linux system in the Yun.


message:
Using INT2/3 on Arduino Micro (Atmega32u4)

My project is using almost all the pins on this board and I require an interrupt pin to read radio state (rather than polling). I'm using I2C, so that leaves INT2 and INT3, which are the TX and RX pins for USB/Serial1. According to the documentation, disabling serial, using `Serial.end()`, should allow me to take control of those pins. However, using the pins as interrupt handlers doesn't work. Here is a sample sketch:

    static int ledpin = 13;
    volatile byte state = LOW;

    void func()
    {
      state = !state;
    }

    void setup() {
      Serial.end();

      pinMode(ledpin, OUTPUT);

      // INT2
      pinMode(0, INPUT_PULLUP);
      attachInterrupt(digitalPinToInterrupt(0), func, CHANGE);

      // INT3
      pinMode(1, INPUT_PULLUP);
      attachInterrupt(digitalPinToInterrupt(1), func, CHANGE);
    }

    void loop() {
      digitalWrite(ledpin, state);
    }

This example is mostly copy-pasted from the Arduino website. All the other interrupts work fine, only INT2 and INT3 don't.

Is there a way to use these interrupts?

body:
You problem isn't with your pins or code, but with debouncing the signals. I've changed the "func()" method to read:

    void func()
    {
      static uint32_t lastChange = 0; // Note millis() don't change inside ISR, but can be read
      if (millis() - lastChange > 100)
      {
        state = !state;
      }
      lastChange = millis(); // Set new value
    }

which will ignore spurious interrupts if they occur within 100ms of each other. This solves the issue that you are seeing, I've tested it on an Arduino Micro I have lying around.


body:
    /*
       2019-08-29 Nicola Bernardelli. Going through the ATmega32U4 Datasheet and applying the steps
       to set up the analog comparator on a Pro Micro board.

       While doing this, I understand that the Analog to Digital Converter must be switched off.
       So, if you are needing to stick with ATmega32U4 but also need the ADC (as I do in my current project), you might have to add a
       circuit with a comparator, e.g. LM393 or LM339, instead of using the built-in Analog Comparator.
       Disabling this interrupt and reactivating the ADC has not been added to this sketch.

       Also, a "real" handling of the interrupt-triggered event has not been added and the sketch leaves the possibility of a very fast
       succession of interrupt requests. You might want to check the (currently only one) answer given here:
       https://arduino.stackexchange.com/questions/49195/using-int2-3-on-arduino-micro-atmega32u4

       [I wanted to ask/contribute here https://arduino.stackexchange.com/questions/17480/using-analog-comparator-on-atmega32u4
       (I see that it is 3 years 9 months old but it's still "searchable" on the Internet, which is how I went there. I think that keeping the
       information under that pertinent title is a better option than opening a new thread.)
       So I created an account, but it turns out that I don't have enough "reputation" there to comment, so I wrote into the edit field
       available to give an answer, and that did not work out either:
       "Thank you for your interest in this question. Because it has attracted low-quality or spam answers that had to be removed,
       posting an answer now requires 10 reputation on this site (the association bonus does not count)."
       So... pretty much chessmate. Well... their board, their rules.]
    */

    #include "Arduino.h"

    #ifndef ARDUINO_AVR_PROMICRO
    #error This sketch is meant for the Arduino Pro Micro, it is based on the ATmega32U4 Datasheet and the Pro Micro pinout. \
           You might decide to try it on a different ATmega32U4-based board if the pins choice is OK (please check/change the LED pin number).
    #endif

    #define THIS_BOARD_LED_BUILTIN 17
    #define LED_ON_DURATION 200

    volatile bool analogCompInterruptToggled;
    unsigned long millisLastTrigger;

    void setup() {

      Serial.begin(9600);

      analogCompInterruptToggled = false;
      millisLastTrigger = 0;
      pinMode(THIS_BOARD_LED_BUILTIN, OUTPUT);
      digitalWrite(THIS_BOARD_LED_BUILTIN, HIGH);

      /* As per Atmega32U4 Datasheet starting pag 293 (and linked pages). */

      PRR0 &= ~bit(PRADC); // Disables power reduction for the ADC in order to use the ADC input MUX.

      /*
         ACME in ADCSRB: When this bit is written logic one and the ADC is switched off (ADEN in ADCSRA is zero),
         the ADC multiplexer is connected to the negative input to the Analog Comparator. When this bit is written
         logic zero, the Bandgap reference is connected to the negative input of the Analog Comparator
      */
      ADCSRA &= ~bit(ADEN); /* Switches off the ADC so we can use the Muxer with the Analog Comparator instead of the ADC. */
      ADCSRB |= bit(ACME);  /* With the line above => the ADC multiplexer is connected to the negative input of the Analog Comparator. */
                            /* See table at page 295: ACME 0 or (ACME 1 and ADEN 1) => bandgap ref as the Analog Comparator Negative Input. */

      /*                                        ******** A0 NEGATIVE INPUT ********
         Let's select pin ADC7 = A0 as the negative input to the Analog Comparator, as per pag 295 of the ATmega32U4 DataSheet:
         ACME to 1 done above, ADEN to 0 done above, MUX2..0 to 111.
      */
      ADMUX |= 0b00000111;

      /*                                        ******** D7 POSITIVE INPUT ********
         When this bit is set, a fixed bandgap reference voltage replaces the positive input to the Analog Comparator.
         When this bit is cleared, AIN0 is applied to the positive input of the Analog Comparator.
      */
      ACSR &= ~bit(ACBG); // AIN0 = D7 => positive input of the Analog Comparator

      /* Pages 294-295 of the ATmega32U4 Datasheet. */
      ACSR &= ~bit(ACIC); /* Analog Comparator Input Capture disabled. */

      /* Comparator Interrupt trigger mode. 0-0 => TOGGLE, meaning any change; 1-0 => FALLING; 1-1 => RISING). */
      // ACSR &= ~bit(ACIS1); ACSR &= ~bit(ACIS0); // TOGGLE
      // ACSR |= bit(ACIS1);  ACSR &= ~bit(ACIS0); // FALLING
         ACSR |= bit(ACIS1);  ACSR |= bit(ACIS0);  // RISING

      DIDR1 &= ~bit(AIN0D); /* It's actually the rightmost bit, we could write DIDR1 &= ~1 */
      /*
         When this bit is written logic one, the digital input buffer on the AIN0 pin is disabled. [...]
         When an analog signal is applied to the AIN0 pin and the digital input from this pin is not needed,
         this bit should be written logic one to reduce power consumption in the digital input buffer.
      */

      ACSR |= bit(ACIE);
      SREG |= bit(SREG_I);
      /* When the ACIE bit is written logic one and the I-bit in the Status Register is set,
         the Analog Comparator interrupt is activated. When written logic zero, the interrupt is disabled.
      */
    }

    ISR(ANALOG_COMP_vect) {
      analogCompInterruptToggled = true;
    }

    void loop() {
      // put your main code here, to run repeatedly:
      if (analogCompInterruptToggled) {
        analogCompInterruptToggled = false;
        digitalWrite(THIS_BOARD_LED_BUILTIN, LOW);
        millisLastTrigger = millis();
        Serial.print("toggled - millis() == ");
        Serial.println(millisLastTrigger);
      }
      else if (millis() > millisLastTrigger + LED_ON_DURATION) {
        digitalWrite(THIS_BOARD_LED_BUILTIN, HIGH);
      }
    }


message:
Play .Wav sound only once on switch change

I have a project where if you change the value of the spdt switch the colour of the LEDs change. As well as this a .wav file plays. The problem is I only want the .wav to play once. At the moment it constantly plays over and over as it's within the loop. I've tried using a mute or disabling the pin after the play through but I am unable to re-enable so I scrapped it. I deally I want to keep the SPDT switch due to asthetics instead of a push switch. This is my code:

    #include <TMRpcm.h>
    #include <SD.h>
    #define SD_ChipSelectPin 10
    #include <SPI.h>

    TMRpcm tmrpcm;

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

    tmrpcm.speakerPin=9;
    Serial.begin(9600);
    if(!SD.begin(SD_ChipSelectPin))
    {
      Serial.println("SD fail");
      return;
    }
         tmrpcm.setVolume(6);
         tmrpcm.play("1.wav");
         while (tmrpcm.isPlaying()) {
         delay(1);
    }
         tmrpcm.setVolume(6);
         tmrpcm.play("3.wav");
    //set the switch input, pin 8, as an
    pinMode(8, INPUT);

    //set both the LED pins, pin 5 and 6 as OUTPUTs
    pinMode (5, OUTPUT);
    pinMode (6, OUTPUT);
     delay(1000);
    }

    void loop()
    {
     int switchValue = digitalRead(8);
     if (switchValue == 1)
    {
       while (tmrpcm.isPlaying()) {
       delay(1);
    }
      tmrpcm.setVolume(6);
      tmrpcm.play("4.wav");
      digitalWrite(5,HIGH);
      digitalWrite(6,LOW);

    }
    else
    {
       while (tmrpcm.isPlaying()) {
       delay(1);
    }
       digitalWrite(6,HIGH);
       digitalWrite(5,LOW);
       tmrpcm.setVolume(6);
       tmrpcm.play("5.wav");

    }
    }
how can I make the wav play once but when the switch changes?

body:
Make a variable to hold the "last state" of the switch. Compare that *last state* to the current state as obtained by `switchValue = digitalRead(8)`.

Only call the play function if the old value and the current value are different.


message:
Arduino controlled relay for certain duration of time

I am using a relay on my Arduino Uno and i want it to be on LOW for a calculated interval of time, let's say ftime=7 seconds, and after that i need it to be set as HIGH (no power through relay). My code below makes no changes to the relay state. How would that be possible? I tried to use "delay()" too (which i know that is generally a bad idea), but had no success.

     unsigned int interval = ftime*1000; //ftime in ms
    do
      {
      digitalWrite(Relay1, LOW);
      }
      while(timeElapsed < interval);
    digitalWrite(Relay1, HIGH);

Also, if i try without:

    digitalWrite(Relay1, HIGH);
relay is LOW (motor running) but it never returns to HIGH obviously.

body:
you need to update the timeElapsed variable inside the while loop:

     unsigned int interval = ftime*1000; //ftime in ms
     unsigned long startTime = millis();
    do
      {
          digitalWrite(Relay1, LOW);
          timeElapsed = millis() - startTime;
      }
      while(timeElapsed < interval);
    digitalWrite(Relay1, HIGH);

Another way is to create a state machine make `startTime` a global and update the logical state (and the pin) when the time is elapsed.

    unsigned long startTime;
    bool relayLOW = false;

    void loop(){

        if(relayLOW && millis() - startTime > interval){
            digitalWrite(Relay1, HIGH);
            relayLOW = false;
        }
        if(!relayLOW){
            bool closeRelay= //decide if relay needs to be triggered
            if(closeRelay){
                startTime = millis();
                digitalWrite(Relay1, LOW);
                relayLOW = true;
            }
        }
    }


message:
Update button state in Blynk app through the code

I'm using Blynk along with a WeMos D1 R2 and i can change modes through an ON/OFF button.

I can succesfully change mode and make my application go from mode 1 (irrigation) to mode 2 (Fertilization), but through the code i manage to switch from mode 2 to mode 1(after my code does what it is meant to do).

However, i cannot make the button show up as being in mode 1 again, if the application is working properly in mode 1. Any ideas on how to update button condition?

My code follows(below the code you can see the app and the button Using the V1 virtual pin):

    void setup()
    {
      Serial.begin(9600);             // opens serial port, sets data rate to 9600 bps
      Blynk.begin(auth, ssid, pass);
      pinMode(Relay1, OUTPUT);        // Setup Relay pin as output pin
      pinMode(Relay2, OUTPUT);        // Setup Relay pin as output pin
    //pinMode(led_pin, OUTPUT);
      pinMode(sensor_pin, INPUT);
      digitalWrite(Relay1, LOW);
      digitalWrite(Relay2, LOW);
      digitalWrite(Relay1,HIGH);
      digitalWrite(Relay2,HIGH);

    }

    BLYNK_READ(V8)
    {
      Blynk.virtualWrite(8,level);    // virtualpin 8 distance
    }

    BLYNK_WRITE(V1)
    {
      pinValue = param.asInt();
    }

    BLYNK_READ(V5)
    {
      Blynk.virtualWrite(5,RH);       // virtualpin 8 distance
    }

    BLYNK_READ(V6)
    {
      Blynk.virtualWrite(6,temp);     // virtualpin 8 distance
    }

    void loop()
    {
      Blynk.run();
      timer.run();
      if (pinValue==0)
      {
        // some code here
      }
      else //(digitalRead(sensor_pin) == 1)
      {
        // some other code
      }}

    else {
      // a lot of code here
      pinValue=0;                     // here i set pinValue to 0 again in order to return to mode1
    }
    }
    BLYNK_READ(V1)
    {
      Blynk.virtualWrite(1,pinValue); // virtualpin 1 state
    }

    //End of program
[![The button in the app][1]][1]
[![Button is on top left][2]][2]

  [1]: https://i.stack.imgur.com/fcNDDm.jpg
  [2]: https://i.stack.imgur.com/OAU8Um.jpg

body:
`BLYNK_READ()` is documented as:

> BLYNK_READ(vPIN)
>
> BLYNK_READ defines a function that is called when device is requested to send it’s current value of Virtual Pin to the server.

That means it is called when the app or the Blynk server requests a state from the hardware/sketch, such as when the app first connects or reconnects to the Blynk server, or when the hardware reconnects to the Blynk server due to some network problem.

But if you just want to update the virtual pin `V1` at an arbitrary time in your sketch, just call:

    Blynk.virtualWrite(V1, pinValue);

at the point in your code where you want to "change" the button's current state. Not in the `BLYNK_READ()` function, but in your main code, such as:

    [...]
    else {
      // a lot of code here
      pinValue=0; //here i set pinValue to 0 again in order to return to mode1
      Blynk.virtualWrite(V1, pinMode);
    }
    [...]


message:
Does the Arduino Yun have to be powered exactly at 5V?

I'm working on a senior project and I am using a ATX PSU to supply power to the Arduino Yun and other components. If I'm not mistaken, its powered through the usb. I took a usb cord, strip the sheath and put the proper connections on the breadboard and connected the red wire from the PSU to the breadboard as well. When I measure it, the voltage is 5.1V max. I'm scared to hook it up to the Arduino since I read that if its above 5, it will fry it. Is this voltage fine? If not, will I have to put resistors on it to get it down?

body:
It is fine. That is only 2% too high. The microcontroller is the ATmega32U4 and it can have 5.5V. The wifi module runs at 3.3V, and it has a voltage regulator. Some voltage is also lost in the cable. If the voltage is 6V, then you are in the danger zone, but not with 5.1V.

There are clones and shields of the Arduino Yún. Each has its own power supply demands. You should read what the specifications are for your board. The official Yún board requires 5V from the USB cable or 5V at the VIN pin.


body: I would avoid directly powering any micro without voltage regulation. Things like zener diodes and dedicated regulators adds complexity. But you can pretty much power it off any positive rail at or above 5v DC.(Use nothing greater than the specs) They can also be had and implemented for very little, that and they are used on the UNO board.


message:
Constants within array of structs causes strange compiler errors?

In my sketch I have the following:

    #define HU_ADDR                 0x190;
    #define ALL_AUDIO_ADDR          0x1FF;
    #define MY_ADDR                 0x360;
    #define UNKNOWN_ADDR            0xFFF;

    typedef byte MessageID;
    enum {
      ACT_UNKNOWN,
      ACT_POWERON,
      ACT_POWEROFF,
      ACT_PASSIVEOFF_0,
      ACT_PASSIVEOFFRARE_0,
      ACT_PASSIVEON_0,
      ACT_KEYTURN,
      ACT_PRESSDISC
    };

    struct MessageDef {
      MessageID ID;
      word MasterAddr;
      word SlaveAddr;
      byte PayloadLength;
      byte Payload[20];
      char Description[20];
    };

    MessageDef MessageTable[] = {
      {ACT_POWERON,           HU_ADDR, UNKNOWN_ADDR, 13,  {0x00, 0x60, 0x31, 0xF1, 0x01, 0x01, 0x81, 0x00, 0x03, 0x01, 0x00, 0x00, 0x00},                   "On call"},
      {ACT_POWEROFF,          HU_ADDR, UNKNOWN_ADDR, 13,  {0x00, 0x60, 0x31, 0xF1, 0x00, 0x00, 0x81, 0x00, 0x03, 0x01, 0x00, 0x00, 0x00},                   "off?"},
      {ACT_PASSIVEOFF_0,      HU_ADDR, UNKNOWN_ADDR, 3,   {0x00, 0x11, 0x01},                                                                               "Passive: Weak"},
      {ACT_PASSIVEOFFRARE_0,  HU_ADDR, UNKNOWN_ADDR, 4,   {0x00, 0x11, 0x01, 0x20},                                                                         "Passive: Strong"},
      {ACT_PASSIVEON_0,       HU_ADDR, UNKNOWN_ADDR, 16,  {0x00, 0x74, 0x31, 0xF1, 0x80, 0x13, 0x10, 0x10, 0x10, 0x10, 0x10, 0x00, 0x00, 0x00, 0x03, 0x03}, "On response"},
      {ACT_KEYTURN,           HU_ADDR, UNKNOWN_ADDR, 11,  {0x31, 0x62, 0x31, 0xF1, 0x00, 0xF8, 0xFF, 0xFF, 0xFF, 0xFF, 0x00},                               "Key turned"},
      {ACT_PRESSDISC,         HU_ADDR, UNKNOWN_ADDR, 4,   {0x00, 0x62, 0x31, 0x9F},                                                                         "DISC pressed"}
    };
When I compile this, for some reason the Arduino IDE points at the first line and says "expected '}' before ';' token". If I replace the text like so:

    #define HU_ADDR                 0x190;
    #define ALL_AUDIO_ADDR          0x1FF;
    #define MY_ADDR                 0x360;
    #define UNKNOWN_ADDR            0xFFF;

    typedef byte MessageID;
    enum {
      ACT_UNKNOWN,
      ACT_POWERON,
      ACT_POWEROFF,
      ACT_PASSIVEOFF_0,
      ACT_PASSIVEOFFRARE_0,
      ACT_PASSIVEON_0,
      ACT_KEYTURN,
      ACT_PRESSDISC
    };

    struct MessageDef {
      MessageID ID;
      word MasterAddr;
      word SlaveAddr;
      byte PayloadLength;
      byte Payload[20];
      char Description[20];
    };

    MessageDef MessageTable[] = {
      {ACT_POWERON,           0x190, 0xFFF, 13,  {0x00, 0x60, 0x31, 0xF1, 0x01, 0x01, 0x81, 0x00, 0x03, 0x01, 0x00, 0x00, 0x00},                   "On call"},
      {ACT_POWEROFF,          0x190, 0xFFF, 13,  {0x00, 0x60, 0x31, 0xF1, 0x00, 0x00, 0x81, 0x00, 0x03, 0x01, 0x00, 0x00, 0x00},                   "off?"},
      {ACT_PASSIVEOFF_0,      0x190, 0xFFF, 3,   {0x00, 0x11, 0x01},                                                                               "Passive: Weak"},
      {ACT_PASSIVEOFFRARE_0,  0x190, 0xFFF, 4,   {0x00, 0x11, 0x01, 0x20},                                                                         "Passive: Strong"},
      {ACT_PASSIVEON_0,       0x190, 0xFFF, 16,  {0x00, 0x74, 0x31, 0xF1, 0x80, 0x13, 0x10, 0x10, 0x10, 0x10, 0x10, 0x00, 0x00, 0x00, 0x03, 0x03}, "On response"},
      {ACT_KEYTURN,           0x190, 0xFFF, 11,  {0x31, 0x62, 0x31, 0xF1, 0x00, 0xF8, 0xFF, 0xFF, 0xFF, 0xFF, 0x00},                               "Key turned"},
      {ACT_PRESSDISC,         0x190, 0xFFF, 4,   {0x00, 0x62, 0x31, 0x9F},                                                                         "DISC pressed"}
    };
Then it compiles with no complaints.
....what? Why? Aren't these functionally identical? Why does the compiler care if I use HU_ADDR instead of 0x190?

body:
Don't put a semi-colon at the end of #define.

Whatever comes after `#define NAME` will be used to replace NAME across the source code.


message:
Decreasing Arduino pro micro power consumption

I'm working on a project that involves sending GPS coordinates wirelessly from an arduino board to another one. I was thinking of using an arduino micro for this task. The problem is that I want it to last as long as possible on a lithium battery. I searched and found too many tutorials on how to decrease arduino pro mini power consumption, but I didn't find anything related to the arduino pro micro. So I was thinking, does the same procedure used to decrease the arduino pro mini consumption apply for the arduino pri micro?
Also, what microcontroller do you suggest for this project? (PIC, Arduino mini, micro, nano...)

body:
> **Bringing Down power consumption by taking the LED out and lowering the
> clock ?**

Yes, you can do that! And you are okay with Arduino unless you want to complicate things more...If you want to check out other methods then you can check out the Microcontrollers Schematics and also the datasheets of their Components...


message:
Increasing number of iterations not increasing time

I am using Arduino Uno with Atmel Atmega328. I am using `micros()` function in Arduino IDE to measure time taken for execution. Here is my code:

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

    void loop() {
        unsigned long a = micros();
        for (unsigned long j = 0; j < 100; ++j);
        Serial.println ((micros() - a));
        delay(1000);
    }
The output comes as `4`. But if I increase the number of iterations in the for loop to say around `1000000000` it still shows that for loop takes same time of `4`. Is there a function which I can use to measure time properly in arduino?

body:
The compiler has realized that your loop doesn't do anything useful and therefore optimized the whole thing away. Thus you are just timing how long it takes to do nothing. (You didn't get a result of zero, because calling `micros` will itself take time).

BTW, the granularity of `micros` is 4 µs, so you won't get a reading of 1 or 2. The code actually probably only took a couple of microseconds.

You need to do something that the compiler thinks "does something", like this:

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

    volatile byte b;

    void loop() {
        unsigned long a = micros();
        for (unsigned long j = 0; j < 100; ++j)
          b++;
        Serial.println ((micros() - a));
        delay(1000);
    }

By making `b` volatile the compiler cannot decide that `b` isn't doing anything useful, so now the timings make sense.

I got 72 for 100 iterations and 144 for 200 iterations.

---

> Is there a function which I can use to measure time properly in arduino?

Your time measurement is fine. Your interpretation of the results indicates you didn't realize how smart the compiler is. :)

---

You can see what the compiler did if you examine the generated code:

        unsigned long a = micros();
      d8: 0e 94 d2 00  call 0x1a4 ; 0x1a4 <micros>
      dc: 6b 01        movw r12, r22
      de: 7c 01        movw r14, r24
        for (unsigned long j = 0; j < 100; ++j);
        Serial.println ((micros() - a));
      e0: 0e 94 d2 00  call 0x1a4 ; 0x1a4 <micros>
      e4: ab 01        movw r20, r22
      e6: bc 01        movw r22, r24

As you can see, between the two calls to `micros` there isn't any sort of loop.

To find the assembled code you can follow the steps documented [here](http://www.gammon.com.au/tips#info1).

Basically, turn on "verbose compiling" which will show near the end of the verbose output the full pathname of the ".elf" file. Then use a command (terminal) window to enter this command:

    avr-objdump -S xxx.elf

You may want to redirect the output to a file:

    avr-objdump -S xxx.elf > myfile.txt

Depending on how the Arduino IDE was installed you may have to find the pull pathname of `avr-objdump` and use that instead of just the program name.


message:
Does the Arduino pro-micro 3.3v use an 8MHz crystal or a 16MHz crystal with a clock divisor of 2?

I am trying to convert some 5v Leonardo-compatible boards to run at a lower 3-3.7v voltage, so that I can power my project using LiPo batteries.

As far as I can tell, the default Leonardo settings (and pro-micro settings) will not run at this voltage. When I power the boards (which expect 5v) from a lithium battery, typically the system does not start at all. My two theories are that either the 16 Mhz xtal oscillator does not start resonating, or that the brown-out detection of the boards precludes booting at the lower voltage.

I would like to modify the boards to run on lower power. Since the pro-micro exists in a 3.3v variant, I presume there is some way to get the Atmega32u4 chip working at lower voltages. I have reviewed the Atmega32u4 datasheet and schematics from sparkfun, as well as examined the fuse bit differences between the 3.3v and 5v versions of the pro micro. As far as I can tell, the only difference in configuration is the brown-out detection. The clock source settings are configured for a crystal between 8Mhz and 16Mhz, so this could be the same for both boards.

I wasn't quite able to understand the build system for the Catarina bootloader, which might give hints as to how the clock is handled. It seems like both the 3.3v and 5v boards bootloaders are built from the same source, but with a different "CPU frequency" variable. However, there are quite substantial differences in the .hex file outputs and I wondering if there is something fancier going on.

As far as I can tell, it's possible to get an 8MHz clock on the Atmega32u4 either by using a 16MHz xtal with a clock divisor of 2, or using an 8MHz xtal with a clock divisor of 1.

Since the pro-micro 3.3v is the "mainstream" supported board using the Atmega32u4 at a lower voltage, I would like to configure my project to be compatible. Which means I need to build in a compatible clock source, if possible.

Does anyone know more details of the pro-micro 3.3v/8Mhz configuration that might help clarify how to set this up?

body: On the schematic of the Sparkfun Pro Micro 3.3V/8 Mhz (here) a resonator of 16 MHz is drawn. But also is stated there: "Board is marked with combination of resonator frequency and regulator voltage". From this you can deduct that the 3.3V/8MHz and the 5V/16MHz versions don't have the same resonator and that the 3.3V/8MHz version most probably has a 8MHz resonator.


message:
Relay active low and ESP8266 GPIO pins

I am using a ESP8266, specifically the ESP-12-E :

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

I have a Relay, SRD-05VDC-SL-C connected to GPIO pin 4.

It is wired in Normally Open(with my device to be powered wired into the top and middle pins counting from the top to the bottom of the picture below):

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

In my arduino code when I issue:

      pinMode(4, OUTPUT);

This seems to pull the pin LOW, which is the active state of the relay, powering it, which turns my device on before my control code has even had chance to run. I want to get the pin for output but keep it floating.

How do I setup my pin for output, but leave it 'floating' from code, or keep it high / floating, so that I have to explicitly issue:

    digitalWrite(4, LOW);

Before low is sent to activate my relay?

Hope this makes sense!

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

body:
The answer thanks to Trevor_G was:

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


message:
How to use the HC-05 properly?

It all started when I was working on my Arduino project, which involves an Arduino Nano, an HC05 module and a bunch of sensors (DHT 11, soil moisture and LDR) with Blynk App. Everything worked as it should (compiled properly) but there was no transfer of data (HC05 was paired).

At that time before pairing, the HC05 was blinking rapidly and after pairing it was blinking twice rapidly every 5 seconds. **Note** I connected everything as the example said... (You know HC05s TX RX to HW Serial Pins vice-versa).

So later I tried again with everything stripped out (took out all sensors and just the barebones sketch) and added the button widget in the app to control the Nano's onboard LED). Again everything worked as it should but there was no connection between the HW and the Blynk APP (it was not switching on the LED).

Then I tried with an another Bluetooth app and it didn't work as it should. Then I got to know something's wrong with the board itself. So I tried to boot it into AT command mode with this [Guide][1]. But it wasn't accepting any commands (NO replies).

So what do I do?

**NOTE:** I didn't get any relevant question so sorry for that. And do you need anything else?

**Edit:** It worked. I dont really know how. I think there was maybe a problem with the voltage divider but not sure. Thanks for your time and answers.

  [1]: https://roboindia.com/tutorials/arduino-hc-05-at-mode

body:
Maybe you use the wrong baudrate with your hardware serial. Your tutorial states, that 38400 baud is the default, but I found other sources ([HC-05][1]), that say the default is 9600 baud (which is also true for my HC-06 modules). Try 9600 baud and if it still doesn't work try some other standard baudrates.

  [1]: http://www.techbitar.com/modify-the-hc-05-bluetooth-module-defaults-using-at-commands.html


body:
This worked perfect for me [HC-05][1]

  [1]: http://www.computacaonaescola.ufsc.br/?page_id=43&lang=en
Try it out.


body: Try enetering AT mode and change the default baudrate for HC-05. Maybe use some higher baudrate, it improves communication. Also, check if you’re doing the serial reading properly.


message:
Can't display any number using 74HC595

I just started using elegoo UNO R3 and I have the problem displaying different numbers on the segment display using the 74Hc595. I have no problem with the uploads and the circuits are working fine. However, the segment  doesn't display any numbers besides 8. Is there a problem with the code or the wiring? any suggestion?

    byte seven_seg_digits[10] = { B11111100,  // = 0
                              B01100000,  // = 1
                              B11011010,  // = 2
                              B11110010,  // = 3
                              B01100110,  // = 4
                              B10110110,  // = 5
                              B10111110,  // = 6
                              B11100000,  // = 7
                              B11111110,  // = 8
                              B11100110   // = 9
                             };
    // connect to the ST_CP of 74HC595 (pin 3,latch pin)
    int latchPin = 3;
    // connect to the SH_CP of 74HC595 (pin 4, clock pin)
    int clockPin = 4;
    // connect to the DS of 74HC595 (pin 2)
    int dataPin = 2;

     void setup() {
      // Set latchPin, clockPin, dataPin as output
      pinMode(latchPin, OUTPUT);
      pinMode(clockPin, OUTPUT);
      pinMode(dataPin, OUTPUT);
    }

    // display a number on the digital segment display
    void sevenSegWrite(byte digit) {
      // set the latchPin to low potential, before sending data
      digitalWrite(latchPin, LOW);

      // the original data (bit pattern)
      shiftOut(dataPin, clockPin, LSBFIRST, seven_seg_digits[digit]);

      // set the latchPin to high potential, after sending data
      digitalWrite(latchPin, HIGH);
    }
       }

    void loop() {
      // count from 9 to 0
      for (byte digit = 10; digit > 0; --digit) {
        delay(0);
        sevenSegWrite(digit - 1);
      }

      // suspend 4 seconds
      delay(0);
    }

here is my circuit and the tutorial diagram:
[![enter image description here][1]][1]
[![enter image description here][2]][2]

  [1]: https://i.stack.imgur.com/91NrY.jpg
  [2]: https://i.stack.imgur.com/AoBRM.jpg

body:
You're not giving your eyes time to see the numbers change. If you were [a pigeon](http://www.neatorama.com/2007/09/22/fun-pigeon-facts-super-vision/) you might just see some numbers flicker past very rapidly, but we mere humans don't have a hope of seeing them - not without introducing some delay.

    void loop() {
      // count from 9 to 0
      for (byte digit = 10; digit > 0; --digit) {
        delay(0);  // <--- Number of ms to wait between each digit
        sevenSegWrite(digit - 1);
      }

      // suspend 4 seconds
      delay(0);  // <--- Number of ms to wait between counts.
    }


message:
Printing char array from array of structs in progmem to serial

(I apologize if this is a c++ question, I'm too green to know if this is unique to the Arduino IDE)

I've moved an array of structs into my PROGMEM because I was running into memory issues:

    #define HU_ADDR                 0x190
    #define ALL_AUDIO_ADDR          0x1FF
    #define MY_ADDR                 0x360
    #define UNKNOWN_ADDR            0xFFF

    typedef byte MessageID;
    enum {
      ACT_UNKNOWN,
      ACT_POWERON,
      ACT_POWEROFF,
      ACT_PASSIVEOFF_0,
      ACT_PASSIVEOFFRARE_0,
      ACT_PASSIVEONRARE,
      ACT_PASSIVEON_0,
      ACT_KEYTURN,
      ACT_PRESSDISC,
      ACT_PRESSAM,
      ACT_CD,
      ACT_STATIONFOUND,
      ACT_ENABLECD,
      ACT_CD2
    };

    struct MessageDef {
      MessageID ID;
      word MasterAddr;
      word SlaveAddr;
      byte PayloadLength;
      word Payload[24];
      char Description[20];
    };

    const MessageDef MessageTable[] PROGMEM = {
      {ACT_POWERON,           HU_ADDR, ALL_AUDIO_ADDR, 13,  {0x00, 0x00, 0x00, 0x00, 0x100, 0x100, 0x00, 0x81, 0x100, 0x01, 0xF1, 0x31, 0x60},                    "Tune Knob"},
      {ACT_POWEROFF,          HU_ADDR, UNKNOWN_ADDR, 13,    {0x00, 0x60, 0x31, 0xF1, 0x00, 0x00, 0x81, 0x00, 0x03, 0x01, 0x00, 0x00, 0x00},                       "off?"},
      {ACT_PASSIVEOFF_0,      HU_ADDR, UNKNOWN_ADDR, 3,     {0x46, 0x01, 0x11},                                                                                "Passive: Weak"},
      {ACT_PASSIVEOFFRARE_0,  HU_ADDR, UNKNOWN_ADDR, 4,     {0x60, 0x45, 0x01, 0x11},                                                                             "Passive: Strong"},
      {ACT_PASSIVEONRARE,     HU_ADDR, UNKNOWN_ADDR, 4,     {0x100, 0x20, 0x01, 0x11},                                                                            "Passive: Fierce"},
      {ACT_PASSIVEON_0,       HU_ADDR, ALL_AUDIO_ADDR, 16,  {0x00, 0x03, 0x03, 0x00, 0x00, 0x00, 0x10, 0x10, 0x10, 0x10, 0x10, 0x100, 0x80, 0xF1, 0x31, 0x74},    "Vol Knob"},
      {ACT_KEYTURN,           HU_ADDR, UNKNOWN_ADDR, 11,    {0x31, 0x62, 0x31, 0xF1, 0x00, 0xF8, 0xFF, 0xFF, 0xFF, 0xFF, 0x00},                                   "Key turned"},
      {ACT_PRESSDISC,         HU_ADDR, ALL_AUDIO_ADDR, 4,   {0x00, 0x9F, 0x31, 0x62},                                                                             "No DISC available"},
      {ACT_PRESSAM,           HU_ADDR, ALL_AUDIO_ADDR, 24,  {0x00, 0x60, 0x31, 0xF3, 0x01, 0x00, 0x01, 0x00, 0x08, 0x00, 0x30, 0x00, 0x58, 0x00, 0x6C, 0x00, 0x77, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00}, "AM/FM Switch"},
      {ACT_CD,                HU_ADDR, ALL_AUDIO_ADDR, 11,  {0x31, 0x62, 0x31, 0xF1, 0x01, 0x30, 0x01, 0xFF, 0xFF, 0xFF, 0x00},                                   "CD switch?"},
      {ACT_STATIONFOUND,      HU_ADDR, ALL_AUDIO_ADDR, 13,  {0x00, 0x00, 0x00, 0x04, 0x00, 0x100, 0x00, 0x81, 0x100, 0x01, 0xF1, 0x31, 0x60},                     "FM station found"},
      {ACT_ENABLECD,          HU_ADDR, ALL_AUDIO_ADDR, 13,  {0x00, 0x00, 0x00, 0x04, 0x00, 0x77, 0x00, 0x81, 0x00, 0x00, 0xF1, 0x31, 0x60},                       "Enter CD mode"},
      {ACT_CD2,               HU_ADDR, ALL_AUDIO_ADDR, 4,   {0x62, 0x45, 0x01, 0x11},                                                                             "CD message 2?"}
    };

    const byte MessageTableSize = sizeof(MessageTable)/sizeof(MessageDef);

I've adjusted accordingly in my code segments that reference this data using pgm_read_byte_near() for example. However, I'm not really sure how to get the Description field anymore. When MessageTable was in dynamic memory I could just use:

    Serial.println(pgm_read_word(MessageTable[msgid].Description))
But now that seems to be printing... maybe the addresses of the data? Instead of printing out the character array I need to see. How do I parse this more correctly?

body:
You can use the `strncpy_P(char* dest, const char* src, size_t maxLen);` function which will copy a zero-terminated string of at max `maxLen` bytes from PROGMEM into RAM. Then print the string from RAM.

Example code:

<!-- language: lang-cpp -->

    //We have global buffer in RAM. +1 for 0 termination
    char descBuf[20 + 1];

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

     //Copy the description string of the first message in the buffer
     strncpy_P(descBuf, MessageTable[0].Description, 20);
     //Print it
     Serial.print("Description: ");
     Serial.println(descBuf);
    }

Together with your code above, that prints on my Arduino Nano as:

    Description: Tune Knob

If you don't want to have a 21 byte big buffer in RAM (or there are larger strings you wish to print), you can also use the `pgm_read_byte` function to read and print the string characters byte-wise. Example:

<!-- language: lang-cpp -->

 Serial.print("Description: ");
 char c = 0;
 for(size_t i=0; i < strlen_P(MessageTable[0].Description); i++) {
  c = pgm_read_byte(MessageTable[0].Description + i);
  Serial.print(c);
 }
 Serial.println();

For further reference, see the Arduino documentation on PROGMEM: https://www.arduino.cc/reference/en/language/variables/utilities/progmem/


message:
Hooking up LCD screens reclaimed from old camcorders to Arduino

Has anyone had any luck using LCD screens reclaimed from old electronics with Arduino, such as camcorders etc?

My 8 yr old has an old sony handycam (dcr-trv103) in bits and now wants to use the LCD screen with the arduino. I'm not even sure how I would go about this. Any tips? How do I figure out 'what does what' in terms of the inputs? How would I drive this thing / what do I need to do to send visual images to it via an Arduino?

Here's the front and back panels of the LCD screen, and their hookups.

The Screen
[![Screen][1]][1]

Screen hookup
[![Screen hookup][2]][2]

I'm assuming this is the backlight
[![I'm assuming this is the backlight][3]][3]

backlight hookup
[![backlight hookup][4]][4]

  [1]: https://i.stack.imgur.com/uRIiS.jpg
  [2]: https://i.stack.imgur.com/P2lTt.jpg
  [3]: https://i.stack.imgur.com/FWqtB.jpg
  [4]: https://i.stack.imgur.com/iqzQK.jpg

Note: someone identified this as a duplicate of another question about reusing a cellphone LCD screen. This question is specifically about reusing an older camcorder LCD screen. Also that other question has very little answers. I found the answers below useful and educational. Thanks all.

body:
This is likely a type of TTL LCD interface.  But it is nearly impossible to describe more as there are so many variations both in hardware and in timing.
Likely a steady stream of Red Green & Blue binary data way faster than an Arduino Uno could possibly manage is required to create an image.  For the necessary processing power, you would have to utilize one of the top end Arduino boards.  Even then, software to create the steady stream of binary data for this particular LCD is still required. Also, there are hardly no standards beyond saying the LCD is a TTL or LVDS.  Which means hours spent on developing software for this LCD will likely only work for this LCD.

It would be far easier to just buy an LCD and interface board known to work together.  If you are using an Arduino Uno, there is not much processing power beyond saying "I want a circle here" or "I want a line there".  Fortunately, there are such COTS parts available.  [Here is a tutorial describing such a device connected to an Arduino Uno][1].

  [1]: https://learn.adafruit.com/adafruit-3-5-color-320x480-tft-touchscreen-breakout/


message:
Honeywell HPMA115S0, sensor not start again after stop

I use HPMA115S0 sensor with Arduino for Nodemcu, i can read it value but face one problem. The sensor not work after send stop measure command (fan not start too).

    const int StartPmMeasure[4] = {0x68, 0x01, 0x01, 0x96};
    const int StopPmMeasure[4] =  {0x68, 0x01, 0x02, 0x95};
    ...
    void stopSensor() {
      if (isSensorStart) {
       Serial.println("INFO: Stop sensor");
       sendCommand(AutoSendOff);
       sendCommand(StopPmMeasure);
       isSensorStart = false;
     }
    }

    void startSensor() {
     if (!isSensorStart) {
      Serial.println("INFO: Start sensor");
      sendCommand(StartPmMeasure);
      sendCommand(AutoSendOn);
      isSensorStart = true;
     }
    }

body:
I have the same problem here. I'm using a HPMA115S0 with an ESP8266 and found out that the sensor don't respond in general if you are doing a deep sleep with the ESP. If the ESP wakes up, the sensor does not respond on commands till you remove the 5 volts of the HPMA for a short time to make an "hard reset" of the sensor.

I think there is a problem with the ttl-level on the UART-RX-line of the HPMA. Because if you're pulling the rx-line of the sensor manually to ground (maby the ESP is doing this if he goes to deep sleep or wakes up), the sensor does not respond after that.

I spend very much time in this phenomenon. I used different pins on the ESP for software UART and used the hardware UART, problem still exists.
I assume that the ESP pulls all his pins on ground level for too long. That means that the stop bit (high-level), which the sensor wants after 8 bits are transmitted, is not present. This leads to strange behavior of the sensor.
I don't have a digital storage scope to see the level on rx-line, so this is only a presumption. But I don't have this problem, if the ESP idles with an sleep-command.
Maby you are also doing a deepsleep with your ESP which results in the same problem?

Best regards


message:
Using an accelerometer with an Arduino as a shock sensor

I really need some help.  I have absolutely no experience with accelerometers and have a project that would work great if I could integrate one into it.  I am not hinting to have some write me a code, just get me looking in the right direction.

My code (below) was written to work with 2 buttons and an LED.  Basically, its nothing but a reaction timer using an RGB liquid crystal display.

Sequence of events...

 1. power on
 2. displays “push button to start”
 3. when panel button is pushed, the loop begins by randomly selecting a
    “FIRE” time when “fire” button is pressed, it echoes the time it
    took
 4. my FOR statement, allows it to loop three times before returning to
    the begin.

This was all what I set out to accomplish, originally.  My sister has been using it at a retirement home for some of the patients to play with.  Lately she asked if instead of a “fire” button it could be programmed to simply, tap the whole unit, push the unit, or even use a tether of some sort.  I figured an accelerometer was the ticket.

I purchased an ADXL345, I tried playing with several sketches from GitHub.  What I find is the accelerometer is ALWAYS giving out information. I thought it would actually “rest” when not being physically moved.

How can I use my ADXL345 to be at  complete standstill, until it is “moved,” that it would activate a WHILE statement???

    #include <Wire.h>
    #include <LiquidCrystal.h>
    #include <SparkFun_ADXL345.h>

    ADXL345 adxl = ADXL345();
    LiquidCrystal lcd(7, 6, 5, 4, 3, 2);

    int lcdRedPWMPin = 17;
    int lcdGreenPWMPin = 16;
    int lcdBluePWMPin = 15;

    void setDisplayRGB(int r, int g, int b)

    {
      analogWrite(lcdRedPWMPin,   r);
      analogWrite(lcdGreenPWMPin, g);
      analogWrite(lcdBluePWMPin,  b);
    }

    void setup()
    {
      lcd.begin(16, 2);
      lcd.clear();
      pinMode(13, OUTPUT);
      Serial.begin(115200);
      adxl.powerOn();
      adxl.setRangeSetting(2);    // Accepted values are 2g, 4g, 8g or 16g
      //adxl.setSpiBit(0);
      adxl.setActivityXYZ(1, 1, 1);
      adxl.setActivityThreshold(70);
      adxl.ActivityINT(1);
      pinMode(13, INPUT);
      digitalWrite(13, LOW);

      pinMode(9, INPUT); //panel button
      digitalWrite(9, HIGH);

      pinMode(8, INPUT); //FIRE button
      digitalWrite(8, HIGH);

      pinMode(10, OUTPUT); //FIRE led
      digitalWrite(10, LOW);

      // int    fireButton = digitalRead(8);
      int    panelButton = digitalRead(9);
      lcd.clear();
      setDisplayRGB(100, 100, 75);
      lcd.setCursor(1, 0);
      lcd.print("Let's see what");
      lcd.setCursor(1, 1);
      lcd.print("what you got!");
      delay(2000);
    }
    double timeToFire = 0; //time it took to (fire-trigger)
    double fireTimerStarts = millis(); //fire (timer starts)
    double triggerTimerStops ; //trigger (timer stops)
    int ran; //random

    void loop()
    {

      int x, y, z;
      adxl.readAccel(&x, &y, &z);
      // byte interrupts = adxl.getInterruptSource();
      int average = (x + y + z);

      while (digitalRead(9) == HIGH)
      {
        lcd.clear();
        setDisplayRGB(40, 200, 75); //purple 40,200,75
        lcd.setCursor(0, 0);
        lcd.print("Press Button");
        lcd.setCursor(0, 1);
        lcd.print("to Start ...");
        delay(50);
      }
      for (int panelButton = 0; panelButton < 3; panelButton++)

      {
        lcd.clear();
        lcd.setCursor(0, 0);
        setDisplayRGB(255, 255, 0); //blue
        lcd.print("  ---READY---");
        delay((int)random(1000, 5000));
        {
          ran = random(1, 3);
          Serial.println(ran);
          if ( ran == 1)
            lcd.clear();
          lcd.setCursor(0, 0);
          setDisplayRGB( 0, 155, 155 );  //red
          lcd.print("     <FIRE>   ");
          lcd.setCursor(0, 1);
          lcd.print(average);
          fireTimerStarts = millis();
          digitalWrite(10, HIGH);

          // if(adxl.triggered>activityThreshold)

          while (adxl.triggered(13, HIGH))

            //while (digitalRead(8) == HIGH)
          {
            triggerTimerStops = millis();
          }
          digitalWrite (13, LOW);
          digitalWrite(10, LOW);

          setDisplayRGB(100, 100, 225); //green
        }
        timeToFire = (triggerTimerStops - fireTimerStarts) / 1000;

        delay(500);
        {
          lcd.clear();
          setDisplayRGB(0, 255, 0);
          lcd.setCursor(0, 1);
          lcd.print(timeToFire);
          lcd.setCursor(11, 1);
          lcd.print("Sec's");
          lcd.setCursor(0, 0);
          lcd.print("Your time was ...");
          delay(1500);
        }
      }

    }

body:
> I purchased an ADXL345, I tried playing with several sketches from GitHub. What I find is the accelerometer is ALWAYS giving out information. I thought it would actually “rest” when not being physically moved.

The accelerometer reports its current acceleration on each axis at all times, whether that acceleration is changing or not. When at rest and upright, it will report close to 1.0 g on the Z axis; when rotated to some other direction and held steady, the *vector magnitude* of the accelerations on the three axes will be close to 1.0. The vector magnitude is computed as the square root of the sum of the squares of the elements, so rather than averaging, you'll want to do this:

    int x, y, z;
    adxl.readAccel(&x, &y, &z);

    float mag = sqrt( x*x + y*y + z*z );

This `mag` value should change only slightly if you gently rotate the accelerometer. That baseline value represents 1.0g of acceleration from Earth's gravity.

A rapid motion of the accelerometer will produce some higher or lower value, briefly. Figure out what threshold makes sense for your application and do something like:

    if (mag > (BASELINE_GRAVITY * 1.2f))
    {
        lcd.setCursor(0, 0);
        lcd.print("You moved!");
    }


body:
An alternative to using an accelerometer is a simple Vibration Sensor Switch. Adafruit has a Fast Vibration Sensor Switch: https://www.adafruit.com/product/1766, Medium Vibration Sensor Switch: https://www.adafruit.com/product/2384 and a Slow Vibration Sensor Switch: https://www.adafruit.com/product/1767, each costing 1 USD.

**Edit 1:**

If you look for "ADXL345_ACTIVITY" in the SparkFun_ADXL345_Example.ino sketch, there is a comment that says "add code here to do when activity is sensed".

My suggestion is to get the ADXL345 working with this sketch first, then start removing the excess code from it that you don't need. Once you have the bare minimum code required to accomplish your goal, try to integrate that with you current sketch.

There are several "sensitivity adjustments" you can make under the "Configure ADXL345 Settings" section of the code.


body: According to the datasheet of adxl345, this chip (so the module) has single-tap, double-tap functionality. As described in the datasheet, you can configure the chip as you want it to operate. The chip has 2 interrupt pins. When it is configured to operate one of the tap modes and senses the tap, it gives an interrupt signal. You can check that signal and process the information.


message:
Fool Proofing My Arduino IC Checker

I am creating an IC checker for some high school juniors since a faulty IC can be a nuisance of a bug to find when bread-boarding. These ICs are all simple TTL gating from the 74LS series; the set I am using are all 14-pin and have VCC and GND at pin 14 and 7 respectively.

Thus far my prototype's hardware looks like this:

 - 14 digital pins to connect to the IC inputs/outputs
 - 1 analog pin reading a joystick to navigate through the IC options
 - 1 analog pin set to digital read as a button, which starts the checking process
 - 1 analog pin writing to an LED to indicate whether the IC is valid
 - 2 analog pins (SDA and SCL) as a serial bus to control my display

I actually have the prototype working for a few ICs, but I am concerned that these high school students may test an IC under the wrong selection. Since the digital pins have to dynamically change input/output depending which IC its checking, this allows for inputs and outputs to be mismatched, which could prove fatal to both the IC and the Arduino board.

I want to know if there is a way to check that inputs and outputs are misaligned without having serious electrical failure. Possible some advanced pin control I am unaware of?

Also, if you could answer my question with an example with the 74LS00, whose pinout is diagrammed below and datasheet can be found [here][1].

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

  [1]: http://ecelabs.njit.edu/student_resources/datas/74ls00.pdf
  [2]: https://i.stack.imgur.com/SfnMI.png

body:
I am tempted to repeat the old engineering trope "You can't make it foolproof - fools are so ingenious".

If you want to proceed, and are prepared for the complexity 2 solutions suggest themselves.

1. Limit the current supplied by the Arduino output if connected to a pin on the IC configured as output.

2. Probably less complex is to test each pin by loading it to 0V and 5V to find which are TTL outputs. A TTL input will unable to source any significant current, while an output will be able to draw current to/from either 0V or 5V.

Either will require quite a bit of additional hardware.

This is not strictly an Arduino problem, but an Arduino would be an ideal solution.


body:
I would connect each of the IC's IO pins to _both_ a digital output and
a digital (or analog) input of the Arduino, like this:

<!-- 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/CpMUB.png)

<!-- End schematic -->

Drive each pin with the digital output, alternatively `LOW` and `HIGH`.
While doing this, read the pin voltage through your input:

* If the IC pin is an input, you will have no significant voltage drop
  through the protection resistor. Your reading should be `LOW` when
  driving the pin `LOW` and `HIGH` when driving it `HIGH`.
* If the IC pin is an output, you will have 5 V through the
  resistor whenever the IC's output value doesn't match your Arduino
  output. The reading on your input will be independent of the level of
  your output.

Obviously, an Uno doesn't have enough I/O pins to implement this idea.
You could use a Mega instead. Notice also that with this setup you don't
need the joystick input: you could just test for every known IC type
until you find one that matches the observed behavior, then display the
part number on your LCD.


body:
The simplest way to "fool proof" your system (i.e., to prevent damage by a fool, not make it so it always works right even with a fool) is to add a resistor to each connection. The resistor should be sized so that if an IO pin is HIGH and it's connected to a LOW output on the chip the current flow is below the maximum allowed by both ends.

<!-- 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/VDkGH.png)

<!-- End schematic -->

If D5 is set HIGH and the output of the NAND is LOW the voltage difference (assuming a 5V Arduino) would be around 5V. I=V/R, so 5/1000 is 5mA - way below the maximum of 25mA (40mA burst) of the Arduino.

It won't tell you that you have connected the wrong chip, but it will protect both the chip and the Arduino in such an event.

Since it now doesn't matter if the wrong chip is selected you could in fact cycle automatically through each of the chips testing each on in sequence until you find one that gives the correct results. No need to select a specific one - if no chip matches then it's a faulty chip.


message:
How does DDRD |= _BV(PD2) differ from digitalWrite(2,HIGH)?

I'm attempting to copycat the work of Louis Frigon's Toyota Aux Enabler. I have (with a lot of help on this site) managed to begin capturing and understanding messages on the AVC-LAN bus, but I can't quite send messages.
Frigon uses the following line to drive output signal to high:

    DDRD |= _BV(PD2) | _BV(PD3);
I have more or less no idea what this means. He then 'releases the output' with the following:

    DDRD &= ~( _BV(PD2) | _BV(PD3) );
If I copy these lines verbatim I don't get the same results. If I set the output high and then read the bus, I don't even see the signal I'm putting out. I wonder if this is related to the differences between his Atmega8 and my Arduino Nano?

I can't paste my or Frigon's work here due to character count limitations, so here is his github for the project: https://github.com/halleysfifthinc/Toyota-AVC-LAN

The most important files to my question are BigSchematic.jpg and AVCLanDriver.c.

Here is a dump of my current code: https://pastebin.com/NG9U5FuL

Here is my schematic: https://i.stack.imgur.com/csiVv.jpg

body:
Each port on the ATmega328P (or the ATmega8 for that matter) is
controlled by two registers¹:

* `DDRx`, where x is B, C or D, is the “data direction register”. It is
  used to set the pin to either input or output. Writing to this
  register is roughly equivalent to calling `pinMode()`.
* `PORTx` is the port's “data register”. It is mostly used in output
  mode to set the pin to `HIGH` or `LOW`. Writing to this register is
  equivalent to calling `digitalWrite()`.

All this is covered by the Arduino tutorial on [direct port access][].
And, of course, by the datasheet; more specifically by
[section 18.2: “Ports as General Digital I/O”][datasheet].

As you may now notice, the original code does not use anything like
`digitalWrite()` to write to the bus, relying instead of the equivalent
of `pinMode()`. This is related to the electrical characteristics of the
bus:

* You write a “physical 1” by actively driving AVC+ high and AVC− low
* You write a “physical 0” by releasing the bus, in which case the
  potentials of those lines are set by the termination resistors.

That's why you see `InitMCU()` setting `PORTD` for driving AVC+ high and
AVC− low, but leaving `DDRD` in its initial state (“leave pins
tri-stated” says the comment). At this point the bus is in the
“released” state. Then pulses are sent by setting the pins to output
mode (“Drive output to signal high” in the comment) and, after an
appropriate delay, setting them back to input mode (“Release output”).

------------------------------------------------------------------------
¹ I am leaving away the details that are irrelevant to the code in
question, like the internal pullup or pin toggling via `PINx`.

[direct port access]: https://www.arduino.cc/en/Reference/PortManipulation

[datasheet]: http://ww1.microchip.com/downloads/en/DeviceDoc/Atmel-42735-8-bit-AVR-Microcontroller-ATmega328-328P_Datasheet.pdf#page=98


message:
USB Host Shield plus 2 identical joysticks

I'm trying to get two identical joystics (Saitek cyborg 3D) running with the USB-Host-Shield on a Mega 2560 and an USB-Hub.

I already get the event-messages of both of them:

    #include <usbhid.h>
    #include <hiduniversal.h>
    #include <usbhub.h>

    // Satisfy IDE, which only needs to see the include statment in the ino.
    #ifdef dobogusinclude
    #include <spi4teensy3.h>
    #endif
    #include <SPI.h>

    #include "hidjoystickrptparser.h"

    USB Usb;
    USBHub Hub(&Usb);
    HIDUniversal Hid1(&Usb);    // first Joystick
    HIDUniversal Hid2(&Usb);    // second Joystick

    JoystickEvents Joy1Events;
    JoystickEvents Joy2Events;

    JoystickReportParser Joy1(&Joy1Events);
    JoystickReportParser Joy2(&Joy2Events);

    void setup() {
            Serial.begin(115200);
    #if !defined(__MIPSEL__)
            while (!Serial); // Wait for serial port to connect - used on Leonardo, Teensy and other boards with built-in USB CDC serial connection
    #endif
            Serial.println("Start");

            if (Usb.Init() == -1)
                    Serial.println("OSC did not start.");

            delay(200);

            if (!Hid1.SetReportParser(0, &Joy1))
                    ErrorMessage<uint8_t > (PSTR("SetReportParser1"), 1);
            if (!Hid2.SetReportParser(0, &Joy2))
                    ErrorMessage<uint8_t > (PSTR("SetReportParser2"), 1);
    }

    void loop() {
            Usb.Task();
            Serial.print("\tX1: ");
            PrintHex<uint8_t > (JoystickEvents::mostRecentEvent.X, 0x80);
            Serial.print("\tY1: ");
            PrintHex<uint8_t > (JoystickEvents::mostRecentEvent.Y, 0x80);
            Serial.print("\tX2: ");
            PrintHex<uint8_t > (JoystickEvents::mostRecentEvent.Z1, 0x80);
            Serial.print("\tY2: ");
            PrintHex<uint8_t > (JoystickEvents::mostRecentEvent.Z2, 0x80);
            Serial.print("\tRz: ");
            PrintHex<uint8_t > (JoystickEvents::mostRecentEvent.Rz, 0x80);
            Serial.println("");

    }

My question is: How can I distinguish the events from the different joysticks.

I'm trying to get some kind of port-information from the USB-Hub. Unfortunately something like

    !hid->GetAddress()

 within the JoystickReportParser doesn't do the job as it always returns 0.

Any ideas?

body:
Not quite the question that was asked but part of the problem.

This is a simple introduction to pointers.

    int variable = 42;                              // Create a variable
    int* pointer = &variable;                       // Create a pointer to the variable (by getting its address)
    *pointer = 99;                                  // Set the address to a new value
    printf ("variable has the value %d", variable); // Print 99.

`&x` get the address of `x`

`*y` `dereferences` the pointer y, which means it 'turns it back to a variable' (this is simplistic view which isn't really true, but will do for now).
So you could, if you wanted (which you wouldn't) do this `*&z` which would be the same as doing `z`.

Basically think of `&` and `*` as a pair of complimentary operators like - and + or * and /.  (They aren't operators, but to start with it might help).

The next problem is when you do this

    SomeFunction(&variable);

All function parameters in C/C++ are passed by value by default.  This means the function gets a copy of them not the actual value.  So if you had:

    void FunctionOne (int val)
    {
        val = 99;
    }
    int val = 4;
    FunctionOne(val);
    printf("val = %d", val);   // You will see 4 printed.

If you pass by reference then you will see 99 printed, to pass by reference you can do it one of two ways.

    void FunctionTwo (int& valByRef);
    void FunctionThree (int* valPointer);

`FunctionTwo` only works with C++ (It will work with an Arduino).

`FunctionThree` might cause a segmentation error if NULL is passed in and the function writes to it.

If it helps in my opinion pointers was one of the hardest concepts to grasp in classic C/C++ so don't worry if you don't understand it just have a play with it and see what you can do.

**Calling Methods**

 - `object.method()` - Call the function method on the instance called
   object which is of type `X`.
 - `object->method()` - Call the function method on the instance called
   object which is a **pointer** of type `X`.
 - `object::method()` - call the function method
   which is a static member of class object (static means it doesn't
   change any data within an instance of a class)
 - *object->method() - Avoid this like the plague.  It either means `*(object->method())` or `(*object)->method()` to know you would need to look at the type of object and the return type of the function.  Its easier just to bracket it to remove ambiguity.

As for `*object.&method()` I've never come across that one, but that doesn't mean it doesn't exist. :)


body:
this could be a possible answer, in Arduino Code, the USB Host Shield 2.0 library is necessary:
```
#include <usbhid.h>
#include <hiduniversal.h>
#include <usbhub.h>

// Logitech Attack 3 HID report
struct GamePadEventData {
 uint8_t X, Y, Z1, Z2, Rz;
} __attribute__((packed));

class JoystickEvents {
 public: virtual void OnGamePadChanged(const GamePadEventData *evt, int joystick);
};

class JoystickReportParser : public HIDReportParser {
 JoystickEvents *joyEvents;
 uint8_t joyId;
 uint8_t oldPad[sizeof(GamePadEventData)];
 public: JoystickReportParser(JoystickEvents *evt, uint8_t id) : joyEvents(evt), joyId(id) {}
 virtual void Parse(USBHID *hid, bool is_rpt_id, uint8_t len, uint8_t *buf);
};

void JoystickReportParser::Parse(USBHID *hid, bool is_rpt_id, uint8_t len, uint8_t *buf) {
 if (!is_rpt_id && len == sizeof(GamePadEventData)) {
  // Checking if there are changes in report since the method was last called
   bool match = (sizeof(oldPad) == len) && (memcmp(oldPad, buf, len) == 0);
   if (!match && joyEvents) {
    joyEvents->OnGamePadChanged((const GamePadEventData*)buf, joyId);
    memcpy(oldPad, buf, len);
   }
 }
}

void JoystickEvents::OnGamePadChanged(const GamePadEventData *evt, int joystick) {
 Serial.print("Joystick ");
 Serial.print(joystick);
 Serial.print(": X: "); PrintHex<uint16_t>(evt->X, 0x80);
 Serial.print(" Y: "); PrintHex<uint16_t>(evt->Y, 0x80);
 Serial.print(" Z1: "); PrintHex<uint8_t>(evt->Z1, 0x80);
 Serial.print(" Z2: "); PrintHex<uint8_t>(evt->Z2, 0x80);
 Serial.print(" Rz: "); PrintHex<uint8_t>(evt->Rz, 0x80);
 Serial.println();
}

USB Usb;
USBHub Hub(&Usb);
HIDUniversal Hid1(&Usb); // first Joystick
HIDUniversal Hid2(&Usb); // second Joystick

JoystickEvents JoyEvents;
JoystickReportParser Joy1(&JoyEvents, 1);
JoystickReportParser Joy2(&JoyEvents, 2);

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

 Serial.println("Start");

 if (Usb.Init() == -1) {
  Serial.println("OSC did not start.");
 }

 delay(200);

 if (!Hid1.SetReportParser(0, &Joy1) || !Hid2.SetReportParser(1, &Joy2)) {
  ErrorMessage<uint8_t>(PSTR("SetReportParser"), 1);
 }

}

void loop() {
 Usb.Task();
}
```


message:
Can you use digital pins as PWM output?

I am currently working on a robotics project that requires 16 PWM outputs to control 16 servos. Is it possible to use Arduino Uno's digital pins as PWM output pins through code?

If it is not possible, what microcontrollers do you suggest to use on such a project?

body:
PWM is not used to control servos.
Servos need a pulse that is 1 to 2 ms wide, with 1.5 ms wide being the center position, that occur every 20 ms (50 Hz).

A 2560 has enough timers and the library to control up to 48 servos.


body:
Only specific Digital Pins marked with ~PWM can generate a PWM signal. In the case of arduino Uno the pins 3,5,6,9,10,11 are all hardware PWM driven, and are marked on the Uno with a ~ or something.
Others can be driven with software PWM(though I wouldn't recommend it). As the Arduino Uno uses the ATMEGA328P, the number of pins is same with other boards using same processor.

On the other hand if you want to run 16pins for PWM, its best if you use Arduino MEGA 2560 because its processor supports more than 6 Hardware pins for PWM. Also you get the advantage of a higher memory storage for your code


message:
Communication over UDP between Dues with Arduino WiFi Shield

I'm using the Arduino WiFi Shield to make two Arduinos Due communicate using UDP. The first node to send a message (the Client) doesn't always receive a reply from the other node (the Server). The code for the Client:

    #include <string.h>

    #include <SPI.h>
    #include <WiFi.h>
    #include <WiFiUdp.h>

    #define BUFSZ 90

    // variables for WiFi connection
    char ssid[] = "ssid";
    char pass[] = "pwd";
    int status = WL_IDLE_STATUS;

    char sendBuffer[BUFSZ];
    char recvBuffer[BUFSZ];

    WiFiUDP Udp;
    unsigned int localPort = 51515;

    IPAddress server(192,168,88,251);
    unsigned int serverPort = 12345;

    void printWifiData()
    {
     // print your WiFi shield's IP address:
     IPAddress ip = WiFi.localIP();
     Serial.print("IP Address: ");
     Serial.println(ip);

     // print your MAC address:
     byte mac[6];
     WiFi.macAddress(mac);
     Serial.print("MAC address: ");
     Serial.print(mac[5],HEX);
     Serial.print(":");
     Serial.print(mac[4],HEX);
     Serial.print(":");
     Serial.print(mac[3],HEX);
     Serial.print(":");
     Serial.print(mac[2],HEX);
     Serial.print(":");
     Serial.print(mac[1],HEX);
     Serial.print(":");
     Serial.println(mac[0],HEX);
    }

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

     // connect to WiFi network
     while (status != WL_CONNECTED) {
      Serial.print("Attempting to connect to WPA SSID: ");
      Serial.println(ssid);
      status = WiFi.begin(ssid, pass);
      delay(10000);
     }

     // print connection details
     Serial.println("You're connected to the network");
     printWifiData();

     Udp.begin(localPort);
     strcpy(sendBuffer, "abcdefghijklmnopqrstuvwxyz123456789101112131415161718192021222324252627282930313233343536");
    }

    void loop()
    {
     Udp.beginPacket(server, serverPort);
     int len = Udp.write(sendBuffer);
     Udp.endPacket();

     Serial.print("Sent ");
     Serial.print(len);
     Serial.println(" bytes.");

     delay(10);

     int packetSize = Udp.parsePacket();
     if (packetSize > 0) {
      Serial.print("\nReceived packet of size ");
         Serial.println(packetSize);

      Serial.print("From ");
         IPAddress remoteIp = Udp.remoteIP();
      Serial.print(remoteIp);
         Serial.print(", port ");
         Serial.println(Udp.remotePort());

      // read the packet into recvBuffer
      int len = Udp.read(recvBuffer, BUFSZ);
      if (len > 0) {
       Serial.println("Contents:");
          Serial.println(recvBuffer);
      }
      else {
       Serial.println("Read 0 bytes.");
      }
     }
     else {
      Serial.println("\nNo packets yet.");
     }
    }

Server:

    #include <SPI.h>
    #include <WiFi.h>
    #include <WiFiUdp.h>

    #define BUFSZ 90

    // variables for WiFi connection
    char ssid[] = "ssid";
    char pass[] = "pwd";
    int status = WL_IDLE_STATUS;

    char sendBuffer[BUFSZ];
    char recvBuffer[] = "acknowledged";

    WiFiUDP Udp;
    unsigned int localPort = 12345;

    void printWifiData()
    {
     // print your WiFi shield's IP address:
     IPAddress ip = WiFi.localIP();
     Serial.print("IP Address: ");
     Serial.println(ip);

     // print your MAC address:
     byte mac[6];
     WiFi.macAddress(mac);
     Serial.print("MAC address: ");
     Serial.print(mac[5],HEX);
     Serial.print(":");
     Serial.print(mac[4],HEX);
     Serial.print(":");
     Serial.print(mac[3],HEX);
     Serial.print(":");
     Serial.print(mac[2],HEX);
     Serial.print(":");
     Serial.print(mac[1],HEX);
     Serial.print(":");
     Serial.println(mac[0],HEX);
    }

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

     // connect to WiFi network
     while (status != WL_CONNECTED) {
      Serial.print("Attempting to connect to WPA SSID: ");
      Serial.println(ssid);
      status = WiFi.begin(ssid, pass);
      delay(10000);
     }

     // print connection details
     Serial.println("You're connected to the network");
     printWifiData();

     Udp.begin(localPort);
     Serial.println("Waiting...");
    }

    void loop()
    {
     int packetSize = Udp.parsePacket();

     if (packetSize) {
      Serial.print("Received packet of size ");
         Serial.println(packetSize);

      Serial.print("From ");
         IPAddress remoteIp = Udp.remoteIP();
      Serial.print(remoteIp);
         Serial.print(", port ");
         Serial.println(Udp.remotePort());

      // read the packet into recvBuffer
      int len = Udp.read(recvBuffer, BUFSZ);
      if (len > 0) {
       Serial.println("\nContents:");
          Serial.println(recvBuffer);

       Udp.beginPacket(Udp.remoteIP(), 51515);
          Udp.write(sendBuffer);
          Udp.endPacket();
      }
      else {
       Serial.println("Read 0 bytes.");
      }
     }
    }

I don't know if it's a timing problem... So I've tried to use delays after the Client send its message but the issue persists. So the Client sends many messages to the Server but receives few replies. I didn't want to put the part of the code in the Client when it's waiting for a response inside a loop in case the first message is lost (so the Client will never receive a response anyway). Did anyone have a simular problem or a suggestion to fix this issue?

body:
I was able to solve the problem. First of all, I needed a bigger delay between the send and receive parts in the Client.

So I'm using `delay(35);`. This is important so the Client can have enough time to receive the reply before sending another message.

Also, inside the Server, the buffers to send and receive a packet were inverted.

So, the correct would be:

    char sendBuffer[] = "acknowledged";
    char recvBuffer[BUFSZ];

I understand the messages can stil be lost because UDP does not guarantee delivery, but with a larger delay in an isolated WiFi network all of the messages from the Client got a reply.


message:
Is it possible for ESP8266WiFi client to request the number of clients currently connected to Access Point?

My system consists of several ESP8266 based 'stations', which are synchronised in a way that all of them go into deep sleep and wake up on the same schedule. All stations are WiFi clients. All stations run on batteries and energy saving is critical.

One of the stations is a Master. It contains a modem/router that serves as AP to all stations.   The AP is switched OFF during the sleep phase. When a Master wakes up it switches on the AP and thus starts a communication session available to all stations. When all stations have their data sessions completed and disconnect from AP, the Master switches off the modem/router and goes to sleep.

My question is about the Master being informed that there are no other clients actively connected to the AP. My current solution is WAN based - each station reports to the Web Service on the start and end of their connection. Is it possible to achieve the same result locally - by a request from the WiFi client to the Access Point?

body: Use `WiFi.softAPgetStationNum()` to return the number of clients connected to an ESP8266 AP.


message:
GSM and GPS module don't work together

I am trying to create a project which involves getting latitude and longitude via GPS Module and send it via GSM Module. My problem here is that individual code is working perfectly. However, if am to initialize both together, none will work.

    #include "GSM.h"//wrapper class for Sim800l library
    #include "GPS.h"//wrapper class for TinyGPS library
    GSM *gsm;
    GPS *gps;
    void setup()
    {
     Serial.begin(9600); // Debugging only
     gsm = new GSM();//initializes SIM800l
     //gps = new GPS(11,10 );//initializes NEO6MV2//uncommmenting this line won't make both modules work
    }
    String telNum;
    int i = 1;
    void loop()
    {
     /*
     Serial.println(gps->getLongitude(),6);
     Serial.println(gps->getLatitude(),6);
     */

     Serial.println(gsm->read(i,telNum));
     Serial.println(telNum);
      ++i;
    }
[![enter image description here][1]][1]

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

body:
You can't use two softwareserial devices together (or not reliably, and not without knowing exactly what you are doing).

It's not even easy using one software and one hardware serial together unless you know what you are doing.

SoftwareSerial blocks everything else from happening while it's sending or receiving, so using it for things that send unsolicited messages (as GPSs do all the time) causes havoc.

The best you can hope for is to use HardwareSerial for the GPS and SoftwareSerial for the GSM, which is call-and-response most of the time.

Better would be to use a better board that has multiple hardware serial ports.


body:
I got it working by initializing and  deleting the pointer to the GPS and GSM object.

Initialization and freeing of the objects are made in the loop function. I initialize the GPS, run it in a loop for sometime, destroy it and initialize the GSM and same procedure as GPS.

Though I don't know if it'll have any effects but its working perfectly

    #include "GSM.h"
    #include "GPS.h"
    GSM *gsm;
    GPS *gps;
    void setup()
    {
     Serial.begin(9600); // Debugging only
    }

    unsigned long previousMillis = 0;//could be any value depending on how quick you want it to elapse
    const long interval = 100; //could be any value depending on how long you want it to run
    void loop()
    {
     gps = new GPS(6, 7);//initialization <SoftwareSerial::begin() function called here>
     while (previousMillis <= interval)
     {
      //GPS codes here
      ++previousMillis;
     }
     delete gps;   //destory initialized object
     previousMillis = 0; //reset value

     gsm = new GSM(); //initialization <SoftwareSerial::begin() function called here>
     while (previousMillis <= interval)
     {

      //GSM codes here
      ++previousMillis;
     }
     delete gsm;//destory initialized object

     previousMillis = 00;//reset value
    }


body:
You can use Listen function
for example:
```cpp
First_softwareserial.listen();// when you need gsm serial
```
```cpp
Second_softwareserial.listen();// when you need gps serial
```