body:
I combined both the heart pulse sensor code and the DHT11 code. I can get a decent reading from the pulse sensor however an error is given from the DHT11 sensor. I am able to get them to function normally when i set them up individually however when i combine the 2 setups, I am unable to get a reading from the DHT11 although i can get one from the pulse sensor.

I am using ArduinoUNO, DHT11 humidity and temp sensor, and the Pulse Sensor.

THE CODE:

    #include <SimpleDHT.h>
    #define USE_ARDUINO_INTERRUPTS true    // Set-up low-level interrupts for most acurate BPM math.
    #include <PulseSensorPlayground.h>     // Includes the PulseSensorPlayground Library.

    //  Variables
    const int PulseWire = A0;       // PulseSensor PURPLE WIRE connected to ANALOG PIN 0
    const int LED13 = 13;          // The on-board Arduino LED, close to PIN 13.
    int Threshold = 550;           // Determine which Signal to "count as a beat" and which to ignore.
    const int pinDHT11 = 2;
    SimpleDHT11 dht11(pinDHT11);                               // Use the "Gettting Started Project" to fine-tune Threshold Value beyond default setting.
                      // Otherwise leave the default "550" value.

    PulseSensorPlayground pulseSensor;  // Creates an instance of the PulseSensorPlayground object called "pulseSensor"

    void setup() {

      Serial.begin(115200);          // For Serial Monitor
      // Configure the PulseSensor object, by assigning our variables to it.
      pinMode(2,INPUT);
    pinMode(A0,INPUT);

      pulseSensor.analogInput(PulseWire);
      pulseSensor.blinkOnPulse(LED13);       //auto-magically blink Arduino's LED with heartbeat.
      pulseSensor.setThreshold(Threshold);

      // Double-check the "pulseSensor" object was created and "began" seeing a signal.
       if (pulseSensor.begin()) {
        Serial.println("We created a pulseSensor Object !");  //This prints one time at Arduino power-up,  or on Arduino reset.
      }
    }

    void loop() {

     int myBPM = pulseSensor.getBeatsPerMinute();  // Calls function on our pulseSensor object that returns BPM as an "int".
                                                   // "myBPM" hold this BPM value now.

    if (pulseSensor.sawStartOfBeat()) {            // Constantly test to see if "a beat happened".
     Serial.println("♥  A HeartBeat Happened ! "); // If test is "true", print a message "a heartbeat happened".
     Serial.print("BPM: ");                        // Print phrase "BPM: "
     Serial.println(myBPM);                        // Print the value inside of myBPM.

      delay(20);                    // considered best practice in a simple sketch.
    }
     Serial.println("Sample DHT11...");

      // read without samples.
      byte temperature = 0;
      byte humidity = 0;
      int err = SimpleDHTErrSuccess;
      if ((err = dht11.read(&temperature, &humidity, NULL)) != SimpleDHTErrSuccess) {
      Serial.print("Read DHT11 failed, err="); Serial.println(err);delay(1000);
      return;

      Serial.print("Sample OK: ");
      Serial.print((int)temperature); Serial.print(" *C, ");
      Serial.print((int)humidity); Serial.println(" H");

      // DHT11 sampling rate is 1HZ.
      delay(1500);
      }
    }

title: I cant seem to form a code to read both DHT11 and pulse sensor

Answers: 0


body:
    int pirPin=2;
    int buzzerPin=12;
    int soundSensor = 19;
    int LED = 3;
    int statusSensor=0;
    int pirVal=0;
    void setup()
    {
    Serial.begin(9600);
    pinMode(pirPin, INPUT);
    pinMode(soundSensor, INPUT);
    pinMode(buzzerPin, OUTPUT);
    pinMode(LED, OUTPUT);
    }
    void loop()
    {
    pirVal=digitalRead(pirPin);
    if(pirVal==HIGH)
    {
    Serial.println("Motion Detected");
    digitalWrite(buzzerPin,HIGH);
    delay(150);
    digitalWrite(buzzerPin, LOW);
    }
    else
    {
    digitalWrite(buzzerPin, LOW);
     }
    statusSensor = analogRead(soundSensor);

      if (statusSensor == 1)
      {
    Serial.println("Sound Detected");
    digitalWrite(LED, HIGH);
    delay(100);
    digitalWrite(LED, LOW);
    }
      else
      {
        digitalWrite(LED, LOW);
      }
    }

title: how can I program my sound sensor and pir motion sensor in 1 arduino uno

Answers: 1

body:
First of all there is no pin with pin number 19 (as you defined a soundSensor on it), and there is no problem you can use my sound sensor and pir motion sensor in 1 arduino uno.

But in order to do that please use **millis** instead of **delay** so that your arduino doesn't wait to read reading of other sensor during the reading of first sensor.

Here is a link which shows how to use arduino for multitasking..

