body:
I want to use an Arduino Genuino Zero as a Modbus slave. I tried to search on google, and found [a library][1]. When I try using the library, I get a timeout error.

Can anyone tell me how to solve that error? Did anyone manage to get the Arduino Modbus RTU slave library working?

  [1]: https://www.dropbox.com/s/a277isxsxqurnpk/MODBUS.rar?dl=0

title: Modbus RTU slave library

Answers: 2

body:
I am unable to simulate and see the result right now; I hope if the library functions properly this might be a communication issue. I can add a one step debug for you to check and see what is happening.

Your device is acting as a Modbus RTU slave, So take another Arduino, make it act it like a master device, and see what response is coming from the slave device.
Here is a glimpse of code I used to make arduino as a master and see the response coming in Serial terminal.

        #include <SoftwareSerial.h>
        #define rxPin 2
        #define txPin 3

        #define RS485_pin 10
        //SoftwareSerial mySerial(rxPin, txPin);
        #define mySerial Serial1

        byte test_data[8] = {0x01,0x03,0x00,0x64,0x00,0x02,0x85,0xD4};

        int data_count = 5;
        byte rcvdata[15];
        int param_value_int[7];

        void setup() {
          // put your setup code here, to run once:
        //mySerial.begin(19200,SERIAL_8E1);
        mySerial.begin(9600);
        Serial.begin(9600);
        delay(1000);
        pinMode(RS485_pin, OUTPUT);
        digitalWrite(RS485_pin,LOW);
        delay(100);
        }
        int count = 0;
        void loop() {

          if(count == 0) {
            Serial.println();
            send_data();
          }

          count++;

          while(mySerial.available()>0)
          {
            byte b=mySerial.read();
            delay(1);
            Serial.print(b,HEX);
            Serial.print(" ");
          }
          //Serial.println(count);
          while(Serial.available())
          {
            digitalWrite(RS485_pin,HIGH);
            byte a=Serial.read();
            delay(1);
            mySerial.print(a);
            digitalWrite(RS485_pin,LOW);
           // Serial.print(a);
          }

          delay(1000);
          //while(1);
        }

        void send_data() {
          Serial.println("send data");

          digitalWrite(RS485_pin,HIGH);
          delay(1);
          for(char i=0;i<8;i++){
            mySerial.write(test_data[i]);
            delay(1);
            Serial.print(test_data[i],HEX);
            Serial.print(" ");
          }

          Serial.println();
          digitalWrite(RS485_pin,LOW);
          delay(1);
        }

Here you can use Software Serial or normal Serial1 or Serial2 on devices like Mega. Make sure if it is RS485 based you have to toggle the RS485 read-write pin each time to enable and disable one feature at a time as RS 485 uses half-duplex communication.

In this case test_data[] uses Function code FC03 Read holding register. You can make your custom data. I am assuming you are familiar with all the types available.Still there is a great site [  [ link](http://www.simplymodbus.ca/FC03.htm) ] to look up to if you don't know the basics. The last two bytes are checksum. And there is an online checksum calculator available if you need also
 <https://www.lammertbies.nl/comm/info/crc-calculation.html>

In this way you can at least debug and share the result, so that we can help more.

body:
so i edited code your as below
    #define mySerial Serial1

    byte test_data[8] = {0x01,0x03,0x00,0x64,0x00,0x02,0x85,0xD4};

    int data_count = 5;

    void setup() {

    mySerial.begin(9600);
    Serial.begin(9600);
    delay(1000);

    }
    int count = 0;
    void loop() {

      if(count == 0) {
        Serial.println();
        send_data();
      }

      count++;

      while(mySerial.available()>0)
      {
        byte b=mySerial.read();
        delay(1);
        Serial.print(b,HEX);
        Serial.print(" ");
      }
      //Serial.println(count);
      while(Serial.available())
      {

        byte a=Serial.read();
        delay(1);
        mySerial.print(a);

      }

      delay(1000);

    }

    void send_data() {
      Serial.println("send data");

      delay(1);
      for(char i=0;i<8;i++){
        mySerial.write(test_data[i]);
        delay(1);
        Serial.print(test_data[i],HEX);
        Serial.print(" ");
      }

      Serial.println();

      delay(1);


body: Since I'm running out of sketch memory, I've decided to use the 512 bytes of EEPROM memory by using `EEPROM.put(addr,variable)`. But every time I use this my sketch memory use in gradually increasing. What am I missing in writing data to EEPROM? Why is the sketch memory use increasing? I'm using Arduino Pro Mini.

title: Sketch Memory and EEPROM

Answers: 1

body:
> What am i Missing in writing data to EEPROM ? Why is the Sketch memory getting increased ?

Reading and writing to EEPROM will increase program memory size. They are function calls. One way to reduce code is to read/write blocks instead of single bytes. Post some code and we can help you rewrite to something smaller. There are plenty of tricks.


body:
I am trying to get the status of appliance using current sensor. My Circuit looks like below image. I don't want to measure current. I just want to know whether appliance is on or off.

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

I am getting following readings when power turned on and off, I don't see any difference, I am not able to figure out whether the bulb is on or off.

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

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

Please help me to know the status of appliance/bulb.

PS. Please find my code below:

    /*
    Measuring AC Current Using ACS712
    www.circuits4you.com
    */
    const int sensorIn = A0;
    int mVperAmp = 185; // Use 100 for 20A Module and 66 for 30A Module

    double Voltage = 0;
    double VRMS = 0;
    double AmpsRMS = 0;

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

    void loop(){

     Voltage = getVPP();
     VRMS = (Voltage/2.0) *0.707;  //root 2 is 0.707
     AmpsRMS = (VRMS * 1000)/mVperAmp;
     Serial.print(AmpsRMS);
     Serial.println(" Amps RMS");
    }

    float getVPP()
    {
      float result;
      int readValue;             // value read from the sensor
      int maxValue = 0;          // store max value here
      int minValue = 1024;       // store min value here

       uint32_t start_time = millis();
       while((millis()-start_time) < 1000)  // sample for 1 Sec
       {
           readValue = analogRead(sensorIn);
           // see if you have a new maxValue
           if (readValue > maxValue)
           {
                /*record the maximum sensor value*/
               maxValue = readValue;
           }
           if (readValue < minValue)
           {
               /*record the minimum sensor value*/
               minValue = readValue;
           }
       }

       // Subtract min from max
       result = ((maxValue - minValue) * 5.0)/1024.0;

       return result;
     }

title: How to find if AC Appliance is on or off using ACS712 current Sensor

Answers: 1

body:
The code looks like it would produce rather larger values than you are seeing, if it gets correct inputs from the sensor.  For that reason, you probably should carefully check your wiring.  Also, with a DVM, measure the sensor output voltage with the light on and with it off, to verify sensor operation.  If you measure ok sensor voltages but don't get good readings, your analog input pin may have a problem; you could try other analog input pins.

Note, when debugging an issue like this, it does not make sense to run a few numbers through five levels of processing before printing anything out.  You should at least add serial prints in `getVPP()`, and just before returning the result, print out `result`, `maxValue`, and `minValue`.

Note, fix the erroneous comment “//root 2 is 0.707”; the square root of 2 is about 1.414213562, while 1/√2 = (√2)/2 is about 0.707106781.


body:
Firstly i printed input[16] then encrypted it and printed the cipher and finally decrypted and printed input[16] but why my result is not matching after decryption ???????

I tried with different baud rate and also different input output array but not working.

Library Used: https://rweather.github.io/arduinolibs/classCBC.html

    #include <CBC.h>
    #include<AES.h>
    CBC<AES128> cbc;

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

     uint8_t key[16] = {0,1,2,3,4,5,6,7,8,9,10,11,12,13,14,15};
     uint8_t iv[16] = {0,1,2,3,0,1,2,3,0,1,2,3,0,1,2,3};
    uint8_t input[16] = {0,1,2,3,0,0,0,0,0,1,1,1,2,2,3,3};
    size_t len = 16;

    cbc.setKey(key, 16);
    cbc.setIV(iv, 16);

    for(int i=0; i<16; i++)
    Serial.print(input[i]);
    Serial.println("");

    cbc.encrypt(input, input, len);
    delay(1000);

    Serial.print("input:");
    for(int i=0; i<16; i++)
    Serial.print(input[i]);
    Serial.println("");

    cbc.decrypt(input, input, len);
    delay(1000);

    Serial.print("input:");
    for(int i=0; i<16; i++)
    Serial.print(input[i]);
    Serial.println("");

    cbc.clear();
    }

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

    }
[![Output][1]][1]

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

title: AES 128 CBC mode Help

Answers: 0


body:
I have an ESC that powers 36v 3 phase BLDC motor. The ESC has limited functionality and can power motor only in one direction. If I switch manually two of the ESC to Motor phase connections, than the motor direction will change. Now, I want to do the same i.e. switching phase to phase connections with 4 power mosfets.

As in scheme, the blue ESC phase will be connected to Mosfet source and the drain will be connected to Motors yellow phase. The next mosfet will connect to ESC yellow at source and motor blue at drain.  Two other mosfets will connect blue to blue and yellow to yellow.

I won't  do the switching while motor is on so I assume it should be safe.

How can I connect MOSFET's gate to Arduino ?
I need no pwm just ON/OFF.

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

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

title: Using N mosfet to switch ESC to BLDC phases

Answers: 1

body:
This is covered fairly well in an [EDN.com “MOSFET pair makes simple SPDT switch”](http://www.edn.com/design/analog/4360638/MOSFET-pair-makes-simple-SPDT-switch) article.  You would use two of the SPDT circuits to make a DPDT.  Attach switch commons to yellow and blue, and attach the “switch points” of one circuit to motor yellow and blue, and those of the other vice versa.  Attach both control pins to one Arduino IO pin.  The picture below comes from the referenced article, which shows the circuit in use for a primary-power vs secondary-power application.   See the article for details.

[![details and overview of circuit][1]][1]

  [1]: https://i.stack.imgur.com/YSaGC.gif


body:
I am trying to make an Arduino heart beat counter . I looked for some code online and found this code on arduino.cc forum but I couldn't understand working of the given code .. specifically these few lines of code:
The full code is given below:

    int sensorValue = 0;
    int sensorValue = 0;  // variable to store the value coming from the sensor
    int count = 0;
    unsigned long time1 = 0;  // store the initial time
    unsigned long time2;    // store the current time
    void setup() {
     // declare the ledPin as an OUTPUT:
     pinMode(sensorPin, INPUT);
     Serial.begin(9600);
    }

    void loop() {
     // read the value from the sensor:
     if (count == 0)
     {
      time1 = millis();
     }
     time2 = millis();
     sensorValue = analogRead(sensorPin);
     if (sensorValue > 156)
     {
      increment();
     }
     if (time2 >= time1 + 10000)
     {
      counter();
     }

    }

    void increment()
    {
     count++;
     while (sensorValue > 156)
     {
      Serial.print("Sensor value is greater than .75V\n");
     }
    }
    void counter()
    {
     count = count * 6;
     Serial.print("Heart beat is ");
     Serial.print(count);
     Serial.print(" per min\n");
     time1 = 0;
     time2 = 0;
     count = 0;
    }

Lines of code I'm not able to understand :

    if (count == 0)
    {
     time1 = millis();
    }
    time2 = millis();
    sensorValue = analogRead(sensorPin);
    if (sensorValue > 156)
    {
     increment();
    }
    if (time2 >= time1 + 10000)
    {
     counter();
    }

PS: the given code is in void loop(). in the beginning of the loop.

if u are not able to understand the code i'm leaving a link to the page:[this is the link][1]

i would be highly obliged if anyone could really help me soon. Thank u in advance :-)

  [1]: http://forum.arduino.cc/index.php?topic=155997.0

title: Trying to make arduino heart beat counter but couldn't understand code

Answers: 1

body:
I've reformatted you code to make it easier to read.

Looking just at the lines you don't understand.

  Line 1 stores the start time of this loop in the variable `time1` and stores the current time in the variable `time2`  these are going to be almost identical until the first heart beat is seen (which will increment count).

  Line 6 `sensorValue = analogRead(sensorPin);` reads the value from the sensor, it the reading is greater than some predetermined threshold (156) then it `increment()` the counter and waits until the value goes below 156.

  Line 11 checks to see if 10 seconds (10,000 mS) have elapsed since the loop started.  If they have then you get your reading via the function `counter()`

Does that make sense?

It would be a lot easier to understand if the original author had put comments in, but most people writing examples assume there code is so easy to understand they don't need to, don't fall into that trap when you become a great programmer! :)


