message:
Read float and long from external EEPROM chip

I am using an Arduino to read information from an EEPROM chip over I2C with the code I found here:
https://playground.arduino.cc/Code/I2CEEPROM

It works great for *int* and *char* values but I also need to read *short*, *long*, and *float* values.

They are stored in this order:  1510543923
is stored as: 01011010 00001001 00010010 00110011

How can I read multiple bytes into a single variable of these types?

I tried the following but it gives me a 16 bit number:

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

    i2c_eeprom_read_buffer(0x50, 25, (byte *)bytes, 4);
    long j = (bytes[3] << 0) + (bytes[2] << 8) + (bytes[1] << 16) + (bytes[0] << 24);

body:
It gives you a 16-bit integer because the compiler automatically makes casts. In particular:

 - `byte << int` returns `int`
 - `int + int` returns `int`

So your `(bytes[1] << 16)` is converted to an `int`, and consequently gets zeroed.

I tried to simulate this code; the results are shown as comments

    int a = 0x1234;
    long b = a << 8;
    long c = a << 8L;
    long d = ((long)a) << 8;
    Serial.println(a); // a is 0x1234
    Serial.println(b); // b is 0x3400
    Serial.println(c); // c is 0x3400
    Serial.println(d); // d is 0x123400

Personally I'd bet that `int << long` would result in a `long`, but apparently I'm wrong.

In any case, you should write

    long j= (bytes[3] << 0) + (bytes[2] << 8) + (((unsigned long)bytes[1]) << 16) + (((unsigned long)bytes[0]) << 24);

This should fix your error. In any case, you can also simply write

    long write_value;
    i2c_eeprom_write_page(0x50, 25, (byte *)&write_value, sizeof(write_value));
    long read_value;
    i2c_eeprom_read_buffer(0x50, 25, (byte *)&read_value, sizeof(read_value));

Please note that accessing directly the pointers, like in this case, will respect the endianness of the compiler. In the case of a big endian implementation, the long with value `0x12345678` will be saved as `12 34 56 78`, while with a little endian implementation it will be saved as `78 56 34 12`. This is not a problem if you always use the same platform, but if you are trying to transfer information over a network you will have to ensure that all the devices have the same endianness or manually correct it


sender: user

sender: assistant

body:
>  1510543923 is stored as: 01011010 00001001 00010010 00110011

This is known as “big endian”, or “MSB first”, because the most
significant byte (MSB, here 01011010) comes first.

I recommend against this order. If you can, swap all the bytes and store
the value LSB first, i.e. with the least significant byte first, and the
most significant byte last. This will make your life easier since it's
the order used internally in the Arduino. If you can go little endian,
then you will be able to read the data straight into the required
variable, with no conversion needed, as in:

    i2c_eeprom_read_buffer(0x50, 25, (byte *) &j, sizeof j);

and it will work identically with any data type.

If you cannot choose the byte order (maybe you cannot control what is
inside the EEPROM), then you will have to reverse all the bytes. You can
do this either with bit shifts or by explicitly moving bytes.

> `bytes[1] << 16`

This will not work. Per the rules of the C++ language, `bytes[1]` is
implicitly promoted to `int` type before the shift, then it is shifted
as an `int`. But on your Arduino an `int` is 16-bits long, thus by
shifting it 16 positions you are dropping off _all_ of the bits.
Actually, this is even worse: you are invoking what is known as
_undefined behavior_, meaning that it is considered nonsense and the
compiler is free to interpret however it wants.

To do this properly, you first have to _explicitly_ cast `bytes[i]` to
`unsigned long`. It has to be unsigned because changing the sign bit on
a `long` by bit shifting is also undefined behavior. Thus, the proper
way of reconstructing the number via bit shifts is:

    long j = ((unsigned long) bytes[3] << 0)
           | ((unsigned long) bytes[2] << 8)
           | ((unsigned long) bytes[1] << 16)
           | ((unsigned long) bytes[0] << 24);

This is portable (it should also work on big-endian architectures) but
only works with integral types, not with floats.

For reconstructing a float, my preferred option would be to use a
`union`, in order to access the bytes of the variable explicitly. Then
you just have to copy the bytes from the buffer to the `union` in
reverse order:

    union { float f; byte b[4]; } data;
    data.b[0] = bytes[3];
    data.b[1] = bytes[2];
    data.b[2] = bytes[1];
    data.b[3] = bytes[0];
    float x = data.f;

One nice thing about this approach is that it works with any data type.


body:
Using [template functions][1] this could be written as:

    template<class T> void i2c_read(uint16_t addr, T& x)
    {
      i2c_eeprom_read_buffer(0x50, addr, &x, sizeof(T));
    }

    template<class T> void i2c_write(uint16_t addr, T& x)
    {
      i2c_eeprom_write_buffer(0x50, addr, &x, sizeof(T));
    }

These two functions take the data type as template parameter. Some examples:

      long x = 0x12345;
      i2c_write<long>(0, x);

      long y = 0;
      i2c_read<long>(0, y);

With `auto` the functions could be written as:

    void i2c_read(uint16_t addr, auto& x)
    {
      i2c_eeprom_read_buffer(0x50, addr, &x, sizeof(x));
    }

    void i2c_write(uint16_t addr, auto& x)
    {
      i2c_eeprom_write_buffer(0x50, addr, &x, sizeof(x));
    }

With `auto` the compiler will determine the data type.

Cheers!

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


message:
Add id to raw data in an array

I am working on an Arduino project, where I am transmitting GPS data between two Arduinos. This code can transmit the raw GPS data:

    int a = Serial1.available();
    if(a){
        uint8_t hej[a];
        for(int i=0; i<a; i++){
            hej[i] = Serial1.read();
        }

        rf95.send(hej, a);
    }

I need to be able to identify the device that's transmitting the data. This can be in form of an integer value. I have tried to add a value to the array, but that messes up the data when I receive it.
Is there a simple way to add an ID to the data I am transmitting?

body:
I would suggest:

1. Use a library (TinyGPS++ for example) to read the GPS data and extract just what you want.
2. Use a `struct` to craft a packet that you can send over bluetooth, or send the data as a textual representation, depending on your needs.

For a struct you can:

    struct packet {
        uint8_t id;
        float latitude;
        float longitude;
    };

    struct packet myPacket;
    myPacket.id = 32; // Unique ID
    myPacket.latitude = gps.getLatitude(); // Whatever function call here
    myPacket.longitude = gps.getLongitude(); // or whatever
    rf95.send((uint8_t *)&myPacket, sizeof(struct packet));


body:
Well, the main problem here is that you don't know when the string will enter from the serial port. For instance, let's see a sample communication:

    $GPGGA,154655,4328.1874,N,00340.5185,W,1,03,08.5,-00044.7,M,051.6,M,,*79
    $GPGSA,A,2,13,23,25,,,,,,,,,,08.5,08.5,00.9*0E
    $GPGSV,3,1,10,02,50,290,26,04,60,210,26,08,33,173,29,10,21,296,00*7E

Making a sample reading like this:

    int a = Serial1.available();
    if(a){
        uint8_t hej[a];
        for(int i=0; i<a; i++){
            hej[i] = Serial1.read();
        }

        Serial.print("Received \"");
        Serial.write(hej, a);
        Serial.println("\"");
    }

you will see something like

    Received "$GPG"
    Received "GA,1546"
    Received "5"
    Received "5,4"

or, most probably,

    Received "$"
    Received "G"
    Received "P"
    Received "G"
    Received "G"
    Received "A"

so it is difficult to detect where to insert your ID.

I have two solutions for you.

The simpler one is to use the fact that the GPS sends formatted sentences. According to the [NMEA specification][1], the message is at most 82 chars long and is terminated by a LF (0x10) char. This means that you can do something like this (I assume you want to use a 4-chars ID, and in this case the ID is `MYID`)

    #define ID_LENGHT 5 /* 4 chars and a separator */
    #define BUFFERSIZE ID_LENGHT+82 /* ID plus the max NMEA sentence*/
    byte recvBuffer[BUFFERSIZE];
    byte recvIdx;

    void setup()
    {
     // ... other initialization

     // Fill the ID at the beginning, and prepare to store data at the end of ID
     memcpy(recvBuffer, "MYID-", ID_LENGHT * sizeof(byte));
     recvIdx = ID_LENGHT;
    }

    void loop()
    {
     // ... other program

     while (Serial1.available())
     {
      byte ch = Serial1.read();
      if (recvIdx >= BUFFERSIZE)
       continue; // Should never arrive here, since the sentences are shorter
      recvBuffer[recvIdx++] = ch;
      if (ch == 0x10) // received LF, so end of sentence
      {
       // Send the buffer (plus the identifier)
       rf95.send(recvBuffer, recvIdx);
       // Reset the idx (and so you will overwrite previous buffer
       recvIdx = ID_LENGHT;
      }
     }

     // ... Other code
    }

This approach transfers a lot more thata then needed, since you want to only transfer the latitude and longitude. So the second (and best) approach in my opinion is to have a NMEA parser on the arduino that extracts the lat and long values you need and then sends a (formatted) message to the master, with ID, lat and long.

This is the best solution, but I don't have experience with NMEA parsers so you'd better try searching online for some library and, most important, have the necessary computational power and flash available to perform this computation

  [1]: https://en.wikipedia.org/wiki/NMEA_0183#Message_structure


