body:
I'm newbie about Arduino.
Can i build arduino robot wheels using Canon/Epson Cartridge inkjet printer?

The idea is like Drawing Robot
[![enter image description here][1]][1]

but i want to use cartridge printer instead of using a pen.

so after searching, and it look like ZUtAPocketPrinter

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

The Drawing Robot is using Trinket Pro
And ZUtAPocketPrinter is using Arduino (don't know using Uno/Nano/etc)

Can I use Trinket Pro or what types of arduino that i can use (Uno, Nano)?

And what hardware, sensor that require to scan/measure size of the paper?

And if there is tutorial, please share the link.

  [1]: https://i.stack.imgur.com/Catpv.png
  [2]: https://i.stack.imgur.com/8XYKF.jpg

title: Inkjet Printer Robot Wheels

Answers: 1

body:
Usually a robot uses 2 identical motors for drive in order to change directions or go straight.  Usually a printer will only have 1 motor to drive the paper and 1 motor to drive the print head.  And usually they are not identical.  Making it difficult to build a useful robot.  Also, printers usually use [stepping motors][1].  Most people building their first (small) robot usually use [continuous servo motors][2].  This makes for an easy to build first (small) robot as seen in this picture:

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

  [1]: https://learn.adafruit.com/all-about-stepper-motors/what-is-a-stepper-motor
  [2]: https://learn.adafruit.com/adafruit-motor-selection-guide/continuous-rotation-servos
  [3]: https://i.stack.imgur.com/7NKJn.jpg


body:
New [Adafruit GPS][1] connected to my Arduino 101 board.

When trying to use the RX/TX hardware serial (on digital pins 0 / 1), with a simple sketch (described by Adafruit) to output a serial response, I'm not seing anything in the serial monitor (9600 baud).

<!-- begin snippet: js hide: false console: true babel: false -->

<!-- language: lang-arduino -->

    // this sketch will allow you to bypass the Atmega chip
    // and connect the Ultimate GPS directly to the USB/Serial
    // chip converter.

    // Connect VIN to +5V
    // Connect GND to Ground
    // Connect GPS RX (data into GPS) to Digital 0
    // Connect GPS TX (data out from GPS) to Digital 1

    void setup() {}
    void loop() {}

<!-- end snippet -->

Wires connected as in the sketch, also tried swapping them out in case of faulty wire.

Went on to try TinyGPS++ default example code, across a variety of pins: 3,4 & 8,9 & 0,1.

<!-- begin snippet: js hide: false console: true babel: false -->

<!-- language: lang-arduino -->

    #include <TinyGPS++.h>
    #include <SoftwareSerial.h>
    /*
       This sample code demonstrates the normal use of a TinyGPS++ (TinyGPSPlus) object.
       It requires the use of SoftwareSerial, and assumes that you have a
       4800-baud serial GPS device hooked up on pins 4(rx) and 3(tx). EDITED BELOW.
    */

    static const int RXPin = 8, TXPin = 9;
    static const uint32_t GPSBaud = 9600;

    // The TinyGPS++ object
    TinyGPSPlus gps;

    // The serial connection to the GPS device
    SoftwareSerial ss(RXPin, TXPin);

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

      Serial.println(F("FullExample.ino"));
      Serial.println(F("An extensive example of many interesting TinyGPS++ features"));
      Serial.print(F("Testing TinyGPS++ library v. ")); Serial.println(TinyGPSPlus::libraryVersion());
      Serial.println(F("by Mikal Hart"));
      Serial.println();
      Serial.println(F("Sats HDOP Latitude   Longitude   Fix  Date       Time     Date Alt    Course Speed Card  Distance Course Card  Chars Sentences Checksum"));
      Serial.println(F("          (deg)      (deg)       Age                      Age  (m)    --- from GPS ----  ---- to London  ----  RX    RX        Fail"));
      Serial.println(F("---------------------------------------------------------------------------------------------------------------------------------------"));
    }

    void loop()
    {
      static const double LONDON_LAT = 51.508131, LONDON_LON = -0.128002;

      printInt(gps.satellites.value(), gps.satellites.isValid(), 5);
      printInt(gps.hdop.value(), gps.hdop.isValid(), 5);
      printFloat(gps.location.lat(), gps.location.isValid(), 11, 6);
      printFloat(gps.location.lng(), gps.location.isValid(), 12, 6);
      printInt(gps.location.age(), gps.location.isValid(), 5);
      printDateTime(gps.date, gps.time);
      printFloat(gps.altitude.meters(), gps.altitude.isValid(), 7, 2);
      printFloat(gps.course.deg(), gps.course.isValid(), 7, 2);
      printFloat(gps.speed.kmph(), gps.speed.isValid(), 6, 2);
      printStr(gps.course.isValid() ? TinyGPSPlus::cardinal(gps.course.value()) : "*** ", 6);

      unsigned long distanceKmToLondon =
        (unsigned long)TinyGPSPlus::distanceBetween(
          gps.location.lat(),
          gps.location.lng(),
          LONDON_LAT,
          LONDON_LON) / 1000;
      printInt(distanceKmToLondon, gps.location.isValid(), 9);

      double courseToLondon =
        TinyGPSPlus::courseTo(
          gps.location.lat(),
          gps.location.lng(),
          LONDON_LAT,
          LONDON_LON);

      printFloat(courseToLondon, gps.location.isValid(), 7, 2);

      const char *cardinalToLondon = TinyGPSPlus::cardinal(courseToLondon);

      printStr(gps.location.isValid() ? cardinalToLondon : "*** ", 6);

      printInt(gps.charsProcessed(), true, 6);
      printInt(gps.sentencesWithFix(), true, 10);
      printInt(gps.failedChecksum(), true, 9);
      Serial.println();

      smartDelay(1000);

      if (millis() > 5000 && gps.charsProcessed() < 10)
        Serial.println(F("No GPS data received: check wiring"));
    }

    // This custom version of delay() ensures that the gps object
    // is being "fed".
    static void smartDelay(unsigned long ms)
    {
      unsigned long start = millis();
      do
      {
        while (ss.available())
          gps.encode(ss.read());
      } while (millis() - start < ms);
    }

    static void printFloat(float val, bool valid, int len, int prec)
    {
      if (!valid)
      {
        while (len-- > 1)
          Serial.print('*');
        Serial.print(' ');
      }
      else
      {
        Serial.print(val, prec);
        int vi = abs((int)val);
        int flen = prec + (val < 0.0 ? 2 : 1); // . and -
        flen += vi >= 1000 ? 4 : vi >= 100 ? 3 : vi >= 10 ? 2 : 1;
        for (int i=flen; i<len; ++i)
          Serial.print(' ');
      }
      smartDelay(0);
    }

    static void printInt(unsigned long val, bool valid, int len)
    {
      char sz[32] = "*****************";
      if (valid)
        sprintf(sz, "%ld", val);
      sz[len] = 0;
      for (int i=strlen(sz); i<len; ++i)
        sz[i] = ' ';
      if (len > 0)
        sz[len-1] = ' ';
      Serial.print(sz);
      smartDelay(0);
    }

    static void printDateTime(TinyGPSDate &d, TinyGPSTime &t)
    {
      if (!d.isValid())
      {
        Serial.print(F("********** "));
      }
      else
      {
        char sz[32];
        sprintf(sz, "d/d/d ", d.month(), d.day(), d.year());
        Serial.print(sz);
      }

      if (!t.isValid())
      {
        Serial.print(F("******** "));
      }
      else
      {
        char sz[32];
        sprintf(sz, "d:d:d ", t.hour(), t.minute(), t.second());
        Serial.print(sz);
      }

      printInt(d.age(), d.isValid(), 5);
      smartDelay(0);
    }

    static void printStr(const char *str, int len)
    {
      int slen = strlen(str);
      for (int i=0; i<len; ++i)
        Serial.print(i<slen ? str[i] : ' ');
      smartDelay(0);
    }

<!-- end snippet -->

Serial is spitting out this for every update:

> No GPS data received: check wiring

GPS is on, and can see based on the fix LED that satellite fix has occurred in both tests – no difference in output. Wires checked.

Maybe suboptimal pin solder job, but can't see that it should give no signal?

[![Solder job][2]][2]

EDIT: After suggestions, re-soldered pinheader – still nothing in the serial prompt on hardware serial (pin 0,1), software serial (pin 3,4) and TinyGPS++ throws the same error (pin 3-4 + 8-9). Double-checked RX/TX order.

A colleague found an old [Ublox Neo 6-M GPS][3], I plugged it in and repeated the above with the same empty serial results, not sure what to make of this..

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

  [1]: https://www.adafruit.com/product/746
  [2]: https://i.stack.imgur.com/15y3s.jpg
  [3]: https://www.u-blox.com/en/product/neo-6-series
  [4]: https://i.stack.imgur.com/4OBUl.jpg

title: No serial data from Adafruit GPS (on Arduino 101)

Answers: 1

body:
Accidentally fixed it when booting up the board tonight – not sure what changed but the serial prompt is on fire.

Wires: 5V - VIN, GND – GND, TX – 8, RX – 9

**Code:**

<!-- language: lang-arduino -->

    #include <SoftwareSerial.h>

    // setup gps serial
    int gpsTxPin = 8;
    int gpsRxPin = 9;
    SoftwareSerial gpsSerial(gpsTxPin, gpsRxPin);

    void setup()
    {
      Serial.begin(9600);  //set monitor to 9600

      gpsSerial.begin(9600); //adjust for GPS unit

      Serial.println("Ready!");
    }

    void loop()
    {
      while(gpsSerial.available())
      {
        char c = gpsSerial.read();
        Serial.print(c);
      }
    }

**Excerpt from serial monitor:**

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

    ...

    $GPVTG,248.75,T,,M,0.19,N,0.35,K,A*3F
    $GPGGA,231351.000,,,,,0,05,,,M,,M,,*7A
    $GPGSA,A,1,,,,,,,,,,,,,,,*1E
    $GPGSV,2,1,07,13,65,290,32,30,54,066,36,20,48,286,33,15,31,288,31*75

    ...


body:
I'm using a Mega2560 board.

My project needs to store some large constant data. To preserve the first 64kb flash chunk, I write these data on addresses beyond this limit.

But there is either an issue doing that or I'm doing something wrong...

After writing data the first time, I can read all bytes without no problem, but if I rewrite these data with new ones, the new data are not written correctly. It seems that, before reprogramming, the flash over 64kb are not erased.

Is this correct? How can I resolve this issue?

---

Note that, to access the data over 64kb, I use a far address.

Reading inside the bootloader source (stk500v2) code, I found that it doesn't erase pages whose addresse falls over 64kb to preserve the bootloader area. It seems that the bootloader is placed at the boundary of the first 64kb.

The following is the relevant the portion of the bootloader source:
<!-- language-all: lang-cpp -->

    // erase only main section (bootloader protection)
    // APP_END is below 64KB
    if (eraseAddress < APP_END )
    {
     boot_page_erase(eraseAddress); // Perform page erase
     boot_spm_busy_wait();  // Wait until the memory is erased.
     eraseAddress += SPM_PAGESIZE; // point to next page to be erase
    }

    /* Write FLASH */
    do {
     lowByte  = *p++;
     highByte  = *p++;

     data  = (highByte << 8) | lowByte;
     boot_page_fill(address,data);

     address = address + 2; // Select next word in memory
     size -= 2;    // Reduce number of bytes to write by two
    } while (size);     // Loop until all bytes written

    boot_page_write(tempaddress);
    boot_spm_busy_wait();
    boot_rww_enable();

