text:
Programming NEMA 17 2 Phase, 4 Wire Stepper Motor
I have successfully programmed the Stepper Motor 28BYJ-48 with ULN2003 driver using the code below. But then I replaced the 28BJY-48 with a NEMA 17 Motor then it won't work anymore. I researched that the 28BJY-48 is a 4 phase stepper motor and the NEMA 17 is a 2 phase stepper motor. Is there a difference on how should I programmed a 2 phase stepper motor from a 4 phase stepper motor?
#define A        2                     // the pin connected to the wire A of the coil A (or to the H-bridge pin controlling the same wire)
#define A_bar    3                     // the pin connected to the wire A- of the coil A (or to the H-bridge pin controlling the same wire)
#define B        4                     // the pin connected to the wire B of the coil A (or to the H-bridge pin controlling the same wire)
#define B_bar    5                     // the pin connected to the wire B- of the coil A (or to the H-bridge pin controlling the same wire)
#define x        4000                  // smaller values may make the motor produce more speed and less torque
#define stepsPerRevolution 200         // you can the number of steps required to make a complete revolution in the data sheet of your motor

void setup() {
  pinMode(A, OUTPUT);
  pinMode(A_bar, OUTPUT);
  pinMode(B, OUTPUT);
  pinMode(B_bar, OUTPUT);
}

void loop() {
  for (int i = 0; i < (stepsPerRevolution/4) ; i++) {
    digitalWrite(A, HIGH);
    digitalWrite(A_bar, LOW);
    digitalWrite(B, HIGH);
    digitalWrite(B_bar, LOW);
    delayMicroseconds (x);

    digitalWrite(A, LOW);
    digitalWrite(A_bar, HIGH);
    digitalWrite(B, HIGH);
    digitalWrite(B_bar, LOW);
    delayMicroseconds (x);

    digitalWrite(A, LOW);
    digitalWrite(A_bar, HIGH);
    digitalWrite(B, LOW);
    digitalWrite(B_bar, HIGH);
    delayMicroseconds (x);

    digitalWrite(A, HIGH);
    digitalWrite(A_bar, LOW);
    digitalWrite(B, LOW);
    digitalWrite(B_bar, HIGH);
    delayMicroseconds (x);
  }

  /*// Counter Direction
  for (int i = 0; i < (stepsPerRevolution/4); i++) {
    digitalWrite(A, HIGH);
    digitalWrite(A_bar, LOW);
    digitalWrite(B, LOW);
    digitalWrite(B_bar, HIGH);
    delayMicroseconds (x);

    digitalWrite(A, LOW);
    digitalWrite(A_bar, HIGH);
    digitalWrite(B, LOW);
    digitalWrite(B_bar, HIGH);
    delayMicroseconds (x);

    digitalWrite(A, LOW);
    digitalWrite(A_bar, HIGH);
    digitalWrite(B, HIGH);
    digitalWrite(B_bar, LOW);
    delayMicroseconds (x);

    digitalWrite(A, HIGH);
    digitalWrite(A_bar, LOW);
    digitalWrite(B, HIGH);
    digitalWrite(B_bar, LOW);
    delayMicroseconds (x);
  }
  delay(1000);*/
}

I changed the stepsPerRevolution to 200 for NEMA 17 and 32 for the 28BJY-48. NEMA 17 does not work.

Is there a difference on how should I programmed a 2 phase stepper motor from a 4 phase stepper motor? .... it is up to you to research the differences between the two ... once you have the information, the solution may become obvious

You can’t use a ULN2003 to drive a bi-polar stepper motor.

I see that others used L293D, so I can use that with the same code?


text:
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?

Depends on the MCU in use.

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.

You do not want the pullup enabled if you are trying to accurately emulate an OC output.

@IgnacioVazquez-Abrams: Right. I edited my answer to address this very valid point.

Depending on the data rate it also may be good to write the pins PORT and DDR registers directly, which works way faster than usage of digitalWrite(). Though for slow communication it doesn't really matter.

Just to clarify, issuing those two commands will enable the pin to input and output a signal?  Correct?  Also, just for out of curiosity, could splitting the data pin between an input and output pin work as well?  Thanks.

@ATL_DEV: Yes, that's it. Splitting the data pin can work, but it will not make matters simpler, and it is essentially pointless.

source: Stack Exchange

license: Creative Commons - Attribution Share-Alike - https://creativecommons.org/licenses/by-sa/4.0/