[https://learn.adafruit.com/multi-tasking-the-arduino-part-1/overview][1]

  [1]: https://learn.adafruit.com/multi-tasking-the-arduino-part-1/overview


body:
I am trying to read sensor data from two MPU9250s with both one Arduino Nano and a Arduino Nano 33 BLE using SPI. As for the Arduino nano, I was successful to acquire the sensor data and output it in the serial monitor. However, unlike the old Nano device, the new Nano 33 BLE does not output any sensor readings in its serial monitor. Sometimes and very rarely though, I do receive a couple of readings (usually not more than 1-2 readings), after which no readings are received. Apparently, at least the sensor initialization seems to be always working on the 33 BLE device as my code runs past the Sensor OK messages in the setup routine.

I have been using bolderflight's MPU9250 library for talking to the sensors.

I've also tried reading only one sensor at a time, but that didn't really help, as I still didn't receive sensor readings. I didn't try I2C so far, mainly due to a lack of time.

Any ideas of what to try or why things might have gone wrong are appreciated.

Here's my code:

    #include "MPU9250.h"

    MPU9250 SENSOR1(SPI, 9);
    MPU9250 SENSOR2(SPI, 10);
    int status1, status2;

    void setup() {
      // serial to display data
      Serial.begin(115200);
      while(!Serial) {}

      // start communication with IMU
      status1 = SENSOR1.begin();
      if (status1 < 0) {
        Serial.println("Sensor 1 error!");
        Serial.println(status1);
        while(1) {}
      }
      Serial.println("Sensor 1 OK");

      status2 = SENSOR2.begin();
      if (status2 < 0) {
        Serial.println("Sensor 2 error!");
        Serial.println(status2);
        while(1) {}
      }
      Serial.println("Sensor 2 OK");
    }

    void loop() {
      // read the sensor
      SENSOR1.readSensor();
      SENSOR2.readSensor();
      // display the data
      Serial.print("X: ");
      Serial.print(SENSOR1.getAccelX_mss(),6);
      Serial.print(" ");
      Serial.println(SENSOR2.getAccelX_mss(),6);
      Serial.print("Y: ");
      Serial.print(SENSOR1.getAccelY_mss(),6);
      Serial.print(" ");
      Serial.println(SENSOR2.getAccelY_mss(),6);
      Serial.print("Z: ");
      Serial.print(SENSOR1.getAccelZ_mss(),6);
      Serial.print(" ");
      Serial.println(SENSOR2.getAccelZ_mss(),6);
      delay(100);
    }

title: MPU9250 with Arduino Nano and Arduino Nano 33 BLE

Answers: 0


body:
So I've been playing with the esp8266 controller lately and today my Usb Host Mini came in that I wanted to connect. So for this I followed the following tutorial https://www.hackster.io/139994/plug-any-usb-device-on-an-esp8266-e0ca8a

The only thing is that I didn't do the following, because I wanted to see that it actually wouldn't work without damaging the Usb Host Mini.

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

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

Now I am wondering, because I didn't do that, and just went on with the wiring, did I actually kill my ESP8266 now? Whenever I remove all the wires, and just connect the ESP8266 to my computer, it just won't show up in the ports.

If I did kill it, what did I actually do here? Did I allow 5V to run through the board and did I fry it that way? If I would've actually made the cut shown above, would it have lived? (Because I think what the cut does, is it stops the 5V from going through the circuit.)

title: Did I kill my ESP8266?

Answers: 1

body:
Well if it doesn't work then it doesn't work so a safe bet is that chip is damaged.

I found [this document][1]. It states:

> **VBUS pad and jumber** can be used to provide 5V to VBUS. By default VBUS is connected to 3.3V; certain USB devices may have issue with
> this.

So I deduce that this is connected directly to 3.3V rail of the chip. Providing 5V without opening the jumper (cutting the trace) is the same as putting 5V at the 3.3V pin.

> **3.3V.** Power pin of the shield. Do not supply 5V to this pin - MAX3421E won't be able to detect devices on VBUS and may also be
> damaged!

Apparently the "proper" way of doing things is to actually unsolder that jumper or cut the trace.

Sorry.

  [1]: http://tet.pub.ro/pages/altele/Docs/Shield USB Host/USB Host Shield Hardware Manual « Circuits@Home.pdf


body:
I am writing an Arduino code to receive SMS from a SIM800 module and then send the same message back to the sender. My code is as follows:

    #include<SoftwareSerial.h>

    SoftwareSerial mySerial(9, 10);//Connect to pin 9&10 on GSM module

    const byte numChars = 128; //character size
    char receivedChars[numChars]; // Store data read from SMS
    boolean newData = false; //flag to check if new data has arrived

    void setup() {
     Serial.begin(9600);
     mySerial.begin(9600);
     Serial.println("<Arduino is ready>");
     mySerial.println("AT");
     mySerial.println("AT+CMGF=1"); //text mode
     mySerial.println("AT+CNMI=1,2,0,0,0");
     mySerial.println("AT+CSQ"); //Check signal strength
       while (Serial.available())
      {
        mySerial.write(Serial.read());//Forward what Serial received to Software Serial Port
      }
      while(mySerial.available())
      {
        Serial.write(mySerial.read());//Forward what Software Serial received to Serial Port
      }
    }

    void loop() {
      //code for checking sms
      scanSMS();
      //Print if a new data arrived
      showNewData();
      delay(25000);
    }

    void scanSMS() {
        static boolean recvInProgress = false;
        static byte ndx = 0;
        char startMarker = '#'; //Start and end markers. Eg. SMS body will be sent as #status#
        char endMarker = '#';
        char rc;
        while (Serial.available())
        {
          mySerial.write(Serial.read());//Forward what Serial received to Software Serial Port
        }

        while (mySerial.available() > 0 && newData == false) {
          Serial.write(mySerial.read());//Forward what Software Serial received to Serial Port

          rc = mySerial.read();

          if (recvInProgress == true) {
            if (rc != endMarker) {
              receivedChars[ndx] = rc;
              ndx++;
              if (ndx >= numChars) {
                ndx = numChars - 1;
              }
            }
            else {
              receivedChars[ndx] = '\0'; // terminate the string
              recvInProgress = false;
              ndx = 0;
              newData = true;
              }
            }
          else if (rc == startMarker) {
            recvInProgress = true;
          }
        }
    }

    /*PRINT IF THERE IS A NEW DATA*/
    void showNewData() {
     if (newData == true) {
       SendMessage(receivedChars);
     newData = false;
     }
    }

    /*SEND BACK WHATEVER SMS IS RECEIVED*/
    void SendMessage(String receivedChars)
    {
      Serial.print("here");
      mySerial.println("AT+CMGS=\"+xxxxxxxxxx\"\r"); // Replace x with mobile number
      mySerial.println("Humidity Alert!");// The SMS text you want to send
      mySerial.print(receivedChars);
       mySerial.println((char)26);// ASCII code of CTRL+Z
    }

The issue is that the module seems to receive only alternate characters instead of the whole message. For example, if I send the text #program#, the Arduino will only print porm or rga. Am I missing something here? Any help is highly appreciated.

title: Arduino accepting only alternate characters

Answers: 1

body:
You wrote:

```c++
Serial.write(mySerial.read());
rc = mySerial.read();
```

Here you are calling `mySerial.read()` twice, and thus reading two
characters from the port's input buffer. You then forward the first
character through `Serial`, and process the second one. Note that you
should normally not read two characters unless you have tested that
`mySerial.available() >= 2`.

You probably want to forward and process one character at a time, thus
only call `mySerial.read()` once within this loop:

```c++
rc = mySerial.read();  // read from mySerial
Serial.write(rc);      // forward through Serial
// now process rc
```


body:
TL;DR: I tried to have a random fading pattern on several leds and it leads to flickering.

Edited following @chrisl answer.

I am in the process of creating a simple lamp that show some light patterns using 6 led and an arduino uno. The goal is that depending on some inputs and a bit of randomisation, the patterns will change. For instance, only 2 lights at the same time but fading up and down randomly on all 6 led. Or 4 lights fading up and down randomly on the 6 leds.

I decided to create a struct that would be a light pattern named a particle, and this particle have a variable named led_position that shows which led it is on at a certain moment. The particle can change its position to light up an other led.

I know this is not the clearest of explanation but I hope my code will be more straightforward:

Main code
        #include "MyTypes.h"

    int led1 = 9;    // the PWM pin the LED is attached to
    int led2 = 10;
    int led3 = 11;
    int led4 = 6;
    int led5 = 3;
    int led6 = 5;

    //int led;
    int brightness;
    int fadeAmount;

    // Definition of the different particles
    particle_type particle[]={
      { 0,led1,0, 2,   false },
      { 1,led2,50, 2,   false },
      { 2,led3,100,  2,   false },
      { 3,led4,80,  2,   false },
      { 4,led5,30,  2,   false},
      { 5, led6,70,  2,   false},
    };

    led_type led[]={
      { 3,false },
      { 5,false },
      { 6,false },
      { 9,false },
      { 10,false },
      { 11,false },
    };

    //initiation of the particles

    void initiate_particle(particle_type& particle_example,led_type led[]){

     //take a random led from list of led
      int number=random(5);
      led[number];
      if (led[number].busy == false){ //if led non-occupied
        particle_example.led_position=led[number].led_position;
        led[number].busy = true ;//take this led as output
        }

      else{
    //    particle_example.led_position=particle_example.led_position; //keep same led
      }

      particle_example.reset = false; //reset turned off
     // delay(30);

    }

    void update_light(particle_type& particle_example,led_type led[]){ //updating led brightness

      analogWrite(particle_example.led_position, particle_example.brightness);  //updating led brightness
      if (particle_example.brightness >=  160) {
        particle_example.fadeAmount = -particle_example.fadeAmount;

      }

      if (particle_example.brightness <=  160 && particle_example.brightness >=  100 ) {
        particle_example.brightness = particle_example.brightness + 2*particle_example.fadeAmount;

      }

      if (particle_example.brightness >= 50 && particle_example.brightness <=  100){
          particle_example.brightness = particle_example.brightness + particle_example.fadeAmount;

      }

      if (particle_example.brightness >= 0 && particle_example.brightness <=  50){
          particle_example.brightness = particle_example.brightness + 0.5*particle_example.fadeAmount;

      }

      if (particle_example.brightness <= 0){
        particle_example.reset= true;
        int number = particle_example.led_position;
        led[number].busy=false;
        particle_example.fadeAmount = -particle_example.fadeAmount;
      }

    }

    void activate_particle(particle_type& particle_example,led_type led[]){ //function to keep led activated

      if (particle_example.reset==true){ //if led not initiated or has finished its dimming down
        initiate_particle(particle_example, led); //initiate it again
      ;}

      else {
       update_light(particle_example,led); //update its brightness
      }
    }

    void setup() { //create led outputs

      pinMode(led1, OUTPUT);
      pinMode(led2, OUTPUT);
      pinMode(led3, OUTPUT);
      pinMode(led4, OUTPUT);
      pinMode(led5, OUTPUT);
      pinMode(led6, OUTPUT);
      Serial.begin(9600); //serial for debug

    }

    void loop() {

      activate_particle(particle[0],led);
    //  activate_particle(particle[1],led);

    //  activate_particle(particle[2],led);
    //  activate_particle(particle[3],led);
    //  activate_particle(particle[4],led);
    //  activate_particle(particle[5],led);
    //

     delay(5); // 20-17-15-12-10-7-2

    }

Mytypes.h

    typedef struct {
        int id;
        int led_position;
        int brightness;
        int fadeAmount;
        bool reset;
    } particle_type;

    typedef struct {
        int led_position;
        bool busy;
    } led_type;

This seems to work more or less but I still have the problem of particles "choosing" the same led to light up and it make the led flickers.

I am struggling on this. I have tried to add a data field for busy and create a new struct for led to no avail.

Even when only one particle is on, the different leds seems to deactivate after a few rounds.

Let me know if you figure it out, thanks!

EDIT 2:

        #include "MyTypes.h"

    int led0 = 3;    // the PWM pin the LED is attached to
    int led1 = 5;
    int led2 = 6;
    int led3 = 9;
    int led4 = 10;
    int led5 = 11;

    //int led;
    int brightness;
    int fadeAmount;

    // Definition of the different particles
    particle_type particle[]={
      { 0,led0,0, 4,   false },
      { 1,led1,50, 4,   false },
      { 2,led2,100,  4,   false },
      { 3,led3,80,  4,   false },
      { 4,led4,30, 4,   false},
      { 5,led5,70,  4,   false},
    };

    led_type led[]={
      { 3,false },
      { 5,false },
      { 6,false },
      { 9,false },
      { 10,false },
      { 11,false },
    };

    //initiation of the particles

    void initiate_particle(particle_type& particle_example,led_type led[]){

     //take a random led from list of led
      int number=random(6);
      Serial.println(number);
      led[number];
      if (led[number].busy == false){ //if led non-occupied
        for (int i=0;i<6;i++){
          if (led[i].led_position==particle_example.led_position){
          led[i].busy=false;
          Serial.println("success");
          Serial.println(led[i].led_position);
          }
        }
        particle_example.led_position=led[number].led_position;
        Serial.println(particle_example.led_position);
        led[number].busy = true ;//take this led as output
        particle_example.reset = false; //reset turned off
        }

      else{
    //  initiate_particle( particle_example,led);
    }

      delay(30);

    }

    void update_light(particle_type& particle_example,led_type led[]){ //updating led brightness
          analogWrite(particle_example.led_position, particle_example.brightness);  //updating led brightness

      if (particle_example.brightness >=  160) {
        particle_example.fadeAmount = -particle_example.fadeAmount;
        particle_example.brightness = particle_example.brightness + 2*particle_example.fadeAmount;
      }

      else if (particle_example.brightness <  160 && particle_example.brightness >=  100 ) {
        particle_example.brightness = particle_example.brightness + 1.5*particle_example.fadeAmount;

      }

      else if (particle_example.brightness > 50 && particle_example.brightness <=  100){
          particle_example.brightness = particle_example.brightness + particle_example.fadeAmount;

      }

      else if (particle_example.brightness > 0 && particle_example.brightness <=  50){
          particle_example.brightness = particle_example.brightness + 0.25*particle_example.fadeAmount;

      }

      else if (particle_example.brightness <= 0){
        particle_example.reset= true;
        particle_example.brightness =0;
        int number = particle_example.led_position;

        if (particle_example.fadeAmount<0){
          particle_example.brightness = 0;
          particle_example.fadeAmount = -particle_example.fadeAmount;
        }
        else{
          particle_example.brightness = particle_example.brightness + 0.5*particle_example.fadeAmount;
        }

      }

    }

    void activate_particle(particle_type& particle_example,led_type led[]){ //function to keep led activated

      if (particle_example.reset==true){ //if led not initiated or has finished its dimming down
        initiate_particle(particle_example, led); //initiate it again
      ;}

      else {
       update_light(particle_example,led); //update its brightness
      }
    }

    void setup() { //create led outputs
      pinMode(led0, OUTPUT);
      pinMode(led1, OUTPUT);
      pinMode(led2, OUTPUT);
      pinMode(led3, OUTPUT);
      pinMode(led4, OUTPUT);
      pinMode(led5, OUTPUT);

      Serial.begin(9600); //serial for debug

    }

    void loop() {

      activate_particle(particle[0],led);
      activate_particle(particle[1],led);
      activate_particle(particle[2],led);
    //  activate_particle(particle[3],led);
    //  activate_particle(particle[4],led);
    //  activate_particle(particle[5],led);
    //

     delay(10); // 20-17-15-12-10-7-2

    }

    void loop() {

      activate_particle(particle[0],led);
      activate_particle(particle[1],led);
      activate_particle(particle[2],led);
      activate_particle(particle[3],led);
    //  activate_particle(particle[4],led);
    //  activate_particle(particle[5],led);
    //

     delay(10); // 20-17-15-12-10-7-2

    }

Now the code works well up to 3 particles but messes things up for 4,5,6 particles with flickering and absence of light.

title: Multi dimming led - figuring out which led is available for dimming

Answers: 1

body:
That seems like a logic problem for me. You define a "particle", which is not bound to a special LED (like a particle, that is jumping from one position to another). Then you included a busy flag, that should prevent, that a LED is used by more than one particle at a time. But you included this flag in the particle. Being busy is a state of the LED, not of the particle, so including this in the particle won't do, what you want.

If you want to use this logic, you need to create a struct, which represents the individual LED. The struct's fields would be the pin number and the busy flag. You can create the LED list with instances of this struct. Then to choose a new position for the particle, you need to check if the busy flag of that position is set. If not, choose this position and set the busy flag. Clear the flag, when you remove the particle from the position.

---

After your edit I see more problems. First a general problem: Currently a new particle, that want's to change it's position, needs a free (not busy) position to move to. You have 6 LED positions, so with 6 particles, there won't be any move. You can change this by freeing a LED position (setting it's busy flag to false), when the fading of a particle is finished. Still there might be timing problems with this way, depending on the overall timing behavior of the sketch (The first particle to free a LED position will not find a different free position and has to wait. This might lead to 2 particles just exchanging there positions).

Then in `void update_light()` you have multiple if statements, which all test the particles brightness. But inside these statements you change the brightness. So it is possible, that multiple of the if statements will execute. You should use `if else if` instead, so that only one of the statements can execute.

And in `void initiate_particle()` you check for the chosen LED position to be busy. But if the position is already busy, you are setting the particles `reset` flag to false anyway. That means that `activate_particles()` will update the particles brightness despite the fact, that the particles does not have a valid LED position currently. You should not set `reset` to false, if the particles hasn't got a valid LED position. And the delay at the end of the initiate function does not serve a function in my eyes.


body:
So I'm planning to build a sort of light switch for my Philips Hue bulbs with an Arduino. This project will be mounted on a shelf next to my door to the room, parallel to the walking direction. In order to detect the movement direction to either turn on or off the lights when a person is entering or leaving the room, I need one or two sensors. I've tried HC sr04 before but got inaccurate results which resulted in random changes of the lightstate.

So what sensors will be best for my application? I was thinking about the Sharp IR sensors (i.e. Sharp GP2Y0A60SZLF) but I'm not sure about any possible interference that comes with it when I mount to of these right next to each other. Any ideas?

Thanks in advance!

title: Which sensors to choose to detect movement direction

Answers: 2

body:
1. I guess you want to use 2 IR sensors with a little distance, so that you can check the direction by checking, which one detected an object first. You surely can do this with the mentioned sensor. To avoid interference, you can measure by one one, deactivating the other over it's enable pin during that time. It should be fast enough, so that you can do this sufficiently.

2. I would say using a distance sensor is overkill here. For checking, if someone comes in or out, you don't need distance information. Just 2 light barriers would be sufficient. For example a little laser pointer (could also be IR), a little mirror at the other side and a fitting photodiode. I think there are ready made modules to buy. Their output would only be digital, not analog.

