message:
Why are commands executing on their own?

This is the program I have used. It's working fine. But I don't known why sometimes it operates on its own. It is used to control a welding machine (Arduino is isolated from earthing). When there is a little vibration the code executes a command. This is the code:

    int a = 9;  //right actuator forward relay 1
    int b = 12; //right actuator reverse relay 2 (orange 10)
    int c = 10; //left actuator forward relay 4
    int d = 11; //left actuator reverse relay 3
    int x = 0;
    int y = 0;
    const int stepPin = 8; // HIGH =DOWN; LOW == UP
    const int dirPin = 7;

    void setup() {
      pinMode(5, INPUT_PULLUP);
      pinMode(6, INPUT_PULLUP);
      pinMode(a, OUTPUT);
      pinMode(b, OUTPUT);
      pinMode(c, OUTPUT);
      pinMode(d, OUTPUT);
      pinMode(stepPin, OUTPUT);
      pinMode(dirPin, OUTPUT);
      pinMode(4, INPUT_PULLUP);
      pinMode(2, INPUT_PULLUP);
      Serial.begin(9600);
      digitalWrite(b, HIGH);
      digitalWrite(d, HIGH);
      delay(2000);
      digitalWrite(b, LOW);
      digitalWrite(d, LOW);
      delay(1000);
      Serial.println("press the foot swtich"); // Serial Monitor for Debugging
    }

    void loop() {
      int Val = digitalRead(5); //   Actuator 1 Clamping
      int ValR = digitalRead(6);//   Actuator 2 Clamping
      int ValS = digitalRead(4);//Stepper Motor anticlockwise
      int ValM = digitalRead(2);//Stepper Motor Clockwise
      if (Val == LOW && x == 0  ) {
        Serial.print("Val000=");
        Serial.println(Val);
        digitalWrite(c, HIGH);
        delay(1750);
        digitalWrite(c, LOW);
        x = 1;
        Val = digitalRead(5);
        Serial.println("fwd");
        Serial.print("Val=");
        Serial.println(Val);
        delay(500);
      }
      if (Val == LOW && x == 1  ) {
        digitalWrite(d, HIGH);
        digitalWrite(b, HIGH);
        delay(2000);
        digitalWrite(d, LOW);
        digitalWrite(b, LOW);
        x = 0;
        Val = digitalRead(5);
        Serial.println("fwd");
        y = 0;
        Serial.print("Val=");
        Serial.println(Val);
        delay(500);
      }
      if (ValR == LOW && y == 0 ) {
        digitalWrite(a, HIGH);
        delay(1350);
        digitalWrite(a, LOW);
        y = 1;
        ValR = digitalRead(6);
        Serial.println("fwd");
        Serial.print("Val=");
        Serial.println(Val);
        delay(500);
      }
      if (ValR == LOW && y == 1 ) {
        digitalWrite(b, HIGH);
        delay(1200);
        digitalWrite(b, LOW);
        y = 0;
        ValR = digitalRead(6);
        Serial.println("fwd");
        Serial.print("Val=");
        Serial.println(Val);
        delay(500);
      }
      if (ValS == HIGH) {
        Serial.println(Val);
        Serial.println("up");
        digitalWrite(dirPin, HIGH);
        // Enables the motor to move in a particular direction
        // Makes 100 pulses for making half cycle rotation
        for (int x = 0; x < 100; x++) {
          digitalWrite(stepPin, HIGH);
          delayMicroseconds(1000);
          digitalWrite(stepPin, LOW);
          delayMicroseconds(1000);
        }
        // Enables the motor to move in a particular direction
        // Makes 200 pulses for making one full cycle rotation
      }
      if (ValM == LOW) {
        Serial.println("down");
        Serial.println(ValR);
        digitalWrite(dirPin, LOW);
        // Enables the motor to move in a particular direction
        // Makes 200 pulses for making one full cycle rotation
        for (int x = 0; x < 100; x++) {
          digitalWrite(stepPin, HIGH);
          delayMicroseconds(1000);
          digitalWrite(stepPin, LOW);
          delayMicroseconds(1000);
        }
        // Enables the motor to move in a particular direction
        // Makes 200 pulses for making one full cycle rotation
      }
    }

body:
Trying to write a proper answer...

According to your description, it looks like you are victim of inductive
noise pickup. The circuit [MCU → Arduino ground pin → foot pedal →
Arduino digital input pin → MCU] is a loop that can pick up magnetic
flux. If this flux varies, either because the magnetic field varies
(ambient electromagnetic noise) or because the geometry of the circuit
changes (you move the wires), this will induce an electromagnetic force
that can make your Arduino read `LOW` even when the button is not
pressed.

There are two things you can try to overcome this effect:

1. Replace the weak internal pullup of the Arduino by a much stronger
   external pullup. Something around 1 kΩ should make it quite hard for
   the noise to pull the signal low.
2. Connect the pedal to the Arduino board using a twisted pair of wires,
   like the ones found in telephone or network cables. This kind of
   cable does a good job at minimizing inductive pickup.


sender: user

message:
HC-05 and p-channel mosfet

I'm trying to use a MOSFET ([BS250P datasheet][1]) to switch a circuit on and off while the MCU is asleep. It's a P-channel MOSFET that closes the circuit when the gate is pulled low. The most power hungry module in my circuit is a HC-05 bluetooth module. The specs on the website I bought it at rates it at 3.3V - 6V and a max current draw of 50mA when pairing and around 9mA when connected. Hooking it up to an Arduino 3.3V source confirms that it works at that voltage and pairs it up with another identical module just fine.

Now when I put that same 3.3V source through the MOSFET with a 10k pull up resistor and connects the HC-05 to the drain, the module does not power up. I measured the voltage on the drain and when nothing is connected it's the same as the source. After connecting the HC-05 it's about 2.4V (maybe this is a clue). Even if I run the power through a step up converter to 4.10V it does not power up through the MOSFET. If I increase the voltage to 5V it all works fine. I would ideally run the circuit at 3.6V in order to preserve current for the rest of the modules, and not having to use a voltage regulator for the RX of the HC-05.

I assume the issue is with the MOSFET properties, but as far as I can read from the datasheet it can sustain 230mA current. It has a VGS(th) of 3.6V, but since I'm always pulling the MOSFET low in this scenario that shouldn't be an issue? Measuring the resistance when the gate is pulled low indeed gives just a few ohms as the datasheet suggests.

So basically, what am I missing here? :-) Thank you for any help with this!

  [1]: http://www.produktinfo.conrad.com/datenblaetter/550000-574999/563346-da-01-en-MOSFET_P_KA_45V_230MA_BS250P_TO_92_3_DIN.pdf

sender: assistant

body:
That's not a good choice of MOSFET I'm afraid.

The on resistance is quoted as 14Ω when the gate is at -10V - however, you are only able to get -5V, so it will be considerably worse.

That massive on resistance will be causing a massive voltage drop, which is what you are experiencing.

You should find a MOSFET with an on resistance that is in the milli-ohm range when the gate is between 0V and -5V.


message:
Casting custom shared_ptr object

I am using custom shared_ptr class for some program on Arduino, and I need to do something like this:

    shared_ptr<Base_class> b_ptr;
    shared_ptr<Child_class> ptr((shared_ptr<Child_class>) b_ptr);

In my shared_ptr class I have three constructors:

    shared_ptr() : pData(0), reference(0){...}
    shared_ptr(T* pValue) : pData(pValue), reference(0){...}
    shared_ptr(const shared_ptr<T>& sp) : pData(sp.pData), reference(sp.reference){...}

and some other stuff...
For casting I tried to write the following:

        template< typename T2 >
 operator T2 * () const
 {
    return (T2 *)pData;
 }

and:

        template< typename T2 >
 operator shared_ptr<T2> () const
 {
     shared_ptr<T2> temp((T2 *)pData);
     return temp;
 }

but can't get it to work.

body:
For doing:

    shared_ptr<Base_class> b_ptr;
    shared_ptr<Child_class> ptr(b_ptr);

you have to use another constructor. If you take a look on this [Example of shared_ptr implementation][1], you can see:

    template<class U> shared_ptr(const shared_ptr<U>& s) ...

That's exactly the constructor, that takes shared_ptr of different type <U>.

And similarly for assigment operator.

  [1]: https://stackoverflow.com/a/9201435/5271927


message:
HC-05 bluetooth module not accepting AT commands

I have been attempting to program my HC-05 ZS-040 Bluetooth module for quite some time, and I cannot get the AT commands to return any values. I have searched google for quite some time, and I none of the answers seem to work for me. I have been following along with this website:

https://sites.google.com/site/wayneholder/inexpensively-program-your-arduino-via-bluetooth

I am using an Arduino Mega 2560 clone by Elegoo to program this Bluetooth module. Currently I have it wired up using this diagram

https://sites.google.com/site/wayneholder/inexpensively-program-your-arduino-via-bluetooth/HC-05-to-FTDI.png?attredirects=0

Currently I have it modified slightly to use a voltage divider between the Arduino's Tx and the HC-05 Rx, as the HC-05 works on 3.3v logic. The one possibility I think could be causing this problem is that the Arduino Mega is just interpreting all Tx incorrectly as I measured that it sounds ardoun 3.2 volts for a high voltage. According to multiple websites the HC-05 is in AT command mode when the LED flashes slowly, about once every 2 seconds, which is happening. I put it in command mode by holding down the button above the EN pin while providing power to the HC-05.

I have been using pin 14 and 15, which are Hardware Serial3 on the Arduino Mega. Here is the code I have written:

      /*
      Software serial multple serial test

     Receives from the hardware serial, sends to software serial.
     Receives from software serial, sends to hardware serial.
     */
    #include <SoftwareSerial.h>

    SoftwareSerial mySerial(15, 14); // RX, TX

    void setup() {
      // Open serial communications and wait for port to open:
      Serial.begin(9600);
      while (!Serial) {
        ; // wait for serial port to connect. Needed for native USB port only
      }
      Serial.println("AT");
      // set the data rate for the SoftwareSerial port
      Serial3.begin(38400);
    }

    void loop() { // run over and over
      if (Serial3.available()) {
        Serial.write(Serial3.read());
      }
      if (Serial.available()) {
        Serial3.write(Serial.read());
      }
    }
Any suggestions are much appreciated!

EDIT:
I have now received some unrecognizable responses from the controller after sending AT multiple times, here is the screenshot, included is a video of my circuit, which shows how the LED is flashing:

https://drive.google.com/open?id=1mc8PEEnhiKpPzzy5kL9QxTvoQA3NAH6b

The only modification to the code is adding a `Serial.println("TESTING");` in the while loop that reads Serial3. I have tried using other Hardware serial ports as well, all with the same result as the above screenshot.

body:
**###### Try This : Your Code Updated With Possible Fixes  ######**

