message:
Having problems with I2C - Slave is receiving "b ~ ,,,"

so I'm facing a pretty large problem. I'm experimenting with I2C and using one Arduino that acts as a countdown timer to send the current reading on the timer to another Arduino. I'm pretty new to electronics in general so bear with me.

The way the countdown timer works is it stores the time as a String, and uses substring and toInt() to adjust the timer.

I know that with I2C you can only send some data, Strings not included, so I tried converting the String to an array of characters using toCharArray(). My conversion seems to be working well, as I have tested it with the Serial.println() and it displays the time correctly.

Therefore, I am convinced the problem lies with the Slave code. I'm not sure how to set up the Slave Arduino to receive the actual time. Below, I've pasted links to the code of both the Master and the Slave respectively.

Master: https://pastebin.com/AFjTDZB7

Slave: https://pastebin.com/viNGWn9c

How should I change my slave code so everything works?

Also, when I changed the datatype of "time" in the Slave code from char* to int, all I got in the Serial Monitor was 48. Weird.

Would really appreciate any help and guidance cause I'm pretty stuck. All the tutorials I find online are pretty complicated.

Thanks!

Master Code:

    #include < Wire.h >
    String time = "10:11";
    boolean doubleDigits = false;

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

    void loop() {
      Serial.println(time);
      sendTime(time);
      int First2 = time.substring(0, 2).toInt();
      if (First2 > 9) {
        doubleDigits = true;
      }

      int Last2 = time.substring(3).toInt();
      if ((time.substring(3) == "00") && (time != "00:00")) {
        First2 = First2 - 1;
        Last2 = 59;
        if (doubleDigits == false) {
          time = "0" + String(First2) + ":" + String(Last2);
        } else {
          time = String(First2) + ":" + String(Last2);
        }
      } else if (time != "00:00") {
        Last2 = Last2 - 1;
        if (Last2 < 10) {
          if (doubleDigits == false) {
            time = "0" + String(First2) + ":0" + String(Last2);
          } else {
            time = String(First2) + ":0" + String(Last2);
          }
        } else {
          if (doubleDigits == false) {
            time = "0" + String(First2) + ":" + String(Last2);
          } else {
            time = String(First2) + ":" + String(Last2);
          }
        }
      }
      if (time.substring(1, 2) == ":") {
        time = "0" + time;
      }
      delay(1000);
    }

    void sendTime(String time) {
      Wire.beginTransmission(9); //transmit to device 9
      char buffer[32];
      time.toCharArray(buffer, 32);
      Wire.write(buffer);
      Serial.println(buffer);
      Wire.endTransmission(); //stops transmitting
    }

    //master

Slave Code:

    #include <Wire.h>
    char* time;

    void setup() {
      Wire.begin(9); //start as slave on address 9
      Wire.onReceive(receiveEvent); //attach a function to trigger when something is received
      Serial.begin(9600);
    }

    void receiveEvent(int bytes) {
      time = Wire.read(); //read one character from the I2C

    }

    void loop() {
      Serial.println(time);
      delay(1000);
    }

    //slave

Edit: added code

body:
In the slave code.  `receiveEvent` takes a number of bytes as a parameter, presumably you are supposed to read this many bytes, can you call read with that number?  Even if you did you are reading to a char pointer, which will cause issues unless read is allocating the memory, which you should then be releasing.  Basically you have a couple of issues here and you need to look at them.

In the Master code. `sendTime` doesn't look right.  I would expect you to have to send a certain number of bytes using the Write function.  You are just sending 32 chars, the fact you are sending signed char's rather than unsigned char's shouldn't be an issue (but its technically incorrect).

I don't really understand what you are trying to achieve in the rest of loop, annotation would help :)