sort: votes


text:
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

Can you post more details about the motor, for example link to data sheet.  Also, what driver you are using. If you are using PWM it should be straightforward to control the speed.

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.
This presents 2 problems.

The Arduino Mega PWM only gives you an adjustable voltage between 0V to 5V.
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.

simulate this circuit – Schematic created using CircuitLab

Looks super easy, would a IRFZ44N N-Channel MOSFET  work?

Without looking too deeply into it (which I recommend you do), it seems a good fit. The max voltage is 55V, tick. The max current is 49A, tick. The gate threshold is less than 4V, tick. 11A output at 5V gate voltage, tick. You may need to add an additional fly-back diode to handle back EMF - but that is more of a question for [electronics.se].

I am gonna do it tonight and check it works or not btw thanks for this helpful answer

all_licenses: Creative Commons - Attribution Share-Alike - https://creativecommons.org/licenses/by-sa/4.0/


text:
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.

println sends \r\n. read until \n. flush() waits until data are send. you do not send data from client. why do you use flush?

flush() is used for waiting till transmission is completed. It can be used at server or client.

you do not transmit from client. only receive.

I am receiving at the client, as per my client code. Is it recommended to remove flush() at the client?

So I removed the flush() from the client sie and used it at the server. The problem still persists.

and the \r\r\n?

Where do I update \r\r\n?

you have client.println(String(duty1)+"\r"); printLN adds \r\n

It worked! Thanks a lot, Juraj! Could you post it as the answer?

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.


text:
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);
  }
}

It may well be the bad soldering. Not short circuits, but dry joints and bad connections.

Okay, i will try it again then...

Add some flux to ease your soldering nightmare.

That PWM signal to control the contrast unsettles me.  At the very least, use a capacitor to smooth out the voltage.  If you google this technique most say not to do it and replace the PWM with a digital pot.  But, then, an analog pot would be much easier to implement.

It that water you are pumping around?  At the very least, get your electronics away from where water might collect in case of a plumbing failure.

I will add some flux then. That's a good idea. And yes, it is demi-water. So don't worry, it does not conduct electricity

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


text:
"Active LOW" relay board Pin configuration
I bought a 5 V Relay Board: LINK (Aliexpress) 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.

Is there a way I'm not seeing to get the Board to switch the Coil if a pin is set to high .... why would you want to change the board? .... changing the arduino sketch is way easier

yeah you're right I just thought about maybe some kind of "jumper" configuration or powering the whole board via an Arduino ping or stuff like this

I don't quite understand what kind of problem you expect. Could you draw a schematic and explain what you think could happen?

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.


text:
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

What sort of computer?  What OS?  You've left out a ton of detail here.

That's Java for you...

what battery backup?

@Majenko I doubt Java is to blame. One could write a busy loop in any language.

@DmitryGrigoryev Indeed, but Java makes it easier for dumbass programmers to write terrible code.

try restarting Ardunio and not compiling anything before using the serial plotter.

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.


text:
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!

Why do you need MQTT over serial. You can just send the number of the relay that should be turned on over serial?

That library is designed for the ESP32 which has substantially more power than the Mega2560.

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.

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.

Thank you @Lieven
It's a very nice project. Even the documentation is very useful. I already have my system set up but I will keep in mind serial2mqtt. I will definitely try it out.


text:
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%60;
    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);
  }
}

think about this ....How do you know when it is time to replace the oil in your car's engine? .... you cannot reset the odometer to zero

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).


text:
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 ;) )!

Let me know if you need a more formal answer.  But, in short, you can not connect  unpowered logic circuits inputs to powered logic circuits.

You could look at the atari 810 schematics and see how they did it: http://www.jsobola.atari8.info/dereatari/literatdere/810fsm.pdf

Thans for the link, Craig, I'll have a look at it.

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.

Thanks, the diodes would probably also explain the varying Ohm readings I got depending on the scale of my multi-meter.

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.


text:
Gyro not zero when returning to original position after random rotations
I am currently trying to make a self balancing robot. Making good progress but stumbled across an issue.
My gyroscope readings do not return to zero if I return in to its original position after random rotations around all 3 axes. Meaning rotation when all angles are not zero.
I am confident this issue is not caused by accuracy of the numerical integration as I have tried jerking the sensor incredibly hard around 1 axis, yet it still returns to 0 when rotated back.
I managed to get the gyro to return to zero when rotating around 1 axes when 1 angle is not zero. Meaning if Y is 45, and I rotate Z 90 degrees, I can transfer the Y angle to X, and once I return all angles back to zero individually, I can return to the original position. I've done this for all 3 pairs of angles (XY, XZ, YZ) and tried to add all 3 equations but the end result does not zero the gyro.
Anyone know any resources that I can look up on, or any idea of what the solution could be? Any help is appreciated.