After examining your code and comparing it to my working code I believe I have found a definitive answer.  I'm altering your code so you can copy it and try it.  I'll add comments where I've changed it.

    #include <SoftwareSerial.h>

    SoftwareSerial mySerial(15, 14); // RX, TX

    void setup() {
      // Open serial communications and wait for port to open:
      Serial.begin(9600);
      Serial.println("Enter AT commands:"); // a prompt in Serial Monitor
      // Deleted while loop, unnecessary

      // set the data rate for the SoftwareSerial port
      // notice that your comment on previous line says SoftwareSerial port
      // but you are setting the Serial3 port -- this is where we use mySerial
      // Serial3.begin(38400); // commented your line of code
      mySerial.begin(38400);
    }

    void loop() { // run over and over
      //if (Serial3.available()) { // we don't use Serial3 any more
      if (mySerial.available()) {
        //Serial.write(Serial3.read());
        Serial.write(mySerial.read());
      }
      if (Serial.available()) {
        //Serial3.write(Serial.read());
        mySerial.write(Serial.read());
      }
    }

I am confident that if you use this newly modified code it will solve your problem.  I should've noticed this earlier.

**Here's the rest of my original answer**.

I have struggled with this myself.  As a matter of fact it took me a few months of owning some HC-05s before I finally dug up an answer.  It's been a while since I worked with it so I'll do my best to explain what to do.

**Arduino Nano**

Also, I use an Arduino Nano to do the programming of the HC-05.

**This Setup Lets You Alter HC-05**

Once you wire it up and run the program (included here) you will be able to send any of the HC-05 commands and they work great.  You can change the name of the device, the 4-digit pass-code and everything.

**Crude Snapshot, But Enough To Build Simple Circuit**

I also have a crude snapshot* of the circuit I used (at the time just for documenting it for my own memory) but I think we can work you thru it.  and I know those wires are all crammed together and it almost looks like they are in the same breadboardholes but they are actually hooked up properly.  I was so excited it finally worked I snapped the pic too fast.

*see image below

Here's the code I use:

    #include <SoftwareSerial.h>

    SoftwareSerial BTSerial(10, 11); // RX | TX

    void setup()
    {
      //pinMode(9, OUTPUT);  // this pin will pull the HC-05 pin 34 (key pin) HIGH to switch module to AT mode
      //digitalWrite(9, HIGH);
      Serial.begin(9600);
      Serial.println("Enter AT commands:");
      BTSerial.begin(38400);  // HC-05 default speed in AT command more
    }

    void loop()
    {

      // Keep reading from HC-05 and send to Arduino Serial Monitor

      if (BTSerial.available())
        {
         //Serial.println("bt available...");
        Serial.write(BTSerial.read());
        }

      // Keep reading from Arduino Serial Monitor and send to HC-05
      if (Serial.available())
        BTSerial.write(Serial.read());
    }

**Does Your HC-05 Have the Button?**

Okay, so the first thing is to check to see if your HC-05 has the little button on it?  If it does that has to be held when you apply power to the circuit.  The HC-05 will blink and then it will be in COMMAND mode and you can let go.

**If No Button**

You can see that mine has the button.  That is why the first two lines the setup() method are commented out.  I don't need D9 to go high (it is not connected to the pin) because mine has the button. If yours has the button (most likely does) then you don't even have to worry about it.

**Looking Back At Your Question**

Now that I look back at your sample code it could be that you're not aware that you have to hold that button when you power up.  Or you don't know that you need to connect that wire to keep the HC-05 in command mode.

**Pins For TX / RX**

That's probably the problem you are having, because everything else looks the same -- except you are using 15 and 14 for TX / RX.  I am using D10 and D11 for mine and I remember something about those pins in the back of my mind so if yours still doesn't work, try switching to those and try using my code.

I remember the first time I finally got this working and I was dancing around the room. Good luck and I hope you are dancing soon.  :)

[![hc-05 via nano][1]][1]

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


body: Thanks for all the help! I had given up on getting Bluetooth module to work, however when working with a simple RGB LED, I noticed my mistake. I was using the ground from my breadboard power supply for the module instead of the ground from the Arduino Mega. I rewired my breadboard so the ground and power come from my Arduino Mega, and everything works perfectly! I ended up using the exact same code that I posted in my original question, so it was just that I was not using the ground from my Arduino Mega


message:
Problem with nodemcu esp-01 can't connect to wifi

i've been working on a project that im using an esp8266 nodemcu-01 as described in the title, and i've been having some headache with this module, first because after searching i figured out that the commands LOW and HIGH are inversed as in LOW outputs 3.3v e HIGH outputs low tension, so i began to grow worried about the possibility that other programming resources may follow the same situation. But with that problem a part, i've been trying a few different codes including the one found in the sketchbook examples and still couldn't connect.

Also another weird problem, is that i was working working with the baudrate set on the arduino IDE settings on 115200, and so is the Serial.begin, that is also set to 115200, however i can only read properly the continuous dot that is contained in the while loop "........." when i set it to 74880, which another thing that i was trying to understand. I also forgot to mention that it keeps spamming dots but does not connect at all.