----------
OK, If you take this as a new version for the slave you should be able to see it working.  It might not be 100%, but you should get something.  (I haven't even compiled this code, so you might have to sort out a few bugs)

    #include <Wire.h>

    #define MaxTimeBufferSize (33)
    #define MaxReadSize  (MaxTimeBufferSize - 1)
    char timeBuffer[MaxTimeBufferSize];

    void setup()
    {
      Serial.begin(9600);  // Init first so you can see any issues during setup.
      Wire.begin(9); //start as slave on address 9
      Wire.onReceive(receiveEvent); //attach a function to trigger when something is received
    }

    // Assumes the bytes are actually printable ASCII characters.
    void receiveEvent(int bytes)
    {
      const int bytesToRead = (bytes < MaxReadSize) ? bytes : MaxReadSize;
      for (int index = 0; index < bytesToRead; ++index)
      {
         timeBuffer[index] = Wire.read(); //read one character from the I2C
      }
      timeBuffer[bytesToRead] = 0; // Null terminate the bytes (so they will print as a string)
    }

    void loop()
    {
      if (timeBuffer[0])  // Only print the buffer if there is new data
      {
        Serial.println(timeBuffer); // The buffer is NULL terminated.
        timeBuffer[0] = 0;  // Stop the buffer  printing again.
      }
      delay(1000);
    }


sender: user

sender: assistant

body:
@A.Lordos, the code by @CodeGorilla shows how to read more than one byte as a Slave. It stores the received data in a buffer, and that buffer is printed to the serial monitor to show it.

May I make a suggestion: start all over and do it right.
Forget the String objects and use a integer (int, or unsigned or unsigned long) as a countdown counter for the seconds. Count the seconds, nothing else.
When you need to display the counter, then you can make it in the format of "10:11". But only to display it, the base of the sketch is still that single variable for the seconds.
When you need to transmit the counter to the Slave, send the integer variable as binary data (the integer itself), not a text string.

In the Arduino examples, a text is transferred over the I2C bus. That is however almost never done. In most cases binary data of variables is transferred over I2C.

This is a good tutorial: [Nick Gammon's Tutorial about I2C][1]

  [1]: http://www.gammon.com.au/i2c


message:
How to use analogWrite() on multiple pins at the same time?

I would like to do,

`analogWrite(100,3);
 analogWrite(200,6);`

at the same time. But the problem is that only the led on pin 3 lights up. I want both to light up at the same time. I've heard about direct port manipulation, but I can only find an alternate for `digitalWrite()` but I couldn't find one for `analogWrite()`. Can someone please help me with just a simple example on just how to do the above operation?

I'm using arduino uno.

body:
You have your parameters the wrong way round:

    analogWrite(2, 100);
    analogWrite(6, 200);

**However**: pin 2 on the Uno cannot do PWM, so you will have to pick a different pin. Look for the pins marked with `~` - they are the PWM pins. On the Uno that is pins 3, 5, 6, 9, 10 and 11.


message:
TWI Wire.setClock() on non arduino AVR MCU issue

Using an Atmega168P - programmed by means of `avrdude` with the `.hex` file generated by Arduino IDE.

The following code sets the 8 MHz Atmega's TWI interface to just 15.625 kHz:

      Wire.begin(); // Initiate the Wire library
      Wire.setClock(100* 1000);
      delay(10);

While this one doubles it to 31.25 kHz:

      Wire.begin(); // Initiate the Wire library
      TWBR = (F_CPU/(100*1000) - 16)/2;
      TWSR &= 0b11111100;
      delay(10);

Looking to get 100 kHz clock. What am I missing ?

body:
> Looking to get 100 kHz clock. What am I missing?

Calculations are int (16-bits) by default in AVR GCC. Try 100*1000L. Or even better:

    #define F_TWI 100000L

and use:

    TWBR = ((F_CPU/F_TWI)-16)/2;

or:

    Wire.setClock(F_TWI);

Cheers!


message:
Attiny85: Watchdog does not initialize properly when using switch(case)

I have a project in which I am putting my ATtiny85 to sleep. Here is the watchdog configuration (in the setup) that works just fine:

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

    void setup()
    {
      /*  Setup the LCD */
      lcd.init();                           // initialize the lcd
      lcd.backlight();                      // Print a message to the LCD.
      lcd.clear();
      lcd.setCursor(0,0);

      /* Inform the user about initialization process */
      lcd.print("Initializing...");
      delay(1000);

      /* Config pins */
      pinMode( LED_PIN, INPUT );
      pinMode( STATUS_PIN, OUTPUT );

      /* Initialize pins */
      digitalWrite( STATUS_PIN, HIGH );

      /*** Setup the WDT ***/

      /* Clear the reset flag of watchdog interrupts, so that they are available again. */
      MCUSR &= ~(1<<WDRF);

      /* Enable configuration changes */
      WDTCR |= (1<<WDCE) | (1<<WDE);

    /*
    WDP3       WDP2    WDP1     WDP0         Number of WDT     Typical Time-out at
                                             Oscillator Cycles     VCC = 5.0V
      0         0      0        0             2K (2048) cycles       16 ms
      0         0      0        1             4K (4096) cycles       32 ms
      0         0      1        0             8K (8192) cycles       64 ms
      0         0      1        1            16K (16384) cycles    0.125 s
      0         1      0        0            32K (32768) cycles    0.25 s
      0         1      0        1            64K (65536) cycles    0.5 s
      0         1      1        0            128K (131072) cycles 1.0 s
      0         1      1        1            256K (262144) cycles 2.0 s
      1         0      0        0            512K (524288) cycles 4.0 s
      1         0      0        1            1024K (1048576) cycles 8.0 s
    */
      /* set new watchdog timeout prescaler value */
      WDTCR =  0<<WDP3 | 1<<WDP2 | 1<<WDP1 | 0<<WDP0 ;

      lcd.clear();
      lcd.print("Initialisation");
      lcd.setCursor(0,1);
      lcd.print("complete.");
      delay(500);
    }

Here is the function that actually puts my microcontroller to sleep:

    void enterSleep(void)
    {
    //  /* disable all interrupts */
    //  cli();
      lcd.clear();
      lcd.print("Asleep...");

      /* Enable the WD interrupt (note no reset). */
      WDTCR |= (1<<WDIE);

      set_sleep_mode( SLEEP_MODE_PWR_DOWN );   /* EDIT: could also use SLEEP_MODE_PWR_DOWN for lowest power consumption. */
      sleep_enable();
      // Status pin goes low
      digitalWrite( STATUS_PIN, LOW );
      /* Now enter sleep mode. */
      sleep_mode();

      /* The program will continue from here after the WDT timeout*/
      sleep_disable(); /* First thing to do is disable sleep. */

      // Status pin goes low
      digitalWrite( STATUS_PIN, HIGH );

      /* Re-enable the peripherals. */
      power_all_enable();

      /* Disable the WD interrupt */
      WDTCR &= ~_BV(WDIE);
    }

 Then I decided to do a switch case construction, so that I won't have to change manually `WDTCR` register each  time I want to change the sleep time. So here is my new setup code:

    int sleepTime = 0;

    void setup()
    {
      /*  Setup the LCD */
      lcd.init();                           // initialize the lcd
      lcd.backlight();                      // Print a message to the LCD.
      lcd.clear();
      lcd.setCursor(0,0);

      /* Inform the user about initialization process */
      lcd.print("Initializing...");
      delay(1000);

      /* Config pins */
      pinMode( IN_PIN, INPUT );
      pinMode( STATUS_PIN, OUTPUT );
      pinMode( DEBUG_PIN, OUTPUT );

      /* Initialize pins */
      digitalWrite( STATUS_PIN, HIGH );
      digitalWrite( DEBUG_PIN, LOW );

      /*** Setup the WDT ***/
    //  sleepDevice.watchdogInit();
        /*** Setup the WDT ***/
        /* Clear the reset flag of watchdog interrupts, so that they are available again. */
        MCUSR &= ~(1<<WDRF);

        /* Enable configuration changes*/
        WDTCR |= (1<<WDCE) | (1<<WDE);

      /*
      WDP3       WDP2    WDP1     WDP0         Number of WDT     Typical Time-out at
                                               Oscillator Cycles     VCC = 5.0V
        0         0      0        0             2K (2048) cycles       16 ms
        0         0      0        1             4K (4096) cycles       32 ms
        0         0      1        0             8K (8192) cycles       64 ms
        0         0      1        1            16K (16384) cycles    0.125 s
        0         1      0        0            32K (32768) cycles    0.25 s
        0         1      0        1            64K (65536) cycles    0.5 s
        0         1      1        0            128K (131072) cycles 1.0 s
        0         1      1        1            256K (262144) cycles 2.0 s
        1         0      0        0            512K (524288) cycles 4.0 s
        1         0      0        1            1024K (1048576) cycles 8.0 s
      */

      switch( sleepTime ){
        case 0:
          WDTCR =  0<<WDP3 | 1<<WDP2 | 1<<WDP1 | 0<<WDP0 ;
          break;
        case 1:
          WDTCR =  0<<WDP3 | 1<<WDP2 | 0<<WDP1 | 1<<WDP0 ;
          break;
        default:
          WDTCR =  0<<WDP3 | 0<<WDP2 | 1<<WDP1 | 0<<WDP0 ;
          break;
      }

      lcd.clear();
      lcd.print("Initialisation");
      lcd.setCursor(0,1);
      lcd.print("complete.");
      delay(500);
    }

The `enterSleep` function is not changed.
But this time sleeping does not work at all! In fact, ATtiny sort of freezes. Does any one has any idea why it is so? To me it looks like the Arduino IDE is confused with switch case instruction, but maybe there is something wrong with my code...

body:
Try this for your sleep function...

    void enterSleep(void)
    {
      lcd.clear();
      lcd.print("Asleep...");

      // Status pin goes low
      digitalWrite( STATUS_PIN, LOW );

      /* disable all interrupts, if we get interrupted we might timeout the WDT */
      cli();

      /* Reset the watchdog counter so we know that we are starting at 0 */
      wdt_reset()

      /* Enable the WD interrupt (note no reset). */
      WDTCR |= (1<<WDIE);

      set_sleep_mode( SLEEP_MODE_PWR_DOWN );   /* EDIT: could also use SLEEP_MODE_PWR_DOWN for lowest power consumption. */

      sleep_enable();
      sei();
      /* Now enter sleep mode. */
      sleep_cpu();
      cli(); // Make sure we have time to disable WDT before we get reset

      /* Disable the WD interrupt */
      WDTCR &= ~_BV(WDIE);

      /* The program will continue from here after the WDT timeout*/
      sleep_disable(); /* First thing to do is disable sleep. */

      sei();

      // Status pin goes low
      digitalWrite( STATUS_PIN, HIGH );

      /* Re-enable the peripherals. */
      power_all_enable();

    }


body:
Alright, thanks to you guys I fixed the issue.
The main thing is that any changes in the configuration have to be made within 4 cycles after the CONFIG ENABLE bit is set. It is done with this instruciton:

    /* Enable configuration
    WDTCR |= (1<<WDCE) | (1<<WDE);

Now switch works like a charm. So the final code for watchdog setup looks like this:

    void Sleeper::watchdogInit( void ){
       /*** Setup the WDT ***/
       /* Clear the reset flag of watchdog interrupts, so that they are available again. */
       MCUSR &= ~(1<<WDRF);

     /*
     WDP3       WDP2    WDP1     WDP0         Number of WDT     Typical Time-out at
                                              Oscillator Cycles     VCC = 5.0V
       0         0      0        0             2K (2048) cycles       16 ms
       0         0      0        1             4K (4096) cycles       32 ms
       0         0      1        0             8K (8192) cycles       64 ms
       0         0      1        1            16K (16384) cycles    0.125 s
       0         1      0        0            32K (32768) cycles    0.25 s
       0         1      0        1            64K (65536) cycles    0.5 s
       0         1      1        0            128K (131072) cycles 1.0 s
       0         1      1        1            256K (262144) cycles 2.0 s
       1         0      0        0            512K (524288) cycles 4.0 s
       1         0      0        1            1024K (1048576) cycles 8.0 s
     */

     switch( sleepTime ){
      case 0:
                /* Enable configuration changes*/
                WDTCR |= (1<<WDCE) | (1<<WDE);
       WDTCR =  0<<WDP3 | 1<<WDP2 | 1<<WDP1 | 0<<WDP0 ;
       break;
      case MSEC_500:
                /* Enable configuration changes*/
                WDTCR |= (1<<WDCE) | (1<<WDE);
       WDTCR =  0<<WDP3 | 1<<WDP2 | 0<<WDP1 | 1<<WDP0 ;
       break;
      case MSEC_250:
                /* Enable configuration changes*/
                WDTCR |= (1<<WDCE) | (1<<WDE);
       WDTCR =  0<<WDP3 | 1<<WDP2 | 0<<WDP1 | 0<<WDP0 ;
       break;
      case MSEC_125:
                /* Enable configuration changes*/
                WDTCR |= (1<<WDCE) | (1<<WDE);
       WDTCR =  0<<WDP3 | 0<<WDP2 | 1<<WDP1 | 1<<WDP0 ;
       break;
      case MSEC_64:
                /* Enable configuration changes*/
                WDTCR |= (1<<WDCE) | (1<<WDE);
       WDTCR =  0<<WDP3 | 0<<WDP2 | 1<<WDP1 | 0<<WDP0 ;
       break;
      case MSEC_32:
                /* Enable configuration changes*/
                WDTCR |= (1<<WDCE) | (1<<WDE);
       WDTCR =  0<<WDP3 | 0<<WDP2 | 1<<WDP1 | 0<<WDP0 ;
       break;
        default:
          /* Enable configuration changes*/
          WDTCR |= (1<<WDCE) | (1<<WDE);
          WDTCR =  0<<WDP3 | 0<<WDP2 | 1<<WDP1 | 0<<WDP0 ;
          break;
     }


message:
Serial communication on Arduino Uno

I have a Raspberry Pi 3 connected to the serial of my Arduino Uno (pins 0 and 1), but I also have another device connected to two other serial pins on the Arduino (pins 10 and 11, using the SoftwareSerial library).

What I want to do is send a string from the RPI, then the Arduino gets it and resends that information through the other serial port to my device.

Until now the Arduino can receive the information from the RPI, but I'm not sure how to send that same string through the other serial port, the one going to the device.

Here is the code I'm using:

    #include <SoftwareSerial.h>

    String b = "0";
    SoftwareSerial portOne(2, 3); //RX= pin 2  TX= pin 3

    void setup() {
      Serial.begin(9600, SERIAL_8N1);
      portOne.begin(9600);
    }

    void loop() {
      if (Serial.available() > 0) {
        b = Serial.readString();
        Serial.println("Data from RPI:");
      }
      portOne.listen();
      while(portOne.available() > 0){
          Serial.println("Data from port one:");
          Serial.println(b);
        }
      }

I just get the data coming from the RPI, but nothing from portOne.

Any thoughts?

body:
Your code is not reading the `SoftwareSerial`. `b` is only populated when the Pi sent data. The loop below sends what it reads from the `SoftwareSerial`, after that is prints a new line `println()` (only because that's what your code is doing)

The `listen()` method of `SoftwareSerial` is only required if you have more than one `SoftwareSerial` connection.

    #include <SoftwareSerial.h>

    String b = "0";
    SoftwareSerial portOne(2, 3); //RX= pin 2  TX= pin 3

    void setup() {
      Serial.begin(9600, SERIAL_8N1);
      portOne.begin(9600);
    }

    void loop() {
      if (Serial.available() > 0) {
        b = Serial.readString();
        Serial.println("Data from RPI:");
      }

     //not required with only one software serial connection
     //portOne.listen();

      if (portOne.available() > 0)
      {
       while(portOne.available() > 0){
          byte byteRead = portOne.read();
          Serial.write(byteRead);
        }
        Serial.println();
       }
      }


body:
If you goal is to relay a string from RPI through the Arduino to a device connected via SoftwareSerial then you should be doing something like this:

    #include <SoftwareSerial.h>

    String b = "0";
    SoftwareSerial portOne(2, 3); //RX= pin 2  TX= pin 3

    void setup() {
      Serial.begin(9600, SERIAL_8N1);
      portOne.begin(9600);
    }

    void loop() {

      if (Serial.available() > 0) { // data available on HW Serial
        b = Serial.readString();    // Read it
        portOne.print(b);           // and write it to SW Serial
      }

    }


body:
After reading more about the SoftwareSerial, I managed to get the communication I wanted in a simpler way. This is what I ended up using in my void loop:

    void loop() { // run over and over

      if (Serial.available()>0) {
        HW = Serial.read();
        mySerial.write(HW);

      }

      if (mySerial.available()>0) {
        SW = mySerial.read();
        Serial.write(SW);
      }
    }

Thank you all for your help, your answers gave me also a better understanding of what I was doing.


message:
How can I store the received data from nRF24l01+ module in an array (code in description)?

This is my sample RX code for 4 Tx and 1 Rx nRF24l01+ modules. I want to store all the data received from 4 pipes into an array (recArray).

    #include <SPI.h>
    #include <nRF24L01.h>
    #include <RF24.h>

    RF24 radio(7, 8);

    const uint64_t pipes[4] = {0xF0F0F0F0E1LL, 0xF0F0F0F0E2LL, 0xF0F0F0F0E3LL, 0xF0F0F0F0E4LL};
    char text[32] = {0}; #received data
    int recArray[4]={0, 0, 0, 0}; # array to store the received bytes

    void setup() {
      Serial.begin(9600);
      radio.begin();
      radio.openReadingPipe(1, pipes[0]);
      radio.openReadingPipe(2, pipes[1]);
      radio.openReadingPipe(3, pipes[2]);
      radio.openReadingPipe(4, pipes[3]);
      radio.startListening();
    }

    void loop() {
      if (radio.available()) {
        radio.read(&text, sizeof(text));
        Serial.println(text);
      }
    }

body:
I would suggest to send 2 bytes to this module
the first byte is the pipe number (0xE1,0xE2,0xE3,0xE4)
and in the second byte Data

    void loop()
    {
      if (radio.available())
     {
      radio.read(&text, sizeof(text));
      for (int i=0; i < 4 ; i ++)
       {
         if( text[0] == ((unsigned char *)(&pipes[i]))[0]
            recArray[i] = text[1];
       }
      Serial.println(text[1]);
     }
    }


message:
HC-06 pairing to arduino

I have a bluetooth module HC-06 and want to pair it to my Arduino UNO. The thing is when I researched how to do so, I got different answers. What pairing should I use? Thank you in advance. I have highlighted the differences.

First version:
https://www.instructables.com/id/Add-bluetooth-to-your-Arduino-project-ArduinoHC-06/

HC-06>>>Arduino

**VCC>>>>3.3v**

GND>>>>GND

TXD>>>>RXD

**RXD>>>>TXD**

Second version:
http://42bots.com/tutorials/hc-06-bluetooth-module-datasheet-and-configuration-with-arduino/

   HC-06            <<>> Arduino

   HC-06 Ground GND <<>> GND

   **HC-06 VCC pin  <<>> 5v**

   HC-06 TX/TXD pin <<>> Arduino RX

   **HC-06 RX/RXD pin << resistors >> Arduino TX**

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

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

body:
Which you use depends on two factors: the HC-06 carrier board you have, and which Arduino you are using.

If your carrier board has (and most do) a 3.3V regulator then you power the board from 5V.

If your Arduino is a 5V Arduino (such as an Uno) then you need a voltage divider on the (arduino)TX->(hc)RX pins otherwise you risk damaging the bluetooth module.


message:
Adafruit Huzzah espcomm_open failed

I recently bought an adafruit huzzah as well as a serial to usb [cable][2] to connect it to my computer running windows 10. I was able to get the board set up in arduino following the directions found [here][3]. I copied and pasted this sketch:

    void setup() {
      pinMode(0, OUTPUT);
    }

    void loop() {
      digitalWrite(0, HIGH);
      delay(500);
      digitalWrite(0, LOW);
      delay(500);
    }

into the arduino 1.8.2 IDE, followed these instructions:

> Hold down the GPIO0 button, the red LED will be lit
>
> While holding down GPIO0, click the RESET button
>
>Release RESET, then release GPIO0
>
> When you release the RESET button, the red LED will be lit dimly, this means it's ready to bootload

and tried to upload only to get an error:

In versions 1.6.5 and 2.0.0 of the esp library I get these errors:

    warning: espcomm_sync failed
    error: espcomm_open failed
    error: espcomm_open failed

In versions 2.1.0 - 2.3.0 of the esp library, I get these errors:

    warning: espcomm_sync failed
    error: espcomm_open failed
    error: espcomm_upload_mem failed
    error: espcomm_upload_mem failed

I've tried switching the tx and rx leads, I've tried versions 1.6.5-2.3.0 of the esp8266 library. I've also tried it on the other board that I ordered and got the same errors. Any ideas on what could be the problem?

EDIT: I've now tried it on a generic esp-01 board and am having the same issue

  [2]: https://www.adafruit.com/product/954
  [3]: https://learn.adafruit.com/adafruit-huzzah-esp8266-breakout/using-nodemcu-lua?view=all#using-arduino-ide

body:
I had to install the SiLabs CP2104 drivers and reboot.
Make sure you don't have 2 connection (Arduino IDEs, VS Code with PlatformIO, ...) open. Also, I kept pressing the reset button the first time.

https://learn.adafruit.com/adafruit-feather-huzzah-esp8266/using-arduino-ide


message:
HMC5883L - Tilt compensation without Accelerometer

Trying to get an **HMC5883L** to compensate for being installed in 90 degrees. Doesn't seem to me that it'll need too complex math or accelerometer. But I have no idea how to do the compensation for it. Any idea?

Using the Adafruit HMC5883L and its library.

body:
You can always use the normal tilt compensation equations with a fixed value instead of a calculation from the accelerometer; Since you know the rotation beforehand the equations may not be as complex. For example, if the tilt is only on one axis, it's just one rotation matrix multiply (and you don't need to calculate the result z axis) instead of 3 in general.

If the tilt is constant and exactly 90 degrees, You just need to swap which magnetometer axis are put into the magnetic field angle equations. If one axis is pointed towards the center of the earth, you can use the other two axis to calculate the direction of the magnetic field without an explicit rotation transformation.


message:
How to make ESP8266-1S module work on Arduino Uno?

I currently have an Arduino Uno with an ESP8266-1S. However I can't make them work... I use the ESP8266wifi.h library and its connection functions do return a true (returns true when received a valid IP), but I can't find it in my network...

When I send 'AT' ending with CR and NL on 115200 baud I still don't get a response.

Also, do I have to connect RX with RX and TX with TX or RX to TX and vice versa?

And also, do I need any converters? Because now I directly connect the TX and RX to the Arduino's TX and RX.

So this is how my board looks like:
[![enter image description here][1]][1]

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

So what am I doing wrong?

body:
>do I have to connect RX with RX and TX with TX or RX to TX and vice versa?

If you want to do serial communication between a sketch running on the Arduino and the ESP8266 you must connect the RX pin on the Arduino to TX on the ESP8266 and the TX pin on the Arduino to TX on the ESP8266.

If you want to do serial communication between the Serial Monitor on your computer through the USB port on the Arduino to the ESP8266 you must connect the RX pin on the Arduino to TX on the ESP8266 and the TX pin on the Arduino to RX on the ESP8266.

TX stands for **Transmit** and RX stands for **Receive**. So it makes sense that you should connect the transmit pin to the receive pin in the first case. But why connect transmit to transmit and receive to receive in the second case? The reason is that you are not communicating between the main microcontroller (ATmega328P on the Uno) and the ESP8266. You are communicating between the USB-serial chip on the Uno (usually ATmega16U4 on the official Arduinos or CH340 on the clones) and the ESP8266. The main microcontroller is not being used at all, you're just using the Arduino as a bulky and inconvenient USB-serial adapter.

In fact some people will go so far as to remove the ATmega328P from their DIP Unos for this purpose. The RX pin on the USB-serial chip is connected to the TX pin on the main microcontroller as well as the TX header pin and vice versa for TX pin on the USB-serial chip. This means by connecting the ESP8266's TX pin to the TX pin on the Uno's header you are actually connecting it to the RX pin on the USB-serial chip. I would highly recommend getting a USB-serial adapter made for this purpose rather than trying to use an Arduino. You can buy FTDI FT232 or CH340 breakout boards on eBay or Aliexpress for < $2 USD w/ free shipping.

>do I need any converters? Because now I directly connect the TX and RX to the Arduino's TX and RX

This is actually two questions. Let's address the easy one first. The TX pin of the ESP8266 is going to put out around 3 V. Even though the ATmega328P is running at 5 V this will still be seen as a high so no level conversion on that pin is necessary.

Now for the question of whether it's needed on the ~5 V level from the Arduino to the ESP8266 RX pin. There's a lot of disagreement on the question of whether the IO pins on the ESP8266 are 5 V tolerant. We certainly know that it's possible to connect the ESP8266 to 5 V levels as there are many projects published online that do this but the question is will this will shorten the life of the ESP8266?

The datasheet for the ESP8266 does not say the inputs are 5 V tolerant. There is a statement on the ESP8266 forum from a member of the Espressif (creator of the ESP8266) staff:
http://bbs.espressif.com/viewtopic.php?t=1145
>We donot recommend you to apply 5V to IO.

We have a comment from someone on Facebook named "Teo Swee Ann" who appears to be the CEO of Espressif:
 https://www.facebook.com/groups/1499045113679103/permalink/1731855033731442/?comment_id=1732364133680532
> i can reply officially here: it is 5V tolerant at the IO. while the supply voltage is at 3.3V.

So there is conflicting information and none of it has been presented in the most official manner, such as actually putting it in the datasheet. One thing we do know for sure, you will not harm the ESP8266 with 3.3 V levels. So the safest option is to avoid giving it 5 V inputs. However, as you are currently struggling just to get the most basic communication working the extra complication introduced by adding level shifting circuitry may not outweigh the possibility of reducing the life expectancy of your ESP8266.


message:
Name of the Arduino Nano clone in the device manager

I'm working on an app using Matlab and it recieves data from an arduino. I've changed my board into an Arduino Nano (clone) recently. My program will automatically check for the device's name in the list of serial devices connected and it will connect to it directly once the user presses connect. The user doesn't have to input any Com port number or baud rate. This worked fine with my previous boards (UNO, Pro Micro, Leonardo). I just need to change the search string in my code and it'll automatically connect. My current board however is different, I'm using VMA102 (Arduino Nano clone). It uses FTDI drivers which I downloaded following [this][1] tutorial. I can upload the codes correctly to it but I just doesn't show a name with in the ports list in Arduino IDE as shown in the picture below.

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

Now when I looked it up in the device manager the name was 'USB Serial Port (COM5)' so I pasted 'USB Serial Port' as my search text in Matlab, it doesn't find it. I concluded that the correct name for it is not 'USB Serial Port' but rather the 'no name' as shown in Arduino IDE. Is there a way to find what is it called or how I can change it into a unique name so that my app can search for it?

Edit: here is the code, it works fine with all the other boards:
    devices = IDSerialComs();%gets all the avilabe com ports and thier names (name, com#)
    assignin('base','devices',devices);%save it to main workspace

    i=1;index=0; tesst= zeros(length(devices),1);%saves the comparison results
    while i<=length(devices)
        tesst(i)= strcmp(devices{i,1},'USB Serial Port');%compare the received names with the board's name
        % 'SparkFun Pro Micro''Arduino Uno'
        if ( tesst(i)==1 )
            index=i;%save the index
        end
        i=i+1;
    end

    if(isempty(find(tesst,1)))
        msgbox({'Connection failed' ' plug the device, wait for 5 seconds then try again'} ,'Connection Failure','error');
    else
        msgbox('Connection successful, proceed to the next tabs', 'Connection success');
    end
    %get the COM# associated with the index and add COM before it to from the comport number as a string
    COM_Num = strcat('COM',num2str(devices{index,2}));
    comport= serial(COM_Num, 'BaudRate', 115200);

and here is a screenshot of my device manager

[![enter image description here][3]][3]

Thanks

  [1]: https://learn.sparkfun.com/tutorials/how-to-install-ftdi-drivers/all
  [2]: https://i.stack.imgur.com/hRdSL.png
  [3]: https://i.stack.imgur.com/3FyHJ.png

body:
If you do a windows search for the device manager you will be able to see all the com devices currently connected to your computer. Unplug and replug your Arduino and it should be pretty easy to spot.

Mine is the USB-SERIAL CH340

[![Mine is the USB-SERIAL CH340][1]][1]

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


body:
The  IDSerialComs() function scans the Windows registry and associated active COM ports with their registered "Friendly Name". To scans using the following path:

    'HKEY_LOCAL_MACHINE\SYSTEM\CurrentControlSet\Enum\USB\'

But driver FTDI uses another path:

    'HKEY_LOCAL_MACHINE\SYSTEM\CurrentControlSet\Enum\FTDIBUS\'

Try to modify the function so that it meets your needs.


message:
Why analogue pins affect each other?

I have a sensor and it generates an analogue signal.

I am reading all analogue data and sending it to my computer.

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

    uint8_t sensors[] = { A0,A1,A2,A3,A4,A5,A6 };
    const int len = sizeof(sensors) / sizeof(sensors[0]);
    void loop(void)
    {
     for (size_t i = 0; i < len; i++)
     {
      auto sensor = sensors[i];
      int sensorValue = analogRead(sensor);
      // Convert the analogue reading (which goes from 0 - 1023) to a voltage (0 - 5V):
      float voltage = sensorValue * (5.0 / 1023.0);
      char t[100];
      sprintf(t, "%d:%d$\n", sensor, sensorValue);
      uint8_t t1[100];
      //PrintSerial.println(t);
      memcpy(t1, t, 100);
      wifi.send(t1, strlen(t));
     }
     delay(300);
    }

I plotted the analogue reading. Why does the graph look like this?

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

  [1]: https://i.stack.imgur.com/amj6Al.jpg
  [2]: https://i.stack.imgur.com/cf1Av.png

body:
This is to be expected.

The other pins have nothing connected to it, so their voltage is floating.

The Arduino MCU only has a single ADC. To read the different analog pins, it uses a multiplexer to connect the pin you want to read to the single ADC. The ADC inside the MCU have a "sample and hold" capacitor inside it.

To read the voltage at the pin, it will connect the pin, to charge the sample and hold capacitor. It will then disconnect and measure the voltage of the sample and hold capacitor, one bit at a time.

So in your case, by reading the voltage at the connected pin, it will charge the capacitor. It will then read the unconnected pins. But because nothing is connected the sample and hold capacitor will stay at about the same voltage, because the unconnected pin will neither charge, nor discharge it.

Measuring the voltage on the sample and hold capacitor will slightly lower this voltage, so that's why in the graph the lines will be lower than the previous measurement.

PS Also, because all the pins are placed in a breadboard, you'll have some capacitive coupling between the adjacent pins.


body:
The acc is really a little capacitor. As you switch channels, the charges in the acc capacitor get carried from one input channel to the next. If the next input channel is of very high impedance, or very low capacitance, the charges on the acc capacitor dominate and its voltage changes little.

In addition, poor code can cause it too - usually from a lack of sufficient time for the add to complete.


message:
Writing a custom character on an lcd

I am using a 16*2 lcd display as a dashboard computer.
I want it to display a logo at the very beginning of the code, but some letters occupy the space of 4 characters, and are using both lines of the display, and creating those letters character by character (some actually require 6 characters) is very difficult.
Is there anyway i can address the lcd as a big matrix ?
there would be 16 lines ( the oringinal 2 lines * 8 lines of each character) and 80 columns (the original 16 columns * 5 columns each character has).
This would make it A LOT easier.

body:
The chip you are using (HD44780) only works with characters; you can't address single pixels. If you read the datasheet, the word "pixel" is absent.

Of course, you can add a wrapper that implement a `drawPixel(row,col)` function by defining custom characters and then sending it to the display.

The result will be unpleasent to the eye, because there is a gap between chars on screen, and another gap between rows.

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

A better alternative is an OLED display like this:

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

You can find the same display with I2C or SPI interfaces. Basic model is B&W, but you also have color and touch sensitive variants.

  [1]: https://i.stack.imgur.com/ZTYWq.jpg
  [2]: https://i.stack.imgur.com/qm5ly.jpg


body:
> some letters occupy the space of 4 character

use CGRAM to define 4 characters and display them over two lines.


message:
ESP8266-01 connected to Arduino Mega - Current output?

[![Arduino ESP8266-01][1]][1]

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

I was thinking of powering my arduino with an external 9 V power source, but I am still trying to figure out the best way to get the right amount of current for the Wi-Fi module. Should I use an external power supply for the ESP8266-01 module that can output about 500mA or amplify the output from the arduino pins using a transistor?

If there is an easier way to do this I am all ears. I will be using Arduino Mega, not uno as shown in the picture.

EDIT: Voltage divider will be used on the RX pin and I might go for a logic level converter instead of the voltage regulator

body:
> Should I use an external power supply for the ESP8266-01 module that can output about 500mA or amplify the output from the arduino pins using a transistor?

Either way you're going to need a power supply that can supply the current. A transistor doesn't magically create more current, it merely allows a small current to control the flow of a larger current.

So you will need an external power source that can provide enough current.

> I might go for a logic level converter instead of the voltage regulator.

Incorrect. A logic leven converter cannot provide anywhere near enough current to power a device. It can barely provide enough to light an LED.

You are right to want to ditch the voltage regulator though.

As it stands you have a chain of regulators, each one wasting power. At 500mA that's lots of power.

    9V -> [REG] -> 5V -> [REG] -> 3.3V

That's 4V dropped in the first regulator at ~500mA, and 1.7V dropped in the second regulator at ~500mA. Since P=VI, 4×0.5 = 2W, and 1.7×0.5 = 0.85W. Since you are providing 9×0.5 = 4.5W of power from the battery, you have 1-((2+0.85)÷4.5) = 0.366, or 36% efficiency. That's about two thirds of your battery power wasted just in heat.

Instead you want to use a switching voltage regulator. These are far more efficient and convert voltage into current rather than voltage into heat. This means that you draw less current from your battery, meaning you can use a battery with a higher internal resistance.

Ideally you would use two - one to convert the 9V into 5V to power the Arduino, and another to convert the 9V directly into 3.3V to power the ESP8266. That would be the most efficient arrangement.

There are plenty of breadboard friendly modules on eBay that can do that, or other small modules you can wire in to your circuit without a breadboard ([I myself sell one on eBay that I designed](http://www.ebay.co.uk/itm/DualBEC-UBEC-3-3V-5V-Dual-Switching-Power-Supply-Battery-LiPo-TC105-Buck-Regulat-/182257612998)).


message:
Arduino Uno WiFi - WiFi mode keeps changing

I have an [Arduino Uno WiFi][1] device, which is turned on all the time (day and night). The WiFi mode is set to 'STA'. But from time to time it switches to 'AP+STA' mode automatically, so the device is visible in the network as an Access Point, which is not what I want. Is there a way to prevent my Arduino Uno to switch the WiFi mode by itself? Can it be done via code maybe? Thank you for your help.

Here's the code that is working on it (and it's still working without any problems):

    #include <Wire.h>
    //#include <Ciao.h> // for older IDE
    #include <UnoWiFiDevEd.h> // for newer IDE

    #include <Adafruit_NeoPixel.h>
    #ifdef __AVR__
      #include <avr/power.h>
    #endif

    int sensorsValues[] = {9999,9999,9999};
    int timerCount = 25;
    static const uint8_t analogPins[] = {A0, A1, A2};

    // for LEDs
    int NUMPIXELS = 9;
    Adafruit_NeoPixel strip = Adafruit_NeoPixel(NUMPIXELS, 2); // (numOfPixels, pinNo, options)

    boolean hasChanged = false;

    void setup() {
      // This is for Trinket 5V 16MHz, you can remove these three lines if you are not using a Trinket
      #if defined (__AVR_ATtiny85__)
      if (F_CPU == 16000000) clock_prescale_set(clock_div_1);
      #endif
      // End of trinket special code
      //start serial connection
      Serial.begin(9600);
      for(int i=0; i<3; i++){
        pinMode(analogPins[i], INPUT_PULLUP);
      }
      strip.setBrightness(40);
      strip.begin(); // Initialize the NeoPixel library.
      strip.show(); // Initialize all pixels to 'off'
      Ciao.begin();
    }

    void loop() {
      for (int i = 0; i < 3; i++) {
        int sensorVal = analogRead(analogPins[i]) >= 1000 ? 1 : 0;
        if( sensorsValues[i] != sensorVal ) {
          hasChanged = true;
          if (sensorVal == 1) {
            // green light
            strip.setPixelColor( (i*3), 100, 255, 100);
            strip.setPixelColor( (i*3)+1, 100, 255, 100);
            strip.setPixelColor( (i*3)+2, 100, 255, 100);
            strip.show();
          } else {
            // red light
            strip.setPixelColor( (i*3), 255, 50, 50);
            strip.setPixelColor( (i*3)+1, 255, 50, 50);
            strip.setPixelColor( (i*3)+2, 255, 50, 50);
            strip.show();
          }
        }
        sensorsValues[i] = sensorVal;
      }
      timerCount += 1;
      if( hasChanged == false && (timerCount % 30) == 0 ){
        CiaoData data = Ciao.write("rest", "xxx.xxx.xxx.xxx", "/d/add/A001/active", "GET");
        if (!data.isEmpty()){
          String st = String(data.get(1));
          String re = String(data.get(2));
        }
      }
      if (hasChanged == true && (timerCount % 5) == 0 ) {
        CiaoData data = Ciao.write("rest", "xxx.xxx.xxx.xxx", "/d/add/A001/a/" + String(sensorsValues[0]) + "," + String(sensorsValues[1]) + "," + String(sensorsValues[2]), "GET");
        if (!data.isEmpty()){
          String st = String(data.get(1));
          String re = String(data.get(2));
        }
        hasChanged = false;
      }
      if (timerCount > 30) timerCount = 0;
      delay(1000);
    }

  [1]: http://www.arduino.org/products/boards/arduino-uno-wifi

body:
OK. I found a little workaround. Arduino UNO Wifi web interface gives some possibilities. When you go to `http://<IPADDRESS>/wifi/info` you'll get json formatted info about its wifi connection settings, including WiFi mode (STA or AP+STA). To set new WiFi Mode you can go to `http://<IPADDRESS>/wifi/setmode?mode=<MODE>` to set new mode. mode=1 is for 'STA', mode=2 is for 'AP' only and mode=3 is for 'AP+STA'.
I've created a little cron job on my server that checks the wifi mode and changes it if needed.


body:
Note that when the Uno WiFi board first boots, it is in AP+STA mode...

- Which means it broadcasts its own SSID (that's the AP part).

AND

- It can connect to an existing wireless AP on your network, if you've configured those settings (that's the STA part, because it's a STAtion off the infrastructure AP).

IDEALLY

- You will change it to STA mode so it connects to your existing wireless AP only and stops broadcasting as its own AP.

Why does yours go back to AP+STA mode?  Is your sketch crashing/running out of memory/rebooting?  Is it older firmware?  I'm not sure.


message:
Adding data to an SD card file

I'm reading data from the Shinyei PPD42 particle sensor unit.
Everything seems to work, but I'm encountering two problems

1. When I restart Arduino, the file is not being extended, nor overwritten. It just remains how it was before.

2. Even though my code looks fine, Arduino stops writing data to the SD card after 90 seconds.

Thanks for having a look at my code.

    #include <SPI.h>  //een bibliotheek aan code toevoegen; Arduino heeft deze nodig om de Shield te kunnen 'lezen'
    #include <SD.h>   //zie hierboven

    int PM=8; //de fijnstofmeter zit in digitaal poortnummer 8

    const int chipSelect = 10; //const = een variabele die nooit verandert

    unsigned long sampletime_ms = 30000;  //unsigned long = een variabele die erg hoog kan oplopen, maar nooit negatief kan zijn

    //hieronder volgen nog enkele variabelen. Denk eraan: float betekent dat het decimale getallen kunnen zijn

    unsigned long duration;
    unsigned long starttime;
    unsigned long lowpulseoccupancy = 0;
    unsigned long timediff;
    float ratio = 0;
    float concentration = 0;
    unsigned long tijd = 30;

    //void setup wordt één keer uitgevoerd, bij het opstarten van de Arduino-minicomputer

    void setup()
      {
        Serial.begin(9600); //de snelheid (in bits/second) aan welke de seriële data zal worden getransfereerd
        pinMode(PM,INPUT);  /*PM is de variabele van helemaal bovenaan: pinMode vraagt twee parameters 1)de poort (werd gedefinieerd bovenaan) 2)INPUT of OUTPUT
                              Ditmaal leest de fijnstofmeter gegevens die we vervolgens IN onze Arduino willen importeren, dus INPUT*/

        starttime = millis(); //hoelang draait het programma? millis() geeft de duur sinds het werd opgestart

        Serial.println("SD-kaart opstarten indien aanwezig... "); //Je schrijft nu neer dat de SD-kaart wordt gezocht en opgestart (println = hierna op volgende regel verder gaan)

        //hieronder staat een 'als'-lus: als aan de eerste voorwaarde wordt voldaan, voert hij uit wat eronder staat, anders gaat Arduino verder achter de afsluitende accolade

        if (!SD.begin(chipSelect)) //Als er NIET (!) kan worden begonnen met de SD-kaart te selecteren ...
          {
            Serial.println("Corrupte of ontbrekende SD-kaart!"); //dan wordt deze boodschap getoond
            return;
          }
        //Als de SD-kaart dus WEL werkt, gaan we hieronder verder

        Serial.println("SD-kaart werkt...");
        Serial.print("Fijnstofsensor start op. Even geduld! Metingen om de 30 seconden.");
        Serial.println("\n");
      }

    //void setup wordt oneindig lang uitgevoerd, tenzij je dat anders bepaalt

    void loop ()
      {
        duration = pulseIn(PM, LOW); //als de fijnstofdetector niet meet (LOW), beginnen meten
        lowpulseoccupancy = lowpulseoccupancy+duration; //na elke meting de 'duration' (30 sec)  optellen bij de totale tijd

        if ((millis()-starttime) >= sampletime_ms)
          {
            //hieronder de wiskundige berekeningen om het fijnstofgehalte te berekenen

            ratio = lowpulseoccupancy/(sampletime_ms*10.0);
            concentration = 1.1*pow(ratio,3)-3.8*pow(ratio,2)+520*ratio+0.62;

            //hieronder alles wat zal worden geprint naar het seriële venster

            Serial.print("Fijnstofconcentratie na ");
            Serial.print(tijd);
            Serial.println(" seconden:");
            Serial.print(concentration);
            Serial.println(" deeltjes/0,01cf");
            Serial.print("\n");

            File dataFile = SD.open("test.txt", FILE_WRITE); //het bestand meting.txt moet op de SD-kaart worden geopend om erin te schrijven

            if (dataFile) //als het bestand kan worden geopend, volgende gegevens printen
              {
                dataFile.print("Fijnstofconcentratie na ");
                dataFile.print(tijd);
                dataFile.print(" seconden: ");
                //dataFile.println(ratio);
                dataFile.print(concentration);
                dataFile.print(" deeltjes/0,01cf");
                dataFile.print("\n");
                dataFile.close();
              }

            else //als het bestand niet kan worden geopend ...
              {
                Serial.println("Fout bij het openen van test.txt");
              }

            tijd = tijd + 30; //meting afgerond, totale tijd = +30 seconden
            lowpulseoccupancy = 0; //de status van de fijnstofmeter is terug 'LOW'
            starttime  = millis(); //volgende meting starten
          }
      }

body:
You need to open the file in append mode:

    SD.open("file.txt", O_RDWR | O_APPEND);

It depends on the file being there. If it fails to open because the file isn't there you can open it in "create" mode instead:

    SD.open("file.txt", O_RDWR | O_CREAT);

For example:

    // Try and append
    File f = SD.open("file.txt", O_RDWR | O_APPEND);
    if (!f) {
        // It failed, so try and make a new file.
        f = SD.open("file.txt", O_RDWR | O_CREAT);
        if (!f) {
            // It failed too, so give up.
            Serial.println("Failed to open file.txt");
        }
    }

    // Only write to the file if the file is actually open.
    if (f) {
        f.print(/* your data here */)
        f.close();
    }


message:
Not sure I'm understanding pipes for NRF24

I've started working with the NRF24 library for some fun little side projects. I have only gotten through some basic tests but I'm starting to look at ways to tinker with the code. I have more experience as a programmer so the hardware side is always new to me. Where I'm a little confused is how the pipes are used. Working from [this example][1], I see that one pipe is used to listen and another is used to transmit. If there's just two devices, why don't they both use the same pipe? If you have multiple devices on the same pipe transmitting, can it jumble the signals? Is there a way to receive on multiple pipes? I'd love more information on how pipes are or should be used.

  [1]: https://github.com/maniacbug/RF24/blob/master/examples/GettingStarted/GettingStarted.pde

body:
I don't see any reason for doing this.

Multiple devices sending data at the same time will cause collisions irrespective of the pipe-nr they are using.

Pipe is also a not very accurate name for what it actually is. It's just a number, that the receiving NRF can check, to see if the packet that was received was intended for it. Kind of like a MAC address on a network.

You can have two unique reading pipes. Then there are 4 more pipes you can use, that are identical to the second pipe, except for the last byte.

The first pipe is used to specify the pipe you are sending through. So if you send to different pipes, this pipe isn't ideal for listening, as you'd have to change it back every time you send a packet. Possibly loosing a packet that was send in between.

If you want more information, i'd suggest reading the datasheet, and read the [documentation of one of the libraries](http://maniacbug.github.io/RF24/classRF24.html). I personally checked the sourcecode of the library a lot while at the same time referencing the datasheet, to really understand what it's doing.


message:
ESP8266 (ESP-01) Not booting with load on IO pin 2

I'm using an ESP-01 to control a load (SSR), which is connected to IO pin 2. This pin needs to be `HIGH` at boot time, otherwise the module won't boot. I've tried driving the load with an optocoupler to avoid driving the pin `LOW` while booting, but it's not working. Do you know of any solution to make it boot correctly without changing the IO pin? (there's only two GPIO pins, both ocuppied, plus serial port pins).

body:
Simply invert the logic - so that LOW turns the SSR on and HIGH turns it off.

Try something like this:

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

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

<!-- End schematic -->

The P-channel FET will invert the logic. Pull GPIO2 LOW and it will turn on the FET which will enable the SSR. The 10KΩ resistor keeps the GPIO pin (and the gate of the FET) HIGH at other times.

If the GPIO pin can sink enough current to directly drive the SSR you can leave out the FET:

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

<!-- End schematic -->

Again the logic is inverted. Pull GPIO2 LOW to sink current through the SSR to turn it on. The resistor keeps the GPIO pin held HIGH when booting.


body:
I did something similar to what @Majenko proposed in his answer (as in I inverted the output), but instead of using R1 as a pullup resistor in paralell with the SSR's LED, I'm using it as a normal current limiting resistor. In other words, I just swapped GPIO2 from sourcing the SSR to sinking it. The schematic is like this:

[![Circuit Schematic][1]][1]

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


message:
Using dynamic variables in URL

I am trying to upload longitude and latitude data into MySQK using a GPRS shield, Arduino Uno R3 and a GPS module. The idea is to get longitude and latitude data from the GPS and use the GPRS to post the information into my database.

I have to insert the latitude and longitude data into the URL like  this `steetalert.co.zw/write_data.php?Longitude=12.124311,Latitude=27,766785`. Values for longitude and latitude have to be dynamic not static. How do I go about this?

body:
It looks like you need to know how to create a string that contains:
`steetalert.co.zw/write_data.php?Longitude=12.124311,Latitude=27,766785`

Its quite easy (I think) try this:

    const int cDecimalPlaces(6);
    String szLon = String(fLongitude, cDecimalPlaces);
    String szLat = String(fLatitude, cDecimalPlaces);
    String szUrl = "steetalert.co.zw/write_data.php?Longitude=" + szLon ",Latitude=" + szLat;

Normally I would use sprint or a Format function, but I can't find those in the reference.


message:
When a pushbutton and sensor are in a certain state, do something for a certain period of time (15 seconds)

I have a sketch that contains code for an analog input (FSR sensor), a pushbutton, and 6 blinking LEDs.

Currently, the sketch is written to allow the LEDs to blink only when the button is pressed and there is sensor input.

Can someone help me write code to make the LEDs blink for a certain period of time once there is input from the analog sensor and while the button is pressed?  I am trying to make the LED blink for 15 seconds and then turnoff.

thank you!

    /*
     6 Flashing LED Lights With A Pushbutton and FSR Sensor
    */

    const int buttonPin = 8;
    const int LedPin1 = 7;
    const int LedPin2 = 6;
    const int LedPin3 = 5;
    const int LedPin4 = 4;
    const int LedPin5 = 3;
    const int LedPin6 = 2;

    int buttonState = 0;
    int SensorPin = A0;
    int SensorPinReading;

    void setup() {
      Serial.begin(9600);
      pinMode(LedPin1, OUTPUT);
      pinMode(LedPin2, OUTPUT);
      pinMode(LedPin3, OUTPUT);
      pinMode(LedPin4, OUTPUT);
      pinMode(LedPin5, OUTPUT);
      pinMode(LedPin6, OUTPUT);
      pinMode(buttonPin,INPUT);
      pinMode(SensorPin, INPUT);
    }

    void loop() {
      SensorPinReading = analogRead(SensorPin);
      Serial.print("Analog reading = ");
      Serial.print(SensorPinReading);

    if (SensorPinReading < 10) {
      Serial.println(" - No Pressure");
    } else if (SensorPinReading < 200) {
      Serial.println(" - Light Touch");
    } else if (SensorPinReading < 500) {
      Serial.println(" - Light Squeeze");
    } else if (SensorPinReading < 800) {
      Serial.println(" - Medium Squeeze");
    } else {
      Serial.println(" - Big Squeeze");
    }

      buttonState = digitalRead(buttonPin);
      if (buttonState == HIGH && SensorPinReading > 10)  {
      digitalWrite(LedPin1, HIGH);
      digitalWrite(LedPin2, HIGH);
      digitalWrite(LedPin3, HIGH);
      digitalWrite(LedPin4, HIGH);
      digitalWrite(LedPin5, HIGH);
      digitalWrite(LedPin6, HIGH);
      delay(600);
      digitalWrite(LedPin1, LOW);
      digitalWrite(LedPin2, LOW);
      digitalWrite(LedPin3, LOW);
      digitalWrite(LedPin4, LOW);
      digitalWrite(LedPin5, LOW);
      digitalWrite(LedPin6, LOW);
      delay(200);
      }
      else {
        digitalWrite(LedPin1, LOW);
        digitalWrite(LedPin2, LOW);
        digitalWrite(LedPin3, LOW);
        digitalWrite(LedPin4, LOW);
        digitalWrite(LedPin5, LOW);
        digitalWrite(LedPin6, LOW);
      }

    }

body:
Here below is modified code based on your requirement. There are some changes in your code and I also comment it out. I hope it will help you.

    /*
     6 Flashing LED Lights With A Pushbutton and FSR Sensor
    */

    const int buttonPin = 8;

    const int LedPin1 = 7;
    const int LedPin2 = 6;
    const int LedPin3 = 5;
    const int LedPin4 = 4;
    const int LedPin5 = 3;
    const int LedPin6 = 2;

    const int kDelay = 1000; // Take one varible "kDelay" and value = 1000

    int buttonState = 0;
    int SensorPin = A0;
    int SensorPinReading;

    void setup()
    {
      Serial.begin(9600);
      pinMode(LedPin1, OUTPUT);
      pinMode(LedPin2, OUTPUT);
      pinMode(LedPin3, OUTPUT);
      pinMode(LedPin4, OUTPUT);
      pinMode(LedPin5, OUTPUT);
      pinMode(LedPin6, OUTPUT);

      pinMode(buttonPin,INPUT_PULLUP); // Provide PULLUP
      pinMode(SensorPin, INPUT);
    }

    void loop()
    {
      SensorPinReading = analogRead(SensorPin);
      Serial.print("Analog reading = ");
      Serial.print(SensorPinReading);

      if(SensorPinReading < 10)
      {
        Serial.println(" - No Pressure");
      }
      else if (SensorPinReading < 200)
      {
        Serial.println(" - Light Touch");
      }
      else if (SensorPinReading < 500)
      {
        Serial.println(" - Light Squeeze");
      }
      else if (SensorPinReading < 800)
      {
        Serial.println(" - Medium Squeeze");
      }
      else
      {
        Serial.println(" - Big Squeeze");
      }

      buttonState = digitalRead(buttonPin);

      if(buttonState == HIGH && SensorPinReading > 10)
      {
        digitalWrite(LedPin1, HIGH);
        digitalWrite(LedPin2, HIGH);
        digitalWrite(LedPin3, HIGH);
        digitalWrite(LedPin4, HIGH);
        digitalWrite(LedPin5, HIGH);
        digitalWrite(LedPin6, HIGH);
        delay(15 * kDelay);            // You need 15 Sec, multiply kDelay with 15
        digitalWrite(LedPin1, LOW);
        digitalWrite(LedPin2, LOW);
        digitalWrite(LedPin3, LOW);
        digitalWrite(LedPin4, LOW);
        digitalWrite(LedPin5, LOW);
        digitalWrite(LedPin6, LOW);
      }
      else
      {
        digitalWrite(LedPin1, LOW);
        digitalWrite(LedPin2, LOW);
        digitalWrite(LedPin3, LOW);
        digitalWrite(LedPin4, LOW);
        digitalWrite(LedPin5, LOW);
        digitalWrite(LedPin6, LOW);
      }
    }


body:
The code shown below is to “make the LEDs blink like the previous sketch during the 15 seconds”.  The  previous sketch (that is, the code in the question) turns the LEDs on for 600 ms and off for 200.  The code below reverses the order – that is, does off for 200 and on for 600 – and repeats that pattern during the first 15 seconds after conditions being met.  The annoyingly complicated `if` statements in the code are to prevent retriggering; that is, to prevent another 15-second blink session immediately starting up if the trigger conditions are still present.  Your problem statement is not perfectly clear on how that should be handled.

    // 6 Flashing LED Lights With A Pushbutton and FSR Sensor

    enum { LedPin6=2, LedPin5, LedPin4, LedPin3, LedPin2, LedPin1 };
    enum { buttonPin=8, SensorPin = A0};
    enum { quantum=200, sessionLength=15000/quantum};

    byte buttonState = 0;
    byte SensorPinReading;
    byte blinkLEDs=false, sessionDone=false;
    unsigned long baseMilli;

    void setLEDlevels(byte level) {
      digitalWrite(LedPin1, level);
      digitalWrite(LedPin2, level);
      digitalWrite(LedPin3, level);
      digitalWrite(LedPin4, level);
      digitalWrite(LedPin5, level);
      digitalWrite(LedPin6, level);
    }

    void setup() {
      Serial.begin(115200);
      pinMode(LedPin1, OUTPUT);
      pinMode(LedPin2, OUTPUT);
      pinMode(LedPin3, OUTPUT);
      pinMode(LedPin4, OUTPUT);
      pinMode(LedPin5, OUTPUT);
      pinMode(LedPin6, OUTPUT);
      pinMode(buttonPin,INPUT);
      pinMode(SensorPin, INPUT);
    }

    void loop() {
      SensorPinReading = analogRead(SensorPin);
      Serial.print("Analog reading = ");
      Serial.print(SensorPinReading);

      if (SensorPinReading < 10) {
        Serial.println(" - No Pressure");
      } else if (SensorPinReading < 200) {
        Serial.println(" - Light Touch");
      } else if (SensorPinReading < 500) {
        Serial.println(" - Light Squeeze");
      } else if (SensorPinReading < 800) {
        Serial.println(" - Medium Squeeze");
      } else {
        Serial.println(" - Big Squeeze");
      }

      buttonState = digitalRead(buttonPin);
      // Turn on 15-second blink session if conditions met
      if (buttonState == HIGH && SensorPinReading > 10)  {
        if (!blinkLEDs && !sessionDone) { // Is session eligible?
          blinkLEDs = true;
          sessionDone = false;
          baseMilli = millis();
        }
      } else {        // A condition failed.
        if (sessionDone)       // Has session finished?
          blinkLEDs = sessionDone = false; // Enable next session
      }

      if (blinkLEDs) {
        int age = (millis()-baseMilli)/quantum;
        setLEDlevels((age&3)>0); // Off for 1 quantum, on for 3 quanta
        // See if blink session has run long enough
        if (age > sessionLength) {
          blinkLEDs = false;        // Stop blinking
          sessionDone = true; // Prevent retrigger until conditions reset
          setLEDlevels(LOW); // Turn off lights
        }
      }
    }

The statement `setLEDlevels((age&3)>0)` calls `setLEDlevels()` with a parameter value of 0 or 1.  It will be 0 if `age` is a multiple of 4.  In binary, multiples of 4 have their lowest two bits clear.  It will be 1 if `age` is not a multiple of 4.  This will alternately turn the LEDs off for one quantum (200 ms) and then on for 3 quanta (600 ms).

---

*Edit 1:* To  “make the sensor read input while the button is not pressed, and then relay that input once the button is pressed so the LEDs immediately light up when it is pressed”, add a state variable (eg `sensorPressed`) to use in place of `SensorPinReading > 10`.  Whenever `SensorPinReading` is large enough (and any other necessary conditions are met), set `sensorPressed`.  When you start a blink session, reset `sensorPressed` (make it false).

Note, from your comment, you've added the following code near the end of `loop()`:

    if (buttonState == LOW && blinkLEDs == true) {
      blinkLEDs = false;
      sessionDone = true;
      setLEDlevels(LOW);
    }

A minor issue with that code is it leaves `sessionDone = true`.  It is minor because the next pass through `loop()` usually will execute the `else` branch (of the `if (buttonState == HIGH && SensorPinReading > 10)` if-statement) which will go ahead and set `sessionDone = false` to enable the next blink session.  Assuming you want to shut down blinking whenever the button is low, what I would do instead of that little code block is this:

    if (!buttonState) {
      blinkLEDs = sessionDone = false;
      setLEDlevels(LOW);
    }

(The expression `!buttonState` has the same value as `buttonState == LOW` and is four syllables shorter.)

Note, the code perhaps can be made more clear by using a *state machine* to control what happens.  To do so, draw a diagram with nodes representing possible states – such as “idle” or “waiting for inputs”, “enabled”, “blinking”, “after blinking”.  Draw lines between states, each labeled with the condition that triggers the particular state transition.  State machines can be implemented using switch and case statements, or via an if–else sequence.


message:
Issue with HC-SR505 sensor

I have been using a HC-SR501 PIR module with my Arduino Mega and it was tracking presence pretty well.

Because of cost constraints, I decided to go with HC-SR505 sensor - bought a bunch of them. The performance is very bad. It almost seems like it is giving random HIGH and LOW values. Out of the 20 odd sensors I bought, may be one or two are fairly ok - others are all behaving weird. Have someone experienced this kind of behavior with HC-SR505?

Are they highly sensitive to noise in the power supply - is there any workaround to mitigate the effect? Help?

Code:

    const int buttonPin = 4;

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

       pinMode(buttonPin, INPUT);
     }
     void loop()
     {
        if (digitalRead(buttonPin) == HIGH)
        {

          Serial.println("Presence Detected");
        }
        else {

          Serial.println("No Presence Detected");
        }

     delay(2000);

     }

body:
You asked if anyone else has experienced this behavior, and from the documentation I can find the answer must be yes.

The 505 holds the HIGH output for a certain amount of time.  None of the documentation I can find on it specifies the amount of time.  So it is very possible that you are operating right near that limit.  If their quality control is not perfect, some might work correctly and some might not.

In other words, I believe the problem is that you are not allowing for the built-in time delay in the SR505.

That is the main difference between the 501 and the 505.  On the 501 it is adjustable in both sensitivity and time delay.  With the 505 those values are preset.

As a workaround, you can try increasing your delay upwards from 2000ms until you find the right value that will work consistently with your batch of them.

The sensitivity cannot be adjusted, either, but this can be an advantage if you are trying to cover a smaller area than you would try with the 501.  They both have the same 90-100 degree width of view, but the 505 is made for shorter range like a doorway, as opposed to the 501 which can cover an entire room.


body:
According to this wiki: https://www.elecrow.com/wiki/index.php?title=HC-SR505_Mini_PIR_Motion_Sensor, there is an 8 second +/-30% delay.

The sensor is very sensitive to motion. Waving your hand in front of it "as fast as you can" (at close range) will trigger the sensor. While testing the two I had purchased, they had to be pointed away from me or there were "false alarms".


body:
I had the same problem of the sensor giving random 1/0 values. I then looked at the circuit closer.

The PINs are badly marked which doesn't tell great detail, PIN-1 is marked with "+", however the word "OUT" is sitting between PINs 2 and 3.

If you connect + to the +5V, and then the middle PIN into the GND and then OUT into your Arduino (say PIN-10 of your Arduino), then you will notice ups and downs that does not correspond to any movements, (i.e. telling you "Bad Sensor")... however:

> Part-1 of the solution:

Swapping PINs 2 and 3 of the sensor (i.e. + goes into +5V of Arduino, Ground is PIN-3 of the sensor, and Middle is what you should be reading (i.e. PIN-10 of Arduino)) then this should start to work, but we're not finished yet, you would still get bad results...

> Part-2 of the solution:

If you are reading from PIN-10 of Arduino, then on your setup() function would usually be like this:

    setup()
    {
     pinMode(10, INPUT);
    }

This is NOT enough for that sensor!... I know,... should be right?!...

Anyway, you MUST tell that PIN to be ZERO at the start, otherwise, it's hell brake loose... Therefore, please write the PIN with 0 and then it should all work fine after that:

    setup()
    {
        pinMode(10, INPUT);
        digitalWrite (10, LOW);
    }

Following the above does resolve the issue, the sensor worked absolutely fine.

One annoying issue however which I am currently trying to work on is to reduce the sensor delay timer from 8 seconds into just 1-2 seconds, i.e. once someone is in-front of the sensor I don't want it to tell me that the person was there still when he left the area almost 7 seconds ago... I might post another article on how to do this later.

In the mean time, I hope this helps to resolve this problem

Regards
Heider


body:
By shining with a bright light through the PCB, I came up with this reverse-engineered circuit diagram. From my understanding, the IC is some sort of special OP amp. I suppose one can change the timing by adjusting the 154 (150k) resistor and the sensitivity by adjusting the 335 (3.3Meg) and/or the 103 (10k) resistor. [![enter image description here][1]][1]

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


message:
How do I change number and bracket colors in the arduino IDE?

I recently personalized my arduino IDE (changed the background color, input text color, etc....) by going into the theme.txt file and replacing some hexadecimal values. I made the background black and the text lime green, but for some reason numbers and brackets still remain black, thus I can't see them against a black background. Anyone know how to fix this? I would really appreciate the help, got sick of looking at a white background when making sketches.

Sal

body:
Inside path `C:\Program Files (x86)\Arduino\lib\theme\syntax` there is file `default.xml` where I made some changes and the following lines are as follows:

      <style token="SEPARATOR" fg="ffffff" />
      <style token="LITERAL_NUMBER_DECIMAL_INT" fg="ffffff"/>
      <style token="LITERAL_NUMBER_FLOAT" fg="ffffff"/>
      <style token="LITERAL_NUMBER_HEXADECIMAL" fg="ffffff"/>

After this brackets and numbers occur white.


message:
Evaluating delay for Xbee

I will explain my task in a simplified way. I'm communicating among 3 Xbee's.

The attached code is for the sender Xbee. This Xbee actually sends multiple values of **value1** (*here for simplification I assigned it to constant value 10*). For finding the value1 it does some other calculations as well and then assigns it.

But I find that if I reduce or remove the delay(100) I end up receiving improper values. I guess delay gives a buffer time for data transmission but my question is how to do I calculate the minimum delay or how can justify that this is the delay needed ?

I hope you can understand my question. If not please comment I will give some more pertinent details.

      // Sender Xbee
        void setup()
        {
        Serial.begin(9600);
        }
        void loop()
        {
        int value1 = 10; // some hardcoded values to send
        Serial.print('H'); // unique header to identify start of message
        Serial.print(value1,DEC);
        Serial.print(","); // note that a comma is sent after the last field
        Serial.print('\n'); // send a cr/lf
        delay(100);
        }

body: Based on my experience with Xbee, I would say the limit is 50ms as Xbee can do the lowest sampling rate of 50ms.


message:
Arduino Due vs Mega 2560

What can an Arduino Due do that a Mega 2560 can't? What can a Mega 2560 do that a Due can't? I've heard the Due is 3.3V so it can't work with most shields.

body:
The Due can do a lot of things much faster. It has more memory and far more processing power. It has more flexible and more powerful built-in peripherals.

It can't easily interface with 5V devices though.

The Mega2560 has less memory and far less processing power, but interfacing with legacy 5V devices is far easier. It's also more forgiving to the novice user than the more complex SAM3X chip.

From an Arduino programming point of view both boards are pretty much programmed the same. The language is, excepting a few esoteric anomalies, largely the same. However when you come to do low-level programming instead if relying on the Arduino API you would find that the ATMega2560 is a much simpler chip to program.  Power comes at a price. The more powerful SAM3X chip is much harder to get to grips with and program.

It's like comparing a Ford Escort with a Boeing 737. They're both vehicles, and they can both get you from A to B. The Boeing does it much faster and can carry more people, but flying it is a lot harder than driving a Ford Escort, and you can't fly it on an old-fashioned road.


body:
The 'R3' version boards and shields are compatible with 3.3V and 5V. For example the Ethernet Shield V1 version 'R3' can be used with the Due. The new Arduino Ethernet Shield 2 is also compatible with the Due.
Many older shield are not compatible with the Due, but do you really need to use an old shield ?

Most sensors are 3.3V, and also a SD memory card is 3.3V. That is a lot easer with the Arduino Due which runs at 3.3V.

The Arduino Mega 2560 board is the only board with 10k pullup resistors at SDA and SCL, therefor it has a 5V I2C bus. When a 3.3V sensor with I2C is used, you need a I2C level shifter. When a 3.3V with SPI is used, you need more hardware.

The Arduino Mega pins can drive more than 20mA, it can be used to drive 10 leds with 20mA simultaneously, the Arduino Due can't do that.

My suggestion is to use an Arduino Uno for all kind of testing. It's always good to have one lying around. Start with an Arduino Uno if you want to learn programming and have fun with leds and buttons.

The Arduino Zero or MKRzero or M0 have a M0+ processor at 3.3V and they can be used for all kind of nice projects. When you already know a little about programming and electronics, this is a very good choice.

The Arduino Due has more processing power then the M0+.

The Arduino Mega 2560 is still used, because there are many libraries and shields that are compatible with the Arduino Mega 2560.


body:
Ahhhh... There is a more profound problem than these mentioned because the MEGA treats double precision declarations as floating point ( far less precision ).  I was working with 1 CM GPS Location coordinates requiring double precision variables.  It took a while for me to discover that ONLY the DUE compiles to a true double precision variable.  The MEGA and most others do not.  They convert double to float at compiler level.  This is only meaningful if extremely precise math must occur.

Donald


message:
Arduino Nano, nodeJS serial

I tried to make a 2 way communication between my Arduino and a PC(running linux mint) using NodeJS:

My Arduino code:

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

    void loop() {
      if(Serial.available()) Serial.println(Serial.readString()+"\r");
    }
My NodeJS code:

    var SerialPort = require('serialport');
    var port = new SerialPort('/dev/ttyUSB0',{
      baudRate: 9600,
      parity: 'none',
      stopBits: 1,
      flowControl: false,
      parser: SerialPort.parsers.readline('\r\n')
    });

    port.on('open',function(){
      setInterval(() => port.write('Test'),1000);
    });

    port.on('data',(data) => console.log(data.toString()));

There is possible encoding error, but I cannot seem to find and fix this. Thanks in advance

body:
Ok, I solved the issue by using pure bytes, and then casting the response to the string in nodeJS, I post the codes in case anyone needs them:

    var SerialPort = require('serialport');
    var port = new SerialPort('/dev/ttyUSB0',{
      baudRate: 9600,
      parity: 'none',
      stopBits: 1,
      flowControl: false,
    //  parser: SerialPort.parsers.readline('\r\n')
    });

    function ab2str(buf) {
      return String.fromCharCode.apply(null, new Uint16Array(buf));
    }

    port.on('open',() => {
      setInterval(() => port.write('Test'),500);
    });

    port.on('data',(data) => {
      console.log(ab2str(data));
    });

And the Arduino code:

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

    void loop() {
      if(Serial.available()) Serial.write(Serial.read());
    }


body:
You don't need to revert to sending single bytes. Line oriented
protocols work well with both Arduino and Node.js. The only difficulty
is that you have to _decide_ what line terminators you want to use, and
then _consistently_ use them.

I tend to use CR for the PC → Arduino stream and CRLF for Arduino
→ PC. Using different line terminators is kind of odd, but this
convention plays well with terminal emulators: the emulator usually
sends CR when you hit `<Enter>`, and expects CRLF in return. Also,
Arduino's `Print::println()` sends CRLF.

Here is a simple test demonstrating this convention. Node.js side:

<!-- language: lang-javascript -->

    var SerialPort = require('serialport'),
        port = new SerialPort('/dev/ttyACM0', {
            baudRate: 9600,
            parser: SerialPort.parsers.readline('\r\n')
        });

    port.on('open', () => setInterval(() => port.write('Test\r'), 1000));
    port.on('data', console.log);

Notice the different line terminators in `readline()` and `write()`.

The Arduino side:

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

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

    void loop() {
        static char buffer[128];
        static size_t pos;

        if (Serial.available()) {
            char c = Serial.read();
            if (c == '\r') {                       // line terminator
                buffer[pos] = '\0';                // terminate the string
                Serial.print(F("Arduino received: "));
                Serial.println(buffer);            // echo received message
                pos = 0;                           // reset buffer position
            } else if (pos < sizeof buffer - 1) {  // regular character
                buffer[pos++] = c;                 // buffer it
            }
        }
    }

Here you may notice that Arduino has no equivalent of
`parsers.readline()`, so I had to implement it (comparing the incoming
character to `'\r'`). Note that explicit buffering of the incoming
message is a standard way of handling line-oriented protocols on
Arduino. `Stream::readString()` does not work well for this purpose, as
it waits for incoming bytes until it times out.
`Stream::readStringUntil()` may work better, but I prefer to avoid it
just because it returns a `String`, which relies on heap allocation.


message:
Middle school Student stuck and needs help

I have a middle school student who is having problems getting her pollution sensor to work when asked to. I have attached her document to this post. Can anyone help her fix the issue?

    int conductivitySensorValue; //initialize an integer variable to hold the sensor reading

    void setup() {
    Serial.begin(9600); //start serial communications so we can print the reading out

    }

    void loop() {
      conductivitySensorValue = analogRead(A0); //gat the integer representation of the sensor reading

      float voltage = conductivitySensorValue*(5.0/1023.0); //put the data in terms of our voltage (5 volts)

      Serial.println("The Conductivity is" + voltage); //print the current reading to the serial port
    }

    Arduino: 1.8.2 (Windows 7), Board: "Arduino/Genuino Uno"

    C:\Users\sushmit\Documents\Arduino\sketch_apr19a\sketch_apr19a.ino: In function 'void loop()':

    sketch_apr19a:13: error: invalid operands of types 'const char [20]' and 'float' to binary 'operator+'

       Serial.println("The Conductivity is" + voltage); //print the current reading to the serial port

                                              ^

    exit status 1
    invalid operands of types 'const char [20]' and 'float' to binary 'operator+'

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

End copy.......

body:
You can't add a string literal and a number together.

Instead you either have to convert one or both into a format that can be joined, or just treat them as separate entities. The simplest way is:

    Serial.print(F("The Conductivity Is: "));
    Serial.println(voltage).

Note the use of `F(...)` around the string literal - that forces it to stay in Flash so it doesn't waste RAM. Maybe not an issue with this project, but a good habit to get into nonetheless.


message:
SoftwareSerial response is semi-gibberish using ESP8266

I have a working SoftwareSerial connection to my ESP8266 module on my Arduino UNO board. However, the response I get from the ESP8266 using the SoftwareSerial library is semi-gibberish.

So I do get the correct response, but some characters are changed.
For example when I ask the IP of the module, it sometimes returns the right IP, but most of the times just alters the IP, for example 092.168/123.5.

So what am I doing wrong?

This is the code I'm currently using:

    #include <SoftwareSerial.h>

    SoftwareSerial esp8266(10, 11);

    void setup() {
      Serial.begin(115200);
      while (!Serial) {
        ; // wait for serial port to connect. Needed for native USB port only
      }

      Serial.println("Started");
    }

    void loop() {
      if (esp8266.available()) {
        Serial.println(esp8266.readStringUntil("\n"));
      }
      if (Serial.available()) {
        esp8266.write(Serial.read());
      }
    }

When I send the ```AT``` command, I sometimes get ```OK□``` or some other extra random characters.

So how do I make the SoftwareSerial show (or receive) the correct response?

body:
Try lowering your baudrate to 9600.

https://blogs.msdn.microsoft.com/abhinaba/2016/01/23/esp8266-wifi-with-arduino-uno-and-nano/


message:
How can I learn to use Generic ESP8266 boards Libraries in Arduino?

I am new to ESP8266. I am using the Arduino IDE to program the ESP8266-01 module. How can learn to make my own codes for ESP using Arduino?

I am going through the example programs and learning which part of the code does what. But, is there a better way to understand the syntax of those libraries.

Thanks!!

body:
They publish a reference page for the included libraries at each release of the ESP8266 core for Arduino. The latest at this time is here:

http://esp8266.github.io/Arduino/versions/2.3.0/doc/libraries.html

You can adjust that URL for the release version you're using.

The libraries try to follow the API of the standard Arduino libraries and that documentation mostly focuses on the differences. So you will also find some documentation for these libraries in Arduino's library reference pages:

https://www.arduino.cc/en/Reference/Libraries

and the reference pages for the Arduino core API:

https://www.arduino.cc/en/Reference/HomePage

Of course the definitive (albeit less beginner friendly) reference will always be the source code. There are two ways to quickly determine the location of the source code for a library:

**Option 1:**

1. Select the appropriate board from the **Tools > Board** menu. The Arduino IDE may select the library to be used based on which board is selected.
2. File > Examples > {library name} > pick any example
3. Sketch > Show Sketch Folder. This will open the {library name}/examples/{example name} folder. The source files for the library will be found in the library root folder, `src` folder, or `utilities` folder.

**Option 2:**

1. File > Preferences > Show verbose output during: > compilation (check) > OK
1. Write or open a sketch that includes the library.
2. Sketch > Compile/Verify
3. Wait for the compilation to finish.
4. Examine the contents of the black console window at the bottom of the Arduino IDE window. The path to any library used by the sketch will be found in that output.


message:
High power consumption of ATmega32u4 when connected to iOS device

Just wondering if I can get some help here.

I have a simple scheme of MIDI controller based on ATmega32u4:
https://electronics.stackexchange.com/questions/280994/atmega32u4-with-txled-and-rxled-as-output-pins-and-usb-functionality

And my team wants me to make this device Android/iOS compatible (because our Arduino prototypes worked fine with iPads and even iPhones).

I am experiencing a high power consumption of ATmega32u4 when connected to iOS devices. When we connect our device to iOS we get the following message:
[![The connected device requires too much power][1]][1]

Meanwhile, when I make almost the same scheme and run the identical sketch on ATmega328 chip it works just fine!

I tried running all the stuff on Arduino boards, and the result is stable:

 * works on Arduino Uno and Arduino Mega (based on ATmega328 chip);
 * doesn't work on Arduino Micro and some of its Chinese clones like Arduino Micro Pro (based on ATmega32u4).

We've found a small trick/workaround: connect even two our ATmega32u4 devices through an active USB hub with additional power supply to one iPad, and they both work perfectly, then we switch off the additional power on the hub, and devices continue to work fine using the power from this single iPad without any messages about high power consumption.
This case leads me to the thought that high consumption of ATmega32u4 chip appears only on the device initialisation stage.

Is there a way to solve this?

Thanks in advance.

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

body:
The major difference between ATmega32u4 and ATmega328 is that the former has USB functionality built in, while the latter requires an external USB to UART chip. When such UART chips go through enumeration, they will tell the host that they only consume 100 mA or less, because they have no idea what else you have on the board. ATmega32u4 however can potentially consume up to 200 mA (sinking 100 mA through each of the IO banks). Maybe it's requesting that current from the host when you connect it, and your phone refuses to power up a device requesting more than 100 mA of current.

You can connect your controller to a computer and check USB properties to confirm this.


message:
Arduino Due DAC pins with 0V

I know the DACs on the Arduino Due only allow for a range of output voltages from 1/6*Vdd to 5/6*Vdd (see [here][1]). This suits my needs, for the most part.

My question is if it is possible to have 0V on the DAC pins by, for example, switching the DACs of completely, or using them as normal digital out pins. I'd like to do this without the need for any external hardware or circuitry.

I googled for solutions but found none.

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

body: The DAC is port B15 and B16 so yes, it is possible to disable the DAC and use those pins as normal GPIO pins. Not sure how you would do it though, if the Arduino definitions have those pins set up for GPIO or not (away from my computer at the moment).


message:
SAMD21 Programming with Atmel ICE Fail to Write

I am trying to program my Adafruit M0 with the SAMD21G18 chip with Atmel studio and the Atmel ICE programmer. I have pin 1 on the ICE connected to 3.3V on the M0, pin 2 connected to SWDIO, pin 4 to SWDCLK, pin 10 to Reset, and pins 3, 5, and 9 to ground. This was all according to the ARM SWD connection section of the Atmel ICE manual. In Atmel Studio, I can read the device signature, but when I go to program the chip, I get the following error:

    Timestamp:     2017-04-20 22:03:32.563
    Severity:  ERROR
    ComponentId: 20100
    StatusCode:     131103
    ModuleName:     TCF command: Modules:writeToMemory failed.

    Failed to write segment at 0x0 to target for memorytype

I have searched the internet for hours, finding no solution to this problem.

body:
Whats is the fuse setting of `NVMCTRL_BOOTPROT`?

it should be:

`NVMCTRL_BOOTPROT = 0x07`

which will set your memory location to 0x00 (no bootloader).

`NVMCTRL_BOOTPROT` sets the amount of space to allocate for the bootloader in flash memory. Setting this fuse to 0x07 tells the chip you are not allocating space for a bootloader and the programmer will start to write at address 0x00, which is the beginning of flash memory. If you are programming with an Atmel ICE, you are not using a bootloader.

[![Boot Allocation and Program Space][1]][1]

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


message:
Converting a message received in char buffer to integer

I am receiving a message from my mobile to my microcontroller via GSM. The message is in a char buffer, but I want to convert it to an integer as I want to perform some mathematical operations on it. I tried many functions such as `atoi`, `toint` but it's not working. Please let me know if there is any way in which I could do this conversion.

body:
`atoi()` is the simplest way:

    int val = atoi(buf);

If that doesn't work then your buffer doesn't start with the number you are after. If that is the case you will have to work out where in the buffer the number is and convert just that portion. How you do that depends on what the format of the data is in your buffer.