body:
My current setup has the arduino in 'stand-by' power saving mode, therefore i am unable to use any means of a traditional soft debouncer, such as Bounce2, as far as I know.

I went ahead and attached the buttons to pin change interrupts, since I have one button on each bank, i.e. pin 7 and pin 11.

The technique I'm using doesn't seem to be behaving since the routines are being fired too regularly (inconsistently), and at the rising edge too.

I have the pins set to use their internal pull-ups.

Using the PCI library:

    void pciSetup(byte pin)
    {
      *digitalPinToPCMSK(pin) |= bit (digitalPinToPCMSKbit(pin));  // enable pin
      PCIFR  |= bit (digitalPinToPCICRbit(pin)); // clear any outstanding interrupt
      PCICR  |= bit (digitalPinToPCICRbit(pin)); // enable interrupt for the

    pciSetup(POWER_SWITCH);
    pciSetup(SELECTOR_BTN);

    // check if IR IN or Power switch
    ISR (PCINT0_vect) // handle pin change interrupt for D8 to D13 here
    {

      if (digitalRead(POWER_SWITCH) == LOW)
      {
        noInterrupts();
        unsigned long last_millis = millis();
        while (millis() - last_millis >= 500);
        ir_power_pressed = true;
      }
      interrupts();
    }

    ISR (PCINT2_vect) // handle pin change interrupt for D0 to D7
      noInterrupts();
      unsigned long last_millis = millis();
      while (millis() - last_millis >= 500);
      ir_selector_pressed = true;
      interrupts();
    }

Am I doing something silly?

**Update 1**

As suggested in the comments, i've adjusted the code, but it still triggers on the rising edge, and a few times rapidly at the falling edge.

    ISR (PCINT2_vect) // handle pin change interrupt for D0 to D7 here
    {
      if (digitalRead(SELECTOR_BTN) == LOW)
      {
        noInterrupts();
        static unsigned long last_millis = millis();
        if (millis() - last_millis >= 500)
        {
          ir_selector_pressed = true;
          interrupts();
        }
      }
    }

title: Soft debouncing from an interrupt during stand-by

Answers: 1

body:
You don't update last_millis.
Also, you don't know whether SELECTOR_BTN went from HIGH to LOW or whether another pin fired the interrupt while SELECTOR_BTN was low. Remember the previous state to solve this.

    const unsigned long debounceTime = 50;
    volatile bool ir_selector_pressed = false;

    ISR (PCINT2_vect) { // handle pin change interrupt for D0 to D7 here
      static unsigned long previousStateChangeMillis = 0;
      static bool previousPinState = HIGH;

      bool pinState = digitalRead(SELECTOR_BTN);
      if (pinState != previousPinState) { // ignore pin changes of pins other than SELECTOR_BTN
        if (pinState == LOW) { // only falling events
          if ((millis() - previousStateChangeMillis) > debounceTime) { // debounce
            ir_selector_pressed = true;
          }
        }
        previousPinState = pinState;
        previousStateChangeMillis = millis();
      }
    }