title: Erasing all flash on boards with over 64kb of program memory

Answers: 0


body:
Desired program:

I have 3 momentary push buttons and a 4-channel relay board with my Arduino Uno. The relays are connected to 2 sinks, a shower, and a pump. Each push button should turn the pump and its respective fixture on for 10 seconds. I used a time buffer to debounce the push buttons.

Problem:

The time in which the function stays on is inconsistent. Sometimes 10 seconds, sometimes 3 seconds. Additionally all the relays turn off at the same time even if they were started at different times. they should all be individually timed and the pump should stay on as long as any of the three other relays are on.

Wiring Diagram:

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

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

Code:

    //initialize and declare variables
    // Pins 10,11,12,13 will be connected to their respected relays
    const int pump = 13;
    const int relay2 = 12;
    const int relay3 = 11;
    const int relay4 = 10;

    //initialize pins 2,3,4 to be connected to the momentary push buttons
    const int buttonPin1 = 2;
    const int buttonPin2 = 3;
    const int buttonPin3 = 4;

    //these variables track the state of the buttons, low if not pressed, high if pressed
    int buttonState1 = LOW;
    int buttonState2 = LOW;
    int buttonState3 = LOW;

    //Initialize pin states for valve check
    int relay2State;
    int relay3State;
    int relay4State;

    long lastDebounceTime = 0; // the last time the output pin was toggled
    long debounceDelay = 100; // the debounce time; increase if the output flickers
    unsigned long previousMillis = 0;
    unsigned long previousMillis2 = 0;
    unsigned long previousMillis3 = 0;
    unsigned long runTime = 10000;

    void setup() {
      //set pins connected to the relays as outputs.
      pinMode(pump, OUTPUT);
      pinMode(relay2, OUTPUT);
      pinMode(relay3, OUTPUT);
      pinMode(relay4, OUTPUT);

      //set push buttons as inputs
      pinMode(buttonPin1, INPUT);
      pinMode(buttonPin2, INPUT);
      pinMode(buttonPin3, INPUT);

      //initialize the starting state of the relay pins
      digitalWrite(pump, HIGH);
      digitalWrite(relay2, HIGH);
      digitalWrite(relay3, HIGH);
      digitalWrite(relay4, HIGH);
    } // close void setup

    void loop() {
      unsigned long currentMillis = millis();
      unsigned long currentMillis2 = millis();
      unsigned long currentMillis3 = millis();
      //sample the state of the buttons
      buttonState1 = digitalRead(buttonPin1);
      buttonState2 = digitalRead(buttonPin2);
      buttonState3 = digitalRead(buttonPin3);
      //check to see if any valves are open
      relay2State = digitalRead(relay2);
      relay3State = digitalRead(relay3);
      relay4State = digitalRead(relay4);
      //filter out any noise by setting a time buffer
      if ((millis() - lastDebounceTime) > debounceDelay) {
        //sample the state of the buttons
        buttonState1 = digitalRead(buttonPin1);
        buttonState2 = digitalRead(buttonPin2);
        buttonState3 = digitalRead(buttonPin3);
        //check to see if any valves are open
        relay2State = digitalRead(relay2);
        relay3State = digitalRead(relay3);
        relay4State = digitalRead(relay4);
      }

      // if button1 has been pressed, let's toggle the pump and relay2 from off
      //to on for 10 seconds
      if (buttonState1 == HIGH) {
        digitalWrite(relay2, LOW); // turn relay2
        lastDebounceTime = millis(); // set the current time
      }
      if (currentMillis - previousMillis > runTime) {
        digitalWrite(relay2, HIGH); // turn relay2
        previousMillis = currentMillis;
      }
      //if button2 has been pressed, lets toggle the pump and relay3 from off
      //to on for 10 seconds
      if (buttonState2 == HIGH) {
        digitalWrite(relay3, LOW); // turn relay3 on
      }
      if (currentMillis2 - previousMillis2 > runTime) {
        previousMillis2 = currentMillis2;
        digitalWrite(relay3, HIGH); // turn relay3 off
      }
      // if button3 has been pressed, lets toggle the pump and relay4 from off to
      //on for 10 seconds
      if (buttonState3 == HIGH) {
        digitalWrite(relay4, LOW); // turn relay4 on
        lastDebounceTime = millis(); // set the current time
      }
      if (currentMillis3 - previousMillis3 > runTime) {
        previousMillis3 = currentMillis3;
        digitalWrite(relay4, HIGH); // turn relay4 off
      }
      // if any valve is open, turn the pump on
      if(relay2State == LOW || relay3State == LOW || relay4State == LOW) {
        digitalWrite(pump, LOW);
      } else {
        digitalWrite(pump, HIGH);
      }
    } // close void loop

Any help would be greatly appreciated. I think I'm stuck in the time buffer for the debounce and my time checks aren't updating right.

title: Multiple timed functions (timing off)

Answers: 2

body:
In a program like this it rapidly becomes quite confusing with the variable names all being so similar. Because of this, this is a good candidate for creating a `class` to do the job for you. This is because you have sets of functionality and variables that are duplicated to do the same job with different settings (IO pins).

It would be a trivial matter to create a `class` that turns on an output for a specified amount of time:

    class TimedOutput {
        private:
            uint8_t _pin;
            uint32_t _started;
            uint32_t _runtime;
            bool _running;

        public:
            TimedOutput(uint8_t pin, uint32_t runtime) {
                _pin = pin;
                _runtime = runtime;
                _started = 0;
                _running = false;
            }

            void begin() {
                pinMode(_pin, OUTPUT);
                digitalWrite(_pin, LOW);
            }

            void start() {
                digitalWrite(_pin, HIGH);
                _running = true;
                _started = millis();
            }

            void run() {
                if (!_running) return;
                if (millis() - _started >= _runtime) {
                    digitalWrite(_pin, LOW);
                    _running = false;
                }
            }
    };

    // Create the object
    TimedOutput shower(10, 10000); // Output on pin 10 for 10 seconds
    TimedOutput sink(11, 3000);    // Output on pin 11 for 3 seconds

    void setup() {
        // Configure the pin
        shower.begin();
        sink.begin();
        pinMode(2, INPUT_PULLUP); // Button
        pinMode(3, INPUT_PULLUP); // Button
    }

    void loop() {
        // Start it if the button is pressed:
        if (digitalRead(2) == LOW) {
            shower.start();
        }

        if (digitalRead(3) == LOW) {
            sink.start();
        }

        // Do the checking for if it needs to stop:
        shower.run();
        sink.run();
    }

body:
Take a modular approach to it.

For example, break the functionality intwo two pieces.

Readbutton1() returns 1 if and only if button 1 has been pressed and it passed debouncing. There are tons of ways to do that.

Energizerelay1() is called to energize relay number 1 for 10 seconds. Again, there are tons of ways to do that.

Then you can integrate them all together in your loop.

Fairly easy. The key to any programming is to break down a task into individual modules and then reintegrate those modules together to perform the desired the task.

Coding those individual modules is often simple.


body:
I compiled the following two sketches with the compiler used by the Arduino IDE and ran them on an Arduino UNO (smd edition).
I'm using:

 - Arduino IDE v. 1.8.0
 - Arduino AVR Boards v. 1.6.20

1.

    void setup() {

      Serial.begin(115200);
      unsigned long a, b;
      //unsigned long c, d;

      a = micros();
      for (unsigned long i = 0; i != 1000000; i++) digitalRead(13);
      b = micros();
      Serial.println(b - a);

      //c = micros();
      //for (unsigned long i = 0; i != 1000000; i++) digitalRead(13);
      //d = micros();
      //Serial.println(d - c);

    }

    void loop () {}

2.

    void setup() {

      Serial.begin(115200);
      unsigned long a, b;
      unsigned long c, d;

      a = micros();
      for (unsigned long i = 0; i != 1000000; i++) digitalRead(13);
      b = micros();
      Serial.println(b - a);

      c = micros();
      for (unsigned long i = 0; i != 1000000; i++) digitalRead(13);
      d = micros();
      Serial.println(d - c);

    }

    void loop () {}

These were the outputs on the serial monitor:

1. `2452320`

2. `3332640
  3332704`

Why did each of the two `for` loops in the second sketch take roughly 33% more time to execute than the loop in the first one?

title: Why don't these sketches produce a similar output?

Answers: 1

body:
The different time implies different (number of) instructions being executed. <s> This is most probably due to the crappy GCC compiler optimizations.