what happens if your code reads and processes only one of the axes?

You mean to see if that axis returns to 0 after random rotations in all 3 axis? If it's just rotation in that axis, without my attempt to correct 2 axis, it will return to 0. The main issue I need fixed is when the vehicle is vertical, XYZ rotation is set to Z. As the vehicle tries to balance, it will end up rotating a bit as well because I don't have speed encoders yet. When it's tilted along Z and rotates around the vertical axis, the 0 of Z will shift, then the vehicle will try to maintain a forward tilt instead.

Which Arduino board, what sensor, which libraries, what sketch do you use? how is the sensor connected? I would try to jump out of this problem by buying another sensor and using other code. Perhaps even make a leap forward and use a bno055.


text:
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.

USB hub  . . .  ?

Yeah that could be possibility, but I want to run them as it is single. Isn't it possible?

let one arduino handle both leds. can't be far one from other if you have a usb connection

How do you connect a single Arduino to your phone now?

Juraj, I just give an example. I am going to use all the analog pins, so I will need more (and second chip will it be), I do not want PWM because they flicker on camera.
Dmitry Grigoryev, at this moment I have not used anything. I see that I can use data cable, and the arduino IDE from the appstore.
Thank you for the comments!

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.

That should do the trick. I was thinking the same but I did not know why should I waste the 40 digital pins on the Mega, But since that's the only case I will do it. Since it will be on my car, managing my headlights (going to add projectors) maybe I will manage to use them from something else..
Thanks again! : ]

You could use a smaller device like an Arduino Uno, with SoftSerial instead of S1/2.

authors: Кристиян Илиев


text:
Grounding analogue signals through ads1115
Quick question - I have some pretty expensive gas flow sensors outputting a 0-5V signal, which need at least 2.5 KOhms minimum load. Can I connect them to the Adafruit ADS1115 breakout (ADS1115 chip, Adafruit breakout board circuit, adafruit ferrite bead input impedance (or I think it is, pls correct me if I'm wrong))? If I put a 2KOhm resistor (for example) from the ADS1115 GND to the arduino ground, will that solve this issue, if it exists?
Many thanks for your help
EDIT: The flowmeter manual is here. It states the impedance of the 0-5V receiver should be greater than 2.5KOhms.

It is unclear if the 2500Ω "minimum load" is the minimum resistance value of a load it can have before the voltage starts to droop, or if it's the maximum allowed resistance to create the minimum required current flow.  The "load strength" is generally taken to be the inverse of the resistance (a "stronger" load has a lower resistance). A proper datasheet is needed.

the product webpage that you provided contains a link to customer service for asking questions ... i suggest that you contact them

OK, will do that and get back to you, cheers

@Majenko and jsotola, Hi I got it - it states the receiver impedance should be greater than 2.5KOhms.

@OliverWalters Ok, so since an ADC is typically hundreds of kΩ or even MΩ, that's not a problem.


text:
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:

    //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";
  }
}

the data sheet says that it reports the value in hPa (hectopascal)  ...... note: i just checked https://www.wunderground.com/ and it reports the atmospheric pressure in my area to be 950.9 hPa (which is 95090 Pa)

to start, test the sensor by removing all the code that has nothing to do with reading the sensor and print out the raw reading from the sensor

i have done that, loaded the basig example sketch onto the uno that comes with the BMP280 lib, with out any convesion it outputs the measured data, and it gives values inbetween 34.000 and 35.000. so it is not a wiring issue i believe, but suspect a faulty chip

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;


text:
Arduino ESP8266 Webserver SD
I connect Micro SD card adapter to my esp8266. I uploaded the SD webserver example sketch into the esp8266, everything works perfectly once I created index.htm, now I add LED to digital pin 4, now, how do I turn on and off LED with just a simple button inside the website?
Like anything I need to add inside the example sketch? Or using javascript inside the .htm file? I tried to figure out but it's just hard, I need some help. I'll be back in couple hours. Thank you.
ESP8266 Arduino IDE example sketch code:
#include <ESP8266WiFi.h>
#include <WiFiClient.h>
#include <ESP8266WebServer.h>
#include <ESP8266mDNS.h>
#include <SPI.h>
#include <SD.h>