body:
You could try [NeoGPS](https://github.com/SlashDevin).  NeoGPS is smaller, faster, more reliable and more accurate than all other GPS libraries.  It packages all the GPS fields into a structure for you:

    #define gpsPort Serial1

    struct msg_t {
      uint8_t ID;   // A node's ID
      gps_fix fix;  // The NeoGPS structure containing all configured GPS fields
    };

    msg_t msg = { THIS_NODE_ID };

    void loop()
    {
      if (gps.available( gpsPort )) {  // parses characters
        msg.fix = gps.read();          // gets the struct when it's ready (once per second)

        rf95.send( (uint8_t *) &msg, sizeof(msg) );  // send the msg struct
      }
    }

The receiving side will similarly read into the same struct, something like:

        rf95.receive( (uint8_t *) &msg, sizeof(msg) );
        if ((msg.id == ROVER_ID) && msg.fix.valid.location) {
          // Check lat/lon against target location
           ...

This will also coordinate the RF transmission with the [GPS quiet time](https://github.com/SlashDevin/NeoGPS/blob/master/extras/doc/Troubleshooting.md#quiet-time-interval), helping to avoid losing GPS characters while the RF transmission is busy.

The `gps_fix` structure can be quite small, depending on what GPS fields you enable in the NeoGPS [configuration](https://github.com/SlashDevin/NeoGPS/blob/master/extras/doc/Configurations.md) files.  This structure is 10x to 80x smaller than the raw NMEA data, so it is transmitted very quickly.  The default configuration uses only 31 bytes; most GPS devices send about 400 bytes per second.

If you'd like to try it, NeoGPS is available from the Arduino IDE Library Manager, under the menu **Sketch -> Include Library -> Manage Libraries**.  You should also read about [Choosing a Serial Port](https://github.com/SlashDevin/NeoGPS/blob/master/extras/doc/Installing.md#2-choose-a-serial-port) and the [Troubleshooting](https://github.com/SlashDevin/NeoGPS/blob/master/extras/doc/Troubleshooting.md) tips.


message:
Can I use a ThunderBorg is a dual motor controller on an Arduino UNO R3

I am new to Arduino and Electronics and am thinking of making a 6 wheel drive all terrain platform similar to the MonsterBorg pi, but I want to use an Arduino instead of a Raspberry pi  to control the motors. The motors I intend to use need to be powerfull.
Any advice on what would be shield or motor controllers I should use would be a great help.

body:
Hello,

You have many possibility for drive one or more motor.

 - Transistor(1 motor)
 - [L293D][1](2 motor backward and forward or 4 motor just forward)
 - [L298D ][2](like L293D but he support more Amp and Vol
 - [L293D Adafruit shield][3](4 motor)
 - ...

Here is an example for
[L293D][1]:

enable PWM(0-255), inputs digital(0-1).

Motor1 : Input1, Input2, Enable1,2

Motor2 : Input3, Input4, Enable3,4

    void motor1RotationDirection(int input1arg, int input2arg){
        digitaleWrite(input1, input1arg);//  LOW  |  HIGH
        digitaleWrite(input2, input2arg);//  HIGH |  LOW
                                         //Forward|Backward
    }

    void motor1speedRotation(int speed){
        analogWrite(enableMotor1, speed);
    }    //for motor2 is the same.

  [1]: https://www.engineersgarage.com/sites/default/files/L293D_1.jpg
  [2]: http://www.fixmasterelectronics.com.ph/wp-content/uploads/2016/06/L298-2-Channel-Motor-Driver.png
  [3]: https://playground.arduino.cc/uploads/Main/adafruit-motorshield2.jpg


message:
: Failed to open /dev/ttyACM0 (port busy)

I am trying to work with the (new) sparkfun razor IMU 9dof, I wrote a silple sktetch to calibrate the magnetometer:

    #include <SparkFunMPU9250-DMP.h> // Include SparkFun MPU-9250-DMP library
    #include <Wire.h> // Depending on your Arduino version, you may need to include Wire.h
    MPU9250_DMP imu; // Create an instance of the MPU9250_DMP clas
    void setup() {
      Serial.begin(115200);

      Serial.println(F("Adafruit 10 DOF Board AHRS Calibration Example")); Serial.println("");

      if (imu.begin() != INV_SUCCESS){
        while (1) {
        Serial.println("Failed to initialize MPU-9250, loop forever");
       }

      }

     imu.setGyroFSR(2000); // Set gyro to 2000 dps

     imu.setAccelFSR(2); // Set accel to +/-2g

     imu.setLPF(5); // Set LPF corner frequency to 5Hz

     imu.setSampleRate(100); // Set sample rate to 10Hz

    imu.setCompassSampleRate(100); // Set mag rate to 10Hz
    }

    void loop(void){
      imu.update();

      // Print the sensor data
      Serial.print("Raw:");
      Serial.print(imu.ax);
      Serial.print(',');
      Serial.print(imu.ay);
      Serial.print(',');
      Serial.print(imu.az);
      Serial.print(',');
      Serial.print(imu.gx);
      Serial.print(',');
      Serial.print(imu.gy);
      Serial.print(',');
      Serial.print(imu.gz);
      Serial.print(',');
      Serial.print(imu.mx);
      Serial.print(',');
      Serial.print(imu.my);
      Serial.print(',');
      Serial.print(imu.mz);
      Serial.println();

      delay(50);
    }

To be sure the Arduino IDE can access to dev/ttcACM0, I did   sudo chmod 666 /dev/ttyACM0

I can dowload successfully but when I want to open the terminal I got the following error:

Erreur d'ouverture du port série « /dev/ttyACM0 ». (Port busy) (see attached screenshot)

More over when I entered dmesg on the console, I can see the following messages:

    [   94.133923] usb 3-2: USB disconnect, device number 2
    [   94.133978] cdc_acm 3-2:1.1: urb 12 failed submission with -19
    [   94.135862] cdc_acm 3-2:1.1: urb 13 failed submission with -19
    [   94.136059] cdc_acm 3-2:1.1: urb 14 failed submission with -19
    [   94.136257] cdc_acm 3-2:1.1: urb 15 failed submission with -19
    [   94.136457] cdc_acm 3-2:1.1: urb 2 failed submission with -19
    [   94.136656] cdc_acm 3-2:1.1: urb 3 failed submission with -19
    [   94.136852] cdc_acm 3-2:1.1: urb 5 failed submission with -19
    [   94.137048] cdc_acm 3-2:1.1: urb 6 failed submission with -19
    [   94.138841] xhci_hcd 0000:03:00.0: WARN Cannot submit Set TR Deq Ptr
    [   94.138843] xhci_hcd 0000:03:00.0: A Set TR Deq Ptr command is pending.
    [   94.931853] usb 3-2: new full-speed USB device number 3 using xhci_hcd
    [   95.316578] usb 3-2: New USB device found, idVendor=1b4f, idProduct=9d0f
    [   95.316581] usb 3-2: New USB device strings: Mfr=1, Product=2, SerialNumber=3
    [   95.316582] usb 3-2: Product: SFE 9DOF-D21
    [   95.316584] usb 3-2: Manufacturer: SparkFun
    [   95.320306] cdc_acm 3-2:1.0: ttyACM0: USB ACM device
    [  858.774849] usb 3-2: USB disconnect, device number 3
    [  904.529058] TCP: wlp1s0: Driver has suspect GRO implementation, TCP performance may be compromised.

Does anyone outhere experienced such issue?

Thank you for your help

Fabrice

body:
`sudo apt-get purge modemmanager`
It helps me for linux user and for many other peoples.
Now I am playing with stm32f103 and opening port was painfull.
That  was problem only for stm32 chip. Arduino nano was working without problems.
Before I need reopened few times port to initiate communication.
That was painfull. After finding that solution now Arduino ID is working without problems.
 I am not sure if deleting modemmanager will have impact for my system.


body:
I solved following serial port related problems in ubuntu 18.04 as follows:

**Problem 1 :  Cannot open /dev/ttyACM0: Permission denied**
Solution  :  Grant permissions to read/write to the serial port with this terminal command --->  `sudo chmod a+rw /dev/ttyACM0`
Here replace tty port with your respective ubuntu port.

**Problem 2 : Failed to open /dev/ttyACM0 (port busy)**
Solution  : This problem appears when serial port is busy or already occupied. So kill the busy serial port with command ---> `fuser -k /dev/ttyACM0`. Here replace tty port with your respective ubuntu port.

**Problem 3 : Board at /dev/ttyACM0 is not available**
Solution : In this case, your serial port in tools menu will be greyed out. I googled a lot for this, but  none of  solution worked for me. Atlast I tried different arduino board and usb connector and it was working for me. So, if you are having old arduino board (can be solved using required drivers) or defected arduino board then only this problem arises.


body: When I had this problem I discovered that running `ps x` showed a lot of tasks involving temporary mount files. So I closed Arduino, ran `sudo rm -rf /tmp/.mount_arduin*` and restarted Arduino. The device attached successfully.


body:
You need to be part of the dial out group. Try this:
Type 'groups', is 'dialout' there ?
sudo usermod -a -G tty yourUserName
Example sudo usermod -a -G tty gil

Log off and log on again for the changes to take effect.
This has consistently worked for me and is now in some of the Arduino install packages.


message:
Which input pins can I use on the ESP8266 NodeMCU

On the ESP8266 NodeMCU I have GPIO2 , GPIO3 , GPIO1 , GPIO9 free but when I assign them to a button they do not work. I assume it is because those pins have other function behind them. When I look at the schematic I found that they are TXD1, RXD0, TXD0, and SSD2. Is there a way to still use these pins as inputs?

If not, can I use an Arduino Uno for my inputs and send signals from there to the analog pin to my ESP8266 NodeMCU for the connection to the MQTT server?

For the record all my other pins are used so I can't use any other input pin than these 4.

body: GPIO2 is NodeMCU D4 which is U1TXD, transmit for the second UART, generally available. GPIO3 is NodeMCU U0RXD, receive for the first UART, generally available if you aren't using serial. GPIO1 is NodeMCU U0TXD, transmit for the first UART, generally available if you aren't using serial. GPIO9 is NodeMCU SPIHD and is NOT available, as it is required for the flash memory. All that is well documented in many places. You can easily use serial to move data between modules, or multiplex your input to the one module. Cannot provide much insight without more details.


message:
Trying to read from AD5934 using Arduino on I2C

I'm trying to read a block of bytes from an AD5934 Impedance converter ([PDF][1]) using I2C.

This is my code so far

Preamble:

    #define AD5934_Address                    0xD
    #define AD5934_Start_Frequency            0x82
    #define AD5934_Block_Read                 0b10100001
    #define AD5934_Address_Pointer            0b10110000

Loop:

    void loop() {
      readAD5934(AD5934_Start_Frequency, test, 3);
    }

Read Function:

    byte readAD5934 (int address, long int  data, int len) {
      byte err = 0, counter;

      if (len > 32)
        return 0xFF;

      else if (len > 1) {
        // Part ONE
        Wire.beginTransmission(AD5934_Address);
        Wire.write((byte) AD5934_Address_Pointer);
        Wire.write((byte) address);

        err = Wire.endTransmission();

        // Part TWO
        Wire.beginTransmission(AD5934_Address);
        Wire.write((byte) AD5934_Block_Read);
        Wire.write(len);

        // Part THREE
        Wire.requestFrom(AD5934_Address, len);
        StartHigh = Wire.read();
        StartMed = Wire.read();
        StartLow = Wire.read();
        err = Wire.endTransmission();
      }
    return err;
    }

For some reason, the Arduino tries to read the three bytes before Part TWO is executed.

I'm aware that I'm ending the I2C transmission after the requestFrom. The datasheet for AD5934 describes how to read a block of bytes on page 26. It does not show a STOP CONDITION before the end.

The oscilloscope shows

START 0001101 WRITE ACK 10110000 ACK 10000010 ACK STOP **START 0001101 READ ACK 00000001 ACK 11000111 ACK 11111111 NACK STOP** START 0001101 WRITE ACK 10100001 ACK 00000011 ACK STOP

Short:
S 0x0D W A 0xB0 A 0x82 A P **S 0x0D R A 0x01 0xC7 0xFF NA P** S 0x0D W A 0xA1 A 0x03 A P

The highlighted part (requestFrom and three Wire.read()) should be at the end.

I've spent a long time trying to figure this out, any help would be very much appreciated.

PS. Working on a Sparkfun Pro Micro 5V

  [1]: https://www.google.co.uk/url?sa=t&rct=j&q=&esrc=s&source=web&cd=1&cad=rja&uact=8&ved=0ahUKEwjTneXr5fXXAhXIPxoKHVZdBqAQFggpMAA&url=http://www.analog.com/media/en/technical-documentation/data-sheets/AD5934.pdf&usg=AOvVaw0oxbzNHLdCt3tEmvhQ1jaS

body:
I think you should re-see [AD5934x datasheet][1].

To read data from AD5934, we have three ways:

- read single byte
- read block
- using pointer command

-------------------------------------------------------
If you want to read multi byte, you can refer to my way:

    unsigned long GetRegisterValue(unsigned char regAddr, unsigned char len)
    {
        unsigned long regValue = 0;
        unsigned char index;
        unsigned char wrData[2] = {0,0};
        unsigned char rdData[2] = {0,0};

        for (index = 0; index < len; index++)
        {
            wrData[0] = 0xB0; //assign pointer cmd
            wrData[1] = regAddr + index;
            I2C_Write(AD5934_ADDR, wrData, 2);
            rdData[0] = 0xff;
            I2C_Read(AD5934_ADDR, rdData, 1);
            regValue <<= 8;
            regValue += rdData[0];
        }

        return regValue;
    }

  [1]: http://www.analog.com/media/en/technical-documentation/data-sheets/AD5934.pdf


message:
Receiving hex data from terminal

I am trying to transmit serial data from terminal to Arduino and I want to reconfirm that its the same data. But I am not able to get the right answer. I want data to be HEX. I want to check only the third last and last bytes since they will be changing every time.

I tried to write it in 2 different ways but none worked.

First try:

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

    byte thisByte[]={0xAA, 0xBB, 0x06, 0x00, 0x00, 0x00, 0x01, 0x01, 0x03, 0x03};
    void setup()
    {
      // start serial port at 9600 bps:
      Serial.begin(9600);
    }

    void loop()
    {
      while (Serial.available())
      {
        delay(250);
        // get the new byte:
        byte thisByte = Serial.read();
        // add it to the inputString:
        //inputString += char(intChar);

        if(thisByte == 0x03 || thisByte == 0x03)
        {
          Serial.print(thisByte, 'Hello');
          //digitalWrite(13, HIGH);   // turn the LED on (HIGH is the voltage level)
          delay(50);             // wait for a second
          Serial.print(thisByte, 'Nothing');
          //digitalWrite(13, LOW);    // turn the LED off by making the voltage LOW
        }
        Serial.print(thisByte,HEX);
        Serial.print(" | ");
      }
    }

Second try:

    const byte message[]={0xAA, 0xBB, 0x06, 0x00, 0x00, 0x00, 0x01, 0x01, 0x03, 0x03};
    boolean found = false;

    byte byte1 = 0xAA;
    byte byte2 = 0xBB;
    byte byte3 = 0x06;
    byte byte4 = 0x00;
    byte byte5 = 0x00;
    byte byte6 = 0x00;
    byte byte7 = 0x01;
    byte byte8 = 0x01;
    byte byte9 = 0x03;
    byte byte10 = 0x03;

    const byte Hallo;
    //void rules();
    void setup() {
      // put your setup code here, to run once:
      Serial.begin(9600);
    }

    void loop() {
      // put your main code here, to run repeatedly:
      // put your main code here, to run repeatedly:
      //int hexIn = Serial.read();
      //Serial.write(message,2);
      //Serial.write(message,sizeof(message));
      //delay(500000);
      while(Serial.available())
      {
        delay(10);  //small delay to allow input buffer to fill
        byte c = Serial.read();
        byte message = c;

        //Serial.print(c,HEX);
        //Serial.print(" | ");

        //if (c =!byte 0xAA && c =!byte 1 0xAA && c =!byte 0xAA && c =!byte 0xAA && c =!byte 0xAA && c =!byte 0xAA && c =!byte 0xAA && c =!byte 0xAA);

        if (c == message);
        //Serial.print("I received: ");
        Serial.println(c);

        // byte c = Serial.read();  //gets one byte from serial buffer
        // readmessage += c;
      } //makes the string readString
      //Serial.print(messsage);
      //readString=""; //clears variable for new input
    }

body:
First, you have to understand what “hex” means. Basically, you are
representing binary data as _text_, where each byte is represented as
two characters. For example, the number 42 is represented as either “2A”
or “2a”. In C and C++, you can write this number as `0x2a`, but I assume
your serial stream sends the raw hex data, without the “0x” prefix.
Thus, on the serial stream you may receive the character “2” (character
code 0x32 = 50 in decimal) followed, some time later, by “a” (charcode
0x61 = 97).

What you need is a conversion routine that takes these characters and
reconstructs the binary data out of them. Here is one such routine I
use. You have to provide it with an input string `in` and an output
array `out` large enough to store the resulting binary data. The
function will return the number of bytes filled in `*size`:

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

    /*
     * Convert an hex string to binary. Spaces are allowed between bytes.
     * The output array is supposed to be large enough.
     * On return, *size is the size of the byte array.
     */
    static void hex2bin(uint8_t *out, const char *in, size_t *size)
    {
        size_t sz = 0;
        while (*in) {
            while (*in == ' ') in++;  // skip spaces
            if (!*in) break;
            uint8_t c = *in>='a' ? *in-'a'+10 : *in>='A' ? *in-'A'+10 : *in-'0';
            in++;
            c <<= 4;
            if (!*in) break;
            c |= *in>='a' ? *in-'a'+10 : *in>='A' ? *in-'A'+10 : *in-'0';
            in++;
            *out++ = c;
            sz++;
        }
        *size = sz;
    }

As a mere convenience, the function above accepts spaces within the
string, but only between bytes. Notice however that it does not attempt
to do any error checking. You may want to improve it in this respect.

Next, you have to devise a way to frame your messages on the serial
line. Serial does not provide any framing per se: it only transmits byte
one by one. When dealing with text, a common scheme is to send a
carriage return (`\r`) to indicate the end of a message. With this
convention, you sketch has to buffer the bytes it receives until it
sees a carriage return. Then it can process the whole message as a
whole. This approach is nicely explained in the blog post [Reading
Serial on the
Arduino](https://hackingmajenkoblog.wordpress.com/2016/02/01/reading-serial-on-the-arduino/),
by Majenko, a regular contributor to this site.

Here is an example that reads an hex string, converts it to binary, and
then sends it back as hex again:

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

    void loop()
    {
        static char buffer[1024];
        static size_t length = 0;

        if (Serial.available()) {
            char c = Serial.read();

            // On carriage return, process the received data.
            if (c == '\r') {
                Serial.println();  // echo

                // Properly terminate the string.
                buffer[length] = '\0';

                // Convert the hex data to a byte array.
                size_t byte_count = length/2;
                uint8_t data[byte_count];
                hex2bin(data, buffer, &byte_count);

                // Echo back the byte array in hex.
                for (size_t i = 0; i < byte_count; i++) {
                    Serial.print(data[i], HEX);
                    Serial.print(" ");
                }
                Serial.println();

                // Reset the buffer for next line.
                length = 0;
            }

            // Otherwise buffer the incoming byte.
            else if (length < sizeof buffer - 1) {
                Serial.write(c);  // echo
                buffer[length++] = c;
            }
        }
    }

Notice the lines with the comment “echo”: they are meant to help you see
in the terminal what you are typing. You can remove them if you do not
what the Arduino to echo your typing. I tested it by sending

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

    AA bb06 000000 0101 03 03

and it replied

    AA BB 6 0 0 0 1 1 3 3


message:
How to Time the Arduino using RTC that I can operate the valves at 7am, 12pm, and 4 am?

The idea of this project is to open 3 valves one after the other for 5 minutes each, at a time like like 7am, 12pm, 4pm in a day.
The for loop should be executed at 7am, where valve 1 is open and water is pumped for 5 minutes, then valve 1 closes and valve 2 runs for 5 minutes, then valve 3 opens and runs for 5 minutes.
The program comes to a stop. Now at 12pm, the same cycle, or process repeats for the 3 valves.
The question is how do I Time the Arduino using the RTC that I can operate the valves at 7am, 12pm, and 4am?

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

    #include <SoftwareSerial.h>

    #include <DS3231.h>

    // intialise Valves for Each Vegetation Bed

    int valvePorts[] = { 4,5,6};

    int valveCount= 3;

    DS3231  rtc(SDA, SCL);

    Time t;
    const int OnHourOne = 12;   // assuming that one Tank- valve takes 5minutes each

    const int OnMinOne = 00;

    const int OffHourOne = 12;

    const int OffMinOne = 30;

    const int OnHourTwo = 16;

    const int OnMinTwo = 00;

    const int OffHourTwo = 16;

    const int OffMinTwo = 30;

    void setup()

    {

     for( int thisvalve=0; thisvalve<=valveCount; thisvalve++)

    {

     pinMode(valvePorts[thisvalve], OUTPUT);

    }

    pinMode(Waterpump,OUTPUT);             // Waterpump

      Serial.begin(9600);
    }

    void loop()

    {

       t = rtc.getTime();

      Serial.print(t.hour);

      Serial.print(" hour(s), ");

      Serial.print(t.min);

      Serial.print(" minute(s)");

      Serial.println(" ");

      delay (1000);

       if(t.hour == OnHour && t.min == OnMin)

    {

         Startwatering(1);

        }

        else if(t.hour == OffHour && t.min == OffMin)
    {
          Startwatering(0);

        }

    void Startwatering(int id)

     {

             if( id== 0)
                      {

                        return;

                      }

         //while(valvePorts[thisvalve],HIGH)

          if(id==1)

         {

       for( int thisvalve=0; thisvalve <=valveCount; thisvalve++)

    pinMode(valvePorts[thisvalve], OUTPUT);

       {

      digitalWrite(Waterpump,LOW);

     delay(5000)

      } // close for loop

         }// close if loop

     } // close for loop

body:
Many ways of doing it.

1. Poll the rtc constantly until the set time is reached. Then operate the valves. Or

2. Set an alarm on the rtc for the next time to operate the valves. The rtc will interrupt the mcu when the time is up. The mcu can then operate the valves.

You don't have to use an rtc for this.


message:
Connecting my Arduino with Bluetooth

What I want to do is to create a temperature measurement bracelet that you wear on your wrist.
So it takes data from the sensors and sends them to the PC.
What I am using to do that:

 - an Arduino Uno
 - a temperature sensor
 - a Bluetooth module to connect with Arduino Uno
 - a mobile phone
 - a PC

I will connect Arduino Uno with the Bluetooth module so it sends data to the mobile for example.
Since I am a beginner I do not have it very clear. Do I need a GPRS SIM (SIM900A for example or whatever) for this to function or just the Bluetooth connection is enough?

Specify that the question is very basic because I am a beginner.

body: Assuming the mobile device to which you are connected by bluetooth is always kept near the bracelet, you don't need a GPRS module. The mobile device, then, would use it's network connection (either GPRS, LTE, WiFi, etc.) to communicate the data to the PC for processing or storage.


body: You should only need the Bluetooth module, not a Sim card.  The HC-05 and HC-06 are Bluetooth modules that are commonly used with Arduinos, are relatively inexpensive, are fairly small, and there's quite a bit of documentation out there on how to use them.


message:
How to fix the Break Beam Sensor programming issue that says "USB Device Disabled"?

I am trying to use the [Adafruit Metro Mini][1] as Arduino (can be used the same way) to program an [IR Break Beam sensor][2] and a stepper motor. I connected the beam sensor to the breadboard and plugged the Arduino into my computer. But  my MAC pops up with the notification:

> "USB Device Disabled - Unplug the device using too much power to
> re-enable USB Devices."

What is the problem causing the issue? Did I short circuit something? I attached photos to my circuit to the post.

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

Thanks so much in advance.

  [1]: https://www.adafruit.com/product/2590
  [2]: https://learn.adafruit.com/ir-breakbeam-sensors
  [3]: https://i.stack.imgur.com/GxbPf.jpg
  [4]: https://i.stack.imgur.com/XOPTi.jpg

body:
The stepper motor driver is installed with the error (shifted) to the breadboard.

The electrolytic capacitor at the output of the voltage stabilizer in reverse polarity.

Power to  Adafruit Metro Mini is put in inverse polarity ...


message:
ESP8266 cannot connect to an existing network after using AT command

I followed [this tutorial][1] to connect the ESP8266 to a wifi network using AT commands. I used the below schematics (without the connection between ESP's CPIO 0 and Arduino's Ground):

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

After that, I was able to follow through the tutorial and got this response in the Serial Monitor:

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

That means my ESP8266 has successfully connected to my Wifi named W3. However, I decided to switch the mode of my ESP8266 from Network Device (mode 1) to Both network device AND Access Point (mode 3) (at this point I called AT+CWJAP? and can still see that it's connected to W3 wifi). I then was able to see the ESP wifi in my wifi list as (AI-THINKER_4C8CF2) but when I connected to it, I cannot connect to the internet. I'm wondering what the problem is and would appreciate any help.

*Note:* **The reason why I switched to mode 3 is because I want to control an Arduino Pro Mini (instead of Arduino Pro) using NodeJS.** I followed [another tutorial][4] and I figured that I need to connect to an ESP8266 access point.

I uploaded the StandardFirmataSketchPlus to my Arduino Pro Mini, with the baud rate set to 115200 (which is the same baud rate with my ESP8266). The schematic I used is similar to the one below, except I used a 3.3V Pro Mini and a Lipo battery, instead of a 5V:

[![enter image description here][5]][5]

The nodejs code is below:

    var VirtualSerialPort = require('udp-serial').SerialPort;
    var firmata = require('firmata');
    var five = require("johnny-five");
    var sp = new VirtualSerialPort({
      host: '192.168.1.243' //I got this number from the AT command (STAIP above)
     });

    var io = new firmata.Board(sp);

    io.once('ready', function(){
        io.isReady = true;

        var board = new five.Board({io: io, repl: true});

        board.on('ready', function(){
            var led = new five.Led(12);
            led.blink(3000);
        });
    });

This code is to test the connection between Arduino and Nodejs and when I run this file, it doesn't work.

  [1]: https://www.agcross.com/2015/09/the-esp8266-wifi-chip-part-2-connecting-to-a-network/
  [2]: https://i.stack.imgur.com/nD18w.png
  [3]: https://i.stack.imgur.com/40WaU.png
  [4]: https://medium.com/@imkiran/connecting-johnny-five-arduino-raspberry-pi-etc-over-wifi-to-the-pc-using-esp8266-a10348fdb300
  [5]: https://i.stack.imgur.com/BxKjQ.jpg

body:
you have Firmata in Atmega, AT firmware in ESP and the 'blink led' js on computer.

you did not follow [the tutorial][1] properly. it requires [jonny-five firmware][2] in esp8266

  [1]: https://medium.com/@imkiran/connecting-johnny-five-arduino-raspberry-pi-etc-over-wifi-to-the-pc-using-esp8266-a10348fdb300
  [2]: https://github.com/anaganisk/johnny-five-esp8266.git


message:
Which voltage should I use with a component that allows between 3v and 5.5v?

I have a DS18B20 temperature sensor that needs between 3v and 5.5v to work, as seen in its documentation.

What's the difference? Should it work better which 5.5v?

I know that a LED with more voltage will bright more but it will burn or a pump with more voltage will take water faster.  But what about the temperature sensor?

![DS18B20 temperature sensor](https://i.stack.imgur.com/tfjK3.jpg)

body:
<p>It's the same thing for a measurement module. You can use the 5V of the arduino, but with a resistance of 4.7KΩ between "Data" and "5V".<p> Like this example [![enter image description here][1]][1]

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


body:
According to the datasheet the absolute maximum is -0.5 V to 6.0 V.

The normal voltage for which it works according to the specifications in the datasheet is 3.0 V to 5.5 V.

That means het DS18B20 works well with 3.3 V and just as well with 5.0 V. One voltage is not "better" than the other. There is not difference. You can use it with a 3.3 V Arduino board and with a 5 V Arduino board.

The power it uses when being active is 1 mA * 5.0 V = 5 mW. It is possible that it causes some self-heating. But let's not go there. That is something for nerds.


body:
When a sensor like this allows a range of power supply voltages it's not because one voltage is "better" than another. It's purely to allow it to work with a wider range of controllers.

The voltage you would use it with is more dictated by what it is you are using it with. If you are using it with a 5V microcontroller, such as the Arduino Uno then you would run the sensor at 5V, since that is the logic levels your MCU will be working at.  If you are using it with a 3.3V microcontroller, such as a Teensy, Due, or chipKIT board, then you would run the sensor at 3.3V to maintain the right logic levels for the board you are using.

By running both the MCU and the sensor at the same voltage you remove the need for any logic level translation between the two.


message:
Difference between ISR and other functions in AVR twi library

I was studying the ISR for twi and I want to know how is it working.

I have two questions about the code handling for ISR and the other functions and what they do exactly:

1. My first question is about how ISR for twi is working? The following example shows a piece of the ISR for twi library. My concern here is how switch statement is working?

And probably I have to understand how TWSR works; for example, I think when twi module sends or receive an address, the TWSR is updated according to TWSR Status codes. But I really don't understand exactly what is happening?! Which happens first?

The programmer issue the twi operation; like, sending a start address. Then, the TWSR is updated with the code 0x08 which means according to the datasheet "A START condition has been transmitted". If that so, then why in the following ISR code. The status code is called as a switch result for twi operation, then it issue an action based on that??!! that what is confusing to me!
So, is the procedure of twi:
1. Send start address.
2. TWSR is updated with 0x08 as a confirmation for the start action.
3. Here the ISR issues another action based on the TWSR again? This is what I didn't understand.

    ISR(TWI_vect)
    {
      switch(TW_STATUS){
        // All Master
        case TW_START:     // sent start condition
        case TW_REP_START: // sent repeated start condition
          // copy device address and r/w bit to output register and ack
          TWDR = twi_slarw;
          twi_reply(1);
          break;

2. My second question is about the relationship between ISR and other functions. For example,

          if (true == twi_inRepStart) {
        twi_inRepStart = false;
        do {
          TWDR = twi_slarw;
        } while(TWCR & _BV(TWWC));
        TWCR = _BV(TWINT) | _BV(TWEA) | _BV(TWEN) | _BV(TWIE);
        }
        else
        TWCR = _BV(TWINT) | _BV(TWEA) | _BV(TWEN) | _BV(TWIE) | _BV(TWSTA);
        while(wait && (TWI_MTX == twi_state)){
        continue;
        }

Here is another start send address operation. So which one is the real one? The start send in the ISR or this one?

body:
The confusing thing is that there is only one interrupt, and it is called for a number of different reasons.

To make sense of why it's being called you also have to know what you have just done in order to know what to expect. In this case we have just sent a START bit, so we set the current status to "start sent". When the interrupt fires we know that it must be in response to the start bit we sent earlier having been completed, so it's time to then send the address.  It's just implementing a simple state machine.

To answer your second question: both are "real" and used.

When sending data to a slave it can be easily implemented with a non-blocking interrupt arrangement. This makes it fast and efficient, and you can get on with doing other things while the data is being sent. That uses the ISR.

When reading from a slave it's harder to implement it with an ISR and still fit into the Arduino ethos of "data is available immediately", so when using `requestFrom` a simpler blocking routine is called that doesn't use the ISR. This means that when the function is completed all the data has been received and you can get on with reading it from the buffer. If you used the ISR instead then data wouldn't have arrived until some unknown time after you have made the request - so you would have to implement either some kind of callback system to execute a user function when the data has arrived, or manually block waiting for the data to arrive polling a status set by the ISR, which is pretty pointless anyway. So it's just been implemented as a simple blocking routine.

It's crude, but like much of the Arduino API it "gets the job done with the minimum of fuss" - sacrificing efficiency for simplicity and ease of use.

----

To break it down for you further:

1. When using `Wire.beginTransmission(...)` the ISR is used to empty the buffer onto the physical wires. Your sketch can continue while that is happening.
2. When using `Wire.requestFrom(...)` the ISR is *not* used. Your sketch cannot continue until the whole buffer has been received (or it times out).

When using `Wire.beginTransmission(...)` you first fill the buffer (32 bytes maximum) with your data to send. Calling `Wire.endTransmission(...)` then starts the sending of the data from the buffer using the ISR.

When you use `Wire.requestFrom(...)` a call to the `Wire.beginTransmission(...)` and `Wire.endTransmission(...)` functions are called to send the address. This uses the ISR.  Following that the `twi_readFrom(...)` function is called to receive the data in a blocking fashion. That first blocks itself waiting for the ISR to signal that the I2C bus is available and it has finished sending the address. The `twi_readFrom(...)` function then, if it's using *repeated start*, sends the start bit again. If it's not using *repeated start* then it just gets on with the task of reading the data into the buffer.  The actual reception of the data triggers an interrupt which copies the data into the incoming RX buffer from the FIFO, but that's pretty much all the interrupt does when receiving.

Much of the confusion (and it's confusing even to me) comes because the Wire library is written in two layers - an Arduino API wrapper class which implements the Wire object that you are familiar with, and a pure C set of helper functions which most likely were ported over from some other Atmel application library originally. This makes it quite hard to follow what is going on, since the two programming styles and ways of working are very different. Following the thought processes of two different parties working in different ways with different goals in mind is tricky at best.

To better understand how it all fits together you want to sit down with a couple of example transactions (both read and write) and a copy of the datasheet and trace exactly how the program would flow and respond to the different events and sequences within those transactions. Have the transaction waveforms on paper in front of you and mark on them where the different interrupts trigger. Follow that through in the code and work out what exactly gets called when and why it gets called. Quite an arduous task, but essential if you want to fully understand exactly what is going on in the code.


body:
ISRs are triggered by status (more precisely status changes). For example, once the device address is sent, the hardware will set a flag, which will be serviced by the isr; if the data is sent, the hardware will set another flag, triggering the isr....

It is through this process that the transmission is carried out in an orderly fashion, without tying up the mcu.

For a more detailed description of how avr i2c modules work, check out datasheet for older lpc/nxp mcus.

The other approach is for the mcu to poll the hardware and process the flags accordingly.

Hope it helps.


message:
Multiple devices on SPI

Whenever I use multiple devices on SPI, [TFT Screen][1], and the BME280 breakout board from Adafruit, the Arduino fails to detect the devices.

Code of the screen separately (works)

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

    // include the necessary libraries
    #include <SPI.h>
    #include <SD.h>
    #include <TFT.h>  // Arduino LCD library

    // pin definitions
    #define sd_cs  7
    #define lcd_cs 10
    #define dc     9
    #define rst    8

    // Define screen pins
    TFT TFTscreen = TFT(lcd_cs, dc, rst);

    //Define variables
    char sensorPrintout[4];
    char sensorPrintout2[4];

    // this variable represents the image to be drawn on screen
    PImage logo;

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

      Serial.print("Initializing SD card...");
      if (!SD.begin(sd_cs)) {
        Serial.println("failed!");
        return;
      } else {
        Serial.println("OK!");
      }

      // Start and clear TFT screen
      TFTscreen.begin();
      TFTscreen.background(0, 0, 0);

      // Lookup image on TFT screen
      logo = TFTscreen.loadImage("Logo.bmp");
      if (!logo.isValid()) {
        Serial.println("error while loading Logo.bmp");
      }
      if (logo.isValid() == false) {
        return;
      }

      //Draw logo on the screen
      Serial.println("drawing image");
      TFTscreen.image(logo, 0, 0);

      // Change textcolor to white
      TFTscreen.stroke(255,255,255);

      //Write some text
      TFTscreen.setCursor(0,25);
      TFTscreen.print("Schuif 1: ");
      TFTscreen.setCursor(75,25);
      TFTscreen.print((char)247);
      TFTscreen.print("C");

      //Write some text
      TFTscreen.setCursor(0,50);
      TFTscreen.print("Schuif 2: ");
      TFTscreen.setCursor(75,50);
      TFTscreen.print((char)247);
      TFTscreen.print("C");
    }

    void loop() {
      // Read value of A0
      int value = analogRead(A0);
      Serial.println(value);
      float voltage = value * (5.0/1023.0);
      Serial.println(voltage);
      String sensorVal = String(analogRead(A0));
      String sensorVal2 = String(voltage);

      // Change sensor value to a character array
      sensorVal.toCharArray(sensorPrintout, 4);
      sensorVal2.toCharArray(sensorPrintout2, 4);

      // Change text color to white
      TFTscreen.stroke(255,255,255);

      // Write value of sensor 1
      TFTscreen.setCursor(55,25);
      TFTscreen.print(sensorPrintout);

      // Write value of sensor 2
      TFTscreen.setCursor(55,50);
      TFTscreen.print(sensorPrintout2);

      // wait  500ms
      delay(1000);

      // Change text color to black
      TFTscreen.stroke(0,0,0);

      // Write value of sensor 1
      TFTscreen.setCursor(55,25);
      TFTscreen.print(sensorPrintout);

      // Write value of sensor 2
      TFTscreen.setCursor(55,50);
      TFTscreen.print(sensorPrintout2);
    }

Code of the BME280 separately (works)

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

    #include <Wire.h>
    #include <SPI.h>
    #include <Adafruit_Sensor.h>
    #include <Adafruit_BME280.h>

    #define BME_SCK 13
    #define BME_MISO 12
    #define BME_MOSI 11
    #define BME_CS 6

    #define SEALEVELPRESSURE_HPA (1013.25)

    Adafruit_BME280 bme(BME_CS); // hardware SPI

    unsigned long delayTime;

    void setup() {
      Serial.begin(9600);
      Serial.println(F("BME280 test"));

      bool status;

      // default settings
      // (you can also pass in a Wire library object like &Wire2)
      status = bme.begin();
      if (!status) {
        Serial.println("Could not find a valid BME280 sensor, check wiring!");
        while (1);
      }
      Serial.println("-- Default Test --");
      delayTime = 1000;
      Serial.println();
      delay(100); // let sensor boot up
    }

    void loop() {
      printValues();
      delay(delayTime);
    }

    void printValues() {
      Serial.print("Temperature = ");
      Serial.print(bme.readTemperature());
      Serial.println(" *C");

      Serial.print("Pressure = ");
      Serial.print(bme.readPressure() / 100.0F);
      Serial.println(" hPa");

      Serial.print("Approx. Altitude = ");
      Serial.print(bme.readAltitude(SEALEVELPRESSURE_HPA));
      Serial.println(" m");

      Serial.print("Humidity = ");
      Serial.print(bme.readHumidity());
      Serial.println(" %");
      Serial.println();
    }

Code of the TFT screen with the BME280 (doesn't work)

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

    // include the necessary libraries
    #include <Adafruit_Sensor.h>
    #include <Adafruit_BME280.h>
    #include <SPI.h>
    #include <SD.h>
    #include <TFT.h>   // Arduino LCD library
    #include <Wire.h>

    // pin definitions
    #define bme_cs  6
    #define sd_cs   7
    #define rst     8
    #define dc      9
    #define lcd_cs 10
    #define mosi   11
    #define miso   12
    #define sck    13

    //var definitions
    #define SEALEVELPRESSURE_HPA (1013.25)

    //Define hardware SPI connection with BME280
    Adafruit_BME280 bme(bme_cs); // hardware SPI

    // Define screen pins
    TFT TFTscreen = TFT(lcd_cs, dc, rst);

    //Define variables
    char sensorPrintout1[6];
    char sensorPrintout2[6];
    unsigned long delayTime;

    // this variable represents the image to be drawn on screen
    PImage logo;

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

      bool status;

      // Initializing SD card
      Serial.print("Initializing SD card...");
      if (!SD.begin(sd_cs)) {
        Serial.println("failed!");
        //while (1);
      } else {
        Serial.println("OK!");
      }

      //Initializing BME280
      Serial.print("Initializing BME280");
      status = bme.begin();
      if (!status) {
        Serial.println("Could not find a valid BME280 sensor, check wiring!");
        while (1);
      } else {
        Serial.println("BME 280 sensor found");
      }

      // Start and clear TFT screen
      TFTscreen.begin();
      TFTscreen.background(0, 0, 0);

      // Lookup image on TFT screen
      logo = TFTscreen.loadImage("Logo.bmp");
      if (!logo.isValid()) {
        Serial.println("error while loading Logo.bmp");
      }
      if (logo.isValid() == false) {
        return;
      }

      //Draw logo on the screen
      Serial.println("drawing image");
      TFTscreen.image(logo, 0, 0);

      // Change text color to white
      TFTscreen.stroke(255,255,255);

      //Write some text
      TFTscreen.setCursor(0,25);
      TFTscreen.print("temperatuur 1: ");
      TFTscreen.setCursor(100,25);
      TFTscreen.print((char)247);
      TFTscreen.print("C");

      //write some text
      TFTscreen.setCursor(0,50);
      TFTscreen.print("luchtvochtigheid 2: ");
      TFTscreen.setCursor(100,50);
      TFTscreen.print((char)37);
      TFTscreen.print("C");
    }

    void loop() {
      // Read value of temperature
      int value1 = bme.readTemperature();
      int value2 = bme.readHumidity();
      String sensorVal1 = String(value1);
      String sensorVal2 = String(value2);

      // Change sensor value to a character array
      sensorVal1.toCharArray(sensorPrintout1, 6);
      sensorVal2.toCharArray(sensorPrintout2, 6);

      // Change text color to white
      TFTscreen.stroke(255,255,255);

      // Write value of temperature sensor
      TFTscreen.setCursor(55,25);
      TFTscreen.print(sensorPrintout1);

      // Write value of humidity sensor
      TFTscreen.setCursor(55,50);
      TFTscreen.print(sensorPrintout2);

      // wait  500ms
      delay(1000);

      // Change text color to black (aka overwrite text)
      TFTscreen.stroke(0,0,0);

      // Write value of temperature sensor
      TFTscreen.setCursor(55,25);
      TFTscreen.print(sensorPrintout1);

      // Write value of humidity sensor
      TFTscreen.setCursor(55,50);
      TFTscreen.print(sensorPrintout2);
    }

Now this is the serial output:

    Initializing SD card...failed!
    Initializing BME280Could not find a valid BME280 sensor, check wiring!

At first it only showed the first line, then it stopped because of the `while(1)` loop. So I put it in comment to see if the BME initializes on its own.

I also tested the screen+SDcard and the BME280 separately, which worked just fine.

**Update**

I tried to test the programs with the complete circuit. The program of the TFT screen works fine that way but when I try the program of the BME280 it doesn't work. I have to remove the TFT screen from the breadboard to make it work.

**Update 2**

After some measurements with the scope I determined that the MOSI is pulled to 0V when I connect the 5V to the TFT screen. I also saw that the MOSI output on the BME280 board is 3.3V instead of 5V.

Could it be that the conflict in voltages is the cause for all my troubles?

 [![Circuit][2]][2]

  [1]: https://www.arduino.cc/en/Guide/TFT
  [2]: https://i.stack.imgur.com/TAIIy.png

body: Connect the BME280 board by I2C, it cannot be used in a multi-SPI setup. The problem is that the MISO line it not decoupled from the bus if CS is HIGH but constantly pulled HIGH. This will disturb other bus members.


body:
Please check [my blog post about this issue][1] exactly.

The main idea is that the different SPI components do not respect the chip select and interfere with each other on the SPI bus. The way I solved it was to toggle between the different components using an array of switches- transistors in a way that in any given time only one component is connected to my Arduino (or any other master) through the SPI.

# How to use multiple SPI devices with Arduino

While building my SmartHomeDIY project I encountered a problem trying to use multiple SPI devices connected to the same Arduino. Although the SPI bus should support multiple devices at the same time (toggling the Chip-Select line), this does not always work (mostly due to the part using the bus not respecting the chip select or other configuration issues). So after reading for some time and experimenting I came up with the following solution.

The above station is an IR recorder and sransmitter station. It can be set into recording state, which then saves the recorded IR-in data into and SDCard connected over SPI. But when not in recording mode it will listen over the RF24 (also connected via SPI) for commands. Once a command is given it will try to send the IR code request (for example turn TV on). To do that it will again have to move to SDCard mode and read the previously recorded data and retransmit it over the IR out LED.

So to solve this I have connected the SPI lines to couple of transistors/switches, then just CUT the lines of the part not being used at the moment and there for prevent the SPI lines collision.

Attached is the code and hardware layout to do just that.

Note that it does not matter which type of project you have. You can always do the same transistor-switch trick to cut of the problematic SPI lines while using the others.

A special note for the transistor configurations. It will not work if you pass as usually suggested, which means to set a logic level by design at the output of the transistor so that the base will toggle the out voltage (same as an amplifier).

Instead I set the signal to go trough the transistor, which is needed, so testing to select the transistor, which does not affect the actual signal (it will depend on the transistor type, spec and configuration...). So it took me some time to figure out the right transistor values and configuration.

For trial and error I used a logic analyzer with 8 logic lines or an oscilloscope.

I inspected the incoming signal and the outgoing signal to make sure the transistor does not temper with the incoming signal, so everything will continue to work as expected (the transistor is transparent to the actual data).

You could also use this logic multiplexer [8 Channel Logic Level Converter Convert TTL Bi-directional] to do the same job, which I have not tested yet. But I think my way is more fun! :)

  [1]: https://www.2bitornot2bit.com/blog/how-to-use-multiple-spi-devices-with-arduino


message:
Transmit IR-Signal A, Receive IR-Signal B

I used the following program to send an IR code and I got the an unexpected result as below:

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

    /*
       IRremote: IRsendDemo - demonstrates sending IR codes with IRsend
       An IR LED must be connected to Arduino PWM pin 3.
       Version 0.1 July, 2009
       Copyright 2009 Ken Shirriff
       http://arcfn.com
    */

    #include <IRremote.h>

    IRsend irsend;

    int j = 0;
    void setup()
    {
    }

    void loop() {
      for (int i = 0; i < 3; i++) {
        irsend.sendNEC(0xFF6897, 32);
        delay(40);
        j = j + 1;
      }
      delay(5000); //5 second delay between each signal burst
    }

With the following schematic:
[![enter image description here][1]][1]

I expected to receive:

> FF6897 Decoded NEC: FF6897 (32 bits) Raw (68): 8750 -4450 550 -550 500
> -600 550 -550 550 -550 550 -550 550 -600 500 -600 500 -600 500 -1650 550 -1650 550 -1650 500 -1650 550 -1650 550 -1650 500 -1700 500 -1650
> 550 -550 500 -1700 550 -1600 550 -600 500 -1650 550 -600 500 -600 500
> -600 500 -1650 550 -550 550 -600 500 -1650 500 -600 500 -1700 500 -1650 550 -1650 550

Instead I receive consistently

> C101E57B Unknown encoding: C101E57B (32 bits) Raw (68): 8850 -4450 500
> -650 450 -600 500 -600 550 -550 500 -650 450 -650 500 -600 450 -650 450 -1800 450 -1700 500 -1750 500 -1700 500 -1750 500 -1700 500 -1750
> 450 -1750 500 -600 500 -1750 450 -1750 500 -600 450 -1750 500 -650 450
> -600 550 -600 500 -1700 500 -600 500 -600 500 -1750 500 -600 500 -1700 500 -1700 550 -1700 450

anyone knows how to fix this?

Code the Reciever uses to decode the just send signal:

    /*
     * IRremote: IRrecvDump - dump details of IR codes with IRrecv
     * An IR detector/demodulator must be connected to the input RECV_PIN.
     * Version 0.1 July, 2009
     * Copyright 2009 Ken Shirriff
     * http://arcfn.com
     * JVC and Panasonic protocol added by Kristian Lauszus (Thanks to zenwheel and other people at the original blog post)
     * LG added by Darryl Smith (based on the JVC protocol)
     */

    #include <IRremote.h>

    /*
    *  Default is Arduino pin D11.
    *  You can change this to another available Arduino Pin.
    *  Your IR receiver should be connected to the pin defined here
    */
    int RECV_PIN = 6;

    IRrecv irrecv(RECV_PIN);

    decode_results results;

    void setup()
    {
      Serial.begin(9600);
      irrecv.enableIRIn(); // Start the receiver
    }

    void dump(decode_results *results) {
      // Dumps out the decode_results structure.
      // Call this after IRrecv::decode()
      int count = results->rawlen;
      if (results->decode_type == UNKNOWN) {
        Serial.print("Unknown encoding: ");
      }
      else if (results->decode_type == NEC) {
        Serial.print("Decoded NEC: ");

      }
      else if (results->decode_type == SONY) {
        Serial.print("Decoded SONY: ");
      }
      else if (results->decode_type == RC5) {
        Serial.print("Decoded RC5: ");
      }
      else if (results->decode_type == RC6) {
        Serial.print("Decoded RC6: ");
      }
      else if (results->decode_type == PANASONIC) {
        Serial.print("Decoded PANASONIC - Address: ");
        Serial.print(results->address, HEX);
        Serial.print(" Value: ");
      }
      else if (results->decode_type == LG) {
        Serial.print("Decoded LG: ");
      }
      else if (results->decode_type == JVC) {
        Serial.print("Decoded JVC: ");
      }
      else if (results->decode_type == AIWA_RC_T501) {
        Serial.print("Decoded AIWA RC T501: ");
      }
      else if (results->decode_type == WHYNTER) {
        Serial.print("Decoded Whynter: ");
      }
      Serial.print(results->value, HEX);
      Serial.print(" (");
      Serial.print(results->bits, DEC);
      Serial.println(" bits)");
      Serial.print("Raw (");
      Serial.print(count, DEC);
      Serial.print("): ");

      for (int i = 1; i < count; i++) {
        if (i & 1) {
          Serial.print(results->rawbuf[i]*USECPERTICK, DEC);
        }
        else {
          Serial.write('-');
          Serial.print((unsigned long) results->rawbuf[i]*USECPERTICK, DEC);
        }
        Serial.print(" ");
      }
      Serial.println();
    }

    void loop() {
      if (irrecv.decode(&results)) {
        Serial.println(results.value, HEX);
        dump(&results);
        irrecv.resume(); // Receive the next value
      }
    }

Schematic wise:

one IR reciever with VCC and Ground connect and signal-out on pin 6

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

body:
In the received RAW codes, the width of the modulated pulses is less than the expected value. And the width of the spaces is bigger than expected.

This is due to the lack of an infrared sensor.

Use infrared receiver another model. For example TSOP4838.

Or try reducing MARK_EXCESS in the [IRremoteInt.h][1] of the Arduino-IRremote library from 100 to 50 or 0.

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

    ...
    // Pulse parms are ((X*50)-100) for the Mark and ((X*50)+100) for the Space.
    // First MARK is the one after the long gap
    // Pulse parameters in uSec
    //

    // Due to sensor lag, when received, Marks  tend to be 100us too long and
    //                                   Spaces tend to be 100us too short
    #define MARK_EXCESS    0
    ...

And please increase the delay time in transmitter sketch (to avoid codes overlapping) :

    ...
    for (int i = 0; i < 3; i++){
      irsend.sendNEC(0xFF6897, 32);
      delay(200);
      j = j + 1;
    }
    ...

  [1]: https://github.com/z3t0/Arduino-IRremote/blob/master/IRremoteInt.h


message:
Arduino Yun with PoE does not work when powered via PoE

I have a [Arduino Yun with PoE](https://store.arduino.cc/arduino-yun-with-poe) with LininoOS version

>Linux arduino 3.3.8 #1 Thu Jun 2 12:28:33 CEST 2016 mips GNU/Linux

I have the Version 4.0 of the module.

I often notice that when I connect the module via a USB cable and login via Serial the __WAN__ and __WLAN__ LEDs blink and I can SSH via both the mediums.

However I cannot do the same when the Yun is completely powered via an Ethernet Cable and the I see the Yun frequently restarting and becoming inaccessible via SSH.

I cannot troubleshoot this problem via software as whenever I connect the USB cable along with the Ethernet Cable the power supply switches completely to the USB and the PoE stops and everything suddenly works well again.

Has someone faced the same issue? Is it because of the [High Frequency Whistle problem][1] where I need to solder a **100µF Electrolytic Capacitor** to the PoE adapter?

### Update

I measured the __5 V__ and __3.3 V__ pins on the Yun they provide their respective voltages via a multimeter.

I have a [Microsens fast ethernet switch with PoE](http://www.microsens.com/products/category/micro-switches/fast-ethernet-switches/serie/Serie/show/fast-ethernet-micro-switch-6-port-with-poe-421/) which provides standard __(minimum 44V DC)__

> Apparently, the __WAN__ LED blinks indicating the Ethernet Connection is available however everytime I ping the Yun it goes down.

  [1]: http://forum.arduino.cc/index.php?topic=312340.15

body:
## PoE Adapter
__Silvertel AG9600 1R__ requires a `100µF 16V Electrolytic Capacitor` between it's `PIN 7` and `PIN 8`

According to the [PoE Yún Thread](http://forum.arduino.cc/index.php?topic=312340.15) the capacitor polarity should be as follows:

> PIN 7 --> Capacitor_Negative. PIN 8 --> Capacitor_Positive

solved my problem. I think the default __470uF__ capacitor might not be able to charge-discharge appropriately with data signals in the PoE.


message:
Are pins 0 and 1 (Rx and Tx) parallel with the USB jack? Can I connect another USB jack th 0 and 1 and use it to upload sketches?

I have a compact weatherproof enclosure and the onboard USB jack of my Mega is close to the edge. I didn't want to add a bulky weatherproof USB jack, so I'd like to just leave a female USB pigtail loose inside the enclosure.

The only thing is, I want to avoid the extra assembly step of soldering leads directly to the lugs on the board. I'd like to make a shield instead, with screw lug headers to attach all my wires to. That way a lot of my connections can be solderless and the assembly tech can just plug in the shield.

Can I connect the four wires of a USB cable to the header pins? I suspect I'd use Vin, GND, pin 0 and pin 1, but I'm not 100% sure. Thanks for your advice, gentlemen.

body: No. For many reasons. No. USB is not TTL. You need an adapter to connect rx/tx pins of arduino to USB. And the on-board adapter has the DTR line connected to reset the Atmega before writing a program into it. Without it, you would need to push the reset button in the right moment.


message:
Should I use an accelerometer or gyroscope in my project?

A friend and I are working on a sign language translation glove.

Our glove currently successfully uses 5 flex sensors to determine the bend of each finger and can accurately detect letters in the sign language alphabet.

We are now trying to add the functionality to detect one-handed words. Many of these words involve making a letter, but adding some motion. For example, the colour "blue" involves making a B, then shaking/waving your hand in the B position.

We are wondering which type of sensor would be able to handle this. From our research so far, we assume this will either be an accelerometer or a gyroscope, but are not sure which one would be best in the scope of our project.

Any help would be much appreciated!

body: An accelerometer is a better choice here. For your application, you aren't worried about initial motion but just acceleration. Plus, an accelerometer is cheaper.


body:
Use both. Accelerometer measure movement in direction of axes when gyroscope measure rotational movement. Being very delicate you can spin accelerometer and sensor won't see any changes, and you can move gyro in one axis without sensor detection. Having both mounted on one board (or in one casing) there is no possibility that motion will be missed by both. Look at the pictures what the sensors do:
[![enter image description here][1]][1]

There is a plenty of integrated accelerometer-gyro sensors, for example MPU-6050 Accelerometer + Gyro with supporting libraries. Please check [here][2]

  [1]: https://i.stack.imgur.com/gtu2Y.png
  [2]: https://playground.arduino.cc/Main/MPU-6050


message:
Looking for link to Double Pole Single Throw (DPST) relay for Arduino

Need to find a DPST relay that is 'Arduino' friendly and that is capable of 30A at 240VAC. Anyone can share links ?

Not looking for recommendation, just ideas on what you saw or used in the past.

Thanks.

body:
You will be hard-pressed to find a mechanical relay that you can directly connect to the Arduino digital pins. Any general purpose relay that fits your specs for the switched side will do, but you will need to pay attention to the datasheet for the coil voltage and current required to activate the relay.

Then, you'll want to use a driver circuit like a transistor (BJT or MOSFET) so that the low-voltage, low-current digital output of the Arduino can control the larger-current needed to trip the relay coil.


body:
A relay that can switch 30A on mains voltage is not going to be able to switch directly from 5V. Getting something that can switch from 24V is much more realistic.

High amp relays are often called contactors. 4-pole ones are not uncommon for industrial motor applications. 3 high-amp poles are for 3-phase power and a low-amp one for a control signal.

You can buffer up the signal using a transistor (you'd need one anyway to supply the coil amps) or another relay.


body:
Do not be scared from other answers. There are relays which hold the coil with 5 V from Arduino. Like the relay on this [Grove 30 A Relay Module][1]. It is powered from 5 V pin and the command to close is from the GPIO pin (works with 3.3V IO too).

Use two of these SPDT modules, if you can't find DPST powered with 5 V.

If you will use the Grove module and you do not use other Grove modules, there is no need to buy the Grove base shield. You can connect the module with [this cable.][2]

  [1]: https://www.seeedstudio.com/Grove-SPDT-Relay(30A)-p-1473.html
  [2]: https://www.seeedstudio.com/Grove-4-pin-Male-Jumper-to-Grove-4-pin-Conversion-Cable-(5-PCs-per-Pack)-p-1565.html
  [3]: https://i.stack.imgur.com/4hUBo.jpg
  [4]: https://i.stack.imgur.com/YoVjt.jpg


message:
Transmit data to long distance (120m)

I want to transmit data from multiple sensors to an Arduino and distance would be approximately 120 meters.

What protocol or configuration should I use?

Actually I am trying to read values from 5 temperature sensors located in 5 different spots of warehouse. I want to read them and trigger some relay based on the values.

I thought about I2C but I have read somewhere that its not built for long distances. Also thought about RS-485, but I don't know if that supports bus (connect all sensors to same line).

Which solution do you suggest?

body: While thinking about RS-485, did you read about it? It is a bus. It is designed for long distances.


body: I2C is not built for long distances (max. some meters) But you can make it via RS485, But you will need to add termination resistors to each end.


message:
How the output of a bicycle dynamo can be displayed using Arduino?

I am on a project in which I need to make bicycle dynamo frequency meter.
The power generator’s output should vary with the speed of the wheel.

Which parts do I need to make it work?

The project should look like: : http://www.lanzo.se/experiments/dynamo/dynamo.html
                 or http://practicalphysics.org/bicycle-dynamo-and-oscilloscope.html

-->without oscilloscope ( which is replaced with Arduino and panel )

body:
It al depends on what is the maximum output of the dynamo.

 - less than 5V (not likely): great just connect it directly with the Analog measuring pin of the Arduino (A1- A7)
 - more than 5V: we got different options here
     -  Make a simple voltage divder to measure the output
     -  use an external ADC


body:
The first thing to look at before you connect the bicycle dynamo to an Arduino is what type of signal / voltage it generates. The link you've provided: http://www.lanzo.se/experiments/dynamo/dynamo.html gives you the answer. It's an AC signal which varies between +4V and -4V (It could be much higher if you spin it faster). On the Atmega328P data sheet under "Absolute Maximum Ratings" it says "Voltage on any Pin except RESET with respect to Ground -0.5V to VCC +0.5V". Obviously, -4V exceeds the -0.5V maximum so don't connect it directly to an Arduino.

The signal from the dynamo to Arduino must be limited to between 0V and 5V (for an Arduino operating at 5V). The answer on how to accomplish this is a general electronics question and should be asked on a different forum e.g. https://electronics.stackexchange.com/questions/132330/8v-ac-signal-into-3-3v-digital-input-pin

The "frequency meter" part of your question is easy to build with an Arduino. You could use an Uno or something smaller like a Pro Mini with a 16 x 2 LCD display and this library: https://github.com/k3ng/k3ng_antenna_tuner/tree/master/libraries/FreqCounter. An I2C backpack for the LCD is only a dollar more and makes the wiring much easier. To use the backpack you'll need this library: https://github.com/marcoschwartz/LiquidCrystal_I2C.


message:
OBOE: Need help understanding, possible type conversion issue

I have an algorithm that its main purpose is decoding, converting, or what have you a string of uppercase letters (A-Z) into a number. This is almost like converting a base 26 number into base 10, however I believe that a base 26 number encoded would actually include numbers, I am working strictly with uppercase letters, I digress.

I have an implantation working in C++11, in fact most of the controller algorithm was a direct copy, with a slight change to the indexOf method.

The C++11 version works as I expect it to. So initially I thought the new indexOf method was incorrect, but after a simple test, it is working as expected. I have narrowed down the problem to a line in the convertTo10 where I am calling the pow function.

As you can see from the Serial.println()'s in the convertTo10 method, the output is printing exactly what we expect, 0 & 26.

However, the output of this function is 25. WHAT?

I have read the docs on the pow method from the Arduino lib, and it takes in two floats and returns a double. Even if the issue was a type conversion issue, converting a double to an int truncates the number, it does not round it. Well, this is from working with C++.

Any help with this issue would be much appreciated.

    #include <string.h>
    #include <stdio.h>
    #include <errno.h>
    #include <stdlib.h>
    #include <inttypes.h>

    #include <Arduino.h>
    #include <avr/pgmspace.h>
    #include <Wire.h>

    const char _values[26] = {
        'A', 'B', 'C', 'D', 'E', 'F', 'G', 'H', 'I', 'J',
        'K', 'L', 'M', 'N', 'O', 'P', 'Q', 'R', 'S', 'T',
        'U', 'V', 'W', 'X', 'Y', 'Z'
    };

    const int _val_len = 26;

    int indexOf(char needle);
    int convertTo10(String value, int len);

    String x = "BA";
    int len = 2;

    void loop() {
      Serial.print(x);
      Serial.print("=> ");
      Serial.println(convertTo10(x, 2));
      delay(50000);
    }

    int convertTo10(String value, int len) {
        int lastIndex = len - 1;
        double output = 0;
        int pos = 0;
        Serial.println();
        for (int i = lastIndex; i >= 0; i--) {
            int r = indexOf(value[i]);

            output += (r * pow((_val_len, pos));
            Serial.print("     output => ");
            Serial.println( output );
            pos++;
        }
        return output;
    }

    int indexOf(char needle) {

     int first = 0;
     int last = _val_len - 1;
     int mid;

      do {
        mid = (first + last) / 2;

        if (_values[mid] == needle)
          return mid;
        if (_values[mid] > needle)
          last = mid - 1;
        else
          first = mid + 1;
      } while (first <= last);

      return -1;
    }

For Reference, Here what it is outputting:

    BA =>
         output => 0.00
         output => 26.00
    25

body:
way too complicated:

    int convertTo10(char *num_26, int len) {
      int tmp = 0;  //hold the output
      int i = 0;  //indexing the input
      while (len--) tmp = tmp * 26 + (num_26[i++]-'A');
      return tmp;
    }

note:
 1. "* 26" can be further simplified;

 2. error checking could be built-in here, or somewhere else (better).

 3. better structuring could get rid of one of the temporary variables.


body:
Your code is incredibly complex for a simple thing like converting a number from another base. This works (prints 26):

    const char * test = "BA";

    long convertTo10 (const char * s)
      {
      long result = 0;
      for (const char * p = s; *p; p++)
        {
        result *= 26;   // base
        result += *p - 'A';  // make zero-relative
        }
      return result;
      } // end of convertTo10

    void setup()
      {
      Serial.begin (115200);
      Serial.println ("Starting.");
      Serial.println (convertTo10 (test));
      }

    void loop() { }

With input "CBA" it prints 1378 as expected.  Sketch size: 2,300 bytes of program memory. The sketch size reduces to 2,236 bytes if I make the function return `int` (as you did) rather than `long`.

You don't need to use `String` (in fact it saves RAM and avoids memory fragmentation to not use it). You don't need to pass the length, with both `char*` and `String` you can deduce the length. If you use `long` as the return type you can handle larger numbers.

By using `pow` you are bringing in a library which is not needed and which will consume program memory. By using `double` you are introducing possible inaccuracies since double does not necessarily store numbers exactly. Your code used 7,604 bytes of program memory once I corrected the syntax error and added an empty `setup` function.

---

Also, the method I illustrate above is *much* faster. I timed it at converting "BA" in 4.3 µs, whereas the method using the `pow` function takes 442 µs. So the simpler method is also 100 times faster.


message:
When Raspberry Pi is preferred over Arduino

We are doing some projects in class. One of my friends is doing a weather and humidity station using raspberry Pi with a couple of sensors and LCD. I have a little experience in Arduino. So I asked her, why doesn't she do it using an Arduino? She said Pi is more 'powerful'. In what aspects, is it more powerful than Arduino? When should I go for Raspberry Pi over Arduino?

body:
> When should I go for Raspberry Pi over Arduino

There is always the price difference but apart from that I would say: The Raspberry Pi can do everything the Arduino can and do it better and faster **EXCEPT** tasks which are very time critical. Thus if you need to responds to events in micro seconds or millisecond or if you need to generate signals in those order of magnitudes you will need an Arduino.


body: As opposed to the Arduino boards, the Raspberry Pi is a single-board computer with a quad-core CPU, a GPU, on-board RAM, and many peripherals. The main difference between the Pi and the Arduino (or any basic microcontroller) is the operating system. The Pi runs many Linux distributions (Debian being the official one), enabling the user to execute complex computing tasks that would be impossible to run on Arduino without external circuitry. Hence, the Raspberry Pi would be adequate for any software requiring significant CPU/GPU power or memory. Keep in mind that most Arduino's can be interfaced with the same type of peripherals that are found on the Raspberry Pi, although processing power might be lacking. Also, low-level interfacing with analog signals is much more convenient with Arduino, since it has integrated ADCs (analog-to-digital converters).


body:
Somewhat of an opinionated question but I'll give some feedback. It depends on various things:

 - How much UX and UI you want to give to your client
 - How easily can you program it
 - Which is a cheaper solution
 - How fast do you want the program to run
 - What is more durable and how long do you want to use the device

To prevent this answer from being lengthy, I'll do a quick comparison from my experiences with both.

**Arduino:** Cheap, easy to program, capable of flexibility with UX and UI but has very limited memory. The Arduino is typically good for something that can just complete tasks on their own. I've written state machines and have used it for PLCs with an Arduino. It's a good device for a cheaper budget. Arduino is pretty fragile, however.

**Raspberry Pi:** More expensive, a lot more powerful in terms of processing speed, has a lot more memory, extremely good for UX and UI devices that are being developed, good for artificial intelligence, state machines, PLCs, etc. Also really good for data logging, image processing, and radio frequency applications. You can also boot an operating system on it (e.g. Linux/Unix). In other words, a Raspberry Pi can used as a computer while the Arduino... well I guess it depends how you define, "computer" LOL.

So if you're trying to do something as simple as using sensors and LEDs, I'd go for the Arduino Uno.


body:
The claim that the Pi is more "powerful" is a bit misleading. What does "powerful" really mean? And is it relevant to making a weather station?

I made a temperature and humidity sensor as described [here](http://www.gammon.com.au/forum/?id=12106) using an Atmega328P (the processor that is in the Arduino Uno). The estimated average power consumption is 42 µA which has allowed it to run from 3 x AA batteries for a couple of years before they needed replacing. I think you'll find that the Pi with its more "powerful" processor and extra components would not be able to do that.

I see from a quick search that the Pi consumes 80 mA to 240 mA when idle (depending on the model). This would make a Pi-powered weather station eat through batteries 2000 times as quickly. Perhaps that would be a consideration.

The Pi is really a Unix PC on a board, which means it goes through the normal boot sequence with a possibility of errors occurring during booting. To see what those errors are you need to connect up a keyboard and screen, or connect via a network to it from another PC.

I don't want to run down the Pi - it's a nice cheap Unix computer on a small board. But the Arduinos (many of them) are somewhat simpler to program. You don't need to worry about the operating system for a start. For a weather station, taking a reading every 5 minutes, who cares if the Pi can take the reading "50 times faster"?

---

## Speed of recovery from sleep

I have an [answer about letting serial data wake an Arduino](https://arduino.stackexchange.com/questions/13167/put-atmega328-in-very-deep-sleep-and-listen-to-serial) - after some experimenting I was able to get the Atmega328P to wake from its deepest sleep (260 nA - yes 0.260 µA!) within 6 clock cycles (750 ns). I doubt you could achieve that on the Pi, either the low power consumption, or waking up in under a microsecond.

This was fast enough to detect the start bit in serial data at 9600 baud, process the start bit, and then the rest of the incoming byte without losing data.


body: In "pure hardware" based systems, real time systems, you can always prefer Arduino over Pi with OS. Power consumption, price are other plus points for UNO. Pi is always the better one in complex computing tasks, where its OS simplifies those tasks. But you don't wanna use a "computer" for sensor related projects for sure !


message:
Arduino uno and ESP8266

**Scenario :**

 - I want to connect ESP8266 to Raspberry-pi's wifi network.

 - Arduino Uno is connected to ESP8266

 - Raspberry-pi will send a signal (1/0) to ESP8266, when its 1 Arduino will turn on/off a Relay.

 - I do not have a USB to UART Serial module

So my question is how to complete this task? Is it a feasible one?

I had been looking for many websites, almost all are using USB to UART Serial module to burn firmware to ESP8266.

body:
You can use the USB-to-Serial adapter of the Arduino UNO, it has one on-board (ATmega16U2). Check the [schematic][1] of the UNO to understand what's going on.

First, upload an empty sketch to the UNO's ATmega328P, to make sure that it doesn't use the UART.

Connect the TX pin of the ATmega16U2 (i.e. the RX pin of the Arduino, digital pin 0) to the RX pin of the ESP8266. Connect a 2kΩ resistor between the ESP's RX pin. Together with the 1kΩ resistor on the ATmega16U2's TX line (on the Arduino), this creates a voltage divider that acts as a level shifter from 5V to 3.3V.

Connect the RX pin of the ATmega16U2 (i.e. the TX pin of the Arduino, digital pin 1) to the TX pin of the ESP8266.

Connect the grounds together as well.

In the Arduino IDE, select the ESP8266 under Tools > Board. Then enter programming mode on the ESP:

 1. Bring reset low
 2. Bring GPIO0 low
 3. Bring reset high
 4. Bring GPIO0 high

Then upload your sketch to the ESP.

I recommend adding simple push buttons and pull-up resistors:
![Pushbuttons for entering programming mode](https://tttapa.github.io/Images/ESP8266-2.png)
(The ESP-01 has GPIO15 shorted to ground internally, so you don't have to worry about that. If you were using an ESP-## module that breaks out this pin, you need an external pull-down resistor.)

Keep in mind that you will also need a decent 3.3V power source, and some decoupling capacitors.

[A Beginner's Guide to the ESP8266][2]

  [1]: https://www.arduino.cc/en/uploads/Main/Arduino_Uno_Rev3-schematic.pdf
  [2]: https://tttapa.github.io/Images/ESP8266-2.png


message:
Problem opening multiple text files simultaneously/in-order using <SD.h>

I am looking to log analog sensor data using 3 pins, A1, A2, A3. My project requires continuous mapping of data, and hence an SD card shield was necessary. However, I need to log the incoming data into 3 different text files, and for that purpose I assumed that opening the 3 files simultaneously might or might not be possible as indicated [here][1] (I am a beginner, so I wasn't able to comprehend everything, and I am short on resources:)

So for the time being, I worked my way around with opening the three files in order. Rather than opening them all at once,writing the data on to each file and then closing them, I did all three tasks in 1) separate functions for all three files and calling them in the loop() function, 2)keeping all the stuff in the loop() function itself.The result for method-1 was no file was ever created, and that for method-2 was only the first file was created and the rest, nope. Here's the code for both the versions. What could I be doing wrong? Thanks in advance!

My board is an Arduino Uno. Yes, I have formatted the SD card with FAT32. My wiring is in place, my code is the only possible problem I see.

 **Method 1**

    #include <SD.h>
    File Cu_volt;
    File Gunmet_volt;
    File Al_volt;
    static float volt_Cu, volt_Gunmet, volt_Al;

    void setup() {
      Serial.begin(9600);
      analogReference(INTERNAL);
      pinMode(A1, INPUT);
      pinMode(A2, INPUT);
      pinMode(A3, INPUT);

      //Initialize SD card module, CS pin set at 4
      Serial.println("INITIALIZING SD CARD...");
      //check for SD errors
      if ( !SD.begin(4)) {
        Serial.println("INITIALIZATION FAIL...");
        while (1);
        return;
      }
      Serial.println("INITIALIZATION DONE");
    }

    void loop() {
      // read the input on analog pin 0 copper electrode:
      // Convert the analog reading (which goes from 0 - 1023) to a voltage (0 to VRef=INTERNAl)
     copperFile();
     gunmetalFile();
     aluminiumFile();
     delay(3000);
   }

    void copperFile() {
      Cu_volt = SD.open("Copper.txt", O_RDWR | O_APPEND);
      if (!Cu_volt) {
        Cu_volt = SD.open("Copper.txt", O_RDWR | O_CREAT);
        if (!Cu_volt) {
          Serial.println("Failed to open file at all");
        }
      }
      volt_Cu = analogRead(A1) * (1.1 / 1023.0);
      // print out the value read(COPPER):
      Serial.print("Copper voltage=");
      Serial.println(volt_Cu);
      if (Cu_volt) {
        Cu_volt.println(volt_Cu);
        Cu_volt.close();
      }
    }

    void gunmetalFile() {
      Gunmet_volt = SD.open("Gun_metal.txt", O_RDWR | O_APPEND);
      if (!Gunmet_volt) {
        Gunmet_volt = SD.open("Gun_metal.txt", O_RDWR | O_CREAT);
        if (!Gunmet_volt) {
          Serial.println("Failed to open file at all");
        }
      }
      volt_Gunmet = analogRead(A2) * (1.1 / 1023.0);
      // print out the value you read(GUNMETAL):
      Serial.print("Gun metal voltage=");
      Serial.println(volt_Gunmet);
      if (Gunmet_volt) {
        Gunmet_volt.println(volt_Gunmet);
        Gunmet_volt.close();
      }
    }

    void aluminiumFile(){
      //opening aluminium file
      Al_volt = SD.open("Aluminium.txt", O_RDWR | O_APPEND);
      if (!Al_volt) {
        Al_volt = SD.open("Aluminium.txt", O_RDWR | O_CREAT);
        if (!Al_volt) {
          Serial.println("Failed to open file at all");
        }
      }
       volt_Al = analogRead(A3) * (1.1 / 1023.0);
      // print out the value you read(ALUMINIUM):
      Serial.print("Aluminium voltage=");
      Serial.println(volt_Al);
      if (Al_volt) {
        Al_volt.println(volt_Al);
        Al_volt.close();
      }
    }

**Method 2**

    #include <SD.h>
    File Cu_volt;
    File Gunmet_volt;
    File Al_volt;
    static float volt_Cu, volt_Gunmet, volt_Al;

    void setup() {
      // initialize serial communication at 9600 bits per second:
      Serial.begin(9600);
      analogReference(INTERNAL);
      pinMode(A1, INPUT);
      pinMode(A2, INPUT);
      pinMode(A3, INPUT);
      //Initialize SD card module, CS pin set at 4
      Serial.println("INITIALIZING SD CARD...");
      //check for SD errors
      if ( !SD.begin(4)) {
        Serial.println("INITIALIZATION FAIL...");
        while (1);
        return;
      }
      Serial.println("INITIALIZATION DONE");
    }

    void loop() {
      // read the input on analog pin 0 copper electrode:
      // Convert the analog reading (which goes from 0 - 1023) to a voltage (0 to VRef=INTERNAl)
      volt_Cu = analogRead(A1) * (1.1 / 1023.0);
      // print out the value you read(COPPER):
      Serial.print("Copper voltage=");
      Serial.println(volt_Cu);
      //opening copper file
      Cu_volt = SD.open("Copper.txt", O_RDWR | O_APPEND);
      if (!Cu_volt) {
        Cu_volt = SD.open("Copper.txt", O_RDWR | O_CREAT);
        if (!Cu_volt) {
          Serial.println("Failed to open file at all");
        }
      }
      if (Cu_volt) {
        Cu_volt.println(volt_Cu);
        Cu_volt.close();
      }
      volt_Gunmet = analogRead(A2) * (1.1 / 1023.0);
      // print out the value you read(GUNMETAL):
      Serial.print("Gun metal voltage=");
      Serial.println(volt_Gunmet);
      //opening copper file
      Gunmet_volt = SD.open("Gun_metal.txt", O_RDWR | O_APPEND);
      if (!Gunmet_volt) {
        Gunmet_volt = SD.open("Gun_metal.txt", O_RDWR | O_CREAT);
        if (!Gunmet_volt) {
          Serial.println("Failed to open file at all");
        }
      }
      if (Gunmet_volt) {
        Gunmet_volt.println(volt_Gunmet);
        Gunmet_volt.close();
      }
      volt_Al = analogRead(A3) * (1.1 / 1023.0);
      // print out the value you read(ALUMINIUM):
      Serial.print("Aluminium voltage=");
      Serial.println(volt_Al);
      //opening aluminium file
      Al_volt = SD.open("Aluminium.txt", O_RDWR | O_APPEND);
      if (!Al_volt) {
        Al_volt = SD.open("Aluminium.txt", O_RDWR | O_CREAT);
        if (!Al_volt) {
          Serial.println("Failed to open file at all");
        }
      }
     if (Al_volt) {
        Al_volt.println(volt_Al);
        Al_volt.close();
      }
      delay(3000);
    }

  [1]: http://forum.arduino.cc/index.php?topic=300875.0

body:
There are several variations of the SD library - some support multiple files, others do not.

Try calling .begin (and .end) on each write loop, and add in .flush - see below.

If that works with your library then take the (.begin / .end) out of the loop and try again.

    #define FILENAME "myfile.txt"

    void writeToFile() {
     File f;
     // begin and end on each write
     if (SD.begin(10, 11, 12, 13)) { // I use an older library that allows pin reassignment
      f = SD.open(FILENAME, FILE_WRITE);  // This will append and create if not exisiting
      if(f) {
       f.println("a string");  // Your write operations
      }
      f.flush();   // This ensured the write buffer actually went to file
           // even if less than the block size (512b?)

      f.close();
      }
     SD.end();     // Do this after every write operation
    }


body: For people having similar problems with creating multiple files on an SD card, it may be a memory issue. You need to have a certain amount of unused dynamic memory (about 300 bytes of free space, in my experience) in order to write to an SD card - and more if you are writing multiple files. Following the instructions on [this page](https://learn.adafruit.com/memories-of-an-arduino/optimizing-sram) may help.


message:
Creating String Arrays and passing each index value to a variable after a given period

Is there a way to take an input string, store it into a array and then pass each index of that array to a variable to hold  before being overwritten by the next array index value?

For example:

A number of input values which are of type:String are being created

   String 1 is given as "Value: 7.93 22-10-2017 10:33:32"
 String 2  is given as "Value: 8.93 22-10-2017 12:10:15"
 .
 .
 .
 String 10  is given as "Value: 6.93 22-10-2017 18:03:04"

The string structure is known but its contents as such will vary

After a time period of say 60sec. The contents of array[0] which will be String 1 will be assigned to a given variable "output"

After the next 60sec time period .The contents of array[1]  Which will be String 2 will be stored into  the same "Output" variable in which the previous value will be now overwritten

This continues until array[9] i.e String 10 in which the array will begin over and start to populate "output" with newly presented string values

body:
Solution Used Below:

    // Input 1-3 represents input string

    String Input1 ="Value: 7.93 22-10-2017 10:33:32";
    String Input2 ="Value: 8.93 22-10-2017 12:10:15";
    String Input3 ="Value: 8.93 22-10-2017 12:10:15";
    String message[] ={Input1,Input2,Input3};

    // Assigned 'Output' Variable will be populated by each index of the array
    String Output;

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

    // Each index of the array will be stepped through and passed to 'Output'
    //delay() will control period between each index value

    void loop()
         {
             for (int i = 0; i < 3; i++)
                {
                      Output=message[i];
                      Serial.println(Output);
                      delay(5000);
                }

         }


message:
Arduino Nano timer, please advice

I'm new here and in the Arduino world. I try to put together a system to cut the power of a LED night light after a preset time. The light is powered by a 5V accu and I would like to avoid to re-charge the accu each morning if the light stays on all night...
I purchased an Arduino Nano, a RTC module and a mini OLED display. I would like to kindly ask you for help in putting the system together: programming the Arduino and connecting the module together. The RTC module should open the possibility to completely automate the system (turn power on and off between precise times) and the OLED Display should give the feedback of the current settings.
The RTC and OLED modules are just "nice to have", my main goal would be to have an automatic cutting of of the power after a certain time (i.E. 60 min.) after initialization of the system (through a push button, for example).
Thank you in advance for your advices!

body:
As Juraj said, you don't need an RTC for this. You just have to:

1. turn the LED on
2. wait for 60 minutes
3. turn it off

And do this every time the user presses a push-button.

The code that does this is pretty trivial:

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

    const uint8_t BUTTON_PIN = 2;
    const uint8_t LED_PIN = 3;
    const uint32_t MINUTE = 60000;
    const uint32_t ON_TIME = 60 * MINUTE;

    void setup() {
        pinMode(BUTTON_PIN, INPUT_PULLUP);
        pinMode(LED_PIN, OUTPUT);
    }

    void loop() {
        if (digitalRead(BUTTON_PIN) == LOW) {  // button pressed
            digitalWrite(LED_PIN, HIGH);       // LED on
            delay(ON_TIME);                    // wait
            digitalWrite(LED_PIN, LOW);        // LED off
        }
    }

Now, you can build on top of that whatever “nice to have” functionality
you want.