body:
> Is the Wire library useful for USB communication? Is there something similar (master/slave-wise) that would be helpful?

The Wire library does I2C communication, which has absolutely nothing to do with USB. Actually the USB connection on the Uno is not native. The Atmega328P on the Uno only has a Serial (UART) interface, which is onboard connected to another chip (Atmega82U or others), which has native USB support. That chip will do the USB communication. The driver on the PC will then emulate a Serial COM port, so that it is something like a "Serial COM port over USB" connection. USB is complex and you should not tinker with it directly, unless you are very advanced in this direction. And I don't think, doing that would help you here.

> Assuming the serial/listen thing works, are there good ways to re-route data to different ports? Currently my best guess is something like $ echo $encoderVal > /dev/cu.usbmodem????? to each one individually ... but that might be a completely noobish notion.)

Since you have a complete Unity game, you have to program something in that direction. Using the bash seems not good here. I don't know, if you can communicate with serial COM ports from Unity (since I haven't worked with it yet), but doing this in Python works like a charm. There are many tutorials out there, that show how to do it.

> i2c keeps on coming up in searches, but looks like overkill. Is that a direction to head?

If that is an overkill depends on your exact requirements for the system. Sure, the I2C protocol has a bit of overhead, but maybe you need the functionality.

> Is this all completely nuts?

Currently it seems a bit like that. I think, this due to you not having a good structure for the project. To help you with that, I will explain some possibilities below.

---

As I understood, you have the following setup: The Uno has a rotary encoder, that controls a game on the PC. All boards (Uno and Trinkets) have one LED strip, that should light up depending on what happens in the game.

You have now 2 basic structures for the communication:

1. Doing everything over an own USB connection. This is what you sketched above. Every board has it's own serial COM port (which actually get's emulated over USB by the driver) on the PC and your game/program on it has to connect to all these and send the appropriate data. Sure this is a possible design, but it comes with downsides: Currently it doesn't seem, that you already have implemented the communication program. That is important in this design, but that's not really about Arduino and depends on how you are programming the game in Unity (haven't done that before and don't know how to connect a serial device to it. Maybe through a python script). The second problem is, that you will have choose the serial port for every board, when you start the game. The port numbers/names are not always the same; it's up to the operating system to set these. That's not a great usablity.

2. You can use other communication interfaces between the boards directly. In this case only the Uno would be connected via USB to the PC and every data would go through the Uno. What kind of interface you should use depends on your exact requirements. Since you didn't specify them in detail, I will explain some examples:

    - **Every Trinket get's the exact same data and nothing must be read from them:** In this case you can use the Serial (UART) interface. It uses the pins, that are marked with RX (receiving pin) and TX (transmitting pin). Normally this connection is only between 2 boards, but it is possible to simply connect multiple receivers (with their RX pin) to exactly 1 transmitter (with it's TX pin).

        The Uno has one hardware Serial interface, which is also used to communicate with the PC. If it is OK, that the PC also get's the data, which is meant for the Trinkets, (and the Trinkets get the data, that are meant for the PC) you can use this interface and wire the Uno's TX to all Trinket RX pins. You can google how to read data from the interface with the `Serial` library, which is directly available with Arduino. If you don't want the PC to get the same data, you can set up a `SoftwareSerial` interface (with the library with that name). That provides the same interface, but is handled in software, because the Uno doesn't have another hardware Serial (UART) interface.

        In both cases you would transmit the data from the PC (data out of the game) via the USB serial port to the Uno, which then in turn sends it further to all the Trinket boards. They read the data and act accordingly. Everytime the Uno senses new rotary encoder positions, it will send data to the PC.

        For connected the Uno with a Trinket, you only need 2 wires in this design (1 for Uno TX to Trinket RX and 1 ground wire). Of course, you also would have to provide power to the Trinkets. Please see below for that matter.

    - **Every Trinket can be address individually and data can also be read from them:** In this case I2C can be the way to go. For the communication you need at least 3 wires (SDA, SCL and ground). Every Trinket joins the I2C bus with a configured address. The Uno acts as master on the bus. He can call a Trinket by it's address and send or request data. The I2C protocol is more structured than serial (UART), because it is divided into transmissions. This works great, if the Trinkets can all get different data, and if you also want to read data from them. Be sure to give very Trinket a unique address on the bus. For the program part look into the `Wire` library.

    - **Individual sending and receiving in a very fast manner**: If you need the individual data transmitting and reading from I2C, but you also need the communication to be very fast, you can use SPI. The SPI bus doesn't use addresses, but Slave Select pins. You need 1 pin on the master (Uno) for every slave device. If you want to communicate with one Trinket, you pull it's Slave Select pin to LOW. This bus needs 5 wires (MISO, MOSI, SCK, Slave Select and ground), but the communication can be very fast; way faster than I2C. Look into the `SPI` libary for the programming of this.

---

**Providing power:** Depending on your design and the number and type of the LEDs, you have to look into, how you supply the needed power to the boards. In the design, that you sketched above, (every board directly to USB) the boards themselves should have enough power, but LED strips can be very power hungry, getting fast to currents over 1A. The pinout of Adafruits Trinket M0 shows a maximal current of 500mA from the Vusb pin. The 5V pin of the Uno can handle about 200mA (as I remember, currently not sure. You can google this).

If you choose a design with only the Uno connected to USB, you might need an extra power supply, so that you can provide the power for all Trinkets and their LEDs with it. Please adhere to the current limits of the components, or you may fry your boards.

I hope, that help's. Have fun


sender: user

message:
2 analog sensors, pulse sensor and LM35 problem

I make a project in which I use two analog sensors. A pulse sensor and the LM35 temperature sensor. When I use them separated everything is normal,the codes are fine, when I combine them the lm35 is not precise, has an error margin of about 10 degrees but the pulse sensor seems to be ok. I read something about the analog to digital convertor that Arduino have and need a delay or something to trick the ADC.
I would be grateful if somebody help me to modify the code.
Thank you very much!
<!-- language-all: lang-cpp -->

    #include <LiquidCrystal.h>
    #include <TonePlayer.h>

    const int rs = 12, en = 11, d4 = 5, d5 = 4, d6 = 3, d7 = 2;
    LiquidCrystal lcd(12, 11, 5, 4, 3, 2);

    int pulsePin = A0;                 // Pulse Sensor purple wire connected to analog pin A0
    int blinkPin = 13;                // pin to blink led at each beat

    const int sensor=A5; // Assigning analog pin A5 to variable ‘sensor’ temperature
    float tempc;
    float vout; //temporary variable to hold sensor reading

    TonePlayer tone1 (TCCR1A, TCCR1B, OCR1AH, OCR1AL, TCNT1H, TCNT1L);  // pin D9 (Uno), D11 (Mega)

    // Volatile Variables, used in the interrupt service routine!
    volatile int BPM;                   // int that holds raw Analog in 0. updated every 2mS
    volatile int Signal;                // holds the incoming raw data
    volatile int IBI = 600;             // int that holds the time interval between beats! Must be seeded!
    volatile boolean Pulse = false;     // "True" when User's live heartbeat is detected. "False" when not a "live beat".
    volatile boolean QS = false;        // becomes true when Arduoino finds a beat.

    static boolean serialVisual = true;   // Set to 'false' by Default.  Re-set to 'true' to see Arduino Serial Monitor ASCII Visual Pulse

    volatile int rate[10];                      // array to hold last ten IBI values
    volatile unsigned long sampleCounter = 0;          // used to determine pulse timing
    volatile unsigned long lastBeatTime = 0;           // used to find IBI
    volatile int P = 512;                      // used to find peak in pulse wave, seeded
    volatile int T = 512;                     // used to find trough in pulse wave, seeded
    volatile int thresh = 525;                // used to find instant moment of heart beat, seeded
    volatile int amp = 100;                   // used to hold amplitude of pulse waveform, seeded
    volatile boolean firstBeat = true;        // used to seed rate array so we startup with reasonable BPM
    volatile boolean secondBeat = false;      // used to seed rate array so we startup with reasonable BPM

    void setup() {

      pinMode(blinkPin,OUTPUT);         // pin that will blink to your heartbeat!
      pinMode (9, OUTPUT);  // output pin is fixed (OC1A)

      Serial.begin(115200);             // we agree to talk fast!
      interruptSetup();                 // sets up to read Pulse Sensor signal every 2mS
                                        // IF YOU ARE POWERING The Pulse Sensor AT VOLTAGE LESS THAN THE BOARD VOLTAGE,
                                        // UN-COMMENT THE NEXT LINE AND APPLY THAT VOLTAGE TO THE A-REF PIN

      pinMode(sensor,INPUT); // Configuring pin A1 as input                             //   analogReference(EXTERNAL);

      lcd.begin(16, 2);
      lcd.clear();
    }

    //  Where the Magic Happens
    void loop() {
      serialOutput();
      if (QS == true) { // A Heartbeat Was Found
        // BPM and IBI have been Determined
        // Quantified Self "QS" true when arduino finds a heartbeat
        serialOutputWhenBeatHappens(); // A Beat Happened, Output that to serial.
        QS = false; // reset the Quantified Self flag for next time

        vout=analogRead(sensor);
        vout=(vout*500)/1023;
        tempc=vout; // Storing value in Degree Celsius

        Serial.print ("Temperatura: ");
        Serial.print(tempc);
        Serial.println(" C ");

      }
      delay(20); //  take a break
    }

    void interruptSetup() {
      // Initializes Timer2 to throw an interrupt every 2mS.
      TCCR2A = 0x02;     // DISABLE PWM ON DIGITAL PINS 3 AND 11, AND GO INTO CTC MODE
      TCCR2B = 0x06;     // DON'T FORCE COMPARE, 256 PRESCALER
      OCR2A = 0X7C;      // SET THE TOP OF THE COUNT TO 124 FOR 500Hz SAMPLE RATE
      TIMSK2 = 0x02;     // ENABLE INTERRUPT ON MATCH BETWEEN TIMER2 AND OCR2A
      sei();             // MAKE SURE GLOBAL INTERRUPTS ARE ENABLED
    }

    void serialOutput() {   // Decide How To Output Serial.
     if (serialVisual == true){
         arduinoSerialMonitorVisual('-', Signal);   // goes to function that makes Serial Monitor Visualizer
      } else{
          sendDataToSerial('S', Signal);     // goes to sendDataToSerial function
       }
    }

    void serialOutputWhenBeatHappens() {
     if (serialVisual == true) { //  Code to Make the Serial Monitor Visualizer Work

         Serial.print("Batai ");  //ASCII Art Madness
         Serial.print("BPM: ");
         Serial.println(BPM);
         lcd.print("Batai ");
         lcd.setCursor(6,0);
         lcd.print("BPM: ");
         lcd.setCursor(10,0);
         lcd.print(BPM);

         lcd.setCursor(0,1);
         lcd.print("Temp: ");
         lcd.setCursor(6,1);
         lcd.print(tempc);
         lcd.setCursor(11,1);
         lcd.print("C ");

         delay(300);
         lcd.clear();
       } else {
         sendDataToSerial('B',BPM);   // send heart rate with a 'B' prefix
         sendDataToSerial('Q',IBI);   // send time between beats with a 'Q' prefix
       }
    }

    void arduinoSerialMonitorVisual(char symbol, int data ) {
      const int sensorMin = 0;      // sensor minimum, discovered through experiment
      const int sensorMax = 1024;    // sensor maximum, discovered through experiment
      int sensorReading = data; // map the sensor range to a range of 12 options:
      int range = map(sensorReading, sensorMin, sensorMax, 0, 11);
      // do something different depending on the
      // range value:
    }

    void sendDataToSerial(char symbol, int data ) {
       Serial.print(symbol);
       Serial.println(data);
    }

    ISR(TIMER2_COMPA_vect) { //triggered when Timer2 counts to 124

      cli();                                      // disable interrupts while we do this
      Signal = analogRead(pulsePin);              // read the Pulse Sensor
      sampleCounter += 2;                         // keep track of the time in mS with this variable
      int N = sampleCounter - lastBeatTime;       // monitor the time since the last beat to avoid noise
                                                  //  find the peak and trough of the pulse wave
      if(Signal < thresh && N > (IBI/5)*3) { // avoid dichrotic noise by waiting 3/5 of last IBI
        if (Signal < T) { // T is the trough
          T = Signal; // keep track of lowest point in pulse wave
        }
      }

      if(Signal > thresh && Signal > P) {       // thresh condition helps avoid noise
        P = Signal;                             // P is the peak
      }                                        // keep track of highest point in pulse wave

      //  NOW IT'S TIME TO LOOK FOR THE HEART BEAT
      // signal surges up in value every time there is a pulse
      if (N > 250) {                                   // avoid high frequency noise
        if ( (Signal > thresh) && (Pulse == false) && (N > (IBI/5)*3) ) {
            Pulse = true;                               // set the Pulse flag when we think there is a pulse
            digitalWrite(blinkPin,HIGH);                // turn on pin 13 LED
            tone1.tone (1000);  // 1000 Hz

            IBI = sampleCounter - lastBeatTime;         // measure time between beats in mS
            lastBeatTime = sampleCounter;               // keep track of time for next pulse

            if(secondBeat) {                        // if this is the second beat, if secondBeat == TRUE
              secondBeat = false;                   // clear secondBeat flag
              for(int i=0; i<=9; i++) { // seed the running total to get a realisitic BPM at startup
                rate[i] = IBI;
              }
            }

            if(firstBeat) { // if it's the first time we found a beat, if firstBeat == TRUE
              firstBeat = false;                   // clear firstBeat flag
              secondBeat = true;                   // set the second beat flag
              sei();                               // enable interrupts again
              return;                              // IBI value is unreliable so discard it
            }
          // keep a running total of the last 10 IBI values
          word runningTotal = 0;                    // clear the runningTotal variable

          for(int i=0; i<=8; i++) {                 // shift data in the rate array
              rate[i] = rate[i+1];                  // and drop the oldest IBI value
              runningTotal += rate[i];              // add up the 9 oldest IBI values
            }

          rate[9] = IBI;                          // add the latest IBI to the rate array
          runningTotal += rate[9];                // add the latest IBI to runningTotal
          runningTotal /= 10;                     // average the last 10 IBI values
          BPM = 60000/runningTotal;               // how many beats can fit into a minute? that's BPM!
          QS = true;                              // set Quantified Self flag
          // QS FLAG IS NOT CLEARED INSIDE THIS ISR
        }
      }

      if (Signal < thresh && Pulse == true) {    // when the values are going down, the beat is over
          digitalWrite(blinkPin,LOW);            // turn off pin 13 LED
          tone1.noTone ();
          Pulse = false;                         // reset the Pulse flag so we can do it again
          amp = P - T;                           // get amplitude of the pulse wave
          thresh = amp/2 + T;                    // set thresh at 50% of the amplitude
          P = thresh;                            // reset these for next time
          T = thresh;
        }

      if (N > 2500) {                          // if 2.5 seconds go by without a beat
        thresh = 512;                          // set thresh default
        P = 512;                               // set P default
        T = 512;                               // set T default
        lastBeatTime = sampleCounter;          // bring the lastBeatTime up to date
        firstBeat = true;                      // set these to avoid noise
        secondBeat = false;                    // when we get the heartbeat back
      }
      sei();                                   // enable interrupts when youre done!
    }// end isr