And to conclude, my problem resumes in not being able to connect to any wifi i've tried, i tried my friend's home and also 4g, both did not work, here's the code, which we tried first:

    #include <ESP8266WiFi.h>

    char* ssid = "Net Wi-fi";
    char* password = "testingtest";
    //
    void setup() {
      WiFi.begin(ssid, password);
      Serial.begin(115200);
      while(WiFi.status()!=WL_CONNECTED)
      {
        Serial.print("Conecting");
        delay(500);
      }
      Serial.println("");
      Serial.print("IP:");
      Serial.print(WiFi.localIP());
    }

    void loop(){

This was the original try, using the arduino sketch example:

    #include <ESP8266WiFi.h>
    #include <WiFiClient.h>
    #include <ESP8266WebServer.h>
    #include <ESP8266mDNS.h>

    const char* ssid = "Net6271";
    const char* password = "megaman";

    ESP8266WebServer server(80);

    const int led = 13;

    void handleRoot() {
      digitalWrite(led, 1);
      server.send(200, "text/plain", "hello from esp8266!");
      digitalWrite(led, 0);
    }

    void handleNotFound(){
      digitalWrite(led, 1);
      String message = "File Not Found\n\n";
      message += "URI: ";
      message += server.uri();
      message += "\nMethod: ";
      message += (server.method() == HTTP_GET)?"GET":"POST";
      message += "\nArguments: ";
      message += server.args();
      message += "\n";
      for (uint8_t i=0; i<server.args(); i++){
        message += " " + server.argName(i) + ": " + server.arg(i) + "\n";
      }
      server.send(404, "text/plain", message);
      digitalWrite(led, 0);
    }

    void setup(void){
      pinMode(led, OUTPUT);
      digitalWrite(led, 0);
      Serial.begin(115200);
      WiFi.mode(WIFI_STA);
      WiFi.begin(ssid, password);
      Serial.println("");

      // Wait for connection
      while (WiFi.status() != WL_CONNECTED) {
        delay(500);
        Serial.print(".");
      }
      Serial.println("");
      Serial.print("Connected to ");
      Serial.println(ssid);
      Serial.print("IP address: ");
      Serial.println(WiFi.localIP());

      if (MDNS.begin("esp8266")) {
        Serial.println("MDNS responder started");
      }

      server.on("/", handleRoot);

      server.on("/inline", [](){
        server.send(200, "text/plain", "this works as well");
      });

      server.onNotFound(handleNotFound);

      server.begin();
      Serial.println("HTTP server started");
    }

    void loop(void){
      server.handleClient();
    }

Board setting: Generic ESP8266 Module.
Crystal Frequency: 40MHz.
Flash Frequency: 80Mhz.
Upload Speed: 115200.
Flash Mode: DIO.
Flash Size: 512k no SPIFFS.

pls help.

body:
ESP-01 modules use 26 MHz crystal. Set the Crystal frequency in IDE to 26 MHz.

Both io pins (0 and 2) on esp-01 have pull-up circuit. That is why you think you measured 'inverted' logic.


message:
Is I2C a good option for transmitting data over 200 meters by cable?

Is I2C a good option for such application or are there other protocols? I know that modules like [these][1] exists to extend I2C range, and I'm planning to use this one (P82B96).

I'd like to use a frequency of 100kHz for I2C and use DMX cables of 20m connected in series.

So, is there any alternative that is more adapted for Arduino to Arduino data transmission over a cable?

EDIT : The solution here is CAN because it allows to have multiple devices on the bus. But if it is a simple communication between two arduinos, then go for the RS-232.
Solution mentionned by @Dmitry Grigoryev and @Joe S

Thanks in advance.

  [1]: https://www.tme.eu/fr/Document/71a9aa14de9dc59baffc455b8858ae1c/P82B96TD.pdf

body: I2C is perhaps the worst possible choice for this type of communication. Instead you should be using something like RS-485 (which is incidentally what DMX uses) with differential signalling.


body:
With I2C, you're unlikely to get reliable communication on a cable longer than 1m. For your reference, here's a [table](http://www.seabird.com/faq/what-maximum-cable-length-real-time-rs-232-data) showing what you can achieve with regular RS-232:

    Length (m)  Maximum Baud Rate
    1600      600
    800      1200
    400      2400
    200      4800
    100      9600
    50          19,200
    25          38,400
    16          57,600
    8          115,200

So, if you don't really need 100 kHz data rate, you could use regular RS-232 (which is cheap). If RS-232 is not fast enough for you, consider more complex solutions. RS-485 is one possiblility. Another one is CAN, which supports topologies up to 500m at 100kHz. The key difference of CAN is that it's a bus, meaning that all devices will share the same pair of wires.


message:
Using modulo for negative values

I want to wrap a random number using modulo, so that values exceeding 11 starts over from 0 and greater. However, i would also like numbers less than 0 to dividend 11 or less.

Please correct me if i'm wrong, but as far as i can tell the modulo operator only dividends values *exceeding* the divisor. If so, how can i write code that also dividends values less than 0?

body:
One crude way:

    while (x > 11) x -= 11;
    while (x < 0) x += 11;

The first could be replaced with a modulo operation.


body:
Simply use modulo

    #include <stdio.h>

    int main(){
       for (int i = -23;i<23;i++) printf("%d %d\n",i,i);
       return 0;
    }

all modern C variants should work the same way https://en.wikipedia.org/wiki/Modulo_operation (result have same sign as divident):

    -23 -1
    -22 0
    -21 -10
    -20 -9
    -19 -8
    -18 -7
    -17 -6
    -16 -5
    -15 -4
    -14 -3
    -13 -2
    -12 -1
    -11 0
    -10 -10
    -9 -9
    -8 -8
    -7 -7
    -6 -6
    -5 -5
    -4 -4
    -3 -3
    -2 -2
    -1 -1
    0 0
    1 1
    2 2
    3 3
    4 4
    5 5
    6 6
    7 7
    8 8
    9 9
    10 10
    11 0
    12 1
    13 2
    14 3
    15 4
    16 5
    17 6
    18 7
    19 8
    20 9
    21 10
    22 0

---

for new formulation of request fixed by @Gerben suggestion

if you want monotonic 0..10 sequencies, add 11, if result is negative :

    #include <stdio.h>

    int main(){
    for (int i = -23;i<23;i++)
     {
     int x= i ;
     x += x<0?11:0;
     printf("    %d %d\n",i,x);
     };
    return 0;
    }

results in

    -23 10
    -22 0
    -21 1
    -20 2
    -19 3
    -18 4
    -17 5
    -16 6
    -15 7
    -14 8
    -13 9
    -12 10
    -11 0
    -10 1
    -9 2
    -8 3
    -7 4
    -6 5
    -5 6
    -4 7
    -3 8
    -2 9
    -1 10
    0 0
    1 1
    2 2
    3 3
    4 4
    5 5
    6 6
    7 7
    8 8
    9 9
    10 10
    11 0
    12 1
    13 2
    14 3
    15 4
    16 5
    17 6
    18 7
    19 8
    20 9
    21 10
    22 0


message:
Servo doesn't work in 'for' loop running under 'if' loop

This is my first StackExchange question. I'm relatively new to Arduino and I am trying to tinker with the components and functionality.

I have a RGB LED coupled to my breadboard with a servo attached. The LED only shows Red and Orange for some reason(Why?), SO I mended my code as per the LED behaviour. The code prompts the user for a color, and depending on that, the Servo should rotate along with the LED lighting up. My servo functions well only in 25-165 degrees range. The code goes as,

Here's the code:

    # include<Servo.h>
    int i;
    Servo n1;

    String color;
    void setup(){

    Serial.begin(9600);
      n1.attach(6);
      pinMode(2,OUTPUT);
      pinMode(3,OUTPUT);
      pinMode(6,OUTPUT);

    }

    void loop(){

    Serial.println("Enter color: ");

    while(Serial.available()==0){
    }
    color=Serial.readString();

    if (color=="red"){
      digitalWrite(2,HIGH);

      for (i=25;i<=165;i=i+5){
            n1.write(i);
            delayMicroseconds(250);
      //}
      n1.write(25);
      delay(2500);
      digitalWrite(2,LOW);
    }

    }else if (color=="orange"){
      digitalWrite(3,HIGH);

      for (i=165;i>=25;i=i-2){
        n1.write(i);
        delayMicroseconds(250);
      }
      n1.write(25);
      delay(2500);
      digitalWrite(3,LOW);
    }
    }

So basically when Red is in, I want the Servo to go from 25 to 165 & come back to 25, and vice versa for Orange. But the servo behaves in 2 ways;

1.When Red is entered first, it turns some angle(I guess 25) and stays there, the programme doesn't even loop for further input of color for a long period. Then whatever the input goes, Servo stops rotating, only LED works.

2.When Orange is entered first, it goes again to the same angle as red, and mildly buzzes, but input is accepted and Servo is motionless.
I simulated the same setup and code in TinkerCad circuits, and the behaviour is the same, so no particular problem with the hardware there.

I'm relatively new to understanding the Arduino workings and Fundamentals, any help is appreciated.
Also, the circuit setup is attached.

Any help will be appreciated.

Thanks!

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

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

  [1]: https://i.stack.imgur.com/oxNbc.jpg
  [2]: https://i.stack.imgur.com/ySQ0d.png

body:
This section of code is never going to run. The for loop says that i starts at 175, and while i>=25175 then execute the n1.write(i) and subtract 2 from i each time it does this.

    for (i = 175; i >= 25175; i = i - 2) {
          n1.write(i);
        }

From the arduino servo example page, n1.write() should only ever be from 0 to 180, as it is the angle the servo is at. So you go from 175 to 180 and it wont move past that.

    //angle: the value to write to the servo, from 0 to 180

    #include <Servo.h>

    Servo myservo;

    void setup()
    {
      myservo.attach(9);
      myservo.write(90);  // set servo to mid-point
    }

    void loop() {}


message:
How do I configure a pin to be a bidirectional and open collector?

I want to communicate with a keyboard asynchronously through a single open collector, bidirectional data pin. As part of the protocol, the data pin is active low and is pulled low by either the host or connected device.

Some code examples configure the pin direction to switch input to output depending on wether the host want to input or output a signal. Constantly switching the pin directions seems a bit naive.

Are there better methods?

body:
If the other end of the link has the same signal voltage as your
Arduino, you can simulate an open collector with a single pin:

* `digitalWrite(pin, LOW); pinMode(pin, OUTPUT);` sets the pin to output
  an active low signal.
* `pinMode(pin, INPUT_PULLUP)` sets the pin to input mode, or output
  passive high which, in open-collector mode, is the same thing.

Note that in the first case the order of the commands is important: on
AVR microcontrollers, if you set the mode to `OUTPUT` before writing
`LOW`, the pin will for a short time output an active high, which is
forbidden in open-collector mode. I don't know how other MCUs would
behave in the same situation though.

**Edit** to address Ignacio Vazquez-Abrams’ comment: An open-collector
bus needs a pullup resistor on each data line to function properly. If
that pullup is already provided by your keyboard, or your cable, then
you should use `pinMode(pin, INPUT)` to accurately emulate an
open-collector output on the Arduino side. Otherwise you have to provide
that pullup, either as an external component or by using the internal
pullup of the MCU. Beware that the latter may be a little bit weak,
depending on your data rate.


message:
How to use control a 48 000 motor with Arduino

I am new to Arduino and I am just playing with it, I wanna control a 48,000rpm motor with 9v voltage via Arduino the plobrem is how could I make that motor slow down, slowly. Any ideas? I am using Arduino mega

body:
So far you haven't added any information about the motor so I am going to assume it is a standard DC motor.

With this type of motor, you can change the speed by varying the voltage. So at 9V it will go full speed (theoretically 48,000 RPM). At 4.5V it should go at about (roughly) half. Of course this varies with the load you are applying to the motor.

You can control the motor speed using the PWM output of the Arduino. If you would like to read more about Pulse-width Modulation (PWM) I highly recommend that you read the Sparkfun [article here][1].

This presents 2 problems.

 1. The Arduino Mega PWM only gives you an adjustable voltage between 0V to 5V.
 2. The current provided on these pins is only small and would not be able to power the motor fully.

To overcome both you need to add a MOSFET. I suggest a N-Channel MOSFET that switches on the low side.

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

<!-- End schematic -->

  [1]: https://learn.sparkfun.com/tutorials/pulse-width-modulation


message:
Sending multiple messages over the serial monitor in nodeMCU

I am trying to send multiple messages wirelessly from one ESP8266-12E NodeMCU to another. I have successfully established the connection and am able to send and receive single messages. The MAC addresses are solely for the verification that the data is going to the right client. My trouble is sending multiple messages which I should be able to observe in the serial monitor.

Here's my server code:

    #include <ESP8266WiFi.h>

    extern "C" {
      #include <user_interface.h>
    }

    int32_t freq = 10000;

    WiFiServer server(80);                            //Initialize the server on Port 80

    void setup() {
      pinMode(D1,OUTPUT);
      pinMode(D2,OUTPUT);
      pinMode(D3,OUTPUT);

      Serial.begin(9600);                             //Start communication between the ESP8266-12E and the monitor window

      analogWriteFreq(freq);

      WiFi.mode(WIFI_AP);                             //This ESP8266-12E is an AccessPoint
      WiFi.softAP("NodeMCU_js", "12345678");          //Provide the (SSID, password)

      IPAddress HTTPS_ServerIP = WiFi.softAPIP();      //Obtain the IP of the Server
      Serial.println("Server IP is: ");                 //Print the IP to the monitor window
      Serial.println(HTTPS_ServerIP);
      server.begin();                                 //Start the HTTP Server

    }

    void loop() {
      WiFiClient client = server.available();         //Check if a client has connected to the server

      struct station_info *stat_info;
      struct ip_addr *IPaddress;
      IPAddress address;

      if (client) {
        Serial.println("Somebody has connected :)");

        stat_info = wifi_softap_get_station_info();

        while (stat_info != NULL){
          IPaddress = &stat_info->ip;
          address = IPaddress->addr;
          Serial.println();

          Serial.print("Client IP Address = ");
          Serial.print(address);
          Serial.println();

          Serial.print("Client MAC Address = ");
          Serial.print(stat_info->bssid[0],HEX);
          Serial.print(":");
          Serial.print(stat_info->bssid[1],HEX);
          Serial.print(":");
          Serial.print(stat_info->bssid[2],HEX);
          Serial.print(":");
          Serial.print(stat_info->bssid[3],HEX);
          Serial.print(":");
          Serial.print(stat_info->bssid[4],HEX);
          Serial.print(":");
          Serial.print(stat_info->bssid[5],HEX);
          Serial.println();

          if (stat_info->bssid[0] == 0xDC && stat_info->bssid[1] == 0x4F && stat_info->bssid[2] == 0x22 && stat_info->bssid[3] == 0x17 && stat_info->bssid[4] == 0xEE && stat_info->bssid[5] == 0x95){
              int duty1 = 150;
              int duty2 = 200;
              int duty3 = 250;
              Serial.println("Duty - 1 : "+String(duty1));
              Serial.println("Duty - 2 : "+String(duty2));
              Serial.println("Duty - 3 : "+String(duty3));

              analogWrite(D1,duty1);
              analogWrite(D2,duty2);
              analogWrite(D3,duty3);

              client.println(String(duty1)+"\r");                          //Server's response to the client
              client.println(String(duty2)+"\r");
              client.println(String(duty3)+"\r");
           }
          else {
            Serial.println();
            Serial.println("Client not recognized.");
          }
         stat_info = STAILQ_NEXT(stat_info, next);
        }
      }
    }

Here's my client code:

    #include <ESP8266WiFi.h>
    #include <ESP8266HTTPClient.h>

    char ssid[] = "NodeMCU_js";
    char password[] = "12345678";

    IPAddress server(192,168,4,1);       // the fix IP address of the server

    WiFiClient client;                // Creates a client that can connect to to a specified internet IP address and port as defined in client.connect()

    void setup() {
      pinMode(D4,OUTPUT);

      WiFi.persistent(false);
      WiFi.mode(WIFI_STA);

      Serial.begin(9600);                 //Serial connection
      WiFi.begin(ssid,password);          //WiFi connection

      while (WiFi.status() != WL_CONNECTED) {         //Wait for the WiFI connection completion
        delay(500);
        Serial.println("Connecting...");
      }
      Serial.println("Connected.");
      client.connect(server,80);
    }

    void loop() {
      if(WiFi.status()== WL_CONNECTED){   //Check WiFi connection status
        String answer1 = client.readStringUntil('\r');
        Serial.println();
        Serial.print("From Server(1): ");
        Serial.print(answer1);
        client.flush();

        String answer2 = client.readStringUntil('\r');
        Serial.println();
        Serial.print("From Server(2): ");
        Serial.print(answer2);
        client.flush();

        String answer3 = client.readStringUntil('\r');
        Serial.println();
        Serial.print("From Server(3): ");
        Serial.print(answer3);
        client.flush();

      }
      else{
        Serial.println("Error in WiFi connection");
      }
    }

It would be helpful if I could get the correct way of doing this.

Thanks in advance.

body: from server you send at the end of line \r\r\n. first \r is in the string and \r\n is added by println. then at the client you read until \r the first line, the you read an empty line until next \r.


message:
LCD display not working properly + inconsistent results

I have soldered the pins to my 20x4 LCD display. The soldering is not very good, but this is the best i can do. I have measured the resistance between each of the pins of the LCD with my multimeter to check if the pins are isolated. And they are! So the bad soldering is not the problem...

Last night, the display showed weird results and non-existent characters, all over the 20x4 display.
This morning, it showed only full blocks. But now it is showing only 2 of the 4 rows.
I think this is weird because i did not touch it in my sleep...

I should see the text 'Welcome', but i only see blocks now.

I dont have a potentiometer any more, so i used a for-loop with a PWM signal to check the contrast i need. This did work the last time for me.

I use the arduino MEGA.
Below you see my code, and photo's of my little project.

    #include <LiquidCrystal.h>
    LiquidCrystal lcd(9, 10, 48, 46, 44, 42);

    const int contrastPin = 8;

    void setup() {
      // put your setup code here, to run once:
      lcd.begin(20,4);
      pinMode(contrastPin,OUTPUT);
    }

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

      lcd.setCursor(0,0);
      lcd.print("Welcome");

      //LOOP TO CHECK TE CONTRAST
      for(int i = 0; i <= 255; i++){
        analogWrite(contrastPin,i);
        delay(30);
      }
    }

[![Top of the LCD][1]][1]
[![Control pins][2]][2]
[![Data pins][3]][3]
[![Screen in for-loop on index 0][4]][4]
[![Screen in for-loop on index 255][5]][5]
[![My current project (cigar humidor v0.1)][6]][6]

  [1]: https://i.stack.imgur.com/DeDEw.jpg
  [2]: https://i.stack.imgur.com/zCAfu.jpg
  [3]: https://i.stack.imgur.com/EAZgR.jpg
  [4]: https://i.stack.imgur.com/jY5VM.jpg
  [5]: https://i.stack.imgur.com/LrUZh.jpg
  [6]: https://i.stack.imgur.com/fOrOe.jpg

body: I re-soldered the pins. Also, I used a small resistor between my PWM signal and the VO port. Now it works perfectly.


message:
"Active LOW" relay board Pin configuration

I bought a 5 V Relay Board: [LINK (Aliexpress)][1] and just realised it's "Active LOW".
I want to control a water pump via a Arduino Micro.

I tested it and as far as i understand the workings of this relay, putting the pin to LOW activates the little LED on the Relay Board and switches to the NC position where I connected the water pumps ground wire.

I don't feel very comfortable with that because normally those relays are activated by setting the pin to HIGH.
I tried to connect the ground wire of the pump to the normally open position but than, if I disconnect the Arduino to simulate a malfunction the pump keeps running.... this doesn't happen with the first configuration.

So my Question: Is it a problem to use the Relay Board in the way described above (Pin to LOW switches Coil to NC Postion).
Is there a way I'm not seeing to get the Board to switch the Coil if a pin is set to high.

  [1]: https://www.aliexpress.com/item/32304609560/32304609560.html?shortkey=3miqMNZF&addresstype=600

body:
That relay module is driven by optocouplers. You are just driving and LED, and that is connected though a resistor to VCC.

In the past it was common to use active low for driving things since an N channel MOSFET could typically sink more current than a P channel one could source. Also in the days before CMOS there was really only low-side (sinking) switching, so active low was the norm.

These days it's not necessary, but it's still common because that is how it's always been.

So yes, active low is both common and accepted.


message:
Arduino IDE giving a blow to battery back-up of PC

When I have _serial plotter_ open in the Arduino IDE with serial communication going on, the fans of my PC go full speed. On checking I found that **Java(TM) Platform SE binary(32 bit)** is using about **29%** of the **CPU**.

This gives a big blow to the PC's battery back-up. Is there some way to reduce the CPU usage ?

> The IDE version I use is **Arduino 1.8.4**

    OS : Microsoft Windows 10 Home (64 bit)

    PC : HP Au620 TX (laptop)

    processor : Intel i5 7th gen (7200)

    RAM : 8GB

body: Run Arduino IDE in a virtual machine which allows CPU allocation. Set a strict limit on CPU resources in that VM, like 200..500 MHz.


message:
MQTT over serial

I'm planning to build a 32 relay IOT node next to my Raspberry Pi. The relays will be controlled by an Arduino Mega 2560. The Pi will run Home Assistant and Mosquitto so I would prefer to communicate with the arduino using MQTT.
The Arduino and the Pi will be next to each other, the simplest connection would be over serial.
I have found a library: https://github.com/vortex314/serial2mqtt it looks not easy to set up. Do you have any other ideas?
Thank you!

body:
Finally I have found the solution!
Using mysensors (mysensors.org) I can use the Arduino Mega as a node and a serial gateway. So Home Assistant can control it directly.


body:
As the author of the serial2mqtt gateway. Maybe it's time to have a new look. I've included the binaries for different platforms in the build : https://github.com/vortex314/serial2mqtt/tree/master/build
So to get started : unzip the binary and update the serial2mqtt.json config.
Should be piece of cake. Let me know otherwise via github.


message:
Function Millis() Arduino

I would like to make a countdown with arduino.
To do this I'm using the millis () function, but I have a problem, I can not reset this.
Reading on the internet I read that it is not possible to do this.
So how can I find an alternative for this?
In practice, when I pressed the button I started the countdown, while if I put it back, I went into the pause mode.

----------

    void inizio(){
      Serial.println("INIZIO");

      currentMillis1_general = millis();
      total_1 = currentMillis1_general - currentMillis_general;
      Serial.println(total_1);

      buttonState = digitalRead(buttonPin);
      if(buttonState == HIGH){
        step_funzione = 1;
        delay(200);
      }
    }

    void countdown(){
      Serial.println("COUNTDOWN");

      display.setBrightness(7);

      currentMillis_general = millis();
      total_general = currentMillis_general - total_1;

      if(total_general - previousMillis_general >= interval_general){
        previousMillis_general += interval_general;
        //previousMillis_general = currentMillis_general;
        m = new_tempo/60;
        s = new_tempo`;
        new_tempo--;
      }

      display.showNumberDec(m, true,2,0);
      display.showNumberDec(s, true,2,2);

      Serial.println(total_general);

      buttonState = digitalRead(buttonPin);
      if(buttonState == HIGH){
        step_funzione = 0;
        delay(200);
      }
    }

body: A way to accomplish "Reset" is to set your starting value equal to millis() again. To do the equivalent of "Pause", you need a pause counter. When you begin a pause, save millis() to `pauseTime`. When you resume running again, add `millis() - pauseTime` to your pauseCounter. Then your interval should not expire until `millis() - pauseCounter > Interval)`.


message:
Input voltage from circuit drops despite Arduino turned off

I'm using an Arduino Uno to emulate an old Atari disk drive as described here:
http://whizzosoftware.com/sio2arduino/

As both the Atari and the Arduino use 5V TTL serial communication, the hardware setup is pretty simple, RX and TX are crossed over, GND is connected an an additional line is used for status information.

All works fine when the Arduino is the only device connected to the Atari's serial port (called SIO). Since the SIO bus is a daisy-chain bus, I should be able to hook up serval devices after each other. However, once I connect an original floppy drive together with the Arduino, both the original floppy drive as well as the one emulated by the Arduino stop working.

What made me wonder is that the original drive couldn't be accessed even if the Arduino was turned off but the wiring left in place. Only after I removed the RX and TX pins from the connection, the original drive could be accessed.

I checked with a scope and realized that data transmission was still reaching both devices, however idle voltage was just around 2V instead of 5V. I then checked the resistance on the Arduino between the digital input pins as well as RX/TX in relation to GND and got (varying, depending on the scale I set my multimeter) values that probably have the effect of a voltage divider and thus reduced the voltage on the whole bus by about half.

I was thinking to add a resistor on the RX/TX lines coming from the SIO bus in order to maintain the voltage on the bus, but that would effectively mean that also less current reaches the Arduino RX/TX pins and might therefore render it useless if the voltage drops below the point where the Arduino can distinguish between logical high and low.

Or is there a way to circumvent these internal resitors between the digital inputs and GND? Does this have anything to do with the pull-up/pull-down resistors which I could probably only influence when the Arduino is on?

Thank you in advance for any pointers (other than adding another switch to physically remove RX/TX from the bus when the device is off ;) )!

body:
To protect the internals of integrated circuits many contain diodes at most input and output pins to VCC.  In normal operation where the voltage at these pins are not expected to become greater than VCC, these diodes are not in forward bias.  However, should the unexpected happen and the voltage at these pins does become higher than VCC the diodes are in forward bias.
 That is to say, the diodes try to keep the voltage at the pin no higher than VCC.

When you removed the power from the Arduino you essentially lowered VCC to zero.  This will likely forward biased the diodes inside the Arduino and drive the voltage at the pin toward zero.

There is a good discussion of this in [this Electrical Engineering StackExchange question & answer][1].

  [1]: https://electronics.stackexchange.com/questions/3675/why-is-it-important-not-to-exceed-vcc-at-the-input-to-a-logic-gate


body:
Although st2000 already answered my question, I still wanted to add how I solved the problem in case someone else faces the same situation:

What in the end worked for me was to add a 560 Ohm resistor each at the entry points of the RX/TX lines. This was low enough that the Arduino was still be able to distinguish logical high and low, and high enough that the SIO bus is still working when the Arduino is powered off. 470 Ohms was already too low to shield the SIO bus, 680 Ohms was too high for the Arduino to function properly when in use. I don't know if there is a way to calculate these values properly, but at least they work for me.


message:
Serial communication between a single Android device and multiple Arduino boards

I am thinking about a project, but I will need let's say two Arduino Uno. I can see that we can just use different USB ports on a PC, but what about an Android device?

I want to "run commands" from it on both Uno boards. Is it possible to connect it as it is single board, just both in parallel? I do not need communication between the boards, just with the smartphone.

For example, let's say that one of the boards will control a green LED and the other a red LED. I want to send from my phone on the serial "toggle green" or "toggle red" and both the boards will change the state of the LED connected to it accordingly to the "command" received. Will both boards be able to receive the "command"?

Thank you!

EDIT:
I see that I forgot to add that I may need to receive on the phone from any of the boards. Something like feedback.

body: Use a third Arduino, which serves as a hub. It is connected to your Android and to all Arduino Uno devices you want to interface. It passes the commands to all Arduino devices, and the feedbacks to the Android device. You could use for instance an Arduino Mega, with the Android on Serial0, and the Arduino Uno devices on Serial1 and Serial2.


message:
BMP280 seems to give odd pressure readings

I have connected an UNO with BMP280 and it sends reading through ESP-01 to thingspeak, and all seems working fine, but my pressure readings seem a bit odd.

To be clear any unchanged pressure reading is around 35.000 value.

As i understood that is in pascal, which is a bit strange, because the expected pascal value should be around 100.000

Code used is below, what am i missing ? Or are the readings ok?

Connection diagram and code used below:
[![connection diagram][1]][1]

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

        //ThingSpeak channel Key
    String statusChWriteKey = "asd";

    //Basic icludes
    #include <Wire.h>
    #include <SPI.h>
    #include <Adafruit_Sensor.h>
    #include <Adafruit_BMP280.h>
    #include <SoftwareSerial.h>
    SoftwareSerial EspSerial(6, 7); // Rx,  Tx
    #define HARDWARE_RESET 8

    #define BMP_SCK 13
    #define BMP_MISO 12
    #define BMP_MOSI 11
    #define BMP_CS 10

    Adafruit_BMP280 bme; // I2C

    int temperature = 0;
    int pressure = 0;
    int altitude = 0;

    // Variables to be used with timers
    long writeTimingSeconds = 17; // ==> Define Sample time in seconds to send data
    long startWriteTiming = 0;
    long elapsedWriteTime = 0;

    int spare = 0;
    boolean error;

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

      pinMode(HARDWARE_RESET,OUTPUT);

      digitalWrite(HARDWARE_RESET, HIGH);

      Serial.println(F("BMP280 test"));

      if (!bme.begin()) {
        Serial.println("Could not find a valid BMP280 sensor, check wiring!");
        while (1);
      }

      EspSerial.begin(9600); // Comunicacao com Modulo WiFi
      EspHardwareReset(); //Reset do Modulo WiFi
      startWriteTiming = millis(); // starting the "program clock"

    }

    void loop()
    {

      start: //label
      error=0;

      elapsedWriteTime = millis()-startWriteTiming;

      if (elapsedWriteTime > (writeTimingSeconds*1000))
      {
        readSensors();
        writeThingSpeak();
        startWriteTiming = millis();
      }

      if (error==1) //Resend if transmission is not completed
      {
        Serial.println(" <<<< ERROR >>>>");
        delay (2000);
        goto start; //go to label "start"
      }
    }

    /********* Read Sensors value *************/
    void readSensors(void)
    {
      temperature = bme.readTemperature();
      pressure = bme.readPressure();
      altitude = bme.readAltitude(1013.25);

    }

    /********* Conexao com TCP com Thingspeak *******/
    void writeThingSpeak(void)
    {

      startThingSpeakCmd();

      String getStr = "GET /update?api_key=";
      getStr += statusChWriteKey;
      getStr +="&field1=";
      getStr += String(temperature);
      getStr +="&field2=";
      getStr += String(pressure);
      getStr +="&field3=";
      getStr += String(altitude);
      getStr +="&field4=";
      getStr += String(spare);
      getStr += "\r\n\r\n";

      sendThingSpeakGetCmd(getStr);
    }

    /********* Reset ESP *************/
    void EspHardwareReset(void)
    {
      Serial.println("Reseting.......");
      digitalWrite(HARDWARE_RESET, LOW);
      delay(500);
      digitalWrite(HARDWARE_RESET, HIGH);
      delay(8000);//Tempo necessário para começar a ler
      Serial.println("RESET");
    }

    /********* Start communication with ThingSpeak*************/
    void startThingSpeakCmd(void)
    {
      EspSerial.flush();//limpa o buffer antes de começar a gravar

      String cmd = "AT+CIPSTART=\"TCP\",\"";
      cmd += "184.106.153.149"; // Endereco IP de api.thingspeak.com
      cmd += "\",80";
      EspSerial.println(cmd);
      Serial.print("sent ==> Start cmd: ");
      Serial.println(cmd);

      if(EspSerial.find("Error"))
      {
        Serial.println("AT+CIPSTART error");
        return;
      }
    }

    /********* send a GET cmd to ThingSpeak *************/
    String sendThingSpeakGetCmd(String getStr)
    {
      String cmd = "AT+CIPSEND=";
      cmd += String(getStr.length());
      EspSerial.println(cmd);
      Serial.print("sent ==> lenght cmd: ");
      Serial.println(cmd);

      if(EspSerial.find((char *)">"))
      {
        EspSerial.print(getStr);
        Serial.print("sent ==> getStr: ");
        Serial.println(getStr);
        delay(500);//tempo para processar o GET, sem este delay apresenta busy no próximo comando

        String messageBody = "";
        while (EspSerial.available())
        {
          String line = EspSerial.readStringUntil('\n');
          if (line.length() == 1)
          { //actual content starts after empty line (that has length 1)
            messageBody = EspSerial.readStringUntil('\n');
          }
        }
        Serial.print("MessageBody received: ");
        Serial.println(messageBody);
        return messageBody;
      }
      else
      {
        EspSerial.println("AT+CIPCLOSE");     // alert user
        Serial.println("ESP8266 CIPSEND ERROR: RESENDING"); //Resend...
        spare = spare + 1;
        error=1;
        return "error";
      }
    }

body:
It appears that you might be looking at a field 3 in Thingspeak instead of field 2...Here is why:

Do you live at a low elevation?  Here is why I ask that question.

This statement:

pressure = bmp.readPressure();

returns the pressure in **pascals** (sea level is 101325 pascals) from the BMP280 and assigns it to the variable pressure.

To get pressure in mb you would divide by 100 (a mb is = to 1 hPa or 100 Pascals).
If you were expecting a value of 100 (kPa?) perhaps that means you would be living near sea level.. perhaps about 100 feet (35m) or so.

If that is the case then the statement:

altitude = bmp.readAltitude(1013.25);

which ultimately feeds the Thingspeak field 3 the calculated altitude in meters (in this case about 35 meters).
Check and make sure you are looking at Thingspeak field 2 and not field 3 for pressure readings.

If you want to see pressure in mb change the line that reads pressure from the BME280 to the following:

pressure = bmp.readPressure()/100;


message:
`.readFileCounts()` not working on DFPlayer mini module

I just played around using a `MP3-TF-16P` module, aka `DFPlayer mini`. The library and the examples I used as a basis can be found [here][1].

My current setup contains a button (NC, normally closed), which is connected to Pin `D2` and has an interrupted attached to it. The button input is debounced by using a time difference inside the ISR. The code (based on [getStarted example][2]) can be found below.

Using the button to play the next song works as expected. However, when trying to get the total number of tracks located on the SD card by calling `Serial.println(player.readFileCounts())` as shown in the [FullFunction example][3] the board does neither print anything nor respond to any further commands. Even using the [FullFunction example][3] does not print anything.

Could someone please double-check this behaviour? Is this a module-related ore a library-related problem, since I am using a `MP3-FT-16P` module which might be a cheap clone of the original `DFPlayer mini` module? Does this work with other `MP3-FT-16P` modules out there meaning that mine is faulty?

    #include "stdint.h"
    #include "SoftwareSerial.h"
    #include "DFRobotDFPlayerMini.h"

    #define interruptPin 2
    #define softSerialRx 10
    #define softSerialTx 11
    #define debounceDelayMillis 1000

    volatile uint32_t lastInterruptTime = 0;
    volatile bool interruptOccured = false;

    SoftwareSerial softSerial(softSerialRx, softSerialTx);
    DFRobotDFPlayerMini player;

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

      pinMode(interruptPin, INPUT_PULLUP);
      attachInterrupt(digitalPinToInterrupt(interruptPin), interruptHandler, FALLING);

      Serial.println(F("Initing player ..."));
      // `player.begin(stream)` returns true when module is initialized
      if (!player.begin(softSerial)) {
        Serial.println(F("... failed"));
        while(true) {
          // never leave this loop since initialization went wrong
        }
      }
      Serial.println(F("... ready."));

      // volume: 0 ... 30
      player.volume(30);

      // when using `player.readFileCounts()` player module does not respond to further commands
      // Serial.println(player.readFileCounts());
    }

    void loop() {
      // read status messages from DFPlayerMini on its software serial port when available
      if (player.available()) {
        printPlayerStatus(player.readType(), player.read());
      }

      if (interruptOccured) {
        Serial.println("Button pressed");
        player.next();
        interruptOccured = false;
      }
    }

    void interruptHandler() {
     uint32_t interruptTime = millis();
     if (interruptTime - lastInterruptTime > debounceDelayMillis) {
       interruptOccured = true;
     }
     lastInterruptTime = interruptTime;
    }

    void printPlayerStatus(uint8_t type, uint16_t value){
      switch (type) {
        case TimeOut:
          Serial.println(F("Time Out!"));
          break;
        case WrongStack:
          Serial.println(F("Stack Wrong!"));
          break;
        case DFPlayerCardInserted:
          Serial.println(F("Card Inserted!"));
          break;
        case DFPlayerCardRemoved:
          Serial.println(F("Card Removed!"));
          break;
        case DFPlayerCardOnline:
          Serial.println(F("Card Online!"));
          break;
        case DFPlayerPlayFinished:
          Serial.print(F("Number: "));
          Serial.print(value);
          Serial.println(F(" Play Finished!"));
          break;
        case DFPlayerError:
          Serial.print(F("DFPlayerError: "));
          switch (value) {
            case Busy:
              Serial.println(F("Card not found"));
              break;
            case Sleeping:
              Serial.println(F("Sleeping"));
              break;
            case SerialWrongStack:
              Serial.println(F("Get Wrong Stack"));
              break;
            case CheckSumNotMatch:
              Serial.println(F("Check Sum Not Match"));
              break;
            case FileIndexOut:
              Serial.println(F("File Index Out of Bound"));
              break;
            case FileMismatch:
              Serial.println(F("Cannot Find File"));
              break;
            case Advertise:
              Serial.println(F("In Advertise"));
              break;
            default:
              break;
          }
          break;
        default:
          break;
      }
    }

  [1]: https://github.com/DFRobot/DFRobotDFPlayerMini
  [2]: https://github.com/DFRobot/DFRobotDFPlayerMini/blob/master/examples/GetStarted/getStarted.ino
  [3]: https://github.com/DFRobot/DFRobotDFPlayerMini/blob/master/examples/FullFunction/FullFunction.ino

body:
These DFPlayer modules are more difficult to drive than the examples suggest. Whenever you send a command to the DFPlayer (such as player.setVolume(30)) the module will return some sort of acknowledgement or a status command.  You need to be calling the player.available() method and then player.readType() and player.read() continually in loop() to keep the SoftwareSerial buffer free before you try sending commands. So calling player.setVolume(30) and then player.readFileCounts() in setup() may be overfilling the buffer before you start clearing it and the buffer will contain unread messages that are not the expected file count reply thus confusing the library. The other thing to consider is that it takes the module a second or two to initialise the SD card after .begin() and you really need to wait for the DFPlayerCardOnline status message to come in before you can ask for file counts.

I've written a more comprehensive library to drive these but it's not mature enough to share yet.


body: OK... For those who are looking for the answer, I found it in a complicated way, reading the library file. When the begin() task is executed, within the parameters, the COM port is required, but two more parameters are also allowed: ACK and doReset. Then begin(com_player, false, true); the ACK parameter blocks the responses of the serial parse.


body:
These worked for me:

int fileCounts = 0;

myDFPlayer.readFileCounts();
fileCounts = myDFPlayer.readFileCountsInFolder(0);

Serial.println(fileCounts);


message:
Noise when running Arduino close to analogue audio circuit

**TL;DR: My Arduino is injecting a lot of noise into an analogue audio circuit, even when not physically connected.**

I'm experimenting with using an Arduino as a low-frequency oscillator in audio circuits (modular synths, guitar effects etc).  I'm using an Arduino Uno powered with a USB + mains plug.

As a test I set up a simple circuit -- I don't believe the circuit matters much in this case but I'm including it here anyway:

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

<!-- End schematic -->

The Arduino is set up with one PWM pin supplying 0-5v, varying in a triangle wave (i.e. ramping slowly up, then slowly down again). This is connected to the JFET, which acts as a variable resistor. I have tested the analogue part of the circuit manually and it works as expected.

With the Arduino connected, however, the circuit produces a very loud "squishing" noise that swamps the audio signal passing through it, not unlike someone tuning an old short-wave radio. The noise "squishes" in time to the oscillation of the voltage.  It's not unlike the sound in this video associated with the PC power supply: [https://youtu.be/lXPJvSU8MwI?t=10m52s][1].

This happens even if I physically disconnect the PWM pin from the circuit -- the closer its wire is to the circuit, the louder the noise, but it's clearly audible even when they're separated by are a foot or more of air.

Things I've tried:

 - Tying the Arduino ground to the analogue circuit ground, and also keeping them separate.
 - Adding power filtering caps to both circuits.
 - Putting the Arduino in an aluminium box, grounded to either its own ground or the analogue circuit's, or both.
 - Powering the Arduino from my laptop instead of plugged directly into the mains.

The analogue circuit is on breadboard right now so some noise is expected, but this is far outside anything I've experienced before even with very badly-behaved circuits.

I'm FAR from knowledgeable about Arduino so my hope is that I'm doing something stupid and easily fixed. I would happily accept an answer that proposes an entirely different way to achieve the desired result.

  [1]: https://youtu.be/lXPJvSU8MwI?t=10m52s

body:
Arduino PWM signal is about 500Hz, so it will be audible (read: noise) by itself. You could implement a low-pass filter between the PWM pin and your J-FET. A simple RC filter tuned to 5Hz would attenuate a 500Hz signal to -40dB, which probably won't be enough for high quality audio. There are filters with better rejection properties which usually require active components to build. One of the simplest of such filters is the [Sallen-Key](https://en.wikipedia.org/wiki/Sallen–Key_topology) topology, which can practically double the rejection ratio using a signle active component (opamp).

Another option is to use a simple RC filter, but increase the the PWM frequency (as described [here](https://arduino.stackexchange.com/questions/3182/what-is-the-frequency-of-pwm-output-on-arduino)) to achieve high rejection ratio. Eventually, increasing the frequency past the audible range (about 16kHz) will ultimately resolve the noise problem, though I would still use an RC filter to keep the J-FET in linear mode. Apparently, the highest frequency you can achieve at full resolution is 62.5KHz, which is more than enough.


message:
Due: Write to digital pin when ADC is running

I have a problem writing to a digital pin on Arduino Due while my ADC is running.

I have the following code:

     #undef HID_ENABLED

    // Arduino Due ADC->DMA->USB 1MSPS
    // by stimmer
    // from http://forum.arduino.cc/index.php?topic=137635.msg1136315#msg1136315
    // Input: Analog in A0
    // Output: Raw stream of uint16_t in range 0-4095 on Native USB Serial/ACM

    // on linux, to stop the OS cooking your data:
    // stty -F /dev/ttyACM0 raw -iexten -echo -echoe -echok -echoctl -echoke -onlcr

    // source: https://gist.github.com/pklaus/5921022
    // applied patch 1 from: http://forum.arduino.cc/index.php?topic=137635.msg2526475#msg2526475
    // applied patch 2 from:  https://gist.github.com/pklaus/5921022 comment on Apr 2, 2017 from borisbarbour

    volatile int bufn,obufn;
    uint16_t buf[4][256];    // 4 buffers of 256 readings

    void ADC_Handler(){     // move DMA pointers to next buffer
      int f=ADC->ADC_ISR;
      if (f&(1<<27)){
       bufn=(bufn+1)&3;
       // patch 2 start
       //ADC->ADC_RNPR=(uint32_t)buf[bufn];
       ADC->ADC_RNPR=(uint32_t)buf[(bufn+1)&3];
       // patch 2 end
       ADC->ADC_RNCR=256;
      }
    }

    void setup() {
      SerialUSB.begin(0);
      while(!SerialUSB);

      pmc_enable_periph_clk(ID_ADC);
      adc_init(ADC, SystemCoreClock, ADC_FREQ_MAX, ADC_STARTUP_FAST);
      ADC->ADC_MR |=0x80; // free running

      ADC->ADC_CHER=0x80;

      NVIC_EnableIRQ(ADC_IRQn);
      ADC->ADC_IDR=~(1<<27);
      ADC->ADC_IER=1<<27;
      ADC->ADC_RPR=(uint32_t)buf[0];   // DMA buffer
      ADC->ADC_RCR=256;
      ADC->ADC_RNPR=(uint32_t)buf[1]; // next DMA buffer
      ADC->ADC_RNCR=256;
      // patch 1.2 start
      //bufn=obufn=1;
      bufn=1;
      obufn=0;
      // patch 1.2 end
      ADC->ADC_PTCR=1;
      ADC->ADC_CR=2;

      // this doesn't work:
      pinMode(52, OUTPUT); //
      digitalWrite(52, HIGH); //
    }

    void loop(){
      // patch 1.1 start
      while((obufn + 1)%4==bufn);// wait for buffer to be full
      // patch 1.1 end
      SerialUSB.write((uint8_t *)buf[obufn],512); // send it - 512 bytes = 256 uint16_t
      obufn=(obufn+1)&3;
    }

Pin 52 says 0 V.

With this function, I can pull the digital output voltage to 1.58 V:

    void digitalWriteDirect(int pin, boolean val){
      if(val) g_APinDescription[pin].pPort -> PIO_SODR = g_APinDescription[pin].ulPin;
      else    g_APinDescription[pin].pPort -> PIO_CODR = g_APinDescription[pin].ulPin;
    }

Any ideas?

body:
I found the problem: The Arduino had been waiting for the `SerialUSB` Connection.

The Serial connection has not been established because I was running the Arduino without running the corresponding Python script. That script would have opened the Serial connection.

When running the Python script, the Arduino Due then works as expected.


message:
To send data perpetually from multiple clients to a server using NodeMCU?

I am working on sending data from multiple clients to a server, all of which are NodeMCUs. I have been able to send data for a single iteration. Trouble arises when I want it to send data repeatedly so that if I update my client data, this new data should be reflected at the server as well.

Since I am using multiple clients, I have employed MAC addresses as the means of identifying the clients. This way, the signals received from a particular client are given as output to a particular pin.

To send data perpetually, I tried to use an infinite loop: `while(true)`, but it reads the first connected client even on recognizing the second client.

Here's my server code:

    #include <ESP8266WiFi.h>
    #define Max_Clients 5

    extern "C" {
      #include <user_interface.h>
    }

    WiFiServer server(80); //Initialize the server on Port 80
    WiFiClient *clients[Max_Clients] = {NULL}; //Initializing client(s)
    String inputs [Max_Clients] ={""}; //Initializing to store the string received from clients

    int32_t freq = 10000;

    IPAddress remoteIP();

    void setup() {
      pinMode(D1,OUTPUT); //Intializing pins for showing output and input
      pinMode(D2,OUTPUT);
      pinMode(D3,OUTPUT);
      pinMode(A0,INPUT);
      Serial.begin(9600); //Start communication between the ESP8266-12E and the monitor window
      analogWriteFreq(freq);
      WiFi.mode(WIFI_AP); //This ESP8266-12E is an AccessPoint
      WiFi.softAP("NodeMCU_js", "12345678"); //Provide the (SSID, password)
      IPAddress myIP = WiFi.softAPIP(); //Obtain the IP of the Server
      Serial.println("Server IP is: "); //Print the IP to the monitor window
      Serial.println(myIP);
      server.begin(); //Start the HTTP Server
    }

    void loop() {
      WiFiClient client = server.available(); //Check if a new Client has connected to the server
      unsigned char number_client;
      struct station_info *stat_info;
      struct ip_addr *IPaddress;
      IPAddress address;
      int k=0;
      if (client) {
        Serial.println("A new Client has connected :)");
       for (int i=0 ; i<Max_Clients ; ++i){ //Acknowledges and sets up new clients
        if (NULL == clients[i]){
          Serial.println(i);
          clients[i] = new WiFiClient(client); //nothing in clients[i] means it is a new client
          break;
        }
       }

       while (true){
        delay(3000);
        number_client = wifi_softap_get_station_num();
        stat_info = wifi_softap_get_station_info();
        Serial.println();
        Serial.print("Total connected clients are = ");
        Serial.print(number_client);
        Serial.println();
        while (stat_info != NULL){
          for(int i=0 ; i<number_client ; ++i)  { //For available clients
            if (NULL != clients[i]) {
              IPaddress = &stat_info->ip;
              address = IPaddress->addr;
              Serial.println();
              Serial.print("Client = ");
              Serial.print(i+1);
              Serial.println();
              Serial.print("Client IP Address = ");
              Serial.print(address);
              Serial.println();
              Serial.print("Client MAC Address = ");
              Serial.print(stat_info->bssid[0],HEX);
              Serial.print(":");
              Serial.print(stat_info->bssid[1],HEX);
              Serial.print(":");
              Serial.print(stat_info->bssid[2],HEX);
              Serial.print(":");
              Serial.print(stat_info->bssid[3],HEX);
              Serial.print(":");
              Serial.print(stat_info->bssid[4],HEX);
              Serial.print(":");
              Serial.print(stat_info->bssid[5],HEX);
              Serial.println();

              if (stat_info->bssid[0] == 0xDC && stat_info->bssid[1] == 0x4F && stat_info->bssid[2] == 0x22 && stat_info->bssid[3] == 0x17 && stat_info->bssid[4] == 0xEE && stat_info->bssid[5] == 0x95) {
                Serial.println("Compared MAC address successfully - 1 :)");
                String request1 = clients[i]->readStringUntil('\r');
                Serial.print("Client 1 asks: ");
                Serial.print(request1);
                inputs[i] = request1;
                int duty1 = request1.toInt();
                analogWrite(D1,duty1);
                clients[i]->flush();
                k++;
                clients[i]->print("From Central Server to Client 1 - 150\r");
              }

              if (stat_info->bssid[0] == 0xDC && stat_info->bssid[1] == 0x4F && stat_info->bssid[2] == 0x22 && stat_info->bssid[3] == 0x18 && stat_info->bssid[4] == 0x1F && stat_info->bssid[5] == 0x9D) {
                Serial.println("Compared MAC address successfully - 2 :)");
                String request2 = clients[i]->readStringUntil('\r');
                Serial.print("Client 2 asks: ");
                Serial.print(request2);
                inputs[i] = request2;
                int duty2 = request2.toInt();
                analogWrite(D2,duty2);
                clients[i]->flush();
                clients[i]->print("From Central Server to Client 2 - 200\r");
                k++;
                }

              if (stat_info->bssid[0] == 0xDC && stat_info->bssid[1] == 0x4F && stat_info->bssid[2] == 0x22 && stat_info->bssid[3] == 0x18 && stat_info->bssid[4] == 0xB && stat_info->bssid[5] == 0x71) {
                Serial.println("Compared MAC address successfully - 3 :)");
                String request3 = clients[i]->readStringUntil('\r');
                Serial.print("Client 3 asks: ");
                Serial.print(request3);
                inputs[i] = request3;
                int duty3 = request3.toInt();
                analogWrite(D3,duty3);
                clients[i]->flush();
                k++;
                clients[i]->print("From Central Server to Client 3 - 250\r");
              }

            if (k == 0){
                Serial.println();
                Serial.println("Client not recognised.");
              }

              stat_info = STAILQ_NEXT(stat_info, next);
              Serial.println();
            }
           }
          }
         }
        }
       } //void loop closure

Here's my client code:

    #include <ESP8266WiFi.h>
    #include <ESP8266HTTPClient.h>

    char ssid[] = "NodeMCU_js";
    char password[] = "12345678";

    WiFiClient client; // Creates a client that can connect to to a specified internet IP address and port as defined in client.connect()
    IPAddress server(192,168,4,1);

    void setup() {
      pinMode(A0,INPUT);
      pinMode(D6,OUTPUT);
      WiFi.persistent(false);
      WiFi.mode(WIFI_STA);
      Serial.begin(9600); //Serial connection
      WiFi.begin(ssid,password); //WiFi connection
      while (WiFi.status() != WL_CONNECTED) { //Wait for the WiFI connection completion
        delay(500);
        Serial.println("Connecting...");
      }
      Serial.println("Connected.");
      client.connect(server, 80);   // Connection to the server
    }

    void loop() {
      if(WiFi.status() == WL_CONNECTED){ //Check WiFi connection status
        while(true){
          int duty = analogRead(A0);
          client.print(String(duty)+"\r"); //Client's message to the server
          String answer = client.readStringUntil('\r'); //Reading response from the server
          Serial.print("Central Server: 200"); //Printing the response
          Serial.print(answer);
         }
       } else {
         Serial.println("Error in WiFi connection");
       }
    }

Kindly suggest a solution. Thanks in advance.

body:
It's vital that either `loop()` return or that you call `yield()` or `delay()` in your `loop()` handler.

Your client code as it's written doesn't do that.

You don't need the `while(true)` at all. Take it out and leave the body of it in the `if` statement. `loop()` will be continuously re-entered and your code will keep running. `loop()` is already an infinite loop.

Leaving `while(true)` inside `loop()` means that `loop()` never returns. When it doesn't return, the SDK doesn't get to perform certain housekeeping functions that are necessary for its proper operation. In particular, networking functions may stop working correctly, so your call to `client.readStringUntil()` may not work correctly.


body:
I found the error. The `if(client)` is to be closed before the `while(stat_info)` otherwise the loop will run only if it finds a new client.
It is running fine now. Thank you everyone for the suggestions. :)


message:
Communicating with magnetic sensor - TLV493D-A1B6 over I2C

I'm using the TLV493D-A1B6 sensor connected to an Arduino Uno: I've attached all necessary documentation at the bottom.

This is a 3D magnetic field position sensor that detects the magnetic field strength of a nearby magnetic field in the X, Y, and Z directions. I am NOT using the 2GO evaluation board. The sensor uses I2C protocol for communication.

I have this sensor all wired up, soldered correctly to a PCB with pinheadings, and ready to go on my breadboard.
Also, I am using a bidirectional logic level converter that is recommended for this sensor. I can confirm this as the I2C scanner sketch detects the sensor and prints out its expected defulat address.

Specifically, I am having trouble understanding the data sheets and how to setup Arduino using the 'Wire.h' library to communicate with the sensor over I2C to obtain the X, Y, Z RAW/decoded readings continuously.

I have tried code from this thread:
https://forum.arduino.cc/index.php?topic=419380.0
I have tried code from this dedicated tutorial for this sensor:
 https://www.allaboutcircuits.com/technical-articles/tutorial-and-overview-of-infineons-3d-magnetic-2go-kit/

I have even tried code from Github for this sensor:
https://github.com/IRNAS/TLV493D-3D-Magnetic-Sensor-Arduino-Library/blob/master/TLV493D/TLV493D.h

Using any of the above, I will get readings of "X=-1, Y=-1, Z=-1" or the sensor will output random readings of "255" and "0" when exposed to any magnet.

I've written my own code and have failed vigorously to get anything but random, clearly wrong readouts, this was my latest attempt, I chopped this code down for simplicity and clarity. I've also tried variations using the I2C.h master library, but no luck:

    #include "Wire.h"

    const int tlv_addr = 0x1F; // obtained by i2c scanner; all default address of tlv sensor - 0x1F, 0x5E, or 0x3E
    const int config_reg = 0x00; // I have scene this in other examples of code for this sensor, I cannot find the "configure" or "command register" address on any of its datasheets
    const int lp_mode = 0x05; //Have found this on the data sheet as the low power mode command
    // Note: I switched from const byte to const int for HEX assignments because I get a warning when compiling the sketch about this and I found online that this is the solution?

    void setup() {
      Wire.begin();   //join I2C bus
      Serial.begin(9600); //start Serial
      while(!Serial); //wait for Serial to be available

      Wire.beginTransmission(tlv_addr); //initiate communication with sensor
      Wire.write(config_reg); //set pointer/access configuration register
      Wire.write(lp_mode); //from what I read, the sensor defaults to power down mode on start up, so I send the low power mode command to the configure register to activate the sensor in low power mode which should cause it to start "sensing"
      Wire.endTransmission(); //end configurations
      delay(100); //delay to allow time for sensor the update
      Serial.print("Setup Complete\n\n");
    }

    void loop(){
      Wire.requestFrom(tlv_addr, 3); //request the 3 raw, UN-decoded bytes from the sensor's readings of X, Y, Z axes

      //---- Read in each byte of sensor data one by one for each axis ----//
      byte Bx = Wire.read(); //Have scene the "*" added to the beginning of the variable on a lot of code, not sure why this is necessary?
      byte By = Wire.read();
      byte Bz = Wire.read();

      //---- Print Out Sensor Axis Readings ----//
      Serial.println("X= ");
      Serial.print(Bx);       //Have also scene "&" added to the beginning of the variable on a lot of code like Serial.print(&Bx);?
      Serial.print("\tY= ");
      Serial.print(By);
      Serial.print("\tZ= ");
      Serial.print(Bz);

      //Expecting something like this: 01011011
      //Getting -1 or 255 or 0 randomly?

      delay(1000); //arbitrary delay
    }

And furthermore, I understand that these values needed to be decoded to make sense of the actual data, I have no idea what is going on the register map sheet and why they are shifting different bits of segments of each byte, seemingly like totally picking the bytes apart then reordering them, and then casting them as integers to get real data?

I am very new to Arduino and especially to I2C. If you could please help me understand especially what I'm missing from the data sheet, or what I'm doing wrong in the simplest of terms, I want to intuitively understand whats going on at every step so I can do this again with another I2C sensor on my own. If anyone could please help me with this.

_____________________________________________________________________________

sensor:
https://www.infineon.com/cms/en/product/sensor/magnetic-position-sensor/3d-magnetic-sensor/tlv493d-a1b6/

datasheet:
https://www.infineon.com/dgdl/Infineon-TLV493D-A1B6-DS-v01_00-EN.pdf?fileId=5546d462525dbac40152a6b85c760e80

Register Map:
https://www.infineon.com/dgdl/Infineon-TLV493D-A1B6_3DMagnetic-UM-v01_03-EN.pdf?fileId=5546d46261d5e6820161e75721903ddd

body:
In your code you read only the 3 first registers and write them to the variables `Bx` to `Bz`. These registers correspond to the correct magnetic values, but only the highest parts of them. The sensor measures 12-bit values - due to the higher precision - , but one register can only hold 8 bits. So the big 12-bit values are splitted into two parts. You will have to read all parts and put them together correctly to get meaningful results. Also the format of the values is a signed 12-bit value in two's complement, meaning that the decimal value is calculated by multiplying the value of the 12th bit with `-1`. You will have to convert this to a 16-bit two's complement for using the `int` type.

In the following part I will use the bitwise AND ( `&` ), the bitwise OR ( `|` ) and the bit-shifting operators ( `<<` and `>>`). I will only shortly explain, how to use them. If you are not familiar with them, please refer to a proper C/C++ tutorial, which can explain this in more detail than this answer.

 1. The bitwise AND will compair each bit of the left value with the corresponding bit of the right value. Only if both bits are `1`, the corresponding bit in the output will be `1`, `0` in every other case. I use it to mask some bits of the value away, effectively deleting these bits. Also note the different writing of literal values: In hexadecimal `0x0F` or binary `0b00001111`.
 2. The bitwise OR will work as the bitwise AND, but will put a `1` into a bit, when at minimum one of the corresponding input bits is `1`, and outputs `0` to this bit, if the input bits are both `0`. I use this, to put all bytes of one value together into one variable.
 3. The shifting operators `<<` and `>>` will shift the bit values to one side. The bits, that are getting out of the values range are lost. On the other side zeros get shifted into the value. I use it for the proper alignment in bytes of a bigger value.

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

This is the important figure from the user manual. It tells you, that you will find bits 11 to 4 of the Bx value in the first register (11 is the most significant bit). The rest of the Bx value is to be found in the 5th register in the 4 most significant bits (bits 3 to 0 of the Bx value). So to get the correct values, we first need to read all the data (I will include the temperature here):

    // Request 7 bytes from the sensor and return, if it didn't send enough (do not read, if there is nothing to read)
    if(Wire.requestFrom(tlv_addr, 7) < 7) return;
    // Read all registers to variables
    byte bx_high = Wire.read();
    byte by_high = Wire.read();
    byte bz_high = Wire.read();
    byte temp_high = Wire.read();
    byte bxy_low = Wire.read(); // This has to be read together. We will split the values later
    byte bz_low = Wire.read();
    byte temp_low = Wire.read();

Now we put together the splitted values in one variable each. To avoid complications with types, I use `unsigned int` here, which is like `byte`, but containing 16 bit. For `Bx` we have to shift the high part 4 bits to the left, since the lower part needs 4 bits of space. Also we have to seperate the lower parts of Bx and By. Since the lower part of Bx lies in the highest 4 bits of the read value, we need to shift them right for alignment with the least significant bit. The rest works similar, but is a bit easier. The temperature value uses another alignment, but the principle is the same.

    unsigned int bx_value = (bx_high << 4) | ((bxy_low & 0xF0)>>4);
    unsigned int by_value = (by_high << 4) | (bxy_low & 0x0F);
    unsigned int bz_value = (bz_high << 4) | (bz_low & 0x0F);
    unsigned int temp_value = (temp_high >> 4) | temp_low;

Now we have packed the 12-bit values into 16-bit unsigned integers. We now have to convert them to 16-bit signed integers. But if we simply cast them, this would result in false values, since the complemented bit here is the 16th, not the 12th like in the sensor. For solving this we use the answer from [this question][2]:

    int16_t Bx = (int16_t)(bx_value << 4) / 16 ;

There is one difference from the answer: We have a 12-bit two's complement, not a 14-bit one. So we have to shift 4 bits, not 2. This corresponds to dividing by 16 (a factor of 2 for each shifted bit).

Now you should have the correct measured values from the sensor.

---

You may have a second issue with your code. It read the registers every second, without regard to the state of the sensor. The datasheet says:

> This sensor does not incorporate shadow-buffers for readout. Thus, it
> is mandatory to read the sensor data not during a running conversion
> to avoid corrupted reads.

So you might also get garbled values because you sometimes read the registers during the sensor writes in them. This may be not a great issue here (maybe it only happens once in a while). But you can circumvent this problem by either using the INT pin of the sensor for triggering a I2C read operation (at best via an interrupt) or by configuring the sensor to run in the "Master Controlled Mode", where it only does a new measurement, when the old values have been read from the registers.

  [1]: https://i.stack.imgur.com/VsCKu.png
  [2]: https://stackoverflow.com/questions/34075922/convert-raw-14-bit-twos-complement-to-signed-16-bit-integer#34076866


message:
Data is not being written into SD card

I want to save the file as date and time  and I want to open the file `mySensorData = SD.open(filename, FILE_WRITE);` in the set up. It shows "insert SD card" when I try to open the file in setup.

The data is not being written into the SD card. It is creating the file but not writing into file.

body:
You start logging set to LOW and then test if it is high, since it isn't you go to the else clause, you call exit(0) and kill your processor, hence your code never gets executed!

    volatile boolean logging = LOW;

    ...

    void loop()
    {
       if(logging == HIGH) // starts low
       {
      ... // never executed
       }
       else
       {
     ... //
        exit(0); // now your Arduino is dead!
       }
    }

The ellipses (...) are where i snipped your code out.

exit(0) turns off interrupts and loops forever with while(1); which has the effect of a full, power-consuming halt; exit(0) should have a sleep call in it, because what exit(...) does isn't very useful for an Arduino!


body:
The problem was related to memory . So i commented some Serial.print commands and then it worked perfectly fine . I edit this part  of my code .

 else
   {
//    Serial.print(mySensorData);
//    Serial.println("Insert SD card for logging");
    digitalWrite(led_pin, LOW);
    lcd.clear();
    lcd.print("Insert SD card");
    delay(1000);
//
   }


message:
Traffic signal simulation: A minor doubt

I am trying to simulate a traffic signal with a provision of a pedestrian button, that when pressed, stops the traffic for a while. Here are the conditions I'm trying to meet,

One green LED (on pin 10) lit for 3 seconds (the first LED to light up).
- Then one orange LED (on pin 11) lit for 1 second
- Then finally one red LED (on pin 12) lit for 3 seconds.

Two-colour light (pedestrian)
- The pedestrian light is constantly red (red LED on pin 9) and only turns green (LED on pin 8) once the button (on pin 2) is pressed.

> **On button press** If the button is pressed while the car traffic light is green, the orange light is lit for 1 second, then the car
> lights turn red for 5 seconds during which the green pedestrian light
> is green.

After those 5 seconds, the pedestrian light turns red again and normal functioning resumes (car traffic light returns to green)

And here's my code for the same,

    int status=0;    //mode:state of button pin
    int buttonpin=2;//pin related to pushbutton
    void setup(){
      pinMode(10,OUTPUT);   //Green LED to pin10
      pinMode(11,OUTPUT);   //Orange LED to pin11
      pinMode(12,OUTPUT);   //Red LED to pin12
      pinMode(9,OUTPUT);    //Pedestrian Red on pin 9
      pinMode(8,OUTPUT);    //Pedestrian Green on pin 8
    }

    void loop(){

      digitalWrite(9,HIGH);//Pedestrian Red is on
      status=digitalRead(buttonpin);

      if (status==HIGH){
        digitalWrite(9,LOW); //pedestrian red is off
        digitalWrite(8,HIGH); //Pedestrian Green is on
        digitalWrite(11,HIGH);//orange lights up
        delay(1000);//1second delay
        digitalWrite(11,LOW);//orange shut off);
        digitalWrite(12,HIGH);//red starts
        delay(5000);//5 second delay
        digitalWrite(12,LOW);
        digitalWrite(9,HIGH);
      }
      else{
        digitalWrite(10,HIGH);//green lights up
      delay(3000);//3 second delay
      digitalWrite(10,LOW);//green shuts off
      digitalWrite(11,HIGH);//orange lights up
      delay(1000);//1second delay
      digitalWrite(11,LOW);//orange shut off);
      digitalWrite(12,HIGH);//red starts
      delay(3000);
      digitalWrite(12,LOW);//red shuts off
     }
    }

The problem is, the pedestrian button only works when it is already pressed at the time of Traffic Green starting(because of the if loop right there in code), but once Traffic green has already been green for say 1.5 seconds, it won't work as the if loop condition check has been already passed.
How can I mend my code to make the "On button Press" sequence explained above work at any time of the Green LED HIGH?

Attached is the circuit if the need be.
[![Traffic Circuit][1]][1]

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

Edited code is:

    #include <TimerOne.h>

    int status=0;    //mode:state of button pin
    int buttonpin=2;//pin related to pushbutton

    void setup(){

      pinMode(10,OUTPUT);
      pinMode(11,OUTPUT);
      pinMode(12,OUTPUT);
      pinMode(9,OUTPUT);
      pinMode(8,OUTPUT);

      Timer1.initialize(100000);
      Timer1.attachInterrupt( buttonCheck );

    }

    void loop(){

      digitalWrite(9,HIGH);
      status=digitalRead(buttonpin);

      digitalWrite(10,HIGH);//green lights up
      delay(3000);//3 second delay
      digitalWrite(10,LOW);//green shuts off
      digitalWrite(11,HIGH);//orange lights up
      delay(1000);//1second delay
      digitalWrite(11,LOW);//orange shut off);
      digitalWrite(12,HIGH);//red starts
      delay(3000);
      digitalWrite(12,LOW);//red shuts off

    }

    void buttonCheck(){

       if (status==HIGH){
        digitalWrite(9,LOW);
        digitalWrite(8,HIGH);
        digitalWrite(11,HIGH);//orange lights up
        delay(1000);//1second delay
        digitalWrite(11,LOW);//orange shut off);
        digitalWrite(12,HIGH);//red starts
        delay(5000);//5 second delay
        digitalWrite(12,LOW);
        digitalWrite(9,HIGH);
        return;
      }
    }

Will this work?

body:
The cause of the issue, is the way you have implemented `delay()` in your sketch. It's true that `delay()` should be avoided 99.9% of the time, but it does have it's uses.

If you start with the BlinkWithoutDelay example that comes with the Arduino IDE, then add a counter variable and a switch statement, you can easily get the traffic lights "part" of your requirements working.

Adding the pedestrian button functionality using non-blocking code is more difficult (for me it's more difficult), but it's a problem easily solved using `delay()`.

But what if you ever want your sketch to do more? What happens if you add another button to it? `delay()` is "blocking" code, so using it will probably "bite" you again if you try to add functionality to this sketch.

    const byte buttonPin = 2;
    byte secondsCounter = 0;
    byte trafficLightState = 0;
    unsigned long oneSecond = 1000;
    unsigned long previousMillis = 0;

    void setup(){
      pinMode(10, OUTPUT);   // Green LED to pin 10
      pinMode(11, OUTPUT);   // Orange LED to pin 11
      pinMode(12, OUTPUT);   // Red LED to pin 12
      pinMode(9, OUTPUT);    // Pedestrian Red on pin 9
      pinMode(8, OUTPUT);    // Pedestrian Green on pin 8
      // I used a wire from GND to "buttonPin" as a switch.
      pinMode(buttonPin, INPUT_PULLUP);
      Serial.begin(9600);
    }

    void loop(){

      // Get the current time.
      unsigned long currentMillis = millis();

      // If the button is pressed while the car traffic light is green,
      // the orange light is lit for 1 second, then the car lights turn
      // red for 5 seconds during which the green pedestrian light is green.
      if(trafficLightState == 0 && digitalRead(buttonPin) == LOW){
        digitalWrite(10, LOW);
        digitalWrite(11, HIGH);
        digitalWrite(12, LOW);
        digitalWrite(9, HIGH);
        digitalWrite(8, LOW);
        Serial.println("Button Pressed. Orange light ON for 1 second, Pedestrian red ON.");
        delay(1000);
        digitalWrite(11, LOW);
        digitalWrite(12, HIGH);
        digitalWrite(9, LOW);
        digitalWrite(8, HIGH);
        Serial.println("Red light ON for 5 seconds, Pedestrian green ON.");
        delay(5000);
        digitalWrite(11, HIGH);
        digitalWrite(12, LOW);
        digitalWrite(9, HIGH);
        digitalWrite(8, LOW);
        Serial.println("Pedestrian red ON.");
        trafficLightState = 0;
        secondsCounter = 0;
        currentMillis = millis();
      }

      // Update the traffic light state every second.
      if(oneSecondTimer(oneSecond, currentMillis) == 1){

        secondsCounter += 1;
        if(secondsCounter > 7){secondsCounter = 1;}

        // Green traffic light.
        if(secondsCounter == 1){
          trafficLightState = 0;
          Serial.println("Green traffic light ON for 3 seconds");
        }
        // Orange traffic light.
        else if(secondsCounter == 4){
          trafficLightState = 1;
          Serial.println("Orange traffic light ON for 1 second");
        }
        // Red traffic light.
        else if(secondsCounter == 5){
          trafficLightState = 2;
          Serial.println("Red traffic light ON for 3 seconds");
        }
      }

      // Turn the traffic lights on/off as required.
      switch(trafficLightState){

        // Turn the green traffic light ON, pedestrian red ON.
        case 0:
          digitalWrite(10, HIGH);
          digitalWrite(11, LOW);
          digitalWrite(12, LOW);
          digitalWrite(9, HIGH);
          digitalWrite(8, LOW);
          break;

        // Turn the orange traffic light ON, pedestrian red ON.
        case 1:
          digitalWrite(10, LOW);
          digitalWrite(11, HIGH);
          digitalWrite(12, LOW);
          digitalWrite(9, HIGH);
          digitalWrite(8, LOW);
          break;

        // Turn the red traffic light ON, pedestrian red ON.
        case 2:
          digitalWrite(10, LOW);
          digitalWrite(11, LOW);
          digitalWrite(12, HIGH);
          // Pedestrian green light ON ONLY if button was
          // pressed while the traffic light was green.
          // digitalWrite(9, LOW);
          // digitalWrite(8, HIGH);
          break;
      }
    }

    byte oneSecondTimer(unsigned long delayTime, unsigned long currentMillis){
      if(currentMillis - previousMillis >= delayTime){previousMillis = currentMillis;return 1;}
      else{return 0;}
    }


message:
What is xrotor micro 30A?

I was watching a video on how to build your own drone and this is one of the items. I tried to understand what it actually does but I couldn´t find any simple information.

I would like to know:
- what it does and
- if it could be replaced by an arduino

Thanks !!

Here is the video:
https://www.youtube.com/watch?v=bQib0sAhUc4

body:
The XROTOR MICRO is an ESC, which means Electronic Speed Control. It is essentially the motor driver in a quadcopter. Most quadcopter use brushless motors, because they are more fitted for the fast speeds of the propeller. But brushless motors aren't as easy to drive as simple DC motors. The current through the different coils has to be commutated depending on the current speed of the motor. The ESC does this for you and takes a PWM wave as input, whose duty cycle marks the requested speed. 30A is the current specification for this ESC. For more information google brushless motor.

> if it could be replaced by an arduino

Short answer: No.

Long answer: An ESC is a highly specialized device, which is very fast and drives high currents. It may be possible to build something like an ESC with an Arduino in it's heart, but this would be a dumb way to waste your time. The Arduino would be busy controlling the motor, so that it would not be able to do anything else. If you look at how many different peripherals the Arduino embodies, this is a total waste. Also the Arduino cannot drive these high currents by itself. You would have to add extra components to do this. If you are able to build this, it would be much bigger than a normal ESC.

All in all: If you aren't a crack in electronics and want to try this just for achieving, then you should simply buy an ESC for your drone project. Mostly Arduinos have vanished from modern drones, because there are many boards, that are better fitted for this.