body:
As the title alludes to, I'm in the process of converting an Arduino sketch to a Processing sketch. So far, mostly pretty straightforward.

I'm running into an issue with creating an array of ints for the channels for two [muxers][1]. Below is the code that I currently have working for the Arduino sketch:

    int writeMux(int channel){
      int controlPin[] = {s0, s1, s2, s3, s4, s5, s6, s7};

      int muxChannel[20][8]={
        //Mux 1
        {0,0,0,0,0,0,0,0}, //channel 0
        {1,0,0,0,0,0,0,0}, //channel 1
        {0,1,0,0,0,0,0,0}, //channel 2
        {1,1,0,0,0,0,0,0}, //channel 3
        {0,0,1,0,0,0,0,0}, //channel 4
        {1,0,1,0,0,0,0,0}, //channel 5
        {0,1,1,0,0,0,0,0}, //channel 6
        {1,1,1,0,0,0,0,0}, //channel 7
        {0,0,0,1,0,0,0,0}, //channel 8
        {1,0,0,1,0,0,0,0}, //channel 9

        //Max 2
        {1,1,1,1,0,0,0,0}, //channel 0
        {1,1,1,1,1,0,0,0}, //channel 1
        {1,1,1,1,0,1,0,0}, //channel 2
        {1,1,1,1,1,1,0,0}, //channel 3
        {1,1,1,1,0,0,1,0}, //channel 4
        {1,1,1,1,1,0,1,0}, //channel 5
        {1,1,1,1,0,1,1,0}, //channel 6
        {1,1,1,1,1,1,1,0}, //channel 7
        {1,1,1,1,0,0,0,1}, //channel 8
        {1,1,1,1,1,0,0,1}, //channel 9
      };

      //loop through the 4 sig
      for(int i = 0; i < 8; i ++){
        digitalWrite(controlPin[i], muxChannel[channel][i]);
      }

      //write the value at the SIG pin
      analogWrite(SIG_pin, testValue);

      //return the value
      return 0;
    }

Below is the slightly varied version that I'm using for my Processing-equivelent sketch.

    int readMux(int channel){
      int controlPin[] = {s0, s1, s2, s3};

      int muxChannel[20][8]={
        //Mux 1
        {0,0,0,0,0,0,0,0}, //channel 0
        {1,0,0,0,0,0,0,0}, //channel 1
        {0,1,0,0,0,0,0,0}, //channel 2
        {1,1,0,0,0,0,0,0}, //channel 3
        {0,0,1,0,0,0,0,0}, //channel 4
        {1,0,1,0,0,0,0,0}, //channel 5
        {0,1,1,0,0,0,0,0}, //channel 6
        {1,1,1,0,0,0,0,0}, //channel 7
        {0,0,0,1,0,0,0,0}, //channel 8
        {1,0,0,1,0,0,0,0}, //channel 9

        //Max 2
        {1,1,1,1,0,0,0,0}, //channel 0
        {1,1,1,1,1,0,0,0}, //channel 1
        {1,1,1,1,0,1,0,0}, //channel 2
        {1,1,1,1,1,1,0,0}, //channel 3
        {1,1,1,1,0,0,1,0}, //channel 4
        {1,1,1,1,1,0,1,0}, //channel 5
        {1,1,1,1,0,1,1,0}, //channel 6
        {1,1,1,1,1,1,1,0}, //channel 7
        {1,1,1,1,0,0,0,1}, //channel 8
        {1,1,1,1,1,0,0,1}, //channel 9
      };

      //loop through the 4 sig
      for(int i = 0; i < 4; i ++){
        digitalWrite(controlPin[i], muxChannel[channel][i]);
      }

      //write the value at the SIG pin
      arduino.analogWrite(SIG_pin, testValue);

      int val = 0;
      return val;
    }