In the former sketch, probably the compiler manages to use only registers, which are very fast. In the second one, the compiler THINKS it needs 8 more bytes, and there are no registers left, so it uses the stack (internal RAM) to store some variables, which is slower. (still, the optimizer should realize that in fact it don't need more bytes, because a and b are not used after the first println()). To access to a SRAM location, you need a LOAD/STORE operation, which takes a longer time, with respect to an operation between registers (beside having to load the memory address to X, Y o Z).
Probably, the compiler is even crappier, because, instead of putting the rarely-used variables a,b,c,d on the stack, it puts i (which is always incremented) or other variables used in digitalRead().

Still, to explain where is the trouble (i.e. where compiler fails in optimizing the register allocation/usage), you should disassemble the object code. Use for instance Atmel Studio, which still uses GCC, but has a good debugger, disassembler and cycle-exact analysis.

Still, this is very strange, perhaps optimizations were not enabled the platform.txt of your arduino? </s>

EDIT:
Using Arduino 1.8.0, I tested the two sketches and analyzed the lss (generated using avr-objdump). The compiler optimizes a lot more the first code. Instead of making a CALL to digitalRead() (as it happens in the second sketch) it probably recognizes that such function is called only once on the code. Therefore it makes a rjmp to it. At the end of that function, there won't be a RET but a branch to the point where i is computerd and checked (actually i is not incremented, actually gets decremented and checked against 0).

In other words, even if the two codes are equal (except that the second sketch runs the same code twice), they are compiled (optimized) differently.


body:
According to page 10 of this PDF https://www.sparkfun.com/datasheets/LCD/HD44780.pdf

The HD44780 has enough DDRAM to operate an 80 character display. A 16x2 display has 32 characters meaning we have 48 characters of free DDRAM. Is there anything in the Arduino's LiquidCrystal library which allows direct access to this DDRAM space? The HD44780 datasheet says it can be used as generalised RAM.

title: HD44780 Extended non-display DDRAM?

Answers: 1

body:
I haven't used that particular library but I have used the ddram and cgram as memory / buffets. So the feasibility is never in question.

The downside with this approach is speed and real estate. Those devices are slow by mcu standard. You then have to provision for the rw pin and the data pins - both read and writes. That's what you should check for in the library.

But it is workable for sure.


body:
I wrote a simple switch program using a teensy LC and transistors, but the Arduino compiler will not compile for the Teensy LC. And not for just my program, but any program, including the example programs included in the Arduino. I have tried compiling for other boards and they all compile fine. This problem was also replicated on another computer running Windows 10, I am running Windows 7, with the same error message. The error message and associated code is below, for reference.

    int led1 = 0;
    int led2 = 1;
    int led3 = 2;

    int input1 = 5;
    int input2 = 7;
    int input3 = 9;

    int bypass1 = 23; //output 1
    int toneStack1_1 = 22; //output 2
    int toneStack1_2 = 21; //output 3
    int bypass2 = 20; //output 4
    int toneStack2_1 = 19; //output 5
    int toneStack2_2 = 18; //output 6
    int bypass3 = 17; //output 7
    int toneStack3_1 = 16; //output 8
    int toneStack3_2 = 15; //output 9

    boolean bypass = true;        //idicators for which mode is active
    boolean toneStack1 = false;
    boolean toneStack2 = false;
    boolean toneStack3 = false;

    void setup()
    {
      pinMode(input1, INPUT);    //setting inputs
      pinMode(input2, INPUT);
      pinMode(input3, INPUT);

      pinMode(led1, OUTPUT);    //setting outputs
      pinMode(led2, OUTPUT);
      pinMode(led3, OUTPUT);

      pinMode(bypass1, OUTPUT);
      pinMode(toneStack1_1, OUTPUT);
      pinMode(toneStack1_2, OUTPUT);
      pinMode(bypass1, OUTPUT);
      pinMode(toneStack2_1, OUTPUT);
      pinMode(toneStack2_2, OUTPUT);
      pinMode(bypass1, OUTPUT);
      pinMode(toneStack3_1, OUTPUT);
      pinMode(toneStack3_1, OUTPUT);

      digitalWrite(bypass1, HIGH);   //sets to bypass mode
      digitalWrite(bypass2, HIGH);
      digitalWrite(bypass3, HIGH);

    }

    void loop()
    {
      input1 = digitalRead(input1);    //reads inputs from pushbuttons
      input2 = digitalRead(input2);
      input3 = digitalRead(input3);

      if(input1 == HIGH && bypass == true) //Bypass to tonestack 1
      {
        digitalWrite(bypass1, LOW);   //turns off bypass transistors
        digitalWrite(bypass2, LOW);
        digitalWrite(bypass3, LOW);

        digitalWrite(toneStack1_1, HIGH);   //turns on tonestack 1 transistors
        digitalWrite(toneStack1_2, HIGH);

        bypass = false;
        toneStack1 = true;
      }

    if(input2 == HIGH && bypass == true) //Bypass to tonestack 2
      {
        digitalWrite(bypass2, LOW);   //turns off bypass transistors
        digitalWrite(bypass3, LOW);

        digitalWrite(bypass1, HIGH);  //needs to be on to let signal flow to tonestack 2

        digitalWrite(toneStack2_1, HIGH);   //turns on tonestack 2 transistors
        digitalWrite(toneStack2_2, HIGH);

        bypass = false;
        toneStack2 = true;
      }

      if(input3 == HIGH && bypass == true) //Bypass to tonestack 3
      {

        digitalWrite(bypass3, LOW); //turns off bypass transistor

        digitalWrite(bypass1, HIGH);  //needs to be on to let signal flow to tonestack 2
        digitalWrite(bypass2, HIGH);

        digitalWrite(toneStack3_1, HIGH);   //turns on tonestack 3 transistors
        digitalWrite(toneStack3_2, HIGH);

        bypass = false;
        toneStack3 = true;
      }

      if(input1 == HIGH && toneStack1 == true) //tonestack 1 to bypass
      {
        digitalWrite(bypass1, HIGH);   //turns on bypass transistors
        digitalWrite(bypass2, HIGH);
        digitalWrite(bypass3, HIGH);

        digitalWrite(toneStack1_1, LOW);   //turns off tonestack 1 transistors
        digitalWrite(toneStack1_2, LOW);

        bypass = true;
        toneStack1 = false;
      }

      if(input2 == HIGH && toneStack1 == true) //tonestack 1 to tonestack 2
      {
        digitalWrite(toneStack2_1, HIGH);   //turns on tone stack 2 transistors
        digitalWrite(toneStack2_2, HIGH);

        digitalWrite(bypass1, HIGH); //sets bypass transistors
        digitalWrite(bypass2, LOW);
        digitalWrite(bypass3, LOW);

        digitalWrite(toneStack1_1, LOW);   //turns off tonestack 1 transistors
        digitalWrite(toneStack1_2, LOW);

        toneStack2 = true;
        toneStack1 = false;
      }

      if(input3 == HIGH && toneStack1 == true) //tonestack 1 to tonestack 3
      {
        digitalWrite(toneStack3_1, HIGH);   //turns on tone stack 3 transistors
        digitalWrite(toneStack3_2, HIGH);

        digitalWrite(bypass1, HIGH);    //sets bypass transistors
        digitalWrite(bypass2, HIGH);
        digitalWrite(bypass3, LOW);

        digitalWrite(toneStack1_1, LOW);   //turns off tonestack 1 transistors
        digitalWrite(toneStack1_2, LOW);

        toneStack3 = true;
        toneStack1 = false;
      }

      if(input2 == HIGH && toneStack2 == true) //tonestack 2 to bypass
      {
        digitalWrite(bypass1, HIGH);   //turns on bypass transistors
        digitalWrite(bypass2, HIGH);
        digitalWrite(bypass3, HIGH);

        digitalWrite(toneStack2_1, LOW);   //turns off tonestack 2 transistors
        digitalWrite(toneStack2_2, LOW);

        bypass = true;
        toneStack2 = false;
      }

      if(input1 == HIGH && toneStack2 == true) //tonestack 2 to tonestack 1
      {
        digitalWrite(toneStack1_1, HIGH);   //turns on tonestack 1 transistors
        digitalWrite(toneStack1_2, HIGH);

        digitalWrite(bypass1, LOW);   //sets bypass transistors
        digitalWrite(bypass2, LOW);
        digitalWrite(bypass3, LOW);

        digitalWrite(toneStack2_1, LOW);   //turns off tonestack 2 transistors
        digitalWrite(toneStack2_2, LOW);

        toneStack1 = true;
        toneStack2 = false;
      }

      if(input3 == HIGH && toneStack2 == true) //tonestack 2 to tonestack 3
      {
        digitalWrite(toneStack3_1, HIGH);   //turns on tonestack 1 transistors
        digitalWrite(toneStack3_2, HIGH);

        digitalWrite(bypass1, HIGH);   //sets bypass transistors
        digitalWrite(bypass2, HIGH);
        digitalWrite(bypass3, LOW);

        digitalWrite(toneStack2_1, LOW);   //turns off tonestack 2 transistors
        digitalWrite(toneStack2_2, LOW);

        toneStack3 = true;
        toneStack2 = false;
      }

      if(input3 == HIGH && toneStack3 == true) //tonestack 3 to bypass
      {
        digitalWrite(bypass1, HIGH);   //turns on bypass transistors
        digitalWrite(bypass2, HIGH);
        digitalWrite(bypass3, HIGH);

        digitalWrite(toneStack3_1, LOW);   //turns off tonestack 3 transistors
        digitalWrite(toneStack3_2, LOW);

        bypass = true;
        toneStack3 = false;
      }

      if(input1 == HIGH && toneStack3 == true) //tonestack 3 to tonestack 1
      {
        digitalWrite(toneStack1_1, HIGH);   //turns on tonestack 1 transistors
        digitalWrite(toneStack1_2, HIGH);

        digitalWrite(bypass1, LOW);   //sets bypass transistors
        digitalWrite(bypass2, LOW);
        digitalWrite(bypass3, LOW);

        digitalWrite(toneStack3_1, LOW);   //turns off tonestack 3 transistors
        digitalWrite(toneStack3_2, LOW);

        toneStack1 = true;
        toneStack3 = false;
      }

      if(input2 == HIGH && toneStack3 == true) //tonestack 3 to tonestack 2
      {
        digitalWrite(toneStack2_1, HIGH);   //turns on tonestack 2 transistors
        digitalWrite(toneStack2_2, HIGH);

        digitalWrite(bypass1, HIGH);   //sets bypass transistors
        digitalWrite(bypass2, LOW);
        digitalWrite(bypass3, LOW);

        digitalWrite(toneStack3_1, LOW);   //turns off tonestack 3 transistors
        digitalWrite(toneStack3_2, LOW);

        toneStack2 = true;
        toneStack3 = false;
      }
    }

And the error message:

    Arduino: 1.8.4 (Windows 7), TD: 1.38, Board: "Teensy LC, Serial, 48 MHz, Smallest Code, US English"

    In file included from C:\Program Files (x86)\Arduino\hardware\teensy\avr\cores\teensy3\IntervalTimer.h:34:0,

                     from C:\Program Files (x86)\Arduino\hardware\teensy\avr\cores\teensy3\IntervalTimer.cpp:31:

    C:\Program Files (x86)\Arduino\hardware\teensy\avr\cores\teensy3\IntervalTimer.cpp: In member function 'void IntervalTimer::end()':

    C:\Program Files (x86)\Arduino\hardware\teensy\avr\cores\teensy3\IntervalTimer.cpp:87:20: error: 'IRQ_PIT_CH0' was not declared in this scope

       NVIC_DISABLE_IRQ(IRQ_PIT_CH0 + index);

                        ^

    C:\Program Files (x86)\Arduino\hardware\teensy\avr\cores\teensy3\kinetis.h:5627:68: note: in definition of macro 'NVIC_DISABLE_IRQ'

     #define NVIC_DISABLE_IRQ(n) (*((volatile uint32_t *)0xE000E180 + ((n) >> 5)) = (1 << ((n) & 31)))

                                                                        ^

    Error compiling for board Teensy LC.

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

I'm at my wits end trying to figure this out. I have reinstalled the Arduino 1.8.4, reinstalled Teensyduino, installed previous version of Arduino, and rebooting my system. Nothing so far has worked. I feel like there is something I am missing with this, as it seems no one else has my problem, from what I could find. Any help would be appreciated.

title: Error Compiling to Board Teensy LC

Answers: 1

body: I experienced a similar error.  Upon further research it seems to be a known issue.  I was able to compile using 1.8.2 and Teensyduino 1.36  I accessed 1.36 from downloading the zip file of the pjrc website in the upper right corner.  The Link was download website.  Then the path was pjrc_2017_04_04\teensy\td_136


body:
I am using ADXL345 accelerometer with Adafruit_ADXL345 library for vibration measurement.

I am reading acceleration at X, Y, Z-axis of a sensor placed on a vibrating platform.And serially sending it to PC at a baud rate of 115200.

When vibration is low sensor shows vibrations but as i increase the vibrations serial transmission seems to be halted. As shown in figure:(x-axis=Samples y-axis=Values )[![Serial Plot Data][1]][1]

 I thought it may be due to loose connections so I soldered its terminals but it behaved the same way at higher vibrations.
 Here is the code that I’m using.

    #include <Wire.h>
    #include <Adafruit_Sensor.h>
    #include <Adafruit_ADXL345_U.h>
    /* Assign a unique ID to this sensor at the same time */

    Adafruit_ADXL345_Unified accel = Adafruit_ADXL345_Unified(12);
    int i=0;
    struct measure
    {
        int timestamp;
        float x;  // ACC in x direction
        float y;  //ACC in y direction
        float z;  //ACC in z direction
    };
    sensors_event_t event;
    struct measure measurements;

    int timestamp = 0;

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

      Serial.println("Accelerometer Test"); Serial.println("");

      /* Initialise the sensor */
      if(!accel.begin())
      {
        /* There was a problem detecting the ADXL345 ... check your connections */
        Serial.println("Ooops, no ADXL345 detected ... Check your wiring!");
        while(1);
      }
      accel.setDataRate(ADXL345_DATARATE_3200_HZ);
      accel.setRange(ADXL345_RANGE_16_G);
         pinMode(LED_BUILTIN, OUTPUT);
      delay(2000);
    }

    void loop(){

     accel.getEvent(&event);
       measurements.timestamp = timestamp++;
       measurements.x  = event.acceleration.x;
       measurements.y  = event.acceleration.y;
       measurements.z  = event.acceleration.z;

    if(measurements.timestamp%2==0)
      digitalWrite(LED_BUILTIN, HIGH);
      else
        digitalWrite(LED_BUILTIN, LOW);

      /* Sending the array with data through serial*/

      Serial.print(measurements.timestamp);
     Serial.print(",");
     Serial.print(measurements.x+0.06);
     Serial.print(",");
     Serial.print(measurements.y+0.7);
     Serial.print(",");
     Serial.println(measurements.z-10.10);
    }

