message:
Control solenoid valve with arduino running on battery

I built a simple setup according to this tutorial using a 9v battery (in the meantime replaced it with a 120A battery):
https://www.bc-robotics.com/tutorials/controlling-a-solenoid-valve-with-arduino/

Also i attached a humiditiy sensor to measure the soil-humidity.
My plan is:
2 times a day (evening and morning before sunrise) wake up arduino and check humidity, if it is below a certain %, open the 12v-valve, wich i operate at 9v (like the one in the tutorial).

I read a lot about how to reduce power on the arduino and found this tutorial for the pro mini, wich seems a LOT easier than to modify the standard arduino uno:
https://www.whizzy.org/2015/06/howto-very-low-power-usage-on-pro-mini-v2-arduino-clone/

Now, my question is:
would a pro mini v2 work as well for controlling the valve? On the uno, i have the vin-pin wich provides the 9v for the valve, on the pro mini instead, as far as i understood, i need to use that pin (named RAW pin there) as power supply for the arduino... but how would i get out the 9v from the arduino like i did on the uno? Is there any possibility at all?

Thanks in advance!

body:
Vin and the barrel jack are the same power input on Uno.

RAW is the label for Vin on Mini Pro.

You can connect the `+` of the battery to power rail of the breadboard and from there to Vin/RAW pin of Arduino and to the solenoid powering contact.


sender: user

message:
Can I use 1 clock module for multiple Arduinos?

I want to connect an RTC to a master Arduino, send the time data to a slave Arduino through I2C, then connect an LCD to the slave and print it out.

can it be done? A think it would mean that the slave Arduino is a master for the LCD a the same time and it would mess up my code. Any input would be highly appreciated.

sender: assistant

body: The LCD is connected over SPI. The MCU can be an I2C slave and the SPI master. There is no conflict.


body:
From what I understood. I think you are trying to pass time to 2 ardruinos using one RTC.
m.a. = master arduino
s.a. = slave arduino

                                RTC
                                /\ (i2c)
                            m.a.  s.a.-------------(LCD)
                             L______|(spi)

No you cannot
but you can read time in master and then relay it to slave using your own protocol (i.e. "Apr  4 21:20:16 IST 2018") and let it print to LCD.

          RTC ------ m.a. ======= s.a. ++++ (lcd)
                i2c          spi
            (read reg.)  (pass string)

Humble NOTE:- If possible draw some digram while you are explaining circuit. It will be far easy to understand and answer than explaining circuit. may be draw on paper and upload to igmur/drive and add link in question or upload it here.
My ascii digrams may not be best but I think they pass message clearly.


message:
How does the build process in Arduino IDE work for ESP8266

How does the build process for esp8266 work in arduino IDE. Arduino ide uses avr-gcc to compile programs For atmel micro controllers. Does it uses same for compiling programs for esp8266?

body:
> Does it uses same for compiling programs for esp8266 ?.

No. It uses `xtensa-lx106-elf-gcc`. The compiler has to match the architecture.

Most of the build "process" (as in the actions that are taken) is the same, but executables specific to the EXP8266's XTensa core are used. There's also a few extra things in there, like building the (optional) SPIFFS image, etc.


message:
MKR1000 - Connecting to Pubnub

I don't know if it's a stupid question but I need some help.<br>
I am trying to follow this [tutorial][1] and I want to connect my arduino to PubNub. In the tutorial it says that I have to 'open PubNub.h and switch the comments for the Ethernet and WiFi lines' with some code provided there. But, when I open the file PubNub.h the only thing in there is this:

    /* -*- c-file-style:"stroustrup"; indent-tabs-mode: nil -*- */
    #include "PubNubDefs.h"

    class PubNub PubNub;

I'm quite new to this so I don't know much. I hope someone can help. Thank you in advance!

  [1]: https://www.pubnub.com/blog/2016-08-10-getting-to-know-arduinos-mkr1000/

body:
It appears the tutorial is now outdated and the PubNum library does not need the changes described in the tutorial.

The [PubNub library][1] has an example titled [PubNubWifi101][2] which shows the client type being set with a `#define` before including the PubNub headers:

    #include <WiFi101.h>
    #define PubNub_BASE_CLIENT WiFiClient
    #include <PubNub.h>

I don't have a MKR1000 to test with, but I was able to compile the example from the [tutorial][3] by adding that single `#define` after the `#include <WiFi101.h>`.

  [1]: https://github.com/pubnub/arduino
  [2]: https://github.com/pubnub/arduino/blob/master/examples/PubNubWifi101/PubNubWifi101.ino
  [3]: https://raw.githubusercontent.com/pubnub/arduino-mkr1000/master/Simple_Publish.ino


message:
Arduino MKR1000 as Access Point

I want to turn my Arduino MKR1000 into an Access Point. My code is the following:

    #include <SPI.h>
    #include <WiFi101.h>
    #define PubNub_BASE_CLIENT WiFiClient
    #include <PubNub.h>

    WiFiServer server(80);
    char ssid[] = "MKR1000";
    int status = WL_IDLE_STATUS;

    void setup() {
      delay(1000);
      Serial.begin(9600);
      Serial.print("Creating access point named: ");
      Serial.println(ssid);
      if (WiFi.beginAP(ssid) != WL_CONNECTED) {
        Serial.println("Creating access point failed");
        while (true);
      }
      server.begin();
      printStatus();
    }

    void loop() {

    }

    void printStatus() {
      Serial.print("SSID: ");
      Serial.println(WiFi.SSID());
      IPAddress ip = WiFi.localIP();
      Serial.print("IP Address: ");
      Serial.println(ip);
      long rssi = WiFi.RSSI();
      Serial.print("signal strength (RSSI):");
      Serial.print(rssi);
      Serial.println(" dBm");
      Serial.print("To connect, join the network and open a browser to http://");
      Serial.println(ip);
    }
After uploading this, in the serial monitor I get this:

    Creating access point named: MKR1000
    Creating access point failed
I'm new to this so I really don't know what's the problem. I hope someone knows what's going on.<br>Thank you in advance.

body:
I found [this reference][1] for `Wifi.beginAP()` in the [Wifi101 library][2], which I hope is the correct one - apologies if it's not.

It says that `beginAP()` returns either `WL_AP_LISTENING` or `WL_CONNECT_FAILED`, so checking for `WL_CONNECTED` is not sensible.

Try this:

    if (WiFi.beginAP(ssid) != WL_AP_LISTENING) {
      Serial.println("Creating access point failed");
      while (true);
    }

  [1]: https://www.arduino.cc/en/Reference/WiFi101BeginAP
  [2]: https://www.arduino.cc/en/Reference/WiFi101


message:
Interaction between Analog Pins when measuring a DC voltage- a common issue?

Just set up a replacement "Piduino" - a RPi3 connected by USB to an Arduino Uno.  The previous one was the victim of a Diet Big Gulp - spilled on the voltage divider breadboard.  Whoops.  The tiny breadboard with the voltage divider began to rust inside so it got really difficult to keep it working correctly.

This is for the plot named "Indoor 12V Lighting System" at https://www.SDsolarBlog.com/montage

I built a new Uno/breadboard from scratch and swapped it in with the breadboard stuck onto the plastic case.  All nice and tidy.

But the analog inputs were really strange.  It would read really close, but then minor changes to the software would produce wildly varying results.

Imagine my surprise when this morning I discovered that I had plugged the divider's analog input to A4 instead of to A1 where it belonged.

Now that it has been fixed all is well.  As long as the correct pin is being used in the `digitalRead` it seems not to matter, perhaps.

Here is the plot from before then after I moved the input to the correct location:

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

The actual voltage was falling from 12.7 down to 12.5, and after moving the pin it settled down to the correct reading.  Then I turned on the charger while the sun is up.  It is tracking the voltmeters perfectly now.

Clearly, the problem was that I was reading the wrong pin.  My fault, obviously. But it got me wondering just how much they affect each other.

So my question is about why I was getting any readings at all?  I would have hoped that the analog inputs were truly separate from each other.  Instead, it appears as if there is crosstalk of some kind.

Is this a common issue?

-----------------
**New information**

I see that it has been pointed out that this was discussed in this Q&A:

https://arduino.stackexchange.com/questions/574/should-all-unused-analog-input-ports-be-tied-to-ground-for-accurate-a2d-measurem

But since that does not call it an imperative, just "one of the problems with using analog" I would have assumed that this is not common, so perhaps there is an implied answer there.

It would be a project all by itself to use half the small breadboard to distribute ground to all the other analog pins.  And I've never seen this referenced in any of the documentation.  Nor is there a tag for crosstalk.

So my question still stands:  Is this common when measuring a DC voltage?

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

body:
This is normal and expected behaviour.  There are a number of factors that influence it, and it will help to understand the basic internals of the ADC.

In simple terms the front-end of the ADC looks like this:

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

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

<!-- End schematic -->

The MUX selects which pin (A0-A5) is being sampled. Switch SW1 connects the *Sample And Hold* capacitor C1 to that selected input, which then charges (or discharges) to the same voltage as the input.

After the acquisition period switch SW1 switches position and the ADC circuit is connected to the capacitor.  Over a period of clock cycles the ADC works out what the voltage across the capacitor is and stores the result in the ADCH and ADCL registers.

Now - on a pin that has nothing connected to it, what voltage will be across that capacitor when SW1 is switched to charge it? Well, this is where your strange results come from:

1. Any charge already in the capacitor will *still be there* (which is why it can be good to connect the unused ADC pins to ground through a resistor, to remove that charge).
2. Signals, either in wires, IC pins, or the silicon circuitry in the chip itself, will be capacitively coupled with what is next to it.

That last one is the most critical for your results.  Capacitive coupling.

Place two wires next to each other and they will, through capacitance, try and get the same charge on them. Under most circumstances that attempt to influence the charge is completely swamped out by what is being send down the wire. But, when there is *nothing* being sent down the wire that charge becomes noticable. A1 will attempt to "float" to the same level as A0, because they're next to each other. A2 will try and float to the same level as A1, A3 to A2, etc.

If you put a signal in to A0 and plot all 6 inputs you will see each has a progressively lower amplitude copy of the signal. It's hopping, capacitively, between the pins. And all because there's nothing to stop it.

If you think "Ah, but it's DC. DC doesn't go through capacitors", then you're wrong.  Wrong in thinking it's DC.  There's a lot of mistaken assumptions about the labels "AC" and "DC".

DC is not what you have.  Yes, there is a "DC component" to what you have (which is manifest as the average of the voltage over time), but there is a large AC component as well.  That AC component is what you are graphing in the form of your changing battery voltage.

Voltage is far more complex than just DC or AC. What you think of as AC is actually a waveform with a fundamental frequency (e.g., 60Hz) and zero "DC offset". Add a DC offset to the signal and it's still AC, but compared to the "lower" end of whatever adds the DC offset, it's just the waveform is "shifted up".

Pure DC, and what doesn't pass through a capacitor, has no signal components. There is only 0Hz and nothing else. Pure DC is almost impossible to create without highly specialized equipment. All voltages in normal life vary, and that variance is the AC component of the signal.


message:
Interacting with a video game - Keyboard & LUFA