#define DBG_OUTPUT_PORT Serial

const char* ssid = "(hidden)";
const char* password = "(hidden)";
const char* host = "esp8266sd";

ESP8266WebServer server(80);

static bool hasSD = false;
File uploadFile;

void returnOK() {
  server.send(200, "text/plain", "");
}

void returnFail(String msg) {
  server.send(500, "text/plain", msg + "\r\n");
}

bool loadFromSdCard(String path){
  String dataType = "text/plain";
  if(path.endsWith("/")) path += "index.htm";

  if(path.endsWith(".src")) path = path.substring(0, path.lastIndexOf("."));
  else if(path.endsWith(".htm")) dataType = "text/html";
  else if(path.endsWith(".css")) dataType = "text/css";
  else if(path.endsWith(".js")) dataType = "application/javascript";
  else if(path.endsWith(".png")) dataType = "image/png";
  else if(path.endsWith(".gif")) dataType = "image/gif";
  else if(path.endsWith(".jpg")) dataType = "image/jpeg";
  else if(path.endsWith(".ico")) dataType = "image/x-icon";
  else if(path.endsWith(".xml")) dataType = "text/xml";
  else if(path.endsWith(".pdf")) dataType = "application/pdf";
  else if(path.endsWith(".zip")) dataType = "application/zip";

  File dataFile = SD.open(path.c_str());
  if(dataFile.isDirectory()){
    path += "/index.htm";
    dataType = "text/html";
    dataFile = SD.open(path.c_str());
  }

  if (!dataFile)
    return false;

  if (server.hasArg("download")) dataType = "application/octet-stream";

  if (server.streamFile(dataFile, dataType) != dataFile.size()) {
    DBG_OUTPUT_PORT.println("Sent less data than expected!");
  }

  dataFile.close();
  return true;
}

void handleFileUpload(){
  if(server.uri() != "/edit") return;
  HTTPUpload& upload = server.upload();
  if(upload.status == UPLOAD_FILE_START){
    if(SD.exists((char *)upload.filename.c_str())) SD.remove((char *)upload.filename.c_str());
    uploadFile = SD.open(upload.filename.c_str(), FILE_WRITE);
    DBG_OUTPUT_PORT.print("Upload: START, filename: ");
    DBG_OUTPUT_PORT.println(upload.filename);
  } else if(upload.status == UPLOAD_FILE_WRITE){

    if(uploadFile) uploadFile.write(upload.buf, upload.currentSize);
    DBG_OUTPUT_PORT.print("Upload: WRITE, Bytes: ");
    DBG_OUTPUT_PORT.println(upload.currentSize);

  } else if(upload.status == UPLOAD_FILE_END){

    if(uploadFile) uploadFile.close();
    DBG_OUTPUT_PORT.print("Upload: END, Size: ");
    DBG_OUTPUT_PORT.println(upload.totalSize);
  }
}

void deleteRecursive(String path){
  File file = SD.open((char *)path.c_str());
  if(!file.isDirectory()){
    file.close();
    SD.remove((char *)path.c_str());
    return;
  }

  file.rewindDirectory();
  while(true) {
    File entry = file.openNextFile();
    if (!entry) break;
    String entryPath = path + "/" +entry.name();
    if(entry.isDirectory()){
      entry.close();
      deleteRecursive(entryPath);
    } else {
      entry.close();
      SD.remove((char *)entryPath.c_str());
    }
    yield();
  }

  SD.rmdir((char *)path.c_str());
  file.close();
}

void handleDelete(){
  if(server.args() == 0) return returnFail("BAD ARGS");
  String path = server.arg(0);
  if(path == "/" || !SD.exists((char *)path.c_str())) {
    returnFail("BAD PATH");
    return;
  }
  deleteRecursive(path);
  returnOK();
}

void handleCreate(){
  if(server.args() == 0) return returnFail("BAD ARGS");
  String path = server.arg(0);
  if(path == "/" || SD.exists((char *)path.c_str())) {
    returnFail("BAD PATH");
    return;
  }

  if(path.indexOf('.') > 0){
    File file = SD.open((char *)path.c_str(), FILE_WRITE);
    if(file){
      file.write((const char *)0);
      file.close();
    }
  } else {
    SD.mkdir((char *)path.c_str());
  }
  returnOK();
}