I'm currently getting an error of `unexpected token: int` error at the following line:

      int muxChannel[20][8]={

And, an error of `The type of expression must be an array type but it resolved to int` at this line:

    digitalWrite(controlPin[i], muxChannel[channel][i]);

Thank you!

  [1]: http://bildr.org/2011/02/cd74hc4067-arduino/

title: Arduino -> Processing conversion: creating mux channels

Answers: 0


body:
I'm developing a project and I need to connect to my Arduino Mini with a SD card breakout board. The problem is that I can't plug it directly to the Arduino since it is already powering some sensors and a BITalino, and I was told that it would, for some reason, be better to connect an external battery to the SD board.

My question is if i can supply this  [MICROSD CARD BREAKOUT BOARD+](https://www.adafruit.com/product/254) with a 3.7V battery, instead of a 5V.

Thank you!

Description:

* Onboard 5V->3V regulator provides 150mA for power-hungry cards
* 3V level shifting means you can use this with ease on either 3V or 5V systems

title: Power suply for MicroSD card breakout board

Answers: 4

body:
Yes you can give power supply to MICROSD CARD BREAKOUT BOARD from a 3.7V battery It has Onboard LP98x Voltage regulator winch provide 3.3V regulated power supply.

Take reference from here [Schematic of MICROSD CARD BREAKOUT BOARD][1]

  [1]: https://learn.adafruit.com/adafruit-micro-sd-breakout-board-card-tutorial/download

body:
> My question is if i can suply this MICROSD CARD BREAKOUT BOARD+ with a
> 3.7V battery, instead of a 5V.

Yes you can supply MICRO SD Card Breakout with 3.7 volt battery as it has onboard voltage regulator which will provide required voltage to the board.

> I was told that it would, for some reason, be better to connect an
> external battery to the SD board.

Because every sensor will take 3V - 5V as per its requirement. So some time Arduino can not be able to provide 3.3 - 3.5 volt to SD Card board and there could be no data logging or some wrong data logging to SD card. Thus it is advised to do such.

body:
You just need to bypass the Pro Mini regulator in order to avoid loading it too much, because the uSD Card board already has one.

Instead of connecting the uSD Card breakout board to the VCC pin, connect it to the RAW pin. Provided that your power source (3.7V battery? wall adapter?) can source enough current for the Pro Mini plus the uSD card board (something that's very likely), everything will be fine. No need to add any extra power source.

The regulators in those boards have very similar dropout characteristics (300-400mV).

body:
The "some reason [it would] be better to connect an external battery to the SD board" is that you need to make sure that the controller chip and SD card are getting enough power that it can write reliably.

To figure out whether and what kind of external power you need you start with the specifications. The first clue is in the [general product description](https://www.adafruit.com/product/254) to which you linked; it says that it has an "Onboard 5v->3v regulator" that "provides 150mA for power-hungry cards." This is a good start, but you'll see below that we'll need further information from a link on the [tutorial page](https://learn.adafruit.com/adafruit-micro-sd-breakout-board-card-tutorial/download).

Linear power regulators give a fixed voltage output (in this case, 3 V) from a higher voltage input. To work properly they need an input voltage a bit higher than their output voltage; the minimum difference between the two is called the dropout voltage. From the [schematic](https://learn.adafruit.com/assets/35635) we can see that the board is using an LP298x regulator. A [datasheet](https://www.ti.com/lit/ds/symlink/lp2985-n.pdf) for a (hopefully typical) part from that series indicates that dropout voltage is 300 mV or 0.3 V. 3.7 V is considerably higher than 3 V + 0.3 V, so you're very likely to be ok in that respect with your external battery. (We also note here that the input voltage can range up to 16 V; we'll use this information later.)

The other thing you need to look at is whether you can supply enough current to the board and card that, under all reasonable circumstances, they can function properly. From the original description you know the board uses a 150 mA regulator which means that the designers expect that you'd never need more than that. (And if you do, the card isn't going to get it anyway.)

For simplicity it's easiest just go go with being able to provide 150 mA or more on the regulator's input, regardless of voltage. (In theory you can supply less power on input if you're giving it a higher voltage, because P = EI, but it's not generally worth the time and effort to go there for a hobbyist project.)

Batteries have a discharge rates known as [C rates](https://en.wikipedia.org/wiki/Battery_(electricity)#C_rate), and unless you know what you're doing (I don't :-)) your best bet is to stay well within the standard discharge rate as specified by the manufacturer. Adafruit sells a typical [3.7v 1200mAh Lithium Ion Polymer Battery](https://www.adafruit.com/products/258); looking at its [datasheet](https://cdn-shop.adafruit.com/datasheets/503562+1200mah.pdf) we see that the standard discharge current is 0.5 C5 A, which is 0.5 * 1200 mAh / 1 h = 600 mA, plenty more than you need. So if you're using that battery you'd be safe. (I started out by looking at the [500 mAh battery](https://www.adafruit.com/products/1578) which has a  0.2 C5 A = 100 mA standard discharge rate; my guess is that that's fine because the maximum discharge rate is 1 C5 A, but this has implications on battery capacity and the like so I'd ask someone first.)

But it would be nice to use your existing power supply for the card rather than use a separate battery, I'm sure. Your best bet for that is the [suggestion from  Enric Blanco](https://arduino.stackexchange.com/a/36581/31794): use an external power supply that can deliver enough current to both the Arduino Pro regulator and the SD Card breakout board regulator that they'll both be happy.

Sadly, Adafruit's [Ardiuno Mini product page](https://www.arduino.cc/en/Main/ArduinoBoardMini) gives no indication of current requirements. However, a quick look at the [v5 schematic](https://www.arduino.cc/en/Main/ArduinoBoardMini) we can see that it's using an LP2985AIM5-5.0 regulator and a web search turns up a [product page](https://www.digikey.com/product-detail/en/texas-instruments/LP2985AIM5-5.0/LP2985AIM5-5.0CT-ND/3701530) for this that says it's rated at 150 mA.

Add the 150 mA for the Arduino Mini to the 150 mA for the SD card board and you can figure that any external power supply that is giving more than 300 mA at the minimum 7 V input voltage specified for the Arduino Mini should be just fine. The 7 V should also be ok for the SD card board regulator since, even if it's a slightly different model from our spec. sheet, it's unlikely to have a maximum voltage hugely below the 16 V for that part. But you could check the exact part your board is using if you're worried.


body:
I am designing a hard real-time data logger. The Uno is a bit marginal in processing speed.

a) Would it be **faster** if I changed to an ATmega2560?

b) On the datasheet, ATMEGA2560 has 135 instructions; it is **4 instructions more** than the ATmega328p.

What are the extra 4 instructions for?

Are they involved in floating point maths?

c) How to select compiler option for **fastest code** at the expense of bigger code size, longer compilation time, etc.?

The system is:

1. Receive data from wireless transceiver chip via hardware SPI port.

2. A good portion of the time is spent on data calculation using floating point maths.

3. Output processed data on serial port (then to PC via the Arduino board USB to Serial chip).

4. Code and RAM size is not an issue, Uno has plenty space left.

title: Will an ATmega2560 board be faster than a Uno for hard real-time data logging?

Answers: 4

body:
No, it will not be any faster. The extra instructions are to access the extra flash memory of the 2560. Instructions like `EIJMP` - *Extended* indirect jump, `EICALL` - *Extended* indirect call, etc.

The compiler option `-O3` optimises the most, but there are other options you can enable, such as `-funroll-loops` which will cause major code bloat but speed things up.  Read the GCC manual pages to boggle at all the millions of optimisation options.

Or... use a faster chip, like an ARM or PIC32.

body:
Use the newest Arduino IDE, because some time ago the 'lto' option was added which is a major optimization for both speed and size.
It is possible to test a few compiler options with the #pragma. Try for example these at the top of the sketch:

    #pragma GCC optimize("-O3")
    #pragma GCC optimize("-ffast-math")

The 'fast-math' is dangerous, be careful with it.

The Arduino Zero and Arduino Due are faster but not a lot faster, because they are not fast with analogRead() and with floating point calculations.

A common mistake is that someone asks for a faster Arduino board, but uses a sketch and libraries with a lot of delay() in it. That won't be any faster with an other Arduino board. Have a good look at your code and at the source code of the used libraries.

Have you tried increasing the baudrate for outgoing data ? If that baudrate is slow, the whole sketch is slowed down because the Serial functions will wait until they can write the data into the Serial buffer. The fastest "baudrate" can be achieved with the Leonardo, Micro and Pro Micro boards. They transmit the data directly onto the USB bus without using the baudrate.

body: In the `platform.txt` file found in `~/Arduino15/packages/arduino/hardware/avr/1.6.17` or similar, you can change the three instances of `-Os` with `-Ofast`. The size of the code can increase dramatically though.

body:
They have very nearly the same instruction set and the same execution speed, so there will be no increase there. If your project spends a significant amount of time in floating-point arithmetic, replacing it with fixed point arithmetic will give you a noticeable speed up. If a few calculations are executed repeatedly (which is typical), you can get most of the advantage by rewriting only that part.

In a nutshell, fixed point arithmetic is what the computer does already, but with an assumed binary point (just like a decimal point) always to the right of the least significant bit. Fixed point arithmetic uses the built-in arithmetic, but you assume the binary point to be wherever you need it, keep track of it during multiplies and divides, and make sure you keep the intermediate results from overflowing.

Search for Fixed Point Arithmetic and you'll find out a whole lot more.


body:
I've found a Z80 processor and a TC5564APL-15 8K static ram chips, and I want to test the RAM chip, because it's really old and I'm not sure that it's not damaged. I do not have any experience with Z80's and RAM chip's, I'm not even sure that I didn't damage it while desoldering. I found [THIS][1] forum link, where a guy wanted to use a different RAM chip, but the code looked OK and I've took it. I did some modifications:

 - I only own one 74HC595, so I used that, I've connected the remaining address lines to 5V via 200Ohm resistors
 - I did not use any capacitors.
 - I've changed some connections.

Here's the modified code:
https://pastebin.com/9nfTQY8X
(Sorry for PB)

So it SHOULD print "0 0 0 8 / 0 0 0 8" to the serial, but it prints "0 0 0 8 / 8 8 8 8". The reason is unknown. Every other number works, I only found that specific bit not working correctly.
I'm not sure. Can my RAM chip be broken, or the circuit causes the problems?

  [1]: https://forum.arduino.cc/index.php?topic=66630.15

title: Interfacing with TC5564APL-15 paralell static ram

Answers: 0


body: I want to find all the Bluetooth addresses of connected devices using  an HC-05/HC-06 Bluetooth module and an Arduino. I can't find any code related to this. Basically I need the addresses to put in an array. Is it possible to do this with an HC-05 or 06?

title: Getting Bluetooth addresses of connected devices via Arduino Uno?

Answers: 2

body:
The HC-05 has an AT command, `AT+BIND?`, that will tell you which slave device it is connected with currently. Since you can connect to one device only at the same time, your array is going to be a very short one.

`AT+INQ` will provide you with a list of nearby devices, to which it ***can*** connect.

body:
You just have to send the above Bluetooth command via serial port to your Bluetooth module using print command.

For example `yourserial.print("AT+BIND?");` OR `yourserial.print("AT+INQ");` if you are using SoftwareSerial. Otherwise just use `Serial.print("AT+BIND?");` OR `Serial.print("AT+INQ");` when using Rx/Tx pins. That will do the job.


body:
I added the ArduinoMenu library https://github.com/neu-rah/ArduinoMenu and when I try to compile one of the examples, I get following error.

> Using library LiquidCrystal at version 1.0.5 in folder: C:\Program Files (x86)\Arduino\libraries\LiquidCrystal exit status 1 Error compiling for board Arduino/Genuino Mega or Mega 2560.

How can I fix this?

title: Error trying to compile an example from newly added Arduino menu library

Answers: 2

body:
I think you have to add your library in the library folder. Below is the path of that folder. It will help you.

`C:\Program Files (x86)\Arduino\libraries`

body:
Can you compile the LCD example for that board?
just to make sure you have LiquidCrystal library ok.

Then tell us what was the example? There are hardware specific examples.

Also try to compile the serial menu example, just to make sure that ArduinoMenu library is ok for your board.


body:
So, trying to configure this code so that when I push the button, the person counter will go to zero and just as it goes, the counter will increase when the LDR will get tripped and again when the button is pressed, the counter will go to 0.

    #include <LiquidCrystal.h>

    int laser=8;
    int pushbutton=12;
    int flag=0;
    int myCounter = 0;
    LiquidCrystal lcd(7,6,5,4,3);

    void setup()
    {
        pinMode(laser,OUTPUT); pinMode(pushbutton,INPUT);
        lcd.begin(16, 2);
        lcd.print("Person Counter:"); lcd.setCursor(0,1);
        lcd.print(0);
    }

    void loop()
    {
        lcd.setCursor(0, 1);
        digitalWrite(laser,HIGH);

        if(analogRead(A0) < 600) //A0= LDR
        {
            flag = 1;
        }

        if(analogRead(A0) > 600 && flag == 1)
        {
            myCounter++;
            delay(200);
            lcd.print(myCounter);
            delay(20);
            flag=0;
        }
    }

title: How to restart a counter in a program using a push button in a LDR Tripwire setup

Answers: 1

body:
Try out this code. I made some modification and also comment out that things.

    #include <LiquidCrystal.h>

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

    int laser = 8;
    int pushbutton = 12;
    int flag = 0;
    int myCounter = 0;

    void setup()
    {
      pinMode(laser,OUTPUT);
      pinMode(pushbutton,INPUT_PULLUP); // Provide pull-up

      lcd.begin(16, 2);
      lcd.print("Person Counter:");
      lcd.setCursor(0,1);
      lcd.print(0);
    }

    void loop()
    {
      lcd.setCursor(0, 1);
      digitalWrite(laser,HIGH);

      if(analogRead(A0) < 600) //A0= LDR
      {
        flag = 1;
      }

      if(analogRead(A0) > 600 && flag == 1)
      {
        myCounter++;
        delay(200);
        lcd.print(myCounter);
        delay(20);
        flag = 0;
      }

      if(digitalRead(pushbutton) == LOW) // When button pressed
      {
        myCounter = 0; // Set counter to 0
      }
    }


body:
Right now I am onto a new project where I am building an obstacle avoiding landrobot.

I use an arduino pro mini as my board and I have a few hc-sr04 sensors here at home. The problem I have right now is that many pins is occupied with other modules, motors and bluetooth.

So right now on my Pro Mini the VCC is occupied by my BLE device and I was wondering if there is a possibility to solder a few wires together so that my BLE device share the same VCC with 4 other hc-sr04 modules? I do this regularly with the GND where I solder multiple wires together and share the GND across different modules which works fine.

I have soldered a wire looking like this:
[![enter image description here][1]][1]

The idea is to power the arduino itself through the "RAW" pin. I have a power distribution board that connects to my battery/motor and the VIN pin of the PDB goes to the "RAW".

I try to avoid a breadboard to decrease the size as much as possible so if it were to be possible then that would be the optimal solution for this project.

Something I am also wondering is if it is possible to use these hc-sr04 on both the analog pins and also the digital pins. I do not have enough space to fit all the sensor cables on the digital pins but if I use the analog pins also then they all would fit. Is this possible? Each HC-sr04 has two cables that needs to be inserted (Trig and echo) and right now I have 3, 4 free and all the analog pins 0, 1, 2, 3, 4, 5 which is enough to fit them all.

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

  [1]: https://i.stack.imgur.com/8fDtH.jpg
  [2]: https://i.stack.imgur.com/QgCHn.jpg

title: Can I share the VCC (5V) on my Arduino Pro mini with multiple modules?

Answers: 2

body:
To be frank you can use even your analog pins as digital pins as the analog pins are also digital pins but they are more enhanced

If you use a common Vcc you may not have enough power left for your board and when you share your ground it doesn't matter a lot as it is the -ve lead of your power  source and you may use an external power source

body:
Yes, you can do that as long as the total current draw of the modules you attach to VCC doesn't exceed the on-board regulator maximum current output.

The Arduino Pro Mini has a MIC5205 regulator capable of [delivering up to 150 mA][1], which is quite low if you plan to attach many modules to its output. So you should look through your modules datasheets and find out the total current draw, including the Pro Mini board itself, and check that against the 150 mA limit.

According to the [HC-SR04 datasheet][2], each module draws 15 mA. The Arduino Pro Mini itself draws about [about 20 mA][3]. The [BLE module peak current consumption][4] is 12.5 mA at active RX and 11 mA at active TX, so lets say 25 mA peak current draw for the BLE module.

Everything adds up to a worst case 105 mA peak current draw, within the maximum 150 mA limit. So **it should be fine**, but I would avoid connecting much more modules to that VCC rail.

[![MIC5205 on board the Arduino Pro Mini][5]][5]

**ADDED according to your additional question:**

If you run out of digital I/O pins, you can use the analog pins as digital pins if needed.

Additional note (thanks go to @jwpat7 for pointing this out in the comments):

However, this is true only of A0–A5 on most Uno and Nano Micro Arduinos, and not true of A6, A7 (except on -PB MCU models like ATmega168PB and ATmega328PB, where A6, A7 can be used as digital pins).

  [1]: https://www.arduino.cc/en/uploads/Main/Arduino-Pro-Mini-schematic.pdf
  [2]: https://cdn.sparkfun.com/datasheets/Sensors/Proximity/HCSR04.pdf
  [3]: http://www.home-automation-community.com/arduino-low-power-how-to-run-atmega328p-for-a-year-on-coin-cell-battery/
  [4]: http://www.nordicsemi.com/eng/Products/Bluetooth-low-energy/nRF8001
  [5]: https://i.stack.imgur.com/y6dK9.jpg


body:
I recently purchased an Arduino UNO along with some other hardware. At the time of purchase, I didn't know about Arduino's motor shield and so I purchased a two channel stepper motor driver (2A per channel) that was said to be "Shield Compatible". I recently received my hardware and have been following the introductory tutorials since I'm completely new to the Arduino platform. Things are going well but I didn't receive any documentation with the motor driver. There is a datasheet provided on the vendor's website but it is beyond my current level of competency.

My question: since the driver is said to be "Shield Compatible", does this mean that I can assume that I can interface with it the same way as an authentic Arduino shield. In other words, can I follow the motor shield tutorial on Arduino's website without any risk of damaging hardware and expect the driver I purchased to function properly.

The product that I purchased can be seen here: http://www.robotshop.com/ca/en/dual-bipolar-stepper-motor-controller-arduino.html

title: Shield Compatible third party motor driver

Answers: 1

body:
You should do you own research as the path followed here did not result in the identically pictured nor identically model numbered item.

You indicated you are using a certain Arduino motor driver board.  On that page there is an "made by" or "by" reference to an OEM.  On the OEM's web page there is a "Dual Bipolar Stepper Motor Shield for Arduino" but the part number and the picture do not (exactly) match your original link.  Regardless, there is what they are calling a "[WIKI page][1]" for this (slightly) different motor shield.  I scanned this page and the example code.  I don't see where any device driver is mentioned.  And I don't think the code will compile by its self.

In general, I suggest people who are starting out with Arduino's to stick with well known hardware and software.  Even then I have had problems with newly released hardware.  Also check if drivers and SDKs have been updated each time you start a project.

Another approach you might entertain is to follow a path starting with the chip used on your shield.  It appears to use two DRV8825.  (But I cannot be sure as pictures and model numbers do not (exactly) match.) [Here is a discussion][2] on the a well known Arduino web site where people are talking about boards with this chip on it.

  [1]: https://www.dfrobot.com/wiki/index.php/Stepper_Motor_Shield_For_Arduino(DRV8825)_SKU:DRI0023
  [2]: https://forum.arduino.cc/index.php?topic=327696.0


body:
I have a device that takes commands in the form of RS232 communication. I've connected the Arduino's USB port, through an adapter, to the device's 9-pin serial port, but no communication has happened.

The full chain of adapters is a printer cable (which would connect the Arduino to a computer), a female-to-female usb adapter, and a Sabrent USB to serial adapter.

I made sure the communication wasn't happening using the code `while (!Serial)` and blinked an LED in a certain pattern.

Is there something I'm missing? How do you get the devices to communicate?

title: How do I connect Arduino to RS232 via USB?

Answers: 2

body:
This is effectively not workable.  USB is not a peer-to-peer standard, but a host/device one.  Both your Arduino and the USB-serial converter are intended to be devices, so they cannot communicate.  While it would be *possible* to use another microcontroller acting as a host to bridge to serial that would be pointless, as the actually central problem of RS232 vs. logic level serial would still need to be solved.

Instead, what you want is an inverting serial level shifter - essentially a board with an IC like a MAX232 or one its many successors.  You would either connect this to arbitrary digital pins of the Arduino and use a Software Serial instance, or decide that it is okay to block usage of the USB port by a computer while this is being operated, in which case you could connect it to the D0 & D1 pins used by the on-board USB interface (there are typically resistors in between the chips on the board to support this overriding).

Ironically, in a way what you want is one of the *original* Arduino boards that had a serial level shifter and 9-pin connector in place of the USB chip and USB connector of modern boards.  But then, you probably want something with an ATMega328p rather than the earlier, more primitive ATmega chips used on the original boards.  If you can still find a board of the original design, upgrading the chip may be an option, or it may be that your task is simple enough not to require it.

There have been many other non-Arduino embedded controller boards released with native RS232 ports as well, especially those dating from around a decade ago might give a good combination of fairly modern capability with not yet having abandoned RS232 in favor of USB.

body:
Any network of USB devices involves [a single **host** talking to many slave **devices**](https://en.wikipedia.org/wiki/USB#System_design). The typical connection to program an Arduino board is, on the USB side:

    PC (USB Host) <-> USB Cable <-> Arduino (USB Device)

On the Arduino board you have the serial side of this communication:

    USB Serial Adapter <-> TTL serial lines <-> Microcontroller (RX/TX on D0/D1 pins)

The microcontroller itself has no idea that any USB communication is involved. The USB serial adapter functions as a device only, not a host, so plugging it into another USB device (though a cable with device connectors on both ends, rather than the usual host connector on one end) will not do anything.

(There are some Arduino boards, such as the [Leonardo](https://www.arduino.cc/en/main/arduinoBoardLeonardo) and the [Micro](https://www.arduino.cc/en/Main/ArduinoBoardMicro), that use an [ATmega32U4](http://ww1.microchip.com/downloads/en/DeviceDoc/Atmel-7766-8-bit-AVR-ATmega16U4-32U4_Datasheet.pdf) microcontroller with a USB device interface built in. These work in substantially the same way as above except with the without the serial adapter and TTL serial link. The built-in USB interface also cannot be used as a USB host.)

### Arduino USB Host Shield

If you really want to use USB communication, SparkFun sells as [USB Host Shield](https://www.sparkfun.com/products/9947) that you can add to a standard Arduino Uno or similar device. The [library](https://www.circuitsathome.com/arduino_usb_host_shield_projects/) for it apparently supports USB serial, though you'd want to confirm that before buying the shield. This would leave the Arduino's USB/Serial interface used for programming free to remain hooked up when using the USB host shield, making development easier.

### Direct Serial Connection

A better method (IMHO) is to drop the USB stuff altogether and, as [Chris Stratton describes in his answer](https://arduino.stackexchange.com/a/36588/31794), have the Arduino talk TTL serial directly to a level shifter (e.g., this [breakout board](https://www.sparkfun.com/products/449) or [this shield](https://www.sparkfun.com/products/13029)) that is connected to your RS-232 device. I would go with communications on non-programming pins (i.e., not digital pins 0 or 1) using the [SoftwareSerial](https://www.arduino.cc/en/Reference/SoftwareSerial) library or the [AltSoftSerial](http://www.pjrc.com/teensy/td_libs_AltSoftSerial.html) library. (You don't mention the speed of the link, but software serial is generally ok up to 57,600 bps and, depending on the device and what else you're doing, even 115,2000 bps.) This will let you use the serial link to the computer for debugging while running your application.

If you need to work at higher speeds or you just prefer to use a [UART](https://en.wikipedia.org/w/index.php?title=UART) (hardware serial), you have two options:

1. Use the [USART](https://en.wikipedia.org/w/index.php?title=USART) on digital pins 0 and 1, and be unable to talk to the computer while you're using it to communicate with your RS-232 device.

2. Use an Arduino board with more UARTs or USARTs on it, such as the [Mega](https://www.arduino.cc/en/Tutorial/MultiSerialMega).


body:
i am trying to use a ESP8266 module to send temperature data using twilio and send it to my phone via text message. However it does not send the sensor data but the text i placed. Is it possible if i can get it to send sensor data instead? If so how can i do this?

    strcat(data,"From=");
        strcat(data,PHONE_FROM);
        strcat(data,"&");

        strcat(data,"To=");
        strcat(data,PHONE_TO);
        strcat(data,"&");

        strcat(data,"sid=");
        strcat(data,TWILIO_ACCOUNT_SID);
        strcat(data,"&");

        strcat(data,"token=");
        strcat(data,TWILIO_TOKEN);
        strcat(data,"&");

        strcat(data,"Body=");
        const char TEXT_MESSAGE_BODY []  = "temperature", temperature;
        strcat(data,TEXT_MESSAGE_BODY);

        wifi.httpPost("iot-https-relay.appspot.com","/twilio/Messages.json",data);

temperature should be getting sensor raw data and paste it after the "temperature" but it is not working.

title: ESP8266 not sending temperature data to text message

Answers: 1

body:
Not 100% sure what you are trying to do with the line:

    const char TEXT_MESSAGE_BODY []  = "temperature", temperature;

This will not assign the value in temperature to TEXT_MESSAGE_BODY, it will create a variable of type char called temperature.

You will need to get your temperature value into a string (array of char) using sprintf() or similar to convert from the base type (float, double?).

Replace const TEXT_MESSAGE_BODY [] ... etc with :

    strcat(data,"temperature");

    char temperature_s[20];
    sprintf(temperature_s, "%f", rawTemperature);
    strcat(data,temperature_s);

Above assumes rawTemperature is a float holding the value read from the sensor, but the same idea applies for other data types..  There is no checking for buffer overflow etc, but you get the idea.


body:
I've use the following circuit to be able to shutting the my Arduino down after some time of it not being used:

<img src="https://dl.dropboxusercontent.com/u/5426092/AutoPower Off.png">

I'm now concerned that while you press the button to turn on the Arduino, the 9V from the battery can flow directly to the PIN X (one of the digital pins of the Arduino configured as output). After the Arduino is started the PIN X will be set to high, to keep the Arduino running when the button is released.

Is this a problem which I need to solve? And if yes how. The finished project is intended for a child, so I assume that the on button can be hold for a long time just as it is funny to press on the button. The circuit itself is running fine.

As a possible solution I thought to add a diode between the junction after the R1 and the PIN X. Would this be an ok solution?

The circuit is not my own invention I've found it here: http://educ8s.tv/auto-power-off-arduino-simple-circuit/

title: Arduino auto power of circuit possible issue with higher voltage agains output pin?

Answers: 2

body:
No.  It is not possible for a modern IC such as an MCU having I/O protection diodes to enable/disable its own power using a *single* external N-Channel or P-Channel device.  The reason is that the path broken by the single switch ends up being partially completed through I/O pin's internal protection diode and your pulldown resistor, and depending on the voltage drop that results across that, partial turn on the FET itself.  This is enough to have the processor at least partially on - perhaps not enough to *operate*, but enough to keep consuming battery, and in some cases also enough to make clean startup on manual operation of the power switch unworkable.

To make this work, you need two stages of switching - two fets are a possibility.

However another easy one is to use one of the USB power switches chips intended to be included in the rarely seen "full" USB hubs that have software control of the downstream ports' power.  These are hardly ever fitted in the hubs sold, but they exist as a part, are easy to apply, typically have low leakage, and are often specified to operate correctly both substantially below and somewhat above the 5v they would see in a USB application.  Most importantly, they are multi-stage solutions in a single package - typically they function as high side switches, but they are enabled by an input going high, and as result, they do not suffer the parasitic partial turn on issue via the MCU's protection diodes in the way that a high side switch enabled by an input going low would.  I believe the RT9701 that I used in the past to do this with an ESP8266 is officially discontinued, but still available and likely replaced by newer similar parts.

Given your input voltage, another thing to consider would be using a regulator with an active-high enable input.  But realize that a *linear* regulator is an inherently wasteful device, and a lot of the compact switchers don't have very high input voltage allowance.

body:
Having 9 volts reaching pin X through R1 is indeed a problem, one that could destroy transistors in the pin's IO structure.  The problem is mentioned in some comments following the video, but no solution is mentioned there.  Presumably users of the circuit usually get away with ignoring the problem because it is one of short duration:  A few milliseconds after the MCU starts up, it sets pin X to +5 V, which then leads to 4 V at 40 μA being dropped harmlessly across R1.  (Note, R1 is 100KΩ rather than 100Ω, per video and its notes.)

One approach to guard against the problem is to place a 5.3–5.7 V zener diode from ground to pin X.

Another way is to use a better and more capable on-off circuit, a [Pololu Pushbutton Power Switch #2808](https://www.pololu.com/product/2808).  This costs about $4, and is rated for operation from 2.2 V to 20 V at up to 6 A.  The board is about 15x18 mm and has a small pushbutton on it, but you can parallel a momentary switch of your own if you like.  The pushbutton toggles power on or off.  The board also has control inputs called On, Off, and Ctrl, with the first two turning the board on or off.

A big advantage of the #2808 switch is its current draw is small (less than 0.1 μA) when switched off.  The circuit illustrated in the link has close to 0.5 mA draw when off, which is enough to run a battery down in a few weeks.


body:
I'm having some trouble wrapping my head around timers in Arduino. I've got a FSR Pressure Sensor and I want it to turn on my NeoPixel LED after pressing on it for 5 seconds. Any help is much appreciated!

My goal:
FSRReading > 1022 then wait 5 seconds, turn on NeoPixel
FSRReading < 1022, then reset timer, turn off NeoPixel

This is what I currently have for my code, I can detect and act on sensor readings, but no timer:

    #include <Adafruit_NeoPixel.h>
    #define PIN 6
    #define NUMPIXELS 16
    #include "Timer.h"

    Adafruit_NeoPixel pixels = Adafruit_NeoPixel(NUMPIXELS, PIN, NEO_GRB + NEO_KHZ800);

    int fsrPin = 9; // FSR is connected to analog 0
    int fsrReading; // the analog reading from the FSR resistor divider int LEDbrightness;
    int LEDbrightness;
    Timer t;

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

    void loop(void) {
    fsrReading = analogRead(fsrPin);
    Serial.println(fsrReading);
    Serial.print("Analog reading = ");

    // we'll need to change the range from the analog reading (0-1023) down to the range // used by analogWrite (0-255) with map!
    LEDbrightness = map(fsrReading, 0, 1023, 0, 255);

    if (fsrReading < 10) {
    Serial.println(" - No pressure"); } else if (fsrReading < 200) {
    Serial.println(" - Light touch"); } else if (fsrReading < 500) {
    Serial.println(" - Light squeeze"); } else if (fsrReading < 800) {
    Serial.println(" - Medium squeeze"); } else {
    Serial.println(" - Big squeeze"); }
    delay(50);

    for(int i=0;i<NUMPIXELS;i++){

      // pixels.Color takes RGB values, from 0,0,0 up to 255,255,255
      if (fsrReading>1022){
      pixels.setPixelColor(i, pixels.Color(0,255,0));
      } else if (fsrReading<1022) {
      pixels.setPixelColor(i, pixels.Color(0,0,0));
      }

      pixels.show(); // This sends the updated pixel color to the hardware.
     }
     }

title: Press on pressure sensor, then wait 5 seconds, turn on LED

Answers: 2

body:
The basic concept for tracking timing in the loop() is as follows:

1) when your event occurs, you store the current time in a variable:

    unsigned long lastReading = 0;
    uint8_t waiting = false;

    if ( !waiting && fsrReading > 1022 ) {
      lastReading = millis();
      waiting = true;
    }

2) you compare the lastReading variable against the current time and when enough time has passed, you can perform you timed action. ie:

    int timeToWait = 5000; // 5 seconds

    // are we waiting? and has enough time passed?
    if ( waiting && millis() - lastReading > timeToWait ) {
       waiting = false; // reset

       // Light up lights
       ...
    }

Note: this specific implementation only requires the sensor to rise above 1022 once, then wait 5 seconds before executing the timed action. If you want the sensor reading to be maintained above 1022 for the entire duration then you would add a check for a release with something like:

    if ( fsrReading < 1022 ) {
      waiting = false; // reset because reading fell below 1022
    }

body:
> My goal: FSRReading > 1022 then wait 5 seconds, turn on NeoPixel FSRReading < 1022, then reset timer, turn off NeoPixel

something like this will do.

      static uint32_t pressed_time; //last time the pressure sensor is pressed
      static uint8_t pressed_state=0; //the previous state. '1'->pressed, '0'->not pressed

      if (pressed()) {
        if (!pressed_state)) { //first time the pressure sensor is pressed
          pressed_state = 1;  //pressure sensor has been pressed
          pressed_time = millis(); //take time now
        }
      } else {                //no longer pressed
        pressed_state = 0;  //reset pressed state
        turnOffled();       //turn the led off
      }

      if ((millis() > pressed_time + LED_DLY) && pressed_state) turnOnled();

untested code, use at your own risk

edit:

the above code in action, with a minor modification to return the desired led state (active high):

       //turn on / off the led pins
      if (led_ctrl()) digitalWrite(LED_PIN, HIGH); //turn on the led, active high
       else digitalWrite(LED_PIN, LOW);  //turn off the led
    }

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

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

Note:
1. pressed() is active low;
2. the led is programmed to turn on 100ms after the button goes low.

hope it helps.


body:
I am not an expert yet, so please forgive any possibly wrong terminology that I may have used.

I am planning to place 6 light sensors in 1 meter (or maybe more) distance from one another, like this (sorry about the bad schematic, I am not an expert, but I hope it makes sense):

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

<!-- End schematic -->

I am going to place them in a relatively dark room. My goal is, when I am pointing a flash light towards them to be able to tell which sensor is measuring the highest values (where the light is coming from), and for how long (in milliseconds).

I know how to do the connections and measure values. My questions are two:

1. Which is the most efficient way to detect which of the 4 sensors is recording the higher values? I am assuming I have to compare the values that they are recording. However, I think that if in each loop I sort the captured values, the process might become heavy. I guess I could minimise the comparisons, since for example if LDR1's value is higher than LDR2 and LDR3, I can assume that the light source is cannot be pointing towards LDR6 for example. However, I am thinking that maybe there could be an even more efficient way to detect that (not necessarily in software).

2. Since the room will not be completely dark, the analog pins will record some values even when I am not pointing the flash light towards them. Is there a way to filter that out? I have come across calibration (https://www.arduino.cc/en/tutorial/calibration), but I am not sure whether this is the optimal solution. Please take into account that the light source might not be very strong (but its light will definitely be brighter than the room light).

title: Detecting the light source location using multiple photoresistors

Answers: 2

body:
There's only one ADC (analog to digital converter) on the ATmega328P; the analog input pins are multiplexed so that you choose which particular pin you want to sample. (See Section 28 of [the datasheet](http://www.atmel.com/Images/Atmel-42735-8-bit-AVR-Microcontroller-ATmega328-328P_Datasheet.pdf) for details.)

Taking a sample takes time; how long depends on how you do it. The [`analogRead()` function](https://www.arduino.cc/en/Reference/AnalogRead) is documented to take about 100 microseconds. Reading your six sensors is thus going to take at least 600 microseconds.

The sample returned is a 10-bit integer and so easily fits into two bytes, or even one byte if you drop the low two bits (which is reasonable for some applications, and probably yours, because they're likely to be more sample error than data anyway). Whether you do that or not, however, you're left with a very tiny amount of data to sort from one set of reads: just six values.

The Arduino runs the ATmega328P at 16 MHz, and most instructions run in single clock, giving you performance approaching 16 instructions per microsecond.

We could work out, based on the type of sort you use, the number of comparisons and swaps you're likely to make in the average and worst cases, but there's no point to that on such a tiny data set because the total time your routine takes is almost certainly going to be dominated by other overhead. So I'm just going to say that the sort will be something on the order of a hundred clock cycles.

That means your sort would add around 6 or 7 microseconds to your 600 microsecond total read time you've got so far, or 1%; you don't have to worry about it at all.

You'll actually spend a lot more time doing other sorts of processing. But it's a pretty fast CPU, as we've seen above, so there's a good chance if you're careful that your loop will still be dominated by the sampling time of the ADC for each of the sensors.

My suggestion is to go ahead and write the thing but record actual timings in your loop for the sampling and the processing. After you've played around with it for a bit you'll have a better idea of the particular costs for each for your particular application and then you can worry about whether or not you need optimization. I suspect you won't.

Regarding the "filtering," that's going to be an integral part of your processing algorithm because the "room light" values can be vastly different from time to time depending on the current lighting in the room. I don't think you want to "filter" anything out, but instead compare the values of all of the photoresistors; at a first guess, similar values from all of them would mean that there's no flashlight and some giving you significantly higher values would indicate that there is one. But my second guess is that a) you'll want your sensors a lot further apart than 1 meter (perhaps in the corners of the room) and b) it's not going to be so simple; you're likely to see fairly different values from the sensors even in a quiescent room. This is where you get to play and experiment to find out how this really works!

It also occurs to me that putting the photoresistors several meters away from the ADC is going to involve a lot of wire, which adds resistance, capacitance and noise, all of which are going to interfere with your measurements. There's not a lot you can do about this; you can play a bit with measuring known-value resistors at the ends of the wires to see how bad the problem is, but if it's terrible you'd probably need to use a separate Arduino for each sensor and have them communicating back to a central place for analysis.

body:
The answer from Curt Sampson provides several good design considerations, plus the quite-reasonable suggestion that you run some experiments to characterize your LDRs and their placements.

Note that if you want to know which sensor has the highest reading, a simple find-maximum-value loop will do that, without any sorting:

    int maxR = reading[1], maxS=1;
    for (byte i=2; i <= nSensors; ++i) {
      if (reading[i] > maxR) {
        maxR = reading[i];
        maxS = i;
      }
    }
    // Now we know sensor maxS has max reading, maxR

The code above follows the 1–6 numbering scheme given in the question, and assumes that `reading[i]` stands for the reading from sensor `i`.

Code below, however, numbers the sensors and their readings from 0 to 5 instead of from 1 to 6, to allow simpler conditions in `for` loops.  From a programming standpoint, it makes sense to call the first sensor 0 if its data is stored in cell 0.

---

**Finding x, y direction of the light**

Assumptions behind the following code are that higher readings indicate more light, and that if necessary some background-lighting calibration has been done, and that background lighting has already been subtracted from readings data.  We also assume that maximum readings are less than (2¹⁵)/N, where N is number of sensors.

The point of the following code is to set two variables, `x` and `y`, that represent the relative location of a light source.  For example, if `x` and `y` are both positive, the light is above and to the right of the top right LDR.  If  `x` is negative and  `y` is near zero, the light is to the left of the middle-left LDR.  If knowing the signs of `x` and `y` is adequate for your purpose, then there's no need to do more arithmetic than shown.  On the other hand, if you want to compute some sort of angle, you can use `atan2(y, x)` to compute the direction of the light, in radians.

    int reading[nSensors];
    const int xdir[] = { -1, 1, -1, 1, -1,  1}; // x-direction sensor weights
    const int ydir[] = {  1, 1,  0, 0, -1, -1}; // y-direction sensor weights
    int x=0, y=0;
    for (byte i=0; i < nSensors; ++i) {
      x += xdir[i] * reading[i];
      y += ydir[i] * reading[i];
    }

---

*Edit 1:* **Tracking the time a light is on**

Issues with light-timing include what levels to start or stop timing at; necessary resolution (milliseconds? minutes?); necessary range (eg, is what happened a minute ago relevant); and when to reset accumulated time data.  It may be simplest to track the on times of all the sensors at the same time, then select one of the times or combine some times.  Do you want the largest time, the newest time, the newest large time, or the time corresponding to the largest light?

For example, the code below tracks light levels that remain high long enough to register, in smoothed averages, as above some threshold.  At intervals, current indications are rotated into bit maps that track the last 16 on-off levels for each LDR, and counts of number-of-ons are updated too.

    // Initialization ...
    uint16_t expAvg[nSensors]={0};  // Exponential averages over time
    uint16_t bitMaps[nSensors]={0}; // Track each sensor's last 16 on-off levels
    byte onCounts[nSensors]={0};    // Number of recent times sensor avg > threshold
    unsigned long prevMilli=millis();
    const int markInterval=50;   // ms interval for recording light levels
    const int onThreshold=547*16; // Some light-is-on threshold

    // In each pass of loop() ...
    for (byte i=0; i < nSensors; ++i)
      expAvg[i] = reading[i] + 15*expAvg[i]; // exponential averaging with 1:16 weight

    // In loop(), at intervals ...
    if (millis()-prevMilli >=  markInterval) {
      prevMilli = millis();
      for (byte i=0; i < nSensors; ++i) {
        onCounts[i] += (expAvg[i] > onThreshold) - (!(bitMaps[i] & 0x8000));
        bitMaps[i] = (bitMaps[i]<<1) | (expAvg[i] > onThreshold);
      }
    }


body:
[first time usage]

I'm checking this config out with a simple sketch derived from one @ https://www.allaboutcircuits.com/projects/understanding-and-implementing-the-hc-12-wireless-transceiver-module/.

The sketch acknowledges a command from the Serial Monitor and responds accordingly along with an "OK".  I have used this sketch countless times before with numerous HC-12 and UNO, and this particular HC-12 functions properly when connected to such.

For the Pro Micro, the command is echoed back instead, which, in my experience, indicates that the HC-12 is not receiving/responding.

The Pro Micro test config is very basic: Pro Micro, HC-12, USB connection, 5 direct jumper connections for vcc, gnd, pins 4-6. Vcc output reads 4.2 volts.

I specify:

    const byte HC12RxdPin = 4; // "RXD" Pin on HC12
    const byte HC12TxdPin = 5; // "TXD" Pin on HC12
    const byte HC12SetPin = 6; // "SET" Pin on HC12

    SoftwareSerial HC12(HC12TxdPin, HC12RxdPin)

I have also tested with an IN4007 in the power connect for the HC-12, but results are the same.

I've swapped HC-12s, and checked out the requisite pins by using another sketch that toggles an led on each.
The Arduino IDE is 1.8.2, and I am specifying a Leonardo board.  This is the suggestion I found whilst researching.

I have seen a few projects using the HC-12 with the Pro Micro and other small boards, but noticed no special considerations for such.

Have you any suggestions or solutions [even better]?

title: Cannot get HC-12 to function with Arduino Pro Micro clone

Answers: 1

body:
Solution to problem is as follows:
 For the Arduino Pro Micro [as for the Leonardo], Serial1 must be used instead of a SoftwareSerial specification, e.g.,

    SoftwareSerial HC12(HC12TxdPin, HC12RxdPin).

Code is to be modified by changing HC12.available() to Serial1.available().  The same holds true for the reads and writes.
Pins are to be wired such that the HC-12 RXD pin connects to the Pro Micro TXD pin, and the HC-12 TXD pin connects to the Pro Micro RXD pin.
My thanks to @mico for providing the reference that explains it all.


body: I am thinking forward to buy a set of Arduino pro mini. I have a very low budget and I can't think of buying a FTDI board. Is there any substitute for the FTDI board that is compatible with these arduino pro mini.

title: Substitute for FTDI board?

Answers: 2

body:
All prices in USD w/ free shipping.

**FT232RL breakout board:**

- Aliexpress: $1.55
- eBay: $1.81

They are probably counterfeit. A Windows driver update (AKA "FTDIgate") at one point "bricked" them but I'm not sure that's an issue anymore. Even if it is it's Windows only and easy enough to work around. I've used these for years on Windows and they work fine for me.

If that's still beyond your budget there are a few other common options. I haven't used these breakout boards but I do have quite a few boards that use the CH340G and they work perfectly once you install the driver. There's a decent chance some of these will also be counterfeit. Some didn't break out the DTR/CTS pin for auto reset but if you're on such a low budget maybe it's worth it to you to press the reset button on every upload to save a few cents. They may not have the standard FTDI header pinout and if so would require you to use jumpers to connect them to the Pro Mini rather than plugging directly into the header.

**PL2303 breakout board:**

- Aliexpress: $0.50
- eBay: $0.74

These don't appear to break out the DTR or CTS pins so they won't do auto-reset.

**CH340G breakout board:**

- Aliexpress: $0.72
- eBay: $0.93

These don't appear to break out the DTR or CTS pins so they won't do auto-reset.

**CP2102 breakout board:**

- Aliexpress $1.00
- eBay: $1.31

body:
Basically, you need any way to talk to the [serial](https://www.arduino.cc/en/Reference/Serial) interface (on digital pins 0 and 1) on the Pro Mini. Remember that for programming you'll also need to be able to [manipulate the reset line](https://rheingoldheavy.com/arduino-from-scratch-part-11-atmega328p-dtr-and-reset/) on the target board, usually done via DTR.

If you already have an Arduino board with USB, you could write a small sketch that uses that as the interface. Using the [SoftwareSerial](https://www.arduino.cc/en/Reference/SoftwareSerial) library or the [AltSoftSerial](http://www.pjrc.com/teensy/td_libs_AltSoftSerial.html) library you could have the USB Arduino talk to the Pro Mini via a couple of data pins and relay the data back and forth. Depending on the Arduino you use and how you program it, it may or may not be able to keep up with 115,200 bps, but rates at or below 57,600 bps should be fine. You'll also need to handle the DTR and CTS signals for programming; this can be done with a couple more data pins.

In general what you're trying to do (whether you go with my solution or another one) is not a beginner project. If you're not familiar enough with Arduino systems to answer the question you posed, I'd strongly suggest buying an [Uno](https://store.arduino.cc/product/A000066), [Nano](https://store.arduino.cc/product/A000005) or other board with integrated USB rather than trying to play with the Pro (which is called that for a reason).

If the cost of a single Arduino board is an issue, make sure you're looking around for the cheapest sources. You can find "non-brand" versions of many boards, such as [this "Nano"](https://smile.amazon.com/dp/B00E87VWY4) for considerably lower prices than you'll see from the name-brand vendors. They're lower quality and you're not supporting the Arduino ecosystem, but they help when you have a very limited budget.


body:
I am working on a arduino Uno project* to detect eye pupil movement and I am thinking of using a serial low-res jpeg camera. I am thinking of implementing a cross-correlation function to detect when the pupil is turned towards the camera.

I am looking, so far unsuccessfully, for a c source code that performs a 2D cross-correlation without using FFT (Fourier Transform). I think such code might have good enough performance even on an Arduino Uno board when running on a low-res image, something like a 32x32 pixels image.

I'd appreciate if you could direct me to such a piece of code or alternatively tell me that this can't be done on an Arduino board due to CPU\RAM limitations.

[Current Device is using an IR range finder to detect IR reflected from the retina when looking directly into the device.][1]

P.S.

* The project is intended to provide ALS patients the capability to use eye-motion to call for help, using a low-cost device.

  [1]: https://www.youtube.com/watch?time_continue=26&v=iaICOBk-bmo

title: 2D cross correlation code for small images

Answers: 0


body:
I am trying to control a Nema 17 motor with a L298n dual bridge and an Arduino Mega.

My wiring is from this Instructable:

http://www.instructables.com/id/Control-DC-and-stepper-motors-with-L298N-Dual-Moto/?ALLSTEPS

When I connect it to my laboratory power supply the current limitation blinks. Normally when there is too much current needed the LED is all the time on and not blinking.

So I increase the current limit and the motor just starts moving on 3.1A @ 12V (doesn't move if less current) and in the description of the motor on amazon
they say "Rated Current/Phase:1.2A" so I am wondering what did I do wrong here?

From my understanding "Rated Current/Phase:1.2A" means that I should run this motor (it's a bipolar stepper motor with 2 phases) not higher than 2.4A?

These are the informations from amazon about this motor:

**Specifications**:

- Led screw diameter: 8mm

- Lead screw length: 300mm

- Step angle :1.8 degree

- Nut material: Brass

- Holding Torque: 400mN*m

- Thrust(full step): 12.5kg

- Rated Current/Phase:1.2A

- Rate Voltage: 3.3v

- Rated Resistance/Phase:2.2±10%ohm

What would be a good voltage to run this motor? I thought 12V is a good idea with.

The motor L298n gets really hot when I run it at 3.2A or more so I think my setup will destroy the dual bridge and / or the motor.

I really appreciate help on this! :-)

[![Arduino Mega with L298n dual bridge, Nemi 17 stepper motor, Arduino Mega and QJ3005EIII][1]][1]

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

title: How to control a Nema 17 stepper motor with an arduino? (too much current / heat)

Answers: 1

body:
The stepper motor does not directly control or limit its own current.  When using the L298n for stepper control, the motor current control is performed by a PWM signal to the L298n ENABLE pin.  If you have ENABLE high (100% duty), current will be a factor of only the DC resistance of the stepper winding and the power supply voltage.  Here you are trying to drive a 1.2A@3.3V-rated stepper from 12V, so naturally the current will be ~3 times greater.

To adjust the motor current to a safe range for the driver, use analogWrite() from a PWM-capable pin on the Arduino connected to the ENABLE pin on the L298n, and set it to something less than 255 (50% is usually a good starting point).  Even then, the instantaneous current draw on the L298n will likely be stressing it outside of its operating envelope.

EDIT: I reviewed the info at the link, and this is the relevant area of the code:

    // set speed to 200 out of possible range 0~255
    analogWrite(enA, 200);
    // set speed to 200 out of possible range 0~255
    analogWrite(enB, 200);

Here is where the code is setting PWM of the two ENABLE pins to 200 (~80% duty cycle).  Drop this to 50 (~20% duty cycle) and you would likely resolve your overcurrent issue.  Reading further still, even the author gives you your first hint at what is happening:

> This is not a speed value, instead power is applied for 200/255 of an
> amount of time at once.


body:
I'm trying to check whether the input string contains all digits or not. I achieved this using 2 different algos. One is to convert the string to integer using String.toInt() and then checking if its value lies between the integer of length of the input string.

e.g. If input string is "123". The corresponding integer must lie between 100-999.

Second, I wrote a function that iterates over each character of the string and checks if its ASCII values lies between 48-57. If not, it returns false.

When I bench marked these two algos, I found that when the string contains only digits, the 2nd algo is about 9 times faster than the 1st one. **But when the string contains even a single non-digit character, the 1st algo takes ~1ms, but the 2nd algo always takes ~5ms.** Why is this? I've not been able to figure this out.

The code:

    unsigned long start;
    unsigned long middle;
    unsigned long end;

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

      // send an intro:
      Serial.println("String toInt():");
      Serial.println();
    }

    void loop() {
      // Read serial input:
      if (Serial.available()) {
        String r = Serial.readString();

        start = micros();
        unsigned long rInt = r.toInt();
        int rLen = r.length();

        if ((rInt >= floor(pow(10, rLen))) || (rInt < floor(pow(10, rLen-1)))) {
          Serial.println("Please enter valid integer value!");
        } else {
          Serial.println(rInt+1);
        }

        middle = micros();

        bool isInt = doesContainInteger(r);
        if (isInt) {
          Serial.println(r);
        } else {
          Serial.println("Please enter valid integer value!");
        }

        end = micros();

        Serial.println(middle-start);
        Serial.println(end-middle);
      }
    }

    bool doesContainInteger(String s)
    {
      int sLen = s.length();
      for (int i=0; i<sLen; i++) {
        char sChar = s.charAt(i);
        if (sChar<48 || sChar>57) {
          return false;
        }
      }
      return true;
    }

title: Benchmarking String.toInt() vs Checking individual characters gives unexpected result

Answers: 2

body:
1 ms means easy calculation.

2 ms means more time spent in calculation.

5 ms means far more time in message printing to Serial buffer.

I calculated the error message passes serial line in 20-30 msec, so that is why I think there has to be a little bit faster buffer in between there.

body:
As pointed out by [Majenko](https://arduino.stackexchange.com/users/4143/majenko) in his (slightly annoyed) comment, you need to change your timing code to time only the calculations you want benchmark, not the I/O or other irrelevant code. For checking the conversion using `toInt()`, for example, try:

    // time our conversion
    unsigned long start = micros();
    unsigned long rInt = r.toInt();
    bool invalid = rInt == 0;
    unsigned long end = micros();

    // print the result
    if (invalid) {
        Serial.print("in");
    }
    Serial.print("valid conversion took ");
    Serial.print(end - start);
    Serial.print(" microseconds.");

Note that your assumption that a three-character input that's a valid integer will be between 100 and 999 is wrong; `"003"` and `"-17"` are both three-character inputs that should be correctly converted.

According to the [`toInt()` documentation](https://www.arduino.cc/en/Reference/StringToInt), `0` is returned on failure to convert, so I check for that in the code above. But since one can't tell the difference between a successful conversion of `"0"` and unsuccessful conversion of `"abc"` or some other non-integer, you really should be sure _before_ you call `toInt()` that you've got a valid integer int the string.


body:
I am trying to make a heart rate analyzer device using an Arduino board that will calculate the BPM of a person by using raw sensor signals greater or equal to the threshold value to calculate pulses/heartbeat in 10 seconds and then multiply the number of pulses by 6.

The circuit is fairly simple: it has a led that is going to flash on the finger of the person. In-front of the finger there is going to be a photoresistor that is going to read changing values of light falling on it. The values will be varying because of the blood flowing through the finger. When there is going to be a  pulse/heart-beat the amount of light falling on the photoresistor will increase, hence the reading of the photoresistor will also increase.

If the raw values read by the sensor are equal to or greater than the threshold value the code will increment the number of pulses by 1. To calculate the heartbeat rate we will have to count the number of pulses/heart-beats for 10 seconds and then multiply the count by 6.

In short the code that I will use will convert raw analog sensor data into BPM (Beats Per Minute) so that a user can get a standard measurement of his pulse rate.

I took the code that I am going to use from [a website][1]. Here is a link to page so that you can also have a look at the code.

  [1]: https://github.com/GeeveGeorge/SUMO_ppg/blob/master/Edison_Sketch.ino

I had some problem in the code and was wondering if anyone could help me with it. The full code is given below:

    int sensorValue = 0;
    int sensorValue = 0;
    // variable to store the value coming from the sensor
    int count=0;
    unsigned long time1=0; // store the initial time
    unsigned long time2; // store the current time

    void setup() {
      // declare the ledPin as an OUTPUT:
      pinMode(sensorPin, INPUT);
      Serial.begin(9600);
    }

    void loop() {
      // read the value from the sensor:
      if(count==0) {
        time1=millis();
      }
      time2=millis();
      sensorValue = analogRead(sensorPin);
      if(sensorValue>156) {
        increment();
      }
      if(time2>=time1+10000) {
        counter();
      }
    }

    void increment() {
      count++;
      while(sensorValue>156) {
        Serial.print("Sensor value is greater than .75V\n");
      }
    }

    void counter() {
      count=count*6;
      Serial.print("Heartbeat rate is ");
      Serial.print(count);
      Serial.print(" per min\n");
      time1=0;
      time2=0;
      count=0;
    }

Part of the code I'm not able to understand. This is located at the very top of `void loop()`:

[note: i pretty much understand how increment and counter functions work but i am not able to understand how the program is able to take input for 10 seconds.basically how the counter function runs for 10 seconds]

     if(count==0) {
        time1=millis();
      }
      time2=millis();
      sensorValue = analogRead(sensorPin);
      if(sensorValue>156) {
        increment();
      }
      if(time2>=time1+10000) {
        counter();

Although I know that this part of the code that I am not able to understand counts the pulses for 10 seconds by taking raw sensor values and checking if these values are above or equal to the threshold value, I am not able to understand how it is working.

I would be highly obliged if anyone could help me with this problem of mine.

title: Trying to make a heart rate analyser with Arduino that will calculate the BPM of a person

Answers: 2

body:
    // Record the start time into time1
    if(count==0) {
      time1=millis();
    }

    // Set time2 to the current time
    time2=millis();

    // Read the sensor
    sensorValue = analogRead(sensorPin);

    // If the sensor value is high enough, increment the beat counter
    if(sensorValue>156) {
      increment();
    }

    // If the current time is greater than, or equal to, the start time
    // plus 10,000 milliseconds (10 seconds), show the heart rate
    if(time2>=time1+10000) {
     counter();
    }

body:
    int sensorValue = 0;
    // variable to store the value coming from the sensor
    int count=0;
    unsigned long time1=0; // store the initial time
    unsigned long time2; // store the current time

    void setup() {
      // declare the ledPin as an OUTPUT:
      pinMode(A1, INPUT);
      Serial.begin(9600);
    }

    void loop() {
      // read the value from the sensor:
      if(count==0) {
        time1=millis();
      }
      time2=millis();
      sensorValue = analogRead(A1);
      if(sensorValue>800) {
        increment();
      }
      if(time2>=time1+10000) {
        counter();
      }
    }

    void increment() {
      count++;
      while(sensorValue>800) {
        Serial.print("Sensor value is greater than .75V\n");
      }
    }

    void counter() {
      count=count*6;
      Serial.print("Heartbeat rate is ");
      Serial.print(count);
      Serial.print(" per min\n");
      time1=0;
      time2=0;
      count=0;
    }


body:
#1. A short preliminary introduction

I'm deploying a small network of three MEGAs connected trough an RS-485 bus.
Each MEGA is connected to up to 16 push-buttons (wall-mounted) and two relay-module (2 x 8-SSR; located close to the MEGA). The objective is to manage the lighting of the whole house (aka: "switching 'ON' the relay 'R1' when the push-button 'PB1' is pressed").

At the moment, everything runs fine: MEGAs are able to 'broadcast' events along the BUS and each node is able to properly react to both locally-generated events, as well as events coming from the BUS.

Above system is running from a couple of weeks and... I'm starting struggling about "updating" the code: having around 40 push-buttons and 35 relay distributed on the three nodes, chances are "high" that some "tuning" (aka: "trial-and-error") is required.

Things get even worse when... you start enjoying the powerfullness of the system (aka: "Hai! What about turning-OFF _ALL_ the lights of the main-floor by long-clicking PB1?"). This, obviously, requires a "patch" to the code and a related "upload" the the MEGAs. And so on: _LOTS_ of uploads :-(

Having some ESP8266-12E modules sitting around, I decided to investigate the possibility to use them, as a sort of "WiFi gateway": reaching them via WiFi; sending them the new code; asking them to kindly "upload" the code to its own MEGA that is phisically connected via USART.

As mentioned in lots of places (including a comment on [this other question][1]) I decided to test the [ESP-Link][2] firmware.

As I'm having problems interconneting the MEGA with the ESP, here I'm, asking this community :-)

#2. Hardware involved
As for the Arduino side, I'm using a common MEGA (a Chinese one, BTW), so I don't get into details, here, 'cause there is nothing special.

As for the ESP8266, strictly speaking I'm **NOT** using a straight ESP8266-12E, but a Development Board. Actually, I'm using a **Lolin NodeMCU v3**, [this][3], that you can see here below:

[![Lolin NodeMCU v3][4]][4]

My plan is to connect _DIRECTLY_ the USART of the ESP to the USART of the MEGA. This raises some problems, described below.

#3. GPIO voltage issues
One of the very first issues that I addressed relates to GPIO voltage.
While it's **crystal clear** that:

- GPIO PINs, on MEGA, are 5V based and, as such:
   * the TX on the MEGA side will send out a 5V current;
   * the RX on the MEGA side expect to receive a 5V current;

-  GPIO PINs, on ESP8266-12E, are 3.3V based and, as such:
   * the TX on the ESP side will send out a 3.3V current;
   * the RX on the ESP side expect to receive a 3.3V current;

I still am **NOT** able to understand if this is --in my case-- a real problem. I'm saying this, 'cause:

1 - Transmission from ESP to MEGA should **NOT** be an issue, as the HIGH/3.3V signal coming in into MEGA should still be recognized as HIGH, from the MEGA, as it's higher than 2.5V;

2 - Transmission from MEGA to ESP **COULD** be a problem, if PINs on the ESP are **NOT** 5V tolerant

As for point 2) I deeply searched all-around and found plenty of contradictory assertions. In the end, I would like to "trust" [the Hackaday article: "Ask Hackaday: Is The ESP8266 5V Tolerant?"][5] as, in several comments, reports various semi-official statements (like a message from Expressif CTO sent from a Facebook account or a message from an "internal" of Espressif) asserting that: "*Yes! GPIO PINs on the ESP8266-12E are 5V tolerant*").
So, again, I decided: "Ok! Let me go! Let's connect the two, **straight**, without a level-shifter". And yes: I know that with such a decision, I'm taking some risks and... can "burn" something, especially on the ESP side.

So, here's my:

> **Question 1: How much I'm "brave" in connecting straight-away the TX/RX of the ESP8266 to the RX/TX of the MEGA? Would you suggest it? And why?**

#4. Ground issues
While working on my RS-485 bus, I learnt that it's critically important to have a "common ground" among my MEGAs. That sounds understandable... as otherwise there is **NOT** a common reference to evaluate the same signal among different devices.

So, now that I've **TWO** equipment and I'm giving them POWER via two distinct sources (MEGA directly connected to my PC; ESP connected to another PC), I'm wondering if:

> **Question 2: Do I need to connect a GND PIN on the MEGA to a GND PIN on the ESP? Do the two boards, to properly operate, need a shared/common GND?**

#5. RESET line on the MEGA
In order to trigger the flashing of the new sketch on the Arduino side, the ESP need to RESET it. To do this, the ESP need to be connected to the RESET line of the MEGA. The RESET PIN is clearly shown on the MEGA so the connection is really easy.

Nevertheless, after some preliminary test... it looks to me that the ESP is **UNABLE** to reset the MEGA.

This lead to:

> **Question 3: Is, an ESP8266-12E OUTPUT PIN (operating at 3.3V), able to properly handle the RESET PIN of the Arduino?**

I'm asking also 'cause based on the [official documentation of the MEGA][6] I read:

    Reset PIN: Bring this line LOW to reset the microcontroller.
    Typically used to add a reset button to shields which block
    the one on the board.

#6. Physical connections
In the [official documentation of ESP-Link][7] I read about potential problems generated (to Arduino) by the ESP as, right after a reboot of the ESP, it send out on TX some debug messages. Due to the USART connections, such characters transmitted by the ESP to the MEGA are received by the MEGA. It's not clear, to me, WHY this could be a problem. Anyway, the same documenation say: "*...If you need to avoid this, you can configure esp-link to swap the uart pins...*"

So, in the end, I connected the two devices following the official doc, with USART PINs swapped:

* GPIO13: connect to TX of microcontroller
* GPIO15: connect to RX of microcontroller and use a pull-down to ensure proper booting
* GPIO12: connect to RESET of microcontroller
* GPIO14: connect to ISP of LPC/ARM microcontroller (not used with Arduino/AVR)
* GPIO0: either a 1k-10k pull-up resistor to 3.3v or a green "conn" LED via a 1k-2.2k resistor to 3.3V (indicates wifi status)
* GPIO2: either a 1k-10k pull-up resistor to 3.3v or a yellow "ser" LED via a 1k-2.2k resistor to 3.3V (indicates serial activity)

As I don't need (currently) any LED feedback, I haven't used GPIO0 and GPIO2. Also, as I don't have an ARM, I haven't used GPIO14.

With help of [this][8] mapping I ended with following connection:

[![enter image description here][9]][9]

#7. Results (...and problems)
To test what's going on, I've uploaded to Arduino a simple sketch that turn ON/OFF the internal LED every second and dump an increasing counter on the console. Here it is:

    unsigned long counter;

    void setup() {
      Serial.begin(9600);
      pinMode(13, OUTPUT);
      counter = 0;
    }

    void loop() {
      Serial.print("[");Serial.print(counter);Serial.print("] ");
      Serial.println("on");
      digitalWrite(13, HIGH);
      delay(1000);
      Serial.print("[");Serial.print(counter);Serial.print("] ");
      Serial.println("off");
      digitalWrite(13, LOW);
      delay(1000);
      counter++;
    }

so, from the console output, I can see if Arduino is correctly operating and if it's restart.

On the ESP-Link side, I've configured the PIN as shown below:

[![enter image description here][10]][10]

With all the above in place, up to know, I've been experimenting the following:

- If I connect ONLY the RESET line and the TX/MEGA to the D7/GPIO13/ESP, I can succesfully reset the Arduino from the ESP-Link web interface and I can see the "console" of the MEGA (I can be sure of succesfully reset, as the counter in the Arduino console, restart);
- Above apply:
   - when the MEGA is powered via a full-USB connection from a PC;
   - when the MEGA is connected via a power-only USB cable from the PC;
   - when the MEGA is powered via a USB-power-bank, but in this case _ONLY_ if thereis a shared-GND between ESP and MEGA

- As soon as I connect the D8/GPIO15/ESP to the RX/MEGA, everything still work, but up to next reset. If I "reset" the Arduino via the ESP-Link web-interface, it reset but.... never boot (I'm sure, as the "blinking" never start).

So, the last question:

> **Question 4: What's wrong with above testbed? Why the D8/GPIO15/ESP disrupt the boot process on the MEGA? I've swapped the UART PINs exactly to avoid this... as far as I understood...**

Sorry to be so long but... I think that details matter :-)

  [1]: https://arduino.stackexchange.com/q/24350/13193
  [2]: https://github.com/jeelabs/esp-link
  [3]: https://it.aliexpress.com/item/new-Wireless-module-CH340-NodeMcu-V3-Lua-WIFI-Internet-of-Things-development-board-based-ESP8266/32556303666.html?spm=2114.46010108.5.1.jxTxQA&&scm=1007.12783.72505.0
  [4]: https://i.stack.imgur.com/ILpco.jpg
  [5]: http://hackaday.com/2016/07/28/ask-hackaday-is-the-esp8266-5v-tolerant/
  [6]: https://www.arduino.cc/en/Main/ArduinoBoardMega
  [7]: https://github.com/jeelabs/esp-link/blob/master/FLASHING.md
  [8]: https://github.com/nodemcu/nodemcu-devkit
  [9]: https://i.stack.imgur.com/LNg2z.jpg
  [10]: https://i.stack.imgur.com/JkaNZ.jpg

title: Uploading Arduino code, OTA, via connected ESP8266-12E running Esp-Link

Answers: 1

body:
I have successfully used ESP-link firmware with esp-01 and Arduino Pro Mini.

For the ESP-01 and Pro Mini, you can find out more on my [blog post][1]. I have connected GPIO 0 of ESP-01 to reset pin of Pro Mini and the Pro Mini can be reset using ESP-Link the web interface. I try to use the same voltage level for both micro-controllers and a single power source. For my example, the Pro Mini is driving the ESP-01 and of-course sharing the common ground.

To answer your questions.

1. I try not do that as ESP has stated that all the GPIO pins are only 3.3v compatible.

2. Yes, both controller must share a ground.

3. My understanding is RESET is an output pin. If connected to ESP8266, there is a possibility that the ESP will be damaged.

4. Not sure if your wiring is correct. You may reference my diagram on how the ESP and Arduino Pro Mini is wired up. For your case, I will recommend a level shifter to prevent damaged to your ESP.

  [1]: http://iotdiary.blogspot.sg/2017/09/using-esp-link-transparent-bridge.html


body:
so please read this whole thing.

My Project: I am making a bell system that is based on PHP. The bell is connected to the arduino UNO via a relay and the arduino is connected to the computer via a USB cable. The interface with the database is built with PHP and MySql. Then we have the code which checks every minuit if the bell has to be rung and if it does send a numeric value to the arduino. There is also an option for a longer bell if we send a '0' to the arduino.

My Code: So this is the file that checks if bell has to rung and sends value to arduino

    <?php
    include('database.php');
    $usb_comPort = "COM3";
    date_default_timezone_set("Asia/Kolkata");
    $time = date("H:i");
    $time = trim($time);
    $sql = "SELECT bell_amount FROM bell_db WHERE DATE_FORMAT(bell_time,'%H:%i') LIKE '$time'";
    $result = mysqli_query($conn, $sql);
    $numRows = mysqli_num_rows($result);
    if ($numRows == 0) {
      echo 'Error: Nothing found!';
    } else {
      $row = mysqli_fetch_assoc($result);
      $bellAmount = $row['bell_amount'];
      $runCommand = "ECHO " . $bellAmount . " > $usb_comPort";
      echo $runCommand;
      exec($runCommand);
    }
    ?>
    <html>
    <meta http-equiv="refresh" content="60">
    <body>
    </body>
    </html>

and this is the arduino's code:

    int b = 0;
    void setup() {
    Serial.begin(9600);
    pinMode(10, OUTPUT); //relay
    }

     void loop() {
      b = Serial.read();

        b = b - 48;
        if(b == 0){
          digitalWrite(10,HIGH);

          delay(3000);
          digitalWrite(10,LOW);
          }
        else{
        for (int i=0; i < b; i++){
          digitalWrite(10, HIGH);
          delay(200);
          digitalWrite(10, LOW);
          delay(200);
          }

        }

    }

The Issue that i am facing: My aim is that the code should run automatically when the computer is turned on. The code works fine but there is random bug. The code is uploaded to the arduino. When the computer is turned on i want that the system should work but when i run the file  (the one that checks if there is a bell to be rung or not ) it processes the code but it is not able to send a value to the com port so the bell does not ring(the serial light on the arduino does not flash). But if i go to the arduino ide and send a value through the serial monitor once then run the php file, it works!

I am running this on a windows 10 computer, i have an arduino UNO and i have tried this with 2 arduino's same result on both.

So anyone know what i can do?

title: Arduino Com port and PHP Bug

Answers: 1

body:
Sounds like the COM port is not setup. Opening the Arduino IDE probably does this automatically.

Try running the following command, only once, after turning on your pc to initialize the COM port.

    mode COM3 BAUD=9600 PARITY=n DATA=8

Ps. I'm not a windows user, so this is an educated guess - [reference](https://batchloaf.wordpress.com/2013/02/12/simple-trick-for-sending-characters-to-a-serial-port-in-windows/).

Pps. I think you're winning the award for the most complicated way to ring a bell. :)


body:
Along all the "advanced" methods [described in this article][1], does simple method as downscaling processor while `delay` makes a difference on power consumption? How much time does the clock alternation takes itself?

Is below example valid?

    #include <avr/power.h>

    void setup() {}

    void loop {

        /*
           here some jobs to do...
        */

        clock_prescale_set(clock_div_256); // downscale clock
        delay(200); // wait
        clock_prescale_set(clock_div_1); // restore clock
    }

  [1]: http://www.gammon.com.au/power

title: Is setting clock divider worth changing on delay() to save power?

Answers: 1

body:
Reducing the CPU frequency should work, but I would expect better
savings by sleeping during the busy loop:

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

    #include <avr/sleep.h>

    void sleepy_delay(uint32_t duration)
    {
        uint32_t start = millis();
        while (millis() - start < duration) {
            sleep_mode();
        }
    }

Note that the sleep will be interrupted at least on every Timer 0
overflow interrupt, which happens every 1024 µs (that's what
increments the value returned by `millis()`), so there is no risk of
oversleeping. You could add some `power_*_disable()` calls for better
savings.