I have an Uno and Leonardo that I am trying to have it interact with the GTA V video game. Using the Keyboard library, it works within the OS. But it ocassionally works within the GTA V process. It seems that the transfer speed may be too slow, as the game sometimes registers the key press and does the assigned command.
For instance, I can have a pushbutton that when pressed, it activates **Keyboard.Write('J')**. While in GTA V, I can rapidly press the pushbutton for 3 seconds and the game will only detect one **J** within that time frame and do the assigned game command.
Yet, if I rearrange the code to be momentary to where the pushbutton is active, it'll constantly send **Keyboard.Write('J')**, this will work for commands that are momentary ingame, like the vehicle horn.
Below is the code I used for my Uno. It works fine within programs.

    /*
      Keyboard Message test

      For the Arduino Leonardo and Micro.

      Sends a text string when a button is pressed.

      The circuit:
      - pushbutton attached from pin 4 to +5V
      - 10 kilohm resistor attached from pin 4 to ground

      created 24 Oct 2011
      modified 27 Mar 2012
      by Tom Igoe
      modified 11 Nov 2013
      by Scott Fitzgerald

      This example code is in the public domain.

      http://www.arduino.cc/en/Tutorial/KeyboardMessage
    */

    #include "Keyboard.h"

    const int buttonPin = 4;          // input pin for pushbutton
    int previousButtonState = HIGH;   // for checking the state of a pushButton
    int counter = 0;                  // button push counter

    void setup() {
      // make the pushButton pin an input:
      pinMode(buttonPin, INPUT);
      // initialize control over the keyboard:
      Keyboard.begin();
    }

    void loop() {
      // read the pushbutton:
      int buttonState = digitalRead(buttonPin);
      // if the button state has changed,
      if ((buttonState != previousButtonState)
          // and it's currently pressed:
          && (buttonState == HIGH)) {
        // increment the button counter
        counter++;
        // type out a message
        Keyboard.write('J');
        //Keyboard.print("You pressed the button ");
        //Keyboard.print(counter);
        //Keyboard.println(" times.");
      }
      // save the current button state for comparison next time:
      previousButtonState = buttonState;
    }

I also tried this same test using LUFA but the same issues were encountered.
I believe it has to do with the game, not my code.
Does anyone have a clue of why this might be?

body:
It is quite common for games to be quite slow at reading the keyboard.

The Leonardo's `Keyboard.write()` command is quite rapid. The OS can pick it up with its interrupt driven buffering, but games tend not to use that buffering so they can get more realtime key control.

The trick here is actually to slow down the Leonardo's sending, by not using `Keyboard.write()`. Instead you need to `press` the key, wait a moment, then `release` the key:

    Keyboard.press('j');
    delay(1);
    Keyboard.release('j');

Increase the delay until it becomes reliable. It's hard to say what the delay should be.


message:
How can I hack my intercom system to buzz people in remotely?

How would you go about activating this button remotely?

This board is from the intercom in my apartment. The button when pressed unlocks the building door. I've just ordered the MKR IoT bundle (https://store.arduino.cc/arduino-iot-mkr1000-bundle). My plan is to learn the basics and figure out how to activate this button remotely.

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

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

body:
3 possible solutions:

 1. Connect the 2 contact for the button to a relay and control that relay from the arduino ([example][1]) But the kit you have doesn't include a relay.
 2. Use a transistor to trigger the switch -- I would not recommend this option as your first project.  It would be easy to damage the intercom and/or your arduino.
 3. Use the servo in the kit to physically press the button.  You will need to figure out the mechanical linkages but you don't need to attach wires to the intercom.

For a beginner project I would probably go with the third option.

  [1]: https://learn.adafruit.com/experimenters-guide-for-metro?view=all#circ11-intro


message:
Two power source for Arduino and a relay

In my work, I have an ESP-8266, Arduino-Uno and a Relay. ESP 8266 and Uno is connected. Relay's data signal is take from arduino's 12th pin. ESP is powered from Uno.

If I use two different power sources for Uno and Relay, Relay does not response for the signal from Uno. (Both have a same common ground)

If relay is powered from Uno, then after load control (power on and off) ESP-8266 goes down.

body:
The uno can't provide enough power to power an ESP8266 __reliably__.  I suggest you power it from a separate source.

When ever you use separate power supplies for a circuit you need to "tie the grounds together", connect them.  Otherwise the circuits don't use the same definition of zero.


body:
Use  a relay driver IC like ULN2003 to drive relay.
Here is a sample circuit diagram : [![enter image description here][1]][1]

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


message:
Sampling and serial transfer

I am trying to get a sampling rate of over 10k Samples per second as well as send each sample over a serial line. Taking a sample and putting it on the serial line each time took too long. I am using Processing 3.3.6 for datalogging into a csv file. I am unable to achieve more than 6k samples per second even at lower prescaler value and high baudrate. What am I doing wrong? Here is my arduino code.

    int val[2000];
    void setup()
    {
      Serial.begin(250000);

      //ADCSRA = 0;             // clear ADCSRA register
      //ADCSRB = 0;             // clear ADCSRB register
      ADCSRA &= ~(bit (ADPS0) | bit (ADPS1) | bit (ADPS2)); // clear prescaler bits
      //ADCSRA |= bit (ADPS0);                               //   2
      ADCSRA |= bit (ADPS1);                               //   4
      //ADCSRA |= bit (ADPS0) | bit (ADPS1);                 //   8
      //ADCSRA |= bit (ADPS2);                               //  16
      //ADCSRA |= bit (ADPS0) | bit (ADPS2);                 //  32
      //ADCSRA |= bit (ADPS1) | bit (ADPS2);                 //  64
      //ADCSRA |= bit (ADPS0) | bit (ADPS1) | bit (ADPS2);   // 128
      //pinMode(A0, INPUT);

    }

    void loop()
    {
      for(int i=0; i<2000; i++) {
        val[i] = analogRead(A0);
      }
      for(int i=0;i<2000;i++){
        Serial.print(val[i]);
        Serial.print('x');
      }

    }

P.S I am new to arduino.

--edit1>>
I am using Arduino Mega 2560.

body:
Probably the serial port is too slow:

Assuming 250 kbits/s, is (including 3 start/stop bits, maybe 2 in your case) in about 250000 (bits/s) / 11 (bits/byte)= about 22 KBytes/s
Assuming each sample has 3 or 4 digits and an 'x' is added (which is 5 characters), 22 (KBytes/s) / 5 (digits/sample) = about 5-6 Ksamples/s you can transfer, which is what you experienced.

So you have to increase the speed for the serial port.


message:
Improper sampling of wave

I am using Arduino Mega 2560 to sample and serially send a square wave. I am using Processing 3.3.6 for logging the data to .csv file. I am receiving about 6k samples at the moment. When I try sampling a square wave, min= 0V, max=3V at 200Hz, the number of samples at the two amplitudes(at 0 and 3V) are not at all close by. What could be going wrong?

This is my Processing code:

    //import the required libraries
    import processing.serial.*;

    Serial mySerial;
    Table table;
    String filename;

    void setup()
    { //print(0);
      //set mySerial to listen on COM port 4 at 1000000 baud
      mySerial = new Serial(this, "COM4", 1000000);

      table = new Table();
      //add a column header "Data" for the collected data
      table.addColumn("Data");
      //add a column header "Time" and "Date" for a timestamp to each data entry
      table.addColumn("Time");
      table.addColumn("Date");
    }

    void draw()
    { print(1);
      //variables called each time a new data entry is received
      int d = day();
      int m = month();
      int y = year();
      int h = hour();
      int min = minute();
      int s = second();
      //int s_prev=0;
      char d1 = 'a';

      if(mySerial.available() > 0)
      { //print(2);

        //set the value recieved as a String
        String value = mySerial.readString();
        //check to make sure there is a value
        if(value != null)
        {
          String[] parts = value.split("x"); //returns an array with the 2 parts

          //print(parts);
          //print('\n');
          for(int i=0;i<parts.length;i++)
          {

            String Part = parts[i];
            TableRow newRow = table.addRow();
            //place the new row and value under the "Data" column
            newRow.setString("Data", Part);
            //place the new row and time under the "Time" column
            newRow.setString("Time", str(h) + ":" + str(min) + ":" + str(s));
            //place the new row and date under the "Date" column
            newRow.setString("Date", str(s + 100));// + "/" + str(m) + "/" + str(y));
          }
        }
      }
    print(4);}

    void keyPressed()
    { print(5);
      //variables used for the filename timestamp
      int d = day();
      int m = month();
      int h = hour();
      int min = minute();
      int s = second();
      //variable as string under the data folder set as (mm-dd--hh-min-s.csv)
      filename = "data/" + str(m) + "-" + str(d) + "--" + str(h) + "-" + str(min) + "-" + str(s) + ".csv";
      //save as a table in csv format(data/table - data folder name table)
      saveTable(table, filename);
      exit();
    }

This is my arduino code:

    int val[2000];
    void setup()
    {
      Serial.begin(250000);

      //ADCSRA = 0;             // clear ADCSRA register
      //ADCSRB = 0;             // clear ADCSRB register
      ADCSRA &= ~(bit (ADPS0) | bit (ADPS1) | bit (ADPS2)); // clear prescaler bits
      //ADCSRA |= bit (ADPS0);                               //   2
      ADCSRA |= bit (ADPS1);                               //   4
      //ADCSRA |= bit (ADPS0) | bit (ADPS1);                 //   8
      //ADCSRA |= bit (ADPS2);                               //  16
      //ADCSRA |= bit (ADPS0) | bit (ADPS2);                 //  32
      //ADCSRA |= bit (ADPS1) | bit (ADPS2);                 //  64
      //ADCSRA |= bit (ADPS0) | bit (ADPS1) | bit (ADPS2);   // 128
      //pinMode(A0, INPUT);

    }

    void loop()
    {
      for(int i=0; i<2000; i++) {
        val[i] = analogRead(A0);
      }
      for(int i=0;i<2000;i++){
        Serial.print(val[i]);
        Serial.print('x');
      }

    }

body:
You are doing 2000 samples really close together in rapid succession with no concept of time between them, then you are spending a considerable amount of time sending that data through serial.

That's not how you sample signals.

Instead, you need to set up some kind of time-based periodic sampling system, either through a timer interrupt or some other facility provided by the ADC (read the datasheet to see what interrupts the ADC can generate and what sample trigger sources there are) which runs completely asynchronously.  Then when (and only when) a sample set has been captured do you send that data through serial.

If your sampling takes longer than your sending through serial (unlikely) and you have the memory for it you can set up two buffers and "ping-pong" between them so you are sampling at the same time as sending.  Otherwise, all you will be able to do is capture a short window of data and then send it afterwards, so you get short bursts of samples.


message:
Digital Band pass filter arduino 1100-1300 Hz

For a project I need to design an digital band pass filter. I started of with this in Matlab:

    wch=1100*2*pi;
    wcl=1300*2*pi;

    sys=tf([1/wch 0],[1/(wch*wcl) 1/wch+1/wcl 1])
    sysd=c2d(sys,9615,'tustin')

    so I got this values:

    3.01e-08 z^2 - 3.01e-08/(z^2 + 2 z + 1)

Then I rewrote it to:

    y[k] = 3.01*10^-8*u[k]-3.01*10^-8*u[k-2] -y[k-2]-2y[k-1]