body:
I am trying to connect arduino uno and ethernet shield and try to send some data to an asp.net web api application. When i upload the sketch, i get in the serial monitor connection failed.
I don't understand what's going wrong ?
Below is the code i am using

    #include "cactus_io_DHT22.h"
    #include <SPI.h>
    #include <Ethernet.h>
    #include <Client.h>

    #define DHT22_PIN 2

    byte mac[] = {
      0xDE, 0xAD, 0xBE, 0xEF, 0xFE, 0xDD };

    IPAddress ip(192,168,0,177);
    IPAddress server(192,168,0,11);
    EthernetClient client;

    DHT22 dht(DHT22_PIN);
    float heatindex1 =0.00;
    float heatindex2 = 0.00;

    void setup() {
      Ethernet.begin(mac,ip);
        delay(1000);  Serial.begin(9600);

        Serial.println("connecting...");
        if (client.connect(server, 80)) {
          Serial.println("connected :D ");
        }
      Serial.print("Arduino server IP address: ");
      Serial.println(Ethernet.localIP());
      Serial.println("DHT22 Humidity - Temperature Sensor");
      Serial.println("RH\t\tTemp (C)\tTemp (F)\tHeat Index (C)\t Heat Index
     (F)\t Max(C)\t\t Min(C)");

      dht.begin();
      dht.readHumidity();
      dht.readTemperature();

    }

    float max1=dht.temperature_C;
     float min1=100;

    void loop() {
      dht.readHumidity();
      dht.readTemperature();
      heatindex1=dht.computeHeatIndex_C();
      heatindex2=dht.computeHeatIndex_F();

      if(dht.temperature_C>max1)
      {max1=dht.temperature_C;}
      if(dht.temperature_C<min1)
      {min1=dht.temperature_C;}

      // Check if any reads failed and exit early (to try again).
      if (isnan(dht.humidity) || isnan(dht.temperature_C)) {
        Serial.println("DHT sensor read failure!");
        return;
      }
      if (client) {

       // When a client sends a request to a webserver, that request ends with a blank line
        boolean currentLineIsBlank = true;

        Serial.println("OK"); }

      if (client.connect(server, 80)) {
        client.print("GET /api/todo?humidity=");
        client.print(dht.humidity);
        client.print("&temperature1=");
        client.print(dht.temperature_C);
        client.print("&temperature2=");
        client.print(dht.temperature_F);
        client.print("&heatindex1=");
        client.print(heatindex1);
        client.print("&heatindex2=");
        client.print(heatindex2);
        client.print("&max1=");
        client.print(max1);
        client.print("&min1=");
        client.print(min1);// And this is what we did in the testing section above. We are making a GET request just like we would from our browser but now with live data from the sensor
        client.println(" HTTP/1.1"); // Part of the GET request
        client.println("Host: 192.168.0.11"); // IMPORTANT: If you are using XAMPP you will have to find out the IP address of your computer and put it here (it is explained in previous article). If you have a web page, enter its address (ie.Host: "www.yourwebpage.com")
        client.println("Connection: close"); // Part of the GET request telling the server that we are over transmitting the message
        client.println(); // Empty line
        client.println(); // Empty line
        client.stop();    // Closing connection to server

      }

      else {
        //If Arduino can't connect to the server (your computer or web page)
        Serial.println("--> connection failed\n");
      }

       Serial.print(dht.humidity); Serial.print(" %\t\t");
      Serial.print(dht.temperature_C); Serial.print(" *C\t");
      Serial.print(dht.temperature_F); Serial.print(" *F\t");
      Serial.print(dht.computeHeatIndex_C()); Serial.print(" *C\t ");
      Serial.print(dht.computeHeatIndex_F()); Serial.print(" *F\t ");
      Serial.print(max1); Serial.print(" *C\t ");
      Serial.print(min1); Serial.println(" *C\t");

      delay(5000);
    }

title: Arduino connection with the server failed

Answers: 1

body:
I don't know of this library, but you're using the connection code twice, once in the setup() and later again in the loop().

You're already checking whether the client exists:

    if (client) {

Why are you asking a few lines down again to connect?

    if (client.connect(server, 80)) {

My guess is, that this if()-Clause is not necessary. Or the connection in the setup() should be removed.

If this isn't the source of the error, first test whether the server on 192.168.0.11 is running and that you can connect (from a different device) to the port 80.


body:
Here's a simple sketch. I have an array `data` and a variable `idx`.
I'm assigning a value to each of the array element, and then sending them to my serial monitor.

    volatile uint16_t data[5];
    volatile uint16_t idx = 5;

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

      while (!Serial) { }
      Serial.println("\nHello!");

      data[0] = 1010;
      data[1] = 1011;
      data[2] = 1012;
      data[3] = 1013;
      data[4] = 1014;

      for(int i = 0; i< idx; ++i)
      {
        Serial.print(data[idx]);
        Serial.write(",");
      }

      while(1){  }
    }

    void loop() {}

When I look into my serial monitor, I get this:

    Hello!
    0,0,0,0,0,

Why is this happening? Did I overlook something fundamental? I'd appreciate if you could offer your thoughts on this.

I'm testing this code on Arduino Mega2560.

title: Changes to array not reflected

Answers: 1

body:
You got confused here:

    Serial.print(data[idx]);

You're printing array slice 5 (the sixth entry in a 5 entry array) 5 times.

You probably meant to write:

    Serial.print(data[i]);

To improve clarity you may want to `#define` it instead:

    #define DATA_SIZE 5
    uint16_t data[DATA_SIZE];

    ...

    for (int i = 0; i < DATA_SIZE; i++) {
        ....
    }

Or you can do it the other way round (get the size from the array):

    uint16_t data[5];
    #define DATA_SIZE (sizeof(data) / sizeof(data[0]))


body:
I have an arduino uno as the master I2C device talking to an ATtiny85 as the slave.
What I want to do is have the Attiny85 receive a message from the UNO to tell it to power off which will then trigger a mosfet to turn all the power off to the UNO and then sleep for a period of time.
This all seems to be working fine but every now and then I seem to get a lock up where the UNO just stays on.
Is what I am doing below ok. I am worried about TinyWireS_stop_check() call and if that is going to be messed up by the fact I have delays in the loop and also the fact it goes to sleep.

Thanks

    // Code for the ATtiny85
    #include <powernap.h>
    #include <TinyWireSlave.h>

    #define I2C_SLAVE_ADDRESS 0x4 // Address of the slave
    #define POWER A3
    // The default buffer size, Can't recall the scope of defines right now
    #ifndef TWI_RX_BUFFER_SIZE
    #define TWI_RX_BUFFER_SIZE ( 16 )
    #endif

    uint8_t sleepInterval = 1;
    bool cycleComplete = false;
    bool sleepNow = false;

    Napper napper;

    enum InterComms
    {
     IDLE = 0,
     PWR_OFF = 1,
     CALIBRATION_MODE = 2,
     SLEEP_INTERVAL = 3,
     KEEPALIVE = 4
    };

    char rxChrData; //Receives the data.
    char rxString[12];  //Varbiable for holding one string of data.
    int rxIndex = 0; //Used to index rxString.
    int i = 99;
    bool calibrationMode = true; //Always true when power is turned on

    void requestEvent()
    {
     TinyWireS.send(calibrationMode);
    }

    void receiveEvent(uint8_t howMany)
    {
     if (TinyWireS.available()) {
      if (howMany < 1)
      {   // Sanity-check
       return;
      }
      if (howMany > TWI_RX_BUFFER_SIZE)
      {   // Also insane number
       return;
      }

      howMany--;
      uint8_t byte = TinyWireS.receive();
      switch (byte)
      {
      case PWR_OFF:
       i = 100;
       sleepNow = true;
       break;
      case CALIBRATION_MODE:
       calibrationMode = true;
       i = 110;
       break;
      case SLEEP_INTERVAL:
       i = 120;
       howMany--;
       sleepInterval = TinyWireS.receive();
       break;
      case KEEPALIVE:
       i = 130;
       measureTimer = millis();
       break;
      default:
       i = IDLE;
       break;
      }
            //Make sure buffer is emppty
      while(howMany--)
       TinyWireS.receive();
     }
    }

    void setup()
    {
     pinMode(POWER, OUTPUT);
     analogWrite(POWER, 255);

     TinyWireS.begin(I2C_SLAVE_ADDRESS); // join i2c network

     TinyWireS.onReceive(receiveEvent); // not using this
     TinyWireS.onRequest(requestEvent);

     napper.setup();

     measureTimer = millis();
     return;
    }

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

     TinyWireS_stop_check();

     if (sleepNow)
     {
      sleepNow = false;
      tws_delay(2000);
      cycleComplete = true;
      calibrationMode = false;
      analogWrite(POWER, 0);
      tws_delay(200);
      napper.napminutes(sleepInterval);
      analogWrite(POWER, 255);
      cycleComplete = false;
      //Reset timer
      measureTimer = millis();
     }

     if ((unsigned long)(currentMillis - measureTimer) > (300000) /*&& !cycleComplete*/)
     {
      analogWrite(POWER, 0);
      tws_delay(1000);
      analogWrite(POWER, 255);
      measureTimer = millis();
     }
    }

title: Is it possible to put ATtiny85 to sleep while using TinywireS?

Answers: 0


body:
I have an ATTiny85 controlling the power to a number of devices. When I first power on it will power the devices via a mosfet. Take the readings it needs to and then puts itself to sleep for 15 minutes then wake up and repeat.

My question is, because I am using the Watchdog timer to put it to sleep, I can't use the reset functionality of the watchdog (ie wdt_Reset). So is there anyway to detect a lock or hang if the ATTiny85 never wakes up for some reason or would I need additional hardware to check for this. If so what kind of circuit would I need.

Thanks

title: Is it possible to recover an Arduino if it does not wake up after putting it to sleep

Answers: 2

body:
Not sure what you mean by "using the watchdog to put it to sleep". You can sleep with or without the watchdog enabled, and you can even use the watchdog to both wake you with an interrupt and also reset in case of a lockup. Check out section 8.5.2 in the datasheet...

> If WDE is set, WDIE is automatically cleared by hardware when a
> time-out occurs. This is useful for keeping the Watchdog Reset
> security while using the interrupt. After the WDIE bit is cleared, the
> next time-out will generate a reset. To avoid the Watchdog Reset, WDIE
> must be set after each interrupt.

body:
> So is there anyway to detect a lock or hang if the ATTiny85 never wakes up for some reason or would I need additional hardware to check for this. If so what kind of circuit would I need.

The whole point of the watchdog timer is to wake (or reset) the chip after a certain (short) time. You don't really need a second watchdog timer to wake the processor if the first one fails.

I made a [temperature and humidity sensor](http://www.gammon.com.au/forum/?id=12106) which is battery powered, and which uses the watchdog timer to wake it and take readings (which sounds like what you are doing). It has been running for a number of years now (over four) and it has never "hung".


body:
Here's sample code to demonstrate my problem:

    #include <DigiKeyboard.h>

    void setup() {
      // put your setup code here, to run once:
      delay(5000);
      DigiKeyboard.print("TESTING TESTING");
      pinMode(1,OUTPUT);
      digitalWrite(1,HIGH);
    }

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

My problem is that I can't get Digikeyboard.print() or other Digikeyboard commands (e.g. sendKeyStroke()) to do anything while they are located inside the setup function. The led command after the print command executes properly.

The print command will work if I place it inside the loop function. However, I want to only execute this code once.

Any assistance would be appreciated, and I would be happy to provide more information if necessary.

EDIT: I worked around this by using a if-expression inside the loop function to only run the code once. However, I am still interested in learning why my original code doesn't work.

title: Digispark / Digikeyboard code doesn't execute inside setup{}

Answers: 1

body:
The (hard to find) documentation on the DigiKeyboard example:
http://digistump.com/wiki/digispark/tutorials/digikeyboard

States:

> It is essential that DigiKeyboard.update() is called regularly (the
> beginning of the loop is good) to maintain USB communication. Using
> DigiKeyboard.delay() will automatically spam DigiKeyboard.update()
> calls during the delay period. If your loop code is fast just using
> DigiKeyboard.delay() will be sufficient.

Without looking deeper into it, I suspect that your initial call to `DigiKeyboard.print()` fills a buffer and `DigiKeyboard` needs subsequent repeated calls in order to empty the buffer.

Does the problem still exist if you put `DigiKeyboard.update()` as the only statement in the `loop()` function?


body: The general AT command for sleep mode (for the SIMCOM GSM modules) is AT+CSCLK=1 (or AT+CSCLK=2). I have given both a shot but they don't work with the A6 module. Does anyone know of any other command that does the same? The manufacturers claim that it can function at very low current levels when in sleep. But sadly they don't mention the sleep AT command.

title: AT command to put the A6 GSM/GPRS into sleep / power down

Answers: 1

body:
A6 module uses a hardware pin (INT/GPIO_1) or (EN) enable on some modules.
There is no AT command as in the SIM900.


body:
I wonder is it possible to change [PCM.h 's lib][1] use of 16-bit timer1 to another 8-bit?
Now I'm getting

    libraries\AltSoftSerial\AltSoftSerial.cpp.o (symbol from plugin): In function `AltSoftSerial::read()':

    (.text+0x0): multiple definition of `__vector_11'

    libraries\PCM\PCM.c.o (symbol from plugin):(.text+0x0): first defined here

    collect2.exe: error: ld returned 1 exit status

    exit status 1

 when compiling

    #include <PCM.h>
    #include <AltSoftSerial.h>

An attempt to avoid XY problem: make AltSoftSerial work alongside with PCM-alike library on Arduino Nano v3 without SD.

I'm poorly familiar with timers and interrupts, so I'll be very grateful for any advice and suggestion!

  [1]: http://highlowtech.org/?p=1963

title: Arduino Nano v3: is it possible to PCM + AltSoftSerial?

Answers: 1

body:
It is not easy to make PCM sounds with the Arduino Uno or Nano. A few libraries can do that, but they use two timers: Timer1 and Timer2. Timer0 is already in use by Arduino. When using those libraries, the Arduino Nano is almost completely occupied to make sounds.

A software serial port also requires a lot from the Arduino Nano. The AltSoftSerial uses Timer1.

Those two will never work together. It is not possible.
For what do you need the serial port ?
Could that be done in a different way ?

The normal SoftwareSerial does not use a timer, but because it also occupies the Arduino Nano a lot, using SoftwareSerial together with a PCM sound at the same time will not work. Perhaps if you carefully design the sketch and never use them at the same time, it might work. I doubt if it will be reliable.

A better option is to swap the Arduino Nano for an Arduino Micro. Then you have a extra hardware serial port and you don't need the AltSoftSerial anymore. The library to make PCM sounds has to be compatible with the Arduino Micro. I suppose that not every PCM library is compatible.

The best option is to use a MP3 shield. Then you can send a command to play a MP3 sound. If you use a MP3 shield with a Arduino Micro or Arduino Leonardo or Arduino Mega 2560 or Arduino Zero or Arduino Due, then you have a extra hardware serial port and you don't need libraries that occupy the most of the Arduino board, and your sketch will be a normal sketch that does normal things.


body:
I'm new to using an Arduino and I am attempting the Simon Says game. Right now, I do not understand why my program will not go from activating the random lights to the user input. Currently it is flashing all the lights three times like I want it to, but then it will flash three random lights and then go straight to flashing every light, right to left (which is the indicator that the wrong button was pushed).

I am working in Tinkercad/circuits.io and have had the physical implementation looked at, and it is good. I just can't figure out the code. Anything will help, thanks!
<!-- language-all: lang-cpp -->

    // Defining LEDs and buttons.
    int leds[] = {12, 10, 7, 4};
    int buttons[] = {11, 9, 6, 3};

    const int max = 40;
    int lightArr[max]; // Array with full patterns of LEDs.
    int currArr[max];
    int gameState = 0;
    int level = 1;
    int count = 0; // Counter for every sequence of iterating over the
    random array of ints (LEDs).
    int buttonPressed = -1;
    int correct = 1;

    void setup() {
      pinMode(leds[0], OUTPUT);
      pinMode(leds[1], OUTPUT);
      pinMode(leds[2], OUTPUT);
      pinMode(leds[3], OUTPUT);
      pinMode(buttons[0], INPUT);
      pinMode(buttons[1], INPUT);
      pinMode(buttons[2], INPUT);
      pinMode(buttons[3], INPUT);
      randomSeed(analogRead(0));
      allOn();
    }

    void loop() {
      if (gameState == 0) {
        resetGame();
      } else if (gameState == 1) {
       play();
      } else if (gameState == 2) {
        gameOver();
      }
    }

    void resetGame() {
      if (level == 1) {
      // Setting up a sequence of random lights.
        for (int i = 0; i < 40; i++) {
          lightArr[i] = random(0,4);
        }
      }
      level = 1;
      gameState = 1;
    }

    void play() {
      while (correct == 1) {
        showPattern();
        int correct = userInput();
      }
    }

    void showPattern() {
      for (int i = 0; i < level; i++) {
        delay(500);
        digitalWrite(leds[lightArr[i]], 1);
        delay(500);
        digitalWrite(leds[lightArr[i]], 0);
        delay(500);
      }
    }

    int userInput() {
      for (int i = 0; i < level; i++) {
        int buttonPressed = readOneButton();
        digitalWrite(leds[buttonPressed], 1);
        delay(500);
        digitalWrite(leds[buttonPressed], 0);
        delay(500);
        if (lightArr[i] != buttonPressed) {
          // User button pressed.
          gameState = 2;
          correct = 0;
        }
      }
    }

    void gameOver() {
      for (int i = 0; i < 3; i++) {
        digitalWrite(leds[0], 1);
        delay(150);
        digitalWrite(leds[0], 0);
        delay(150);
        digitalWrite(leds[1], 1);
        delay(150);
        digitalWrite(leds[1], 0);
        delay(150);
        digitalWrite(leds[2], 1);
        delay(150);
        digitalWrite(leds[2], 0);
        delay(150);
        digitalWrite(leds[3], 1);
        delay(150);
        digitalWrite(leds[3], 0);
        delay(150);
      }
      gameState = 0;
    }

    int readOneButton() {
      if (digitalRead(buttons[0])) {
        return 0; // Button: Red
      } else if (digitalRead(buttons[1])) {
        return 1; // Button: Green
      } else if (digitalRead(buttons[2])) {
        return 2; // Button: Blue
      } else if (digitalRead(buttons[3])) {
        return 3; // Button: Yellow
      }
    }

    void allOn() {
      for (int i = 0; i < 3; i++) {
        digitalWrite(leds[0], 1);
        digitalWrite(leds[1], 1);
        digitalWrite(leds[2], 1);
        digitalWrite(leds[3], 1);
        delay(500);
        digitalWrite(leds[0], 0);
        digitalWrite(leds[1], 0);
        digitalWrite(leds[2], 0);
        digitalWrite(leds[3], 0);
        delay(500);
      }
    }

title: Simon Says Project - Can't go from random lights to user input

Answers: 1

body:
    void play() {
      while (correct == 1) {
        showPattern();
        int correct = userInput();
      }
    }

Why do you create a new variable called correct and put the value form userInput in that?  Why don't you put the return from userInput into the variable named correct that you already have?  Two variables with the same name in the same scope is NEVER a good idea.  The original correct will never be changed here so this becomes an infinite loop.

Next, look at readOneButton.  It will take the Arduino just a few microseconds to run through that for loop and the whole userInput function.  Unless you are super duper fast at getting that button pressed, it is just going to decide that you didn't press any buttons.  You don't have a case in there for no button pressed, so it is going to return 0.  You should probably wait until the user presses a button before you decide whether he is right or wrong.


body:
I gave 7.5v to the arduino mega board through battery. 5v pin in the board gives me the same voltage as input. Earlier it was working fine now it is giving problem.Please let me know the solution as soon as possible.

Thanks and regards,
Thippeswamy

title: Arduino mega board 5v pin does not gives 5v when 7.5v is applied through external source

Answers: 2

body: If you apply 7.5V to the power barrel jack and the 5V pin is 7.5V then your Arduino board is broken. Don't connect it to a computer. Don't use it anymore.

body:
It is highly likely that you have destroyed your Arduino. This can happen in a number of ways. Rugged Circuits has a great article on [10 ways you can destroy the Arduino][1].

The giveaway is that you are measuring 7.5V on the 5V pin. Most likely the voltage regulator has blown. Page 355 of the [ATMega2560 datasheet][2] says the absolute maximum voltage for the chip is 6.0V, so this also means that the microcontroller is blown as well. It is most likely unsalvageable.

Go out and buy yourself a new one. Before you turn it on, check the wiring is correct.

We have all let the [magic smoke][3] out at some point.

  [1]: https://www.rugged-circuits.com/10-ways-to-destroy-an-arduino/
  [2]: http://www.atmel.com/Images/Atmel-2549-8-bit-AVR-Microcontroller-ATmega640-1280-1281-2560-2561_datasheet.pdf
  [3]: https://en.wikipedia.org/wiki/Magic_smoke


body:
I am using I2C communications to control a AD5694RBRUZ (http://www.analog.com/media/en/technical-documentation/data-sheets/AD5696R_5695R_5694R.pdf) with my Arduino Nano. If i enter two bytes it wil Wire.write only the first line from top to bottom. In the datasheet it is shown that you muust first fill the command byte, then the high and last the low byte. How can i fill the low byte? I have now scraped the idea to input two bytes separately and decided to input one uint16_t byte. How do i fill the low byte at the same time as the high byte, or if it possible how to input the uint16_t value?

My code is as follows:

    #include <Wire.h>

    #define Address 0x0D

    void setup()
    {
    Serial.begin(9600);
    Wire.begin();
    AddressWrite(0x3F,0x05B0);
    Serial.print ("Biti = ");
    Serial.println (AddressRead(0x01));
    }

    void loop()
    {
    }

    void AddressWrite (byte Naslov, uint16_t Cifra1)
    {
    byte Hi, Lo;
    Hi = highByte(Cifra1);
    Lo = lowByte(Cifra1);
    Wire.beginTransmission(Address);
    Wire.write(Naslov);
    Wire.write(Cifra1);
    Wire.endTransmission();
    Serial.print ("Biti Hi = ");
    Serial.println (Hi);
    Serial.print ("Biti Lo = ");
    Serial.println (Lo);
    Serial.print ("Biti Cifra = ");
    Serial.println (Cifra1);
    }

    byte AddressRead (byte naslov)
    {
    Wire.beginTransmission(Address);
    Wire.write(naslov);

    Wire.requestFrom(Address,2);

    while(!Wire.available())
      {
      }

    return Wire.read();
    }

Thank you for your time and help.

title: How do i fill the second byte?

Answers: 1

body:
You can use a number of Wire.write to write data.
The AD5694R should get three bytes and two bytes can be read from it. There is a "multiple dac readback sequence", but that is an extra.

Your AddressWrite requires an extra Wire.write.
Your AddressRead is missing a Wire.endTransmission and the `while(!Wire.available())` should be removed.

    void AddressWrite (byte Naslov, uint16_t Cifra1)
    {
      byte Hi, Lo;
      Hi = highByte(Cifra1);
      Lo = lowByte(Cifra1);

      Wire.beginTransmission(Address);
      Wire.write(Naslov);       // command byte
      Wire.write(Hi);           // msb first
      Wire.write(Lo);           // lsb second
      Wire.endTransmission();
    }

    uint16_t AddressRead (byte naslov)
    {
      Wire.beginTransmission(Address);
      Wire.write(naslov);       // command byte
      Wire.endTransmission(false);  // repeated start

      uint16_t hi, lo, result;
      Wire.requestFrom(Address,2);
      hi = Wire.read();
      lo = Wire.read();
      result = word(hi,lo);
      return result;
    }

I have added a repeated start, because that is according to the datasheet.

Could you make the names more according to the datasheet ? For example 'command' or 'commandByte' instead of 'Naslow'. And perhaps better names for the functions, for example 'writeAD5694R' instead of 'AddressWrite'.


body:
This code is working fine to switch on/off one LED. Can anyone help me add 3 more on/off buttons so that I can control 4 LEDs?

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

    byte mac[] = {
      0xDE , 0xAD , 0xBE , 0xEF , 0xFE , 0xED
    };
    byte ip[] = {
      192 , 168 , 2 , 20
    };
    byte gateway[] = {
      192 , 168 , 2 , 1
    };
    byte subnet[] = {
      255 , 255 , 255, 0
    };
    EthernetServer server(80);
    String richiesta;
    int pinLed = 9;

    void setup() {
      Ethernet.begin(mac,ip,gateway,subnet);
      pinMode(pinLed,OUTPUT);
      Serial.begin(9600);
      richiesta = "";
    }

    void loop() {
      EthernetClient client = server.available();
      if(client) {
        Serial.println("Tujse na ho payega");
        while(client.connected()) {
          if(client.available()) {
            char c = client.read();
            richiesta.concat(c);
            if(c == '\n') {
              Serial.print(richiesta);
              if(richiesta.indexOf("Led=1")>0) {
                Serial.println("Pin will be high");
                digitalWrite(pinLed,HIGH);
              } else {
                Serial.println("Pin will be low");
                digitalWrite(pinLed,LOW);
              }
              client.println("HTTP/1.1 200 ok");
              client.println("Content-Type: text/html");
              client.println();
              client.println("<title> Home Automation</title>");
              client.print(" ButtonOn  Buttonoff ");
              client.stop();
              richiesta = "";
            }
          }
        }
      }
    }

title: Help adding 3 more on/off switches so that I can control 4 LEDs

Answers: 2

body:
Use arrays, one for switches, one for leds. I don't see the code for leds in your code.

Note that you need 8 pins (4 for switches, 4 for leds).

Initialize them, e.g.

   int switchPins[] = { 2, 3, 4, 5 };

Same for leds

    int ledPins[] = {6, 7, 8, 9};

To access them, use a for loop:

    for (int iLed = 0; iLed < 4; i++)
    {
       digitalWrite(ledPins[iLed], HIGH);
    }

Because 4 might be used a lot, consider them making const or define:

    #define NR_OF_LEDS 4

    for (int iLed = 0; iLed < NR_OF_LEDS; i++)
    {
       digitalWrite(ledPins[iLed], HIGH);
    }

or use the length of the array

    for (int iLed = 0; iLed < sizeof(ledPins) / sizeof(int); i++)
    {
       digitalWrite(ledPins[iLed], HIGH);
    }

body:
The html you send must be changes to add the buttons:

    client.print(" Button1On  Button1off ");
    client.print("Button2On  Button2off ");
    client.print("Button3On  Button3off ");
    client.print("Button4On  Button4off ");

Then you need to add some ifs:

      if(richiesta.indexOf("Led1=1")>0) {
        Serial.println("Pin1 will be high");
        digitalWrite(pin1Led,HIGH);
      } else if(richiesta.indexOf("Led1=0")>0){
        Serial.println("Pin1 will be low");
        digitalWrite(pin1Led,LOW);
      }
      if(richiesta.indexOf("Led2=1")>0) {
        Serial.println("Pin2 will be high");
        digitalWrite(pin2Led,HIGH);
      } else if(richiesta.indexOf("Led2=0")>0){
        Serial.println("Pin2 will be low");
        digitalWrite(pin2Led,LOW);
      }
      //etc.

you can use arrays and loops to avoid the repeated code each time.


body:
I am using RadioHead library for the communication between nrf24l01.
I am sharing the snippet of my code below because the code is too huge.
The problem i am facing here is on the receiver side i am not be able see the data i am sending , it is showing squares and not the proper characters.
my output showing to me is :

name :?!

skill :

Sender Code :

    struct DataHolder {
      String name;
      String skill;
    };

    DataHolder dh;

    RH_NRF24 nrf24(10, 9);

    //THIS METHOD I AM USING TO SEND DATA FROM SENDER NRF
    void sendtonrf(){

     dh.name = "xyz";
     dh.skill = "classA";

     nrf24.send((uint8_t *)&dh, sizeof(dh));

    }

receiver code:

    struct DataHolder {
    String name;
    String skill;
    };

     DataHolder dh;

     void loop{

     if (nrf24.available()) {

      uint8_t buf[RH_NRF24_MAX_MESSAGE_LEN];
      uint8_t len = sizeof(buf);

        if (nrf24.recv(buf, &len)) {

        String str1 = (((DataHolder*)buf))->name;
        String str2 = ((DataHolder*)buf)->skill;
        Serial.println("name :" + str1);
        Serial.println("skill :" + str2);

        }
     }
    }

title: RadioHead library nrf24 sending and receiving struct data problem

Answers: 1

body:
Your problem is that you are working with pointers.  You have a pointer to a block of memory with some text in it, then you take that pointer, get the address of the variable that stores it, convert it to a pointer to an 8-bit value, and send that.  Which of course won't work.

Instead you need to send the *content* of the memory the pointer points to:

    nrf24.send((uint8_t *)strm, strlen(strm));

`strm` is *already* a pointer, you don't need to convert it to a pointer with `&` - that just confuses things and gives you a pointer to a pointer, which in this context is garbage.

A `struct` made up of `String` objects will not do what you think it does.  A `String` object does not contain the string itself. Instead it just allocates an external block of RAM (from the *heap*) using `malloc()` and holds a pointer to that memory. If you try transferring a `struct` which contains `String` objects all you will be sending is the data associated directly with those `String` objects, including the pointer to the string content, which is completely meaningless to the remote end.

Instead you will either have to send the strings separately along with their length and some identifier to say what the string is, or rebuild the string content into a fixed size buffer.

Personally I would use a fixed size buffer. In this method you change your `struct` so it contains two character arrays with a fixed size. For instance:

    struct DataHolder {
        char name[10]; // Room for 9 characters + NULL
        char skill[10]; // Room for 9 characters + NULL
    };

Then copy your string data into it:

    struct DataHolder data;

    strncpy(data.name, "Fred", 10); // Maximum 10 bytes
    strncpy(data.skill, "ClassA", 10); // Again, max 10 bytes.

    Now you can send the struct in its entirety:

    nrf24.send((uint8_t *)&data, sizeof(struct DataHolder));

The data sent (and indeed the data held in the Arduino's RAM) will be:

    Fred\0\?\?\?\?\?ClassA\0\?\?\?

Where `\?` represents any possible character (undefined, basically, and depends on how the variable was created - if it's global it'll be all 0, if it's on the stack then it will be whatever was in that block of memory beforehand) and `\0` is the standard C end of string NULL character (ASCII 0).

For receiving it's exactly the same. Use the same struct, and go:

    struct DataHolder data;

    int len;
    if (nrf24.recv((uint8_t *)&data, &len)) {
        // Do something with data.name and data.skill
    }

Or you can use a buffer and a pointer, which may be safer since you have no chance of overrunning the buffer with a message coming in that is bigger than the data structure size:

    struct DataHolder *data;
    uint8_t buf[RH_NRF24_MAX_MESSAGE_LEN];

    if (nrf24.recv(buf, &len)) {
        data = (struct DataHolder *)buf;
        // Do something with data->name and data->skill
    }

Note the change from `.` to `->` for the struct access since it's now a pointer.

Also note that you don't want your `struct` to be any bigger than your maximum packet size. To send anything bigger you will have to chunk the data up and send it in little bits.


body:
Board: ESP8266MOD module from AI Thinker.

Using ArduinoHttpClient I am unable to send a post message to an Azure IOT Hub endpoint. The endpoint is listening on 443 and expects a shared key passed via a custom header.

The error I get is "Connection Timed Out"

Here is the brief sketch

    char serverAddress[] = "myapp.azure-devices.net";
    int port = 443;
    string sig = "Azure shared access signature";
    HttpClient client = HttpClient(wifiClient, serverAddress, port);
      String jsonPayload = payload; // passed into this function
      client.beginRequest();
      String contentType = "application/json";
      client.post("/devices/deviceId/messages/events?api-version=2016-02-03");
      client.sendHeader(HTTP_HEADER_CONTENT_TYPE, contentType);
      client.sendHeader("Authorization", sig);
      client.sendHeader(HTTP_HEADER_CONTENT_LENGTH, jsonPayload.length());
      client.beginBody();
      client.print(jsonPayload);
      client.endRequest();

      statusCode = client.responseStatusCode();
      response = client.responseBody();

The Status Code is -3 indicating a Timeout

I then created a simple REST API that accepts the JSON. Hosted it as an Azure website on port 80.

The board is able to connect to this HTTP endpoint

Question(s):
1. Is the board underpowered to handle HTTPS?
2. Is creating an HTTP proxy the only option?
3. Am I not using the right library?

Thanks

title: How do you post json data to HTTPS endpoint from ESP8266MOD?

Answers: 2

body:
You are only making an HTTP request to an HTTPS server. It's not going to work.

AFAIK there is no direct support for HTTPS in the ESP8266 libraries, but there is support for SSL, and you can then manually create an HTTP request over that - as detailed in the [HTTPSRequest.ino](https://github.com/esp8266/Arduino/blob/master/libraries/ESP8266WiFi/examples/HTTPSRequest/HTTPSRequest.ino) example.

body:
Thanks to @Majenko I was able to find the right solution.

The resolution is [here][1]

  [1]: https://github.com/arduino-libraries/ArduinoHttpClient/issues/13

Essentially, a secure WiFiClient needs to be created and used in the HttpClient constructor

 1. Paste the HTTPS URL You are trying to connect to, in a browser
    window and grab the SHA1 Fingerprint of the certificate
 2. Create aninstance of WifiClientSecure
 3. Call Connect on WifiClientSecure passing in the HTTPS URL and Port number
 4. Upon successful connection, call the Verify method of WifiClientSecure to verify the fingerprint.
 5. Pass the fingerprint from setp1 and URL to this method
 6. Use the WifiClientSecure instance when creating an instance of
    HttpClient.

Hope this helps.


body:
Hi I want to control a DC motor using Arduino mega2560 and Arduino Uno as a slave. Mega have to process data from an ultrasonic sensor(measuring distance) and control the motor based on the input. I tried to google but couldn't find a better tutorial or code. I'm using Adafruit motor shield l293d. I have the idea about the wiring part just need a simple code.

    Eg:

     if( distance < 20) {
       //send signal to slave to run the motor forward
     }else {
       //send signal to slave to stop the motor
     }

title: How to control a DC motor via Arduino Uno as a slave and Mega 2560 as master?

Answers: 1

body:
Serial is quite easy to implement and use the `SoftSerial`.

Example code for serial can be found in the Arduino IDE under the menu:

    File | Examples | 04. Communication


body:
Are there Arduinos (or clones) that can be **powered with one or two AA batteries or one CR2032 3V battery**? (it would sleep 99% of the day, and only send a few bytes per day)

If so, will they also have a +3.3V or even +5V output (produced by an internal step-up chip) that can be used by another chip?

(I know it might sound like having one's cake and eat it too, but maybe it exists?)

title: Arduino (or clone) powered with one or two AA batteries or one CR2032, but still able to give +3.3V or +5V

Answers: 1

body:
The modern low voltage versions of a bare ATmega chip can run from either 2xAA or a lithium coin cell - you wouldn't want to use a voltage regulator, as that is not only unnecessary but introduces losses but increases the required input voltage by its `dropout` meaning your circuit will fail earlier in the discharge curve that in it would without.

Bypassing the regulator on an Arduino Mini style of board is possible.  You probably do not want a board with an on-board USB-serial solution.

You'll need to make sure the clock rate is low enough for operation at the rated voltage (and for sleep efficiency).  This might involve using the fuse for the internal oscillator and ignoring a crystal/resonator that might be present, though if your board was originally intended for 3.3v operation it might be okay.

You will also need to set the brownout detector to the lowest voltage or disable it entirely - this again is in the fuses.

A boost converter to a higher voltage is *possible* but may not be a good idea, especially from a coin cell.  This is because to supply 1 milliamp at 5v, a boost converter must draw 2 milliamps at 2.5v - and then a bit more, to account for its own losses.  If you go shopping for a boost converter to use, make sure it has an enable, look at the quiescent power consumption when disabled and enabled without load, and look at the minimum input voltage.


body:
I'm trying to set up a watchdog timer interrupt to execute a routine in the WDT_vec ISR at some recurring interval. I don't want the processor to reset, just to execute the code in the interrupt and return to "normal" operation. I have the following test jig appropriated from the 'net that claims to set that up:

    #include <avr/wdt.h>

     void setup_WDT() {
          noInterrupts();  // disable all the interrupts
          MCUSR = 0;       // ensure that the reset vectors are off

          /* Disable and clear all Watchdog settings. */

          _WD_CONTROL_REG = (1 << WDCE) | (1 << WDE);
          _WD_CONTROL_REG = 0;

          /* Setup Watchdog for interrupt and not reset, and a approximately 500ms timeout */
          _WD_CONTROL_REG = (1 << WDIE) | (1 << WDP2) | (1 << WDP0);

          interrupts();  // re-enable interrupts
        }

    void setup() {
      setup_WDT();
      Serial.begin(9600);
      Serial.println("Startup");
    }

    void loop() {
    }

    ISR(WDT_vec) {
      Serial.println("Watchdog Interrupt");
    }

The output indicates that the processor is just resetting repeatedly and never reaching the ISR. Also I get the following warning on compilation from the IDE (Arduino 1.8.2):

> warning: 'WDT_vec' appears to be a misspelled signal handler, missing
> __vector prefix [-Wmisspelled-isr]  ISR(WDT_vec) {

title: How can I set up a watchdog interrupt vector timer on the Arduino Redboard/Uno?

Answers: 2

body:
Two errors:

1. The watchdog interrupt vector is named `WDT_vect`, not `WDT_vec`.
2. The statement `_WD_CONTROL_REG = 0;` serves no useful purpose, and
   will likely mess up with the timed sequence for changing the watchdog
   setting. Just remove it.

body:
_WD_CONTROL_REG = 0; serves an important purpose. If the Watchdog is accidentally enabled, for example by a runaway pointer or brown-out condition, the device will be reset and the Watchdog Timer will stay enabled. If the code is not set up to handle the Watchdog, this might lead to an eternal loop of timeout resets. To avoid this situation, the application software should always clear the Watchdog System Reset Flag (WDRF) and the WDE control bit in the initialization
routine, even if the Watchdog is not in use.
if you are using it in developing a product whose programme should never freeze than this is important to remember.


body:
My students use the Sparkfun RedBot Inventor's Kit for their final design projects. The documentation about this board isn't great. There are connectors to SPI pins (they are not soldered to headers, but they exist, see diagram below); however the bumpers and wheel encoders use pins 10 and 11, which are pins used in SPI communication.

My question is: is it possible to solder headers into that SPI socket and use SPI communication without interfering with the bumpers and wheel encoders (for example if my students want to hook up a 7-segment display to show the RedBot's speed)?

[![Redbot mainboard][1]][1]

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

title: Is it possible to use SPI on Redbot Mainboard?

Answers: 1

body:
From the silkscreen on the board you appear to be either mistaken or already re-purposing signals - pins 10 and 11 are labeled as used for Servo position command PWM, not for sensor input.

Therefore, as long as you don't use those signals for servos (or ignore the labeling and use them for something else) there should be no issue using pins 11, 12, and 13 in the ordinary manner for SPI, by finding them in any available place on the board, including the 6-pin ISP connector your identify.

If you did need to use pins 11 and 12 for another purpose you could still "bit-bang" "software SPI" on any other available set of four pins.

It is also vaguely possible that you could share functions by connecting bumper switches through resistors - when the software is driving those signals as SPI outputs, it will dominate the resistors, but at other times it can re-purpose the pins as inputs to read the bumper switch state. However this may require modification of Arduino library code to accomplish repeated mode switching.


body:
I have several [single coil latching relays][1], (**EC2-5SNU**).

I am trying to control them by an MCU; connected directly they work fine, but I am iffy about keeping it this way so I'm trying to power them through a [darlington pair array][2], (**ULN2003**).

Using the non-latching type, these work fine through the ULN2003, but attempting to interface the code below with the latching type isn't going so well and i can't figure out why:

    int right = 12;
    int left = 10;

    void setup() {
      pinMode(right, OUTPUT);
      pinMode(left, OUTPUT);
    }

    void loop() {
      digitalWrite(right, HIGH);  //reset
      digitalWrite(left, LOW);
      delay(2000);
      digitalWrite(right, LOW); //set
      digitalWrite(left, HIGH);
      delay(2000);
    }

I have four connected with a common pin, but to simplify i've tried and failed to have the code above work on a single relay, as shown below:

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

[![enter image description here][4]][4]

Measuring the voltages out of the MCU show the correct levels, keeping in mind the ULN2003 acts an inverter, so i've set the boolean logic accordingly.

The voltages at the output of the ULN seem to stick at 0.6V, I've tried a bunch of permutations, including having one pin (on the common pin setup) connected directly to the MCU.

Does anyone have any ideas?

  [1]: http://www.mouser.com/ds/2/212/KEM_R7002_EC2_EE2-540906.pdf
  [2]: http://www.ti.com/lit/ds/symlink/ulq2004a.pdf
  [3]: https://i.stack.imgur.com/QFGxr.png
  [4]: https://i.stack.imgur.com/IduzD.png

title: MCU to switch single coil latching relay not working (attempting array with common gnd)

Answers: 2

body:
You need to use an h-bridge as if you were driving a motor. For this kind of relay you need to be able to both sink and source current, which a Darlington pair cannot do, it can only sink.

I guess you may be being thrown by the symbol of an inverting buffer used in the schematic symbol for the ULN2803 in your schematic capture package. It's incorrect, since it's not an inverting buffer, it's a Darlington pair:

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

<!-- End schematic -->

As you can see, setting the input HIGH will allow the transistor pair to conduct, but setting it to LOW will stop it conducting - so the output is either connected to ground, or is floating.

body:
I'm sure that you've solved this, given that the post is old, but it would work if you use pull-ups on the ULN2003 outputs. However, you should wire at least two open-drain buffers of the ULN2003 to both endings of the relay coil to ensure enough current when the microcontroller pulls down.

See this 2009 EDN post:
[https://www.edn.com/drive-a-single-coil-latching-relay-without-an-h-bridge-circuit/][1]

  [1]: https://www.edn.com/drive-a-single-coil-latching-relay-without-an-h-bridge-circuit/


body:
I want to make a countdown timer with a LilyPad Arduino for 3 seconds with red (1 second), then orange(1 second), then yellow (1 second), then green (3 seconds), all being triggered by a button. I want to check to see if I have the right code. I am a self taught programmer, so apologies if this is a little messy. (or a lot)

<!-- language: lang-js -->

    #include <Adafruit_NeoPixel.h>
    const int inputPin = 3;

    void setup() {
      // put your setup code here, to run once:
      pinMode(inputPin, INPUT_PULLUP);
      strip.begin();
      strip.show();
    }

    void loop() {
      // put your main code here, to run repeatedly:
      If (digitalRead (inputPin) == LOW) {
        For (int i = 0; i < 12; I++) {
          Int pixelNum1 = 1;
          strip.setPixelColor( pixelNum1, 244, 0, 0);
          strip.show();
          delay (27);
          pixelNum1 ++;
        }

        For (int i = 0; i < 24; I++) {
          Int pixelNum2 = 1;
          strip.setPixelColor( pixelNum, 247, 247, 0)
          strip.show();
          delay (27);
          pixelNum ++;
        }

        For (int i = 0; i < 12; I++) {
          Int pixelNum3 = 1;
          strip.setPixelColor( pixelNum, 0, 247, 41)
          strip.show();
          delay (27);
          pixelNum ++;
        }
      }
    }

title: How do you make an Arduino count down timer?

Answers: 2

body:
    For (int i = 0; i < 12; I++) {
          Int pixelNum1 = 1;
          strip.setPixelColor( pixelNum1, 244, 0, 0);
          strip.show();
          delay (27);
          pixelNum1 ++;
        }

Assuming you fix the upper-case lower-case issues here first, you've still got a scope issue.  Since pixelNum1 is defined inside the for loop, it will go out of scope at the end of the for loop.  So it will be 1 on every iteration and it won't increment like you seem to think it will.

Why don't you just get rid of it altogether and use i+1 instead?

body:
In addition to what has already been said, I would add these two
recommendations:

1. Do not repeat yourself. If you are repeating the same code, only with
   different data, then put that data into an array and loop through it.
2. Define all your constants at the beginning, instead of having them as
   “magic numbers” within the code itself.

Note that those are only good programming practices. They are not
critical for the functioning of your code, but they make it easier to
read and to maintain.

Applying those recommendations, here is my throw at this. Note that the
`Color` struct is only meant to make it easier to define colors as
constants:

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

    #include <Adafruit_NeoPixel.h>

    struct Color {
        uint8_t r, g, b;
    };

    const uint8_t  INPUT_PIN  =  3;
    const uint8_t  STRIP_PIN  =  6;
    const int      LED_COUNT  = 12;
    const uint32_t LED_DELAY  = 27;
    const int      NUM_COLORS =  4;
    const Color    COLORS[NUM_COLORS] = {
                       {244,   0,  0},  // red
                       {247, 122,  0},  // orange
                       {247, 247,  0},  // yellow
                       {  0, 247, 41}   // green
                   };

    Adafruit_NeoPixel strip(LED_COUNT, STRIP_PIN);

    void setup()
    {
        pinMode(INPUT_PIN, INPUT_PULLUP);
        strip.begin();
        strip.show();
    }

    void loop()
    {
        // Nothing to do until the button is pressed.
        if (digitalRead(INPUT_PIN) == HIGH)
            return;

        // Cycle through the colors.
        for (int i = 0; i < NUM_COLORS; i++) {
            Color color = COLORS[i];
            for (int led = 0; led < LED_COUNT; led++) {
                strip.setPixelColor(led, color.r, color.g, color.b);
                strip.show();
                delay(LED_DELAY);
            }
        }

        // Switch off.
        strip.clear();
        strip.show();
    }


body:
I am making a triac-controlled light dimmer. To control the triac I want to use pins A4 or A5, because others are occupied. I have tried the following functions and methods, but nothing seems to put the pins to HIGH state:

     1. pinMode(A4, OUTPUT);
        digitalWrite(A4, HIGH);
     2. pinMode(18,OUTPUT);
        digitalWrite(18,HIGH);
     3. DDRC |= (1 << DDC4);
        PORTC |= (1 << PC4);

I have tried the same things with A5 and other A# pins to no avail. The only pin that works is A0. Only when the triac is connected to it, the lamp lights on.

Is this a valid way to set analog pins?

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

    void loop(){
      digitalWrite(A4, HIGH);
    }

 * Edit: My code was quite messy, it appears that some other functions prevented from using pins A4 or A5. It is working now.
 * It was the DS1307Emulator library. After initialization I had to use `DS1307Emulator.busDisconnect();`
Didn't know it uses I2C.

[![Schematic][1]][1]

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

title: Analog pins as output by using digitalWrite

Answers: 1

body:
My code was quite messy, it appears that some other functions prevented from using pins A4 or A5. It is working now.
    It was the DS1307Emulator library. After initialization I had to use DS1307Emulator.busDisconnect();
    Didn't know it uses I2C.


body:
We are doing a project and have to use around 25 temperature sensors. Is there a way to shift through them on one Arduino similar to using a shift-register?

It is a set of analog sensors in a fridge.

title: Is there a way to shift through sensors

Answers: 4

body:
Have you looked at [OneWire temperature sensors][1]? You connect them to a [bus IC][2] and the bus IC to your Mcu. This allows you to multiplex many sensors.

You can also forego the master bus IC and just bit bang using a GPIO pin. The Arduino [OneWire library][3] uses this approach.

You can learn a lot about from this [one wire sensors tutorial][4].

[1]: https://www.maximintegrated.com/en/products/analog/sensors-and-sensor-interface/DS18S20.html
[2]: https://www.maximintegrated.com/en/products/interface/controllers-expanders/DS2482-100.html
[3]: https://github.com/PaulStoffregen/OneWire
[4]: https://playground.arduino.cc/Learning/OneWire

body:
Another way to do this is with a series of actual shift registers (74HC595 or similar, daisy-chained.)

The shift register outputs drive a transistor. Each transistor has its collector connected to the temperature sensor, and the emitters are all collected into a single Arduino input. Depending on the number you shift into the shift register, you can pick any of the temperature sensors you want to query.

[![Simplified schematic][1]][1]

The LED in this simplified schematic actually represents the Arduino input pin. Shift a 2 into the register to query T1; 4 to query T2; 8 to query T3, and so on.

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

body:
If you are using analog sensors, consider using the [CD4051B analog multiplexer][1] (link to data sheet). It's great for expanding analog I/O pins.

  [1]: http://www.ti.com/lit/ds/schs047i/schs047i.pdf

body:
As I mentioned in the comments, one way to do this is to use a multiplexer.

You haven't said which temperature sensors you are planning to use, so I'll illustrate this example using the [TMP36][1] Analogue temperature sensor.

Now, if you were using just one of these, the connection would be trivial:

![Single TMP36 sensor][2]

But you want more sensors than available pins. That's where the multiplexer comes in.

I'm going to illustrate this using 16 sensors and the [Sparkfun 16-channel multiplexer][3] breakout board which is based on the [74HC4067][4] multiplexer. For 25 sensors, you could use a 32-channel multiplexer (like the Analogue Devices [ADG732][5], for example), or just combine two 16-channel multiplexers (which is probably cheaper, but requires a little more care in the wiring).

[If your soldering skills are OK, I wouldn't even bother with the Sparkfun breakout board myself. It's pretty simple to connect something like this on protoboard, or make your own PCB.]

The 16 sensors are connected to pins Y0 - Y15 on the 74HC4067 (pins C0 - C15 on the Sparkfun board). **Take care** to note which sensor is connected to which pin!

With 16 inputs, we need 4 bits to address them. The address pins are labelled S0 - S3. The Sparkfun [datasheet][6] for their breakout board includes a Truth Table mapping the addresses to the inputs:

![Truth table][7]

The input from the selected device becomes the output from the multiplexer (pin Z on the 74HC4067; the SIG pin on the Sparkfun breakout board).

The diagram below shows one way of connecting 16 TMP36 analogue temperature sensors to an Arduino Nano using the Sparkfun breakout board:

![Nano multiplexer][8]

Note the mapping chosen for the address pins:

 - D5 -> S0
 - D4 -> S1
 - D3 -> S2
 - D2 -> S3

This makes the drawing layout simpler, but may not be the most intuitive mapping when you come to write your code. My advice is to assign meaningful labels to the pin-mappings in your code, **and document that decision with comments!** (I'm sure that I'm probably preaching to the choir here, but this may help someone reading this in the future to avoid some of the pitfalls.)

Now, you cycle through a loop:

    while true {
        increment the address to be written to pins D5-D2 (note the order)
        read the input on A0
        <do whatever you need to do with the temperature reading>
    }

And Robert is the male relative of your choice.

  [1]: http://www.analog.com/media/en/technical-documentation/data-sheets/TMP35_36_37.pdf
  [2]: https://i.stack.imgur.com/DUoo1.png
  [3]: https://www.sparkfun.com/products/9056
  [4]: https://assets.nexperia.com/documents/data-sheet/74HC_HCT4067.pdf
  [5]: http://www.analog.com/en/products/switches-multiplexers/analog-switches-multiplexers/adg732.html#product-overview
  [6]: https://www.sparkfun.com/datasheets/IC/cd74hc4067.pdf
  [7]: https://i.stack.imgur.com/lUo4Z.png
  [8]: https://i.stack.imgur.com/ZOTWQ.png


body:
I recently got my wifi module and connected it to my Uno. I am now trying to send a http request. I have the code that comes with the esp8266wifi library in which it demonstrates and gives an example on how to send a http request. This is the code:

[CODE.][1]

I am getting the following error

        Arduino: 1.8.4 (Windows 8.1), Board: "Arduino/Genuino Uno"

    In file included from C:\Users\Yasmeen\Documents\Arduino\libraries\ESP8266WiFi\src/ESP8266WiFi.h:33:0,

                     from C:\Users\Yasmeen\AppData\Local\Temp\arduino_modified_sketch_200757\HTTPSRequest.ino:14:

    C:\Users\Yasmeen\Documents\Arduino\libraries\ESP8266WiFi\src/ESP8266WiFiType.h:26:19: fatal error: queue.h: No such file or directory

     #include <queue.h>

                       ^

    compilation terminated.

    exit status 1
    Error compiling for board Arduino/Genuino Uno.

Obviously it seems to be an file path error but I'm not sure why. I've imported the library through the Arduino IDE.. But maybe the way I aquired the library was wrong? What I did was download the esp8266wifi folder ([here][2]) and zipped the file and imported it.. is that okay to do?

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

title: Getting no such directory file error when compiling

Answers: 1

body:
The ESP8266WiFi library is for programming the ESP8266 directly. You are trying to compile source code for the ESP8266 for the Arduino UNO, that obviously won't work.

[A Beginner's Guide to the ESP8266](https://tttapa.github.io/ESP8266/Chap01 - ESP8266.html)


body:
This is my first post and I am a little bit confused about one thing.
I would need to do the following project:
have about 5-6 load cells to be connected to a microcontroller.
I am not sure if there is a way to connect multiple load cells to the same arduino.
I would need each load cell to act individually, so I would need an individual result from all each load cell.

I believe I would need to connect 1 load cell to 1 load cell amp and then connect the load cell amp to the Arduino and repeat this process 5-6 times (for each load cell that I need)

I'm not sure if this is possible using one Arduino or I would need 1 Arduino for each individual load cell.

The main idea of the project is to have a load cell to be placed under different kitchen supplies (1 load cell to continuously check the weight of Flower, another one to check for bread, another to check for paprika, and so on)

After this is read from the sensors, I need to write the weight of each item in a table / DB every 30 minutes.

Also, if this can be done with another board, like a microcontroller (Raspberry Pi) I'm open to that.

title: Connecting multiple load cells to the same microcontroller

Answers: 3

body:
All you need is the following :

 - Arduino (Mega, if you need alot of inputs.)
 - Load Cell Amplifier
 - Load Cells (I recommend only using four wire cells)
 - Resistors (Only if you are connecting one cell to one amplifier)

If you are using only one load cell per "Scale" , you would connect it as you say correctly. One load cell to each load cell amplifier and then to the Arduino.

Yes, a single Arduino can in theory take as many scales as the number of Digital inputs you have can provide. You can use the Analog inputs as well but from my experience I would recommend you only use the Digital inputs. You can just share the power and ground sources.

Usually each Load Cell Amplifier will need to use two(2) Digital inputs.

If you want to use multiple load cells together (to improve accuracy) to act as a single scale, you would connect them together in what they call a Quarter, Half or Full Bridge wiring configuration depending on how many you would like working together.

You can write to a DB if you want sure.
What I personally like to do is send the readings to the cloud using dweet.io or ThingSpeak. ThingSpeak.com would probably be best for you.

I usually use the NodeMCU arduino boards that have WiFi built in. They are cheap and work great.

I hope this helps.

body:
I had a similar project awhile back that involved multiple flex sensors. I ultimately had to use multiple op amps to boost each signal from the flex sensors.
Some IC contain multiple op-amps though which will lessen your circuit footprint.
Each output of the op amp was run to a separate ADC channels on an Arduino. Depending on your Arduino you should have 8 (mini) - 16 (mega) analog pins to read your sensors.

body: You can use multiplexers to multiplex the loadcells and you can select the loadcells using only less selector pins


body: Since a Floating Point Unit (FPU) is not present in Arduino Uno, I wanted to know how float operations are performed. If it is simulated as integer operations, I want to know how exactly the simulation is done.

title: Floating-point without FPU

Answers: 2

body:
software emulation. The float is decomposed into sign, exponent and mantissa and then integer operations are used to do the actual math.

Addition and subtraction means shifting the mantissas to a common magnitude, adding/subtracting them and then checking the highest set bit for the new exponent.

Multiplication means adding the exponents and multiplying the mantissas. Division is subtracting.

body:
As I said in my comment, all float operations are implemented in
software. As a simple test, I compiled the following program:

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

 volatile float x, y, z;

 int main(void)
 {
  z = x + y;
  return 0;
 }

The compiler translated the sum operation into a call to `__addsf3`.
This function extends its arguments to `flt40_t` format (non-standard 40
bits float), calls `__addsf3x` to do the 40-bit addition, then calls
`__fp_round` to convert the result into the standard `float` format.
`__addsf3x` also makes a few library calls of its own. In the end, the
addition pulled the following functions into the compiled program:
`__subsf3`, `__addsf3`, `__addsf3x`, `__fp_inf`, `__fp_nan`,
`__fp_pscA`, `__fp_pscB`, `__fp_round`, `__fp_split3`, `__fp_splitA`,
`__fp_zero` and `__fp_szero`.

All these functions are provided by the avr-libc. You can find them in
the [libm/fplib directory][fplib]. See for example the files:

- [addsf3.S][]
- [addsf3x.S][]
- [fp_round.S][]

[fplib]: http://svn.savannah.gnu.org/viewvc/avr-libc/trunk/avr-libc/libm/fplib/
[addsf3.S]: http://svn.savannah.gnu.org/viewvc/avr-libc/trunk/avr-libc/libm/fplib/addsf3.S?revision=2473&view=markup
[addsf3x.S]: http://svn.savannah.gnu.org/viewvc/avr-libc/trunk/avr-libc/libm/fplib/addsf3x.S?revision=2473&view=markup
[fp_round.S]: http://svn.savannah.gnu.org/viewvc/avr-libc/trunk/avr-libc/libm/fplib/fp_round.S?revision=2191&view=markup


body: In a line there're voltage levels representing words of dots and dashes. In particular, the device is intended to raise an output each time a given pattern of five short/long signals (say 1s and 2s durations, respectively) is recognized (and restart if nothing comes in for a given time). A sort of Morse code recognizer (Arduino Uno preferred, but others are also OK) would be a good starting point. Any hint is welcome, I'm new in this community.

title: Recognize Morse-like code words

Answers: 1

body:
Use a GPIO of an Arduino and check (at the speed you need) the HIGH/LOW state.

Depending on the speed at which is sent, you can check the dots and dashes being sent, e.g. by keeping a timer since the last change checking if it is a short or long 'HIGH'.

You have to sample often enough to check if there is a drop (between dots/dashes).


body:
I am new to the whole arduino scene. I have connected my wifi module (esp8266 v01) to my arduino Uno like this:

http://www.teomaragakis.com/hardware/electronics/how-to-connect-an-esp8266-to-an-arduino-uno/

And have downloaded the arduino ide framework so that I may be able to use the arduino IDE as opposed to sending AT commands through the serial monitor.

When trying to upload an example sketch that sends a http request that I found on github, I get the following error:

        Arduino: 1.8.4 (Windows 8.1), Board: "Generic ESP8266 Module, 80 MHz, 40MHz, DIO, 115200, 512K (64K SPIFFS), ck, Disabled, None"

    Archiving built core (caching) in: C:\Users\Yasmeen\AppData\Local\Temp\arduino_cache_354217\core\core_esp8266_esp8266_generic_CpuFrequency_80,FlashFreq_40,FlashMode_dio,UploadSpeed_115200,FlashSize_512K64,ResetMethod_ck,Debug_Disabled,DebugLevel_None_____9d1d735445f8d7bf19746e2177d24e71.a
    Sketch uses 285417 bytes (65%) of program storage space. Maximum is 434160 bytes.
    Global variables use 38688 bytes (47%) of dynamic memory, leaving 43232 bytes for local variables. Maximum is 81920 bytes.
    error: failed reading byte
    warning: espcomm_send_command: cant receive slip payload data
    error: failed reading byte
    warning: espcomm_send_command: cant receive slip payload data
    error: failed reading byte
    warning: espcomm_send_command: cant receive slip payload data
    error: failed reading byte
    warning: espcomm_send_command: cant receive slip payload data
    error: failed reading byte
    warning: espcomm_send_command: cant receive slip payload data
    error: failed reading byte
    warning: espcomm_send_command: cant receive slip payload data
    error: failed reading byte
    warning: espcomm_send_command: cant receive slip payload data
    error: failed reading byte
    warning: espcomm_send_command: cant receive slip payload data
    error: failed reading byte
    warning: espcomm_send_command: cant receive slip payload data
    warning: espcomm_sync failed
    error: espcomm_open failed
    error: espcomm_upload_mem failed
    error: espcomm_upload_mem failed

After looking online and researching, I can see that it has something got to do with flashing the firmware or something. I came across this question:

https://arduino.stackexchange.com/questions/44445/esp8266-error-espcomm-upload-mem-failed-while-uploading-sketch

and the answer did say that he bought a converter.. what does this mean? Does it mean buying this?:
https://www.amazon.co.uk/gp/product/B06Y3FNGJF/ref=oh_aui_detailpage_o00_s00?ie=UTF8&psc=1

I really need help, been stuck on this for the past few days now and seriously contemplating whether to get the arduino wifi shield since it comes prebuilt with wifi.. even though it costs quite a lot!

title: error: espcomm_upload_mem failed when uploading a sketch

Answers: 5

body:
The ESP8266 has two "modes". "Run" mode and "Flash" mode.  In "Run" mode the firmware installed onto the ESP8266 executes. The default firmware is the AT firmware that allows you to control the device with AT commands through serial.

Note that the site you link to has erroneous information about CH_PD that should be talking about GPIO0.

In "Flash" mode you get to upload new firmware (AKA a "sketch") to make the device do something different.

The basic programming sequence is:

1. Switch the device to Flash mode (connect GPIO0 to GND)
2. Upload the sketch using the IDE
3. Switch the device to Run mode (connect GPIO0 to 3.3V).

Because of these extra steps many people choose to invest in a small USB interface board designed specifically for programming the ESP8266 to make their life easier. These generally have a switch on them to set whether GPIO0 is connected to GND or 3.3V.

body:
By default, the ESP8266 runs the program in flash memory.
To upload new firmware over UART, you have to change the boot mode by connecting GPIO0 to ground during reset.
GPIO15 should be low and GPIO2 should be high during boot in both cases. GPIO needs an external pull-down resistor, the internal pull-up resistor for GPIO2 is enabled during boot, so you don't need to add an external one.
To prevent from shorting GPIO0 if it's used as an output in your sketch, it's recommended to add a series resistor to limit the current.

![ESP8266 schematic][1]

**To upload a sketch**:
1. press and hold the reset button
2. press and hold the program button
3. release the reset button, the ESP will boot in program mode
4. release the program button
5. upload the sketch

If your USB-to-Serial breaks out the RTS and/or DTR lines, you can [automate the reset and programming mode procedures][2].

  [1]: https://tttapa.github.io/Images/ESP8266-2.png
  [2]: https://tttapa.github.io/ESP8266/Chap06 - Uploading.html

body:
I had the same issue while uploading to the NodeMCU.

The issue was that the mode was not selected to `program mode` even after doing the below steps:

1. press and hold the reset button
2. press and hold the program button
3. release the reset button, the ESP will boot in program mode
4. release the program button
5. upload the sketch

To solve the issue, do this:

1. short the pin GPIO 0(D3) to ground using a jumper wire.
2. press reset button
3. upload the sketch
4. remove the jumper wire

Done!!!!

body:
This is one of the simple solutions that worked for me:

1. Plug out the USB connection with the computer;
2. Hold the flash button on the nodemcu/esp8266;
3. Plug in the usb connection and quickly release the flash button;
4. Now try uploading the sketch.

Thank you.

body:
depending on the USB speed cable that you are using, sometimes this problem often occurs if I use a cable that is not suitable. if your com setting is 9600 then you have to set up upload speed in the tools menu -> upload speed faster than 9600 ... for exp: 57600.
this is should be work!!


body:
I'm just learning how to use the Arduino Uno and I'm trying to control the speed of an AC fan. I made a sketch of this project on proteus but the triac seems not to be responding. I guess there's a problem with the attachInterrupt part of the code. Here's the code:

    #define triacPulse 5
    #define interruptPin 2

    //button event
    #define button1 6

    void setup() {
      // put your setup code here, to run once:
      pinMode(button1, INPUT);
    }

    void loop() {
      // put your main code here, to run repeatedly:
      if(button1==HIGH){
        attachInterrupt(0, triacControl, FALLING);
      }
    }

    void triacControl()
    {
      delay(5);   //delay for 5 milliseconds
      digitalWrite(triacPulse, HIGH);
      delay(5);

      digitalWrite(triacPulse, LOW);
    }

Thanks for the answer in advance

title: Attach Interrupt problem

Answers: 1

body:
First of all your if statement will always be false. You ask if 6 equals 1 (from arduino.h).
It schould be `digitalRead(button1) == HIGH`. Also it looks like your button should start an impulse of 5ms. Am I right?
In this case you will attach the Interrupt to the Button. Also don't put delays in the Interrupt function. Another thing, that isn't important in small Projects only for you, is to increase the readability by typing "define constants" uppercase, so you know where to find them and that they aren't changeable variables (For this reason HIGH, LOW, INPUT, RISING, ... are all uppercase).

All in all the code should be look like this:

    #define BUTTON1PIN          6
    #define TRIACPIN            5
    #define TRIACPULSE          5                       // [ms]

    bool doPulse = false;
    long triacStartTime = 0;

    void setup(){
      pinMode(BUTTON1PIN, INPUT);
      pinMode(TRIACPIN, OUTPUT);
      attachInterrupt(BUTTON1PIN, pulseISR, RISING);    // attach a Interrupt once!
                                                        // pulseISR is called everytime the button is pressed
                                                        // ISR: Interrupt service Routine (only for Readability)
    }

    void loop(){
      if(doPulse){
        digitalWrite(TRIACPIN, HIGH);
        triacStartTime = millis();
        doPulse = false;
      }
      if(millis() > triacStartTime + TRIACPULSE){        // Shut down after 5 ms
        digitalWrite(TRIACPIN, LOW);
      }
    }

    void pulseISR(){
      doPulse = true;                                    // NO delays in ISR! And as short as possible
    }


body: Is it possible to use some sort of multitasking OS like ScmRTOS on Arduino based on Atmel 328 chip?

title: Operating system on Atmel 328 Arduino?

Answers: 1

body:
You can use FreeRTOS on the AVR family:

* http://www.freertos.org/a00098.html


body:
After spending countless hours trying to get my wifi module to work only to fail, I've decided I might as well get an [Arduino with built-in wifi][1].

Would I be able to send HTTP requests (GET, POST etc) straight out of the box or would I have to configure and connect some additional components/modules to the board?

Also, I plan on connecting a thermistor and a GPS module to the Arduino. When the thermistor reaches a certain level, it sends the GPS coordinates of my server. Is this possible in terms of practicality and voltage? And would I be able to write a sketch using the Arduino board or would I have to switch the board to something like 'Generic ESP8266 Module' (something we have to do if we want to program the ESP8266 using the Arduino IDE).

  [1]: https://www.amazon.co.uk/Arduino-A000008-Yun-Microcontroller/dp/B00MBCGWQQ/ref=sr_1_21?s=computers&ie=UTF8&qid=1506630245&sr=1-21&keywords=arduino wifi

title: Will I be able send a HTTP request using the Arduino Yún?

Answers: 1

body:
Looking at your other two questions as well I see you have had limited success with a ESP8266.  I have never used a Yun, but I haven't seen much good stuff about them on here.  If you want a Linux based none real time system then you may as well get a PI.

Most people seem to think the way to use an ESP8266 is to hook it up to an Arduino and use it as a 'serial over wifi' link.  You can do that, but its like owning a Porsche and Kia and always using the Kia on Motorway journeys.  The ESP8266 is an 80MHz chip with 0.5 MByte of RAM, and you could program it in just the same way as an Arduino if you download the board support package.  It does have only 10 Digital pins and 1 Analog (which I think has lower resolution that the Arduino), but that's where the Arduino comes in.  If you need to hook up lots of pins, then stick the Arduino on the I2C bus as a slave to the ESP.

Now I suspect you have an ESP-01 board and are wondering what the [heck] I am talking about, 10 pins.  The number '01' is the number of GPIO pins that are taken to the edge of the board, so really you want to look at ESP-12E or ESP-13E boards (they still cost about the same $1).  You might want to look at a Wemos D1 or a Node MCU.  Both are fully fledge dev boards, jus plug in the USB and away you go.

So to answer your question:

Get a Wemos D1, hook the hardware up like you wood the Arduino (thermistor and GPS - via SoftwareSerial) and then either code a web server to run on the Wemos or Get it to Post message to you favourite server (see examples for details of either approach)


body:
I want to create a system to separate between an aluminum can and a plastic bottle.

Both are lightweight, so I'm thinking of using the transparency property, meaning that the can is not transparent, but the plastic bottle is.

Will the light sensor work out?

Or would you suggest me another type of sensor I should use?

title: What sensor is used to judge transparency?

Answers: 2

body:
A light sensor should work. If the aluminium can reflect much light, you can consider putting the light and light sensor on the same side, close together.

If not, put the light and light sensor of opposite sides so the light beam goes through the bottle.

body:
A light sensor should work. Another option would be an inductive Sensor to detect the Aluminium Can. And if you need to know if there is a Can in your sensor area you can combine it with an IR (or capacitive) Sensor, which should detect both Can types.

So it would be something like this:

    if(IRdetect == true){
      if(inductive == true){
        type = alu;
      }else{
        type = plastic;
      }
    }else{
      // no Can
    }

Some cheap sensors as Example:

 - Inductive: [Banggood][1]

 - Infrared: [Banggood][2]

  [1]: https://www.banggood.com/Wholesale-NPN-DC-6-36V-Inductive-Proximity-Sensor-Detection-Switch-p-41603.html?rmmds=search
  [2]: https://www.banggood.com/Adjustable-Infrared-Proximity-Switch-Photoelectric-Detect-Sensor-NPN-p-1046453.html?rmmds=search


body:
The project is to make a 4WD car using arduino uno(clone) and four toy dc motors. I am using a adafruit motor shield v1.2(clone). The car is required to run autonomously, please suggest batteries for the arduino and the shield.
Also when I am using external power connector for arduino, all the motors start at different timing.

title: Power source for arduino project

Answers: 2

body:
I've been using usb power packs.

 - Easy to source (can be found in all electronics stores and many general stores).
 - Come in many sizes (500mAh to 20,000 mAh are common).
 - Rechargable, usually by using a generic phone changer with a usb micro connector.
 - Not costly.
 - Quite roubust.
 - Most Arduino boards and many motor driver boards are designed to be powered from usb.

Make sure you get one that is rated for enough current for your project.

body:
Car batteries are wonderful, and almost never explode. A badly mistreated Li-{Fe,Po,Ion}, however... ouch. Otherwise use banks of NiMh/NiCd.

If you don’t fear death, use Li-Ion batteries with a TP4056 + DW01A IC, it can handle charging from USB, and provides over-discharge protection, so your batteries don’t die.
https://www.addicore.com/TP4056-Charger-and-Protection-Module-p/ad310.htm
It also has current limiting built-in.


body:
I have some problems with i2c. I can not use long wires on SDA and SCK bus.

This seems to be the consequence of the capacity between the SDA and SCK wires and not between SDA/SCK and GND.

I figured this out by placing capacitors in a breadboard with a Arduino UNO and some MCP23017's (with 2k2 pull-up resistors).

100pF capacitor between SDA and SCK: No problem.

150pF: The communication stops.

1nF from SDA to GND and/or 1nF from SCK to GND: No problem.

A two wire cable is approx 50pF per meter, so 2 meters seems the limit.

With an ATtiny85 (8MHz clock, 100k i2c speed) as master it is even worse:
With 2k2 pull-up a capacity of 68pF is killing.

By reducing the pull-up resisters to 470E I was able to go up to 200pF  (hurray: 4 meters of wire).

Someone any idea how to increase the distance by tuning the SDA/SCK timing?

title: i2c wire length

Answers: 2

body:
As @majenko wrote, the I2C bus was not designed to go over wires or into a cable. It is ment for components on the same pcb board.
As @mikaelpatel wrote there are bus drives which convert the I2C signal into some kind of RS-485 signal for twisted pair cables.

The crosstalk between SDA and SCL should be avoided at all times. Don't put SDA and SCL into wires that are next to each other. When using twisted pair cable (for example Cat5), then use SDA in a different pair than SCL.
The worst situation is when SDA and SCL are next to each other in a flat ribbon cable.

The capacitance caused by the cable from SDA to GND and from SCL to GND can be compensated some by a lower value of the pullup resistors and by lowering the clock speed.

The maximum current is specified as 3 mA. That means with 5V, the lowest value for the pullup resistor is 1k6.
A little more can be achieved with a current driver of 3 mA instead of the pullup resistors. This is not often done, but it creates a better signal.

The Arduino Wire library for the Arduino Uno can be set to 50 kHz with Wire.setClock. I don't know the lowest value, but there is a limit without warning. I don't know the lowest clock speed for an Attiny microcontroller. A software I2C bus implementation can often go much lower.
*Note that some sensors have a minimum clock speed.*

The rule of thumb is that 50 cm is the maximum for the I2C wires. However, some say that they are able to use the normal I2C bus over 6 meters cable. My opinion is that the I2C should always work, since it is not very fault tolerant, and the Arduino Wire library for the Arduino Uno is not fault tolerant at all. Therefor, don't go near the limits.

The [MultiSpeedI2CScanner][1] (probably only working for Atmega chips) helped me a lot to learn about the I2C limits in different situations.

  [1]: https://github.com/RobTillaart/Arduino/tree/master/sketches/MultiSpeedI2CScanner

body:
With 2 shielded cables, separate for SDA, SCL no problem to go several meters.

I just connected 2 I2C devices on common shielded cables 6m long SDA, SCL
3.3V and GND on non-shielded cables

Successfully tried also computer mice shielded cables, it's about 1.5m working no problem

Pull up resistors approx. 4k7


body:
I'm working on project which for example 3 nodemcu connected with eachother in a line(1 connected to 2 and 2 connected to 3) and they are all in access-point mode (they are all server) and now my problem is how to communicate between 1 to 2 and 2 to 3 i have tried tcp but its for server-client

any help would be appreciated

title: How To Communicate Three NodeMcu In Access Point Mode

Answers: 1

body:
Look at the WiFi library. The function WiFi.mode() can set your NodeMCU as access point, station or both access point and station (WIFI_AP, WIFI_STA, WIFI_AP_STA or WIFI_OFF).

In the mode WIFI_AP_STA, your NodeMCU works both as access point and as a station independently; no need for special considerations.

You still need to know the IP address of each NodeMCU to make them to talk to each other. You can configure things to get fixed IP for each NodeMCU as a station.


body:
As is known, the speed of sound depends of [temperature and Relative Humidity](http://www.rane.com/pdf/ranenotes/Enviromental_Effects_on_the_Speed_of_Sound.pdf). I'm trying to calibrate HC-SR04 sensor taking account these factors.

In [SparkFun page](https://www.sparkfun.com/products/13959) there is no mention about environmental conditions in calibration (only is informed that speed of sound is 340 m/s). I found [a paper](http://www.sciencedirect.com/science/article/pii/S221302091630163X) with some calibration, but again it is no mention of original conditions.

I'm using the time elapsed per response to calculate distance in Arduino with access to a temperature & humidity chamber, so I want to recreate the calibration conditions to probe if the sensor is accurate.

Anyone know the environmental conditions of HC-SR04 calibration?

title: HC-SR04 calibration conditions

Answers: 1

body:
The HC-SR04 is not calibrated, nor does it take any measurements.

All it does is allow *software* on a connected microcontroller or system like an Arduino to measure the sum of the round trip time delay and some small internal offset delay, and from this calculate distance.

As the timing and calculation are entirely in *your* program, calibration is entirely up to you.

Under known conditions you could measure both a short and a long distance.  This would give you a slope and intercept - the slope from the speed of sound (which should not depend on the device at all, only on the conditions and your timing reference), and the intercept or offset, having to do with latencies in the system.

You could then cross-check at other distances, but under fixed conditions behavior should be linear.

As there is some initial ringing of the sender which can couple to the receiver and be mistaken for an echo, there will be a minimum distance below which you cannot reliably take a reading - as a guess, this is more than 5 cm, but you'll have to see, and it may even vary a little from unit to unit.

*To a degree, it's a little bit amazing that these even work.  They use an RS232 level shifter to generate transmit pulses, and it's been alleged that the receive circuit is horribly mistuned, not really matching the emitted frequency at all... but despite that they do seem to work fairly well*.


body: I am looking for a low power solution for my ATmega32U4. It uses Serial1 to communicate with Bluetooth, so I need to have it active. When I receive data from Serial1, I want to power up the Arduino, do some magic, and then power it off...

title: Arduino with ATmega32U4 low power but keep Serial1 working

Answers: 1

body:
For Power Down/Standby Mode you would have to use an Interrupt Pin to reactive the MCU. If you do not mind possible loss of the first character you could connect an Interrupt Pin to Serial1 RX and wake up on the first start bit.

The startup delay (i.e. time until UART is up and working) may impact the first character received. You could always start off by sending a number of null character as a "wake up call"; classical break sequence.

Cheers!

Ref. ATmega16/32U4, Chap. 7. Power Management and Sleep Modes.