body:
The PIR sensors can work in your case. They are passive and detect only moving objects that emit IR radiation. So anything that's hotter than background like people, cats, dogs but not doors.

The raw sensor looks like this:

[![PIR sensor][1]][1]

But it's usually available as a part of an IC that includes a plastic lens that focuses IR rays from broader area on the sensor.

[![PIR IC][2]][2]

Remove that lens (or not) and add something made of cardboard to limit the area that sensor sees and you have a directional sensor that detects moving hot things.

Technically you can completely hack the raw sensor and get info if the hot object is moving left or right. Read [this article][3] and look at the sensor response graph.

  [1]: https://i.stack.imgur.com/4jTjV.png
  [2]: https://i.stack.imgur.com/wArQ9.png
  [3]: https://learn.adafruit.com/pir-passive-infrared-proximity-motion-sensor/how-pirs-work
  [4]: https://www.youtube.com/watch?v=x8vmd3DkzDg


body:
I'm trying to  run an Arduino code that simultaneously:
1) blinks an led on-off every 3 seconds
2) gets a voltage input from an EMG sensor and positions a servo motor accordingly

While I run this program, I'd like to plot the following on the same graph
1) LED status on/off printed as 600 if on and 0 if off
2) EMG value being fed to the arduino
3) The angle the Arduino is sending to the servo motor

I wrote the following code which works to an extent but the problem I'm facing is, I only get two graphs on the plotter instead of 3, I think the EMG value and the angle have combined into a single line as seen in this picture:

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

However, if I remove the angle print statement, I get a proper graph for the other 2 as this:

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

How do I change my code so I can plot all three separately?
Thanks in advance.

```c++
#include <Servo.h>
Servo myservo;
const int ledPin =  LED_BUILTIN;
int ledState = LOW;
unsigned long previousMillis = 0;
const long interval = 3000;
int led=0;
int servovalue=0;
void setup() {
  Serial.begin(9600);
  myservo.attach(9);
  pinMode(ledPin, OUTPUT);
}

void loop() {
  int sensorValue = analogRead(A0);
int angle = map(sensorValue, 0, 1023, 0, 180);
myservo.write(angle);
Serial.print(sensorValue);
Serial.print(“ ”)
Serial.println(angle);
delay(15);
  unsigned long currentMillis = millis();

  if (currentMillis - previousMillis >= interval) {
    previousMillis = currentMillis;
    if (ledState == LOW) {
      ledState = HIGH;
      led = 600;
    } else {
      ledState = LOW;
      led = 0;
    }
    digitalWrite(ledPin, ledState);
  }
  Serial.print(" ");
    Serial.println(led);
}
```

  [1]: https://i.stack.imgur.com/lYAp0.png
  [2]: https://i.stack.imgur.com/94JRa.png

title: multiple graphs on serial plotter

Answers: 1

body:
The part of your code that prints data to the serial looks like this:

```c++
void loop() {
    (...)
    Serial.print(sensorValue);
    Serial.print(“ ”)
    Serial.println(angle);
    (...)
    Serial.print(" ");
    Serial.println(led);
}
```
The bug is in the `Serial.println(angle);` line. The `println` method inserts a "newline" character at the end. Try changing it to `Serial.print(angle);` so there is only one "newline" character.

```c++
void loop() {
    (...)
    Serial.print(sensorValue);
    Serial.print(“ ”)
    Serial.print(angle);
    (...)
    Serial.print(" ");
    Serial.println(led);
}
```


body:
I have recently purchased an Arduino Nano-33-BLE-Sense with Headers and wrongly assumed that it would come with a USB cable with it. I was searching the online store for the cable but the only cable on the store that I see is for Type A to Type B which in its description does not mention my board.

Does anyone have any experience with this board and know which cable I need? Thanks in advance!

title: Need to know what USB cable to get for Arduino Nano-33-BLE-Sense

Answers: 1

body:
Looks like this board

[![Nano-33-BLE-Sense][1]][1]

Is connected to the PC with connector commonly named simply "Micro USB". [Wikipedia][2] calls it "USB 2.0 Micro-B"
It's the same cable that all mobile phones used (before USB-C standard arrived). Check your phone charger.

[![cable][3]][3]

  [1]: https://i.stack.imgur.com/SjqvO.jpg
  [2]: https://en.wikipedia.org/wiki/USB_hardware
  [3]: https://i.stack.imgur.com/ZQohd.jpg


body:
Need help for this [Tutorial][1]. I tried to compile the code, but I'm getting compiling error.

I tried to ask on that forum too but got no answer, the error is:

    In file included from C:\Program Files (x86)\Arduino\libraries\SD\src/utility/SdFat.h:32:0,
    Multiple libraries were found for "SD.h"from C:\Program Files (x86)\Arduino\libraries\SD\src/SD.h:20,
     Used: C:\Program from D:\FEMV3FKI7YLJVQQ\FEMV3FKI7YLJVQQ.ino:1:
     Not used: C:\Users\IBNUM
    C:\Program Files (x86)\Arduino\libraries\SD\src/utility/BlockDriver.h:31:10: fatal error: FatLib/BaseBlockDriver.h: No such file or directory
    Multiple libraries were found for "SPI.h"
     #include "FatLib/BaseBlockDriver.h"
     Used: C:\Program
              ^~~~~~~~~~~~~~~~~~~~~~~~~~
    compilation terminated.
    exit status 1
    Error compiling for board Arduino/Genuino Mega or Mega 2560.

  [1]: https://www.instructables.com/id/Arduino-Ethernet-Camera/

How can I fix this Arduino compile error?

title: Library compilation error

Answers: 1

body:
I have the same problem since version 1.8.10.

With a good running sketch I don't get any message "Multiple libraries were found" (and no warnings also)

But with every small compiler error I get a whole list of "Multiple libraries were found"

My custom libraries are in a sketchbook location
D:\DATA BACKUPPED\Documenten Albert\Arduino\Sketchbook-and-user-libraries


body:
I would like to make a small project, which would allow me to recognize if the grass has grow enough to lawn. I don't know too much the ecosystem of available sensors for such problem. And I have a lot of grass and some irregular areas to clean once in a while.

Is that something I can do with an arduino and some sensors, or should I need to use more processing power and cameras/AI?

TIA!

title: What sensors to measure grass growth?

Answers: 1

body: My idea: Two light sensors on a short stick embedded in the ground. If the top sensor detects light, but the bottom one does not it means that it's daytime, and grass is long enough that it covered the bottom sensor. You will probably need several of those, because there is no guarantee that grass will actually cover the bottom sensor, and you will need to filter out random elements by testing if values don't change to much.


body:
I'm using a timer to fire a interrupt in configurable time periods.
In that ISR, a pin is toggled, and a `uint32_t` variable is incremented.

In the main program, a `while` loop waits until that variable has reached a certain threshold - to then disable the timer via its clock source selection.

    while(stepcounter <= threshold) {
    }
    disablecounter();

Sometimes - depending on optimization level, whether I put a small delay in the while loop, etc., this check seems to fail - advancing to `disablecounter()` even though `stepcounter` has not reached `threshold`.

If I stack the `while` loop like this:

    while(stepcounter <= threshold) {
    }
    while(stepcounter <= threshold) {
    }
    disablecounter();

it runs just fine. This also works:

    while(stepcounter <= threshold) {
      while(stepcounter <= threshold) {
      }
    }
    disablecounter();

I'm assuming there's some odd behaviour when comparing rapidly changing 32-bit numbers against a threshold.
This issue also occurs when using a `uint16_t` for `stepcounter`, but after a higher number of cycles.

For analysis, I'm simply running this loop over and over again; setting `stepcounter` back to `0` and restarting the timer. With `uint32_t`, it usually fails after the 5th or so loop. For `uint16_t`, it fails after around 25 loops.

Using a `tempstepcounter` like this also seems to work, but only when comparing against both counters at the same time:

    while(tempstepcounter <= threshold || stepcounter <= threshold) {
      tempstepcounter = stepcounter;
    }
    disablecounter();

Any ideas on this? It this because 32-bit numbers take longer to read from the registers than the time from ISR to ISR?
ISR frequency should be around 32 kHz during this.

ISR code:

    ISR(TIMER1_COMPA_vect) {
      PORTF ^= (1 << PORTF0));
      stepcounter++;
    }

title: Variable updated in ISR is miscounting

Answers: 1

body:
You need to declare it volatile in both places *and* shut off interrupts while reading it. The mainline  has to read it byte-by-byte, and an interrupt could otherwise occur between any two byte-reads, rendering the result of the 4-byte read as garbage.