and so I put hoped that this arduino script should do the Job:

    #include <TimerOne.h>

    float out;

    float second_filt(float x0) {
      static float y1=0;  // y[n-1]
      static float y2=0;  // y[n-2]
      static float x1=0;  // x[n-1]
      static float x2=0;  // x[n-2]
      float y0 = 3.01*10^(-8)*x0-3.01*10^(-8)*x2-2*y1-1*y2 ;

      // Shift values
      y2 = y1;  // Shift y[n-1] to y[n-2]
      y1 = y0;  // Shift y[n] to y[n-1]
      x2 = x1;  // Shift x[n-1] to x[n-2]
      x1 = x0;  // Shift x[n] to x[n-1]
      return y0;
    }

    void setup() {
      Timer1.initialize(32); //Initialize timer with a period of 32 us
      Timer1.pwm(9,0); // Use pin 9 for PWM
    }

    void loop() {
      if (isTime()) {
        out=second_filt(analogRead(0));
        Timer1.setPwmDuty(9,out); //Sets the duty cycle to the analog value on pin 0
      }
    }

    bool isTime(){ //Checks if 300 us elapsed since the last call
      static unsigned long t0=0;
      static unsigned long t1=0;

      t1 = micros();

      bool res = (t1-t0)>300;

      if (res) {
        t0 = t1;
      }
      return res;
    }

Now I don't know what the error: 'invalid operands of types 'double' and 'double' to binary 'operator^' means and I am not sure if this is actually gonna work. Pleas help me out I have been busy with this for days.

body:
You cannot use ^ as mathematical power symbol in C. Ini C it means the exclusive-or bit operation (hence the error showing it is a bit operation).

For the mathematical power function, you should use the math C library. See [library explanation][1]. To include it, use:

    #include <math.h>

The power function has the following prototype:

    double pow(double x, double y)
    Returns x raised to the power of y.

However if you only need to write a float/double in exponential format, you can use

    3.01e-8

  [1]: https://www.tutorialspoint.com/c_standard_library/math_h.htm


body:
You have more than one problem here...

> `3.01e-08 z^2 - 3.01e-08/(z^2 + 2 z + 1)`

I don't quite understand your Mathlab code, but there is something wrong
with this transfer function. The denominator can be rewritten as
(z + 1)2. Thus there is a double pole at
z = −1, i.e. at the Nyquist frequency. An infinite gain at
Nyquist is not what you expect from a bandpass filter.

> `y[k] = 3.01*10^-8*u[k] - 3.01*10^-8*u[k-2] - y[k-2] - 2y[k-1]`

This is implementing the transfer function
3.01 × 10−8 (z2 − 1)/(z2 + 2 z + 1),
which is **not** the same as the one written above: mind the
parentheses.

> `float y0 = 3.01*10^(-8)*x0-3.01*10^(-8)*x2-2*y1-1*y2;`

As explained in Michel Keijzers’ answer, the constant should be written
`3.01e-8`. Also, you can save one multiplication by writing it as

    float y0 = 3.01e-8*(x0 - x2) - 2*y1 - y2;

> `if (isTime()) { out=second_filt(analogRead(0)); ... }`

You cannot expect to get a uniform sampling time with `analogRead()`, as
your timing will depend on how long your program takes to get trough the
loop, which is data dependent and affected by interrupts.

> sysd=c2d(sys,9615,'tustin')

I assume 9615 is the expected sampling rate, which translates to
104 µs between samples. This is the time it takes for the ADC to
perform one reading. You cannot achieve this rate if you do computations
_in between_ the readings.

Here your best option is to configure the ADC in _free-running mode_. In
this mode it will take one sample every 104 µs, and you will
achieve the desired sampling rate. You should also do the filtering _in
parallel_ with the readings, and have the CPU and the ADC work
concurrently instead of sequentially. For implementing this, you will
first have to read the datasheet of the ATmega328P powering your Uno.


message:
Is there alternative to arduino IDE program ESP8266 and ESP32 with arduino toolchain?

I use ESP8266 and ESP32 with arduino toolchain rather than pure arduino hardware.
Arduino IDE is standard and proven but what are the other IDE and advantage/disadvantage ?

body:
For example, Eclipse IDE with Sloeber plugin is much better than Arduino IDE. You have all the features of Eclipse (coloring, error highlighting, auto-complete, open declaration ('drill down' to libraries), ...*). And every project has own settings (board settings, port, programmer ...). And the Arduino IDE buttons Upload, Verify, Session Monitor are there and the Arduino toolchain too.

*... projects management, version control, TODO lists, outline, ...


body:
Not an exhaustive list. Most **advantages** will be subjective.

 - [UECIDE][1] - Wide variety of boards, not only Arduino, better editor and serial monitor, plug-in based modules.
 - [PlatformIO][2] (Available as plugin for [Atom editor][3], [MS Visual Studio][4] and [Eclipse IDE][9]) - Automatic library updating, one `ini` file that defines project settings and external libraries, making projects portable to other users without having to download all external libraries.
 - [Arduino IDE for Visual Studio][5] - For those who like VS?
 - [Arduino Makefiles][6] - More like old-school command-line coding, Linux-style development. Not an IDE.
 - [Eclipse][7] - Another quite popular IDE outside Arduino world.
 - [Atmel/Microchip Studio 7][8] - Provided by the manufacturer of the AVR chips. "Arduino" sketches may not compile without changes to make them more like standard C++.

  [1]: https://github.com/UECIDE/UECIDE
  [2]: https://platformio.org/platformio-ide
  [3]: https://github.com/atom/atom
  [4]: https://www.visualstudio.com/
  [5]: https://marketplace.visualstudio.com/items?itemName=VisualMicro.ArduinoIDEforVisualStudio
  [6]: https://github.com/sudar/Arduino-Makefile
  [7]: https://www.eclipse.org/community/eclipse_newsletter/2017/april/article4.php
  [8]: https://www.microchip.com/avr-support/atmel-studio-7
  [9]: http://docs.platformio.org/en/stable/ide/eclipse.html


message:
MEGA I2C and interrupts on 0,1

Looking at the pinout for the Arduino MEGA:

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

I see that Pins 20 and 21 can be both SDA and SCL or Interrupts 0 and 1.

If I'm using an [Adafruit I2C 16x2 RGB LCD Shield][2] connected to the SDA and SCL pins by the USB Jack, is there anything I can do in my code to still use INT0 and INT1 off Pins 20 and 21 for a different purpose?

  [1]: https://i.stack.imgur.com/bBUfz.png
  [2]: https://www.adafruit.com/product/716

body:
No, there is nothing you can do.

Both the SCL pins and both the SDA pins are physically connected together by copper tracks. They are in effect the same pin. If you use I2C you can't use INT0 or INT1. You have INT2 and INT3 though (pins 18 and 19), as well as Pin Change Interrupts on a large number of other pins.


message:
Why is Arduino Pro Mini not powering this LED?

First off, I'm very new to Arduinos and electronics in general, so feel free to explain like I'm 5.

As a bit of background to this question, the project is simply using a Pro Mini to run a servo, with a button to turn it on and off, and an led to indicate when it's on. To make sure I was getting the button right, I built the circuit on a breadboard with just the button and LED. The button was supposed to switch the LED on and off. It did not.

I removed the button from the equation and **just tried to power the LED with the Mini. No go.**

It's a **blue LED**, so the **resistor (100)** was chosen **assuming a forward voltage of 3.3V and current of .02A**. **I've tested the resistor and LED combo** with JUST the battery pack, and it lights up bright like it should.

