message:
How do I stop 5v on the I2C port of a pro mini so I can use 3.3v devices?

The theory is that you can use 3.3v I2C devices from a 5v device as long as the pull ups are only to the 3.3v. I have a 5v pro mini connected to a bmp180 board which has a 3.3v regulator but no level shifters. It is working and giving me data but I am hoping I can get better quality measurements. One observation is the power rail on the BMP board after the 3.3v regulator is being pulled towards 5v. On the scope this looks to happen between i2c messages. I am using the "Adafruit-BMP085-Library" which is in turn using "Wire". In the wire library there is a comment that says that the writedigital() of 1 to the port is setting the pull ups.

Does anyone have any general advice on this issue?

What does the comment about setting the pull-ups mean? How is that function setting the pull ups?

When does the I2C switch back to being an GPIO? Are the lines being pulled high between messages because it is reverting to an GPIO?

body:
Whoever decided it would be a good idea to default to using the Arduino internal pull-up resistors on I2C needs taking out back and giving a good kicking. It is so wrong on so many levels.

Yes, if you disable the internal pull-up resistors you can safely use 3.3v devices. The simplest way to do this is to turn them off again as soon as you have done `Wire.begin();` by writing 0 to the pins with `digitalWrite()`.


sender: user

message:
How to store 1 bit Boolean data into EEPROM and retrieve this 1 bit data?

I am building a project where I have to store the digital state which is Boolean (either HIGH or LOW) of each I/O port such that after power off the state of I/O ports store in EEPROM and I can retrieve this I/O port's state after power on.

This is my code..

        #include <IRremote.h>
        #include <EEPROM.h>
        int EEPROMaddress = 0;
        int EEPROMaddress1 = 1;
        byte EEPROMbyte = EEPROM.read(EEPROMaddress);
        byte EEPROMbyte1 = EEPROM.read(EEPROMaddress1);
        int RECV_PIN = 11;
        int led = 10;//1FE50AF
        int led1 = 9;//1FED827
        boolean previousState = bitRead(EEPROM.read(EEPROMaddress), led);
        boolean previousState1 = bitRead(EEPROM.read(EEPROMaddress1), led1);
        boolean state;
        boolean state1;
        IRrecv irrecv(RECV_PIN);
        decode_results results;
        void setup()
        {
          Serial.begin(9600);
          pinMode(10,OUTPUT);
          pinMode(9,OUTPUT);
          irrecv.enableIRIn();
        }
        void loop() {
          if (irrecv.decode(&results))
          {
            Serial.println(results.value, HEX);
            switch(results.value)
            {
               case 0x1FE50AF:
               if (previousState == LOW)
               {state = HIGH;
                digitalWrite(led,state);
               previousState=state;
               bitWrite(EEPROMbyte,led,state);
               EEPROM.update(EEPROMaddress,EEPROMbyte);
               delay(50);}
               else
               {state=LOW;
               digitalWrite(led,state);
               previousState=state;
               bitWrite(EEPROMbyte,led, state);
               EEPROM.update(EEPROMaddress,EEPROMbyte);
               delay(50);
               }
               break;
                case 0x1FED827:
               if (previousState1 == LOW)
               {state1=HIGH;
               digitalWrite(led1,state1);
               previousState1=state1;
               bitWrite(EEPROMbyte1,led1, state1);
               delay(50);}
               else
               {state1=LOW;
               digitalWrite(led1,state1);
               previousState1=state1;
               bitWrite(EEPROMbyte1,led1,state1);
               delay(50);}
               break;
    }
            irrecv.resume();
          }
    }

sender: assistant

body:
Since this is Arduino SE I'm going to do this with the Arduino functions, there are other ways of course.

Write a bit to EEPROM:

    byte EEPROMbyte = EEPROM.read(EEPROMaddress);
    bitWrite(EEPROMbyte, pinBit, pinState);
    EEPROM.update(EEPROMaddress, EEPROMbyte);

Read a bit from EEPROM:

    boolean pinState = bitRead(EEPROM.read(EEPROMaddress), pinBit);