Where does problem lie? How to resolve this issue?

Circuit Connections:
[![Circuit][2]][2]

  [1]: https://i.stack.imgur.com/pDamO.png
  [2]: https://i.stack.imgur.com/85KIS.jpg

title: ADXL345 hangs the micro-controller as vibrations increase

Answers: 1

body:
There is a known issue with the default "Wire" library, where if a certain transition is missed, the code goes into an infinite loop (rather than timing out). You possibly are reaching that situation. A possible reason is your printing of numbers at quite a high baud rate. The printing could be taking up so much time (itself causing serial interrupts as the serial buffer empties) that the I2C code doesn't execute in time the I2C interrupt.

You could try dropping the printing baud rate (something I wouldn't normally recommend) which means the serial interrupts would occur less frequently.

There is a library by DSS Circuits that has a time-out for I2C which may work around this issue to an extent:

http://dsscircuits.com/articles/arduino-i2c-master-library

Another thing you could try would be to summarize the data (eg. sample for 500 ms and then send the average), which would reduce the amount of serial comms.

---

Also you might try lower values for the pull-up resistors, like 4.7k.

---

So, my recommendations are:

* Drop the baud rate (eg. to 9600 baud) and see if the hanging goes away
* Summarize data rather than sending each reading
* Try 4.7k pull-up resistors

If you have a logic analyzer you could look at the I2C signals and see if you can work out if the data is being transmitted as expected when the vibrations occur.

[Saleae](https://www.saleae.com/) sell logic analyzers, the cheapest being $US 109. I use their (more expensive) analyzers extensively for debugging this sort of thing.


body:
I've been working on a project with I2C protocol where an ATmega328 (Arduino) configured as slave, receives messages from an ATtiny (ATtiny85, ATTinyCore by SpenceKonde) configured as master, or from an ESP8266 (ESP-01, Arduino core) configured as master.

All using the standard wire library, powered with 3.3v (LM1117 regulator), SDA and SCL 4.7kohms pull-ups.
The ESP pins used are RX and TX, with 330ohms pull-ups.

Individually, it works (ATtiny to ATmega; ESP to ATmega), but when i connect the three on the same bus, after the first message it stops working and the ATmega doesn't receive more messages.

----------

Code (modified for readability)

ATmega slave:

    #include <Wire.h>

    const int ADDRESS = 56;

    void receiveEvent() {
     Serial.println(Wire.read());
    }

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

    void loop() {
    }

ESP master:

    #include <Wire.h>

    const int DISPLAY_ADDRESS = 56;
    const int PACKET_SIZE = 1;
    const int SDA_PIN = 1;
    const int SCL_PIN = 3;

    void setup(){
     Wire.begin(SDA_PIN, SCL_PIN);
    }

    void loop() {
     byte packet[PACKET_SIZE];
     packet[0] = 'e';
     Wire.beginTransmission(DISPLAY_ADDRESS);
     Wire.write(packet, PACKET_SIZE);
     Wire.endTransmission();
     delay(2500;)
    }

ATtiny master:

    #include <Wire.h>

    const int DISPLAY_ADDRESS = 56;
    const int PACKET_SIZE = 1;
    // SDA = 0; attiny85 pin 5
    // SCL = 2; attiny85 pin 7

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

    void loop() {
     byte packet[PACKET_SIZE];
     packet[0] = 'a';
     Wire.beginTransmission(DISPLAY_ADDRESS);
     Wire.write(packet, PACKET_SIZE);
     Wire.endTransmission();
     delay(1000);
    }

----------

After some research I found out that the wire library can only work with a single master, is this correct? And the esp can only work in master mode.

Am I doing something wrong, or is this simply not possible?

Are there any protocol alternatives for this design?
A single device that only cares about receiving messages, and multiple other devices that only care about sending messages to the central.

Thank you for your time!

title: I2C from two masters (ATtiny85, ESP8266) to one slave (ATmega328)

Answers: 2

body:
If you have 1 receive only device, and 2 send-only devices, why not make the receive-only device the master, but have it poll (periodically, repeatedly ask) the slave devices to send any data they have pending. That way, there is only one master, and it only asks for data when it's ready (that is, not receiving from some other device.)

One purpose of a master/slave bus system is to avoid contention (two or more devices talking at the same time.) The master tells each device when to send, and only listens after it asks.

body:
The problem is in your implementation. If you REALLY need 2 masters there should be a way to make it work.

At the moment the problem that I can see is that both masters continually poll the I2C data lines, effectively this means that the data on the lines is all mixed up and scrambled together. What could do is have 2 wires connecting both masters. When one of the masters is writing to the slave pull the line high, the other master should read this line as high, and not write data to the I2C lines. When the line drops low, it should then take its turn to write to the AtMega. This method would ensure only one master is using the data lines at one time. The implementation is pretty rudimentary and fairly crude and I'm aware the ATtiny may not have enough pins for this.

The best way to solve your problem I think is to have the ESP8266 as your single master, with your ATtiny and ATmega as slaves. Make the ESP poll the ATtiny for its data/instructions it wants to pass to the Atmega, and get the ESP to pass on this data or instructions to the ATmega along with its own data and instructions. This should be a robust and reliable fix.


body:
EDIT 4/2/18: The Arduino tutorial schematics have been corrected! See https://github.com/arduino/Arduino/issues/6433 for that issue.

I have a project where I am trying to load a 16-bit number onto an EEPROM using an Arduino hooked up to two [74HC595][1] Shift registers.

I'm loosely following this Arduino tutorial: https://www.arduino.cc/en/Tutorial/ShiftOut, but I'm getting unexpected outputs depending on the number I try to load into the register. I've reduced everything to as simple a setup as I can, and have spent several hours trying to figure out what the heck is going wrong... obviously to no avail.

Here is the schematic - with the exception that I moved the capacitor off of ST_CP (why would they put that in the tutorial?) to between power and ground:

[![Schematic][2]][2]

Here is my code:

    #define SHIFT_DATA 2
    #define SHIFT_CLK 3
    #define SHIFT_LATCH 4

    void setup() {
      pinMode(SHIFT_DATA, OUTPUT);
      pinMode(SHIFT_CLK, OUTPUT);
      pinMode(SHIFT_LATCH, OUTPUT);

      int address = 0b1111111111111111;  // Case 1
    //int address = 0b0000000000000000;  // Case 2
    //int address = 0b0101010101010101;  // Case 3
    //int address = 0b1010101010101010;  // Case 4
    //int address = 0b0101100110101110;  // Case 5

      shiftOut(SHIFT_DATA, SHIFT_CLK, MSBFIRST, (address >> 8)); // Load first 8 bits
      shiftOut(SHIFT_DATA, SHIFT_CLK, MSBFIRST, address);        // Load second 8 bits

      digitalWrite(SHIFT_LATCH, LOW);
      digitalWrite(SHIFT_LATCH, HIGH);
      digitalWrite(SHIFT_LATCH, LOW);
    }

    void loop() {
      // none
    }

Here is a picture of my breadboard setup with Case 1 loaded:

[![Breadboard setup][3]][3]

And here follows my test cases.

 1. All 1's (1111111111111111). Looks good.
 2. All 0's (0000000000000000). Looks good.
 3. Repeated 01's (0101010101010101). Looks good.
 4. Repeated 10's (1010101010101010). Output: 1010101000000000. First 8 bits match, last 8 are zeros. Huh?
 5. Random sequence (0101100110101110). Output: all over the place. Initially the first 8 bits match as in Case 4, but on repeated resets of the Arduino the output changes, with some weird momentary flickering going on for some of the LEDs. If I press it enough times I can get it back to the initial output, but never what I expect. I am completely stumped. Here is an animated gif of this behavior running on the breadboard: http://i.imgur.com/KEwpSXe.gifv.

What could my problem be? I assume it's something very simple and I'm being an idiot.

  [1]: https://assets.nexperia.com/documents/data-sheet/74HC_HCT595.pdf
  [2]: https://i.stack.imgur.com/q7Pok.gif
  [3]: https://i.stack.imgur.com/akqZU.jpg

title: Weird output from chained 74HC595 shift registers

Answers: 2

body:
I have [forum post about the 595 chip](http://www.gammon.com.au/forum/?id=11518) and [a question and answer about SPI](https://arduino.stackexchange.com/questions/16348/how-do-you-use-spi-on-an-arduino/).

You can use SPI to do the transfer. This is faster and simpler than shiftOut. Also you need to bring the latch low **before** transferring the data.

Simple example sketch:

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

    #include <SPI.h>

    const byte LATCH = 10;

    void setup ()
    {
      SPI.begin ();
    }  // end of setup

    byte c;
    void loop ()
    {
      c++;
      digitalWrite (LATCH, LOW);
      SPI.transfer (c);
      digitalWrite (LATCH, HIGH);
      delay (20);
    }  // end of loop

body:
You should change your capacitors.

You only have 0.1µF instead of 1µF for the bulk capacitor (which really wants to be 10µF). In addition you should add 0.1µF (100nF) capacitors directly across the power pins of each chip:

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

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


body:
I'm trying to send data from an Arduino program to an app running on Google App Engine but `WiFiSSLClient.connect()` always returns false.

This is despite

 - the server being up and running;
 - the code working when the web app was on a different server.

The only possible explanation I can come up with is that the App Engine app uses a `LetsEncrypt` certificate while the other server was using one by another company.

    WiFiSSLClient client;
    if (client.connect(server, 443)){
        // Connected to server
    } else {
        // Failed to connect
    }

Does anyone have any solutions to this problem? I had a look at `WiFiClientSecure`; it has the ability to set the CA certificate in code but this seems like a bit of a pain.

title: WiFiSSLClient will not connect to servers with LetsEncrypt certificates

Answers: 1

body:
The solution is to update the certificates the WIFI 101 Firmware Updater tool (in the Arduino IDE).

1. Install the `FirmwareUpdater` sketch, as described on the [Arduino site][1].
2. Select *Tools -> WiFi 101 Firmware Updater*. Click on the *Add domain* button at the bottom, enter your domain and click *Upload Certificates to WiFi module*.
[![Adding a new domain][2]][2]

3. Upload the sketch to your Arduino. It should now connect to the server.

  [1]: https://www.arduino.cc/en/Tutorial/FirmwareUpdater
  [2]: https://i.stack.imgur.com/lF5Jk.png


body:
I am wondering if someone could explain this to me.

I want to calculate sampling rate of external ADC.
I am using [ADS8320][1] which has max sampling rate of 100kHz, with Arduino MEGA 2560.
SPI divider is set to 128, which makes SPI frequency 125kHz.
Baud rate is 115200 (I am not sure if this is important).

Thanks a lot!

  [1]: http://www.ti.com/lit/ds/symlink/ads8320.pdf

title: How do I calculate sampling rate of external ADC?

Answers: 2

body:
Easy.

1. Based on your set up, figure out the spi speed.

2. Take a look at the adc datasheet, figure out it's frame of transmission . Aka how many pulses per frame / sampling.

3. The product of the numbers in 1 and 2 gives you the minimum time per frame. The inverse of it is the maximum transmission in your application. That speed is cap by the devices own max sampling rate (100ksps).

4. Your actual sampling rate will depend on your specific application but it should not go above the number obtained in 3.

5. You may need to factor in other timing requirements as well so read the datasheet carefully. But the gist is the same.

body:
To get an idea of the sampling rate write a loop that takes 10,000 measurements and time how long it takes. You have your sample rate, not perfect but gives you some idea.

    long start = millis();
    // the loop

    Serial.print( 10000000/(millis() - start) );
    Serial.println(" samples per second");


body:
I'm trying to get my servo motor to sweep from 0 to 180 degrees then back to 0 degrees for infinite amount of times. I using the following code but my motor keeps resetting when it get backs to 0 degrees (meaning it goes 0-->180-->0 then completes a 360 and starts over). Also the 0-180 degree sweep appears to be more of a 0-270 degree sweep. Anyone running into these problems?

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

    int angle = 0;

    void setup() {
      myservo.attach(9);
      myservo.write(angle);
    }

    void loop()
    {
      for (angle = 0; angle < 180; angle += 1)
      {
        myservo.write(angle);
        delay (50);
      }

      for (angle = 180; angle > 0; angle -= 1)
      {
        myservo.write(angle);
        delay(50);
      }
    }

title: Servo motor sweeps beyond 180

Answers: 3

body:
Are you trying to have the servo sweep at a particular speed? Why not just use:

    void loop()
    {
      angle=180;
      myservo.write(angle);

      delay(500); //Allow 0.5 seconds for servo to complete it's move; adjust as necessary depending on servo's rotation speed.

      angle=0;
      myservo.write(angle);

      delay(500); //Allow 0.5 seconds for servo to complete it's move; adjust as necessary depending on servo's rotation speed.
    }

body: Is your servo the modified 360 degree type with no position feedback (meaning the internal feedback potentiometer has been disabled)?

body:
I had a bunch of SG90 mini servos so I tried your code. My servos turn 0 -> 180 -> 0 -> 180 -> 0 -> 180, over and over. No 360 spins at all.

 - Maybe your servo is defect? (can you check with another servo?)
 - Maybe it is not getting enough power? (how are you powering it?) It needs at least 4.8V and at least 220mA
 - Maybe it doesn't get a strong clean PWM signal? (You'll probably need an oscilloscope to check this)


body:
I have bought a ESP8266 wifi shield and I want to use it hotspot, I have tried the examples that have been provided in Arduino IDE, and the shield is getting connected to my network and giving me a wifi but without internet access (like I can connect my phone to the shield but I cannot browse the internet).
Any suggestion please?

Thanks......

title: How to use ESP8266 wifi shield as a hotspot?

Answers: 1

body:
Connecting through the ESP8266 to the internet would require the ESP8266 to handle Network Address Traversal and/or routing, which is not officially supported.

However, if you are prepared to do a lot of work, it can be done. The performance and reliability is bad, but it can be done. See http://bbs.espressif.com/viewtopic.php?t=960 Note that this will require far more skills than running the examples in the Arduino IDE.


body:
I have tried almost everything but my NodeMCU keeps hanging after random intervals, it usually stops working after 2 days, but well... I will describe it's behaviour, what I mean by hanging is that the server stops responding to the assigned static ip, if I restart my modem or the node it works again, but this device is meant to be working endlessly and shouldn't stop working even if it has been connected during one week, I have tested it a lot, it has worked for 2 days, for 3 days, once it worked for 4 days without any problem, but after reconnecting it in another place, hanged again after almost 2 days. I started to think that probably the problem it's related to NodeMCU. So please I would really appreciate any helpful suggestion like assigning ip through the modem or something that can help. Thanks in advance.

The NodeMCU is connected to a usb power hub (A regular android phone wall charger), and it controls a relay.

Here is my code:

    #include <ESP8266WiFi.h>

    const char* ssid = "INFINITUM5607";
    const char* password = "********";

    int ledPin = 13; // GPIO13
    int ledPin2 = 12; // GPIO13
    int desconectado = 5;
    int conectado = 4;
    WiFiServer server(80);
    WiFiClient client;

    int counter = 0;
    int count;

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

      WiFi.mode(WIFI_STA);

      pinMode(ledPin, OUTPUT);
      digitalWrite(ledPin, HIGH);

      pinMode(ledPin2, OUTPUT);
      digitalWrite(ledPin2, HIGH);

      pinMode(conectado, OUTPUT);
      pinMode(desconectado, OUTPUT);
      digitalWrite(desconectado, HIGH);

      connectWifi();

      Serial.print(F("Setting static ip to : "));
      Serial.println(WiFi.localIP());

      // Start the server
      server.begin();
      Serial.println("Server started");

    }

    void loop() {

      delay(200);

      if (WiFi.status() != WL_CONNECTED) {
        delay(100);
        digitalWrite(conectado, LOW);
        digitalWrite(desconectado, HIGH);
       connectWifi();
      }

      // Check if a client has connected
      client = server.available();
      if (!client) {
        return;
      }

      // Wait until the client sends some data
      Serial.println("new client");
      count = 0;
    while(!client.available()){
    delay(1);
    count++;
    if ( count > 1000 )
    {
    Serial.println("Abandoned Client");
    client.stop();
    return;
    }
    }

    //Serial.println("new client");
    //  int t = millis();
    //  while(!client.available()){
    //  delay(1);
    //  if (millis()-t>130) return;
    //  }

      // Read the first line of the request
      String request = client.readStringUntil('\r');
      Serial.println(request);
      client.flush();

      client.println("HTTP/1.1 200 OK");
      client.println("Access-Control-Allow-Origin: *");
      client.println("Content-Type: text/html");
      client.println(""); //  do not forget this one

      // Match the request
      if (request.indexOf("/switch") != -1)  {
        digitalWrite(ledPin, !digitalRead(ledPin));
        digitalWrite(ledPin2, !digitalRead(ledPin2));
        printSwitch();
      }else if (request.indexOf("/uno") != -1) {
        client.print("Canal 1 apagagado | Canal 2 encendido");
        digitalWrite(ledPin, HIGH);
        digitalWrite(ledPin2, LOW);
      }else if (request.indexOf("/dos") != -1){
        client.print("Canal 1 encendido | Canal 2 apagado");
        digitalWrite(ledPin, LOW);
        digitalWrite(ledPin2, HIGH);
      }else if (request.indexOf("/tres") != -1){
        client.print("Canal 1 apagado | Canal 2 apagado");
        digitalWrite(ledPin, HIGH);
        digitalWrite(ledPin2, HIGH);
      }else if (request.indexOf("/cuatro") != -1){
        client.print("Canal 1 encendido | Canal 2 encendido");
        digitalWrite(ledPin, LOW);
        digitalWrite(ledPin2, LOW);
      }else if (request.indexOf("/cinco") != -1){
        printIP();
      }else if (request.indexOf("/apagaruno") != -1){
        client.print("Canal 1 apagado");
        digitalWrite(ledPin, HIGH);
      }else if (request.indexOf("/apagardos") != -1){
        client.print("Canal 2 apagado");
        digitalWrite(ledPin2, HIGH);
      }else if (request.indexOf("/prenderuno") != -1){
        client.print("Canal 1 encendido");
        digitalWrite(ledPin, LOW);
      }else if (request.indexOf("/prenderdos") != -1){
        client.print("Canal 2 encendido");
        digitalWrite(ledPin2, LOW);
      }else if (request.indexOf("/canaluno") != -1){

        if(digitalRead(ledPin) == HIGH) {
          client.print("Off");
      } else {
        client.print("On");
      }

      }else if (request.indexOf("/canaldos") != -1){

        if(digitalRead(ledPin2) == HIGH) {
        client.print("Off");
      } else {
        client.print("On");
      }

      }

    // Set ledPin according to the request
    //digitalWrite(ledPin, value);

      // Return the response

      delay(1);
      Serial.println("Client disonnected");
      Serial.println("");
      client.stop();

    }

    void printSwitch(){

      if(digitalRead(ledPin) == LOW) {
        client.print("Canal 1 Encendido");
      } else {
        client.print("Canal 1 Apagado");
      }
      Serial.println("");
      if(digitalRead(ledPin2) == LOW) {
        client.print("Canal 2 Encendido");
      } else {
        client.print("Canal 2 Apagado");
      }
    }

    void printIP(){
      delay(100);
      client.print(WiFi.localIP());
    }

    void connectWifi()
    {
      Serial.print("Connecting to "+*ssid);
      WiFi.begin(ssid, password);
      while (WiFi.status() != WL_CONNECTED) {
      delay(500);
      Serial.print(".");
      }

      // config static IP
      IPAddress ip(192, 168, 1, 66);
      IPAddress gateway(192, 168, 1, 1);
      IPAddress subnet(255, 255, 255, 0);
      WiFi.config(ip, gateway, subnet);
      digitalWrite(conectado, HIGH);
      digitalWrite(desconectado, LOW);
      Serial.println("");
      Serial.println("Connected");
      Serial.println("");

      // Print the IP address
      Serial.print("Use this URL to connect: ");
      Serial.print("http://");
      Serial.print(WiFi.localIP());
      Serial.println("/");
    }//end connect

title: NodeMCU keeps hanging after random time

Answers: 1

body: Check the power source. If you're powering it via USB it is likely to malfunction over time, but if you use an external and stable power source you won't have that kind of problem.


body:
I searched for very long range wireless communications between two Arduinos, but can't find solutions. I don't live in USA, In my country there are regions, where GSM does not work.
I want wireless communication approximately 500-1 000 KMs.
What are options without GSM for that distance wireless communication(500-1000 KM)?

title: Very long range wireless communication between two arduinos(500-1000 KM)

Answers: 2

body:
> What are options without GSM for that distance wireless communication(500-1000 KM)?

1) use the internet;