I have a **9V battery running into RAW** (I've also tried a 6V pack). I had **pin 2 as an output with digitalWrite(HIGH)**, running into the resistor, then into the LED (+, long end), and then back to a ground pin. I've tried other ground pins on the board to make sure it's not that. **I've switched pin 2 to analogWrite(255)**, still nothing. **I have tried connecting it to VCC** instead. Nothing.

However, **writing HIGH to the onboard LED works fine**, so I can see that the sketch is indeed running.

**I've verified the LED polarity. I have tried a different Pro Mini**. Nothing. It's a **Pro Mini 328P** according to the stamp on the back, which **Google says runs at 5V and 16 MHz**.

Please tell me what stupid mistake I am making so I can stop wanting to rip my hair out. Thank you.

body:
This was my mistake. I had attached the Arduino to the breadboard by pushing in the provided pin strips, and then putting the mini on top of those, assuming that since the pin was through the hole and looked to be touching, a connection was made. It wasn't.

Rather than continue to mess around with fiddly connections, I just took the plunge and soldered the entire thing to a circuit board. The LED and the button work perfectly as expected, and now I just need to attach the servo.


message:
NodeMCU not responding AT after blink app

I've just bought NodeMCU LoLin ESP8266, I tried to send AT commands (after spending days on ESP8266-01) and everything was okay. Than I've uploaded the Blink example to the board, after that moment it's not responding to any command.

I tried to update firmware, it's updating successfully but nothing has changed. By the way blink app is not working also...

body:
If you replaced AT firmware in esp8266 with Blink and you want it back, download the AT firmware from [Espressif download page][1] and flash it with the [Espressif Flash Download Tool][2] (Windows) or with [esptool.py][3].

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


message:
C++ Adding Two 16 bit binary numbers together

I am trying to add two 16 digit binary numbers together. Each binary number will have been entered by the user and saved as: `int binaryOne[16] and int binaryTwo[16]`. Originally,

    int binaryOne[16] = {0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0};
    int binaryTwo[16] = {0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0};

are the values declared. Then, the user has the option to change these values using buttons that I implement before the Solution() function. So, once the used gets to the Solution() function, the numbers may be stored as:

    int binaryOne[16] = {0,0,0,0,0,0,0,0,0,1,0,0,0,0,0,1};
    int binaryTwo[16] = {0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,1};

This is what I have so far:

    void Solution() {
      /*
        Rule of binary addition:
        0 + 0 = 0
        1 + 0 = 1
        0 + 1 = 1
        1 + 1 = 1 and carry = 1
       */
       lcd.clear();
       lcd.setCursor(0,0);
       lcd.print("Solution");
       lcd.setCursor(0,2);

        int a[16] = binaryOne[16];
        int b[16] = binaryTwo[16];
        int i = 0;
        int remainder = 0;
        int sum[32];

        while(a[16] != 0 || b[16] != 0){
          sum[i++] = (a[16] % 10 + b[16] % 10 + remainder) % 2;
          remainder = (a[16] % 10 + b[16] % 10 + remainder) / 2;
          a[16] = a[16] /10;
          b[16] = b[16] / 10;
        }
        if(remainder != 0){
          sum[i++] = remainder;
        }
        i--;
        while(i>=0){
          lcd.print("%d", sum[i--]);
       }
       return 0;
    }

I believe I am doing something wrong with calling the arrays since I am renaming them to a[16] and b[16] within this function. I'm also curious, since I only have 16 bits of space on the screen, what if the user enters a binary number such as 1111111111111111 + 1000000000000000 and therefor there is going to be a carry on that first digit? Would it be best just to have an error message?

body:
You're making a mountain out of a molehill.

You're trying to manually manipulate binary digits in an array, but C can already manipulate binary digits. Everything is binary already - you just need to represent it as such.

All you need to do is convert the contents of your array into an actual number, then do simple mathematics on that number.  One of the simplest ways of doing that is to shift the bits into a variable:

For instance:

    int binaryOne[16] = {0,0,0,0,0,0,0,0,0,1,0,0,0,0,0,1};
    int binaryTwo[16] = {0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,1};

    uint16_t binOne = 0;
    uint16_t binTwo = 0;

    for (int i = 0; i < 16; i++) {
        binOne <<= 1;
        binOne |= binaryOne[i];
        binTwo <<= 1;
        binTwo |= binaryTwo[i];
    }

Now you can add them together, since they're just numbers:

    uint32_t result = binOne + binTwo;

And you can output it as binary:

    Serial.println(result, BIN);

If you want to convert back into an array again (why?!) you can just do the opposite as before:

    bool resultBin[32];

    for (int i = 0; i < 32; i++) {
        resultBin[i] = (result & (1 << (31-i))) ? 1 : 0;
    }


body:
A few issues here:

1. The way you “rename” the arrays is wrong, and furthermore there is no
   point in doing such renaming.
2. There is no reason to divide by 10 (ten, in decimal) within your
   code: as everything you do is binary, the number _ten_ has nothing to
   do with what are trying to accomplish.
3. While doing the addition, you forgot to _loop_ over the bits.
4. You shouldn't `return 0` in a function of type `void`. In fact, you
   shouldn't return any value.

Fixing those issues should give you something similar to this:

    void Solution() {
        lcd.clear();
        lcd.setCursor(0, 0);
        lcd.print("Solution");
        lcd.setCursor(0, 2);

        // Compute the sum.
        int sum[16];
        int remainder = 0;
        for (int i = 0; i < 16; i++) {
            int s = binaryOne[i] + binaryTwo[i] + remainder;
            sum[i] = s % 2;
            remainder = s / 2;
        }

        // Print it.
        for (int i = 15; i >= 0; i--) {
            lcd.print("%d", sum[i]);
        }
    }

Note that there is no point in computing a 32-bit result if you can only
print 16 bits: just accept that the computation is done modulo
216, just like a 16-bit ALU would do, or the `unsigned int`
data type in the Arduino.

Of course, the whole idea of doing the computation one bit at a time is
highly inefficient. See Majenko's answer for a more idiomatic and
efficient way of managing numbers bit-wise in C and C++.


message:
What is the use of 1k resistor shown in the picture and why it is used? Please check Arduino Uno Schematics for more info

[![Arduino Uno Schematics][1]][1]

Can anyone tell me why 1k resistor is used on pin 13 of ATmega16U2 in arduino uno schematics. I have also seen a 100k resistor used in this position?

  [1]: https://i.stack.imgur.com/494pj.png*

Link for schematics - https://www.arduino.cc/en/uploads/Main/Arduino_Uno_Rev3-schematic.pdf

body:
Its a pulldown resistor!

Comment there says "USB Boot Enable" so safe assumption that it's an digital pin.

They're handy because they mean if there is no input to whether that pin is headed, the voltage at the pin will be 0 instead of floating.

The value doesn't matter too much, "When in doubt 10k it out" is a pretty well known saying around electronics people, meaning just use a 10k Ohm resistor and you'll be fine.


body: Pin 13 of the USB interface chip is connected to RESET line of the ATMEGA328 MCU. I would guess (also from "USB boot En" label) that pressing/issuing board reset gives the USB interface an interrupt (INT7), such that USB bootloader gets activated and the ATMEGA328 can start loading firmware code over USB. The resistor is a pull-down resistor ensuring LOW signal, and its value shouldn't matter much. However, there is a capacitor (C5) which provides a short pulse to the interrupt line. This is not the best way to form a digital signal and initiate an interrupt, but the RC should be long enough, so I would expect that if 100k is used, the cap can be much smaller than 100n as in 1k case.


message:
Connect BotBoarduino with servos and Ultrasonic sensor HC-SR04

I am new to Arduino and I am making a Walking Quadruped using BotBoarduino as microcontroller.
I want to install an Ultrasonic Sensor HC-SR04 so that it will stop when an obstacle is detected.
I have connected the sensor to Arduino UNO. RX-TX of both the boards are cross-connected. Now I have written this code for UNO:

    const int trigPin = 9;
    const int echoPin = 10;
    // defines variables
    long duration;
    int distance;

    void setup() {
      pinMode(trigPin, OUTPUT); // Sets the trigPin as an Output
      pinMode(echoPin, INPUT); // Sets the echoPin as an Input
      Serial.begin(9600); // Starts the serial communication
    }

    void loop() {
      // Clears the trigPin
      digitalWrite(trigPin, LOW);
      delayMicroseconds(2);
      // Sets the trigPin on HIGH state for 10 micro seconds
      digitalWrite(trigPin, HIGH);
      delayMicroseconds(100);
      digitalWrite(trigPin, LOW);
      // Reads the echoPin, returns the sound wave travel time in microseconds
      duration = pulseIn(echoPin, HIGH);
      // Calculating the distance
      distance= duration*0.034/2;
      // Prints the distance on the Serial Monitor
      Serial.println(distance);

      delay(200);
    }

And I am doing this on BotBoarduino:

    int byteRead;

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

    void loop() {
      while (Serial.available())
      {
        byteRead = Serial.read();
      }

      if(byteRead >= 10)
      {
        walk();
      }
      else
      {
        stand();
      }
    }

Whenever distance = 10 or above, let it walk. Else stop.

But it's not working. It's not stopping on obstacles. Sensor is doing its work perfectly, but I think Botboarduino is not getting the values.

Any idea guyz?

body:
You have a misconception, how the Serial interface works.

The Serial interface is basically a stream of bytes (and sometimes start/stop and parity bits, which you normally don't care about) without any structure. This has to be implemented by you.

Also you have to understand, that you don't and cannot know, when a specific byte actually is being send. The fact that you typed a complete string into the serial monitor (or send a string via one call for `Serial.println()`) does NOT mean, that they are transmitted as a complete packet. The bytes of the string are send one after another and there may be a short delay between two arbitrary bytes. So with your reading `while()` loop, you are reading bytes until there is a delay long enough for the microcontroller to notice or until the message is send complete. You cannot know, which is the case for this very specific transaction. Also it seems odd, that you are only using the last read byte in your code, since the variable `byteRead` is overwritten on every `while()` loop cycle.

Then there is the format, in which you can send data through Serial.

 1. **Binary data:** Since it is a byte stream, you can directly use the binary values of the bytes to reflect the data. This is easy and good for cases, in which only one value of the size of one byte is transfered every time. So there is no need to distinguish between different parts of the message. In this case you have to use `Serial.write()` on your sending end. This will write binary data. (You will not be able to see the values in your serial monitor, since it is displaying only ASCII-encoded characters).
 2. **ASCII-encoded data string:** You are using `Serial.println()`, which sends an ASCII-encoded string representing the data followed by a NEWLINE character ('\n'). In case of the value `10` you are currently sending 3 bytes: '1', '0', '\n'. In this method, you are using a delimiter character (in this case '\n') to mark the end of a message. On the receiving end you have to read all bytes into a buffer, until you are receiving the delimiter character. Then you can process the message as a whole. In your case you would convert the ASCII-encoded string into an integer variable (for example with the function `atoi()`)

To exactly explain, what is happening with your code: As Chad wrote in his comment, you are trying to use the binary value of a byte, that is an ASCII-encoded character. When looking at an ASCII table, you can see, that there is no printable character with a binary value under 10. So, since you send only printable characters with `Serial.println()`, There will never be a value, that is under 10.

So now you have 2 options:

 1. Send the variable as binary data in one (!!!) byte (since you are not using distances as big as 255cm the value can fit in there; just make sure, that the byte variable does not roll over) and use every read byte on the receiving end for your code.
 2. Send the variable as ASCII-encoded data with `Serial.println()` and do the correct processing of the resulting message on the receiving end. Refer to the Serial examples in the Arduino IDE for this. You can directly integrate their code into yours.


message:
How to compile Arduino ESP8266/32 on CI/CD (CLI shell cmd) platform?

Like make for not ESP Arduino target, is there a CLI command like **esptool.py** to upload in the hardware ?

I've seen [**makeEspArduino**](https://github.com/plerup/makeEspArduino) but seems to be not trivial ?

What about [**espressif ESP32** component](https://github.com/espressif/arduino-esp32/blob/master/docs/esp-idf_component.md) ?

Is [**Visual Micro** Arduino CLI (Command Line Interface)](http://www.visualmicro.com/page/Visual-Micro-Command-Line-Interface.aspx) tool mature ?

body:
Easiest answer: Use [PlatformIO][1]. (Yes this answer is technically an advertisement, but it *is* the correct solution here.).

*Why not the others?*

* `makeEspArduino` is dependent on GNU `make`, hard to make modification to, hard to get support for when something goes wrong
* Visual Micro Arduino is Visual Studio extension, thus native to Windows

*Why PlatformIO?*

On the other hand, PIO is just a framework written in python2, runs on Windows, Mac & Linux alike and supports tons of boards and frameworks. Not only is it OS-agnostic but it also IDE agnostic. It exports project files for Eclipse, Visual Studio Code, CLion, Visual Studio, Sublime, Atom and other IDEs. The Arduino IDE will always be only a (bad) syntax highlighter.

Support boards (479 of them) range from Arduino Unos to ESP8266/ESP32 over to STM32 and nRF boards. It's also possible to compile one firmware for different environments (board), so with a well-written firmware, PIO can generate firmwares for multiple boards and frameworks alike. Frameworks include Arduino cores, ESP-IDF, STM32HAL and more.

To create a new project, you'd do

    user@somefolder/$ pio init --board=nodemcuv2 --ide=vscode

To compile from CLI, you just have to execute the `run` target:

    user@somefolder/$ pio run

To upload you'd just

    user@somefolder/$ pio run -t upload

With optional `--upload-port=/dev/ttyUSB0` or alike. Updating wirelessly over ArduinoOTA is also supported.

Video: https://www.youtube.com/watch?v=EIkGTwLOD7o

Documentation: http://docs.platformio.org/en/latest/

  [1]: https://platformio.org/


message:
how to send data to Adafruit Bluefruit Feather (32u4) over bluetooth?

Sup yo.

I have my Adafruit Bluefruit Feather all wired up.  It's lovely.  I've got it responding to commands over the USB serial, activating an array of octocouplers.  It's terrific.  Here's the thing though.  I need to talk to it wirelessly.

I can only pair it (MacOS) the Adafruit Bluefruit LE Connect app.  It doesn't show up in my Bluetooth preference pane.

`$ ls /dev/tty.*`  shows `/dev/tty.Bluetooth-Incoming-Port` and the Arduino IDE can see it.  Unfortunately the word *Incoming* is right there in the middle of that port name.  Sending commands through the Arduino serial monitor doesn't seem to do anything.

The Bluefruit connect app appears to be able to send commands over something called UART but my board doesn't respond to the stuff that works over USB serial.

How do I talk to this board over Bluetooth?

body:
First you should do some research on just what Bluetooth LE is.  First and foremost, what it is not, is a serial port.

In fact the BLE specification has no concept of serial ports, not like the old Bluetooth 2.x SPP specification.

Yes, you can use it *like* a serial port, but the point I am making is there is no GATT profile for serial data transfer. Every module manufacturer has their own way of doing it, so it's down to your application to implement that method (usually using libraries provided by the manufacturer). You can't present BLE as a serial port (COM3, /dev/rfcomm0 etc).

Sure, you could write a daemon that connects the MFG's custom method to a PTY and make it look more like a serial port (and such a thing may already exist in the community for some devices), but it will only ever work with that device and never any other device. There is no serial - there is only serial emulation and it's specific to the device. If it were standard no doubt someone would write a driver for it - like SPP of Bluetooth 2.x. But with GATT you just don't get that standard facility.

BLE is intended for sending short packets of data back and forth using minimal power. Many manufacturers have chosen to create a profile that can be used in a similar way to a serial port (in that you send data through a virtual "pipe"), however you require special software to interface with it. And, since there is no standard, and manufacturers just don't talk to each other, the software is specific to the device you are talking to.

If you are directly programming a BLE chip itself with your own firmware there is nothing to stop you from implementing your own protocol for serial data transfer and writing an application, driver, daemon, whatever, for communicating with that custom firmware. The same thing stands though: whoever wants to use it will require *your* specific application to communicate with it.

The only people who want to use BLE for serial are people like us. Everyone else (that's 99.999% of the market) uses it for what it is intended - connecting sensors and HID devices to mobile phones etc. That's why all the GATT profiles are for such things as heart rate, blood sugar levels, cycle speed, etc.

So no. You can't use it like a serial port. It's not a serial port. The only foolproof way (and the way to which I have resorted in the past) is to create a USB dongle that exposes a CDC/ACM interface to the computer, and contains a BLE module that is capable of communicating directly with a similar BLE module through its own proprietary profile (the one I use has a "transparent UART" mode when two modules are paired together). The MCU in the dongle then forwards data between the computer and the BLE module.


body:
The “UART” being referred to is the [Nordic UART GATT Service](https://learn.adafruit.com/adafruit-feather-32u4-bluefruit-le/uart-service). This is not a serial port or USB connection. It is a high level BLE protocol that *simulates* a serial port via the Bluetooth connection.

In order to connect to the device from your Mac you’ll need to write some C or Obj-C. I’ve done this for Windows, but not a Mac, so I’m afraid I can’t give you detailed instructions. However, [the source code for the iOS Adafruit Bluefruit LE Connect app](https://github.com/adafruit/Bluefruit_LE_Connect) you’re using is open source and should be a good starting point.

Be warned of a few things though.

 1. You’re going to have to learn a bit about the BLE protocols and standards. It’s not exactly for the faint of heart.
 2. Apple throttles the speed/throughput of BLE for their iOS devices (as does Android) to protect battery life. I don’t know if they apply the same throttling to their laptops. You may not be able to achieve a satisfying data rate if you’re looking to create a high throughput “data pipe”.  With Win10 and the Bluefruit LE I was able to achieve 40 bytes every 30ms. You’ll likely be limited to 20 every ~30ms.

    If you’re looking to just send some occasional text (maybe AT style) commands to the device via BLE though, you won’t come close to those limitations.


message:
Linking Mulitiple Arduino's

I have a project in which several Arduinos will be running independent programs. I would like to use an Arduino Mega as the main controller. It will receive input from a variety of switches, as well as data input from 2 Arduino Unos and 3 Arduino Nanos.

Each Nano will run a basic collection of switches and LED displays.

Each Arduino Uno will be connected to a 2 axis joystick and will have several button inputs from the joystick, as well as several 7 segment Led displays and several LED indicator displays.

The Mega would need to gather information of at least 16 bytes from each slave at highest possible speed, and be able to transfer at least 16 bytes to each slave at the same rate. I would also need the clock signal for all devices to default to the Mega.

What would be the best way to begin setting up the program logic to get these boards to interact in a smooth manner without a lot of lag in communication between boards?

Also, what would be the limitations on speed with this sort of com setup between the boards?

If more setup or function information is needed I can add description, just didn't want this post to be overly lengthy.

body:
Why do you need so many Arduinos, Nanos and a Mega?  You want to read/control 2 joysticks, some switches and some LED.  If you do this using a multi-processor environment then you are adding a significant overhead to the processing and the development time which you can probably do without.

So, could you connect everything to a Mega, do you have enough IO pins?  If not would the use of GPIO expander ICs, I2C devices, etc help solve this issue.

Connecting the joysticks via interrupts will allow a more responsive system, can you do this?

Is an Arduino even the best platform for this?  What about an ESP32 or PI?

You want to minimise the comms overhead, so a star network would be better than a ring.
Serial is going to be the lowest programming overhead solution, but by far the slowest.  Using WIFI via an ESP8266 is going to be the simpelist and you can hand off some of the processing to the ESP.


message:
Arduino Square Wave Phase Shift by 270 degrees

I am using this code to generate a square wave with Arduino and shift it by 90 and 180 degrees. However, this code is not able to shift it to 270 degrees. Could you please suggest how may I modify the code so that it supports a 270 degrees square wave phase shift operation.

    void setup() {
      pinMode( 9 , OUTPUT );    // Arduino Pin  9 = OCR1A
      pinMode( 10 , OUTPUT );   // Arduino Pin 10 = OCR1B
      // Both outputs in toggle mode
      TCCR1A = _BV( COM1A0 ) |_BV( COM1B0 );
      // CTC Waveform Generation Mode
      // TOP=ICR1
      // Note clock is left off for now
      TCCR1B = _BV( WGM13) | _BV( WGM12);
      OCR1A = 0;    // First output is the base, it always toggles at 0
    }
    // prescaler of 1 will get us 8MHz - 488Hz
    // User a higher prescaler for lower freqncies

    #define PRESCALER 1
    #define PRESCALER_BITS 0x01
    #define CLK 16000000UL    // Default clock speed is 16MHz on Arduino Uno

    // Output phase shifted wave forms on Arduino Pins 9 & 10
    // freq = freqnecy in Hertz (  122 < freq <8000000 )
    // shift = phase shift in degrees ( 0 <= shift < 180 )
    // Do do shifts 180-360 degrees, you could invert the OCR1B by doing an extra toggle using FOC
    /// Note phase shifts will be rounded down to the next neared possible value so the higher the frequency, the less phase shift resolution you get. At 8Mhz, you can only have 0 or 180 degrees because there are only 2 clock ticks per cycle.
    int setWaveforms( unsigned long freq , int shift ) {
      // This assumes prescaler = 1. For lower freqnecies, use a larger prescaler.
      unsigned long clocks_per_toggle = (CLK / freq) / 2;    // /2 becuase it takes 2 toggles to make a full wave
      ICR1 = clocks_per_toggle;
      unsigned long offset_clocks = (clocks_per_toggle * shift) / 180UL; // Do mult first to save precision
      OCR1B= offset_clocks;
      // Turn on timer now if is was not already on
      // Clock source = clkio/1 (no prescaling)
      // Note: you could use a prescaller here for lower freqnencies
      TCCR1B |= _BV( CS10 );
    }
    // Demo by cycling through some phase shifts at 50Khz
    void loop() {
      setWaveforms( 40000 , 0 );
      delay(1000);
      setWaveforms( 40000 , 90 );
      delay(1000);
      setWaveforms( 40000 , 180 );
      delay(1000);
    }

body:
The Arduino can only shift across a range of 180 degrees in CTC-mode using a 16 bit Timer. If you shift one channel to 90 degrees (other OCR set to 1, not zero) and then add a logic-inverter, you'll get the equivalent of 270 degrees as mentioned by Edgar Bonet.

As for using FOC (forced output compare), Edgar B. is again correct. It's possible to preset a channel as inverted, then perform the shift with an OCR set for 90 degrees -- you won't need an extra logic inverter. But this method is not for someone new. You'll want an O-Scope handy to make it work (and some time to study FOC and CTC mode-12).

I think it easier to use a single section from a 7404 hex-inverter to flip your 90 degree shifted waveform to 270.

Search for "Phase Shift Square Waves" and you'll find a VIDEO (as of 2022) for an example project that uses FOC tactics to create runtime-adjustable phase shifts on an Arduino. Perhaps you'll see a way to make an easy code change for the flipped-phase you want...

FWIW `stockvu`


message:
serial communication between arduino to 89c51 with gsm

I need to connect the 89c51 with Arduino UNO but same time I need to connect 89c51 microcontroller with Arduino without using serial reception and transmission pins of UNO b'coz that pins already engage with GSM module. plz, suggest me the program solution to serially receive data from 89c51 and send the message to gsm module.

body:
The Arduino Uno only has one (hardware) serial port. Since you need two, you have in principle two solutions:

- Use a software serial, this will work only for low speed transmissions. You can download this as a library.
- Use an Arduino (or other microcontroller) which has more than one hardware serial port, like the Arduino Mega which has 4.


message:
Help with my project on motors using the Arduino Board

I was given the task of being able to drive two motors in the forward direction, able to drive two motors in the reverse direction, and they must be able to drive each motor independently. I was wondering if anyone can give me directions, advice, or tips on the coding for this task. All I know is that:
if(switchState == HIGH){
digitalWrite(motorPin, HIGH);
}
else{
digitalWrite(motorPin, LOW);
}
}
I know this code makes the motor turn on and off with the high and low, but what type of code do I use to make it work at a certain speed, and to move independently?

body: you can use PWM function of digital pins (analogWrite())to control the motor speeds as desired.


message:
Sending dynamic data to webserver

I am trying to send data to a php file via http GET method.

I am able to send static data but I am unable to send dynamic data.

    #include <SoftwareSerial.h>
    SoftwareSerial gprsSerial(9, 10);

    char inchar;
    int ledPin = 13;
    int sensorPin = A0;
    int sensorValue = 0;

    boolean gs = true;
    boolean es = true;
    boolean ss = false;

    void setup()
    {
      gprsSerial.begin(9600);
      gprsSerial.println("AT+CNMI = 2,2,0,0");
      Serial.begin(9600);
    }
    void loop()
    {
       currentMillis = millis();
       if(gprsSerial.available()>0)
      {
        inchar = gprsSerial.read();
        if (inchar == '#')
        {
          delay(10);
          inchar = gprsSerial.read();
          if (inchar == '1')
          {
            Serial.println("System Enabled");
            ss = true;
            snd_msg(0);
          }
          else if (inchar == '0')
          {
            Serial.println("System Disabled");
            ss = false;
            snd_msg(1);
          }
          delay(10);
          inchar = gprsSerial.read();
          if (inchar == '1')
          {
            Serial.println("Geofence Enabled");
            gs = true;
            snd_msg(2);
          }
          else if (inchar == '0')
          {
            Serial.println("Geofence Disabled");
            gs = false;
            snd_msg(3);
          }
          delay(10);
        }
      }
        gprs();
        delay(10000);
    }

    void toSerial()
    {
      while(gprsSerial.available()!=0)
      {
        Serial.write(gprsSerial.read());
      }
    }
     void snd_msg(int a)
    {
      gprsSerial.println("AT+CMGF=1");    //Sets the GSM Module in Text Mode
      delay(1000);  // Delay of 1000 milli seconds or 1 second
      gprsSerial.println("AT+CMGS=\"+918148090646\"\r"); // Replace x with mobile number
      delay(1000);
      if ( a == 0)
      {
        gprsSerial.println("System Enabled");
      }
      else if ( a == 1)
      {
        gprsSerial.println("System Disabled");
      }
      else if ( a == 2)
      {
        gprsSerial.println("Geofence Enabled");
      }
      else if ( a == 3)
      {
        gprsSerial.println("Geofence Disabled");
      }
      delay(100);
       gprsSerial.println((char)26);// ASCII code of CTRL+Z
      delay(1000);
      gprsSerial.println("AT+CNMI = 2,2,0,0");
      delay(1000);
    }
    void vibra_sensor()
    {
      sensorValue = analogRead(sensorPin);
      Serial.println(sensorValue);
      for(int i = 0; i < 5; i++)
      {
      if (sensorValue > 500)
      {
        es = true;
        break;
      }
      else
        es = false;
      delay(500);
      }
      delay(1000);
    }
    void gprs()
    {
      vibra_sensor();
      Serial.println("Config SIM900...");
      delay(2000);
      Serial.println("Done!...");
      gprsSerial.flush();
      Serial.flush();

      // attach or detach from GPRS service
      gprsSerial.println("AT+CGATT?");
      delay(100);
      toSerial();

      // bearer settings
      gprsSerial.println("AT+SAPBR=3,1,\"CONTYPE\",\"GPRS\"");
      delay(2000);
      toSerial();

      // bearer settings
      gprsSerial.println("AT+SAPBR=3,1,\"APN\",\"www\"");
      delay(2000);
      toSerial();

      // bearer settings
      gprsSerial.println("AT+SAPBR=1,1");
      delay(2000);
      toSerial();
      // initialize http service
      gprsSerial.println("AT+HTTPINIT");
       delay(6000);
       toSerial();

       // set http param value
     **gprsSerial.println("AT+HTTPPARA=\"URL\",\"adnansait74.000webhostapp.com/operation.php?timestamp=02:50:00&latitude=11.374545&longitude=76.728986&gfence=OFF&estatus=OFF&sstatus=ON\"");**
       delay(5000);
       toSerial();

       // set http action type 0 = GET, 1 = POST, 2 = HEAD
       gprsSerial.println("AT+HTTPACTION=0");
       delay(6000);
       toSerial();

       // read server response
       gprsSerial.println("AT+HTTPREAD");
       delay(1000);
       toSerial();

       gprsSerial.println("");
       gprsSerial.println("AT+HTTPTERM");
       toSerial();
       delay(300);

       gprsSerial.println("");
       delay(10000);
       gprsSerial.println("AT+CNMI = 2,2,0,0");
      delay(1000);
    }

**What I've Tried**

1.) Saving URL in a string

    String URL = "adnansait74.000webhostapp.com/operation.php?timestamp=02:50:00&latitude=11.374545&longitude=76.728986&gfence=OFF&estatus=OFF&sstatus=";
        URL += ss;
        gprsSerial.println("AT+HTTPPARA=\"URL\",\"+URL\"");

Doesn't Work

2.)Attaching values using print statement

    gprsSerial.println("AT+HTTPPARA=\"URL\",\"adnansait74.000webhostapp.com/operation.php?timestamp=02:50:00&latitude=11.374545&longitude=76.728986&gfence=OFF&estatus=OFF&sstatus=");
    gprsSerial.println(ss+"\"");

3.)Entering value directly in URL

    gprsSerial.println("AT+HTTPPARA=\"URL\",\"adnansait74.000webhostapp.com/operation.php?timestamp=02:50:00&latitude=11.374545&longitude=76.728986&gfence=OFF&estatus=OFF&sstatus="+ss+"\");

**Error**

    invalid operands of types 'const char*' and 'const char [2]' to binary 'operator+'

I'm using an arduino uno and a sim 900a GSM module.

**QUESTION**

How do I send dynamic values for **gfence, sstatus, estatus**?

I am also using a messaging service, the code is included. **The help I need is in the gprs() function.**

The data I need to send is,

gfence from gs

sstatus from ss

estatus from es

body:
You should split it up:

    gprsSerial.print(F("AT+HTTPPARA=\"URL\",\"adnansait74.000webhostapp.com/operation.php?timestamp=02:50:00&latitude=11.374545&longitude=76.728986&gfence=OFF&estatus=OFF&sstatus="));
    gprsSerial.print(ss);
    gprsSerial.println(F("\""));

Note the use of `print` on each part up until the *last* part which is the only one that uses `println` in order to terminate the line.

Also note the use of the `F()` macro to reduce the wastage of RAM that string constants cause.


message:
Change RF Receiver Frequency by Antenna Length

This may be a very stupid question, but I have got me one of those cheap 433 MHz RF modules for the Arduino.
I'm wondering if I can vary the receiver's frequency by simply changing the length of the antenna? Or does the circuit limit the frequency band to 433 MHz?

Thanks in advance.

body: No, changing the antenna length will only change the resonant frequency of the antenna circuit. That is, it will affect the sensitivity of the receiver, but won't actually change the frequency that the receiver "listens" to.


message:
Powering an Arduino Uno using 2 (or as few as possible) AAA batteries

[Background] I'm constructing a water bottle rocket which is going to use apogee detection and a mechanism for the parachute release.

Connected to the Uno will be an accelerometer and a servo, now due to the need to minimise the dry mass of the rocket I want to use as few and as light batteries as feasible. Would it be possible to power this setup with 2 AAAs? If not how many would be necessary? Would other types of Arduino such as a micro work on fewer batteries?

Thanks for the help

body:
I've got [a page about power saving](http://www.gammon.com.au/power).

My first suggestion would be to not use a Uno, which is quite heavy (because of its size) but a smaller Arduino like a Mini. Second, I think you'll find that LiPo batteries are quite light, and come in various sizes (and thus, weights). A single cell will output around 3.7V which is fine for driving an Atmega328P. Possibly you could drop the clock to 8 MHz because of the voltage.

If you don't need it to be "awake" all the time consider using the techniques described in my link above to make it sleep for (say) 4 seconds at a time and then take a measurement.


message:
Parsing HTTP get response to extract values

Basically I created a web page to control 4 channel relay, then I made an HTTP get request from that page and got the following response:

    Linked

    T+CIPSEND=4,50

    > GET /ard/sensor.html HTTP/1.1
    Host: localho
    SEND OK

    +IPD,4,351:HTTP/1.1 200 OK
    Date: Sat, 07 Apr 2018 01:22:58 GMT
    Server: Apache/2.4.9 (Win32) PHP/5.5.12
    Last-Modified: Sat, 07 Apr 2018 01:17:13 GMT
    ETag: "72-56937eec1c277"
    Accept-Ranges: bytes
    Content-Length: 114
    Content-Type: text/html

    <p> Relay1 = 1#  </p> </br>
    <p> Relay2 = 0#  </p> </br>
    <p> Relay3 = 0#  </p> </br>
    <p> Relay4 = 1#  </p> </br>
    OK

    OK
    Unlink

Now I want to store Relay1 status (which is 1 here) in a variable, also all other Relays in order to control them high or low
Note : # is supposed to be the separator
and here is my code:

        #include <SoftwareSerial.h>

    const int LED_PIN = 13;

    String ssid = "ABC";
    String password = "a14102016a";
    const byte rxPin = 6;
    const byte txPin = 7;

    SoftwareSerial ESP8266 (rxPin, txPin);

    unsigned long lastTimeMillis = 0;

    void setup() {

      Serial.begin(9600);
      ESP8266.begin(9600);
      reset();
      connectWifi();
      delay(2000);
    }

    //reset the esp8266 module

    void reset() {

      ESP8266.println("AT+RST");
      ESP8266.println("AT+CIOBAUD=9600");
      delay(1000);

      if (ESP8266.find("OK") ) Serial.println("Module Reset");

    }

    //connect to your wifi network
    void connectWifi() {

      String cmd = "AT+CWJAP=\"" + ssid + "\",\"" + password + "\"";
      ESP8266.println(cmd);

      delay(4000);

      if (ESP8266.find("OK")) {

        Serial.println("Connected!");

      }

      else {

        connectWifi();

        Serial.println("connect to wifi");
      }

    }

    void printResponse() {
      while (ESP8266.available()) {
        Serial.println(ESP8266.readStringUntil('\n'));
      }
    }

    void loop() {

      if (millis() - lastTimeMillis > 30000) {
        lastTimeMillis = millis();

        ESP8266.println("AT+CIPMUX=1");
        delay(1000);
        printResponse();

        ESP8266.println("AT+CIPSTART=4,\"TCP\",\"192.168.1.161\",80");
        delay(1000);
        printResponse();

        String cmd = "GET /ard/sensor.html HTTP/1.1\r\nHost: localhost";
        ESP8266.println("AT+CIPSEND=4," + String(cmd.length() + 4));
        delay(1000);

        ESP8266.println(cmd);
        delay(1000);
        ESP8266.println("");
      }
      if (ESP8266.available()) {
        Serial.write(ESP8266.read());

    Byte R[ ] = ESP8266.read () ;
    Serial write (R[ ]);

    //    if (readString.indexOf("Relay1=1">0))
    {
        Serial.write("found");
    }
      }

    }

Any suggestions ?

body:
First of all, I would avoid using the `String` class, because of the
memory fragmentation issues that come with it. The most obvious solution
is probably to store the result in a character array, then parse the
array, with `strstr()` or `sscanf()`, to extract the values you want.
However, this requires storing the whole response in RAM, which is
expensive. A better option is to parse the string as it comes, character
by character, using a kind of finite state machine.

Here is how I would do it. First, I assume you know what you want to do
with these values. Since I don't, I will instead use this dummy function
to just print the values out to the serial port:

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

    static void parse_relay_callback(uint8_t index, uint8_t value)
    {
        Serial.print("parsed: relay ");
        Serial.print(index);
        Serial.print(": ");
        Serial.println(value);
    }

You will have to replace this with whatever is appropriate for your
application.

Then here is the parser:

    static void parse_relay(char c)
    {
        static const char templ[] = "RelayI = V#"; // I: index, V: value
        static uint8_t pos, index, value;
        char expected = templ[pos++];
        if (expected == 'I' && c >= '0' && c <= '4')
            index = c - '0';
        else if (expected == 'V' && (c == '0' || c == '1'))
            value = c - '0';
        else if (expected == '#' && c == '#')
            parse_relay_callback(index, value);
        else if (c != expected)
            pos = 0;
    }

You just feed it one character at a time, with something like:

    while (ESP8266.available())
        parse_relay(ESP8266.read());

Feeding the parser with your response example gives the following on the
serial port:

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

    parsed: relay 1: 1
    parsed: relay 2: 0
    parsed: relay 3: 0
    parsed: relay 4: 1


message:
Reading data from potentiometer with MISO and MOSI on same pin

I am working with the MCP4131 Digital Potentiometer and I am running into some trouble. The MISO and MOSI functionalities are multiplexed onto the same pin. Obviously, this means that I have to have Pin 13 and 12 hooked into the same pin on the chip.

I want to read send a READ command to the chip so that I can get the current value of the POT; however, when I send the lower byte in order to retrieve the value, I simply am getting back whatever I send because pins 13 and 12 are hooked into the same spot.

Is there any examples on how to work with a module such as the MCP4131 where the MISO and MOSI are on the same pin? Thank you!

body:
You need to do a little conversion:

* Connect the SDI/SDO line to MISO on the Arduino.
* Connect a 1kΩ resistor between MISO and MOSI on the Arduino.

Then you first send the command byte(s) to the slave. You will receive these back, but you can just ignore them.

Then you receive the data. You do this by sending 0xFF for each byte. The 1kΩ resistor means the slave can override the 0xFF from the MOSI. The MOSI -> MISO resistor effectively becomes a pullup resistor and is, to all intents and purposes, ignored (it's just in parallel to the pullup resistor internal to the slave).


message:
What is the tool to send file to SPIFSS on ESP8266/32?

Is there good tools (IDE, CLI or IDE addon) to send file via USB port to SPIFSS internal espressif ESP hardware SoC ?

body:
The [mkspiffs][1] tool creates bin from file system data (or extracts data from bin).

SPIFFS bin is uploaded with esptool over USB or with espota over WiFi. It can be uploaded with the sketch binary in one command.

Example:

    esptool.py -p /dev/ttyUSB0 write_flash 0x0 sketch.bin 0x300000 spiffs.bin

[The IDE plugin][2] adds SPIFFS upload to Arduino IDE Tools menu.

  [1]: https://github.com/igrr/mkspiffs
  [2]: https://github.com/esp8266/arduino-esp8266fs-plugin/blob/master/README.md


message:
How to write Arduino API code in VL53L1X?

I'm trying write code for the VL53L1X on Arduino,  but I didn't get the VL53L1X registers. How to access them and how to measure the data in VL53L1X? Can anyone help me?

body:
He's not asking about a VL53L1X Arduino. He's asking for code to support the VL53L1X (which is an ST distance sensor) that runs on an arduino.

ST have provided a library, but it's huge with many large buffers and doesn't run on an arduino as distributed. They've also forbidden anonymous distribution of a corrected version, presumably because they don't want to make it easy to run on 16-bit processors. It might run easily on a Teensy 3.

Sparkfun have just released a library. It's much smaller but, like the Polulu library for the  VL53L0X, it's full of magic numbers where they've stripped the structure out and just write the end result into the registers - so it will be difficult to get the best from the sensors.

https://github.com/sparkfun/SparkFun_VL53L1X_Arduino_Library/blob/master/src/SparkFun_VL53L1X_Arduino_Library.cpp

There is a good case for writing something halfway : without the overcomplicated code typical of ST's Cube environment but with a bit more content than Sparkfun's version.

It's a boring job unless you have something you need from it. Worthwhile only if you have a good case to support it on AVR. If you try to build the ST sources, look carefully at the maximum write size on I2C (135 bytes) and compile with maximum warnings enable (it will pick up several 16/32 bit wordsize errors, mostly critical).


message:
Can external power supply above current limit lead to errors/shutdown arduino?

- I have an Arduino Due that is connected both over native USB to PC and a 12v power supply in the Jack.

- Mounted on the Arduino I have a custom PCB that drives 3 motor drivers. The Motor drivers are powered via the arduinos VIN Pin with 12v.

As Ive read elsewhere the arduino automatically chooses the 12v powersupply in this case. My question is: If the 3 motor drivers exceed the 1amp that the powersupply can supply, will the arduino encounter errors/shutdown or automatically switch back to USB for power supply?

If so, is there a way I can force the arduino to take the USB 5v even though 12v are connected through the Jack?

Also, how much current can I safely drive through the VIN Pin?

Thanks!

body:
If the incoming voltage drops below 6.6V the MOSFET will activate for the USB power and that will become available. But it's not perfect.

The MOSFET is always "partially" active - that is, the "body diode" is always available, so if the 5V rail drops below the USB voltage minus the forward voltage of that body diode the USB power will take over regardless of what else is happening. That 5V rail then feeds the 3.3V regulator, and
since the ARM chip on the Due is a 3.3V chip, even a dip of a volt or so on the 5V rail should have no effect on the MCU.

So theoretically the chip should keep running fine all the time regardless of what happens with the power.

> Is there a way I can force the arduino to take the USB 5v even though 12v are connected through the Jack?

Not really, no.  You can remove the 12V from the jack though and just power from USB. Connect the 12V to your motor drivers, and link its ground to the Arduino ground. The motors will use the 12V supply, and the Arduino the 5V supply.

> Also, how much current can I safely drive through the VIN Pin?

The diode inline with the barrel jack is rated at a maximum sustained current of 1A. Any more than that and you risk blowing that diode.


message:
LMT01 temperature sensor code does not run - need help

Apr 06, 2018, 09:52 pm
I hope this is appropriate.  I posted this question on the Arduino/Sensor site, got 42 views, but no reply.
-----------------------------------
I had no success getting help with any earlier post on this subject, so I am starting over with new code by Kevan Darrah. He is a good  programmer, so the code should work, but it doesn't.  I did a lot of reading and I understand how it should work, so let me spend few words explaining what I learned and maybe someone can take it from there. The LMT01 output is 0.6V to 1.6V pulses 10 usec wide, I verified this using a scope, the total number of theses pulses is proportional to the temperature. This repeats every 100 msec.  This signal is input to pin D2, but that is a digital pin: High=5V, Low= 0V, but Arduino IDE does something sneaky when you use the special function "attachInterrupt(pin,ISR,Falling)" - It redirects the signal internally to pin A0N of the positive side of an Analog Comparator, and attaches to AN1 internally a stable reference voltage of 1.1V. Now the 0.6V to 1.6V pulses are exactly centered on the comparator so it puts out a perfect 1's and 0's for easy counting.
So to repeat myself only Pin2 is attached with the LMT01 to the Arduino. Why doesn't this  &!#^-thing work, it compiled and uploaded correctly.  If I had  a debugger on this software, moving one line at a time I could fix it myself.  Code follows:
------------------------------------------------------------------------

     //Sample Code for LMT01 Temperature Sensor
    //LMT01ELPGQ1
    //Kevin Darrah

    //TempPins
    #define pulsePin 2 //D2 on arduino D5 on esp8266 **This is the output from the LMT01

    //globals for the LMT01 temp sensor
    volatile unsigned int pulseCount = 0;//pulses out of the sensor
    float temperatureC = 0, temperatureF = 0;//converted temperatures
    float tempHIGH, tempLOW = 1000;

    //functions
    void pulseDetect();//interrupt function
    float getTemperature();//call this to get temperature from the LMT01 - returns a float for the temperature in (C)

    void setup() {
      Serial.begin(115200);
      pinMode(pulsePin, INPUT);//output from LMT01 sensor circuit

    }

    void loop() {
      temperatureC = getTemperature();// call getTemperature() to return temp in C
      if (temperatureC != 1000) {//returns 1000 if anything went wrong
        temperatureF = temperatureC * 9.000 / 5.000 + 32;
        if (temperatureF > tempHIGH)
          tempHIGH = temperatureF;
        if (temperatureF < tempLOW)
          tempLOW = temperatureF;
        Serial.print(temperatureC);
        Serial.print("C  ");
        Serial.print(temperatureF);
        Serial.print("F  HIGH=");
        Serial.print(tempHIGH);
        Serial.print("F  LOW=");
        Serial.print(tempLOW);
        Serial.print("F  DIFF=");
        Serial.print(tempHIGH - tempLOW);
        Serial.print("F  ");
        Serial.print(pulseCount);
        Serial.println("pulses  ");
        for (int i = 0; i < random(50, 200); i++)
          delay(1);
      }

    }

    float getTemperature() {// *********  GET TEMPERATURE FUNCTION *** returns the temperature C
      attachInterrupt(digitalPinToInterrupt(pulsePin), pulseDetect, FALLING);//using interrupt pin tp trigger on falling edge

      unsigned long conversionStartTime = millis();//keeps track of timing

      while (millis() - conversionStartTime < 10) { //looking for silence, in case we go to read temperature mid-measurement, ride it out till next one
       // yield();//for the ESP8266 to keep other tasks happy
        if (pulseCount > 0) {
          pulseCount = 0;
          conversionStartTime = millis();
        }
      }

      pulseCount = 0;//reset pulse count
      while (millis() - conversionStartTime < 150) {//wait for first pulse
       // yield();//for the ESP8266 to keep other tasks happy
        if (pulseCount > 0)
          break;
      }
      if (pulseCount == 0)
        return 1000;//FAIL - never got a pulse

      conversionStartTime = millis();//conversion done, so reset time
      unsigned int oldPulseCount = pulseCount;//just to help keep track of timings when pulse pin goes idle
      unsigned long pulseTime = millis();
      while (millis() - conversionStartTime < 60) { //measure pulses
       // yield();//for the ESP8266 to keep other tasks happy

        if (pulseCount != oldPulseCount) {//new pulse, so update timer
          oldPulseCount = pulseCount;
          pulseTime = millis();
        }
        else if (millis() - pulseTime > 5) {//no pulses for a while, must be done.
          break;
        }
      }
      //^^^ Stays stuck here counting pulese for 60ms

      if (pulseCount < 5) { //this is just noise, false trigger... I mean only 5 pulses, that can't be right
        return 1000;//FAIL
      }

      detachInterrupt(digitalPinToInterrupt(pulsePin));//done with the interrupt
      temperatureC = 256.000 * pulseCount / 4096.000 - 50;//conversion
      //see 7.3.2 Output Transfer Function in Datasheet

      return temperatureC;//throw the temp back
    }

    //change this function to look like this if using the ESP8266
    //void ICACHE_RAM_ATTR pulseDetect()

    void pulseDetect() {// *********  PULSE COUNTER INTERRUPT FUNCTION
      pulseCount++;
    }

body:
This is added 15 months after the OP but there is very little information on this sensor.

You have not included your schematics which would be useful. For this setup TI gives you four options: transistor level shifting, isolation, multiple devices to one MCU pin, and common ground with high-side signal. Kevin Darrah uses the transistor level shifting method in his videos. Please refer to the [TI datasheet][1] for connections, pages 3 and 21 are relevant in setting that up. There is also [this sample code][2] supplied with a video that shows setup using the comparator.

NOTE: Ensure you do not have your sensor reverse biased or it will not work and may wreck it. Diodes are a good idea here.

Try commenting this out:

    if (pulseCount < 5) { //this is just noise, false trigger... I mean only 5 pulses, that can't be right
    return 1000;//FAIL
  }

I found this sensor gives very low pulse readings if you have something setup incorrectly which will come out around -50C and this line may be causing it to read a fail. If that is the case you will need to rewrite the getTemperature() function, possibly using the comparator method supplied by TI which will require you to rewire, see their training code which includes a video. TI notes the first couple of readings may be incorrect. In my code I have my function perform several throwaway tests before spitting out a reading.

TL;DR If you use the TI comparator method, you can use the digital pins for power instead of the +5VDC like they do but use a diode (needed also for multiple sensors) to isolate the sensor to prevent reverse bias. If you do this you can shut the sensor off by switching it to INPUT but be aware, OUTPUT mode goes to ground by default which can cause reverse bias and fry your sensor. Use digitalWrite(pin,HIGH) prior to switching to OUTPUT to change default behaviour to +5V rather than GND (true, the diode should protect you here but adding this line is necessary anyway so do it in this order, safety first). I needed multiple sensors in my build so this is what I found, I used the Arduino-based comparator method quite successfully.

I don't have the necessary components to connect with transistor level shifting and actually test this at the moment but you could try this code if you want. I trimmed it down, eliminated most of the ESP8266 stuff you weren't using anyway and modified the getTemperature function to resemble what I have working right now.

    //Sample Code for LMT01 Temperature Sensor
    //LMT01ELPGQ1
    //Kevin Darrah
    // Ben Nesbitt, 2019

    // For LMT01 if using transistor method of connection

    //TempPins
    #define pulsePin 2 //D2 on arduino  **This is the output from the LMT01

    //globals for the LMT01 temp sensor
    volatile unsigned int pulseCount = 0;//pulses out of the sensor
    float tempC = 0;//converted temperatures
    float tempHigh = 151;
    float tempLow = 151;
    unsigned long timeMillis = millis();

    //functions
    void pulseDetect();//interrupt function

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

      pinMode(pulsePin, INPUT);//output from LMT01 sensor circuit

    }

    void loop() {
      timeMillis = millis();
      tempC = getTemp(pulsePin);// return temp in C

      Serial.print(tempC); Serial.print("C  ");
      Serial.print(pulseCount); Serial.println("pulses  ");

      while (millis() - timeMillis < 5000) {} // Change this for how often you want to sample the temperature.

    }

    float getTemp(int pin)
    {
      attachInterrupt(digitalPinToInterrupt(pin), pulseDetect, FALLING);//using interrupt pin tp trigger on falling edge
      float temperature = 0;
      unsigned long timeMillis = millis();//keeps track of timing
      int counterRef = 0; // Pulse count reference

      while (millis() - timeMillis < 10) { //looking for silence, in case we go to read temperature mid-measurement, ride it out till next one
        if (pulseCount > 0) {
          pulseCount = 0;
          timeMillis = millis();
        }
      }

      pulseCount = 0;//reset pulse count
      for (int i = 0; i < 3; i++)
      {
        while(pulseCount < 1) {}  //* TI recommends aborting the first one or two tests as inaccurate

        if(pulseCount != 0){
          //Wait for counting to be complete
          counterRef = 0;
          while(pulseCount != counterRef)
          {
            counterRef = pulseCount;
            timeMillis = millis();
            while (timeMillis == millis()){}
          }
          if (i < 2)
          {
            pulseCount = 0;
          }
          else
          {
             temperature = 0.0625 * pulseCount -50; // Pulses to temperature conversion
          }
        }
      }

      detachInterrupt(digitalPinToInterrupt(pin));//done with the interrupt

      //see 7.3.2 Output Transfer Function in Datasheet

      return temperature;
    }

    void pulseDetect() {// *********  PULSE COUNTER INTERRUPT FUNCTION
      pulseCount++;
    }

  [1]: https://www.ti.com/lit/ds/symlink/lmt01.pdf
  [2]: https://training.ti.com/how-interface-lmt01-temperature-sensor-arduino


message:
How do I get a nonzero output from my HX711 and load cell?

I am trying to set up a load cell using the HX711 amplifier. Whenever I upload my sketch, my serial monitor only will read zeros regardless of load applied to the sensor (no signal appears to be sending from my load cell).

Here is my wiring, with the Arduino Uno connected to a COM port. I am using an Arduino Uno, HX711, and Sparkfun's TAL220 Straight Bar 10kg load cell.

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

Here is the calibration sketch I am using (from the HX711 hookup guide):

    #include <HX711.h>

    #define DOUT 9
    #define CLK 8

    HX711 scale(DOUT, CLK);

    float calibration_factor = 282650; //-7050 worked for my 440lb max scale setup

    void setup() {
      Serial.begin(9600);
      Serial.println("HX711 calibration sketch");
      Serial.println("Remove all weight from scale");
      Serial.println("After readings begin, place known weight on scale");
      Serial.println("Press + or a to increase calibration factor");
      Serial.println("Press - or z to decrease calibration factor");

      scale.set_scale();
      scale.tare(); //Reset the scale to 0

      long zero_factor = scale.read_average(); //Get a baseline reading
      Serial.print("Zero factor: "); //This can be used to remove the need to tare the scale. Useful in permanent scale projects.
      Serial.println(zero_factor);
    }

    void loop() {

      scale.set_scale(calibration_factor); //Adjust to this calibration factor

      Serial.print("Reading: ");
      Serial.print(scale.get_units(), 1);
      Serial.print(" kgs"); //Change this to kg and re-adjust the calibration factor if you follow SI units like a sane person
      Serial.print(" calibration_factor: ");
      Serial.print(calibration_factor);
      Serial.println();

      if(Serial.available())
      {
        char temp = Serial.read();
        if(temp == '+' || temp == 'a')
          calibration_factor += 10;
        else if(temp == '-' || temp == 'z')
          calibration_factor -= 10;
      }
    }

And here is a typical output from the serial monitor (I previously had this load cell functioning correctly, which is why my calibration factor is so different).

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

Observations:

 - Whenever I upload the sketch and open the serial monitor, the TX LED on my Arduino Uno will light up flashing, but the RX LED stays off.
 - Removing the scale.tare() step will output a constant nonzero value, but the load cell is unaffected by any loading:

[![image description][3]][3]

 - I have tried adding an external power supply to the hookup assembly (I don't know if this is even necessary, but I know the load cell requires excitation to function, so I thought I'd give it a try). So far it has not changed the output in any way.
 - I have also tried adjusting the calibration factor, which only offsets the constant value outputted.
 - I have re-soldered the connecting wires to the load cell and replaced the remaining wires, as well as tried multiple Uno Boards and a new USB cord. I have also gone over my wiring and had my labmate check it too (though I will definitely not rule out it being some small wiring/hardware mistake on my part, as I am still very new to Arduino).

Thank you for any suggestions!

  [1]: https://i.stack.imgur.com/Dasf8.png
  [2]: https://i.stack.imgur.com/WVEOpm.png
  [3]: https://i.stack.imgur.com/ibTqNm.png

body: The zero factor 8388607 showed up in a similar question on another forum and is associated with the range of the HX711 amplifier. This indicated that my amplifier was broken; I have since replaced it and am now receiving a signal from the load cell.


message:
Comparing custom variable type definitions

In a library I am using with an OBD adapter, they define a public function to get the state of the OBD connection using some strange (and, in my opinion, useless) custom defined variable type:

    // states
    typedef enum {
        OBD_DISCONNECTED = 0,
        OBD_CONNECTING = 1,
        OBD_CONNECTED = 2,
        OBD_FAILED = 3
    } OBD_STATES;

    ...

    // get connection state
    virtual OBD_STATES getState() {
          return m_state;
    }

How can I get the state into a variable such as `boolean isConnected` or `int state` so it can interact with the rest of my code? I have tried the following with no luck:

    boolean isConnected = obd.getState() == OBD_CONNECTED;
    if(isConnected) { ... }

    int state = (int) obd.getState();
    if(state == 2) { ...}

body:
I found the answer to my problem, but it is not very convenient.

    Serial.write("ODB State: ");
    OBD_STATES state = obd.getState();
    if(state == OBD_DISCONNECTED) Serial.write("Disconnected");
    if(state == OBD_CONNECTING) Serial.write("Connecting");
    if(state == OBD_CONNECTED) Serial.write("Connected");
    if(state == OBD_FAILED) Serial.write("Failed");
    Serial.write("\n");


body:
In response to your answer: why don't you think it is convenient? As you already noticed, you can use the enum values directly in your sketch.

Anyway, it is better to use a switch statement:

    Serial.write("ODB State: ");
    switch (odb.getState()) {
      case ODB_DISCONNECTED:
        Serial.write("Disconnected");
        break;

      case OBD_CONNECTING:
        Serial.write("Connecting");
        break;

      case OBD_CONNECTED:
        Serial.write("Connected");
        break;

      case OBD_FAILED:
        Serial.write("Failed");
        break;

      default:
        // Error case
        break;
    }
    Serial.write("\n");

This way, whenever the enum is changed (e.g. added items), you automatically fall into the error state, so you know you have to adapter the code.


message:
How to control a DSP-G1 programmatically/electronically?

I want to generate music/sounds for a video game I am making with my son (using an Arduino Mega and a 240x320 LCD graphical display). I have a basic understanding of the MIDI protocol. I've been a computer programmer for over 30 years. I read the MIDI implementation in the [DSP-G1](https://cdn-shop.adafruit.com/product-files/2400/2400.pdf) manual, but I don't understand how to go from this to sending the right signals from the dev board to the chip pins.

Everything I find is about connecting a physical MIDI device. Can anyone possibly provide or point me to information on how to control the [DSP-G1](https://www.adafruit.com/product/2400) programmatically/electronically? I think I need some hardware or software to serialize MIDI protocol bytes into a sequence of voltage changes, but all my searching leads me to info about a physical device.

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

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

body:
The purpose of the MIDI output circuit is to convert the TTL signal into a 5 mA current.
The purpose of the MIDI input circuit is to convert the current back into a TTL signal.

If the Arduino and the DSP-G1 are part of the same circuit (and share the ground), you can omit these conversions, and connect the Arduino's TX directly to the LPC810's RX, without any other components needed. (The LPC810 requires a 3.3 V power supply, but its RX pin is 5 V tolerant.)

MIDI was designed to work with most microcontrollers, so it uses standard UART signals at 31250 baud. The only configuration you need is:

    Serial.begin(31250);


message:
Most compact way to power 5V Arduino boards?

So I have quite a few ideas for wearable devices using Arduino boards (mainly the Nano and the Micro clones). With that in mind, I want to determine what the best way to power an Arduino is, with compactness in mind (and cost too, of course). One single button cell battery does not supply enough power to the Arduino to power it properly. I can use [these 2x button cell battery holders (6v)][1] but they mainly ship only from China and, for some reason, are relatively expensive ($15 for 6 of them).

Does anyone know of a better and cheaper way of powering these Arduino boards, with wear-ability in mind?

Thanks! :)

  [1]: https://i.ebayimg.com/images/g/6HEAAOxyeglTXeyb/s-l1600.jpg

body:
I made a [torch locator](http://www.gammon.com.au/forum/?id=12769) which looks like this:

[![Torch locator][1]][1]

That was powered by a single button cell. The actual processor is an ATtiny85. As you can see it isn't much bigger or heavier than the coin cell.

You can run the Atmega328P (and the ATtiny) at 3V (as from that battery) provided you slow them down to 8 MHz. That is quite easy to achieve, and then you don't need an external crystal as the Atmega328P has an inbuilt oscillator which can drive it at that frequency (as does the ATtiny).

I have [a page about power saving](http://www.gammon.com.au/power) which might help you with your design.

A possible alternative is a single LiPo cell (nominally 3.7V) which, if you get a small one, should be quite light.

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


message:
Arduino - Raspberry Pi serial communication

I need to connect a Raspberry Pi and an Arduino Uno through serial communication and decided to follow [this guide][1], which mentions the use of a voltage divider.

I understand the connection to the Raspberry Pi GPIO requires 3.3V but I also plan to power the Raspberry Pi from the Ardunio's 5v output pin.

What's the safest approach to achieve this and the recommended current? Thanks.

  [1]: https://oscarliang.com/raspberry-pi-and-arduino-connected-serial-gpio/

body:
1. You **CAN NOT** reliably power any model Pi from the Arduino 5V output.

2. You can interconnect the Arduino serial to the Pi using a voltage divider or (preferably) a level converter, as suggested in the linked article. (I might add that the linked article contains a number of errors which will not work on recent Pi models).

Better still you can use a USB connection, to provide serial communication to the Arduino, **AND** you can power the Arduino from the Pi (I often do this).


message:
put_index = (put_index + 1) % 100;

Can someone interpret the code in the Title line for me?  Specifically the function of the "%" sign?  It is a line having to do with a 100 element circular buffer.

body: In C the % symbol is the modulo operator : https://en.m.wikipedia.org/wiki/Modulo_operation


body:
The `%` is the modulo operator in C/C++, which basically means:

1. Divide the value to the left of the `%` by the value to the right of it
2. Discard the quotient and keep only the remainder.

For instance, `10 % 5 = 0`, because 10/5 = 2 with no remainder. Whereas `11 % 5 = 1`, because the remainder of the division is 1.

In your case, the modulo operator is likely being used to keep the value of `put_index` less than 100 at all times. If it became 100 because of the operation `put_index = put_index + 1`, then the modulo operation would make the 100 into 0, so `put_index` will keep incrementing 0–99 repeatedly.