void printDirectory() {
  if(!server.hasArg("dir")) return returnFail("BAD ARGS");
  String path = server.arg("dir");
  if(path != "/" && !SD.exists((char *)path.c_str())) return returnFail("BAD PATH");
  File dir = SD.open((char *)path.c_str());
  path = String();
  if(!dir.isDirectory()){
    dir.close();
    return returnFail("NOT DIR");
  }
  dir.rewindDirectory();
  server.setContentLength(CONTENT_LENGTH_UNKNOWN);
  server.send(200, "text/json", "");
  WiFiClient client = server.client();

  server.sendContent("[");
  for (int cnt = 0; true; ++cnt) {
    File entry = dir.openNextFile();
    if (!entry)
    break;

    String output;
    if (cnt > 0)
      output = ',';

    output += "{\"type\":\"";
    output += (entry.isDirectory()) ? "dir" : "file";
    output += "\",\"name\":\"";
    output += entry.name();
    output += "\"";
    output += "}";
    server.sendContent(output);
    entry.close();
 }
 server.sendContent("]");
 dir.close();
}

void handleNotFound(){
  if(hasSD && loadFromSdCard(server.uri())) return;
  String message = "SDCARD Not Detected\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 += " NAME:"+server.argName(i) + "\n VALUE:" + server.arg(i) + "\n";
  }
  server.send(404, "text/plain", message);
  DBG_OUTPUT_PORT.print(message);
}

void setup(void){
  DBG_OUTPUT_PORT.begin(115200);
  DBG_OUTPUT_PORT.setDebugOutput(true);
  DBG_OUTPUT_PORT.print("\n");
  WiFi.mode(WIFI_STA);
  WiFi.begin(ssid, password);
  DBG_OUTPUT_PORT.print("Connecting to ");
  DBG_OUTPUT_PORT.println(ssid);

  uint8_t i = 0;
  while (WiFi.status() != WL_CONNECTED && i++ < 20) {//wait 10 seconds
    delay(500);
  }
  if(i == 21){
    DBG_OUTPUT_PORT.print("Could not connect to");
    DBG_OUTPUT_PORT.println(ssid);
    while(1) delay(500);
  }
  DBG_OUTPUT_PORT.print("Connected! IP address: ");
  DBG_OUTPUT_PORT.println(WiFi.localIP());

  if (MDNS.begin(host)) {
    MDNS.addService("http", "tcp", 80);
    DBG_OUTPUT_PORT.println("MDNS responder started");
    DBG_OUTPUT_PORT.print("You can now connect to http://");
    DBG_OUTPUT_PORT.print(host);
    DBG_OUTPUT_PORT.println(".local");
  }

  server.on("/list", HTTP_GET, printDirectory);
  server.on("/edit", HTTP_DELETE, handleDelete);
  server.on("/edit", HTTP_PUT, handleCreate);
  server.on("/edit", HTTP_POST, [](){ returnOK(); }, handleFileUpload);
  server.onNotFound(handleNotFound);

  server.begin();
  DBG_OUTPUT_PORT.println("HTTP server started");

  if (SD.begin(SS)){
     DBG_OUTPUT_PORT.println("SD Card initialized.");
     hasSD = true;
  }
}

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

Now my html code:
<!DOCTYPE html>
<html>
    <head></head>
    <body>
        <form>
            <input type="submit" name="TURNON" value="LED"/>
        </form>
    </body>
</html>

create a html form with action url directing to esp8266 and handle that url in the sketch. https://www.w3schools.com/html/html_forms.asp

https://babaawesam.com/2015/11/26/control-input-output-of-esp8266-with-ajax/

Tip: create a new server.on(...) for your new URL to react to the button press.

And which parameters should I set?

@SupBoy, the url parameter is yours, name it and set a value you want

you need to build a hardware-controlling micro API for your web page to hit using ajax or plain forms

Would you plz tell how to connect SD card module in node MCU pin.


text:
Reading data from Adafruit SGP30 Air Quality Sensor
I am trying to conect  Adafruit SGP30 Air Quality Sensor to arduino nano and get values from it,  but it seems that my code is not working properly. I followed instruction on the adafruit webpage, installed the Adafruit_SGP30 library and uploaded to my microcontroller.
But surprisingly when I open serial monitor text appears: SGP30 test,        but no data.
Does anybody know where I made mistake?
This is my code:
#include <Wire.h>
#include "Adafruit_SGP30.h"