2) use narrow band transmission, like qrp;

3) use relays;

4) use satellite phones;

5) use a high-powered lw transceivers.

6) ...

body:
Back in the old days, we used things called modems to connect computers across POTS.

[![old modems][1]][1]

Your country may not have GMS, but I bet you still have old land lines. In that case, you can use a land line + modem to connect the arduinos directly , no Internet involved, no ISP needed, no overhead, no lag, nothing. It's just one Arduino at each end of a very long cable. No TCP/IP needed, but you need your own protocol to keep data in sync and filter out errors. There is lot of well proven ones from the golden era of BBS.

I search Aliexpress, I didn't find any modem suitable for direct conection with Arduino, but there is a lot of USB modem like this:

[![USB Modem][2]][2]

I don't know if they can work with Arduino. I'm afraid that they are *win-modem* only.

What it really works with anything is a traditional modem, like this [model][3] from Multitech (not an endorsing):

[![Multitech modem][4]][4]

You will need a RS-232 level converter however, because RS-232's voltages can go up to 25V. The converter avoids you to deal with the peculiarities of the RS-232 standard and DB-9 connector.

[![RS232-TTL level converter][5]][5]

And a cable, of course.

You can develop and test your project using a *null modem* cable, to connect both Arduinos, a few meters apart, without need of a land line.

  [1]: https://i.stack.imgur.com/HILmV.jpg
  [2]: https://i.stack.imgur.com/Q5LtI.jpg
  [3]: https://www.multitech.com/brands/multimodem-zba
  [4]: https://i.stack.imgur.com/twd2u.png
  [5]: https://i.stack.imgur.com/0ZDHQ.jpg


body:
I have a HDMI switcher which uses a TL1338 IR LED that's connected via a 3.5mm audio jack. It has its own remote for switching between the inputs, but I want to use my TV remote.