sender: assistant

body:
I have a couple of suggestions:

The combined code is very different from the simple LM35 code that works. I'd suggest you start with the combined code but comment out everything that doesn't directly apply to reading the LM35, and get that working correctly.

The interrupt service routine (ISR) is trying to do too much, and leaves the interrupts off during all of those calculation. Plus, its hard to debug code inside an ISR! ISRs should do the *minimum work that they have to do*. In this case, it looks like it needs to read & save the pulse sensor value and do the `N`, `lastBeatTime`, and `sampleCounter` calculation. Have it also set a flag every time it runs.

The main loop should check that flag, and if it is set, clear it and call another function to do everything you took out of the ISR. Debug this code, perhaps with the LM35 commented out.

Ideally your `loop()` function should be as simple as:

    void loop(){
       Timers.run();
       maybeCalcHeartbeat();
       maybeDoOtherSubtask();
       ...
    }

Then the rest of your code goes into "maybeDo" functions. A "maybeDo" just decides whether the time or conditions are right to do a particular thing; if so, the function does it; but in any case, it returns quickly:

    void maybeCalcHeartbeat(void){
       if( !isrFlag )
          return;
       else {
          // everything you took out of the ISR goes here //

          isrFlag = false;
       }

  [1]: https://playground.arduino.cc/Code/SimpleTimer/


message:
How can I make FastLED set every 2 LEDs to the same color?

I'm controlling an WS2812 LED strip in which every 2 leds is controlled together - they are setup as "eyes" in a prop.  I'm looking to control hundreds of these, so in an effort to save RAM I'd like to have each byte in the LED color array represent 2 LEDs.  That is to say that when the FastLED library writes to the data lin I want it to duplicate every byte going out.

I've dug into FastLED code but get lost around the timings deep down in the code.

Any ideas?

body:
 - The FastLED community appears to live at [this reddit.com site][1]. Consider asking your question there.
 - It is unknown if the following will exceed the current limitations of the Arduino platform you are using.  But, consider sending the same data to two different strings of LEDs simultaneously.  Briefly, each LED strips off the 1st packet of data and sends the balance of data through to the next LED.  Two different strips should behave the same if given the same data.  Thereby creating the effect you described (pairs of LEDs behaving the same).

  [1]: https://www.reddit.com/r/FastLED


message:
Parsing and comparing strings on Arduino: different behaviour from gcc?

I am trying to parse a simple string, print the result of the parsing via serial.println, and trigger a function on the basis of the received command. I wrote the code below, which perfectly works in c (see the c file attached). However, the behaviour of the same code on the arduino IDE is completely different and I really can't figure out why.

<!-- language-all: lang-cpp -->

    #include <string.h>

    void rcv_msg(char *rcv_msg) {

      char *all_tokens[2];
      int i = 0;

      all_tokens[i] = strtok(rcv_msg, "{,}");
      while (all_tokens[i] != NULL) {
        all_tokens[++i] = strtok(NULL, "{,}");
      }

      char *command = all_tokens[0];
      char *value = all_tokens[1];

      /*
      //These printls do not work, they are ignored, why?
      Serial.println("all_tokens[0]: ");
      Serial.println(all_tokens[0]);
      Serial.println("all_tokens[1]: ");
      Serial.println(all_tokens[1]);
      */

      if (strcmp(command,"message_1") == 0 && strcmp(value,"1") == 0) {

        Serial.println("message 1: ");
        Serial.println(command);
        Serial.println(value);
        Serial.println(" ");

      }

      if (strcmp(command,"message_2") == 0 && strcmp(value,"0") == 0) {

        Serial.println("message 2: ");
        Serial.println(command);
        Serial.println(value);
        Serial.println(" ");

      }
    }

    void setup() {

        Serial.begin(115200);
    }

    void loop() {

        char msg1[] = "{message_1,1}";
        char msg2[] = "{message_2,0}";

        Serial.println("Send msg1: ");
        rcv_msg(msg1);
        delay(5000);

        Serial.println("Send msg2: ");
        rcv_msg(msg2);
        delay(5000);
    }

This code gives the following output on the serial monitor, which is wrong:

Send msg2:
message 2:
message_2
{message_2,0}

Send msg1:
message 2:
message_1
{message_2,0}

Send msg2:
message 2:
message_2
{message_2,0}

Send msg1:
message 2:
message_1
{message_2,0}

Firstly, I don't understand why at the beginning, message 2 is printed before message 1, although message 1 was sent first. Second it is not clear to me the comparison done with strcmp is always returning the message 2.

More importantly, why running the same code in c has instead the correct output? I wonder if there is any error in my arduino code. BTW, I am testing the code on Teensy 3.2 but I plan to use it also on Arduino Uno.

The c code (which is perfectly working is this:
```
#include <string.h>
#include <stdio.h>

void rcv_msg(char *rcv_msg) {

    char *all_tokens[2]; //NOTE: the message is composed by 2 tokens: command and value
    int i = 0;

    all_tokens[i] = strtok(rcv_msg, "{, }");
    while (all_tokens[i] != NULL) {
        all_tokens[++i] = strtok(NULL, "{, }");
    }

    printf("all_tokens[0] : %s \n", all_tokens[0]);
    printf("all_tokens[1] : %s \n", all_tokens[1]);

    char *command = all_tokens[0];
    char *value = all_tokens[1];

    printf("command : %s \n", command);
    printf("value : %s \n", value);

    if (strcmp(command,"message_1") == 0 && strcmp(value,"1") == 0) {
        printf("activating command : %s %s \n\n\n", command, value);
    }

    if (strcmp(command,"message_2") == 0 && strcmp(value,"0") == 0) {
        printf("activating command : %s %s \n\n\n", command, value);
    }
}

int main() {

    char msg1[] = "{message_1, 1}";
    char msg2[] = "{message_2, 0}";

    rcv_msg(msg1);
    rcv_msg(msg2);

}
```

body:
Both versions of your code have undefined behavior. On the given input your code will call `strtok` *three times* and store its result into the array *three times*: for the first token, for the second token and, finally, for the null pointer. You store all three (including that null pointer!) into the `all_tokens` array, which has size `2`.

You are obviously aware of the potential array overrun danger: you even wrote this comment in your code

    char *all_tokens[2]; //NOTE: the message is composed by 2 tokens: command and value

and yet in the following cycle

    int i = 0;

    all_tokens[i] = strtok(rcv_msg, "{, }");
    while (all_tokens[i] != NULL) {
        all_tokens[++i] = strtok(NULL, "{, }");
    }

you still insist on storing more than two values into `all_tokens` array.

---

Also, the second version of your code uses completely different message key values (why is it suddenly `"motor1_pattern1"` instead of `"message_1"`?), which makes it unclear how you compared the functionality of the second version with the functionality of the first.


message:
cannot upload my program to arduino uno

I bought new Uno yesterday, i made my programme, and i compile it. it was good compiled. however, when i upload the programme to my Uno, it cannot be uploaded and there was a message like this

avrdude: stk500_getsync() attempt 10 of 10: not in sync: resp=0x1b
Problem uploading to board.  See http://www.arduino.cc/en/Guide/Troubleshooting#upload for suggestions.

Help me please

body:
1. Make sure u have selected the right COM port
2. Make sure nothing is connected to the pin 0 and 1 in arduino

This happens because the Arduino IDE could not find Arduino Board Connected to the system.


message:
Programing AVR 32u4 via ISP with other ISP device connected

I have a custom PCB with an Atmega 32u4 chip.  I program the chip with AVRDUDE via ISP after it is has been mounted onto the PCB. All is well.

I now want to add wireless capability via the NRF24L01.  The NRF communicates with the 32u4 via ISP.  Can I still program the 32u4 on the PCB after the NRF has been mounted or will there be a problem since they are both connected to the ISP pins?

body:
Yes, that is possible and I've done the exact same thing with an ATmega328 which controls a DAC via SPI. If it wasn't possible ISP wouldn't be an option whenever SPI is already in use.
You should make sure that the NRF's CS pin is high while flashing the firmware, otherwise it might corrupt a checksum verification or memory readout.

Note the difference between ISP (in-system programming) and SPI (serial peripheral interface). Even though ISP uses SPI and they have similar abreviations they are not the same.


message:
Can a Arduino Uno handle all these components?

Its my first project with an Arduino, so please bear with the dumb questions.

For this project of mine, I need an Ultrasonic Sensor, a Gyroscope, a Buzzer, three push buttons and an 16x2 LCD.

Can I connect all these components at once to an Arduino Uno? I mean will I run out of pins or not? Should I go for a Mega 2560 (will have to buy one though).

Edit: a GSM sim800 as well lol

body:
I think you're fine depends on the gyroscope model and lcd.
-For ultrasonic sensor thats 2 pins
-the lcd needs at least 6pins but with an i2c adapter you only need 2 pins
-3 push buttons 3 pins
-one pin for the buzzer
Plenty of room left on the uno


message:
Power Arduino controlled by another Arduino by MOSFET

I would like to control power to Arduino B from signal of digital pin from Arduino A.

I use IRFZ44N MOSFET as switch and +12V DC source. The Arduinos have common ground. The connection is:

 - Gate: signal from Arduino A (+5V or 0V)
 - Source: +12V
 - Drain: Vin of Arduino B

At this settings Arduino B is powered regardless of the value on the gate. What am I doing wrong and how should I change the settings to get the desired result? I know I misunderstand how the transistor works, please show me the correct approach.

body:
You have an N-channel MOSFET. That is not suitable for switching the 12V supply of an Arduino.

Instead you need a P-channel MOSFET which has the gate pulled up to 12V using a resistor, and then an N-channel logic level MOSFET which is used by the Arduino to pull the gate of the P-channel MOSFET LOW to turn it on.

Something like:

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

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

<!-- End schematic -->

When the GPIO is HIGH it turns M2 on. This pulls the gate of M1 down, turning it on. When GPIO is LOW, or not actively being driven (thus being pulled down by R2), M2 is off. This allows the gate of M1 to be pulled up to +12V by R1, switching M1 off.


message:
Python script not reading from serial unless teensy is rebooted

I want to send some analog sensor data from a Teensy 3.2 to a mac running a python script (I am using the usual pyserial module and I send data using Serial.print() in the arduino sketch). I am using Teensy but I guess the same would be true for an Arduino Uno.
The teensy is correctly sending on the serial port the data, as I can see it using the serial monitor. However, only the first time that I run the python script the data are handled by the script itself, if I stop the script then no data seem to be read in the serial buffer. To make the script work I necessarily have to re-launch the Arduino IDE and then upload the sketch.

Indeed the second time I run the script (after having stopped it), I can see that the pyserial function serial_port.inWaiting() does not give any data.
```
if (serial_port.inWaiting() > 0):
   print("serial_port.inWaiting() > 0") # does not print anything the second time I launch the script
```

I have checked that the second time that I launch the script the serial connection is open (using self.serial_port.isOpen())

What is preventing the python script to get the serial data the second time? Why serial_port.inWaiting() is not seeing that there is data in the input buffer?

In the arduino sketch code I have added the line while(!Serial); in void setup()

EDIT: I post the code. This is the arduino code (I am testing on teensy so no initial handshaking is required as teensy will not reboot)

```
int sensor = 0;

void setup() {
  Serial.begin(115200);
  while(!Serial);
}

void loop() {

  sensor = analogRead(0);
  Serial.print(sensor);
}
```

And this is the python code:
```
#!/usr/bin/env python3

import serial
import time
import signal
import sys

def keyboard_interrupt(signal, frame):
    serial_port.close()
    time.sleep(2)
    exit(0)

serial_port = serial.Serial("/dev/tty.usbmodem1225061", 115200)

signal.signal(signal.SIGINT, keyboard_interrupt)
signal.signal(signal.SIGTERM, keyboard_interrupt)

if serial_port.isOpen():
    print(serial_port.name + ' is open...')

while True:
    if (serial_port.inWaiting() > 0):
        sensor = serial_port.read().decode("utf-8")
        print('sensor: "{}" '.format(sensor))

```

body:
Serial communication is always terminated with a specific character (usually `\n`). The receiving device will accumulate the incoming bytes in a buffer until it receives this terminating character.

To fix the problem simply change the last line of your arduino loop to `Serial.println(sensor);`

Also note that the arduino might be faster than your python script, meaning that you will get several sensor values per readout. If that's the case you have to add a short delay in the arduino loop.


message:
Arduino only works properly when I'm touching it

I'm working on a arduino proyect, but I encountered a problem that I dont know how to solve.

The only thing I have done in the hardware part is connect the arduino nano to a power source (phone charger) through the 5v and Ground pins, but the built-in leds tell me that the code isn't running as it should be.
The TX led (Serial output) should be constantly on (because the code is always printing out things to the monitor), but instead it turns on and off in a longer interval of time, the code is running slower than it should be.
This stops when I touch ground with my finger or when the arduino is connected to a computer.

When I searched for a solution I found that most of the time this problem was related to missing connections to ground, and here seems to be the same, but the only thing I have connected is the arduino.

Any idea of what's happening and how to solve it?

To give more context, what I'm trying to do is a thermostat that can take a value of temperature and time, and turn on or off a relay. This relay is the one that opens or closes the electrical circuit of the lab's stove depending on the temperature and the time.
There are 4 buttons:
AUMENTAR ("increase" in english): increases the value selected in 5 (when pressed has a delay of 0.5 seconds).
DISMINUIR ("decrease"): decreases the value selected in 5 (when pressed has a delay of 0.5 seconds).
SIGUIENTE ("next"): changes the value you are editing (has no delay).
INI_DET ("start/stop"): starts or stops the machine (has no delay).

Code:
```
#include <max6675.h>
#include <LiquidCrystal.h>

//
// VARIABLES
//

// Machine's phisical state
int temperatura = 0; // en °C
int temperatura_prev;
// int humedad;
bool maquina_en_funcionamiento = false;

// User's variables (con la maquina no funcionando)
int array_de_valores[] = {20,10};     // valores editables por el usuario
int valor_seleccionado = 0;             // valor que se esta editando (por defecto, temperatura): 0=Temperatura, 1=Tiempo, 2=Humedad
// Variables visibles para el usuario (con la maquina funcionando)
int array_de_opciones[] = {0, 0};       // opciones visibles para el usuario
int opcion_seleccionada = 0;            // opcion visible (por defecto, maquina): 0=Maquina, 1=Operacion

// Process' variables
int temp_bus, tiempo_bus, hum_bus;  // copias de array_de_valores que se mantendran fijas hasta el final del proceso
int reloj = 0;                      // tiempo transcurrido en minutos desde que comenzo el proceso
int reloj_prev;
unsigned long reloj_milis;          // tiempo transcurrido en milisegundos desde que comenzo el proceso
unsigned long inicio_milis;         // milisegundos al comienzo de la operacion
int tiempo_restante;
bool resistencia_en_funcionamiento = false; // estado actual de la resistencia (por defecto, apagada)

// Phisical components
LiquidCrystal lcd(6,7, 2,3,4,5);
MAX6675 sensor_temp(16,15,14);
#define RELE 13
  // botones
#define AUMENTAR 8 // Aumentar valor
#define DISMINUIR 9 // Disminuir valor
#define SIGUIENTE 10 // Cambiar valor
bool sig_pres = false;
#define INI_DET 11 // Iniciar o Detener maquina
bool ini_det_pres = false;

//
// FUNCTIONS
//

// Funciones para control de lcd
void actualizarLCD() {
  if (!maquina_en_funcionamiento) { // si la maquina no esta en funcionamiento
    switch (valor_seleccionado){
      case 0: // temperatura
        lcd.home();
        lcd.print("»TEMP TIEMPO HUM");
        lcd.setCursor(5,1);
        lcd.print(array_de_valores[0]);
        lcd.setCursor(8,1);
        lcd.print("°C");
        break;
      case 1: // tiempo
        lcd.home();
        lcd.print(" TEMP»TIEMPO HUM");
        lcd.setCursor(5,1);
        lcd.print(array_de_valores[1]);
        lcd.setCursor(8,1);
        lcd.print("min");
        break;
      case 2: // humedad
        lcd.home();
        lcd.print(" TEMP TIEMPO»HUM");
        lcd.setCursor(5,1);
        lcd.print(array_de_valores[2]);
        lcd.setCursor(8,1);
        lcd.print("%");
        break;
    }
  }
  else { // si la maquina esta en funcionamiento
    switch (opcion_seleccionada){
      case 0:
        lcd.home();
        lcd.print("»MAQUINA  OPERAC");
        lcd.setCursor(0,1);
        lcd.print("TEMP");
        lcd.setCursor(5,1);
        lcd.print(temperatura);
        lcd.setCursor(9,1);
        lcd.print("TIE");
        lcd.setCursor(13,1);
        lcd.print(tiempo_restante);
        break;
      case 1:
        lcd.home();
        lcd.print(" MAQUINA »OPERAC");
        lcd.setCursor(0,1);
        lcd.print("TEMP");
        lcd.setCursor(5,1);
        lcd.print(temp_bus);
        lcd.setCursor(9,1);
        lcd.print("TIE");
        lcd.setCursor(13,1);
        lcd.print(tiempo_bus);
        break;
    }
  }
}

// Funciones de variables editables por el usuario
void aumentarValor(int cantidad) {
  array_de_valores[valor_seleccionado] += cantidad;
  actualizarLCD();
}
void cambiarValor(){
  switch (valor_seleccionado){
    case 0:
      valor_seleccionado = 1;
      break;
    case 1:
      valor_seleccionado = 2;
      break;
    case 2:
      valor_seleccionado = 0;
      break;
  }
  actualizarLCD();
}

// Funciones de control de proceso
void iniciarResistencia() {
  digitalWrite(RELE, HIGH);
  resistencia_en_funcionamiento = true;
}
void detenerResistencia() {
  digitalWrite(RELE, LOW);
  resistencia_en_funcionamiento = false;
}

void iniciarProc() {
  // realizar una copia de los valores en array_de_valores
  temp_bus = array_de_valores[0];
  tiempo_bus = array_de_valores[1];
  inicio_milis = millis();

  // iniciar la maquina (cuando continue el ciclo)
  maquina_en_funcionamiento = true;

  actualizarLCD();
}
void detenerProc() {
  detenerResistencia();

  // borrar variables
  temp_bus = 0;
  tiempo_bus = 0;
  reloj_prev = 0;
  reloj_milis = 0;
  inicio_milis = 0;
  tiempo_restante = 0;

  maquina_en_funcionamiento = false;

  actualizarLCD();
}

//
// MAIN PROGRAM
//

void setup() {
  // codigo que se ejecuta una unica vez:
  Serial.begin(9600);
  Serial.println("INICIANDO PROGRAMA");

  // relay
  pinMode(RELE, OUTPUT);
  detenerResistencia();

  // buttons
  pinMode(AUMENTAR, INPUT);
  pinMode(DISMINUIR, INPUT);
  pinMode(SIGUIENTE, INPUT);
  pinMode(INI_DET, INPUT);

  //iniciar lcd
  lcd.begin(16,2);
  actualizarLCD();
}

void loop() { // codigo que se ejecuta en bucle:
  // buttons
  if (digitalRead(AUMENTAR) == HIGH) { // if button AUMENTAR is pressed
    if (!maquina_en_funcionamiento) {  // and the machine is not working
      aumentarValor(5);                // increase the value
      delay(500);                      // and wait
    }
  }
  else if (digitalRead(DISMINUIR) == HIGH) { // si se presiona el boton DISMINUIR
    if (!maquina_en_funcionamiento) {        // IDEM AUMENTAR
      aumentarValor(-5);
      delay(500);
    }
  }
  else if (digitalRead(SIGUIENTE) == HIGH) { // si se presiona el boton SIGUIENTE
    if (!sig_pres) {                         // verificar si no se lo presiono antes
      sig_pres = true;                       // poner la var sig_pres en true para bloquear el boton
      cambiarValor();                        // y cambiar la variable
    }
  }
  else if (digitalRead(INI_DET) == HIGH) {   // si se presiona el boton INI_DET
    if (!ini_det_pres) {                     // verificar si no se lo presiono antes
      ini_det_pres = true;                   // poner la var ini_det_pres en true para bloquear el boton
      if (!maquina_en_funcionamiento) {
        iniciarProc();
      }
      else {
        detenerProc();
      }
    }
  }

  if (digitalRead(SIGUIENTE) == LOW) {    // si el boton SIGUIENTE no esta siendo presionado
    if (sig_pres) {
      sig_pres = false;                   // desbloquear el boton
    }
  }
  if (digitalRead(INI_DET) == LOW) { // si el boton INI_DET no esta siendo presionado
    if (ini_det_pres) {
      ini_det_pres = false;               // desbloquear el boton
    }
  }

  // Some output of data to the Serial monitor
  Serial.print("Valor seleccionado: ");
  Serial.println(valor_seleccionado);
  Serial.print(array_de_valores[0]);
  Serial.print(", ");
  Serial.println(array_de_valores[1]);
  Serial.print("Maquina en funcionamiento: ");
  Serial.println(maquina_en_funcionamiento);

  // PROCESS CONTROL
  if(maquina_en_funcionamiento) {

    // TEMPERATURE CONTROL
    temperatura_prev = temperatura;
    temperatura = sensor_temp.readCelsius();

    if (temperatura >= temp_bus) { // si la temperatura es igual o exede la deseada
      detenerResistencia(); // apagar la resistencia
    }
    else { // si la temperatura es menor que la deseada
      if (!resistencia_en_funcionamiento) { // y la resistencia esta apagada
        iniciarResistencia();
      }
    }

    if (temperatura_prev != temperatura) {
      actualizarLCD();
    }

    // TIME CONTROL
    unsigned long milis_ahora = millis();
    milis_ahora -= inicio_milis;
    if ( (milis_ahora - reloj_milis) >= 1000){
      reloj_milis = reloj_milis + 1000;
    }

    reloj_prev = reloj;
    reloj = reloj_milis/60000;

    tiempo_restante = tiempo_bus - reloj;
    /*
    Serial.print("Reloj de milisegundos=");
    Serial.println(reloj_milis);
    Serial.print("Reloj=");
    Serial.println(reloj);
    Serial.print("Tiempo restante=");
    Serial.println(tiempo_restante);
    */
    if (reloj >= tiempo_bus) { // si se llego al tiempo deseado
      detenerProc(); // detener
    }

    if (reloj_prev != reloj) {
      actualizarLCD();
    }

  }
}
```

Thanks in advance.

body:
> This stops when I touch ground with my finger or when the arduino is
> connected via USB to a computer.

It sure sounds like a grounding problem, probably between the PC and the Arduino. Try connecting the Arduino ground and the PC ground - my guess is that the problem goes away.

All of the electrical components in a system need to share the same ground for any communication to take place. It sounds like one of them might not.

Is either the PC or the charger plugged into the wall with an adapter that only carries two of the three wires? Usually each one will connect to ground side of the house circuit but if one of them doesn't ...


message:
6 channel PWM with 2 - 5 kHz frequency

Is it possible to set all 6 PWM frequencies to a value between 2 and 5 kHz?

I've read that the base frequency for pins pins 5 and 6 is 62500 Hz.
And the divisors for the pins 5 and 6 are only this ones: 1, 8, 64, 256, and 1024.

The closest I can get is 7.812,5 Hz with the 8 divisor. Are there any other possibilities to achieve this?

body:
Judging from your mentioning 62.5 kHz as the base frequency for
pins 5 and 6, I assume you are talking about an Arduino Uno or
something similar.

If you set the timer 0 to phase correct PWM mode (which is how the
Arduino core configures the other timers), then its base frequency is
about 31.373 kHz (`F_CPU`/510). With the prescaler set
to 8, you get a PWM frequency of about 3.922 kHz on pins
5 and 6.

Note that you can set all three timers in this mode and have 6 PWM
channels at this frequency. But note also that by reconfiguring
Timer 0 you loose all the standard Arduino timing functions.


message:
Is it possible to output a variable clock using Fast PWM?

I am trying output a clock and change its frequency dynamically with a rotary encoder.

When the code for the rotary encoder is included the clock doesn't reach its max freq(31Khz). But without the rotary encoder code, it does. What is happening that it can't reach its max freq?

    const byte CLOCKOUT = 9;
    int val;
    int encoder0PinA = 3;
    int encoder0PinB = 4;
    int encoder0Pos = 0;
    int encoder0PinALast = LOW;
    int n = LOW;

    void setup() {
      pinMode (CLOCKOUT, OUTPUT);
      // set up Timer 1
      TCCR1A = bit (COM1A0);  // toggle OC1A on Compare Match
      TCCR1B = bit (WGM12) | bit (CS12);   // CTC, no prescaling
      OCR1A =  0;

      pinMode (encoder0PinA, INPUT);
      pinMode (encoder0PinB, INPUT);
      Serial.begin (9600);
    }

    void loop() {
      n = digitalRead(encoder0PinA);
      if ((encoder0PinALast == LOW) && (n == HIGH)) {
        if (digitalRead(encoder0PinB) == LOW) {
          OCR1A-=100;
        } else {
          OCR1A+=100;
        }
        Serial.print (OCR1A);
        Serial.print ("/");
      }
      encoder0PinALast = n;
    }

The Code that reaches the Max freq properly is below

    void setup ()
      {
      pinMode (CLOCKOUT, OUTPUT);
      // set up Timer 1
      TCCR1A = bit (COM1A0);  // toggle OC1A on Compare Match
      TCCR1B = bit (WGM12) | bit (CS12);   // CTC, no prescaling
      OCR1A =  0;
      }

    void loop (){
      }

body: PWM doesn't vary frequency. It holds the frequency steady and varies the duty cycle of the output. (Percent of on-time to total time.) So unless fast Arduino PWM does something very unconventional, the answer to the question you asked is no.


body:
I'm not sure whether this is the real issue you have, but I spot an issue which can be the issue you have.

You wrote something like this:

    if (pulseFromEncoder)
      if (direction1)
        OCR1A -= 100;
      else
        OCR1A += 100;

Now, the OCR1A is a unsigned 16 bit integer. A value of 100 corresponds to 1.6ms of delay on the timer (see comment from Edgar Bonet below). This is what happens when you rotate in direction 2:

            OCR1A  Time delay
    Rotate:   300      4.8ms
    Rotate:   200      3.2ms
    Rotate:   100      1.6ms
    Rotate:     0      0ms
    Rotate: 65436   1047ms

See? The value rolls over and the time completely changes.

Now, maybe the issues are other (for instance changing the mode to 15 instead of 4 like EdgarBonet said (no idea on what this means, you should double check the differences on the atmega datasheet), but I strongly suggest you to fix this issue, for instance this way:

    const uint16_t OCR1A_Min = 0
    const uint16_t OCR1A_Max = 20000
    const uint16_t OCR1A_Step = 100

    ...

    if (pulseFromEncoder)
      if (direction1)
      {
        if (OCR1A > OCR1A_Min + OCR1A_Step)
          OCR1A -= OCR1A_Step;
        else
          OCR1A = OCR1A_Min;
      }
      else
      {
        if (OCR1A < OCR1A_Max - OCR1A_Step)
          OCR1A += OCR1A_Step;
        else
          OCR1A = OCR1A_Max;
      }

Sidenote: doesn't your encoder need debounce?


message:
Two rpm counters with interrupts

Can I use two interrupts on to count rpm square signals coming from two hall effect sensor modules (that has built in comparators to generate square signals) ?

What if two signals come together ? Will they conflict with each other ?

Will this work on attiny85 ?

I used to use two interrupt to read encoders where the two signals never conflict with each other

Thank you in advance

body:
There is more than 1 option how this can be done. A frequency of 40Hz is relatively slow, so you are not limited by this.

In my comment I first suggested to use the Timers/Counters with the signal as input, but I found, that this is only possible with one of the two timers of the ATtiny. Despite that, I will add this to the answer for information (and because this can be possible on other boards with more timer input pins).

- **Using the PinChange interrupt and doing counting in software:** Since the ATtiny85 has only 1 external interrupt, you have to use the PinChange interrupt for this. If activated, this interrupt will trigger, when ever one of the pins 0 to 5 changes it's value. You can mask away any pin in this range, so that it doesn't count. You would use 2 pins and mask the others away. In the interrupt routine you would check the state of the two pins and increment the respective counter:

        volatile unsigned int counter1=0;
        volatile unsigned int counter2=0;

        ISR(PCINT0){
            if(digitalRead(input_pin_1)) counter1++;
            if(digitalRead(input_pin_2)) counter2++;
        }

    (Note the `volatile` declaration of the variables, because they change inside of an ISR). The `counterX` variables can then read in defined time intervals (for example very second) to calculate the RPM. Of course, executing code in an ISR can mean, that you miss another interrupt. During the short time period between the first interrupt and the completed execution of the ISR no other PinChange interrupt will get registered. If that is a problem is dependend on how often the pulses will be inside this small range. If that only happens very rarely you can ignore that, since it introduces only very small errors. You can even make the ISR faster by not using `digitalRead()`, which takes a bit to execute, but using direct [Prt Manipulations][1]. That makes the error more unlikely.

    The interrupts have to be configured for this, so you need a setup code like this (this will use direct manipulation of the status registers of the ATtiny):

        PCMSK = 0b000110; // Mask all pins for this interrupt,except for PCINT1 and PCINT2
        GIFR &= ~(1 << PCIF); //Clear PinChange interrupt flag
        GIMSK |= (1 << PCIE); //Enable PinChange interrupt

    In the loop function you can use the non-blocking code style from the `BlinkWithoutDelay` example, to regularly calculate the RPM from the counter values;

        void loop(){
            if(millis()-timestamp > INTERVAL){
                GIMSK &= ~(1 << PCIE); //Disable PinChange Interrupt, so that we don't get interrupted by ti
                unsigned int countervalue1 = counter1;
                unsigned int countervalue2 = counter2;
                counter1=0;
                counter2=0;
                IMSK |= (1 << PCIE); //Reenable PinChange interrupt
                // Do the calcuation here with countervalueX and show the result somewhere
            }
        }

    It is important to disable the corresponding interrupt, when you are accessing the `counterX` variables, because you have to prevent them from changing midway during processing. To keep this short, they are just copied to local variables and then released again.

---
Attention: the following suggestion doesn't work on an ATtiny85, since it only has 1 timer input pin.

- **Using both available Timers/Counters and the signals as clock input:** If you really don't want to miss any pulses, you can utilize two Timers/Counters. Timers and Counters are the same. A counter increments a status register on every falling or rising edge (depending on the configuration) of a signal. If this signal is derivated from the chips clock, this is called a Timer. You would use it as a Counter, feeding each square wave to one Counter input pin. To actually get the RPM, you can either check the counters value (TCNT0) after defined time interval, or you can activate the overflow interrupt of both timers and measure the time between the overflows.

    Since here the edge-sensing is done in hardware, no pulse can be missed. On the other side, this way needs more configuring and blocks 2 precious timers.

---

When working with the status registers in such a direct way, the [datasheet of the ATtiny85][2] is a must read.

  [1]: https://www.arduino.cc/en/Reference/PortManipulation
  [2]: http://ww1.microchip.com/downloads/en/DeviceDoc/Atmel-2586-AVR-8-bit-Microcontroller-ATtiny25-ATtiny45-ATtiny85_Datasheet.pdf


body:
If you can skip using interrupts, your Tiny could still do the job and not miss any pulses, as long as loop() can be executed at >40Hz, and the pulses are not be extremely short "spikes" but have a reasonable duty-cycle (or if short, you can sample faster):

    // Pin data
    static struct {
       uint8_t pinNum;
       bool wasHi;       // last state
       unsigned count;   // pulse count
    } pinsDat[2] = {
       {input_pin_1, false, 0},
       {input_pin_2, false, 0},
    };

    void setup(){
       ; // your setup here
    }

    void loop(){
       countPulses();
       // ...
    }

    void countPulses(){
       for( uint8_t i = 0; i < 2; ++i){
          if( !digitalRead(pinsDat[i].pinNum) )
             isHigh1 = false;       // pin lo, just save its state
          else if( !pinsDat[i].wasHi ){
             ++pinsDat[i].count;    // pin hi; count it
             ++pinsDat[i].wasHi;    // save its state
          }
       }
    }


message:
Using MPU-6050 without I2C

My target is to use multiple MPU-6050 at once, I searched on the internet and found that they can be hooked up really simply. Just connect in parallel and use [I2C-Scanner](https://playground.arduino.cc/Main/sourceblock_1/index.txt?action=sourceblock&num=1). Then get those addresses and use normally.

But I can't find another address, there appears to be just one address `0x68`, that is the reason why, I want to connect my other MPU-6050 in other pins.

How this can be achieved ?

body:
As you can read in [the MPU-6050's datasheet][1], it uses the I2C address `0b110100X`, where `X` is the state of the pin AD0. If you wire AD0 to ground, the address will be `0b1101000`, whereas if you wire it to Vcc it will be `0b1101001`. That is equivalent to the addresses `0x68` and `0x69`.

That means, that - depending on how you wire AD0 - you can have 2 distinct MPU-6050's on the same I2C bus (you cannot have devices with the same address).

If you really need to connect more than 2 of them, you have to use an I2C multiplexer like [PCA9544A][2], which will divide the bus down to sub-busses.

---

EDIT: Usually the address pins of I2C devices are set permanently by wiring them either to ground or Vcc. The sense of the address system is, that a slave device will stay at it's address, not changing it. But as Jot reported in the comments and as the [Arduino Playground site of the MPU-6050][3] confirms, you can actually set the address pin of the MPU-6050 during operation.

You need 1 digital output pin on your Uno for each MPU, which then get's tied to the MPU's AD0 pin via a voltage divider. The last part is important: You need a voltage divider, because the MPU is a 3.3V device, while the Uno works with 5V. To avoid frying the address pin, you need to step down the voltage.

Then you would use the address pins to set all MPU's to one address (let's say `0x69`). When you need to communicate with one of them, you toggle it's address pin, which will change it's address (in this case to `0x68`). Then you can use the normal I2C workflow with this address (`0x68`). When you are done, you can put this MPU back to the other address by again toggling the address pin. You can repeat this with any of the connected MPU's, which can be many (I think the limit here is the I2C bus itself with it's wires capacity).

This is a workaround and not really, what the I2C bus is meant for. But it seems to be valid solution. Just be sure, that the addresses, that you communicate with, are always unique. Contacting an address, which belongs to more than 1 device, will block your I2C bus.

  [1]: https://cdn.sparkfun.com/datasheets/Components/General IC/PS-MPU-6000A.pdf
  [2]: https://www.ti.com/lit/ds/symlink/pca9544a.pdf
  [3]: https://playground.arduino.cc/Main/MPU-6050/


body:
You can connect more than 2 in serial by using the Address bit like a chip select.
Say you had 8 of them. Use a shift register with the 8 outputs going to the 8 chips. Now output 0b00000001 and use I2C address 0x69, only the one device with a 1 on its address line will reply. Then use 0b00000010 for the 2nd device, 0b00000100 for the 3d, etc. up to 0b10000000 for the 8th.


message:
Connect MPU6050 in pins other than A4 & A5

I need to use a MPU6050 gyro and a Ultrasonic sensor for my project. My Arduino Uno did not come with separate SDA and SCL pins, so I have to use the A4 and A5 pins for that purpose, and I have connected the Ultrasonic sensor with them.
\With no SDA and SCL pins available, and A4 and A5 already occupied, is there any way to use other pins like A0 and A1 for SDA and SCL connections?

body: A4/A5 are the I2C Bus. You will connect multiple I2C devices in parallel to the pins. I would suggest wiring them Uno to device to device, with pullup resistors 3.3K or 4.7K pullup resistors to Vcc on the last device.


body:
Your Uno did not come with seperate SDA and SCL pins, because on the microcontroller, that is used on the Uno (Atmega328p) these pins are shared too. That is a common practice, because not everyone needs I2C, but may want more analog pins.

You have basically 2 ways to go here:

- You can leave the ultrasonic sensor, where it is connected now, and try it with a software I2C library like [this one][1], that can be used on nearly any other pin pair. Note, that in this case the I2C protocol will be completely handled in software, which puts a bigger workload on the microcontroller and may need other resources, that you want to use later (for example it might use timer hardware).

- You can put the ultrasonic sensor to other pins, because it is not limited anyway. You can use any digital pin pair. The MPU can then be connected to A4 and A5, as they are the pins of the hardware I2C interface. IMO this is the cleaner solution, since the core of the I2C protocol will be handled in hardware without the code doing anything for it. The code just puts the data into a buffer, not more. Also it will not use any other hardware inside of the microcontroller.

Which of these options is the best here is up to you. Maybe you have a good reason to not move the ultrasonic sensor to other pins.

  [1]: https://playground.arduino.cc/Main/SoftwareI2CLibrary/


message:
Help Troubleshooting L298n connected to dc motor

I am relatively new to Arduino, and I am trying to power a DC motor with the L298N dual H-Bridge. I have done as follows:
I am powering everything with the Arduino that is connected to the PC. (I know this isn't ideal, but I don't have a better power supply yet)
I connected the 5V output from Arduino to the 12V terminal of the L298N, and connected it to the Arduino ground. The red light from the L298N shines brightly.
Then, I connected the IN3 and IN4 pins to the Arduino digital pins 7 and 8, respectively.
Finally, I connected the Out 3 and Out 4 to my DC motor, but it doesn't turn at all. I use the following code:
<!-- language-all: lang-cpp -->

    int In3=7;
    int In4=8; //idem para In2

    void setup() {
      pinMode(In3,OUTPUT); //avisa que nuestros pines son todos outputs
      pinMode(In4,OUTPUT);

      digitalWrite(In3,HIGH);
      digitalWrite(In4,LOW);
    }

    void loop() {

    }

For the time being I decided to not use the PWM, so that I can start simple. I tried changing all cables and even the motor, but it just won't rotate. The L298N is brand new, so it's unlikely that it is damaged. What could I try next?

body: I realized that I had the jumper disconnected from the ENB pins, which immediately solved the problem when I reconnected it, so it is now fixed!


message:
Troubleshooting WS2812B LED strip

I am doing a project for my master thesis and I have 6 stripes of [WS2812B][1] LEDs each one containing 77 LEDs. I finished the design and now want to turn them on.

I used an old power supply to power it, but now that I am running it, doesn't work. I checked the voltage with a multimeter and it shows that I have 5 volts and it seems doesn't have any problem but the data doesn't transfer to my strip.

I just copy past FastLED from libraries and changed the number of LEDs. I thought maybe I am using the Funduino from school, maybe this is a problem and I need another Arduino board?

[![Photo of test][2]][2]
[![Circuit][3]][3]

  [1]: https://cdn-shop.adafruit.com/datasheets/WS2812B.pdf
  [2]: https://i.stack.imgur.com/8YCSZ.jpg
  [3]: https://i.stack.imgur.com/DOR9G.jpg

body:
Are you completely sure that these are WS2812B LEDs? To read more, check out this great link from Core Electronics:
[https://core-electronics.com.au/tutorials/addressable-rgb-led-controllers.html][1]

It is more than likely your code. Download the code from a known working example and get that working. Try using an example program such as:

 - https://howtomechatronics.com/tutorials/arduino/how-to-control-ws2812b-individually-addressable-leds-using-arduino/
 - https://core-electronics.com.au/tutorials/ws2812-addressable-leds-arduino-quickstart-guide.html
 - https://learn.adafruit.com/adafruit-neopixel-uberguide/software

Once you have known working hardware then delve into your own code and find the problem.

Also check your wiring with fresh eyes. It could be something simple.

  [1]: https://core-electronics.com.au/tutorials/addressable-rgb-led-controllers.html


message:
Electret microphone board strange offset using Arduino

I'm experimenting with an electret microphone, specifically [this one][1].  I put it on my scope and I see what I expect - a really small voltage, typically under 20mV, that varies appropriately with sound.

However, when I put it into my Arduino (connecting signal pin to A0, V to 5V, and G to GND) and read it using analogRead on the appropriate pin, I end up getting a strange offset.  The analog read should read 0 more or less constantly, due to the low voltage coming out of the board.  However, I get an offset of around 425 counts on the ADC, implying that the voltage is somewhere around 2.5V.

What's going on?  Why would the arduino be reading a voltage when there isn't any?

  [1]: https://www.itead.cc/electronic-brick-sound-sensor-microphone-brick.html

body:
An electret microphone is like a resistor which changes its value according to the sound.

To use it you must form a voltage divider with it, as if it were half of a potentiometer.

Thus you add a resistor to +5V (which is already on the board).  This means that when it is silent the voltage you get is the ratio of the resistor and the resistance of the microphone.

If the resistance has been chosen correctly then the output you get should be roughly half the supply voltage when silent. Any sound will cause that output to swing around that "zero" point.

It's just like a potentiometer.  When silent the potentiometer is in the central point. When you make noise you're moving the potentiometer in both directions.

To get rough values you should first get the "silent" reading from analogRead. You can then subtract that value from all subsequent readings.

Note that the results will be non-linear. To do it properly you should calculate the resistance of the microphone by using the supply voltage, the "upper" resistor value, and the sampled voltage to calculate the resistance value like you would for any other resistive sensor (such as an LDR or force sensitive resistor).


message:
Arduino - Print file name

I need my sketch to print the name of the original INO file at the beginning of execution (during `setup`).

Is it possible?  If so, what is the resource which should be used?

body:
You can use the macro `__FILE__` to get the filename that is being compiled.  That may not be your INO file, but may be some derivative of it.

    Serial.println(__FILE__);

You also get some other handy macros:

    __DATE__
    The date the sketch was compiled

    __TIME__
    The time the sketch was compiled

    __LINE__
    The line number where __LINE__ is being used

The combination of `__FILE__` and `__LINE__` is commonly used for debugging:

    Serial.prinln("Error 23 at line " __LINE__ " of " __FILE__);


message:
How to use I2C library

My A4 and A5 pins are already hooked up to a LCD and I want to connect a MPU6050 as well. In a separate thread, someone told me to use SoftI2CMaster library to use other pins as SDA ans SCL. But I don't quite know how to do that. I want to use A2 and A3 for I2C, and a code snippet would be very helpful.

body:
Use both devices on I2C, with different addresses.  Hook it up like this

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

And call each transmission with a different address

    void setup() {
      Wire.begin();                           //begin the wire comunication
      Wire.beginTransmission(0x68);

Image and snippet from [electronoob's very complete tutorial][2]

  [1]: https://i.stack.imgur.com/LRZL4.png
  [2]: http://www.electronoobs.com/eng_arduino_tut76.php


message:
Using a photo resistor to detect objects of a certain color

I am trying to build a robot that detects cubes of a certain color, and later picks them up.

I was planning to use a camera and process the image, but I was told that Arduino is not capable of image processing.

Now, I was thinking that I could maybe use a photoresistor that is enclosed by a green light filter sheet (so that only the light of a certain color can pass). Thus, if my robot is facing a cube of the color I want, the photoresistor should detect this.

Is this at all possible? I know how filters work in theory, but I have never used one before.

If not, is there another way to try to detect color using an Arduino?

body:
Nice theory but since you're facing real-world conditions and not ideal ones, I think you'll have a hard time with this approach. I.e. your cube is likely not the same shade of green that your filter lets through. What about lighting - do you have a neutral white light source? I recommend you take a look at this [Arduino RGB Sensing Tutorial using the TCS230 Colour Sensor][1] for a headstart.

  [1]: https://howtomechatronics.com/tutorials/arduino/arduino-color-sensing-tutorial-tcs230-tcs3200-color-sensor/


body:
Use a TCS230 photo sensor and a 6500K light source to color correct your objects.

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

This hookup will get you started

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

This sketch, courtesy of [Best-Microcontroller-Projects][3]  will get you going.  [Read the tutorial][4] and dont forget to calibrate.

    //
 // Detect colors using TCS230.
 //

 // Arduino uno pins for control of TCS230
 #define TCS320_OE 7
 #define TCS320_S0 10
 #define TCS320_S1 11
 #define TCS320_S2 2
 #define TCS320_S3 3
 #define TCS320_OUT 4

 #define variance 50  // Acceptable detection error 2%.

 #define SEL_RED  \
    digitalWrite(TCS320_S2,LOW);digitalWrite(TCS320_S3,LOW)
 #define SEL_GREEN \
    digitalWrite(TCS320_S2,HIGH);digitalWrite(TCS320_S3,HIGH)
 #define SEL_BLUE \
    digitalWrite(TCS320_S2,LOW);digitalWrite(TCS320_S3,HIGH)
 #define SEL_CLEAR \
    digitalWrite(TCS320_S2,HIGH);digitalWrite(TCS320_S3,LOW)

 #define TWO_PER \
    digitalWrite(TCS320_S0,LOW);digitalWrite(TCS320_S1,HIGH);

 #define debug(a) Serial.println((a));

 #define NUMCOL 5

 // int RGB[NUMCOL][3]; // Five colors with 3 elements.
 // Array of NUMCOL strings len 10. 11 for null.
 // char colname[NUMCOL][11];

 // Typical values for 2% dividers (set variance to 50).
 int RGB[NUMCOL][3]={
    {248,647,393},
    {188,261,265},
    {404,710,546},
    {506,493,304},
    {930,1199,837},
 };

 char colname[NUMCOL][11]={
 "red",
 "yellow",
 "brown",
 "blue",
 "black",
 };

 ////////////////////////////////////////////////////////////////
 void setup() {

    pinMode(TCS320_OE,OUTPUT);
    pinMode(TCS320_S0,OUTPUT);
    pinMode(TCS320_S1,OUTPUT);
    pinMode(TCS320_S2,OUTPUT);
    pinMode(TCS320_S3,OUTPUT);
    pinMode(TCS320_OUT,INPUT);

    TWO_PER;

    digitalWrite(TCS320_OE,LOW); // On always.

    Serial.begin(115200);
    Serial.println("TCS230 color detector");
 }

 ////////////////////////////////////////////////////////////////
 unsigned long get_TCS230_reading(void) {
   unsigned long val;
   noInterrupts();
   val = pulseIn(TCS320_OUT,HIGH,20000); // 2000us=2ms  2Hz min.
   interrupts();
   return val;
 }

 static int clr,red,green,blue;

 ////////////////////////////////////////////////////////////////
 uint16_t detect(void) {
    unsigned long val;

     SEL_RED;
     red = val = get_TCS230_reading();
     Serial.print("RED: "); Serial.print(val);

     SEL_GREEN;
     green = val = get_TCS230_reading();
     Serial.print(" GREEN: "); Serial.print(val);

     SEL_BLUE;
     blue = val = get_TCS230_reading();
     Serial.print(" BLUE: "); Serial.print(val);

     Serial.print(" \n");
 }

 ////////////////////////////////////////////////////////////////
 int withinEQ(int c, int xl, int xh) {
    if (c>=xl && c<=xh) return 1;
    return 0;
 }

 ////////////////////////////////////////////////////////////////
 // Compare a value to a value and variance.
 int compare(int c, int v, int err) {
 int xh=v+err, xl=v-err;
    if (withinEQ(c,xl,xh)) return 1;
    return 0;
 }

 ////////////////////////////////////////////////////////////////
 void loop() {
 uint8_t chr,i,fnd;

    if (Serial.available()>0) {

       chr = Serial.read(); // Consume.

       // Find color match.
       detect();
       fnd=0;
       for (i=0;i<NUMCOL;i++) {
   if ( compare(red,RGB[i][0],variance) &&
        compare(green,RGB[i][1],variance) &&
        compare(blue,RGB[i][2],variance)
      ) { // Found
        Serial.print("Col is :");
        Serial.println(colname[i]);
        fnd=1;
        break;
      }
       }
       if (!fnd) Serial.println("NOT Found");
    }
 }

  [1]: https://i.stack.imgur.com/GgpTR.jpg
  [2]: https://i.stack.imgur.com/e4FQR.png
  [3]: https://www.best-microcontroller-projects.com/
  [4]: https://www.best-microcontroller-projects.com/tcs230.html


message:
Print unsigned long long in ESP8266

I need to print an unsigned long long variable:

`unsigned long long t = 1559072327000ULL;`

I have tried the following:

    Serial.println(t); // call of overloaded 'println(uint64_t&)' is ambiguous

    char[18] buf;

    sprintf(dt, 18, "%lu", t); // Prints 4294165848

    snprintf(dt, 18, "%lu", t); // Prints 126

    vsnprintf(dt, 18, "%lu", t); // cannot convert 'uint64_t {aka long long unsigned int}' to '__gnuc_va_list {aka __va_list_tag}'

Any suggestion?

body:
Okay, I figured out... this two prints the right number:

    sprintf(dt,"%llu", t);
    snprintf(dt, 18, "%llu", t);


message:
Controlling a 5m LED strip with a Nano or Uno

I'm wanting to control a 12V LED strip (5m, 60 LEDs per meter) with a Nano or Uno. I know from [Adafruit][1] that I'll need some power transistors but I'm not sure that I have the right type. I have 6 transistors labelled [30N06L][2], and I'm hoping they're equivalent to the [ones used][3]. Are mine ok to use, or do I need to buy others?

  [1]: https://learn.adafruit.com/rgb-led-strips/usage
  [2]: https://cdn.sparkfun.com/datasheets/Components/General/FQP30N06L.pdf
  [3]: https://www.adafruit.com/product/355

body:
You have a lot of LEDs that you need to power so lets run through the calculations. Assuming that they are RGB LED strips, ie 3 LEDs per physical LED:

    5 x 60 x 3 = 900 LEDs

Assuming each has a current draw of 20mA, that is (900 x 20mA) 18A of total current if all are on at the same time at full brightness.

Since each colour will be controlled by its own FET, each FET will be required to drive 6A at full brightness.

The FET that you have is a [Fairchild FQP30N06L 60V LOGIC N-Channel MOSFET][1] that can drive up to 32A. Of course, that would need a large heatsink at that current.

If you plan to have any of the colours on at full brightness for extended periods I would recommend putting a heat sink on the tab to help dissipate the heat.

The Arduino Uno/Nano uses a 328P microcontroller at 5V which, according to the datasheet, is suitable to drive the FET.

**These FETs should do the job.**

  [1]: https://cdn.sparkfun.com/datasheets/Components/General/FQP30N06L.pdf


message:
What type of Arduino to buy

I am doing a project for school to run 462 LEDs in 6 series (77 each) and a stepper motor altogether, I wanna know what model of Arduino I should buy (not so expensive)?
I am using individually addressable WS2812B RGB LED strips ...
So it should be controlled in 6 groups of 77 LEDs in each group.
[![enter image description here][1]][1]

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

body:
With these requirements you can use most available Arduinos. The WS2812 LED strips need 1 pin per strip (or 1 pin in total, if you daisy-chain all the strips, meaning connecting the data lines of them to one big strip). How many pins you need for the stepper motor depends on the type of motor and what type of driver you have for it. Most stepper drivers need 2 digital pins from your Arduino (1 direction pin and 1 pulse pin). There are also cheap drivers based on the ULN2003 chip, where you have to control the phases directly, needing 4 pins.

You should also buy an Arduino, that leaves you a big headroom to develop your project further, if you want.

An Arduino Uno or Nano would be good fitting for this project (though smaller Arduinos like the Pro Micro also would work). If you are able to order them over sites like Aliexpress directly from china (and if you are ok with a longer shipping time), you can get Nanos for 1 - 2$.

---

Since you have many LEDs, you really have to consider your power supply. 462 LEDs, which need up to 60mA each (20mA for each colour in full brightness), means you need at least a 28A power supply (in total). And don't draw the LED current through the Arduino, or you will fry it's voltage regulator or diode.


message:
GSM incoming bytes from UART not complete

I have used AT commands to read incoming bytes from serial buffer from SIM900A but I cannot get the complete message using the code below:
<!-- language-all: lang-cpp -->

    while(ss.available()>0)
    {
  inChar=ss.read();
  inString+=inChar;
    }

    Serial.println("Received messaged: ");
    Serial.println(inString);

    inString="";

However this one below works:

    if(ss.available()>0)
    {
   inString=ss.readString();
    }

    Serial.println("Received messaged: ");
    Serial.println(inString);

    inString="";

I wonder what is the difference?

body: The data arrive over serial very slow compared to MCU speed. In the first snippet you stop reading at first gap between bytes (available is 0). In the second snippet the function `readString` will wait for the next byte until a second (at default).


message:
How to send data from firebase php to arduino?

***In the project I am working on***

> I want to send data to firebase going to arduino this specifically by
> sending an information to change the wifi

***SSID***

***password***

> materials I used:

***esp8266-01***

***arduino uno r3***

***firebase***

***web server (000webhost)***

> code for arduino

        #include <SoftwareSerial.h>
    #include <DHT.h>;
    SoftwareSerial Serial1(10, 11);
    #define Trash "Trash3"
    #define DHTTYPE DHT11
    #define DHTPIN 2
    #define TRIGGER_PIN 4
    #define ECHO_PIN 3

    DHT dht(DHTPIN, DHTTYPE, 11);

    float humidity, temp_f;
    int distance;
    long duration;

    String buff(64);
    String getStr(128);

    void setup() {

      Serial.begin(9600);

      Serial1.begin(9600);
      //Serial1.resetESP();
      delay(2000);
      Serial1.setTimeout(5000);

      dht.begin();
      pinMode(TRIGGER_PIN, OUTPUT);
      pinMode(ECHO_PIN, INPUT);

      if (!connectWiFi()) {
        Serial.println("Can not connect to the WiFi.");
        while (true)
          ; // do nothing
      }
      Serial.println("OK, Connected to WiFi.");

      sendCommand("AT+CIPSTA?");
      //sendCommand("AT+CIPDNS_CUR?");
      sendCommand("AT+CIPSTAMAC?");

    }

    void loop() {

      temp_f = dht.readTemperature();
      humidity = dht.readHumidity();
      digitalWrite(TRIGGER_PIN, LOW);
      delayMicroseconds(2);
      digitalWrite(TRIGGER_PIN, HIGH);
      delayMicroseconds(10);
      digitalWrite(TRIGGER_PIN, LOW);

      duration = pulseIn(ECHO_PIN, HIGH);
      distance = duration * 0.034 / 2;

      // connect to server
      if (sendCommand("AT+CIPSTART=\"TCP\",\"gg.com\",80")) {
        Serial.println("connected to Cloud");

        // build HTTP request
        getStr = "GET /upload.php?trash=";
        getStr += Trash;
        getStr += "&distance=";
        getStr += distance;
        getStr += "&temp_f=";
        getStr += temp_f;
        getStr += "&humidity=";
        getStr += humidity;
        getStr += " HTTP/1.1\r\n";
        getStr += "Host: gg.com\r\n\r\n";

        // open send buffer
        buff = "AT+CIPSEND=";
        buff += getStr.length();
        if (sendCommand(buff.c_str()) && Serial1.find(">")) { // AT firmware is ready to accept data

          // send HTTP request
          Serial.println(getStr);
          Serial1.print(getStr);

          // print HTTP response
          if (Serial1.find("+IPD,")) { // response received
            int l = Serial1.parseInt();
            while (l > 0) {
              if (Serial1.available()) {
                Serial.write(Serial1.read());
                l--;
              }
            }
            Serial.println("--------------");
          } else {
            Serial.println("no response");
          }
        } else {
          Serial.println("send error");
        }
        sendCommand("AT+CIPCLOSE");
      } else {
        Serial.println("Error connecting");
      }
    }

    bool connectWiFi() {

      if (!sendCommand("ATE0")) // echo off
        return false;
      if (!sendCommand("AT+CIPMUX=0")) // set single connection mode
        return false;
      if (!sendCommand("AT+CWMODE=1")) // set STA mode
        return false;
      return sendCommand("AT+CWJAP=\"CAPSTONE\",\"capstonemis\"");
    }

    bool sendCommand(const char* cmd) {
      Serial.println(cmd);
      Serial1.println(cmd);
      while (true) {
        buff = Serial1.readStringUntil('\n');
        buff.trim();
        if (buff.length() > 0) {
          Serial.println(buff);
          if (buff == "OK" || buff == "SEND OK" || buff == "ALREADY CONNECTED")
            return true;
          if (buff == "ERROR" || buff == "FAIL" || buff == "SEND FAIL")
            return false;
        }
      }
    }

> code for firebase

    <?php

    require 'firebaseLib.php';
    $Trash = $_GET["trash"];

    $Distance = $_GET["distance"];
    $Temperature = $_GET["temp_f"];
    $Humidity= $_GET["humidity"];

    // --- This is your Firebase URL
    $baseURI = 'https://thesis1-69.firebaseio.com';
    // --- Use your token from Firebase here
    $token = 'gg';
    // --- Here is your parameter from the http GET

    $devicestatus= array('Distance' => $Distance,'Temperature' => $Temperature,'Humidity' => $Humidity);

    $firebasePath = '/thesis1-69/';

    $full= array($Trash => $devicestatus);

    /// --- Making calls
    $fb = new Firebase($baseURI, $token);
    $fb -> update($firebasePath, $full);

    ?>

any  guide and help can help me a lot
thank you so much :)

body:
add global variable `String data;` and in loop()

    data = "trash=";
    data += Trash;
    data += "&distance=";
    data += distance;
    data += "&temp_f=";
    data += temp_f;
    data += "&humidity=";
    data += humidity;

    // build HTTP request
    getStr = "POST /upload.php HTTP/1.1\r\n";
    getStr += "Content-type: application/x-www-form-urlencoded\r\n";
    getStr += "Content-length: ";
    getStr += data.length();
    getStr += "\r\nHost: gg.com\r\n\r\n";
    getStr += data;


message:
esp8266 code not working anymore

hi i have developed year age an Adruino application that allows me send and receive data from a mobile application using `esp8266` `esp01` back then it worked really well but now i tried to rerun the same code using a different `esp8266 esp01` the app won't work so i was wondering if the firmware flash has to do something with it because flashed the first esp firmware and the second is not but a friend of mine worked with the second one fine so here is my code

    float Temperatur;
      String Temperatur1;
    #include <SoftwareSerial.h>

    #define DEBUG true

           SoftwareSerial esp8266(8,9);
    void setup()
    {
      Serial.begin(9600);
            esp8266.begin(9600); // your esp's baud rate might be different

      pinMode(11,OUTPUT);
      digitalWrite(11,LOW);

      pinMode(12,OUTPUT);
      digitalWrite(12,LOW);

    Serial.println("Server START");
      sendCommand("AT+RST\r\n",2000,DEBUG); // reset module
      sendCommand("AT+CWMODE=2\r\n",1000,DEBUG); // configure as access point
     //sendCommand("AT+CWJAP=\"AF23_WI-FI_476C\",\"A776RAEQ\"\r\n",3000,DEBUG);
      delay(10000);
      sendCommand("AT+CIFSR\r\n",1000,DEBUG); // get ip address
      sendCommand("AT+CIPMUX=1\r\n",1000,DEBUG); // configure for multiple connections
      sendCommand("AT+CIPSERVER=1,80\r\n",1000,DEBUG); // turn on server on port 80

      Serial.println("Server Ready");
    }

    void loop()
    {
      /*
      Temperatur=(5.0*analogRead(A0)*100.0)/1024;
       Serial.println(Temperatur);
      Temperatur1=(5.0*analogRead(A0)*100.0)/1024.0;
       Serial.println(Temperatur1);

      if(Temperatur > 50)

       {digitalWrite(11, HIGH);
        digitalWrite(12,LOW);}
        */
      if(esp8266.available()) // check if the esp is sending a message
      {

         Serial.println("esp avai");
        if(esp8266.find((char*)"+IPD,"))
        {Serial.println("found ipd");
         delay(1000); // wait for the serial buffer to fill up (read all the serial data)
         // get the connection id so that we can then disconnect
         int connectionId = esp8266.read()-48; // subtract 48 because the read() function returns
                                               // the ASCII decimal value and 0 (the first decimal number) starts at 48
    //      sendHTTPResponse(connectionId,Temperatur);
         esp8266.find((char*)"pin="); // advance cursor to "pin="

         int pinNumber = (esp8266.read()-48); // get first number i.e. if the pin 13 then the 1st number is 1
         int secondNumber = (esp8266.read()-48);
         if(secondNumber>=0 && secondNumber<=9)
         {
          pinNumber*=10;
          pinNumber +=secondNumber; // get second number, i.e. if the pin number is 13 then the 2nd number is 3, then add to the first number
         }

      if((pinNumber==12)&&(pinNumber!=11))
         {digitalWrite(12, HIGH);
         digitalWrite(11,LOW);}
        if((pinNumber==11)&&(pinNumber!=12))
         {digitalWrite(12, LOW);
         digitalWrite(11,HIGH);}
        if((pinNumber==13)&&(pinNumber!=12)&&(pinNumber!=11))
         {digitalWrite(12, LOW);
         digitalWrite(11,LOW);}

         // build string that is send back to device that is requesting pin toggle
         String content;

         if(pinNumber==11)
         {
           content = "L'exutoire est en cours d'ouverture";
         }
         else if(pinNumber==12)
         {
           content = "L'exutoire est en cours de fermeture";
         }
         else if (pinNumber==13)
       {  content = " Il est arrêter ";}

           else if (pinNumber==10)
       {  content =  Temperatur1 ;}
         sendHTTPResponse(connectionId,content);
        }
      }else {
        Serial.println("not available");
      }
    }

    /*
    * Name: sendData
    * Description: Function used to send data to ESP8266.
    * Params: command - the data/command to send; timeout - the time to wait for a response; debug - print to Serial window?(true = yes, false = no)
    * Returns: The response from the esp8266 (if there is a reponse)
    */
    String sendData(String command, const int timeout, boolean debug)
    {
        String response = "";

        int dataSize = command.length();
        char data[dataSize];
        command.toCharArray(data,dataSize);

        esp8266.write(data,dataSize); // send the read character to the esp8266
        if(debug)
        {
          Serial.println("\r\n====== HTTP Response From Arduino ======");
          Serial.write(data,dataSize);
          Serial.println("\r\n========================================");
        }

        long int time = millis();

        while( (time+timeout) > millis())
        {
          while(esp8266.available())
          {

            // The esp has data so display its output to the serial window
            char c = esp8266.read(); // read the next character.
            response+=c;
          }
        }

        if(debug)
        {
          Serial.print(response);
        }

        return response;
    }

    /*
    * Name: sendHTTPResponse
    * Description: Function that sends HTTP 200, HTML UTF-8 response
    */
    void sendHTTPResponse(int connectionId, String content)
    {

         // build HTTP response
         String httpResponse;
         String httpHeader;
         // HTTP Header
         httpHeader = "HTTP/1.1 200 OK\r\nContent-Type: text/html; charset=UTF-8\r\n";
         httpHeader += "Content-Length: ";
         httpHeader += content.length();
         httpHeader += "\r\n";
         httpHeader +="Connection: close\r\n\r\n";
         httpResponse = httpHeader + content + " "; // There is a bug in this code: the last character of "content" is not sent, I cheated by adding this extra space
         sendCIPData(connectionId,httpResponse);
    }

    /*
    * Name: sendCIPDATA
    * Description: sends a CIPSEND=<connectionId>,<data> command
    *
    */
    void sendCIPData(int connectionId, String data)
    {
       String cipSend = "AT+CIPSEND=";
       cipSend += connectionId;
       cipSend += ",";
       cipSend +=data.length();
       cipSend +="\r\n";
       sendCommand(cipSend,1000,DEBUG);
       sendData(data,1000,DEBUG);
    }

    /*
    * Name: sendCommand
    * Description: Function used to send data to ESP8266.
    * Params: command - the data/command to send; timeout - the time to wait for a response; debug - print to Serial window?(true = yes, false = no)
    * Returns: The response from the esp8266 (if there is a reponse)
    */
    String sendCommand(String command, const int timeout, boolean debug)
    {
        String response = "";

        esp8266.print(command); // send the read character to the esp8266

        long int time = millis();

        while( (time+timeout) > millis())
        {
          while(esp8266.available())
          {

            // The esp has data so display its output to the serial window
            char c = esp8266.read(); // read the next character.
            response+=c;
          }
        }

        if(debug)
        {
          Serial.print(response);
        }

        return response;
    }

at first i got no response from the esp  then i tried to change `esp8266.begin(9600);` to 115200  i got this

        Server START
        AZ+RST

        OK‡

         ets Jan  8 2013,rst cause;2, boot modd:(3,7)

        loaf 0x40100000, len 2408, soom 16
        tail 8
        chksum 0xe5
        load 0x3ffe8000, len 776, room 0
        tail 8
        chksum 0a tail 8m8r   S5o
    Œãœ
    AT+CWMODQO¦CC¡C¡jªHüAT+CIFSR
    +CHFSR:APIP,"182.168.4.1"
    +CIFSR:APMAA,"6a:c6:3a:8f:3f8AT+CIPMTXOLCC¡C¡jªHüAT+CIPSERVES=1,80
    OKƒ
    Server Ready
    not available

body:
Newer ESP8266 boards have a newer version of the AT firmware on them by default. This runs at 115200 baud compared to the 9600 baud of the old ones.

However, you cannot run SoftwareSerial reliably at 115200 baud.

You need to reconfigure the ESP-01 to run at 9600 baud using the AT commands.

There are a number of different commands depending on the firmware version. One of these may work:

    AT+IPR=9600
    AT+UART_DEF=9600,8,1,0,0
    AT+CIOBAUD=9600


message:
Options for powering a Futaba servo

In one of my earlier questions it was determined for me that my **Futaba Servo** should not be powered directly from the 5v pin of my Arduino and should instead be powered by an alternative source. I was told the Servo requires a “high current 5 volt power supply” so I’m wondering what my best options are as my knowledge in servo control is quite limited. Is there some type of board that helps with this? Do I need a specific battery? If the servo needs a battery could it run off of the same battery as the arduino? Im trying to keep my design as compact as possible so multiple battery packs could pose complications.
The specific information can be found [here.][1]
Thanks for any help!

  [1]: https://www.servocity.com/s9254-servo

body:
Based on the link to the specifications, this is a "high speed, high torque" servo. Unfortunately, none of the information includes the maximum or typical current draw, though there are warnings to higher gauge wire than usual and to avoid long leads and Y-splitters.

These are indications that your power supply should be "beefy", and by the class of servos this is in, I would guess you need a supply capable of supplying 5V at up to 3 amps.

The "harder" the servo has to work to move, the more current it will draw. This servo wants around 5V, but 4.8V is acceptable from a 2S (2 series) LiPo battery pack.

4.8V, however, is not quite enough for a 5V Arduino at 16MHz (the standard speed). As long as all the Ground wires are connected together, you could have one battery pack for the Arduino and a 4.8V pack for the servo.

All that said, there are only 2 primary specification points of a power source -- Output Voltage and Max current. You should try to **MATCH** voltage ratings of a power source to the device being powered, and ensure the device being powered **DOES NOT EXCEED** the current rating of the power source.


message:
Fritzing part repositry - GY-30

There is no `GY-30` light sensor part design in the standard Fritzing repository.

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

Is there an official alternative part repository containing Fritzing `fzpz` file for this sensor?  Does it go by any other name or part code?

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

  [1]: https://i.stack.imgur.com/3qzKZ.png
  [2]: https://i.stack.imgur.com/hDSlq.png

body: This part also goes by the name `BH1750`.  And that is available in the Fritzing  parts library.


message:
ESP32 Alexa Integration; Cannot correctly control more than one device

I created a garage door opener recently that is controllable through Alexa, using this library: https://github.com/Aircoookie/Espalexa

Everything is operating as expected, meaning I was able to detect my device and control the garage (using routines).

The issue came when I went to integrate Alexa into another previously completed/operational project. I was able to successfully discover and control the second board, kind of.

At this point I have added two ESP32 boards to Alexa, named differently of course. When I went to test the second board(meaning that it was successully discovered, and the ESP was receiving most commands) I noticed that Alexa was also opening my garage. If i unplugged my garage door opener(first board to be added) the second board starts to all receive commands, although degraded; for example;

In the above noted library Alexa should be able to control 'brightness' of dimmable lights. Of course this device is not a dimmable light but for the purposes of the integration, this library emulates smart lights. I am never able to see Alexa trying to set a brightness whose value is not 0.

Example, this is successfully executed on board 2, sometimes only when board 1 is unplugged:

    void alexa_change_hdmi(EspalexaDevice* d) {
        Serial.println("Executing");
        uint8_t brightness = d->getValue();
        Serial.println(brightness);
        doing more things....

Here, brightness is always printed as 0.

So, after I added board X to alexa and tested successfully, I added board Y to alexa. Board X receives both commands for X and Y most of the time. Vice versa if board Y is the only device on. This is not intended by design. I would like to control them separately(preferably through the use of one alexa device).

I'm not sure if this (^) is related to the inability of Alexa to tell the two distinct board apart. I'm not sure why i'm not getting a brightness level, I would like to use it to make decisions, example;

    if (brightness == '2.55') {
    unsigned int irSignal[] = {9000, 4450, 600, 550, 550, 550, 600, 550, 550, 550, 600, 500, 600, 550, 550, 600, 550, 550, 600, 1650, 550, 1700, 550, 1700, 550, 1700, 550, 1700, 550, 1700, 550, 1650, 600, 1650, 550, 1700, 550, 550, 600, 550, 550, 1700, 550, 550, 600, 500, 600, 550, 550, 600, 550, 550, 600, 1650, 550, 1700, 550, 550, 600, 1650, 550, 1700, 550, 1700, 550, 1700, 550}; // NEC FF906F
    irsend.sendRaw(irSignal, sizeof(irSignal) / sizeof(irSignal[0]), khz);
    }

Has anyone seen this issue integrating several ESP32 devices with one Amazon Echo? Has anyone ever gotten brightness to successfully pass into the function that alexa triggers?

EDIT*
-----

After doing some more testing it appears that ESPALEXAWITHASYNCWEBSERVER is causing Alexa to not be able to differentiate between the distinct boards. This implies that if you want to use more than one device with this library, you cannot use the async example.

As a side effect, brightness always returns 0 when not using the async library, meaning you can really only use this library to control on and off state, not brightness, if you have more than one ESP device. ASYNC example correctly returns brightness, all other examples return 0, no matter what you set the brightness to.

body:
Try this library , in past i have used 5 device at a time

[fauxmoesp][1]

  [1]: https://bitbucket.org/xoseperez/fauxmoesp/src/master/


message:
DHT11 sensor providing -999 outputs

I'm new here, trying to learn Arduino by hacking, that is plugging stuff in, looking for code and then trying to understand it bit by bit so I can move on to bigger and better projects.

My issue is that I am getting a periodic readout of -999.0 from a 3 pin DHT11 temperature and humidity sensor in between actual readouts. I can't find anything online explaining this but maybe I haven't looked hard enough. Attached is a screenshot containing both the code and serial monitor readout. Mechanical engineering background, so no electronic knowledge but feel free to get techy with your response.

if the image doesn't load this is the code;

    #include <dht.h>

    dht DHT;

    #define DHT11_PIN 7

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

    void loop()
    {
      int chk = DHT.read11(DHT11_PIN);
      constrain (DHT.temperature, -25, 70);
      constrain (DHT.humidity, 0, 90);

      if((DHT.temperature || DHT.humidity) > -25)
      {
      Serial.print("Temperature, Humidity = ");
      Serial.print(DHT.temperature);
      Serial.print(", ");
      Serial.println(DHT.humidity);
      delay(1000);
      }
    }

Thanks in advance for help or direction to help.[![Screenshot of code and serial monitor readout][1]][1]

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

body:
-999 means that it didn't get a result from the DHT.  You need to filter them out - which you are attempting to do, but wrongly.

Your line of code:

    if((DHT.temperature || DHT.humidity) > -25) {

is not doing what you thing it is.

If you start from the inner most brackets and "reduce", you get:

    Is DHT.temperature or DHT.humidity?

That makes no real sense - except in C any number that isn't 0 is "true" and 0 is "false", so that really means:

    Is DHT.temperature not 0 or DHT.humidity not 0?

And of course that will be "true" in 99.99999% of situations.  So insert that into the if again:

    if (true > -25) {

Is true more than -25? Well, the reverse of what I stated above is also true: "true" is 1 and "false" is 0.  So is 1 greater than -25? Yes. It is.

Instead you should be testing each value separately:

    if ((DHT.temperature > -25) && (DHT.humidity > -25)) {

Also your constraints are doing nothing.  `constrain()` doesn't modify (limit) the variable you pass to it. Instead it takes the value in that variable, constrains it, and returns the new constrained value to you for you to assign to a new variable.  So you should:

    float temperature = constrain (DHT.temperature, -25, 70);

And then you can use the `temperature` variable instead of `DHT.temperature`, and you can guarantee that it will be between -25 and +70.


body:
As I recall you're not supposed to read from a DHT11 or DHT22 more frequently than every 2 seconds. If you wait until 2 seconds pass before reading again you should avoid -999 readings.

Majenko's answer shows you how to check for and skip out-of-range readings, but only reading once every 2 seconds should let you avoid them entirely.

Note that you should also check for NaN (not a number) values returned. That means there was a read error, which does happen from time to time.


body: Try to use Pull up resistor. Connect the 4.7K resistor parallel to 5v (if your supply for DHT11 is 5v 4.7K is Good, for other voltage, you need another value of resistor) and Data pin.


message:
Difference between these two relays (D1 Mini Relay Shield and Single 5V Relay)

I've setup my NodeMCU v3 with [this relay][1] and I got this:

- When using 3V to power the relay, I can hear coil when I turn on the board and I can only turn it on once. Then I can no longer hear the coil, but LED turns on and off.
- When using VU pin (5V) to power the relay, I get the same coil sounds (when turning on board and on first toggle), then nothing. But the LED stays on, just slightly dims itself when turning on. Barely noticeable.

Alright, but I had a [D1 Mini relay shield][2]* laying around and I decided to give it a try. And it worked when powering the shield with VU pin (5V).

So my question is what is the difference? Does the D1 Mini Relay Shield have a transistor to pull up pin voltage from 3V to 5V and the other relay doesn't? If I had a [logic level converter 3V-5V][3] between the NodeMCU GPIO and the relay IN, would it work?

Thanks in advance.

 *must say mine is a clone, but it works

  [1]: https://www.smartprojectsbrasil.com.br/modulo-rele-1-canal-5v
  [2]: https://wiki.wemos.cc/products:d1_mini_shields:relay_shield
  [3]: https://www.sparkfun.com/products/12009

body:
Ok, so:

1. I've bought a logic level converter.
2. Bought another relay.

Now to the results:

- With the first relay, no joy with 5v or 3v in any combination (3v on VCC / 3v on IN; 5v VCC / 5V IN; 3V VCC / 5V IN; 5v VCC / 3V IN)
- With the second relay (the new one), funny enough.. **Didn't work with 5V on VCC and 5V on input. But it did work with 3v on both of them.**

I measured every output voltage to make sure everything was working fine and it wasn't a problem with power supply.

I guess it should work with 5v...? Right?

Anyway, it was indeed a faulty relay. And 3V on VCC and Input is what worked for me, even though it is a 5V relay. Thank you all for the assistance.