Adafruit_SGP30 sgp;

void setup() {
Serial.begin(115200);
Serial.println("SGP30 test");

if (! sgp.begin()){
Serial.println("Sensor not found :(");
while (1);
}
Serial.print("Found SGP30 serial #");
Serial.print(sgp.serialnumber[0], HEX);
Serial.print(sgp.serialnumber[1], HEX);
Serial.println(sgp.serialnumber[2], HEX);
}

void loop() {
sgp.IAQmeasure();
Serial.print("TVOC "); Serial.print(sgp.TVOC); Serial.print("\t");
Serial.print("eCO2 "); Serial.println(sgp.eCO2);
delay(1000);
}

Did you run a i2c scanner? Do you have an other i2c sensor to check if the bus is working? Can you be more precise what the output is to the serial monitor? Is it only "SGP30 test"? then it might get stuck inside sgp.begin, that means the i2c bus is not working, perhaps shorted somewhere or the sensor module has no power.

Do you have pullup resistors on the I2C bus lines?

I have the same problem as yours.


text:
`.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.
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) 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 the board does neither print anything nor respond to any further commands. Even using the FullFunction example 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;
  }
}

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.

Tried to implement your suggestions, but without any success. Do you have some similar hardware available in order to try my code with your suggestions added to it?

These worked for me:
int fileCounts = 0;

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

Serial.println(fileCounts);

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.


text:
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:

simulate this circuit – Schematic created using CircuitLab
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.
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.

you can't make a triangel wave with pwm. it is always squares. a train of squares with different lengths of 0 and 1 level

@Juraj Fair point but I don't think the difference is material in this case, right? It fades an LED as if it were a varying DC voltage (I confess I don't really understand why this works, though).

a led can be fooled to act as it is a continuous voltage. a transistor can't

@Juraj That's very interesting -- so I guess I'd need to replace my FET with an LED/LDR combo. Thanks for enlightening me! Sadly the noise problem would still be a deal-breaker though.

use a DA converter module

@Juraj A LED can't be fooled by PWM, your eyes can. You simply stop seeing blinking past ~100Hz frequency.

@Juraj Because it's turned on half of the time.

The audio output is an AC signal. So it’s voltage will be below GND for about half the time. Are you sure you can use a JFET to switch negative voltages?

@Gerben Yes, I believe it's only shunting the +ve side of the audio to ground. Gives an audible result though -- good enough for a test (this circuit isn't the end product of course!)

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 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) 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.

Thanks for this suggestion. I'll try pushing the PWM frequency up above the audio range and see what effect that has. I suspect a filter on the input won't help as the noise seems to be radiated rather than limited to the circuit itself, but it can't hurt (and is probably good design practice anyway). I'll report back -- it may be later in the week before I get a chance to try it.

@helveticat Noise is "radiated" as long as you allow the J-FET to pick it up by leaving the gate floating. The filter will tie the gate to ground (via a capacitor), and it won't pick anything. Having the gate connected to the Arduino pin will also eliminate noise which is external to the circuit.

I had a chance to quickly try the RC network idea and got significant improvements, with both this and an LED/LDR combination replacing the JFET. Thanks for helping me out!


text:
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?

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.


text:
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.

why do you think there is a relation between client returned by the WebServer and client station number from soft AP?

One of my nodeMCUs is a server. I am not using any WebServer.

sorry WifiServer

wifi_softap_get_station_num() is a count of stations if I understand it correctly

Precisely. The number of clients connected to the server.

but all are connected to AP from setup()

I tested and does not work.

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. :)

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.

On removing the while(true), the program executes fine but does not run perpetually. I require this because the analogRead() signals will be changing and I want to observe the changes in the output without having to re-run the code.

There's something weird going on if it doesn't continue running.The whole purpose of loop() is to be called over and over again, in an infinite loop. Try doing some debugging, put some Serial.println()'s inside loop() to confirm what's actually happening. There is no way it will ever operate correctly if you have a while(true) inside loop().

Is there an alternative to while(true)? Any other way to create an infinite loop within the void(loop)? I've been through the program several times and am not finding any clues whatsoever.

loop() IS an infinite loop. If it's not, something is broken somewhere else.
Have you tried putting debugging Serial.println()s to confirm that you're not re-entering loop() after it returns? If something is so broken that loop() isn't reentering it's best not to make assumptions about what's running.
So something like:
void loop() {
Serial.println("entered loop");
if(WiFi.status() == WL_CONNECTED){ //Check WiFi connection status
Serial.println("wifi connected");
int duty = analogRead(A0);
...
(comments are too short to hold all the code)

I have done that. Loop never runs again.


text:
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

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.

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.
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.
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.

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:
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.

This a great help and a tremendous amount of clarity, thank you so much for your answer.


text:
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.

and the first line "Pressure, Temperature, Depth,Altitude" is in the file?

in setup you open "sensor1.txt" and in loop filename. test if (!mySensorData), not if (mySensorData==0)

Sorry! I just upload the new code.  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 .

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!

Sorry, I didn't get your answer. Would you please explain it to me .

@brar_kev I had stripped down the code to the structure so you can see; the first thing your loop does is check if (logging == HIGH) it was initialized it to LOW so flow goes to else clause, you do some stuff then you call exit(0) which halts the proccessor, the uC will not execute anymore instuctions until it is reset. so everything else never gets called.

But in the interrupts logging = ! logging .. so i'm making it low .. The code was working fine but when i added the RTC module then it stopped writing into the file. I checked when try to open the file in the set up the it shows iNSERT sd CARD AND  if i comment the open file section then it works . I'm  new to programming  and don't know how should i change it now .Thank for help

@brar_kev exit(0) disables interrupts, so your interrupt handler can't be executed either.

How should i proceed now ?  I'm stuck don't know what should i change to make it work

@brar_kev sorry if it wasn't obvious, but remove the exit(0) and see how it works then.

I removed that one and it still printing Insert SD card .

do the samples work? also SD.begin(4) should only be called once; remove it from the while loop in setup

I tried the Sd examples and they are working perfectly fine. I removed the SD.begin from while loop and it's still showing Insert Sd card. Thank you so much for help.

Anybody knows .. What should i do ?? I'm stuck

@brar_kev start with the sample, and add pieces to it until it works or something breaks, whatever breaks may tell you what is broken, or a better question to ask

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);
//
   }

Please list the lines that you had to comment out. Your answer may help someone with the same problem.


text:
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.

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?

Reconstruct your code by ditching all those delay() calls (using delay isn't a good idea in almost all situations). Instead use non-blocking code with the millis() function. Refer to the BlinkWithoutDelay example of the Arduino IDE for this. Also it will be good to learn, how to code a finite state machine (sounds more complex than it is). There are plenty tutorials on the web for this.

While I agree that completely non-blocking code is better, for this purpose you could say, you have a "flow" which you want to "interrupt", so have a look at "pin interrupts".

you need a state machine to manage this behavior model

@Paul I have used interrupts in my code and edited the answer, will this work?

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;}
}

this code doesn't work the way problem has been specified.

What's it doing differently?

In your original sketch and the new one you've added using TimerOne, you turn the Pedestrian Green light on the first time the button is pressed and then you leave it on until the Arduino is re-booted. I didn't see that listed as one of your requirements. Are you sure that's what you want to do? Have the Pedestrian Green light on regardless of the traffic light color?

What my aim is, when the traffic light is green, if the pedestrian button is pressed, it follows this sequence: 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. Then the pedestrian light turns red back again and traffic light resumes its normal functionality. This is the problem in my (and your) code.

What happens when you press the button when the traffic light is green using my sketch? Is the output in the serial monitor correct? One more thing to check would be to verify the button and LEDs are wired correctly.

Well, I ran your code a coupe of days ago on Tinkercad, I don't remember the exact output your code gave but certainly remember that it wasn't what I wanted. I reckon the wirings were correctly done, you should try your code on Tinkercad too.

I tried it on an Uno and it worked perfectly.


text:
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

What video?  I'm sure some contact would help.

this one https://www.youtube.com/watch?v=bQib0sAhUc4

And where in the video does it talk about this thing?  Do I have to watch the whole 16 minutes to help you?  I don't want to do that.  Please be a little considerate here.

Ok, don't help me then. Is that simple haha

Why don't you add a time stamp to the link, to set the video playing from exactly the correct point? You add &t=XXX to the end of the URL. Where XXX is the time in seconds. It's quite simple, and it would help people who have the same issue, from having to watch the whole video.

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.

Thanks you very much for that very complete answer! I appreciate it Chris !


text:
ESP8266 light sleep - can't wake up
I am attempting to implement a light sleep mode on an esp8266 (feather huzzah) which, when a button is pressed, wakes the system up so that it can continue its normal task.
I cobbled together some code from this post, which I've slightly modified:

#include <ESP8266WiFi.h>
#include <WiFiUdp.h>
#define WAKE_PIN 5

extern "C" {
    #include "gpio.h"
}

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

void setup(){
    Serial.begin(115200);
    Serial.println("Setup");

    pinMode(WAKE_PIN, INPUT_PULLUP);
    gpio_init(); // Init GPIO pins
}

void loop(){
    Serial.println("Do something...");
    Serial.println(digitalRead(WAKE_PIN));
    delay(500); //random delay for that stuff to be done

    if(!digitalRead(WAKE_PIN)){ //if we don't detect pin, sleep
        sleep();
    }
    delay(1000);

}

void sleep(){
    Serial.println("Going to sleep...");
    delay(10);
    wifi_fpm_set_sleep_type(LIGHT_SLEEP_T); // set sleep type
    gpio_pin_wakeup_enable(GPIO_ID_PIN(WAKE_PIN), GPIO_PIN_INTR_LOLEVEL);  //LO OR HI?
    wifi_fpm_open(); // Enables force sleep
    wifi_fpm_do_sleep(5000); //Sleep for short time
    delay(100);
    Serial.println("Woke up!");
}

Here is how I have things wired:

So the setup function works as expected, as well as "do something". The button reads high (1) when it is unpressed, and when I push it, it reads low (0) - which sends the ESP to sleep. In the serial monitor, I see:
Going to sleep...
Soft WDT reset

ctx: cont
sp: 3ffef7a0 end: 3ffef9a0 offset: 01b0

>>>stack>>>
3ffef950:  0001260d 00000600 3ffee970 4021fc84
3ffef960:  00001388 402020ba 402020b1 402020a1
3ffef970:  00000000 00000000 3ffee944 40202115
3ffef980:  3fffdad0 00000000 3ffee968 402027d4
3ffef990:  feefeffe feefeffe 3ffee980 40100710
<<<stack<<<

 ets Jan  8 2013,rst cause:2, boot mode:(1,6)

 ets Jan  8 2013,rst cause:4, boot mode:(1,6)

wdt reset

I'm not very experienced with Arduino or Electric Engineering, so I'm not exactly sure what is happening vs. what should happen, but this is my interpretation:
I read somewhere that reset causes are as follows:
reset causes:
    0:
    1: normal boot
    2: reset pin
    3: software reset
    4: watchdog reset

boot device:
    0:
    1: ram
    3: flash

In which case, if soft reset is considered light sleep for the esp, then the rst cause:2 is expected behavior, as it means it was triggered by pin 5. The rst cause: 4 i'm not sure about though - watchdog reset. Seems to be a protective mechanism for the device, in which case maybe the reset of this must coincide with the reset triggered by sleep mode and is normal? Or does it indicate a crash? In any case, I have no idea what all the stack stuff is, but the system does not restart - I cannot get any further readings from the serial monitor after this.
I'm not sure whether GPIO_PIN_INTR_LOLEVEL should be high or low - I couldn't find documentation on this (though I did see it in the [GPIO header source file] on git.5
I read something where someone else had a similar problem and someone made a reference to adding resistors and making sure GPIO 0 should be high, and 15 should be low. The link they posted was dead, but it made me think of something I read about deep sleep, in which you have to wire RST to 0. I actually tried running a wire between RST and holding to the #0 pad that's right by the USB port on the feather huzzah, and after that, the code would actually go to sleep, then wake itself up automatically and resume the normal loop function - but what I want is for only the button to wake up the ESP.
I'm stuck from here. Anyone have any ideas of what might be happening and how to fix it?

what does #include "gpio.h" do?

Includes the GPIO library which allows access to gpio_pin_wakeup_enable - as far as I know.

You can make the ESP8266 wake from deep sleep by just pulsing RST low briefly. Crudely you can just use your switch to connect it to GND perhaps with a pullup resistor to +v. If you want to be a bit more elegant you could use a small capacitor to smooth out the switch bounce so your code only restarts once. I use this on an ESP8266 that is solar-powered. Most of the time it is in deep-sleep. It wakes up, connects to MQTT and deep sleeps again only when the sensor it is monitoring changes state.