In order to do that I want to connect the IR led to an ATTiny85 to receive the input and send the 'translated'code to the switcher.

When analysed with an oscilloscope it seemed that Arduino Libraries output a PWM signal, while the TL1838 outputs a digital signal. Is there a way to simulate a TL1838 signal?

Original situation:
[![Original situation][1]][1]

Goal situation with ATTiny85.
[![Updated situation][2]][2]

  [1]: https://i.stack.imgur.com/hX47O.png
  [2]: https://i.stack.imgur.com/ihD6d.png

title: Simulate V1838B IR LED output

Answers: 1

body:
What you want to do is send "unmodulated" IR Codes, but the library is trying to modulate them with a 38khz carrier. (The TL1838 device has a built-in demodulator.)

While your question is not a duplicate, [this answer][1] applies.

  [1]: https://arduino.stackexchange.com/questions/18582/how-to-send-unmodulated-ir-signal-via-cable


body:
I plan to make an air quality monitoring system that uses Arduino uno, but I can't decide how I will be able to distribute the air condition and harmful gas concentration info and have it available to other people.

Aside from using a GSM module to text individual persons and making a new website to chart the data from the Arduino, what else can I use to receive information that my Arduino sensed to people's smartphones/computers wirelessly?

title: How to send information from Arduino?

Answers: 4

body:
There is a Wi-Fi module named "ESP-01" (which uses the ESP8266 microcontroller) and it comes ready to be used with Arduino. But better than that, I think, is that you can program it directly via Arduino's IDE if you flash it with [NodeMCU's firmware][1]. You can also use a NodeMCU instead of Arduino, but ESP-01 has the advantage of being much, much cheaper.

  [1]: http://randomnerdtutorials.com/flashing-nodemcu-firmware-on-the-esp8266-using-windows/

body:
You can use a pair of ESP8266 WiFi Transceiver modules (one as the client and the other as the server).

There are a few guides to [getting started with the ESP8266][1] out there, which generally contain some helpful tips.

I also found this fairly straightforward [ESP8266 – Wireless Weather Station with Data Logging to Excel][2] project which illustrates the principle of using a pair of ESP8266 modules as client and server.

  [1]: http://randomnerdtutorials.com/getting-started-with-esp8266-wifi-transceiver-review/
  [2]: http://randomnerdtutorials.com/esp8266-wireless-weather-station-with-data-logging-to-excel/

body:
Others suggest ESP8266, but I think it's now outdated, there's a new and improved version of it available named ESP32, it's better in basically every way (faster, more RAM, ROM etc.), not that much more expensive and can still be programmed using the Arduino IDE, that means programming it just as simple as programming an ESP8266.

Disclaimer: ESP32 Arduino core is still under development, some less frequently used features might be experimental or missing.

body:
> what else can I use to receive information that my Arduino sensed to people's smartphones/computers wirelessly?

take a different route. get the information to a pc (or to a server through a pc) and you have much more flexibility.

there are many ways to get that information to a pc, like serial, spi, i2c, acquisition cards, wired / wireless, ....


body:
I read that I'll need a logic level converter like [this][1] to run an ESP8266-01 from the Uno.

But I saw this ESP adapter:

http://www.ebay.com/itm/ESP-01-ESP8266-Serial-Wi-Fi-Wireless-Adapter-Module-3-3V-5V-Compatible-Arduino-/282524471281?hash=item41c7c54ff1:g:wp0AAOSwQ59ZaClP

Two questions:

1. The ESP-01 has 8 connections but this has only 4, how come? Will I get the same functionality?

2. If I'll use this adapter, then I won't need the logic level converter?

  [1]: https://www.sparkfun.com/products/12009

title: ESP-01 adapter and logic level converter

Answers: 3

body:
The module has a 3.3V voltage regulator circuit and **5v-3.3v onboard level conversion circuit**.

Yes, the module can be used with Arduino UNO R3 or compatible board without needing an additional level converter, as it is integrated in the module.

The module has Vcc, GND, TX and RX, so it means it uses a serial protocol for Arduino communication (and you will need two pins in the Arduino). Other pins in the ESP-01 are not needed in this scenario, but you still have access to them via the 8-pins female connector on the module.

It's totally plug and play.

**Addendum: The old way**

This how you connect a standard ESP-01 with an Arduino. The module you are looking at include all the resistors and also connect the CH_PD pin to Vcc. You only need to connect four pins. It saves you time, money and space.

[![Tradicional ESP-01][1]][1]

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

body:
The ESP-01 is a microcontroller that works only with 3.3V. If you don't use a logic converter, it will not work correctly with 5V on TX and RX and you might even damage your module if you use it like that. So answering your second question, the important thing to keep in mind is that you need to power it with 3.3V and the logic level of the data you send must also be 3.3V.

As for the number of pins, the 4 pins are for VCC, GND, TX and RX. These are the only ones you'll need to connect with Arduino. The other pins on the ESP-01 are CH_PD, RST and two GPIOs.