This is for updating/reading a single bit at a time as asked. If you need to read/write multiple bits at the same time(as I'd assume you are doing after power on) then it's more efficient(and less wear on the EEPROM in the case of the write) to do all the bits at once instead of one EEPROM read/write per bit.

I assume by "I/O ports" you mean Arduino pins. If you're working directly with the PORT registers(e.g. PORTB) then you can just write or read the whole register to the EEPROM, no need to deal with the individual bits.


body:
Note that writing EEPROM is slow - on the order of milliseconds per write - which may limit the performance of your sketch.

A better technique is to provide a limited backup power supply to the MCU; enough to complete a set of EEPROM writes + a safety margin. A capacitor could possibly provide enough run time if doesn't have to power much else. Then, detect and interrupt on a failure of the main supply, immediately write your backup data to EEPROM, and enter an infinite loop to wait for the backup supply to fail. When the system resets, examine the EEPROM to be sure there is valid backup data there, restore what needs to be restored, and resume your task.

Update:

A search for "arduino backup power" finds a number of articles related to switching an Arduino from mains power to battery power when the mains fails. You would only need a very small battery if you're willing to only save necessary information then shut down until the power returns. A capacitor might keep your MCU running long enough to do that. Designing the circuit depends on too much we don't know about your system, though.

In fact, simply switching a backup battery as some of these articles describe, or better, running on a battery which is kept on a mains charger, may make a much simpler system that can surviVe reasonably long power outages without shutting down. Again, we don't know how often or how long your power goes out, and how reliable your system is required to be.


body:
You can store any bits or bytes into eeprom in byte units. The eeprom itself doesn't care whether the data ISS bits or bytes or multi bytes.

Your code only needs to make sure that consistency is maintained in storying and retrieving of eeprom data.


message:
Is it better to use Vraw or Vcc on Mini Pro?

I have 12V and 5V power available. Is it better to feed the 5V through the Vcc pin or either the 12V or 5V through the Vraw pin?

body:
Use the 5V connected to the Vcc pin.

If you use the Vraw pin, the voltage goes through a voltage regulator. This voltage regulator will convert the higher voltage down to 5V by converting the extra volts to heat. So in case of using 12V you'd be throwing away around 60% of the power. Which is both wasteful, and will heat up the regulator quite a bit (depending on the load).


message:
Huge nested loop in Arduino

I am completely new to programming and I am trying a brute force programming on my garage door opener. I want to use an Arduino for learning purposes. I wrote the following program that finally did what it should and now I am wondering whether there is a shorter code that does the same. Is anyone able to help me in that matter?

I do know that about 2^12 possibilities existed so I ran through all of them. I also knew that some parts of the "pulsetrain" (the set of necessary pulses) start with a particular sequence that is always the same (for all "brute forced" trains) and that the closing sequence is also always identical. I then simply wrote that down in the following, nasty code:

    /*
      Transmitter is connected to Arduino Pin #2
    */

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

    void pulsetrain(int a, int b, int c, int d, int e, int f, int g, int h, int i, int j, int k, int l, int m) {
      PORTD &= ~_BV(PD2);
      //set to LOW, hardwired to make it faster, see http://www.instructables.com/id/Arduino-is-Slow-and-how-to-fix-it/?ALLSTEPS
      delayMicroseconds(283); // (D2)
      PORTD |= _BV(PD2); //set to HIGH
      delayMicroseconds(566);
      PORTD &= ~_BV(PD2);
      delayMicroseconds(283);
      PORTD |= _BV(PD2);
      delayMicroseconds(566);
      PORTD &= ~_BV(PD2);
      delayMicroseconds(a);
      PORTD |= _BV(PD2);
      delayMicroseconds(b);
      PORTD &= ~_BV(PD2);
      delayMicroseconds(c);
      PORTD |= _BV(PD2);
      delayMicroseconds(d);
      PORTD &= ~_BV(PD2);
      delayMicroseconds(e);
      PORTD |= _BV(PD2);
      delayMicroseconds(f);
      PORTD &= ~_BV(PD2);
      delayMicroseconds(g);
      PORTD |= _BV(PD2);
      delayMicroseconds(h);
      PORTD &= ~_BV(PD2);
      delayMicroseconds(i);
      PORTD |= _BV(PD2);
      delayMicroseconds(j);
      PORTD &= ~_BV(PD2);
      delayMicroseconds(k);
      PORTD |= _BV(PD2);
      delayMicroseconds(l);
      PORTD &= ~_BV(PD2);
      delayMicroseconds(m);
      PORTD |= _BV(PD2);
      delayMicroseconds(283);
      PORTD &= ~_BV(PD2);
      delayMicroseconds(566);
      PORTD |= _BV(PD2);
      delayMicroseconds(283);
      PORTD &= ~_BV(PD2);
      delayMicroseconds(566);
      PORTD &= ~_BV(PD2); // last LOW
    }

    void loop() {
      int signals[2] = {283, 566};
      for (int a = 0; a < 2;  a++) {
        for (int b = 0; b < 2;  b++) {
          for (int c = 0; c < 2;  c++) {
            for (int d = 0; d < 2;  d++) {
              for (int e = 0; e < 2;  e++) {
                for (int f = 0; f < 2;  f++) {
                  for (int g = 0; g < 2;  g++) {
                    for (int h = 0; h < 2;  h++) {
                      for (int i = 0; i < 2;  i++) {
                        for (int j = 0; j < 2;  j++) {
                          for (int k = 0; k < 2;  k++) {
                            for (int l = 0; l < 2;  l++) {
                              for (int m = 0; m < 2;  m++) {
                                pulsetrain(signals[a], signals[b], signals[c], signals[d], signals[e], signals[f], signals[g], signals[h], signals[i], signals[j], signals[k], signals[l], signals[m]);
                              }
                            }
                          }
                        }
                      }
                    }
                  }
                }
              }
            }
          }
        }
      }
    }

body:
All those variables `a`, `b`, etc. are just the individual bits of a
13-bit number. When you loop through all combinations, you are actually
looping through all the possible _numeric values_ of a 13-bit number.
This can be simplified as this (warning: not tested):

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

    // the bitstream is: 0.101x xxxx.xxxx xxxx.0101
    void pulsetrain(uint16_t code) {
        uint32_t bitstream = (((uint32_t) code) << 4) | 0x0a0005UL;
        for (uint8_t i = 0; i < 21; i++) {
            PIND = _BV(PD2);    // toggle pin
            if (bitstream & 0x100000)
                delayMicroseconds(566);
            else
                delayMicroseconds(283);
            bitstream <<= 1;
        }
        PORTD &= ~_BV(PD2); // last LOW
    }

    void loop() {
        for (uint16_t code = 0; code < 0x2000; code++) {
            pulsetrain(code);
        }
    }


message:
Electronically, should single or several ground pins be used?

I have heard two theories of grounding: pretty much ground a board at single point, or ground everything in sight.

With the Mini Pro, is it better to provide one source of ground through the Gnd pin next to the Vraw pin, or ground with multiple Gnd pins on the board?

body:
There are times when you want a single ground point (*star* grounding), separate grounds with filters (separate analog and digital grounds, for instance), or you just don't care (99% of the time).

Regardless, this is usually a concern when you are laying out a circuit on a PCB. When you already have a PCB the grounds become a moot point because the PCB dictates how they operate.

For a module like an Arduino, unless otherwise stated, all grounds are equal and can be used for whatever whenever.


message:
Set pins to LOW over time

I've written a simple sketch that adds threshold to an PIR sensor. If the PIR sensor sends 3 `HIGH` ex. `HIGH`...`LOW`...`HIGH`...`LOW`...`HIGH` (The `LOW` == no movement) it will trigger and alarm.

I want to reset the counter of `HIGH`s if there's no movement detected. The problem is the `loop` will get delayed if I put it inline. My code: (Don't mind my code, I'm pretty newbie)

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

    int calibrationTime = 30;
    int pirPin = 5;
    int ledPin = 6;
    int sensorState;
    int stateCount = 0; //How much movement is detected
    int stateThreshold = 3; //THRESHOLD
    bool isSensorHigh;

    void setup() {
      Serial.begin(9600);
      pinMode(pirPin, INPUT);
      pinMode(ledPin, OUTPUT);
      pinMode(2, OUTPUT);
      pinMode(3, OUTPUT);
      pinMode(4, OUTPUT);
      digitalWrite(pirPin, LOW);
      Serial.print("calibrating sensor ");
      for (calibrationTime; calibrationTime > 0; calibrationTime--) {
        Serial.print(calibrationTime);
        delay(1000);
      }
      Serial.println(" done");
      Serial.println("SENSOR ACTIVE");
      delay(50);
    }
    void loop() {
      sensorState = digitalRead(pirPin);
      //Serial.println(sensorState);
      if (sensorState == 1) {
        isSensorHigh = true;
      }
      if (sensorState == 0 && isSensorHigh == true) {
        isSensorHigh = false;
        stateCount++;
      }
      //Set pins 2,3,4 here to LOW if there's no movement detected over time
      if (stateThreshold == 3) {
        switch (stateCount) {
          case 1:
            digitalWrite(2, HIGH);
            break;
          case 2:
            digitalWrite(3, HIGH);
            break;
          case 3:
            digitalWrite(4, HIGH);
            break;
        }
      }
      if (stateCount == stateThreshold) {
        blinkLeds();
        delay(3000);
        digitalWrite(2, LOW);
        digitalWrite(3, LOW);
        digitalWrite(4, LOW);
        digitalWrite(ledPin, LOW);
        stateCount = 0;
      }
      Serial.println(stateCount);
      delay(150);
    }

    void blinkLeds() {
      for (int x = 4; x > 0; x--) {
        digitalWrite(2, HIGH);
        digitalWrite(3, HIGH);
        digitalWrite(4, HIGH);
        delay(1000);
        digitalWrite(2, LOW);
        digitalWrite(3, LOW);
        digitalWrite(4, LOW);
        delay(1000);
      }
    }

body:
Use millis() instead on delay.
Ref: https://www.arduino.cc/en/reference/millis


message:
Arduino stops loop randomly whenever a button is pressed

I'm having a problem with this Arduino code.

So whenever I press the "button" in port 11, which is supposed to either reset the burglar alarm or stop it, the whole program stops (the void loop() function stops). The wiring is most likely not the problem, because I've tested it on multiple occasions with different codes. The button, too, works perfectly well as a button with different codes.

In the Serial port, it keeps printing "78005", which it should before the button is pressed, until when I press the button, at which it randomly breaks off printing (resulting in 78, 780, 7, 7800, or 78005 as the last line printed).

Can anyone explain why the arduino will behave in this way?

Thank you so much.

    int button = 11;
    int receiver = 12;
    int buzzer = 13;
    int frequency = 1000; // frequency of buzzer

    bool keepAlerting = false; // toggles Alarm regardless of detected charge
    int receiverVal = LOW; // value from port 12
    int buttonVal = LOW; // value from button
    int oldButtonVal = LOW;

    int setupTime = 5000; // time the user has to close the box after toggling alarm

    bool alarmOn;
    int buttonMode = 0;
    const int resetButton = 1;
    const int stopButton = 2;
    int buttonModeDecider = 0;

    void setup() {
      // put your setup code here, to run once:
      pinMode(buzzer, OUTPUT);
      pinMode(receiver, INPUT);
      pinMode(button, INPUT);
      Serial.begin(9600);

      noTone(buzzer);
    }

    void loop() {
      // put your main code here, to run repeatedly:
      Serial.print("7");
      receiverVal = digitalRead(receiver);
      buttonVal = digitalRead(button);
      Serial.print("8");

      if(alarmOn == true){
        Serial.print("6");
        setAlarm();
      }

      Serial.print(buttonVal);
      Serial.print(oldButtonVal);

      if(buttonVal == HIGH && oldButtonVal == LOW){
        buttonModeDecider = 1 - buttonModeDecider;
        Serial.print("Toggled");

        if(buttonModeDecider == 1){
          buttonMode = resetButton;
          Serial.print("1");
        } else {
          buttonMode = stopButton;
          Serial.print("2");
        }

        switch(buttonMode) {
          case resetButton:
          {
            delay(setupTime);
            alarmOn = true;
            break;
            Serial.print("3");
          }
          case stopButton:
          {
            alarmOn = false;
            Serial.print("4");
          }
        }
      }
      Serial.println("5");
      oldButtonVal = buttonVal;
    }

    void setAlarm() {
      if(receiverVal == LOW || keepAlerting == true) {
        tone(buzzer, frequency);
        keepAlerting = true;
      }
    }

body:
A 10 Ohm resistor when switched to ground can cause the power supply to drop below the operating voltage of the Arduino. If you mean to have a pulldown resistor to ground use a 10K value instead.

Note that a 10 Ohm resistor across a 5V supply draws 0.5 Amps of current.


body:
> Arduino stops loop randomly whenever a button is pressed

your button is shorting the supply?


message:
Change select pin of USB Host library

### TL;DR

With regards to the [USB host library][3]:

 - Which is the correct file to modify the Arduino pin used for the USB Host slave select (SS) line?

----

I would like to add USB host functionality, to a particular Arduino setup, whilst, also, being able to use an Ethernet/SD (or just SD) shield.

As both the Ethernet shield and USB Host shield use pin 10 to select the W5500 and MAX3421E respectively1, obviously I can not use a standard USB Host shield. However, I could employ one of the small form factor boards, such as the [USB Host Shield 2.0 Arduino UNO MEGA ADK Compatible Google Android ADK][1] which I found on eBay:

[![USB Host shield][2]][2]

As this board is not in the usual shield "shape", one would not be constrained by which pin to connected to which MAX3421E input/output, in particular the chip select (SS) input. So, one could use a pin (or pins) that is not reserved by the Ethernet shield.

*However*, it does not appear to be possible to simply specify the "select pin" (i.e. the Arduino pin connected to the SS line) when using the [USB Host shield library][3] (or any of the pins used by the library), in `setup()`.

Therefore, I wondered if it was possible to modify the library, so that the pin used to select the USB/MAX3421E could be changed, either by:

 - "Hardcoding" a *different* "select" pin number into a header file;
 - Adding an argument to the `Init()` method, or;
 - Adding a method to the `USB` class, such as `Usb.DefineSelect()`.

The latter two options, I could work through, given the time. However, as a quick and dirty hack, where would I hardcode in a change from pin 10 to a pin of my choosing? Does anyone know? Has anyone had to do this?

-----

### Nitty-gritty

I have had a look through the library to see where pin 10 is defined as the chip select, and [avrpins.h][4] looked like a possible candidate for modification, although it would be rather "rude" (for want of a better word) and probably mess up the other boards.

[usbhost.h][5] seems a much better proposition. Looking at usbhost.h, the [lines 88-91][6]:

    #if defined(__AVR_ATmega1280__) || (__AVR_ATmega2560__) || defined(__AVR_ATmega32U4__) || defined(__AVR_AT90USB646__) || defined(__AVR_AT90USB1286__)
    typedef SPi< Pb1, Pb2, Pb3, Pb0 > spi;
    #elif  defined(__AVR_ATmega168__) || defined(__AVR_ATmega328P__)
    typedef SPi< Pb5, Pb3, Pb4, Pb2 > spi;

Looking at the statement

    typedef SPi< Pb5, Pb3, Pb4, Pb2 > spi;

the last argument appears to be the pin used for *select*. For the Uno (ATmega328P), in avrpins.h ([line 535][7]) `Pb2` is `P10` (pin 10), so I could substitute `Pb2` for some other pin definition, i.e. `Pd5` for `P5` (pin 5) ([line 529][8] in avrpins.h).

However, what I don't understand is that for the statement

    typedef SPi< Pb1, Pb2, Pb3, Pb0 > spi;

which deals with the Mega (ATmega2560), in avrpins.h ([line 512][9]) `Pb0`is `P53` (pin 53). As `Pb4` is actually `P10` (pin 10) ([line 466][10]), why is `Pb0` en lieu of `Pb4` used? That doesn't tie up with the fact that Pin 10 is used for both the Uno and Mega boards. It seems to suggest the pin 10 is used on the Uno and pin 53 is used on the Mega. Unless I have misinterpreted the `typedef`.

------

### Footnote

1 For the USB host shield, from [Arduino USB Host Shield][11]

> Arduino communicates with the MAX3421E using the SPI bus (through the
> ICSP header). This is on digital pins 10, 11, 12, and 13 on the Uno
> and pins 10, 50, 51, and 52 on the Mega. On both boards, pin 10 is
> used to select the MAX3421E. Pins 7, 8 and 9 are used for GPX, INT and
> RES pins.

The key piece of information here is that pin 10 is used by *both* the Uno and Mega boards.

For the Ethernet shield, from [Arduino Ethernet Shield V2][12]

> Arduino communicates with both the W5500 and SD card using the SPI bus
> (through the ICSP header). This is on digital pins 10, 11, 12, and 13
> on the Uno and pins 50, 51, and 52 on the Mega. On both boards, pin 10
> is used to select the W5500 and pin 4 for the SD card. These pins
> cannot be used for general I/O. On the Mega, the hardware SS pin, 53,
> is not used to select either the W5500 or the SD card, but it must be
> kept as an output or the SPI interface won't work.
>
> Note that because the W5500 and SD card share the SPI bus, only one at
> a time can be active. If you are using both peripherals in your
> program, this should be taken care of by the corresponding libraries.
> If you're not using one of the peripherals in your program, however,
> you'll need to explicitly deselect it. To do this with the SD card,
> set pin 4 as an output and write a high to it. For the W5500, set
> digital pin 10 as a high output.

Here, yet again, the key piece of information here is that pin 10 is used by *both* the Uno and Mega boards to select the Ethernet.

  [1]: http://www.ebay.co.uk/itm/182052269837
  [2]: https://i.stack.imgur.com/QVuZN.jpg
  [3]: https://github.com/felis/USB_Host_Shield_2.0
  [4]: https://github.com/felis/USB_Host_Shield_2.0/blob/master/avrpins.h
  [5]: https://github.com/felis/USB_Host_Shield_2.0/blob/master/usbhost.h
  [6]: https://github.com/felis/USB_Host_Shield_2.0/blob/master/usbhost.h#L88
  [7]: https://github.com/felis/USB_Host_Shield_2.0/blob/master/avrpins.h#L535
  [8]: https://github.com/felis/USB_Host_Shield_2.0/blob/master/avrpins.h#L529
  [9]: https://github.com/felis/USB_Host_Shield_2.0/blob/master/avrpins.h#L512
  [10]: https://github.com/felis/USB_Host_Shield_2.0/blob/master/avrpins.h#L466
  [11]: https://www.arduino.cc/en/Main/ArduinoUSBHostShield
  [12]: https://www.arduino.cc/en/Main/ArduinoEthernetShield

body:
In order to change the Arduino pin used to select the USB Host board, in order words, where the device's SS line is assigned to an Arduino pin (with the Arduino as the SPI Master and the USB host is the SPI slave), the line to change is at [line 43 in `UsbCore.h`](https://github.com/felis/USB_Host_Shield_2.0/blob/master/UsbCore.h#L43):

    typedef MAX3421e<P10, P9> MAX3421E; // Official Arduinos (UNO, Duemilanove, Mega, 2560, Leonardo, Due etc.), Intel Edison, Intel Galileo 2 or Teensy 2.0 and 3.x

So to use pin 5, for example, en lieu of pin 10, the line would become:

    typedef MAX3421e<P5, P9> MAX3421E; // Official Arduinos (UNO, Duemilanove, Mega, 2560, Leonardo, Due etc.), Intel Edison, Intel Galileo 2 or Teensy 2.0 and 3.x

The clue was in the comment on [line 27 in `UsbCore.h`](https://github.com/felis/USB_Host_Shield_2.0/blob/master/UsbCore.h#L27)

    /* shield pins. First parameter - SS pin, second parameter - INT pin */

With this suggested modification to the code, Pin 5 would go to the USB Host SS line and then there would be no conflict with the Ethernet board that uses Pin 10 for its SS line.

-------
This issue, I have subsequently discovered, is covered by the [USB Host Shield Hardware Manual][1], under the **Interface modifications** section. I guess I should have just read the manual first! RTFM...

-------
###Clarification of the issue

I must be honest that my question was somewhat confused. After having read the [SPI library][2], it states that

> **Note about Slave Select (SS) pin on AVR based boards**
>
> All AVR based boards have an SS pin that is useful when they act as a
> slave controlled by an external master. Since this library supports
> only master mode, this pin should be set always as OUTPUT otherwise
> the SPI interface could be put automatically into slave mode by
> hardware, rendering the library inoperative.
>
> It is, however, possible to use any pin as the Slave Select (SS) for
> the devices. For example, the Arduino Ethernet shield uses pin 4 to
> control the SPI connection to the on-board SD card, and pin 10 to
> control the connection to the Ethernet controller.

With respect to the first paragraph, the Uno uses pin 10 and Mega uses pin 53 as the Arduino SS line - so that must be set as an output in order for the Arduino to be the Master. Are realising this as being my source of confusion, it became apparent that the `typedef` statements, in `usbhost.h`, were _not_ where I should have been looking to change the device's Slave Select pin.

With respect to the second paragraph,  I want to use pin 5 (for example) to control the Slave Select (SS) for the USB Host device, instead of the default pin 10.

  [1]: https://www.circuitsathome.com/usb-host-shield-hardware-manual/
  [2]: https://www.arduino.cc/en/reference/SPI


message:
How to detect pinout at run-time

Is it possible to query the **pin-out** and each pin's attributes at *run-time* with Arduino?

If not, can it be done at compile-time?

Finally, if not, how can I incorporate this kind of information into my project to avoid completely rewriting my program for each possible Arduino model?

I am looking for something like this:

    PinProperties props= getPinProperties(pinNumber);

    props.supportsDigitalInput();
    props.supportsDigitalOutput();
    props.supportsAnalogInput();
    props.supportsAnalogOutput();
    props.supportsPWM();
    props.analogInputBits();
    props.analogOutputBits();
    props.pullupResistance();
    props.pulldownResistance();

etc.

NOTE: [This question][1] is similar and I might use the board model to look up a pre-stored pin-out.

  [1]: https://electronics.stackexchange.com/questions/58386/how-can-i-detect-which-arduino-board-or-which-controller-in-software

body:
There is no strong relation with pin numbering and the hardware as far as I know.

To be more specific, the datasheet tells you what registers can be used for what functions. The microcontroller does not neccesarily know what registers it has or what functionality it's registers have.

You could make your own library or class for a pin.

I would go by something like:

    Pin input1 = new Pin(.....);

    if(input1.isAnalog()){
       input1.setupAnalog();
    }

    if(input1.analogIsReady()){
       input1.readAnalog();
    }

Instead of having a "pinproperties" object for a pin.

You'll have to look how you want to make the class.
You can create one single class that has all functions and just checks if there is an implementation for that pin.

You may go by classes like:

    class pin

    class analogPin extends pin

    class pwmPin extends pin

However, this may fail if your analog pin doesn't support the regular "pin" functions (like I/O).

Theoretically you could use C++'s multiple inheritance to inherit things as I/O, PWM and Analog, but I've heard that it doesn't perform very well on embedded targets.

----------

Alternatively you could make a list of pins that support PWM. And a list of pins that support Analog. And a list of pins that support I/O.

When a person (runtime) tries to set a pin's state, you can check if that pin supports I/O, but I'm not sure what behaviour you'll expect if one tries to set a pin that doesn't support that option.


body:
> Finally, if not, how can I incorporate this kind of information into my project to avoid completely rewriting my program for each possible Arduino model?

The libraries are designed so that you don't really need to know that. One issue is the relationship between the chip pins and the board pins. Just as an example, pin 19 on the Atmega328P goes to the *board* pin 13 (digital pin 13) on a Uno.

If your program needs a couple of digital inputs and a couple of digital outputs, you could use (say) D2 and D3 as inputs and D4 and D5 as outputs. Then let the underlying libraries work out which chip pin that is, and configure it correctly when you use `digitalRead`, `digitalWrite` and `pinMode`.

You can self-query for the chip type (for example [here](https://www.gammon.com.au/forum/?id=11633&reply=2#reply2)) however that doesn't tell you what board the chip is mounted on.

---

> to avoid completely rewriting my program for each possible Arduino model

What are you envisaging that would require a *complete rewrite*? Many libraries and projects are written to work on multiple boards with only minor changes (if any). You can detect the processor type at compile-time.

I simply don't see where "complete rewrite" comes into it. Use functions to abstract out the parts that interface with pins (as `digitalRead`, `digitalWrite` and `pinMode` **already do**) and a few constants at the start of the code to indicate which pins you have chosen for this particular board.


body:
pins_arduino.h has some standard macros that can be used for some of what you're looking to do. Using the `arduino:standard` variant used by Uno for example:

https://github.com/arduino/Arduino/blob/1.8.1/hardware/arduino/avr/variants/standard/pins_arduino.h#L35:

    #define digitalPinHasPWM(p) ((p) == 3 || (p) == 5 || (p) == 6 || (p) == 9 || (p) == 10 || (p) == 11)

Or if you want to use your naming scheme:

    #define supportsPWM(p) digitalPinHasPWM(p)

After that it gets a bit more sketchy:

https://github.com/arduino/Arduino/blob/1.8.1/hardware/arduino/avr/variants/standard/pins_arduino.h#L28

    #define NUM_DIGITAL_PINS 20

So, assuming that Arduino digital pins will always be numbered consecutively from 0 and any pin that supports digital input also supports digital output(which is the case in any variant I'm familiar with), you could use that to write some macros:

    #define supportsDigitalInput(p) ((p) < NUM_DIGITAL_PINS)
    #define supportsDigitalOutput(p) supportsDigitalInput(p)

https://github.com/arduino/Arduino/blob/1.8.1/hardware/arduino/avr/variants/standard/pins_arduino.h#L29

    #define NUM_ANALOG_INPUTS 6

Could be used to write this macro(with numbering assumption):

    #define supportsAnalogInput(p) ((p) < NUM_ANALOG_INPUTS)

Note that this will not work for the `An` analog pin names(e.g. `A0` vs `0`).

As for:

    props.supportsAnalogOutput();
    props.analogInputBits();
    props.analogOutputBits();
    props.pullupResistance();
    props.pulldownResistance();

I'm don't know of pre-existing code for those. There is probably a way to get it for the first three in an architecture specific manner. The last two you'd most likely need to get the information from datasheets for all of your target microcontrollers and define then using processor specific macros.


message:
How safe is it to use my body as part of a circuit?

I have two polystyrene balls wrapped in copper tape. When the balls touch, the tape completes a circuit from a digital pin on an Arduino inside one of the balls to an Arduino inside the other (both powered by 9v batteries). This allows them to send information to each other via the copper tape path.

I was testing the balls out, and they were working too well. Even when the balls weren't quite touching, the signal was getting through! Turns out that's because the signals were travelling via my body. Even if I held one ball in one hand and the other ball in the other hand, digital reads on one Arduino were correctly reading the digital writes from the other.

This is actually great for my project!... unless it's not safe. So I'm looking for two things:

1. A reliable reference on what is and isn't safe in terms of voltage/wattage/amperage travelling from hand to hand.

2. A second opinion on the voltage/wattage/amperage that two Arduinos will actually pump through me (from digital pin to digital pin).

body:
If you are talking about running at 5V, then I doubt there is any safety issue. After all, 9V batteries (the sort you put in your smoke detector) just have bare terminals and no-one tells you not to touch them.

There is quite a bit of related information at [How much voltage is “dangerous”?](https://electronics.stackexchange.com/questions/19103/how-much-voltage-is-dangerous). That link seems to have enough information that there isn't a lot of point of repeating it all here.

There is a reference on that page to someone holding a metal pole connected to a 12V battery wading through water which completed the circuit and he was unable to let go of the pole. But that is **12V** (more than twice 5V) and in circumstances where there was good conduction (his body was wet).

---

In the interests of science I set up a small test. I connected myself to a 5V lab supply via an ammeter. I grasped the terminals firmly (with dry hands) and measured about 3 µA of current. From the page I referenced above there seems to be a consensus that 1 mA would be just noticeable, so this is about 300 times less.

I found if I wet my fingers I got up to about 20 µA of current, still a lot less than 1 mA.

That page mentions that 60V is getting into the range where you might get a shock.

---

Hopefully it goes without saying that if you are going to touch metal balls then you need to be certain that 5V is the maximum, and that some sort of failure in a power supply might not deliver a lot more. But if the balls are battery powered you should be pretty safe.

---

You've added that they are powered by 9V batteries. That doesn't change my answer much. The most that could "escape" due to some malfunction is then 9V. Under normal operation you would have 5V from a digital output pin.

I measured my body resistance as being around 1.5 MΩ, which is consistent with getting 3 µA of current through it.

    I = V / R
    I = 5 / 1500000 = 0.000003 A


body:
In fact the voltage is almost irrelevant. The current is the issue. 30mA is normally considered the limit - this is the value [RCD](https://en.wikipedia.org/wiki/Residual-current_device) are set to trigger at.

Even low voltages applied to intimate places can be fatal. (I have a couple of wires in my heart, these can certainly cause a significant impact).

There is little risk with the low energy available, but if you want to be safe you can use a series resistor. I have (a very early) touch sensor installed on lights in my house. The touch pad is effectively connected to 240V, but is quite safe as the pad is connected through 2 10MΩ resistors. (2 are needed as they are rated at 500V.)


message:
String use in arduino IDE (this question for understanding)

I'm using arduino several month now, And i don't understand when i can use the arduino object of String. I'll explain, I read a lot and the it's look like that this object is a good way to read/write and use strings, But everywhere they say that this object take a lot of RAM. So i made some project, And almost in all of them the String object not work as i expected. When i check the RAM in my projects i see that when my usage of RAM is greater then 65% the string object start to do problems. Because of this i stop use the string object and use only char arrays.

So my question is:

 - How can i know when i can use String from the beginning?
 - there is a way to change from char array to string or vase versa easily (i know this is completely different logic)?
 - How can i avoid the memory problems with the String object?

All this questions come from that the String object is very effective and easy to use and i want to use it, But i'm fear from RAM problems so i'm not using it.

Thank you very much for reading all this, Hope you can help me!

body:
String objects are simple to use. There is a trade-off for simplicity. Strings work by using dynamic memory allocation. Something like this for example:

    String foo;
    ...
    foo += 'a';

By adding one character to a string the class has to allocate new memory for the slightly longer string. If you keep doing this you get memory fragmentation.

You are probably better off deciding what your maximum size string is and making that a static array of characters.

---

### So should I use the String objects?

For occasional use they are fine (for example, holding the name of something). They tend to fall down once you start with a small String and keep adding to it, because the code has to dynamically allocate memory, allocating (say) 5 bytes, then 6 bytes, then 7 bytes, and in the process freeing up the original 5 bytes, then 6 bytes and so on. This allocating/freeing process can leave holes in the "heap" causing a thing known as memory fragmentation.

Done to excess you can run out of memory. That is, you might need 100 bytes but have 10 lots of 10 bytes free, with stuff in-between that isn't free.

You don't have lots of memory to start with, so it is probably better, faster and more efficient to decide the largest amount you need for some string, and just make that a character array.


message:
Is there a way to "list" (in BASIC, or "cat" in LINUX) the current sketch loaded in my xxxDUINO?

I was surprised when I couldn't find an old post where someone asked this question. Seems like a natural beginner, uh excuse me, "newbie" question, but then I'm a throw-back to the days when a home computer came with 3,583 bytes (three-thousand, five-hundred eighty-three). So again, as seen in the title, can I "list" my sketch? I'm pretty sure the answer is NO since if it were a good question someone would have asked it already. It just strikes me as odd that my old VIC-20 could do something this phenomenal techno-marvel can't. Not much of an accomplishment for the dinosaurs, but HEY! We're on the scoreboard now! [nothing's worse than that miserable goose-egg :(   ]

body:
No. the code burned in an Arduino is compiled not interpreted like Basic.

Basically your C language sketch is compiled into AVR assembly language. The resulting hexadecimal is what is burned to the Arduino.

Yes you could disassemble the hex like we used to do in the good old days, but as before it is highly unpredictable and most of the time not very useful.

Just a quick example. The following simple Arduino sketch that just sets a pin in output and then sets it HIGH:

    void setup() {
      pinMode(13, OUTPUT);
      digitalWrite(13, HIGH);
    }

    void loop() {
    }

The resulting hex file is 3.5Kb.This include various sections of data and code. One would have to analyse the section, convert the hex (op-code) to assembly language and find which part correspond to the C code.

It is possible, and there are probably tools that do a fairly good job. Would the C language generated by the decompilation once recompile perform exactly like the original compiled cole. I doubt it.


message:
How to burn bootloader/program an ATMega 328P with an external crystal 8 MHz oscilator?

I need to program a ATMega328P on a breadboard, running on an external crystal at 8 MHz.

All of the guides I can find either use the arduino environment and describe a 16 MHz config, or using the 8 MHz internal oscillator - which is too inaccurate for this project.

How do I do this?  Configure the chip to run at 8 MHz and upload the program?

body:
myself as of 3 hours ago.

 1. Get an arduino or similar, install the ArduinoISP sketch
 2. Connect the two as described [here][1].
 3. Change the board to Arduino Pro or Pro Mini, Processor to 3.3V, 8Mhz, Programmer: Arduino as ISP
 4. Hit burn bootloader button
 5. Load up the sketch that you want on the device
 6. Without changing anything, use "Upload using programmer"
 7. Remove arduino, fix wiring changes required to use as programmer

Committed to Electronics Stackexchange  for posterity.  Or so I can find it when I forget next time...

  [1]: https://www.arduino.cc/en/Tutorial/ArduinoToBreadboard


message:
Wireless Sensor communication with 100Hz rate

I'm doing my project on haptic feedback systems. I need a 56bits of data transmitted over wirelessly to a computer to process and send the output to another arduino. I tried ESP8266 using TCP/IP protocol. But it is very slow. Are there any faster modules to do the above task with 100hz speed?

body:
Make one static tcp connection with a regular check and on error event to restore it in case it drops. Tcp must be able to run data at your rate.
If not, maybe the main arduino loop has delays in it.


message:
Avrdude fails to verify after upload

I'm using the most recent Arduino IDE to upload a sketch to an Arduino Uno, and the upload seems to succeed, but the final verification step fails with the error:

    avrdude: AVR device initialized and ready to accept instructions

    Reading | ################################################## | 100% 0.00s

    avrdude: Device signature = 0x1e950f
    avrdude: reading input file ".build_ano/uno/firmware.hex"
    avrdude: writing flash (30908 bytes):

    Writing | ################################################## | 100% 5.01s

    avrdude: 30908 bytes of flash written
    avrdude: verifying flash memory against .build_ano/uno/firmware.hex:
    avrdude: load data flash data from input file .build_ano/uno/firmware.hex:
    avrdude: input file .build_ano/uno/firmware.hex contains 30908 bytes
    avrdude: reading on-chip flash data:

    Reading | ################################################## | 100% 3.96s

    avrdude: verifying ...
    avrdude: verification error, first mismatch at byte 0x7800
             0xff != 0xfe
    avrdude: verification error; content mismatch

    avrdude: safemode: Fuses OK (H:00, E:00, L:00)

    avrdude done.  Thank you.

I've re-ran the upload several times, and tried different USB cables, but I get the exact same verification error each time. Does this mean the upload effectively failed (presumably because the flash memory has gone bad), and that my sketch is not running on the Arduino? Is there any way I can fix this?

I tried uploading to a different Arduino Uno, and I received the exact same error.

body:
So here is my official answer ;-)

Your sketch goes above the 30k flash available on the Arduino Uno.

Yes the Uno has 32k of flash, but 2k is used for the Arduino bootloader. if you convert 0x7800 in decimal that gives you 30720 which is exactly 30k. And your sketch is 30908 bytes so it's 188 bytes too long.

Try optimizing it.

A second alternative would be to use the Optiboot bootloader replacement (https://github.com/Optiboot/optiboot) which only uses 512 bytes.


message:
Is it possible to have an Adafruit music maker shield and a sensor connected to the same Arduino?

Are the analog I/O pins on the Arduino still available for sensors when there is an Adafruit Music Maker shield attached to it? I want to play a sound file, but only when a PIR sensor senses motion.

body:
If you look at the PCB of the Adafruit Music Maker here:

https://learn.adafruit.com/assets/16643

You can see that there are no connections on the analog I/O of the Arduino.


message:
Multi-LED Toggle Switch

I am using a Python3 GUI on my RPi3 to control my DFRobot Bluno Mega 2560 via USB.  The Mega is hooked up to a breadboard with 4 LED's and I am trying to control each LED with their own toggle switch.  I was able to do this with one LED but for some reason when I try to achieve the same with more than one it doesn't work, I get absolutely no response from the LED's whatsoever.  It is something to do with how the arduino is receiving the ASCII code, or I think it may be a problem with how I am implementing tkinter as I have little experience with it.  If anyone can tell me what I am doing wrong please let me know.

Here is the Python3 GUI code:

    import serial # import the serial library
    import time # import the time library
    from tkinter import * #import Tkinter GUI library

    def toggleRed():
        if redBtn.config('relief')[-1] == 'sunken':
            redBtn.config(relief="raised")
            arduino.write('a'.encode())
        else:
            redBtn.config(relief="sunken")
            arduino.write('b'.encode())

    def toggleGreen():
        if greenBtn.config('relief')[-1] == 'sunken':
            greenBtn.config(relief="raised")
            arduino.write('c'.encode())
        else:
            greenBtn.config(relief="sunken")
            arduino.write('d'.encode())

    def toggleBlue():
        if blueBtn.config('relief')[-1] == 'sunken':
            blueBtn.config(relief="raised")
            arduino.write('e'.encode())
        else:
            blueBtn.config(relief="sunken")
            arduino.write('f'.encode())

    def toggleYellow():
        if yellowBtn.config('relief')[-1] == 'sunken':
            yellowBtn.config(relief="raised")
            arduino.write('g'.encode())
        else:
            yellowBtn.config(relief="sunken")
            arduino.write('h'.encode())

    print ('Connecting...')
    arduino = serial.Serial("/dev/ttyACM0", 9600)
    time.sleep(3)
    print ('Connection established successfully')

    appWindow = Tk() # creates the application window (you can use any name)
    appWindow.wm_title("RGB LED Control") # displays title at the top left
    appWindow.config(bg ="#037481")

    mainFrame = Frame(appWindow, bg="#037481") #define the main frame of the GUI
    mainFrame.grid() #grid the frame into the App Window

    btnFrame = Frame(mainFrame, bg="#037481") #define the frame within the main frame that holds buttons
    btnFrame.grid() #grid the frame into the main frame

    redBtn = Button(btnFrame, text="RED", width=12, bg="red", relief="raised", command=toggleRed)
    redBtn.grid(column=0,row=0,sticky='EW')

    greenBtn = Button(btnFrame, text="GREEN", width=12, bg="green", relief="raised", command=toggleGreen)
    greenBtn.grid(column=0,row=1,sticky='EW')

    blueBtn = Button(btnFrame, text="BLUE", width=12, bg="blue", relief="raised", command=toggleBlue)
    blueBtn.grid(column=0,row=2,sticky='EW')

    yellowBtn = Button(btnFrame, text="YELLOW", width=12, bg="yellow", relief="raised", command=toggleYellow)
    yellowBtn.grid(column=0,row=3,sticky='EW')

    appWindow.mainloop()# begins main loop

Here is the arduino code:

    int ledRed = 13;
    int ledGreen = 11;
    int ledBlue = 9;
    int ledYellow = 7;

    //int ledRedStatus;
    //int ledGreenStatus;
    //int ledBlueStatus;
    //int ledYellowStatus;

    void setup() {
      pinMode(ledRed, OUTPUT);
      pinMode(ledGreen, OUTPUT);
      pinMode(ledBlue, OUTPUT);
      pinMode(ledYellow, OUTPUT);
      Serial.begin(9600);
    }
    void loop() {
      if(Serial.available() == '97') {
        digitalWrite(ledRed, LOW);
      }
      if(Serial.available() == '98') {
        digitalWrite(ledRed, HIGH);
      }
      if(Serial.available() == '99') {
        digitalWrite(ledGreen, LOW);
      }
      if(Serial.available() == '100') {
        digitalWrite(ledGreen, HIGH);
      }
      if(Serial.available() == '101') {
        digitalWrite(ledBlue, LOW);
      }
      if(Serial.available() == '102') {
        digitalWrite(ledBlue, HIGH);
      }
      if(Serial.available() == '103') {
        digitalWrite(ledYellow, LOW);
      }
      if(Serial.available() == '104') {
        digitalWrite(ledYellow, HIGH);
      }
    }

body:
Adding comments to your code would help us understand your intentions.

It is assumed you are sending the ASCII values for 'a', 'b', 'c', ... for different buttons and their actions.  And that you want to receive these on an Arduino over the USB using the USB serial port protocol. It is also assumed that your Python script works and the Linux OS is creating a /dev/ttyACM0 or some such serial device when you plug in your Arduino.

Looking at your Arduino code we see you are only checking for the number of bytes in the Arduino's serial port receive buffer by using the [Serial.available()][1] method call.  If your intentions were to read a byte of data you would instead call the [serial.read()][2] method.

It is suggested that you check if there is any data available and if there is you would read it once and save it to a variable. Then you can check this variable many times and decide what action to take based on its value.  If you read the buffer many times you would be pulling a new byte of data from the buffer with each read.  If you run out of data to read you will be supplied with the value of -1 as an indication there is no more data.

  [1]: https://cdn.arduino.cc/reference/en/language/functions/communication/serial/available/
  [2]: https://www.arduino.cc/en/Serial/Read


body:
      if(Serial.available() == '97')

Make sure the comparison is actually valid and Serial.available() does what you think it does. If you wish to read a value from serial port, .available() doesn't seem to be the right function for that.


message:
Using both a stepper motor and a DC motor with Arduino motor shield R3

We are trying to reprogram a remote control car with an Arduino Uno. This car runs the power with a DC motor, and it controls steering using a stepper motor.

We have the Motor Shield R3 attached to the Arduino, but it has just now occurred to us that we can't support both motors with the motor shield (as the motor shield only allows for two DC motors or one stepper motor). Is there a way to somehow work around this? Or is it possible that we would need to replace the stepper motor with DC?

body:
You are right: Motor Shield R3 can drive two DC motors or one step motor.
 So, there are 2 (maybe  3) solutions:

1. Have another shield - now you can drive 2 step motors, or one DC motor(using 'half' of shield, and one step motor using another whole shield.

2. Replace your step motors with DC motor. This option can be more complicated, as no precise position control will be possible when you try to use DC motor for steering. (DC motor are hard to select and hold position, when stepper motors are quite easy to 'go to certain position' AND 'hold'). There is also good mechanical skill needed to remove/place it precisely.

optional option 3. Instead of Motor Shield R3 you can try to use cheap Easy Driver to drive your step motor.


message:
SocketIO Arduino TCP Port ISSUE

Initially I was sending sensor data to NodeJS using socketIO and this worked perfectly. I had to add a function to control an RGB LED using [this][1]. This also works but I'm unable to perform these two functions simultaneously.

I have tried to use two different ports on my Arduino. One to send data and another to control the LED but one overrides the other.

**Question:** Is there a way around this ? Is it practical to use two different ports?

**arduino sketch**

    if (client.connect(server, 4000)) {
        Serial.println("connected");
      }
      else {
        // if you didn't get a connection to the server:
        Serial.println("connection failed");
      }

      pinMode(pin, OUTPUT);
    }

    void loop()
    {

      //if you are connected and data is available
      if (client.available()) {
        char c = client.read();
       // Serial.print("Message is :  ");
        Serial.print(c);

        // '1' was received, return '1' for HIGH
        if (c == '1') {
          pinVal = HIGH;
        //  client.print("ON");
        }
        else if (c == '0') {
          pinVal = LOW;
        //  client.print("OFF");
        }

        //turn led pin to new position
        digitalWrite(pin, pinVal);

      }

    int chk = DHT.read11(DHT11_PIN);
      int t = DHT.temperature;
      int h = DHT.humidity;

              // send data to the server
            sendData(t, h);

      Serial.print("Temperature = ");
      Serial.print(t);
      Serial.print( "," );
      Serial.print("Humidity = ");
      Serial.print(h);
      Serial.print("\n");
       delay(6000);

    }

    void sendData(int temperature, int humidity)
    {
      if(!client.connected())
      {
        if (client.connect(server, 3000)) {

          Serial.println("Sending data...");
          // send the HTTP PUT request:
          client.print("GET /weatherserver/");
          client.print(temperature);
          client.print("/");
          client.print(humidity);
          client.print("/");

          client.println(" HTTP/1.1");
          client.println("Host: localhost");
          client.println("User-Agent: arduino-barom");
          client.println("Connection: close");
          client.println();
          client.stop();
        } else {
           Serial.println("Could not connect.");
           client.stop();
        }
      }
      delay(6000);
    }

  [1]: https://github.com/sergiomajluf/node-session/blob/master/socket/arduino/server-w-tcp.js

body:
I'm not sure what you are doing, but you seem to be using two different protocols on two different ports.  So does you server side code open two ports? and does it accept the two different protocols?

If I was you I would change the RGB control to use REST (like you are doing with the DHT)  So you would send something like `GET /RGB/<id>/<state>`.

I'm not sure how your temperature is arriving at the server since you have sent a GET command rather than a PUT command (this could be the bug you are looking for).


body:
I implemented a better solution differentiating the client as `EthernetClient clientA` & `EthernetClient clientB`
> Client A handles TCP port and Client B handles HTTP GET Request.


message:
Issue with Arduino Timing

I am working with an Arduino on a project for which timing is very important. I use TimerOne to trigger timer interrupts and use micros() for delays (delayMicroseconds() was causing problems worse than the one explained below). The program is sending a manual PWM signal to an LED and it is very important that the signal is sent with an error that is less than 8 microseconds (ideally, the signal is sent at the same time in each period). My test code is shown below:

    #include <TimerOne.h>
    #include <SPI.h>

    const int LED_PIN = 3;
    const int CHIP_SELECT = 12;

    const int PERIOD = 4000;
    const double DUTY_CYCLE = .5;
    const int HIGH_TIME = PERIOD * DUTY_CYCLE;
    const int LOW_TIME = PERIOD - HIGH_TIME;
    const int INITIAL_SIGNAL_DELAY = LOW_TIME / 2;
    const int HIGH_TIME_TOTAL_DELAY = INITIAL_SIGNAL_DELAY + HIGH_TIME;

    const int RESISTOR_VALUE = 255;

    boolean triggered = false;
    boolean data = false;

    unsigned long triggeredTime;
    unsigned long s;
    unsigned long e;

    boolean found;
    int i = 0;

    void setup()
    {
      s = micros();

      Timer1.initialize(PERIOD);
      Timer1.attachInterrupt(trigger);

      pinMode(LED_PIN, 3);
      pinMode(CHIP_SELECT, OUTPUT);

      SPI.begin();

      digitalWrite(CHIP_SELECT, LOW);
      SPI.transfer(B00010001);
      SPI.transfer(RESISTOR_VALUE);
      digitalWrite(CHIP_SELECT, HIGH);

      e = micros();

      Serial.begin(115200);
      Serial.print("s: ");
      Serial.println(s);
      Serial.print("e: ");
      Serial.println(e);
    }

    void loop()
    {
      if(triggered)
      {
        while(micros() - triggeredTime < INITIAL_SIGNAL_DELAY)
        { }
        s = micros();
        digitalWrite(LED_PIN, data);
        while(micros() - triggeredTime < HIGH_TIME_TOTAL_DELAY)
        { }
        digitalWrite(LED_PIN, LOW);

        data = !data;
        triggered = false;

        e = micros();
        //micros();

        if(s % 100 > 28 || s % 100 < 12)
        {
         found = true;
        }

        if(!found)
        {
          Serial.print("s: ");
          Serial.println(s);
        }
        else
        {
          Serial.print("ERROR: ");
          Serial.println(s);
        }
        //Serial.print("e: ");
        //Serial.println(e);
      }
    }

    void trigger()
    {
      triggeredTime = micros();
      triggered = true;
    }

(it should be noted that the first signal sent is always xx20, usually 5020).

So, with this code, I eventually get an error. I am not sure why, but this error occurs at the same point every single time:

    .
    .
    .
    s: 1141020
    s: 1145020
    s: 1149020
    ERROR: 1153032
    ERROR: 1157020
    ERROR: 1161020
    .
    .
    .

Now, the really weird part is if I remove the comments before micros() (the micros() right after e = micros()), there is no error (or at least there is not an error within the first 30 seconds). I was wondering if anybody could provide an explanation for why this happens. I have dedicated many hours trying to get the timing working properly and everything was working well until I encountered this error. Any help would be very much appreciated. Thank you!

body:
the code flow doesn't make a lot of sense to me. seems to me that you can simplified quite a bit.

>if(s % 100 > 28 || s % 100 < 12)

I would use a few brackets to make it clear to the compiler what you want it to do.


message:
Not getting proper readings on Arduino from MAP Sensor

In recent project, I have to take reading from MAP sensor. So basically, we used analog pin for this. But in my case, I don't get proper result which actually I want.

When I'm taking readings through multi-meter then I got proper readings. Means when I start the vehicle then it's show 0.99 V. When I provide full throttle then voltage also increase and it's reach to 1.66 V. And finally when suddenly come back to normal throttle then also voltage decrease around like 0.48 V and then within a second again show normal 0.99 V.

Here, when I'm taking readings from MAP sensor through multi-meter then I'm providing ground to multi-meter. And when I taking readings from MAP sensor through Arduino then I'm not providing any ground to Arduino. Because I think it may be damage my Arduino.

So, I think this is also one possibility and may be possible that's why I'm not getting that type of voltage output through Arduino.

Here, the ground which I provide to multi-meter is from 12V DC battery which is used in CNG Auto rickshaw. So, that's why I'm not providing ground to Arduino. So, give me some suggestions about this. What should I do for this. Providing ground to Arduino or not.

Here, it's my code.

    int kMAP1 = 0;
    float kMAP2 = 0;

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

    void loop()
    {
      kMAP1 = analogRead(A0);
      kMAP2 =  kMAP1 * (5.0 / 1023.0);

      Serial.print("MAP1: ");
      Serial.print(kMAP1);

      Serial.print("\t");

      Serial.print("      MAP2: ");
      Serial.println(kMAP2);

      delay(1000);
    }

And it's my serial monitor output.

    MAP1: 490       MAP2: 2.39
    MAP1: 433       MAP2: 2.12
    MAP1: 270       MAP2: 1.32
    MAP1: 0           MAP2: 0.00
    MAP1: 447       MAP2: 2.18
    MAP1: 401       MAP2: 1.96
    MAP1: 518       MAP2: 2.53
    MAP1: 487       MAP2: 2.38
    MAP1: 344       MAP2: 1.68
    MAP1: 374       MAP2: 1.83
    MAP1: 611       MAP2: 2.99
    MAP1: 429       MAP2: 2.10
    MAP1: 647       MAP2: 3.16
    MAP1: 668       MAP2: 3.26
    MAP1: 460       MAP2: 2.25
    MAP1: 489       MAP2: 2.39
    MAP1: 278       MAP2: 1.36
    MAP1: 277       MAP2: 1.35
    MAP1: 318       MAP2: 1.55
    MAP1: 383       MAP2: 1.87
    MAP1: 238       MAP2: 1.16
    MAP1: 237       MAP2: 1.16
    MAP1: 134       MAP2: 0.65
    MAP1: 191       MAP2: 0.93
    MAP1: 230       MAP2: 1.12
    MAP1: 308       MAP2: 1.51
    MAP1: 479       MAP2: 2.34
    MAP1: 388       MAP2: 1.90
    MAP1: 544       MAP2: 2.66
    MAP1: 518       MAP2: 2.53
    MAP1: 419       MAP2: 2.05
    MAP1: 544       MAP2: 2.66
    MAP1: 586       MAP2: 2.86
    MAP1: 544       MAP2: 2.66
    MAP1: 575       MAP2: 2.81
    MAP1: 184       MAP2: 0.90
    MAP1: 202       MAP2: 0.99
    MAP1: 883       MAP2: 4.32
    MAP1: 671       MAP2: 3.28
    MAP1: 884       MAP2: 4.32
    MAP1: 487       MAP2: 2.38
    MAP1: 403       MAP2: 1.97
    MAP1: 184       MAP2: 0.90
    MAP1: 426       MAP2: 2.08
    MAP1: 412       MAP2: 2.01
    MAP1: 428       MAP2: 2.09
    MAP1: 434       MAP2: 2.12
    MAP1: 420       MAP2: 2.05
    MAP1: 312       MAP2: 1.52
    MAP1: 414       MAP2: 2.02
    MAP1: 435       MAP2: 2.13
    MAP1: 405       MAP2: 1.98
    MAP1: 418       MAP2: 2.04
    MAP1: 515       MAP2: 2.52
    MAP1: 462       MAP2: 2.26
    MAP1: 578       MAP2: 2.83
    MAP1: 332       MAP2: 1.62
    MAP1: 330       MAP2: 1.61
    MAP1: 164       MAP2: 0.80
    MAP1: 425       MAP2: 2.08
    MAP1: 345       MAP2: 1.69
    MAP1: 226       MAP2: 1.10
    MAP1: 0           MAP2: 0.00
    MAP1: 97       MAP2: 0.47
    MAP1: 872       MAP2: 4.26
    MAP1: 55       MAP2: 0.27
    MAP1: 492       MAP2: 2.40
    MAP1: 531       MAP2: 2.60
    MAP1: 1023       MAP2: 5.00
    MAP1: 43       MAP2: 0.21
    MAP1: 6           MAP2: 0.03

body:
Although the circuit isn't shown and description isn't perfectly clear, evidently there is some question about how to connect up the various grounds.

Voltage, being “the difference in electric potential energy between two points per unit electric charge” [ref [Voltage article in Wikipedia](https://en.wikipedia.org/wiki/Voltage)], is measured between two points in an electric circuit.  If the two points are in unrelated and isolated circuits meaningful measurements can't be taken.

In typical [MAP sensor circuits](https://www.google.com/search?q=MAP+sensor+circuit&num=50&tbm=isch&tbo=u&source=univ&sa=X&ved=0ahUKEwiwipG7ucfRAhUH92MKHbzeC4oQsAQIGw&biw=1538&bih=804), the sensor output is relative to automotive ground, so your Uno's analog ground should be connected to automotive ground.  Whether this is electrically safe depends on several things:
• Sensor output voltage range – The multimeter readings showed a safe range.  The range is narrow compared to the Uno ADC's default +5V range; if you want a bit or two more resolution, you could either set up a 2 V external ADC reference, or could amplify the sensor output up to a range of about 5 V, or could use a unity gain op amp circuit followed by a voltage divider to get into a 0-to-1.1 V range, and use the internal 1.1 V bandgap reference.
• Uno power supply ground voltage – If the Uno's supply is isolated, its ground can be connected to automotive ground with no problem.  Or, if its supply ground already connects to automotive ground, no problem.  Where a problem might occur is if you measure a large voltage between automotive ground and Uno ground.  If so, connect a 100 Ω resistor between the two grounds and measure the voltage across it.  If the voltage is near zero, you can connect the grounds or could leave them connected by a small resistor like that.  If, on the other hand, some appreciable voltage appears across the resistor, or if it disappears in a puff of smoke, then they can't connect safely and you would need to use a different power supply for the Uno that doesn't have such a problem.
• Ground wire topology – The wiring path from Uno ground to automotive ground should not share any segments with high current devices.   In normal operation, or in case of a [load dump](https://en.wikipedia.org/wiki/Load_dump), several volts difference can arise between the ends of a piece of ground wire to a high current device.


body:
The ground does need to be connected. I have also added a RC filter to stabilize the sensor reading.

Connection :

>Arduino 5V  ----> MAP Vcc
>
>Arduino GND ----> MAP GND
>
>Arduino Analog Pin A0 <---- RC Filter <---- MAP Output pin

Using this connection, I get the proper readings.

Readings on Serial Monitor :

    // When Vehicle not start //
    MAP1: 376         MAP2: 1.84
    MAP1: 376         MAP2: 1.84
    MAP1: 376         MAP2: 1.84
    MAP1: 376         MAP2: 1.84
    MAP1: 376         MAP2: 1.84
    MAP1: 376         MAP2: 1.84
    MAP1: 376         MAP2: 1.84
    MAP1: 376         MAP2: 1.84
    MAP1: 376         MAP2: 1.84
    MAP1: 376         MAP2: 1.84
    MAP1: 376         MAP2: 1.84
    MAP1: 376         MAP2: 1.84
    MAP1: 376         MAP2: 1.84
    MAP1: 376         MAP2: 1.84

    //When start vehicle//
    MAP1: 343         MAP2: 1.68
    MAP1: 332         MAP2: 1.62
    MAP1: 341         MAP2: 1.67
    MAP1: 255         MAP2: 1.25
    MAP1: 215         MAP2: 1.05
    MAP1: 336         MAP2: 1.64
    MAP1: 320         MAP2: 1.56
    MAP1: 321         MAP2: 1.57
    MAP1: 308         MAP2: 1.51
    MAP1: 316         MAP2: 1.54
    MAP1: 326         MAP2: 1.59
    MAP1: 326         MAP2: 1.59
    MAP1: 325         MAP2: 1.59
    MAP1: 177         MAP2: 0.87
    MAP1: 219         MAP2: 1.07
    MAP1: 216         MAP2: 1.06
    MAP1: 220         MAP2: 1.08
    MAP1: 208         MAP2: 1.02
    MAP1: 211         MAP2: 1.03

    //Provide full throttle//
    MAP1: 319         MAP2: 1.56
    MAP1: 324         MAP2: 1.58
    MAP1: 341         MAP2: 1.67
    MAP1: 349         MAP2: 1.71
    MAP1: 353         MAP2: 1.73
    MAP1: 352         MAP2: 1.72
    MAP1: 352         MAP2: 1.72
    MAP1: 356         MAP2: 1.74
    MAP1: 357         MAP2: 1.74
    MAP1: 359         MAP2: 1.75
    MAP1: 355         MAP2: 1.74
    MAP1: 354         MAP2: 1.73
    MAP1: 327         MAP2: 1.60

    //Suddenly come back to normal throttle//
    MAP1: 181         MAP2: 0.88
    MAP1: 181         MAP2: 0.88
    MAP1: 192         MAP2: 0.94
    MAP1: 205         MAP2: 1.00
    MAP1: 201         MAP2: 0.98
    MAP1: 210         MAP2: 1.03
    MAP1: 218         MAP2: 1.07
    MAP1: 222         MAP2: 1.09

    //Provide full throttle again//
    MAP1: 309         MAP2: 1.51
    MAP1: 375         MAP2: 1.83
    MAP1: 395         MAP2: 1.93
    MAP1: 376         MAP2: 1.84
    MAP1: 261         MAP2: 1.28
    MAP1: 360         MAP2: 1.76
    MAP1: 307         MAP2: 1.50
    MAP1: 361         MAP2: 1.76
    MAP1: 259         MAP2: 1.27

    //Suddenly back again normal throttle//
    MAP1: 156         MAP2: 0.76

    //Again provide full throttle//
    MAP1: 295         MAP2: 1.44
    MAP1: 267         MAP2: 1.30
    MAP1: 287         MAP2: 1.40
    MAP1: 372         MAP2: 1.82
    MAP1: 380         MAP2: 1.86
    MAP1: 375         MAP2: 1.83
    MAP1: 229         MAP2: 1.12
    MAP1: 359         MAP2: 1.75
    MAP1: 339         MAP2: 1.66
    MAP1: 337         MAP2: 1.65
    MAP1: 359         MAP2: 1.75
    MAP1: 344         MAP2: 1.68

    //Again suddenly back to normal throttle//
    MAP1: 121         MAP2: 0.59
    MAP1: 164         MAP2: 0.80
    MAP1: 202         MAP2: 0.99

    //Again provide full throttle//
    MAP1: 310         MAP2: 1.52
    MAP1: 339         MAP2: 1.66
    MAP1: 356         MAP2: 1.74
    MAP1: 361         MAP2: 1.76
    MAP1: 274         MAP2: 1.34

    //Again suddenly back to normal throttle//
    MAP1: 127         MAP2: 0.62
    MAP1: 178         MAP2: 0.87
    MAP1: 221         MAP2: 1.08
    MAP1: 247         MAP2: 1.21
    MAP1: 224         MAP2: 1.09

    //Again provide full throttle//
    MAP1: 292         MAP2: 1.43
    MAP1: 278         MAP2: 1.36
    MAP1: 265         MAP2: 1.30
    MAP1: 367         MAP2: 1.79
    MAP1: 328         MAP2: 1.60
    MAP1: 358         MAP2: 1.75

    //Again suddenly back to normal throttle//
    MAP1: 182         MAP2: 0.89
    MAP1: 174         MAP2: 0.85
    MAP1: 242         MAP2: 1.18
    MAP1: 253         MAP2: 1.24
    MAP1: 261         MAP2: 1.28

    //Vehicle stop//
    MAP1: 307         MAP2: 1.50
    MAP1: 360         MAP2: 1.76
    MAP1: 375         MAP2: 1.83
    MAP1: 375         MAP2: 1.83
    MAP1: 375         MAP2: 1.83
    MAP1: 376         MAP2: 1.84
    MAP1: 375         MAP2: 1.83
    MAP1: 375         MAP2: 1.83
    MAP1: 376         MAP2: 1.84
    MAP1: 376         MAP2: 1.84
    MAP1: 377         MAP2: 1.84
    MAP1: 377         MAP2: 1.84
    MAP1: 377         MAP2: 1.84
    MAP1: 377         MAP2: 1.84


body: I once used an arduino to check the map sensor on my ford f150.  As an FYI, I will state that the ford map gave a digital pulse as output for the engine computer and was not analogue as the one you seem to be using.  I'm only commenting here for others who might be having trouble with a MAP sensor, so that they realize that some give pulse outputs and not voltage outputs.  So, I'm not sure about your map sensor, or turning the pulses into an average reading, but I simply used the interrupt to count pulses over a second and then recorded those readings over several minutes of drive time.  (I was having intermittent engine stumbling and I was ruling out the various sensors as causing the trouble.)  I was checking to make sure the MAP sensor didn't completely drop out from time to time.  In the end, it was my ignition module giving out due to heat fatigue that was the problem.  But, I can say that with a handful of resistors and a probe I was able to check all the sensors in the vehicle in short time...except for the oxygen sensor which I was afraid to damage due to its sensitivity.


message:
Controlling a button

I'm going to write a sketch that would light up the first LED (D1) of the training shield at the beginning, then move the LED light to the left or to the right whenever you press the S1 or S2 buttons, respectively. When the LED is already at the first (D1) or the last (D8), it should no longer move when going further to the left or right, respectively.

Looks exactly like this: https://www.youtube.com/watch?v=_KQQTdDMgOU

Here's what I made so far:

    int x = 0;

    void setup() {
      for(int i=11; i <= 18; i++) {
        pinMode(i, OUTPUT);
      }
    }

    void loop() {
      x = digitalRead(pushButtonPin);
      if (pushButtonState == HIGH) {
        // turn LED on:
        digitalWrite(ledPin, HIGH);
      } else {
        // turn LED off:
        digitalWrite(ledPin, LOW);
      }
    }

body:
What you made so far is only turn on and off LED according to button state. I believe there's more efficient code out there, but you can try:

    int x = 11;

     void setup() {
     for(int i=11; i <= 18; i++) pinMode(i, OUTPUT); //assuming the led is on pin 11-18
     }

     void turnLED(int num)
     {
      for(int i=11; i <= 18; i++)
       if (num==i) digitalWrite(i,HIGH); else
          digitalWrite(i,LOW);
     }

     void loop() {

     if (digitalRead(buttonRight))
     {
      x++;
      if (x>18) x=18;
     }
     else if (digitalRead(buttonLeft))
     {
      x--;
      if (x<11) x=11;
     }
     turnLED(x); //turn LED on according to value of 'x'
     delay(500);
    }


message:
Suse or Debian Linux Installation on Raspberry PI 3

Is I can install Suse or Debian Linux Installation on Raspberry PI 3. I yet to try. Based on the answer I can opt for it. Because I need in particular either of this OS for my requirement in classified project. Does this PCB design supports this OS.

Any advice or suggestions is greatly appreciated.

body:
It is always best to try then post in one of the Stack Exchange groups.

This question is very general.  So the answer will also be vague as the actual porting of a Linux OS distribution to a new platform is not trivial and contains many steps.  And not all of them may have been completed to the extent to suit your needs.

Evidently you can run Debian on a Raspberry Pi.  But there are a few issues.  [Look here][1] and do the research to understand if these limitations will cause you to abandon this path.

As for Suse, evidently it is a "specially packaged version of SUSE".  So may not actually have all the features a normal Suse distribution has.  [Look here][2] to decide if it will work for you.

  [1]: https://wiki.debian.org/RaspberryPi
  [2]: https://www.suse.com/products/arm/raspberry-pi/


message:
Reduce current consumption on ATtiny85

I am trying to reduce current consumption on my project. Right now it is using ~1.28mAh, it should be possible to get it much lower (I am using AA batteries as the power source).

The ATtiny85 has its fuses set to run at 1MHZ, with BOD disabled.

I am using [this board][1] to mount the CPU. I desoldered the power LED and the regulator, feeding power directly from the batteries to the 5V input.

Nothing was connected to any other pins while measuring, just 5V and GND. The code was running in debug mode, so every 8 seconds it flashed a debug LED. I don't know for how much this could account.

Full code:

    #include <avr/sleep.h>
    #include <avr/power.h>
    #include <avr/wdt.h>
    #include <avr/interrupt.h>

    #define DEBUG (true)
    #define INT_PIN (0)
    #define OUT_PIN (2)
    #define LED_PIN (1)

    /***************************************************
     *  Name:        ISR(WDT_vect)
     *
     *  Returns:     Nothing.
     *
     *  Parameters:  None.
     *
     *  Description: Watchdog Interrupt Service. This
     *               is executed when watchdog timed out.
     *
     ***************************************************/
    EMPTY_INTERRUPT(WDT_vect);
    EMPTY_INTERRUPT(PCINT0_vect);

    /***************************************************
     *  Name:        enterSleep
     *
     *  Returns:     Nothing.
     *
     *  Parameters:  None.
     *
     *  Description: Enters the arduino into sleep mode.
     *
     ***************************************************/
    void enterSleep() {
      set_sleep_mode(SLEEP_MODE_PWR_DOWN);
      sleep_enable();
      sleep_cpu();
      sleep_disable(); /* First thing to do is disable sleep. */

      #if DEBUG
        digitalWrite(LED_PIN, HIGH);
        for (uint16_t dbg = 0; dbg < 65535; dbg++);
        digitalWrite(LED_PIN, LOW);
      #endif
    }

    /***************************************************
     *  Name:        setup
     *
     *  Returns:     Nothing.
     *
     *  Parameters:  None.
     *
     *  Description: Setup for the serial comms and the
     *                Watch dog timeout.
     *
     ***************************************************/
    void setup() {
      pinMode(INT_PIN,INPUT);
      pinMode(OUT_PIN,OUTPUT);
      pinMode(LED_PIN,OUTPUT);
      ADCSRA &= ~_BV(ADEN); // ADC off
      power_all_disable();
    }

    /***************************************************
     *  Name:        enterSleep
     *
     *  Returns:     Nothing.
     *
     *  Parameters:  None.
     *
     *  Description: Main application loop.
     *
     ***************************************************/
    void loop() {
      digitalWrite(OUT_PIN, LOW);
      digitalWrite(LED_PIN, LOW);
      /*** Setup the WDT ***/
      wdt_reset();
      /* In order to change WDE or the prescaler, we need to
       * set WDCE (This will allow updates for 4 clock cycles).
       * WDTCR on ATTINY85 / WDTCSR on ATMEGA
       */
      WDTCR |= (1<<WDCE) | (1<<WDE);
      /* set new watchdog timeout prescaler value */
      WDTCR = 1<<WDP0 | 1<<WDP3; /* 8.0 seconds */
      /* Enable the WD interrupt (note no reset). */
      WDTCR |= _BV(WDIE);
      // sleep for 8 seconds x 43200 = 96 hours = 4 days
      for (uint16_t i = 0; i < 43200; i++)
        enterSleep();
      wdt_reset();
      wdt_disable();
      GIMSK |= _BV(PCIE); // Enable Pin Change Interrupts
      PCMSK |= _BV(PCINT0); // Use PB0 as interrupt pin
      enterSleep();

      #if DEBUG
        digitalWrite(LED_PIN, HIGH);
      #else
        digitalWrite(OUT_PIN, HIGH);
      #endif
      enterSleep();
      PCMSK &= ~_BV(PCINT0); // Turn off PB0 as interrupt pin
    }

  [1]: http://makbit.com/web/firmware/breathing-life-into-digispark-clone-with-attiny-mcu/

body: Today I measured again without the development board. Just the CPU, same setup otherwise (original code, using the FTDI cable as power source) and I got a reading of about 6-8µA. I guess that answers it! Thanks everyone for your help!


message:
Is there any way to check with Arduino UNO if a sensor is connected and ready to be read?

I would like to check the status of the sensors with Arduino UNO. For example, when I turn on the robot, I would like to check if all the sensors are connected and ready to be read or not. Maybe one sensor is unplugged and I want to detect this situation.

I read something about pull up resistors, but I didn't find any clear example of my problem. Also, I don't have any idea how to connect the resistor, how to calculate the resistor needed, as well as how to use the pull up resistor for digital and analog sensors.

Any schema, explanations and example would be very helpful!

body:
Basically pull-up resistor pulls up the line, when nobody/nothing is doing otherwise (for example wire unconnected, or connected to INPUT, or to I2C bus, which is not doing something right now ...). If some device (or Arduino) sets the wire to LOW (0V, GND, ground), the it overrules the resistor and the wire is LOW.

So the value of the resistor must be high enought to anable any attached device to draw the wire LOW. So if you know, how much of current can a device sink and what is considered LOW value on input, then you can compute the minimal value of the resistor from Ohm law (and the Vcc, where the resistor is connected). If you do not want calculate anything, just put 10KOhm between the wire and Vcc and it would probabelly work just fine.

---

About detecting sensor - you have to know, what sensor and where is supposed to be attached (as you construct the robot). So you just send any command to the sensor (probabelly to read a value) and see, if you get answer and the answer make a sense (eg. temperature is like 0-100 Celcius, or so). If it works OK, then the sensor is connected and can be used, otherwise you should stop the robot, light big red light and wait for user to repair what is broken. Thing also about the type of sensor, if it needs some time to "boot up" and it it needs some time to "seatle the value and answer" to provide that time before testing (like with delay()).

---

The pull-up resistors fits there in the way, that they are connected to Arduino, so if there is no connection to sensor, then the unconnected pin is not "floating" (and possibly return any random or not random value), but is weakly drawn up ti HIGH, so if the connetor is broken/unattached, then all reads are just plain HIGH, no communication from sensor (or any noise to be messing with the detection). So you can detect "no answer" status and after a while (when sensor really, really should answer, but did not) flash that big red light.


message:
Why is SD card failing to begin?

I recently bought a micro SD storage shield for my arduino project, this is the [link][1]. My final goal is to log information every 100 ms about the temperature and pressure of my device using another one of my sensors. However, I started by testing out the SD card through the SdInfo class that comes as an example with the SdFat library. This is the outcome (through the Serial monitor):

    SdFat version: 20160719

    Assuming the SD is the only SPI device.
    Edit DISABLE_CHIP_SELECT to disable another device.

    Assuming the SD chip select pin is: 10
    Edit SD_CHIP_SELECT to change the SD chip select pin.

    type any character to start

    init time: 748 ms

    Card type: SDHC

    Manufacturer ID: 0X28
    OEM ID: BE
    Product: 68BHO
    Version: 0.8
    Serial number: 0XD50B3A66
    Manufacturing date: 11/2010

    cardSize: 32026.66 MB (MB = 1,000,000 bytes)
    flashEraseSize: 128 blocks
    eraseSingleBlock: true
    OCR: 0XC0FF8000

    SD Partition Table
    part,boot,type,start,length
    1,0X0,0XC,8192,62543872
    2,0X0,0X0,0,0
    3,0X0,0X0,0,0
    4,0X0,0X0,0,0

    Volume is FAT32
    blocksPerCluster: 64
    clusterCount: 976992
    freeClusters: 976905
    freeSpace: 32011.22 MB (MB = 1,000,000 bytes)
    fatStartBlock: 9310
    fatCount: 2
    blocksPerFat: 7633
    rootDirStart: 2
    dataStartBlock: 24576

    type any character to start

    cardBegin failed
    SD errorCode: 0XA
    SD errorData: 0X5

This is the code of the class SdInfo:

    /*
     * This program attempts to initialize an SD card and analyze its structure.
     */
    #include <SPI.h>
    #include "SdFat.h"
    /*
     * SD chip select pin.  Common values are:
     *
     * Arduino Ethernet shield, pin 4.
     * SparkFun SD shield, pin 8.
     * Adafruit SD shields and modules, pin 10.
     * Default SD chip select is the SPI SS pin.
     */
    const uint8_t SD_CHIP_SELECT = SS;
    /*
     * Set DISABLE_CHIP_SELECT to disable a second SPI device.
     * For example, with the Ethernet shield, set DISABLE_CHIP_SELECT
     * to 10 to disable the Ethernet controller.
     */
    const int8_t DISABLE_CHIP_SELECT = -1;
    SdFat sd;

    // serial output steam
    ArduinoOutStream cout(Serial);

    // global for card size
    uint32_t cardSize;

    // global for card erase size
    uint32_t eraseSize;
    //------------------------------------------------------------------------------
    // store error strings in flash
    #define sdErrorMsg(msg) sdErrorMsg_F(F(msg));
    void sdErrorMsg_F(const __FlashStringHelper* str) {
      cout << str << endl;
      if (sd.card()->errorCode()) {
        cout << F("SD errorCode: ");
        cout << hex << int(sd.card()->errorCode()) << endl;
        cout << F("SD errorData: ");
        cout << int(sd.card()->errorData()) << dec << endl;
      }
    }
    //------------------------------------------------------------------------------
    uint8_t cidDmp() {
      cid_t cid;
      if (!sd.card()->readCID(&cid)) {
        sdErrorMsg("readCID failed");
        return false;
      }
      cout << F("\nManufacturer ID: ");
      cout << hex << int(cid.mid) << dec << endl;
      cout << F("OEM ID: ") << cid.oid[0] << cid.oid[1] << endl;
      cout << F("Product: ");
      for (uint8_t i = 0; i < 5; i++) {
        cout << cid.pnm[i];
      }
      cout << F("\nVersion: ");
      cout << int(cid.prv_n) << '.' << int(cid.prv_m) << endl;
      cout << F("Serial number: ") << hex << cid.psn << dec << endl;
      cout << F("Manufacturing date: ");
      cout << int(cid.mdt_month) << '/';
      cout << (2000 + cid.mdt_year_low + 10 * cid.mdt_year_high) << endl;
      cout << endl;
      return true;
    }
    //------------------------------------------------------------------------------
    uint8_t csdDmp() {
      csd_t csd;
      uint8_t eraseSingleBlock;
      if (!sd.card()->readCSD(&csd)) {
        sdErrorMsg("readCSD failed");
        return false;
      }
      if (csd.v1.csd_ver == 0) {
        eraseSingleBlock = csd.v1.erase_blk_en;
        eraseSize = (csd.v1.sector_size_high << 1) | csd.v1.sector_size_low;
      } else if (csd.v2.csd_ver == 1) {
        eraseSingleBlock = csd.v2.erase_blk_en;
        eraseSize = (csd.v2.sector_size_high << 1) | csd.v2.sector_size_low;
      } else {
        cout << F("csd version error\n");
        return false;
      }
      eraseSize++;
      cout << F("cardSize: ") << 0.000512*cardSize;
      cout << F(" MB (MB = 1,000,000 bytes)\n");

      cout << F("flashEraseSize: ") << int(eraseSize) << F(" blocks\n");
      cout << F("eraseSingleBlock: ");
      if (eraseSingleBlock) {
        cout << F("true\n");
      } else {
        cout << F("false\n");
      }
      return true;
    }
    //------------------------------------------------------------------------------
    // print partition table
    uint8_t partDmp() {
      cache_t *p = sd.vol()->cacheClear();
      if (!p) {
        sdErrorMsg("cacheClear failed");
        return false;
      }
      if (!sd.card()->readBlock(0, p->data)) {
        sdErrorMsg("read MBR failed");
        return false;
      }
      for (uint8_t ip = 1; ip < 5; ip++) {
        part_t *pt = &p->mbr.part[ip - 1];
        if ((pt->boot & 0X7F) != 0 || pt->firstSector > cardSize) {
          cout << F("\nNo MBR. Assuming Super Floppy format.\n");
          return true;
        }
      }
      cout << F("\nSD Partition Table\n");
      cout << F("part,boot,type,start,length\n");
      for (uint8_t ip = 1; ip < 5; ip++) {
        part_t *pt = &p->mbr.part[ip - 1];
        cout << int(ip) << ',' << hex << int(pt->boot) << ',' << int(pt->type);
        cout << dec << ',' << pt->firstSector <<',' << pt->totalSectors << endl;
      }
      return true;
    }
    //------------------------------------------------------------------------------
    void volDmp() {
      cout << F("\nVolume is FAT") << int(sd.vol()->fatType()) << endl;
      cout << F("blocksPerCluster: ") << int(sd.vol()->blocksPerCluster()) << endl;
      cout << F("clusterCount: ") << sd.vol()->clusterCount() << endl;
      cout << F("freeClusters: ");
      uint32_t volFree = sd.vol()->freeClusterCount();
      cout <<  volFree << endl;
      float fs = 0.000512*volFree*sd.vol()->blocksPerCluster();
      cout << F("freeSpace: ") << fs << F(" MB (MB = 1,000,000 bytes)\n");
      cout << F("fatStartBlock: ") << sd.vol()->fatStartBlock() << endl;
      cout << F("fatCount: ") << int(sd.vol()->fatCount()) << endl;
      cout << F("blocksPerFat: ") << sd.vol()->blocksPerFat() << endl;
      cout << F("rootDirStart: ") << sd.vol()->rootDirStart() << endl;
      cout << F("dataStartBlock: ") << sd.vol()->dataStartBlock() << endl;
      if (sd.vol()->dataStartBlock() % eraseSize) {
        cout << F("Data area is not aligned on flash erase boundaries!\n");
        cout << F("Download and use formatter from www.sdcard.org!\n");
      }
    }
    //------------------------------------------------------------------------------
    void setup() {
      Serial.begin(9600);

      // Wait for USB Serial
      while (!Serial) {
        SysCall::yield();
      }

      // use uppercase in hex and use 0X base prefix
      cout << uppercase << showbase << endl;

      // F stores strings in flash to save RAM
      cout << F("SdFat version: ") << SD_FAT_VERSION << endl;
      if (DISABLE_CHIP_SELECT < 0) {
        cout << F(
               "\nAssuming the SD is the only SPI device.\n"
               "Edit DISABLE_CHIP_SELECT to disable another device.\n");
      } else {
        cout << F("\nDisabling SPI device on pin ");
        cout << int(DISABLE_CHIP_SELECT) << endl;
        pinMode(DISABLE_CHIP_SELECT, OUTPUT);
        digitalWrite(DISABLE_CHIP_SELECT, HIGH);
      }
      cout << F("\nAssuming the SD chip select pin is: ") <<int(SD_CHIP_SELECT);
      cout << F("\nEdit SD_CHIP_SELECT to change the SD chip select pin.\n");
    }
    //------------------------------------------------------------------------------
    void loop() {
      // Read any existing Serial data.
      do {
        delay(10);
      } while (Serial.available() && Serial.read() >= 0);

      // F stores strings in flash to save RAM
      cout << F("\ntype any character to start\n");
      while (!Serial.available()) {
        SysCall::yield();
      }

      uint32_t t = millis();
      // initialize the SD card at SPI_HALF_SPEED to avoid bus errors with
      // breadboards.  use SPI_FULL_SPEED for better performance.
      if (!sd.cardBegin(SD_CHIP_SELECT, SPI_HALF_SPEED)) {
        sdErrorMsg("\ncardBegin failed");
        return;
      }
      t = millis() - t;

      cardSize = sd.card()->cardSize();
      if (cardSize == 0) {
        sdErrorMsg("cardSize failed");
        return;
      }
      cout << F("\ninit time: ") << t << " ms" << endl;
      cout << F("\nCard type: ");
      switch (sd.card()->type()) {
      case SD_CARD_TYPE_SD1:
        cout << F("SD1\n");
        break;

      case SD_CARD_TYPE_SD2:
        cout << F("SD2\n");
        break;

      case SD_CARD_TYPE_SDHC:
        if (cardSize < 70000000) {
          cout << F("SDHC\n");
        } else {
          cout << F("SDXC\n");
        }
        break;

      default:
        cout << F("Unknown\n");
      }
      if (!cidDmp()) {
        return;
      }
      if (!csdDmp()) {
        return;
      }
      uint32_t ocr;
      if (!sd.card()->readOCR(&ocr)) {
        sdErrorMsg("\nreadOCR failed");
        return;
      }
      cout << F("OCR: ") << hex << ocr << dec << endl;
      if (!partDmp()) {
        return;
      }
      if (!sd.fsBegin()) {
        sdErrorMsg("\nFile System initialization failed.\n");
        return;
      }
      volDmp();
    }

I have noticed that the SD card is detected only upon start up, after that it all goes to errors. I had the same situation using the default SdInfo class from the built-in Arduino examples, sometimes it would register the card, sometimes it wouldn't. **Why does this happen and how can I ensure it always reads the card?**

I have already read [this][2] question and ensured my wiring is proper and I have also formatted my card using the software and SdCard.org, it is a Fat32 format.

This is my setup:

[![Image 1][3]][3]

and

[![Image 2][4]][4]

  [1]:
https://www.amazon.com/gp/product/B00SL0QWDU/ref=oh_aui_detailpage_o01_s00?ie=UTF8&psc=1

  [2]: https://arduino.stackexchange.com/questions/17062/sd-card-fails-to-initialize
  [3]: https://i.stack.imgur.com/9HJ5d.jpg
  [4]: https://i.stack.imgur.com/QhN5H.jpg

body:
SdInfo is an example, but I hope you know there's no reason to call `sd.begin`  to re-initialize the SD library.  The example is really intended to scan several different cards, not the same card.

`sd.begin` is normally something you would do once, in `setup`, even if something else is using SPI (e.g., Ethernet).  You probably won't get this error in your "real" sketch.

**But to answer your question:**

I see that your card takes a long time to initialize (almost a full second).  The error code says that the card does not re-initialize within 2 seconds.  I had a [similar problem](https://arduino.stackexchange.com/questions/21368#21373), and the solution was to edit the SD library and slow down how quickly it asked the card, "Are you initialized yet?"

Error code 0x0A is SD_CARD_ERROR_ACMD41, so perhaps you can use the same technique in this loop, line 171 of SdSpiCard.cpp:

      // initialize card and send host supports SDHC if SD2
      arg = type() == SD_CARD_TYPE_SD2 ? 0X40000000 : 0;

      while (cardAcmd(ACMD41, arg) != R1_READY_STATE) {
        // check for timeout
        if (((uint16_t)millis() - t0) > SD_INIT_TIMEOUT) {
          error(SD_CARD_ERROR_ACMD41);
          goto fail;
        }
        delay( 150 ); // <-- wait a little
      }

###Update

There is a related question and answer [here](https://arduino.stackexchange.com/questions/3850/sd-begin-fails-second-time).  Calling `sd.begin` twice is actually an open issue in the library.


message:
How to get each byte in byte array out and be able to work with them on their own?

I am currently sending data via my bluetooth and to it I send with me 4 different values looking like this:

    byte[] myByte = {"HelloOne", "HelloTwo", "HelloThree", "HelloFour"};
 WriteAsync(myByte);

And now I am looking for a way to store all these Hello's in different values.

What I have started with is something like this:

    if (Bluetooth.available())
    {
     while (true)
     {
       delay (50);
       char c = Bluetooth.read();
       readString += c;

       if (readString.length() >0) {

        if (readString[0] == "HelloOne")
        {
           Serial.println ("Hello One has been sent!");
        }

        if (readString[1] == "HelloTwo")
        {
           Serial.println ("Hello Two has been sent!");
        }

        if (readString[2] == "HelloThree")
        {
           Serial.println ("Hello Three has been sent!");
        }

        if (readString[3] == "HelloFour")
        {
           Serial.println ("Hello Four has been sent!");
        }

       }

     }

    }

And I have not actually been able to debugg (not currently at home but eager to get to fix this problem asap) so there is a slim chance that my current code might be working? Very unlikely though.

So my question is, what is the correct way to get each value out in a byte array that is being sent with bluetooth to arduino?

body:
Sorry if this sound patronising, its not meant to, I'm just trying to cover all aspects.

    byte[] myByte = {"HelloOne", "HelloTwo", "HelloThree", "HelloFour"};
    WriteAsync(myByte);

You are assigning 4 strings to the array `mByte`.  A string (lets ignore the Arduino type string for now) is a char* or a char[], so:

    char hello1[] = "HelloOne";
    char hello2[] = "HelloTwo";
    char hello3[] = "HelloThree";
    char hello4[] = "HelloFour";
(You don't need to do this in the code, how you have done it is fine, it just shows what you are really saying)

In English mByte should be an array of strings which in code is

    char* mByte[] = {"HelloOne", "HelloTwo", "HelloThree", "HelloFour"};

You could do it as

    char mByte[][] = {"HelloOne", "HelloTwo", "HelloThree", "HelloFour"};//ERROR

But this won't compile, because the inner array (the text) is different length and the compiler doesn't like that.

Assuming that `writeAsync` takes a byte as a parameter then the code to write the data becomes this:

    for (int stringCounter = 0; stringCounter < 4; ++stringCounter)
    {
        // get a pointer to the first element of the string
        // & means get the address (so the value can be set to a pointer)
        // (byte*) means cast (change) the value into a byte pointer.
        byte* currentLetter = (byte*)(&mByte[stringCounter][0];)
        // currentLetter != NULL means the pointer is not equal to NULL, because looking at a null pointer will crash the code.
        // *currentLetter != NULL means the thing pointed to by currentLetter is not the end of the string.
        while (currentLength != NULL || *currentLength != NULL)
        {
            // Write the thing pointed to by the pointer to the function.
            writeAsych(*currentLetter);
            currentLetter++;  // Move on the pointer
        }
    }

Sorry I can't compile that at the moment, but it looks about write.  I hope it helps you understand it.


message:
Following on ESP8266 Board pins, how do they map on the motor shield?

Here is the answer: All pins corresponding to the G row are connected to ground. All Pins corresponding to the V row are connected to NodeMCU's 3V3 pin.

D row pins tagged from 0 to 8 correspond to NodeMCU's D1-D8 pins. D row pins tagged with SD2, SD3 corresponds to NodeMCU's SD2, SD3 pin
UTART/SPI section:

Tags corresponding to the pins are self explanatory.
Near the white-colored power switch we have a pin called "AD". I couldn't figure how this motor shield's "AD" pin is interfaced to NodeMCU. Do you have any idea?

Following on https://arduino.stackexchange.com/questions/25260/basic-question-esp8266-board-pins, I can't seem to map the pins on its motor shield to software (the ones named UART/SPI, the GPIOs and the Analog Inputs). See the third image, with a NodeMCU installed.

[![Motor Shield][1]][1]

The GPIOs seem to conflict with the motors on Arduino, and I have no idea what to do here. Documentation is pretty much useless.

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

  [1]: https://i.stack.imgur.com/Q3URi.jpg
  [3]: https://i.stack.imgur.com/RXJJo.jpg

body:
You see the pins marked `PWMA`, `PWMB`, `DA` and `DB`? Those are the pins that control the motors (`PWMx` is the speed, `Dx` is the direction). Whatever pins on your ESP8266 board plug into those holes are the pins you need to use in your code. How those pins map to names and numbers in the Arduino API depends entirely on what the board is you're plugging in and what the author of the board definition files was thinking at the time.

In short, look at your board (*which we cannot see*) and see what GPIO pins are in the same location as the pins I pointed out. Then control those pins in your software.


message:
Typedef Function Pointer Invoking Issue

I'm having an issue trying to use a normal non-member function of my main sketch file as a callback.  I can't get the function pointer to invoke from a function other than it was saved.  More info below;

MotorEncoder.h

    typedef void (*cb)(int16_t,int16_t);
    class MotorEncoder
      ...
      private:
        cb _motor_callback;

Program.ino

    cb encoder_cb = NULL;
    ...
    encoder_cb = function_that_accepts_2_int16
    DC_Encoder_1.move(motor_pos, speed, motor_id, encoder_cb);

**EDIT:** I want to edit the description as to not confuse anyone.  The code with the callbacks above is all correct.  The issue was I was working with open-source software and another developer was setting the selected serial-port connection back to the bluetooth channel in-correctly.  The callback was executed, I was connected to the ATMega2560 via serial connection to a raspberry pi and was looking for the callback to show there, not monitoring bluetooth so I didn't see any data come across.  Document your code.

body:
This answer contains a few debugging guidelines, as I don't know what the problem is and don't see how one could tell without a good deal more of information.

I suggest creating a [Minimal, Complete, and Verifiable example](https://stackoverflow.com/help/mcve) (MCaVe) of your code, not just snippets, so that other people can compile and run the code, thus being able to observe what happens in more detail and perhaps with added debugging output.

I'm presuming your callback is triggered as a consequence of an interrupt occurring.  I suggest you write the MCaVe to depend on a pin-change interrupt, rather than a motor-controller interrupt, to allow testing on a system consisting of no more than an Arduino with a button, a serial interface, and perhaps a few LED indicators.  Pressing the button would change pin voltage and cause an interrupt; your ISR would turn on an LED to signal it handled the interrupt, then trigger the callback.  The callback routine would turn on another LED as its signal.  The main loop would read the pin register bits for the two LEDs, record and report the times they came on, and turn them off after a second or two.  If you get a simple setup like this to work, the technique probably would carry over to your motor-controller case; or if not, probably being a smaller program and setup should be easier to debug and figure out why not.