'volatile' informs the compiler that the variable might not contain what it did last time (which the compiler might otherwise expect if the code being compiled doesn't change it. Turning off the interrupts protects the variable being changed while it's being read.

An even better way to protect the reads than turning off interrupts, is for the ISR to update the counter, then set a single-byte flag to indicate that there's a new count. The mainline would monitor that flag and read the counter only when the flag gets set, then clear the flag. This can work as long as the mainline checks the flag frequently enough that it will never not notice the flag until just before the next update by the ISR. But if you can keep to that constraint, this is a better idea than turning off interrupts.

If too many sub-tasks resort to turning off interrupts, it can have a negative effect on response time or even cause missed interrupts in some cases. This is less likely to be a problem for the relatively simple programs most of us write and run, most of the time. But when you get to tracking and controlling more complex processes and make heavier use of the interrupt system, bad habits have a way of coming back to bite you.


body:
I have the following code for Arduino mega to output 40 kHz square waves at the analog pins. I need to apply specific phase delays for the signals at each pin though and am struggling to find out how to do this. Any help would be appreciated.
Thanks!

    byte TP = 0b10101010; // Every other port receives the inverted signal

    void setup() {

    DDRF = 0b11111111; // Set all analog ports to be outputs
    DDRK = 0b11111111; // Set all analog ports to be outputs
    // Initialize Timer1

    noInterrupts(); // Disable interrupts

    TCCR1A = 0;

    TCCR1B = 0;

    TCNT1 = 0;

    OCR1A = 200; // Set compare register (16MHz / 200 = 80kHz square wave -> 40kHz full wave)

    TCCR1B |= (1 << WGM12); // CTC mode

    TCCR1B |= (1 << CS10); // Set prescaler to 1 ==> no prescaling

    TIMSK1 |= (1 << OCIE1A); // Enable compare timer interrupt

    interrupts(); // Enable interrupts

    }

    ISR(TIMER1_COMPA_vect) {

    PORTF = TP; // Send the value of TP to the outputs
    PORTK = TP;
    TP = ~TP; // Invert TP for the next run

    }

    void loop() {

    // Nothing left to do here :)

    }

title: ultrasonic phased array

Answers: 0


body:
I have a line following bot which uses IR sensors (LSA08, more specifically) to detect the white line on black surface and stay on track. For the project however, there is a trick in the track. At a certain point, the line changes from white to black and the bot is expected to follow the black line on the white surface.

My question is, how would I design the algorithm which will make the bot recognise that the track and conditions have changed.

title: Follow black and white line simultaneously

Answers: 2

body: It depends a bit on your precise requirements. Currently you are following the black line (meaning sensing black in the middle and white on the sides). Instead you could follow the border of that line. To do this you would have to control the motors in a way, so that in at the middle of the sensors there is a high contrast (black at the right, white at the left, or vice versa). It will not follow the exact same path as before, but a bit to the side.

body:
Assume the "road" line is narrower than the bot's width. Sense light/dark across the road-width by enough more that it can see both edges plus enough to regain the roadway at a sharp bend.

Now pretend we don't know what color the roadway is - which is in fact, true! But we do know that the sensors should see either:
[W, W, W, ... W, B, B, ..., B, W, ..., W] (black stripe), or
[B, B, B, ... B, W, W, ..., W, B, ..., B] (white stripe).

Call W(hite) a 1 and B(lack) a zero. The above conditions, stored in an unsigned int, might look (in binary) like:

1111110000111111, or
0000001111000000.

One is just an inversion of the other, right? So read your sensors (and I'm going to assume perfect robo-vision for a moment: no noisy signals and we know we're on the roadway), and if necessary, *invert the result* so it look like my second case, 0000001111000000, a group of ones surrounded by a group of zeros shows we're (somewhat) centered on the track. *You no longer need to know what color the roadway is!*

We assumed perfect signals - in reality you'll need some smarts to detect and correct an odd 1 in the midst of a bunch (technical term here) of 0s, or vice versa.

We assumed your bot is kind of centered on the track; able to see both roadway edges. In reality, sometimes you may be losing it - 111000000000000, or drifting to the right. If you can't ensure this won't happen, you'll need to be able to recognize it and correct it. And, here is where we need to know something about the roadway color. We knew what color it was recently, just before we started to drift off, so we'll just continue inverting (or not inverting) our stored sensor data - IF the color doesn't change until the bot re-centers itself (nasty track designers)! If your design criteria can include that the bot doesn't lose either edge of the track, you can always recover, even during a color change. Otherwise you'll have to recognize and respond to a color change even when you can only see one edge. Use the recent road-color to keep track of this.

Hope that helps.


body:
I would like to use the external libraries that are downloaded by Arduino IDE into the default sketchbook location (*~/Arduino/libraries/*).

If you open Library Manager in Arduino IDE and if you install an external library (e.g **DHT sensor library 1.3.7** and its dependency **Adafruit Unified Sensor 1.0.3**) then it will be downloaded to the sketchbook location and you can use them freely in case of writing code in Arduino IDE.

However I really like auto code completion, managing source code in GIT repository, formatting source lines, etc. which functionalities are not provided by Arduino IDE, so I changed to CLion.

I have installed **CLion** and **Arduino Support 1.4.4 Plugin** and created a new Arduino Sketch Project.

Project Structure:
-
```
.
+--cmake
   +--Platform
      +--Arduino.cmake
   +--ArduinoToolchain.cmake
+--libs
   +--Adafruit_Sensor
      +--Adafruit_Sensor.h
      +--library.properties
      +--README.md
   +--DHT
      +--DHT.cpp
      +--DHT.h
      +--DHT_U.cpp
      +--DHT_U.h
      +--keywords.txt
      +--library.properties
      +--README.md
+--CMakeLists.txt
+--first_test_project.ino
+--User_Setup.h
```
first_test_project.ino:
-
```lang-c
#include <Arduino.h>
#include "User_Setup.h"
#include <libs/Adafruit_Sensor/Adafruit_Sensor.h>
#include <libs/DHT/DHT.h>

DHT *dht;

void setup() {
    dht = new DHT(7, DHT22);
}

void loop() {

}
```

So I have copied over the downloaded libraries from *~/Arduino/libraries* folder to the project folder under *libs* folder.

When I try to upload the code to Arduino Board I am getting the following in the log:
```
undefined reference to `DHT::DHT(unsigned char, unsigned char, unsigned char)'
```

Could somebody please explain what is wrong here.

Thank you very much!

title: How to use external libraries in CLion

Answers: 2

body:
Did you add your libraries to the cmake files?

I don't have any experience with CLion but `undefined reference` normally means that
the linker couldn't find the function/class your are using.

So make sure the libraries are compiled and the linker knows where to find the object files.

body:
In my opinion, the easiest way for the beginner is to use Platformio, it sets up CLion project automatically.

See [docs][1] for more info.

  [1]: https://docs.platformio.org/en/latest/ide/clion.html


body:
I want to know why `Wire.onRequest` can not detect below massage and what I can do to detect it.(I am not able to change I2C massage)

I was able to read this part of the massage with `wire.onReceive`:

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

But I can not read this massage at all, which is requesting:
[![enter image description here][2]][2]

    #include <Wire.h>
    byte val = 170;
    int sendv;

    char c;

    byte dataArray[16];

    void setup() {
      Wire.begin(0x77);                // join i2c bus with address #8
      Wire.onReceive(receiveEvent); // register event
      Wire.onRequest(requestEvent); // register event
      Serial.begin(9600);           // start serial for output
    }

    void loop() { }

    void receiveEvent(int howMany) {
      Serial.println(howMany);

      if (howMany >= 2) {
        for (int i = 0 ; i < howMany; i++) {
          dataArray[i] =  Wire.read();
          Serial.println(dataArray[i], HEX);
        }

      } else {
        c =  Wire.read();
        Serial.println(c, HEX);
      }
    }

    void requestEvent() {
      Serial.println("REqEVENT");
    }

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

title: I2C Wire.onRequest not detected

Answers: 1

body:
I was able to solve the issue with by adding  twi_stop(); to twi.c

base on this website
[enter link description here][1]

  [1]: https://github.com/helenarobotics/Arduino/commit/8aff39a229362e0167e5f48f6c15d02b39b0fbca


body:
Today I finally got two HM-10 modules. I did flash firmware using [this][1] tutorial. It worked until I didn't send `AT+RENEW` command. Now, LED blinks, I see device in BT terminal(Android phone) but I can't connect to it. Terminal says `Connection failed: write descriptor failed`. I tried sending commands over COM port from PC, but it doesn't responde.
Also I connected pin 11 to GND, problem is still here. Strange thing - After firmware flash, `AT+HELP` doesn't exist, while `AT+HELP?` returns some website.

For second module, LED doesn't blink but I see module in BT terminal. It also stopped working after `AT+RENEW`. When I try to connect, I get same error.

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

title: HM-10 doesn't responde after RENEW

Answers: 1

body: change your COM serial baud rate to 115200. I had the same problem and the moment I change the baud rate on my Serial Com or Serial monitor. it works for me


body:
I've made a dice roller (to make it easier to roll the dice) using an Arduino UNO and an LCD keypad shield but I can't get the correct numbers (1, 6 (7)) to show up, I've tried using int, float and everything in between. the buttons on the shield are connected to A0, can someone help me please?

    #include <LiquidCrystal.h>
    // select the pins used on the LCD panel
    LiquidCrystal lcd(8, 9, 4, 5, 6, 7);

    #include "DFRkeypad.h"
    String line2 = "Press Select to roll"; // Scrolling line

    // just some reference flags
    //int stringStart, stringStop = 0;
    //int scrollCursor = screenWidth;

    // define some values used by the panel and buttons
    int lcd_key     = 0;
    int adc_key_in  = 0;
    #define btnRIGHT  0
    #define btnUP     1
    #define btnDOWN   2
    #define btnLEFT   3
    #define btnSELECT 4
    #define btnNONE   5

    // read the buttons
    int read_LCD_buttons()
    {
      adc_key_in = analogRead(0);      // read the value from the sensor

      // For V1.0 comment the other threshold and use the one below:

      if (adc_key_in > 1000) return btnNONE; // We make this the 1st option
      for speed reasons since it will be the most likely result
      // For V1.1 us this threshold
      if (adc_key_in < 50)   return btnRIGHT;
      if (adc_key_in < 195)  return btnUP;
      if (adc_key_in < 380)  return btnDOWN;
      if (adc_key_in < 555)  return btnLEFT;
      if (adc_key_in < 790)  return btnSELECT;

      return btnNONE;  // when all others fail, return this...
    }

    void setup() {
      randomSeed(analogRead(1));
      lcd.begin(16, 2);              // start the library
      lcd.setCursor(3, 0);
      lcd.print ("Catan Dice");
      lcd.setCursor(0, 1);

      // while(line2)
      //
      // lcd.print(line2);
      // break;
    }

    void loop() {

      //Dice
      byte DiceOne = random(1, 7);
      byte DiceTwo = random(1, 7);

      //local varables
      int buttonState = read_LCD_buttons(); // read the button pad
      int lastButtonState = btnNONE; // previous state of the button

      // the following variables are unsigned longs because the time, measured in
      // milliseconds, will quickly become a bigger number than can be stored in an int.
      unsigned long lastDebounceTime = 0;  // the last time the output pin was toggled
      unsigned long debounceDelay = 50;    // the debounce time; increase if the output flickers

      switch (buttonState)
      {
        case btnSELECT:
          lcd.clear();
          //Row, Colum
          lcd.setCursor (0, 4);
          lcd.print(DiceOne);
          lcd.setCursor (1, 4);
          lcd.print(DiceTwo);
          break;
      }

      DELAY(100)

      // read the state of the switch into a local variable:
      int reading = digitalRead(buttonState);

      // check to see if you just pressed the button
      // (i.e. the input went from LOW to HIGH), and you've waited long enough
      // since the last press to ignore any noise:

      // If the switch changed, due to noise or pressing:
      if (reading != lastButtonState) {
        // reset the debouncing timer
        lastDebounceTime = millis();
      }

      if ((millis() - lastDebounceTime) > debounceDelay) {
        // whatever the reading is at, it's been there for longer than the
        debounce
        // delay, so take it as the actual current state:

        // if the button state has changed:
        if (reading != buttonState) {
          buttonState = reading;
        }
      }

UPDATE, i got it working now

title: Dice is not showing the correct numbers

Answers: 2

body:
It seems that your issue is probably connected with LCD timing. Sending data to LCD requires a precise timings, and the onboard chip of the LCD module very much like a few milliseconds of time to finish processing the data sent, instead you pass the entire clear and draw command each loop cycle.

I used the default Tinkercad LCD display example.
This code works fine:
```c++
#include <LiquidCrystal.h>

LiquidCrystal lcd(12, 11, 5, 4, 3, 2);

void setup() {
  randomSeed(analogRead(1));
  lcd.begin(16, 2);
  lcd.setCursor(3, 0);
  lcd.print ("Catan Dice");
  lcd.setCursor(0, 1);
}

void loop() {
  byte DiceOne = random(1, 7);
  byte DiceTwo = random(1, 7);

  lcd.clear();
  lcd.setCursor (0, 4);
  lcd.print(DiceOne);
  lcd.setCursor (1, 4);
  lcd.print(DiceTwo);
  delay(100);
}
```
[![tinkercad example][2]][2]

but as soon as I remove the `delay(100)`
```c++
void loop() {
  byte DiceOne = random(1, 7);
  byte DiceTwo = random(1, 7);

  lcd.clear();
  lcd.setCursor (0, 4);
  lcd.print(DiceOne);
  lcd.setCursor (1, 4);
  lcd.print(DiceTwo);
  //delay(100);
}
```
Weird things start to show on the LCD.

[![incorrect number displayed][1]][1]

Try rewriting your code that the commands are sent to LCD only once per button press.

  [1]: https://i.stack.imgur.com/J2gpv.png
  [2]: https://i.stack.imgur.com/0npPk.png

body:
You are calling setCursor() with:

    //Row, Colum
    lcd.setCursor (0, 4);
    lcd.print(DiceOne);
    lcd.setCursor (1, 4);
    lcd.print(DiceTwo);

While your comment notes the order is `Row`, `Column`, there appear to be several LiquidCrystal libraries floating about, some of which use `Column`, `Row` order in the `SetCursor()` function. The [official Arduino library source][1] indicates the `col`, `row` order.

You are writing both values on row 4 (even though that doesn't exist on your display), and in columns 0 and 1, thus you are correctly computing the Dice values, but they are being written with no gap between.

  [1]: https://github.com/arduino-libraries/LiquidCrystal/blob/master/src/LiquidCrystal.cpp#L188


body:
This code is measuring distance from object by using the Ultrasonic Sensor and print onto serial monitor.

However, serial monitor constantly output values.
I want to print only one time if detected value not change.
and serial monitor print again only when detected value change.
and The above condition keeps repeating.

How can i change the code?

    int distance ;
    int trig = 3;
    int echo = 2;

    void setup()
    {
      Serial.begin(9600);
      pinMode(trig, OUTPUT);
      pinMode(echo, INPUT);
    }

    void loop()
    {
      digitalWrite(trig, HIGH);
      delayMicroseconds(10);
      digitalWrite(trig, LOW);
      distance = pulseIn(echo, HIGH) / 58;
      Serial.println(distance);
    }

title: I want to print onto serial monitor when it's detected the value change

Answers: 1

body:
    int distance;
    int last_distance; // <== To hold the value from the previous pass
    int trig = 3;
    int echo = 2;

    void setup()
    {
      Serial.begin(9600);
      pinMode(trig, OUTPUT);
      pinMode(echo, INPUT);
    }

    void loop()
    {
      digitalWrite(trig, HIGH);
      delayMicroseconds(10);
      digitalWrite(trig, LOW);
      distance = pulseIn(echo, HIGH) / 58;
      if (distance != last_distance) {  // <== Check if new distance is different
        Serial.println(distance);       //     Print only if the values are different
      }
      last_distance = distance;         // <== Store this loop's distance for next round
    }


body:
0

I've been trying to make my own board with a SAM3X and W5500 (Arduino Ethernet Shield) on it with those two chips connected via SPI.

From the Arduino Due Board, most of the stuff, we don't need. So obviously, almost everything went off. Particularly, I remove the power switching circuits since we won't be varying power anyway. The native USB Programming also went off as well as the Programming port circuit.

I've only left headers so I can connect the 16U2 (with 16MHz crystal) circuit externally. Headers are VIN (5V from USB), RX (from a level shifter), TX and Ground. I'd not included the reset signal so from the 16U2 pin, I connected a 1kohm resistor (R23) to the reset line in my board.

The 16U2 I have externally is programmed with the new file in

[https://github.com/arduino/ArduinoCore-sam/tree/master/firmwares/atmega16u2][1]

When I connect the 16U2 circuit to my USB Port, I was able to see it as the programming port correctly. However, when I try uploading a sketch to the board (sample blink), the IDE says No Device Found on the COM port.

I've tried using bossac and modifying the COM port thru command prompt but I still get the same result.

I've checked the SAM3X checklist and it says there that for SAM-BA to boot, I only need to have the correct supplies and the 12 MHz Crystal Oscillator. I've checked everything using multitester and all the supplies are in the correct voltage. I've checked the crystal using an oscilloscope and I can see that it outputs the expected waveform.

I've also checked the TX and RX line from the 16U2. There are data being send by the 16U2 but the SAM3X is not responding.

One thing I notice is that the 32 kHz crystal is not working. But from what I've read in these forum, that is not powered by the SAM3X until the slow clock oscillator is enabled to be externally sourced.

The last thing I think that I've done different is that I'd connected the VBUS pin to the 3.3V supply rail where it was directly connected to the USB power. The reason I've done this is because I'm not using USB anyway.

Also, the data lines for the native USB, I've terminated them using 1MHz resistors to ground just so they're not left flaoting.

Are these (VBUS and datalines) causing my SAM3X to not reply and properly work so sketches can be uploaded? Would want to confirm VBUS first before destroying the trace in my board as I'm afraid I might fry the SAM3X chip with 5V.

Are there other things I've done wrong?

  [1]: https://github.com/arduino/ArduinoCore-sam/tree/master/firmwares/atmega16u2

title: No Device Found On Bare-bones SAM3X Chip

Answers: 0


body:
I want my Arduino to log data while connected to a battery.
After few hours, I need to reconnect the Arduino via COM port to a PC and read the logged data.

The com port will not reconnect. This is part of the code I am using. It works if I am not disconnecting the com port. Any idea how to fix this?

    if (digitalRead(buttonPin) == HIGH) {
        LoopIndex=0;
        Serial.begin(9600);
        Serial.println("Start printing");
        while (LoopIndex < MinCounter) {
            // print the results to the serial monitor:
            Serial.print("Time = ");
            Serial.print(PressurePerMin[LoopIndex++]);
            Serial.print("\t sensor = ");
            Serial.println(PressurePerMin[LoopIndex++]);
        }
     }

title: Reconnect to a com port

Answers: 0


body:
    #include <LiquidCrystal.h>
    LiquidCrystal lcd(A0,A1,A2,A3,A4,A5);

in this code the error given by IDE is 'A1' was not declared in this scope.
So whats the problem please help

title: Arduino IDE gives error a1 is not declared

Answers: 0


body:
I would like to use those two components for an upcoming project :

 - [BH1790GLC heart rate sensor](https://www.rohm.com/datasheet/BH1790GLC)
 - [TMP117 temperature sensor](http://www.ti.com/product/TMP117)

I especially like the fact that they’re so tiny.

Could I connect them directly to an Arduino board or some other well-known microcontroller ?

title: Can you connect BH1790GLC and TMP117 sensors to an Arduino board?

Answers: 1

body:
Yes, the sensors will work with microcontroller(s). What you look for is the **interface** they use. In this case it is **I2C** interface. Be careful thou: You have to check voltage levels your microcontroller works with and selected sensor voltage level. Some of the Arduino works with 5V levels and some sensors may accept max of 3.3V or 4.5V on I2C pins. This is why you would need either:

 - Choose 3V powered microcontroller
 - Use 5V powered microcontroller (like Arduino Uno) and voltage level converter

Also worth to note that these two sensors would need some additional circuitry to work with your microcontroller. Before any commitment I would try to find a development board (a board with mentioned circuitry with easy to acces pins for providing necessary signals/voltages/ground/etc).
Good luck!


body:
Total Arduino newbie here.
I was playing with mBlocks, with the Arduino Uno extension enabled. That extension offers you to "update firmware" which I accidentally did. What exactly is this firmware? Is it just a compiled sketch or does it alter stuff like bootloader or reside permanently in the memory?

title: mBlock update firmware

Answers: 1

body: Usually by Firmware we understand "a program that was prepared by company that produced the hardware and that is necessary for that hardware to work correctly". I suppose that developers of mBlock are smart enough not to allow people to "brick" their Arduino's. I suspect that ether you updated your bootloader (it's also a firmware) to latest version or simply nothing happened. In both cases your device should be operational. Burning a bootloader onto an Arduino is not as hard as it seems so even if you broke something you should be able to fix it.


body:
In a part of my sketch I put by mistake
pinMode(7,INPUT_PULLUP);
Which is dedicated pin for external flash chip (gpio7/SDIO_DATA_0/SPI_MISO) that not supposed to use for sketch. after uploading sketch now ESP is not responding to any further programming.

Could be Flash chip got corrupted due to the above mistakes?. Is it possible to recover?
I already bricked two of my modules with same sketch before identifying above mistake.
Sketch where working normal on Modules without above code.

When I connect to module with boad-rate 74880 chip returns
 ets Jan  8 2013,rst cause:2, boot mode:(3,7)
please check what happens when I try to upload the code [upload error][1]

  [1]: https://hastebin.com/oxeyuqeyib.rb

title: ESP8266 seems to be bricked , how to recover?

Answers: 2

body:
No, your sketch can not brick the device in that way. It's the bootloader that decides after a reset/power-up whether the esp has to accept a firmware (flash button is pressed) or has to run the uploaded sketch. At that point, nothing of your sketch has yet been executed and gpios have their default configuration, which is input anyway.

Also, when a pullup is in charge, one can still apply a logic level to the respective pin. The gpio then won't see any effect from the pullup.

body:
No, you have not bricked your ESP8266 by turning on GPIO7's pullup.  All that will do is provide a weak pullup on the MISO line of the flash chip, which itself will have no effect - the flash chip's SPI Data Out pin will be able to easily override that weak pullup.

You can remove the flash chip and replace it with a completely blank brand new flash chip with nothing on it and still upload new code. There is nothing in the flash chip that the ESP8266 relies on to operate.

The boot sequence of the ESP8266 is as follows:

    - Start executing the bootloader from the built-in ROM
      - Read the GPIO pins to determine code execution source
      - If flash is selected then initialize flash chip and read from address 0
        - Code on flash examines partition table to find code entry point
        - Jump to code entry point
      - If UART is selected then initialize UART
        - Wait for commands over the UART and respond accordingly

The startup code (boot stage 0) is in ROM. It's impossible to "brick" that.  All that is in the flash is the code that tells the ESP8266 how to find the user's code, and that gets flashed to the chip every time you reprogram it.

You can think of it like BIOS boot on a PC.  In the ROM is the BIOS that tells the CPU how to read from the hard drive. Then at the start of the hard drive is the code that tells the CPU how to load the operating system.  The hard drive doesn't come with that code on it - you install that along with the operating system. But the motherboard has the BIOS built into ROM which tells it how to get going and read that boot sector.

However it is possible to destroy an ESP8266 by connecting the wrong things up to it in the wrong way.  It is also possible to destroy some USB chips (the CH340G in particular) by wiring things up wrong.

So chances are that if you *have* bricked your ESP8266 it has nothing to do with your program and everything to do with what you have wired to it.


body:
Extreme Newbie here ...I am using an Arduino Uno and a PCA9685 16 Ch. Driver board to control servos using a push button and LED feedback.  When I pust the button, the servo move but when I release the button, the servo move back to it original position.  What I would like to have happen is that when I push the button once, the servo moves and holds its position.  When I push the button again, return to its starting position.  Thanks in advance for the assistance.

Here is the sketch:

    #include <Wire.h>
    #include <Adafruit_PWMServoDriver.h>

    Adafruit_PWMServoDriver pwm = Adafruit_PWMServoDriver();

    int buttonPin0 = 2;   // Can add as many buttons as needed
    int ledPin0C = 3;     // C designates Closed position of turnout
    int ledPin0T = 4;     // T designates Thrown position of turnout
    int buttonState0 = 0;

    int buttonPin1 = 5;
    int ledPin1C = 6;
    int ledPin1T = 7;
    int buttonState1 = 0;

    void setup() {
        Serial.begin(9600);
        Serial.println("pca9685_TurnoutFinal!");
        pwm.begin();
        pwm.setPWMFreq(60);
        delay(30);

        pinMode(ledPin0C, OUTPUT);
        pinMode(ledPin0T, OUTPUT);
        pinMode(buttonPin0, INPUT);
        pinMode(ledPin1C, OUTPUT);
        pinMode(ledPin1T, OUTPUT);
        pinMode(buttonPin1, INPUT);
    }

    void loop() {
        ///////////
        buttonState0 = digitalRead(buttonPin0);
        if (buttonState0 == HIGH) {
            pwm.setPWM(0, 0, 370);
            digitalWrite(ledPin0T, LOW);
            digitalWrite(ledPin0C, HIGH);
        }
        else {
            pwm.setPWM(0, 0, 285);
            digitalWrite(ledPin0C, LOW);
            digitalWrite(ledPin0T, HIGH);
        }
        //////////
        buttonState1 = digitalRead(buttonPin1);
        if (buttonState1 == HIGH) {
            pwm.setPWM(1, 0, 370);
            digitalWrite(ledPin1T, LOW);
            digitalWrite(ledPin1C, HIGH);
        }
        else  {
            pwm.setPWM(1, 0, 285);
            digitalWrite(ledPin1C, LOW);
            digitalWrite(ledPin1T, HIGH);
        }
        //////////
    }

title: How to manage button state

Answers: 1

body:
The code in loop is always running so when you release the button, the code sees this as digitalRead(btn) = HIGH.

You need a state variable to know where the motor is currently.  Something like this:

    boolean state = false;
    int oldButton = HIGH;

    void loop() {
        delay(20); // enough to debounce very most buttons

        int newButton = digitalRead(buttonPin0);
        if (oldButton == HIGH && newButton == LOW) { // only when button changes from "released" to "pressed"
            state = !state;

            // tell the servo where to go
            if (state) {
                pwm.setPWM(0, 0, 370);
            } else {
                pwm.setPWM(0, 0, 285);
            }
        }
        oldButton = newButton;
    }


body: I am trying to build a portable device that can record from at least 3 microphones. I had a look and saw I2S is good for audio so I bought an Arduino MKR Zero to read them with. I was wondering how to record from multiple microphones on the I2S bus at once. The only thing that I have been able to do is record stereo from two mics but I need the microphone readings to be mono. I am using the Adafruit I2S MEMS Microphone SPH0645LM4H.

title: How to use more than 2 I2S microphones on MKR Zero?

Answers: 1

body:
By definition, the I2S bus only allows up to 2 channels to be transmitted at the same time.  Here is a quote from the [Details section][1] of the Wikipedia's [I2S page][2]:

> The word select clock lets the device know whether channel 0 or
> channel 1 is currently being sent, because I²S allows two channels to
> be sent on the same data line.

This is further illustrated in Figure 8 / Page 6 of the [Knowles SPH0645LM4H data specifications][3].  In this figure we see where 2 SPH0645LM4H microphones are configured (ground or Vcc to the SEL pin 2) such that they can be multiplexed onto the I2S bus by the I2S bus master.

  [1]: https://en.wikipedia.org/wiki/I²S#Details
  [2]: https://en.wikipedia.org/wiki/I²S
  [3]: https://media.digikey.com/pdf/Data Sheets/Knowles Acoustics PDFs/SPH0645LM4H-B.pdf


body:
recently I have this project which needs to read 2 wiegand signal using Arduino Mega 2560.

I have an access control device which will output wiegand signal once the user is allow to enter, and there's a RFID reader which will transmit the card no in wiegand signal to my access control device.

So I need to get card no from the RFID reader and also from the Access control device, so I connect them like the attachment given, using a library here: ( https://github.com/ugge75/Wiegand-V3-Library-for-all-Arduino ), everything works fine at first, but once a while, I can't read signal from the RFID Reader, and sometimes I can. Could anyone let me know why is this happening?

[![Can 1 wiegand output for 2 controller?][1]][1]

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

title: Can 1 wiegand output for 2 controllers?

Answers: 2

body:
There is missing information.  Assuming a 5V Arduino and all D0s and D1s swing from 5V to 0V as the Wiegand protocol defines.  This despite the 12V power supply in the question's diagram.

Examining the [driver code on GitHub][1], we see it's [falling edge interrupt][2] driven.  So any noise when the line is expected to be at a steady 5V will cause the driver to run.  And there are a number of locations in the code where data is dumped because it is considered bad. It appears that any unexpected noise during a valid signal will cause missing data.

Consider the possibility of noise affecting the RFID data.  Shorten the length of the RFID's Wiegand cable in an effort to improve the RFID reliability.

Consider re-writing the driver code to improve noise rejection.  Currently, it appears the driver code will accept any falling edge as valid data to be processed.  Alternatively, the driver code could detect a falling edge then sample the same input a fixed interval of time later.  A valid signal is assumed to last longer than noise.  Therefor any falling edge interrupt followed by a high sample can assumed to be noise and ignored / not-processed.

  [1]: https://github.com/ugge75/Wiegand-V3-Library-for-all-Arduino/blob/master/Wiegand.cpp
  [2]: https://en.wikipedia.org/wiki/Interrupt#Edge-triggered

body:
In the readers there is switch transistors that pull down voltage provided from controllers, in other words is shutting signal to the ground. In my practice i tested many solutions and simplest one is with diodes from each controller D0 D1 in direction to the reader. In that case is not crossing voltage from controllers. For 2 controllers and 1 reader you need 4 diodes - 2 on each line.

Controller 1 - D0 --> anode on Diode 1 --> cathode to common connection for line D0

Controller 1 - D1 --> anode on Diode 2 --> cathode to common connection for line D1

Controller 2 - D0 --> anode on Diode 3 --> cathode to common connection for line D0

Controller 2 - D1 --> anode on Diode 4 --> cathode to common connection for line D1

Common connection D0 --> reader D0

Common connection D1 --> reader D1

Works fine up to 20 meters since every diode makes voltage drop.
For diodes 1N4001/4007 works fine.
Noise is not a problem, this is very slow connection with 5v amplitude.


body:
This is for an esp8266 project that uses EasyAsyncTCP. In EasyAsyncTCP.cpp they   `#include "lwip/tcp.h"`. But I can't figure out where that file is. I've found a tcp.h in the following directories on my c drive:

- c:\Program Files (x86)\Arduino\hardware\arduino\avr\firmwares\wifishield\wifiHD\src\SOFTWARE_FRAMEWORK\SERVICES\LWIP\lwip-1.3.2\src\include\lwip
- c:\Program Files (x86)\Arduino\libraries\WiFi\extras\wifiHD\src\SOFTWARE_FRAMEWORK\SERVICES\LWIP\lwip-1.3.2\src\include\lwip
- c:\Users\me\AppData\Local\Arduino15\packages\esp32\hardware\esp32\1.0.2\tools\sdk\include\lwip\lwip
- c:\Users\me\AppData\Local\Arduino15\packages\esp32\hardware\esp32\1.0.2\tools\sdk\include\lwip\lwip\prot
- c:\Users\me\AppData\Local\Arduino15\packages\esp8266\hardware\esp8266\2.5.2\tools\sdk\lwip\include\lwip
- c:\Users\me\AppData\Local\Arduino15\packages\esp8266\hardware\esp8266\2.5.2\tools\sdk\lwip2\include\lwip
- c:\Users\me\AppData\Local\Arduino15\packages\esp8266\hardware\esp8266\2.5.2\tools\sdk\lwip2\include\lwip\prot

but so far I've only tested the first two. I've tested them by either straight up deleting the directory and using the `#error got here` directive. No matter what I do my project builds. So I think I must either have the wrong file or it doesn't rebuild the entire thing.

How can I determine which tcp.h my program is including?

title: Where is tcp.h?

Answers: 1

body:
While this isn't the right way of doing it I'm sharing the way that I figured it out.

**Step1:**

cd c:\

dir tcp.h /s

c:\Program Files (x86)\Arduino\hardware\arduino\avr\firmwares\wifishield\wifiHD\src\SOFTWARE_FRAMEWORK\SERVICES\LWIP\lwip-1.3.2\src\include\lwip

c:\Program Files (x86)\Arduino\libraries\WiFi\extras\wifiHD\src\SOFTWARE_FRAMEWORK\SERVICES\LWIP\lwip-1.3.2\src\include\lwip

c:\c:\Users\Me\AppData\Local\Arduino15\packages\esp8266\hardware\esp8266\2.5.2\tools\sdk\lwip2\include\lwip\protUsers\Me\AppData\Local\Arduino15\packages\esp32\hardware\esp32\1.0.2\tools\sdk\include\lwip\lwip

c:\Users\Me\AppData\Local\Arduino15\packages\esp32\hardware\esp32\1.0.2\tools\sdk\include\lwip\lwip\prot

c:\Users\Me\AppData\Local\Arduino15\packages\esp8266\hardware\esp8266\2.5.2\tools\sdk\lwip\include\lwip

c:\Users\Me\AppData\Local\Arduino15\packages\esp8266\hardware\esp8266\2.5.2\tools\sdk\lwip2\include\lwip

**Step2:**

I went through and tested each one. It was... `C:\Users\Me\AppData\Local\Arduino15\packages\esp8266\hardware\esp8266\2.5.2\tools\sdk\lwip2\include\lwip\tcp.h`


body:
I'm working on a project that will eventually scale to 864 LEDs on WS2815 LED strips (three rows of 288 LEDs). I'm currently running it on an Arduino Uno with a single test strip of 144 LEDs.

FastLED stores its data in 3-byte structs, so I obviously cannot simply hold all of the data in SRAM and work with it directly (at least not without upgrading to a controller with more memory). I'm going to use a Raspberry Pi to send the Arduino data, one section at a time. To *further* save memory, I want to implement an RGB color lookup table in flash, then instead of

    CRGB pixels[PIXEL_COUNT];

taking up over 2KiB of memory 800+ values, or

    CRGB pixels[PIXEL_BUFFER_COUNT];

with a buffer of 288 RGB values consuming most of my working memory (864 bytes), I would have

    CRGB *pixels[PIXEL_BUFFER_COUNT];

Where each pointer would reference a location in a `PROGMEM` 256-entry table of `CRGB` values. This is a more manageable 576 bytes in SRAM.

**I realize FastLED does not work this way**. There's a  lot of work ahead of me if I do this, but before I get started, my question:

---------

Will I run into issues with reading the actual data from flash memory while sending to the LED strips? As currently implemented in FastLED, RGB data is in SRAM, but each pointer dereference will require reading from flash. Is the subsequent delay enough that it will cause an issue with sending data to the strips?

title: How fast is flash reading compared to SRAM?

Answers: 2

body:
Because flash is on a different data bus to SRAM there is extra shuffling around needed internally in the CPU to get the data to where it needs to be.  This uses a special "LPM" instruction (Load Program Memory), which takes an extra clock cycle to operate. On top of that the only way of using it is through the Z "index" register - there's no kind of immediate or offset loads.  So it can be a little clunky to work with.  All that is masked by the provided C functions, of course.

The upshot is that yes, it is somewhat slower reading from flash.  How much slower, though, is impossible to say.  Best case scenario: each access will take 1 more clock cycle. Worst case: well, it's impossible to know.  That somewhat depends on both how you implement your reading of the CLUT and how the compiler batches things together.

I would suggest that you will need to employ the use of an oscilloscope and just try it out.  Implement your changes, then manually adjust the delays and timing to get the output waveform just right.

body:
On an Arduino Uno, or other AVR-based Arduino, reading a byte from RAM
takes 2 CPU cycles. Reading it from flash takes 3 cycles. So flash vs.
RAM is not such a high overhead. However, if you store a LUT in flash,
and the color indexes in RAM, then each pixel would require:

 * 2 cycles for reading the color index from RAM
 * 3 × 3 cycles for reading the RGB values from flash.

That's a total of 11 cycles, vs. 6 cycles it would take to read the RGB
values from RAM, as is done in the stock FastLED library.

It sounds bad, but it could be that the precise timing is not such a big
issue. I don't know the WS2815, but if they are similar to the WS2812,
then you don't need to be anywhere as precise with the timings as the
datasheet suggests. C.f. the blog post [NeoPixels Revealed: How to (not
need to) generate precisely timed signals][post].

**Edit**: there will be a few more cycles needed for the pointer
arithmetic. I estimate something around 7 cycles. At low level, the code
for getting a color should look roughly like this:

```c++
uint8_t *pixel = ...;
uint8_t index = *pixel;            // read from RAM: 2 cycles
uint8_t pgm_p;                     // pointer to flash
pgm_p = &pgm_lut + 3 * index;      // pointer arithmetic: ≥ 7 cycles
struct CRGB color;
color.r = pgm_read_byte(pgm_p++);  // read from flash: 3 cycles
color.g = pgm_read_byte(pgm_p++);  // read from flash: 3 cycles
color.b = pgm_read_byte(pgm_p);    // read from flash: 3 cycles
```

[post]: https://wp.josh.com/2014/05/13/ws2812-neopixels-are-not-so-finicky-once-you-get-to-know-them/


body:
Created a "variableInput.h" file for editing variables in one place; instead of searching multiple lines of code, to find lines needing editing.

    //   variableInput.h
    //
    //   User defineable variables; one location for editing variables

    // Replace with your network details
    #define host = "esp32"
    #define ssid = "YOURSSID"
    #define password = "YOURPASSWORD"

    //NTP Time Servers
    #define udpAddress1 = "198.50.238.156"  //NTP Time server
    #define udpAddress2 = "132.163.96.3"  //NTP Time server

    //publicIP accessiable over Internet with Port Forwarding; know the risks!!!
    //WAN IP Address.  Or use LAN IP Address --same as server ip; no Internet access.
    #define publicIP = "YOURPUBLICIP"
    #define LISTEN_PORT  8030  //default listening Port 80 for "GET" requests.

    //Graphing requires "FREE" "ThingSpeak.com" account..
    //Enter "ThingSpeak.com" data here....
    //iframes of graphed data are available from "ThingSpeak.com."
    #define myChannelNumber = 123456
    #define myWriteAPIKey = "E12345"

    //FTP Credentials
    #define ftpUser = "FTPUSER"
    #define ftpPassword = "FTPPASSWORD"

    //setting the addresses
    #define ip(10,0,0,200);
    #define gateway(10,0,0,1);
    #define subnet(255, 255, 255, 0);
    #define dns(10,0,0,1);

    //Restricted access to client ip list.
    #define Restricted = "/ANYNAME"

    //OTA Credentials
    //default username: USERNAME
    //default password: PASSWORD

    // "setting the addresses" is the part that I do not understand.

Segment of related code from "wifi_Start" function:

    //setting the addresses
    IPAddress ip;
    IPAddress gateway;
    IPAddress subnet;
    IPAddress dns;

Is there a solution?

William

title: How to set "IPAddress ip" using a variable?

Answers: 2

body:
Here's how I do it (for an Arduino that connects to my Mosquitto server) using wired ethernet (WiFi works the same way):

    #include <Ethernet.h>
    #include <PubSubClient.h>
    EthernetClient ethClient;
    PubSubClient client(ethClient);

    byte mac[]    = {
      0xde, 0xad, 0xbe, 0xef, 0xca, 0xfe
    };
    IPAddress ip(192, 168, 1, 75);
    IPAddress server(192, 168, 1, 11);
    void setup() {

      client.setServer(server, 1883);
      client.setCallback(callback);

      Ethernet.begin(mac, ip);

    }

body: You are not using #define correctly. The syntax is #define {name}  {value}.  There is no = between name and value so for your IP address lines you want #define myIp ip(192, 168, 1, 11)


body:
I'm trying to generate a pulse width modulated sound using Arduino Nano.

But it generates the weird sound unlike my expectation.

**Here's my code:**

    class Phasor
    {
    public:
        Phasor(const float frequency)
        :frequency(frequency)
        ,phase(1.0f)
        ,lastTimeMicros(0){};
        virtual ~Phasor(){};
        void setFrequency(const float frequency)
        {
            this->frequency = frequency;
        }
        float process()
        {
            const unsigned long currentTimeMicros = micros();
            if (phase == 1.0f) lastTimeMicros = currentTimeMicros;
            const unsigned long elapsedTimeMicros = currentTimeMicros - lastTimeMicros;
            const unsigned long cycleDurationMicros = static_cast<unsigned long>(1000.0f / frequency) * 1000;
            if (elapsedTimeMicros < cycleDurationMicros)
                phase = static_cast<float>(elapsedTimeMicros) / static_cast<float>(cycleDurationMicros);
            else
                phase = 1.0f;
            return phase;
        }
    private:
        float frequency;
        float phase;
        unsigned long lastTimeMicros;
    };

    class PulseOsc
    {
    public:
        PulseOsc(const float frequency, const float pulseWidth)
        :phasor(frequency)
        ,pulseWidth(pulseWidth){};
        virtual ~PulseOsc(){};
        void setFrequency(const float frequency)
        {
            this->phasor.setFrequency(frequency);
        }
        void setPulseWidth(const float pulseWidth)
        {
            this->pulseWidth = pulseWidth;
        }
        float process()
        {
            const float phase = phasor.process();
            if (phase <= pulseWidth)
                return 1.0f;
            else
                return -1.0f;
        }
    private:
        Phasor phasor;
        float pulseWidth;
    };

    Phasor *phasorLFO;
    PulseOsc *pulseOsc;

    void setup()
    {
        Serial.begin(9600);
        pinMode(9, OUTPUT);
        phasorLFO = new Phasor(0.1f);
        pulseOsc = new PulseOsc(440.0f, 0.5f);
    }

    void loop()
    {
        pulseOsc->setPulseWidth(phasorLFO->process());
        int outVal = LOW;
        if (pulseOsc->process() > 0.0f) outVal = HIGH;
        digitalWrite(9, outVal);
    }

The resulting sound is very weird and glitchy.
It works fine when I fix the pulse width value. (without LFO)

What is wrong with my code?
How do I fix this? I would appreciate any advice.

title: Weird sound when modulating the pulse width on Arduino

Answers: 2

body: Seems like you are using the system clock `micros()` to  calculate `elapsedTimeMicros`, so probably the time spent on the process of calculation and sending signal to the pin may affect it, which may lead to inconsistent duty cycle.

body:
I see two issues with this program. The first one has already been
pointed out by Majenko in a comment: you are doing too much floating
point calculations. The second has to do with the way your `Phasor`
manages the time.

If you take a look at the [Blink Without Delay][] Arduino tutorial, you
will see something along these lines:

```c++
if (currentMillis - previousMillis >= interval) {
    previousMillis = currentMillis;
    toggle_the_LED();
}
```

In this code, `interval` is the _minimum_ time between toggles. Whenever
the program gets a little bit late and `currentMillis - previousMillis`
is strictly larger than `interval`, this extra time is lost and the
program will be late for all the subsequent LED toggles. If instead of
the minimum you are interested in the _average_ time between toggles,
then you should write:

```c++
if (currentMillis - previousMillis >= interval) {
    previousMillis += interval;  // <- advance by exactly one period
    toggle_the_LED();
}
```

Now, `previousMillis` is no more the time when the last toggle was
_performed_, it is the time when the last toggle was _scheduled_. With
this version you can still have some jitter, but at least the average
frequency should be right. If the program is so busy that it can get
late by a full period, then it would be better to replace the `if` by a
`while`, in order to catch up all the missed periods.

Your `Phasor::process()` method is a little bit more involved than the
tutorial above, yet the line

```c++
if (phase == 1.0f) lastTimeMicros = currentTimeMicros;
```

is going to get you out of schedule for exactly the same reason.

That being said, here is my take at your phasor idea, _completely
untested_:

```c++
class Phasor()
{
public:
    Phasor(float frequency_Hz)
    {
        period = round(1e6 / frequency_Hz);
        frequency = 0x10000 / period;
    }
    uint16_t process()
    {
        uint16_t now = micros();
        while (now - last_time >= period)
            last_time += period;
        return (now - last_time) * frequency;
    }
private:
    uint16_t period;     // unit = 1 us
    uint16_t frequency;  // unit = 1/(2^16 us) ~ 15.3 Hz
    uint16_t last_time = 0;
};
```

I changed a few things from your implementation:

 * removed the `setFrequency()` method because [YAGNI][]
 * no floating point except in the constructor, for performance reasons
 * only 16-bit arithmetics, for the same reason
 * no division in `process()`, because division is expensive
 * the phase is not stored, because there is no use to storing it
 * the phase is an integer in units of 2<sup>−16</sup> periods

Note that the unit chosen for the phase is the most natural one when
dealing with 16-bit arithmetics. Note also that storing microseconds in
16-bit variables only works for frequencies higher than 15.3 Hz. A
very low frequency phasor (your “LFO” for instance) would need 32-bit
arithmetics.

[Blink Without Delay]: https://www.arduino.cc/en/tutorial/BlinkWithoutDelay
[YAGNI]: https://en.wikipedia.org/wiki/You_aren't_gonna_need_it


body:
I am trying to build an emergency shutdown of a gas valve based on the output of a smoke detector.

It basically measures the voltage on the buzzer of the smoke detector, and if high enough, changes the direction of the motordriver, which is  connected to an actuator (with automatic shutdown) that operates the gas valve.

A button is used to reset the alarm.

The actual setup is soldered on a prototype board, but below the layout as a breadboard.

[![breadboard layout][1]][1]

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

The nano is powered by a step down converter connected to the 5V pin, that in turn is powered by the 12V power supply that also drives the actuator. Its output is 5.13V according to my multimeter, and seems stable when I measure it.

The problem I have is that the system continuusly enters alarm state.

After some experimenting I have found out that when I short the analog pin to ground, I always read 0, but when I use a resistor, as in the breadboard layout, I get a couple of 0 readings, then a sort of peak, that goes back to 0, and that behaviour in a cycle of approximately 10 sec.

The cyclic pattern is consistent, the values differ depending on how I power the system (external of from the USB of my PC), and whether I connect the smoke detector or use the resistor.

Below the code (I left out the utility functions for brevity), and the output when I use the 100k resistor between A2 and ground, with the board powered by the USB connection.

Can anyone explain what is going on here?

```
void setup() {
  bool storedAlarm;

  initOutput(activeLedPin);
  initOutput(alarmLedPin);
  initOutput(gasValveIn1Pin);
  initOutput(gasValveIn2Pin);

  EEPROM.get(0,storedAlarm);
  alarm = false;

  Serial.begin(9600);
  Serial.print("start with Alarm ");
  Serial.println( storedAlarm ? "ON" : "undetermined" );

  digitalWrite(activeLedPin, HIGH);
  blinkAlarmLed(500,333,3);

  if (storedAlarm) {
    switchAlarmOn();
  }
  // never switch off automatically
  // if the valve is open it will stay open
}
void loop() {
  int sensorValue = analogRead(sensorPin);
  bool reset = digitalRead(alarmResetPin);

  Serial.println(sensorValue);
  if ( sensorValue > 500 ) {
    switchAlarmOn();
    if (reset) {
      blinkAlarmLed(100,100,7); // show refusal
    }
  }
  else if ( reset ) switchAlarmOff();

  delay(800);
}
```

Output:

```
14:01:08.587 -> start with Alarm ON
14:01:11.061 -> alarm
14:01:11.367 -> 36
14:01:12.148 -> 35
14:01:12.963 -> 9
14:01:13.778 -> 0
14:01:14.559 -> 0
14:01:15.374 -> 0
14:01:16.155 -> 0
14:01:16.970 -> 0
14:01:17.784 -> 0
14:01:18.564 -> 0
14:01:19.380 -> 0
14:01:20.161 -> 0
14:01:20.974 -> 0
14:01:21.787 -> 17
14:01:22.568 -> 62
14:01:23.383 -> 65
14:01:24.162 -> 67
14:01:24.977 -> 54
14:01:25.791 -> 137
14:01:26.570 -> 104
14:01:27.385 -> 29
14:01:28.165 -> 17
14:01:28.980 -> 0
14:01:29.795 -> 0
14:01:30.575 -> 0
14:01:31.390 -> 0
14:01:32.171 -> 0
14:01:32.986 -> 0
14:01:33.801 -> 0
14:01:34.581 -> 0
14:01:35.397 -> 0
14:01:36.178 -> 0
14:01:36.993 -> 37
14:01:37.809 -> 64
14:01:38.589 -> 69
14:01:39.404 -> 64
14:01:40.184 -> 34
14:01:40.997 -> 136
14:01:41.811 -> 120
14:01:42.592 -> 46
14:01:43.406 -> 16
14:01:44.187 -> 8
14:01:45.003 -> 0
14:01:45.784 -> 0
14:01:46.600 -> 0
14:01:47.415 -> 0
14:01:48.196 -> 0
14:01:49.012 -> 0
14:01:49.793 -> 0
14:01:50.607 -> 0
14:01:51.422 -> 0
14:01:52.201 -> 0
14:01:53.016 -> 0
14:01:53.796 -> 0
14:01:54.611 -> 28
14:01:55.427 -> 53
14:01:56.208 -> 65
14:01:57.022 -> 72
14:01:57.803 -> 68
14:01:58.617 -> 73
14:01:59.432 -> 0
14:02:00.212 -> 140
14:02:01.027 -> 136
14:02:01.808 -> 101
14:02:02.622 -> 46
14:02:03.437 -> 22
14:02:04.218 -> 16
14:02:05.032 -> 8
14:02:05.812 -> 0
14:02:06.627 -> 0
14:02:07.409 -> 0
14:02:08.224 -> 0
14:02:09.038 -> 0
14:02:09.820 -> 0
14:02:10.633 -> 0
14:02:11.415 -> 0
14:02:12.231 -> 0
14:02:13.047 -> 0
14:02:13.828 -> 0
14:02:14.642 -> 0
14:02:15.422 -> 40
14:02:16.237 -> 73
14:02:17.050 -> 72
14:02:17.830 -> 65
14:02:18.644 -> 11
14:02:19.427 -> 131
14:02:20.240 -> 108
14:02:21.054 -> 61
14:02:21.834 -> 18
14:02:22.648 -> 14
14:02:23.428 -> 0
14:02:24.242 -> 0
14:02:25.058 -> 0
14:02:25.839 -> 0
14:02:26.654 -> 0
```

title: Strange cyclic errors in analogRead on Nano

Answers: 0


body:
I am trying to make a scale that measuring weight. In internet i did some researches so i got some questions.
I have this module as a HX711 [![HX711 Module][1]][1]

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

And square 3 wired loadcells( Red,White,Black Wired).

My mcu is Noedmcu V3. When i check from the Visual Studio Code, it says Adafruit Huzzah. This MCU's operation voltage is 3.3v and got ESP8266EX chip.

Some Hx711 modules (ex. sparkfun red board) got VDD pin for logic level. But my module has not. Can i operate this hx711 and loadcell with 3.3 volts?

If i cant, i can use 5volts for excitation voltages but communication will be on 5Volts. My mcu operating on 3.3volts. can i add voltage divider to  DT,SCK pins to regulate voltage around 3.3volts? Is it proper solution?

Or if you have any hint about that, can you share with me?

title: HX711 with NodeMcu

Answers: 0


body:
I am using arduino mega with LCD 4X20 character to measure weight by 40 kg load cell and pt 100 to measure the temp. I have 4 output to 4 relay module. all are powered from 12vdc /3 amp Power supply..
the problem is.. the display started normally showing every thing perfectly.. but when the output comes out and the loads runs.. random characters appear
is the power supply is not enough? or another problem..
Please advice. ![enter image description here](https://i.stack.imgur.com/fg3A9.jpg)![enter image description here](https://i.stack.imgur.com/Mf0en.jpg)

title: random characters

Answers: 2

body: I'd suspect that it is a software error. Did you check your circuit if it induces desync between the Arduino and the LCD, or did you just use the wrong drivers?

body:
Random Characters can Happen in several ways.

- Check the Wires for: Loosen Ends; Broken Wires and Wrong Pin Connections.
- Check your Code.


body:
I recently upgraded my windows10 from version 1803 to 1903. I had to do a clean install to accomplish it though, but my question is, I downloaded Adriano IDE 1.8.9 and installed it but it won't launch. It starts, then the window closes and that's it. Does anybody have any thoughts on what's going on? Or better yet what's not going on?

Thanks, Dennis

title: Arduino 1.8.9 Won't Load

Answers: 0


body:
I am trying to interface with the ICM-20789 over I2C. [DataSheet][1]

I have been successfully able to get all three gyroscope readings and all three accelerometer readings. I am now trying to get the pressure readings from the device, since it has a built-in pressure sensor, but cannot seem to get it working.

In the datasheet, it says to enable Bypass Mode.

> Bypass Mode: Set register INT_PIN_CFG (Address: 55 (Decimal); 37 (Hex)) bit 1 to value 1 and I2C_MST_EN bit is ‘0’
(Address: 106 (Decimal); 6A (Hex). Pressure sensor data can then be accessed using the procedure described in Section 10

In the setup I use this code:

      Wire.beginTransmission(gyro_address);
      Wire.write(0x37);      //INT_PIN_CFG
      Wire.write(0x02);      //00000010
      Wire.endTransmission();

I am having trouble finding I2C_MST_EN in the datasheet as well, as I cannot find it in the 6A Address.

Once I have the bypass bit enabled, I try to request the pressure and temperature data from the sensor using this code:

    Wire.beginTransmission(0x63);
    Wire.write(0x7866);
    Wire.endTransmission();
    Wire.requestFrom(0x63, 16);

    while (Wire.available() < 16);
    pressure = Wire.read() << 16 | Wire.read() << 8 | Wire.read();
    temp_2   = Wire.read() << 16 | Wire.read() << 8 | Wire.read();

Unfortunately, the device freezes when I try to run this code. I know I am obviously doing something wrong here, just don't know exactly what yet.

  [1]: http://www.invensense.com/wp-content/uploads/2017/10/DS-000169-ICM-20789-TYP-v1.3.pdf

title: I2C Communication with the ICM-20789

Answers: 1

body:
There are four things wrong with your code.

1. You are not sending the "start measurement" command properly. The `Wire.write()` function can only send 8 bits, but you are passing it a 16-bit value. Instead you should break it apart into 2 separate 8-bit values:

    Wire.beginTransmission(0x63);
    Wire.write(0x78);
    Wire.write(0x66);
    Wire.endTransmission();

2. The data returned is spread over 9 bytes, not 16.  According to the datasheet:

> Temperature data is transmitted in two 8-bit words and pressure data is
transmitted in four 8-bit words.

and:

> Two bytes of data are always followed by one byte CRC checksum

That's 2 + 4 = 6 + (6/2) = 9

3. You aren't waiting for the conversion to complete. According to the datasheet, in "ultra low noise" mode (0x7866) it takes up to 94.5ms to perform the measurement.  So you should add a delay of slightly more than that to allow it to do what it needs to do.

4. The command you are sending responds with temperature first, not pressure, but you are reading pressure first (and reading the wrong bytes anyway).

In all, your code should look more like:

    Wire.beginTransmission(0x63);
    Wire.write(0x78);
    Wire.write(0x66);
    Wire.endTransmission();

    delay(100);

    Wire.requestFrom(0x63, 9);
    uint8_t tmsb = Wire.read(); // Temperature highest byte
    uint8_t tlsb = Wire.read(); // Temperature lowest byte
    Wire.read();

    uint8_t pmmsb = Wire.read(); // Highest pressure byte
    uint8_t pmlsb = Wire.read(); // Next highest pressure byte
    Wire.read(); // Discard checksum
    uint8_t plmsb = Wire.read(); // Next lowest pressure byte
    uint8_t pllsb = Wire.read(); // Lowest pressure byte
    Wire.read(); // Discard checksum

    pressure = (pmmsb << 24) | (pmlsb << 16) | (plmsb << 8) | pllsb;
    temp_2   = (tmsb << 8) | (plsb << 8);


body:
I want to copy an SD card to another.

What is the best way to attack this problem?

Should i get two sd card shields?
If yes, is it possible to stack two together, or will there be problems with the interface protocols (SPI/I2C)?

title: Copy one SD card to another

Answers: 1

body:
It should be perfectly possible to do it. As long as the SD cards and shields play ball then there should be no problem from a hardware perspective.

From a hardware perspective you should be able to share the MOSI, MISO and SCK lines and just have separate CS pins per card.

However some SD card shields employ level translation that doesn't properly release the SPI bus when idle, and some cheap SD cards don't release the bus in a timely manner too.

From a software perspective though it may be a different matter. I am not sure how well you can run two instances of the SD classes at once on an Arduino.  You may be better off looking at FatFS instead which is far more flexible.

You have two strategies when copying cards, each of which has a different way of programming it.

1. Block copy the entire card: this involves reading a 512 byte block from one card and writing it to the other one.  This would be the most efficient from a resource perspective (you don't need to care about the contents of the card, so don't need any filesystem code), but if the card is not close to full it will be very inefficient from a runtime perspective. Also the two cards have to be the same size for it to work well.
2. File copy. For this you need much more complex code, but it you only copy each file from one card to the other. It's much better though if the cards don't have much data on them - also the cards can be different sizes.


body:
I have a problem with remaining headers. Can't seem to find the first header "RtcUtility.h". Anyone how to fix? I've provided a picture for you to see.

[![Sample picture][1]][1]

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

Error Messages:

> Arduino: 1.8.10 (Windows 7), Board: "NodeMCU 1.0 (ESP-12E Module), 80 MHz, Flash, Disabled, All SSL ciphers (most compatible), 4M (no SPIFFS), v2 Lower Memory, Disabled, None, Only Sketch, 115200"

> sample_time:6:24: error: RtcUtility.h: No such file or directory

> Multiple libraries were found for "ArduinoOTA.h"
 #include <RtcUtility.h>

> Used: C:\Users\user\AppData\Local\Arduino15\packages\esp8266\hardware\esp8266\2.5.2\libraries\ArduinoOTA
                        ^

> Multiple libraries were found for "Wire.h"
compilation terminated.

> Used: C:\Users\user\AppData\Local\Arduino15\packages\esp8266\hardware\esp8266\2.5.2\libraries\Wire
Multiple libraries were found for "ESP8266WiFi.h"
 Used: C:\Users\user\AppData\Local\Arduino15\packages\esp8266\hardware\esp8266\2.5.2\libraries\ESP8266WiFi
Multiple libraries were found for "ESP8266mDNS.h"
 Used: C:\Users\user\AppData\Local\Arduino15\packages\esp8266\hardware\esp8266\2.5.2\libraries\ESP8266mDNS
exit status 1
RtcUtility.h: No such file or directory

> This report would have more information with
"Show verbose output during compilation"
option enabled in File -> Preferences.

title: RtcUtility.h: No such file or directory

Answers: 1

body:
Please add the RTC library in the Arduino as below.

*Open the Library Manager and search for "Rtc by Makuna" and install.*

You can also checkout the Github page for that particular library at

https://github.com/Makuna/Rtc


body:
I am using NodeMCU for my project.I wanted to know how much current it takes in its all modes like sleep mode,deep sleep mode and also in its wifi modes like station and access point mode.

Thanks in advance...

title: NodeMCU current consumption in all modes

Answers: 0


body:
I am using a bi-directional 3.3-5V logic converter to control 5V relay with 3.3V D5 pin of nodemcu. link of logic  converter is [here][1]

However, I expected to control the relay but it didn't work. I don't think there is a problem with electrical connection or code since that is simple.

3.3V sides of nodemcu is connected to LV and 5V side of Relay is connected to HV.

Code:-

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

    void loop() {
      // put your main code here, to run repeatedly:
    digitalWrite(D5, HIGH);
    delay(2000);
    digitalWrite(D5, LOW);
    delay(2000);
    }

My Observations:-
1) When relay is removed, multimeter shows 3.3V at the LV & HV side. (so logic converter is not working i guess)
2) When relay  is  connected, multimeter shows 2.5V on  both sides.

Everything is powered from nodemcu pins. Does  it means that i have to supply extenal power or something wrong with logic converter?[![enter image description here][2]][2]

What do you guys think?

PS  - I  soldered the pins another way around on logic converter. Does it change anything?

circuit image, nodemcu is powered by the laptop USB

[![circuit][1]][1]

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

title: Nodemcu is connected to 5v relay with logic converter but still not working

Answers: 3

body:
The converter and/or the nodemcu can't provide enough current to drive the relay. So you should get a 5V psu.
For further details we need more information about the parts you use.

body: To make that work you'd need to connect the HV connection to the Vin of the NodeMCU (as well as to the relay board) which should be the 5 V coming form the USB port. You'd also need to connect the GND on the HV side to the GND of the NodeMCU.

body:
You must supply a steady, regulated voltage to both 3.3v and 5v pins at all time (see Voltage Inputs on https://learn.sparkfun.com/tutorials/bi-directional-logic-level-converter-hookup-guide/all).

Logic level controller does NOT convert 3.3v to 5v for powering the relay, it just let you turn 3.3v signal to 5v so a relay can get activated. Relay's positive pin still needs to be supplied with a 5v from a PSU or other sources.