(I'm not sure if you need to connect any of these while using it with Arduino, but in my experience using it standalone i know CH_PD must be connected to VCC in operation mode, and RST must be connected with GND on flashing mode.)

body: I used in one of my projects, instead of a logic level converter, some voltage dividers on the pins, Arduino inputs don't mind the 3.3v, it works just the same.


body:
I have an ESP8266 ESP-01 WiFi module.
I have a project where I need to use the following and send their data to a firebase database.

2x Force Sensitive Resistors(Sensor)

1x GPS module

My question is what GPS module can I use to send GPS location thru the ESP8266 Wifi module. My ESP-01 has only 2 GPIO. What should I do so I can use 2 FSR and GPS module at the same time send all 3 data to firebase realtime database.

Thanks

title: Using multiple sensors on ESP8266 Wifi module

Answers: 2

body:
You really need something external to both provide the analog inputs for the force sensors and the serial communication for the GPS module.

The simplest "something" is another microcontroller.  Ideally one with two UART ports.

You can then:

* Communicate between the microcontroller and the GPS with one UART
* Sample the FSRs with the microcontroller
* Format and send the data to the ESP-01 through the other UART

Using `SoftwareSerial` you chould just about do it with an Arduino Uno (though you'd have to disconnect whatever was on the hardware UART every time you wanted to program it), but ideally something with more UARTs would be better, such as a Mega2560.

A halfway house between the two would be a board based around the ATMega32U2 which uses a direct USB connection for programming leaving the hardware UART free to be used permanently. However you'd still need to use `SoftwareSerial` to emulate the second UART (maybe best for the GPS since it's then only used for receiving).

body:
I would go for an i2c A/D converter, example ADS1015 (4 analog input, 12 bit) and connect that to the ESP-01.

Ref.:

https://en.wikipedia.org/wiki/I²C

https://www.youtube.com/watch?v=6IAkYpmA1DQ&t=32s


body: Is there a way to turn on or off the power supply of up to seven hard drives with the help of an Arduino? Or maybe there is another way to ultimately - but restorable - prevent read/write access to the disks.

title: How to switch on or off up to seven devices individually?

Answers: 3

body:
An Arduino have 13 digital I/O pins so theoretically you can control 13 devices without any additional additional circuits.

You will probably need some circuits for the devices you want to control.

body:
If you want to control them externally, I suggest buying e.g. an 8 channel relay. This way you can easily control them with the Arduino, and using external power for the devices to switch on/off.

If you want extra protection (especially with motors or expecting spikes on signals), use relays with opto-couplers.

body:
Switching power on and off to hard drives is not as simple as you may think.

First you have three voltages to control - 3.3V, 5V and 12V, and on top of that you have (ideally) pre-charging for the 5V and 12V pins. The power-on sequence would ideally be:

1. Power up 5V and 12V pre-charge
2. Power up 3.3V, 5V and 12V main power

That's 5 poles for one drive (although you can get away without the pre-charge).

So you would be switching at minimum 3 power signals per drive. For 7 drives that would be 21 power signals that need to be switched.

**HOWEVER**

**Switching off power to a hard drive using mechanisms that aren't directly under the control of the operating system can cause file-system corruption and data loss.**

The operating system caches data internally and writes it to the hard drive when able to. If the hard drive is turned off while there is still data cached that data will never get written to the hard drive. Worse still, if you turn it off *whilst it is writing* the file-system could become irrevocably corrupted (depending on the file-system in use and the resilience of it).

Most hard drives have the ability to power themselves down at a command from the operating system. I suggest you use this mechanism instead, since it is more reliable that blindly shutting off the power. Chances are your hard drives are already doing this, since most operating systems enable it by default.


body:
I've recently bought a SIM900A A6 GSM module. Whenever I send a command it gives an error: +CME error 58.

Does anybody know what this means and how to solve it?

title: SIM900A A6 module Arduino +CME error 58

Answers: 2

body: Your sim card is probably protected by a PIN. Easiest way to get it working is to put the SIM into a normal phone and remove the PIN protection.

body: I had the same error.  My error was using the incorrect baud rate.  Set the baud rate to 115200.  Also, ensure that "Both NL & CR" option is selected for new line options.  After changing those settings, I had to reboot the A7, and wait for all the status messages to complete before I could send the AT command.


body:
I don't write a lot of C, so I'm always discovering things I only partly understand in the Arduino variety. One of these is how `Serial.print` handles `char[]`.

Does Serial.print always require a null terminator? In the case of (say) `Serial.print(88, DEC);` is a null implied?

What happens in the following cases?

    char buff[3] = "ABC"; // warned because no room for a null
    Serial.print(buff);   // will absence of a null cause overrun?

    char buff[4] = "ABC"; // now there's a null
    Serial.print(buff);   // will the null character be sent too?

Any references appreciated.

title: Serial.print and char[] & null

Answers: 2

body:
When passing a char* you need to also pass some way of telling the function where it ends. In C that is usually the null terminator and that's all a null terminator is for. If that is missing then you get a buffer overrun.

The null terminator is not sent.

body:
The "Serial" is a object/class and that makes it possible to have more than one function for [`Serial.print()`][1]. According to the type of the parameter the proper `Serial.print()` is selected.

This is the include file for the `Serial.print()`: [Print.h][2]
And these are the possibilities:

 - `size_t print(const __FlashStringHelper *);`
 - `size_t print(const String &);`
 - `size_t print(const char[]);`
 - `size_t print(char);`
 - `size_t print(unsigned char, int = DEC);`
 - `size_t print(int, int = DEC);`
 - `size_t print(unsigned int, int = DEC);`
 - `size_t print(long, int = DEC);`
 - `size_t print(unsigned long, int = DEC);`
 - `size_t print(double, int = 2);`
 - `size_t print(const Printable&);`

The reference for [`Serial.print()`][1] is short, but it explains pretty well that those different parameters are possible.

Your `Serial.print(88, DEC);` does not use a string of text, it uses the integer number 88.

As soon as a string of text is used, it should be zero-terminated.
The line `char buff[3] = "ABC";` is indeed wrong, as you already wrote. That is one of the things of the 'c' language. The "ABC" gets a zero-terminater and that makes 4 bytes.

  [1]: https://www.arduino.cc/en/Serial/Print
  [2]: https://github.com/arduino/Arduino/blob/master/hardware/arduino/avr/cores/arduino/Print.h


body:
I have 12V,700mA AC-DC adapter power jack. Is it ok power on arduino board directly using this power jack?

Though Arduino webpage suggests that arduino can stand and upto 20V power supply, I ask this because somewhere it is written that supply 12v, 700mA will end up the board to smoke and need a converter to make it 5V.

Is this correct?

Thanks,
Jyoti Raj

title: Powering Arduino with 12V AC-DC Adapter Jack

Answers: 2

body: You can use that to power the Arduino through the barrel jack or the VIN pin.  The only way you end up with smoke is if you try to pull too much current through that setup.  Don't power any motors or solenoids directly off of output pins for example.

body:
> Is it ok power on arduino board directly using this power jack?

it depends on the regulator used and the current you expect to draw from the regulator.

essentially, you want to make sure that the power dissipation over the regulator isn't too much. that power dissipation is proportional to the voltage drop over the regulator (Vin - Vcc) and the current draw (20ma + whatever you may draw from the arduino).

once you have that, check against the regulator datasheet to make sure that its temperature rise is within range.


body:
My project is to use an Arduino to control the lighting of a small apartment. My preferred option is to replace each wall light switch with a 4x4 membrane keypad (https://www.amazon.co.uk/Mirocle-Matrix-Membrane-Keyboard-Arduino/dp/B01LMU6OPG/ref=sr_1_19?s=electronics&ie=UTF8&qid=1504376458&sr=1-19&keywords=membrane+keypad). The UX would allow any keypad to control any light, eg. pressing 1-4 will set light 1 to brightness 4.

The problem I have is this will result require 4 x 8 = 32 pins, so I'm looking for alternatives.

So my questions:-

1/ Is there a simple pll to serial converter that I should be using to interface the keypads?

2/ Can I wire multiple keypads onto the same set of 8 pins? Only one keypad will ever be touched at one time.

3/ Are there simple serial versions of the classic membrane keypad.

title: connecting multiple keypads

Answers: 2

body:
As far as I know, you can connect multiple keypads of this type to a single set of 8 pins.  However, it seems like a lot of wire needs to be strung to get this to work, for each switch, 8 wires for the keypad, and two, or more, for power control.

Were I to do this project.  I would likely handle each switch independently, embedding a Pro Mini in each switch box along with an HC-12, or some such.  This means no wires are needed, any pad could control any switch, and expansion is much easier.

Of course, this is only what I would do, and you understand your own requirements far better than I.

body:
Or the 8 pins 4 will be connected to output pins to be enabled one at a time and 4 will be connected to input pins that get shorted to the input pins when the button is pressed.

The way to get a keypress from this will be to pull a single output pin high and then check all of the inputs, if any of them are high then the corresponding button is pressed.

If you want to treat all keypads the same then you can simply put them in parallel. If you want to treat each of them differently then you can parallel either the inputs or the outputs. But the other set needs to have a S2P or P2S shift register to get the proper data or make the correct pin high.

Though it will probably be simpler if each got their own microcontroller to poll the keypad and use a different longer range protocol to communicate to the main controller.


body:
For my project i need to send some data logged into a SD card to a remote server.
For this im using an XBee S6b wifi module connected to an arduino. ive had trouble connecting the xbee module to wifi. and also how can i set the ssid and other information through arduino?

title: XBee s6b internet

Answers: 1

body:
You configure the XBee with AT commands. However there is one important thing to know about the XBee: it loves to be in "data" mode and won't stay in command mode while you play with it.

You need to first get into command mode by sending `+++` with a delay each side of it:

    delay(1000);
    xBeeSerial.print(F("+++"));
    delay(1000);

Then you can send commands:

    // Set the SSID:
    xBeeSerial.println(F("ATIDThis Is My SSID"));
    // Set the wireless key:
    xBeeSerial.println(F("ATPKTh!sI5mYk3Y"));

Once you have set the details you need to write the settings to flash and reset the XBee for the changes to take effect:

    xBeeSerial.println(F("ATWR"));
    xBeeSerial.println(F("ATFR"));

After each command you should really be looking for the "OK" response.

If at any time you don't sent anything for more than a few seconds the XBee will exit command mode and go back to data mode - at which point you will have to go back to command mode with the delays and `+++`.

It's easiest to configure the XBee using your computer and an XBee Explorer.

All the AT commands are detailed [here](https://www.digi.com/resources/documentation/Digidocs/90002180/).


body:
Arduino newbie here, so this question might sound too simple. I am trying to run a parallax continuous rotation servo using Arduino Uno. From the reference, I learned that the servo needs to be "attached" to one of digital pins with PWM capability, and the servo's speed can be controlled by `write(0~180, 90=stop)`.

But I am having a hard time understanding the role of the PWM digital pin. If the servo's speed and direction of rotation is determined by `write()`, what is the role of `attach(pin#)`?

Thanks in advance!

title: Servos: attach() and write()

Answers: 2

body:
`attach` tells the servo library which pin it should be writing to, this is stored somewhere in ram and `write` will look it up and communicate with the correct pin.

It's possible that you are using the other pwm capable pins for other purposes and suddenly having that library interfere with that is not a good thing.

body:
First of all, you don't need to connect it to one of the PWM pins. Any digital output pin will work just fine.

Judging by the Arduino reference, attaching the servo to a pin is kind of like to declare a variable. By using `myservo.attach(pin)` you also give the servo a name (myservo in this case), and you can also add maximum and minimum values to the servo's rotation by adding two extra values to the end: `myservo.attach(pin, min, max)`

When you then use the `myservo.write()` function, the Arduino will "remember" what pin myservo is connected to, as well as the maximum/minimum settings for it.


body:
Guys i have done project home automation over Android in which i have use NodeMCU and relay to control switching of lights but this is a offline project.

Now I want to connect it with internet please tell me if I can connect NodeMCU to mobile WiFi.

I don't have router at home  please tell me if it is possible and how?

title: Is it possible to connect nodemcu to mobile internet and how?

Answers: 3

body:
If you have a mobile wifi router, the nodemcu can connect to it just as it would connect to a fixed router.
If you want to connect the nodemcu to the internet without a mobile wifi router, you can use a gsm/gprs/3G/4G module, for example the SIM800L. (Provided the location has cell coverage.)

body:
You don't need an external router or LAN to connect nodeMCU with Android or any other TCP/IP device. nodeMCU is capable of works as a WiFi access point, among other things.

You use he function `wifi.setmode()` to configure the WiFi mode to use. NodeMCU can run in one of four WiFi modes:

 1. **Station mode**, where the NodeMCU device joins an existing network.
 2. **Access point** (AP) mode, where it creates its own network that others can join.
 3. **Station + AP mode**, where it both creates its own network while at the same time being joined to another existing network
 4. **WiFi off**

When using the combined Station + AP mode, the same channel will be used for both networks as the radio can only listen on a single channel.

Now, to connect to Internet you will need something else. You can use a SIM800/SIM900 module, which let you conect your nodeMCU to Internet and send/receive SMS.

In this scenario, nodeMCU will connect directly to Internet for your remote connections, and will also works as WiFi router for local connections.

Keep in mind that nodeMCU is a lightweight router.

body:
I have a wifi library.This is how I connect the NodeMCU with that library.

    #include <ESP8266WiFi.h>

    #define WIFI_SSID "name_of_your_hotspot"
    #define WIFI_PASSWORD "password_of_hotspot"

    void setup() {
       Serial.begin(9600);
       WiFi.begin( WIFI_SSID,  WIFI_PASSWORD) ;

        Serial.print("connecting");

        while (WiFi.status() != WL_CONNECTED ) {
            Serial.print(".");
            delay(500);
        }

         Serial.println();
         Serial.print("connected");
         Serial.println(WiFi.localIP);
    }

    void loop () {
        // Your code
    }

I used this tested and working code. Comment if any issue.

Make sure you import the library.

Hope this fixed your issue.

***EDIT : 4th Jan 2018***

I know this topic is old and maybe the OP solved this problem but I saw many people struggling with this same situation how to connect nodeMCU to an internet connection.

So, I created a medium post with detailed information on how to Connect ESP8266 module to the internet? You can read the [story here][1] (I am not paid or sponsored by this post I made this story to help the newbies)

If you still have any problem comment down below or add a response in my medium story.

  [1]: https://medium.com/@raajnadar/connect-esp8266-module-to-internet-81cab724b8c3


body:
I am trying to set IAC of HC05 via AT Commands, but for some reason, the result is not as desired.

I need to set the IAC as '1234', for which I enter the command:

    AT+IAC=1234

The module responds OK, but when I ask `AT+IAC?`, it replies '01234'.

Now, it has been troubling me for the past few days. I've also tried adding '\r\n' to the end of command, but it sets the IAC as '1234444'

I would be thankful if you could help me with this! I tried searching the net but to no avail.

title: How to set Inquire Access Code (IAC) via AT commands on HC-05?

Answers: 1

body:
You have to have `\r\n` in both the set and read command.

Example:

    AT+IAC=12345f\r\n
    OK

    AT+IAC?\r\n
    +IAC: 12345f
    OK


body:
I am a newbie and have followed a tutorial to build a battery level indicator as below
[![the basic design ][1]][1]

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

Please suggest any changes I'll need to make to make the circuit useful with a 48V battery as the above circuit is tested with a 12V one.
Thank You.

title: I have built a battery level indicator and have tested with a 12V battery Would it harm my arduino board if I connect a 48V battery?

Answers: 2

body:
You have a voltage divider there, which would give (if the pre-set pot was set to the maximum):

    Vout = (Vin * R2) / (R1 + R2)
    Vout = (12 * 10000) / (100000 + 10000)
    Vout = 1.09

Thus a 12V battery would present 1.09V at the analog input.

This same wiring would seem to be in range for a 48V battery:

    Vout = (48 * 10000) / (100000 + 10000)
    Vout = 4.36

Since the analog input can handle up to 5V, then that should be OK. However I would test the voltage divider output first with a multimeter to make sure it doesn't exceed 5V - before connecting it to the Arduino.

---

You would probably need to change the code to test for different ranges of input voltages, other than what is used for the 12V battery.

body:
To get a smoother switch from one level to another you could introduce another resistor and use analogWrite() to dim one LED and make next brighter.

Ref.: https://www.arduino.cc/en/Tutorial/PWM

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

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


body:
I am trying to prototype a wearable device which will have about 120 RGB LEDs. I was considering the WS2812B but they seem to draw about 50mA and so may not be a good option since I will be powering them from a battery.

I would be glad to know of other options or ways to implement the LEDs in order to consume less power.

title: Low power RGB LED for wearable device

Answers: 1

body:
You can reduce the current by simply reducing the duty cycle. For example, to display red, rather than sending 255 as the red component, send 42.

If you divide each of the R/G/B values by the same figure you get the same colour, just duller. In a quick test I found that a 24-pixel strip only used 67 mA if I sent red=0, green=0, blue=42 which made them look a dull blue. If you send a value of 8 (in a single channel) then it takes 25 mA for 24 pixels.

A bit more testing reveals a base consumption of 21 mA even if you are sending black. That is, the overhead is 21 mA, which works out at about 1.1 mA per neoPixel.

Based on that, you would consume 335 mA to make 120 NeoPixels show a moderately bright red.

I don't think there is going to be some "magic bullet" that lets you light up 120 LEDs brightly, but not use much power. However using the NeoPixels which lets you have fine control over the brightness of each of the R/G/B pixels is probably going to be about as close as you can get.

The figure of 50 mA which you quoted is to have "full brightness" on all three colours (ie. bright white).


body: I have bought a HC05 bluetooth module and I think I accidentally short circuited it. Is there any way to change the voltage regulator or methods to reuse it again?

title: HC-05 module short circuit

Answers: 1

body:
I suppose you're referring to the HC05 module, already soldered on a board, with the 6-pin header. The regulator is on that board.

Online you'll find several versions of that board, therefore you should check the schematics, to find which you need to mount. For instance, on some board, a R1114-33 is used.

Changing the regulator is not the hardest task on earth, however, other components are very close to it (capacitors).

Still there are 2 things to consider:

 - Is it worthy to change the regulator? That module will cost few
   bucks.
 - As you can see from the datasheet, the regulator is short-circuit protected (yes, it does not mean that it will be indestructible). I think, instead, you destroyed one of the two ICs of the bluetooth module soldered on board. And those one, beside of being quite difficult to find and expensive in small quantity, they are very hard do replace.

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

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


body:
I run Arduino IDE on both my Mac and under Raspbian on a Raspberry Pi, both running the latest version of OS.

The Raspberry Pi has `Arduino 2:1.0.5+dfsg2-4.1` and I am running the latest `1.8.4` on macOS.
Debian is always somewhat behind the latest software, and this has not concerned me before, as I have never had issues before. (I know I could download the latest ARM32 build or compile from source, but this would probably generate a lot of dependencies.)

I have recently run into a couple of problems.
Compiling a script which has `#include <SdFat.h>` generates an error, although the library is present in `~/sketchbook/libraries/SdFat/src/SdFat.h`. This does not seem to be an issue on macOS.

I was also trying to program an Atmega using a Uno as ISP as in "Using an Arduino as an AVR ISP". I have done this in the past, but the instructions and the Arduino program seem to have changed; there is no longer "Upload Using Programmer" menu, but suggests the "Burn Bootloader" command. Does this upload both the Bootloader and Sketch?

title: Differences between Arduino IDE versions

Answers: 2

body:
> Debian is always somewhat behind the latest software

No, when it comes to the Arduino IDE Debian is *frozen* on an ancient version.

1.0.5 is considered to be too old to use. Many many things have changed since then - bug fixes, optimisations, new API components. And not least the implementation of the Board Manager for installing support for more boards, both by Arduino and other makers, and support for multi-arch libraries (which your SdFat library is with a `src` folder in it).

You should never install the Arduino IDE from the Debian repositories. Instead you should download the current version of the Arduino website (http://arduino.cc/download) as a tar.\z file and extract it into a folder and run it from there.

body:
Majenko answered why my sketch did not compile.

I decided to give it a try and downloaded `arduino-1.8.4-linux32.tar.xz`.
I was somewhat concerned that there seemed to be no indication whether the `Linux ARM` supported ARM6, or ARM7.

The download itself contained absolutely no information, not even a README. I ran `install.sh` as outlined in  https://www.arduino.cc/en/Guide/Linux and Arduino IDE installed alongside the existing Arduino IDE, and worked (at least on the PI3).

I also solved my issue using a Uno as ISP. The documentation on the Arduino site now describes "Use the Burn Bootloader command". I found the missing "Upload Using Programmer" menu under the Sketch menu.


body:
My Arduino Uno R3 is not detected by any laptop (I tried 3 laptops). Under devices there is no Arduino port or other devices option. It does not make sound on inserting USB cable. On plugging the USB LED 13 doesn't blink. I is just continuously on. Reset also didn't blink LED 13. Even on external power also it's not resetting.

I checked the USB cable but it's working for my friend's Arduino in my laptop too.

5V Pin giving voltage around 4.96 v, and 3.3 also giving voltage around 3.27 v.

Now I don't have access to any other Arduino for testing. Is there any way to figure out whether the ATmega chip is fried or whether it's a bootloader problem? And how to fix them? Thanks in advance.

title: Can't upload the program to Arduino Uno

Answers: 4

body:
If you have access to a linux computer, what does `lsusb` say when it is plugged in over USB? Compare that output to lsusb with no Arduino plugged in. If you don't, does the arduino show up as a device to your OS at all?

[You could also use your friend's arduino to reflash your bootloader][1]. If that still doesn't work, or if your arduino doesn't show up as a device, [you can try reflashing the atmega16u4][2] ( the USB <-> serial chip ). It is the chip responsible for telling the computer that it is an arduino serial port, so if things are still getting power, but not showing up, I would check that chip.

If it is neither of those things, there may be something wrong with one of the passive USB components, maybe one of the varistors died and is now shorted to ground, for instance. I could give more help if you share the schematic for your specific board.. is it an official Arduino, or a clone?

  [1]: https://learn.sparkfun.com/tutorials/installing-an-arduino-bootloader
  [2]: https://www.arduino.cc/en/Hacking/DFUProgramming8U2

body:
> Can't upload the program to Arduino Uno

if your trouble is limited to just "the program", then the issues must be specific to that program.

if you cannot upload "any program", then the issues must be hardware or host related.

body:
While installing the Arduino software,

there are several **window pop ups** which occur to **install the  drivers** needed for the operating system to communicate with the device.

Click **install** to all of them.

body: It is probably not a problem with the Atmega328p chip or its bootloader; the Uno has a separate processor to handle USB - an Atmega 32U4, which is the flat, surface-mount chip right behind the USB connector on the board. If that or its firmware is damaged, your PC won't recognize the device when you plug it in. If that chip is up and running, your PC will see it.


body:
I have two somewhat similar sketches that use both HC-12 [for data collection] and a W5100-type Ethernet Shield [for Email construction and transmit].
Both sketches run fine until the code for the Ethernet Shield is invoked, which creates a connection and successfully transmits an Email.
Once this happens, the HC-12 no longer receives transmits.  No exceptions are raised, and I am at a loss to determine the cause of the problem.
[The HC-12 is using pins 50-52.]

I have other sketches that use either the HC-12 or the Ethernet Shield, and they work fine.  Before I build a custom sketch to attempt problem isolation,
I thought I would simply ask the question of whether known conflicts exist.  I know that many questions are resolved by posting the sketch and someone other
than the author scanning it.  I think that impractical in this particular case.  The sketch comprises 6,000+ lines of code.

If no helpful responses are forthcoming, I will continue with problem isolation, and post again if no success is achieved.

title: Known conflicts between use of HC-12 and Ethernet Shield on Mega2560?

Answers: 1

body:
As suggested by Majenko, the problem results from using Software Serial for the HC-12, and unfortunately choosing the pin set 50-52, which conflicts with the pin usage specification for the Ethercard Library.
Hence, the HC-12 code works fine until usage of the Ethernet shield is finally activated.  From that point on, the Ethernet code functions properly,  whilst the HC-12 code does not.  The recommended solution, which does indeed solve the problem, is to abandon usage of SoftwareSerial for the HC-12, and use Serial1, or Serial2, or Serial3 instead.

I do not feel that the solution to the problem is truly mine, but post it only that the information may be of subsequent use to a user encountering a problem of similar nature.


body:
I'm working on a midi device with a pro micro, it's reading as a midi device, but not outputting any notes, here's my program:
    const int button1 = 2;
    const int button2 = 3;
    const int button3 = 4;
    const int button4 = 5;
    const int button5 = 6;
    const int button6 = 7;

    int note = 0;

    const int c3 = 36;
    const int d3 = 38;
    const int e3 = 40;
    const int f3 = 41;
    const int g3 = 43;
    const int a3 = 45;

    void setup() {

      pinMode(button1,INPUT);
      pinMode(button2,INPUT);
      pinMode(button3,INPUT);
      pinMode(button4,INPUT);
      pinMode(button5,INPUT);
      pinMode(button6,INPUT);

      Serial.begin(31250);

    }

    void loop() {
      int button1State = digitalRead(button1);
      int button2State = digitalRead(button2);
      int button3State = digitalRead(button3);
      int button4State = digitalRead(button4);
      int button5State = digitalRead(button5);
      int button6State = digitalRead(button6);

      if (button1State == HIGH) {
        note = c3;
        noteOn(0x90, note, 0x64);
      }
      if (button1State == LOW) {
        note = c3;
        noteOn(0x90, note, 0x00);
      }

      if (button2State == HIGH) {
        note = d3;
        noteOn(0x90, note, 0x64);
      }
      if (button2State == LOW) {
        note = d3;
        noteOn(0x90, note, 0x00);
      }

      if (button3State == HIGH) {
        note = e3;
        noteOn(0x90, note, 0x64);
      }
      if (button3State == LOW ) {
        note = e3;
        noteOn(0x90, note, 0x00);
      }

      if (button4State == HIGH) {
        note = f3;
        noteOn(0x90, note, 0x64);
      }
      if (button4State == LOW) {
        note = f3;
        noteOn(0x90, note, 0x00);
      }

      if (button5State == HIGH) {
        note = g3;
        noteOn(0x90, note, 0x64);
      }
      if (button5State == LOW) {
        note = g3;
        noteOn(0x90, note, 0x00);
      }

      if (button6State == HIGH) {
        note = a3;
        noteOn(0x90, note, 0x64);
      }
      if (button6State == LOW ) {
        note = a3;
        noteOn(0x90, note, 0x00);
      }

    }

    void noteOn(int cmd, int pitch, int velocity) {
      Serial.write(cmd);
      Serial.write(pitch);
      Serial.write(velocity);
    }

title: Midi Program not sending notes

Answers: 2

body:
Check:

- If your serial properties are ok (baudrate 31250, 8 bits, 1 stop bit)
- Check if noteOn is really called (print out the values which are sent)
- Show your MIDI circuit, assuming you think no MIDI notes are send because you have a MIDI connector attached.
- Use a protocol analyzer if you have one to check the MIDI signals sent
- Check the components of your circuit, e.g. if you use an opto-coupler, what types is it? some are too slow for MIDI
- Do not use virtual serial ports, I tried with MIDI and they give bad results (checked on Uno).

body:
You are handling your buttons in completely the wrong way. You are basically saying:

> While I press this button send a constant stream of NOTE ON commands. Otherwise send a constant stream of NOTE OFF commands.
>
> At the same time, send more NOTE OFF commands because the other buttons aren't pressed.

So you can see it's going to be a bit of a mess.

Instead you need to detect *changes* in the state of a button.

For example:

    void loop() {
        static bool oldButton1 = LOW;

        bool button1State = digitalRead(button1);

        if (button1State != oldButton1) { // It changed from last time
            oldButton1 = button1State; // Remember it for next time
            if (button1State) { // Pressed
                noteOn(0x90, c3, 0x64);
            } else { // Released
                noteOn(0x80, c3, 0x00); // Note: 0x80 is NOTE OFF, not 0x90.
            }
        }

        ... etc for the other buttons ...
    }


body:
I'm starting to explore using an Arduino to control a couple of switches programatically. I have read somewhere about relays firing during reboot due to floating inputs/outputs during the reboot phase.

What is the best way to ensure that a relay will not fire on a reboot?

Is there a simple wiring diagram to explain it? I am using an Arduino Uno and a [Relay Module][1].

Any assistance would be greatly appreciated.

  [1]: https://www.jaycar.com.au/medias/sys_master/images/8978832654366/XC4419-dataSheetMain.pdf

title: Wiring diagram for Arduino to prevent relay firing on reboot

Answers: 3

body: You can add a pull down/up resistor between the wire and ground/vcc so that when the arduino pin is set to high impedance during reboot the wire is pulled low/high as desired.

body:
Two things:

1. If that relay uses a FET input with no pulldown then you should add your own. If it uses an opto-isolator there is no floating problem to deal with.
2. Don't use pin 13 for a relay - that is connected to the LED which blinks during reset and will "flash" your relay.

body:
> What is the best way to ensure that a relay will not fire on a reboot?

put pull-up/down, as appropriate, on those pins.