body:
im trying to connect wifi module to my MEGA 2560 board.
i set up the board as the picture bellow

[![board setup][1]][1]

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

and my program is as follows

    #include <SoftwareSerial.h>

    #define DEBUG true

    SoftwareSerial esp8266(18,19); // make RX Arduino line is pin 2, make TX Arduino line is pin 3.
                                 // This means that you need to connect the TX line from the esp to the Arduino's pin 2
                                 // and the RX line from the esp to the Arduino's pin 3
    void setup()
    {
      Serial.begin(9600);
      esp8266.begin(9600); // your esp's baud rate might be different

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

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

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

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

      sendCommand("AT+RST\r\n",2000,DEBUG); // reset module
      sendCommand("AT+CWMODE=1\r\n",1000,DEBUG); // configure as access point
      sendCommand("AT+CWJAP=\"mySSID\",\"myPassword\"\r\n",3000,DEBUG);
      delay(10000);
      sendCommand("AT+CIFSR\r\n",1000,DEBUG); // get ip address
      sendCommand("AT+CIPMUX=1\r\n",1000,DEBUG); // configure for multiple connections
      sendCommand("AT+CIPSERVER=1,80\r\n",1000,DEBUG); // turn on server on port 80

      Serial.println("Server Ready");
    }

    void loop()
    {
      if(esp8266.available()) // check if the esp is sending a message
      {

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

         esp8266.find("pin="); // advance cursor to "pin="

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

         digitalWrite(pinNumber, !digitalRead(pinNumber)); // toggle pin

         // build string that is send back to device that is requesting pin toggle
         String content;
         content = "Pin ";
         content += pinNumber;
         content += " is ";

         if(digitalRead(pinNumber))
         {
           content += "ON";
         }
         else
         {
           content += "OFF";
         }

         sendHTTPResponse(connectionId,content);

         // make close command
         String closeCommand = "AT+CIPCLOSE=";
         closeCommand+=connectionId; // append connection id
         closeCommand+="\r\n";

         sendCommand(closeCommand,1000,DEBUG); // close connection
        }
      }
    }

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

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

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

        long int time = millis();

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

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

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

        return response;
    }

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

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

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

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

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

        long int time = millis();

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

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

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

        return response;
    }

but i always recieve the following error

    Arduino: 1.6.12 (Windows 7), Board: "Generic ESP8266 Module, 80 MHz, 40MHz, DIO, 115200, 512K (64K SPIFFS), ck, Disabled, None"

    Sketch uses 228,949 bytes (52%) of program storage space. Maximum is 434,160 bytes.
    Global variables use 32,796 bytes (40%) of dynamic memory, leaving 49,124 bytes for local variables. Maximum is 81,920 bytes.
    warning: espcomm_sync failed
    error: espcomm_open failed
    error: espcomm_upload_mem failed
    error: espcomm_upload_mem failed

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

any idea where i went wrong ?

title: connecting ESP8266 to mega 2056

Answers: 2

body:
* Do not use SoftwareSerial on a hardware serial port. It is pointless.
* Do use a voltage divider to convert the Arduino's 5V TX to the required 3.3V the ESP8266 needs.
* Do not try and program the Arduino as if it were an ESP8266 - it won't work.

I think you are getting a little confused here...

body: Connect your ESP directly to your PC. Test AT commands first. They will tell you if your good to go or not. Just open your serial monitor and set the baud rate to 115200. Select carriage return and type in AT. If it responds OK. Then your code is the problem. If it doesn't return OK, then your ESP or circuit is the problem.


body:
I am currently using arduino library to logically set my digital pins high or low, but I just realized how slowly it actually sets those pins, which is especially problem as i am doing this in a ISR routine. Can't this be done faster by actually acessing the direct port, and setting the current pin?

How do I convert something like this

      digitalWrite(11, !digitalRead(11));

To something faster?

I am using a Arduino UNO..

title: Is possible to set a pin faster than digitalWrite?

Answers: 6

body: Yes that can be done by manipulating the ports directly. Here is the link to Arduino https://www.arduino.cc/en/Reference/PortManipulation

body:
Yes there is!
You can directly manipulate the port. The Arduino website has a pretty good explanation for it [here.][1]

Togelling a pin as asked by you can be simply done by something like this:

      PORTB ^= _BV(PINNUMBER)

A simplified way is the [digitalWriteFast][2] library.
> This library consists of a complex header file that translates digitalWriteFast, pinModeFast, digitalReadFast into the corresponding PORT commands. It provides syntax that is as novice-friendly as the arduino's pin manipulation commands but an order of magnitude faster.

  [1]: https://www.arduino.cc/en/Reference/PortManipulation
  [2]: https://code.google.com/archive/p/digitalwritefast/

body:
Since pin 11 on the ATmega328P is PB3:

    PINB |= _BV(PB3);

body:
**Yes, it is possible**

The atmel chip at the core of the arduinos can set or clear individual pin output levels in a single operation. There are special instructions to do so ```SBI``` and ```CBI```- you just need to figure out what C compiles down to those instructions.

Each pin is represented by one bit of a port byte, for pin 11 it's bit 3 on port B.  So you can toggle it with

    PORTB ^= _BV(PB3);

or set it with

    PORTB |= _BV(PB3);

or clear it with

    PORTB &= ~_BV(PB3);

Probably the last two will compile to a single ```SBI```/```CBI``` instruction while the toggle one may or may not, depending on the code and how the compiler optimises it.

body:
The fastest way may be to use assembly from your C++ code:

    asm volatile("SBI %[IOREG], %[BIT] \n\t"::[IOREG] "I" (&PINB), [BIT] "I" (PB3));

This forces a `1` to the bit for pin 11 (bit 3 on port B of the ATmega328), which, as per the Atmel datasheet, will simply toggle output (1 to 0 or 0 to 1) on that pin (provided it was initially setup as output).

As far as I remember the assemby instruction `SBI` used above cannot be generated by g++ (the C++ compiler used by Arduino IDE), hence you have to code it yourself.

You won't be able to achive a better performance as this single assembly instruction takes exactly 2 clock cycles to execute (ie **125 ns** on an Arduino UNO).

body:
The Arduino [GPIO][1] library has been developed to allow high performance digital pin access. Most access functions are compiled to a single instruction and execute in 1-2 clock cycles. The library functions are more than 10 times faster than the Arduino digital pin functions. In some cases as much as 100 times faster.

Additional support classes are available for Shift Register Input/Output, and Software Serial. These also demonstrate how the GPIO template class may be used to construct additional libraries.

This library supports boards based on SAM3X8E, ATmega168, ATmega328P, ATmega32U4, ATmega1280, ATmega2560, ATtinyX4 and ATtinyX5.

The classical [blink][2] sketch looks like this:

    GPIO<BOARD::D13> led;

    void setup()
    {
      led.output();
    }

    void loop()
    {
      led = HIGH;
      delay(1000);
      led = LOW;
      delay(1000);
    }

Please see [github][1] for benchmarks and further [documentation][3] and examples.

  [1]: https://github.com/mikaelpatel/Arduino-GPIO
  [2]: https://github.com/mikaelpatel/Arduino-GPIO/blob/master/examples/Blink/Blink.ino
  [3]: https://mikaelpatel.github.io/Arduino-GPIO/


body:
i need to read a voltage with an arduino pro mini using the analog pins.

I created this simple test code:

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

    int sensorValue;
    float voltage;

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

    void loop() {
      sensorValue = analogRead(A0);
      voltage= sensorValue * (5.0 / 1023.0);
      Serial.println(voltage);
    }

my setup looks like this:
![hardware setup](https://i.stack.imgur.com/dzobb.png)

everything works so far. I get about 4,5v as a result. Now i want to port everything to an arduino pro mini. After i did that i only got 2,5v as a result. I also tried it with different pins and with an other arduino pro mini.

So what did i do wrong? Do i need an other pull-up resistor?

title: arduino pro mini analog pins read different values

Answers: 1

body:
I made a circuit bellow for you. Note that the top resistor is 100 ohm and the bottom one is only 10 ohm. What I did is called a voltage divider. This way you can read voltages up to 50V. Simply connect the positive of your power source that you want to measure to the red wire and the ground of that same source to the black wire.

I also included a code that you could use:

Please notify me if any mistakes were spotted.

    #define sensor A0 //defining sensor pin

    float resistor1 = 100; //you can change it if you want, just make sure you also do it on the circuit
    float resistor2 = 10;

    float Vmax = (5*resistor1 + 5* resistor2)/resistor2;

    void setup() {
      pinMode(sensor, INPUT); //declaring sensor as an output
      Serial.begin(9600);

      Serial.print("Do not input more then (V) : "); // print max input voltage
      Serial.print(Vmax);

      Serial.println(); //skip line
    }

    void loop() {
      float V = analogRead(sensor); //measuring analog values

      V = analogRead(sensor) * Vmax / 1024

      Serial.println(V); //printing voltage
    }

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

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


body:
I am using 20 x 4 LCD And 3 x4 keypad I want to enter and store 3 inputs in different variables the code I am using can store 3 inputs and display it right in serial monitor example I type 5 digits using keypad it will store and display correctly in LCD and serial monitor the right value however if its more than five it has negative output and very far to what inputted. Thank you for help .The code is...  [![enter image description here][1]][1][![enter image description here][2]][2]

  [1]: https://i.stack.imgur.com/F17ID.jpg
  [2]: https://i.stack.imgur.com/Ju2Nc.jpg

    #include <SoftwareSerial.h>
    #include <LiquidCrystal.h>
    SoftwareSerial mySerial(6,5);
    #include <Keypad.h>
    LiquidCrystal lcd(7, 8, 9, 10, 11, 12);
    const byte ROWS = 4; //four rows
    const byte COLS = 3; //three columns

    char keys[ROWS][COLS] = {
      {'1','2','3'},
      {'4','5','6'},
      {'7','8','9'},
      {'*','0','#'}
    };
    byte rowPins[ROWS] = {19, 18, 17, 16}; //connect to the row pinouts of the keypad
    byte colPins[COLS] = {15, 14, 13}; //connect to the column pinouts of the keypad

    int count=0;
    Keypad kpd = Keypad(makeKeymap(keys), rowPins, colPins, ROWS, COLS);

    char entryStr[12];   // This can hold up to 4 digits
    int i=0;

    void setup()
    {
        mySerial.begin(9600);
        Serial.begin(9600);
        lcd.begin(20, 4);
    }

    void loop(){
        long n1, n2 , n3;

        lcd.setCursor(0,0);
        lcd.print("Enter n1:   ");

        lcd.setCursor(0,1);
        n1 = GetNumber();
        Serial.println ("n1: ");
        Serial.println (n1);
        lcd.clear();
        lcd.setCursor(0,0);
        lcd.print("Enter  n2:   ");

        lcd.setCursor(0,1);
        n2= GetNumber();
        Serial.println ("n2: ");
        Serial.println (n2);
        lcd.clear();
        lcd.setCursor(0,0);
        lcd.print("Enter n3:   ");
        lcd.setCursor(0,1);
        n3 = GetNumber();
        Serial.println ("n3: ");
        Serial.println (n3);
    }

    int GetNumber()
    {
        long num = 0;
        char key = kpd.getKey();
        while(key != '#')
        {
            switch (key)
            {
                case NO_KEY:
                break;

                case '0': case '1': case '2': case '3': case '4':
                case '5': case '6': case '7': case '8': case '9':
                lcd.print(key);
                num = num * 10 + (key -'0');
                break;

                case '*':
                num = 0;
                lcd.clear();
                break;
            }
            key = kpd.getKey();
        }
        return num;
    }

title: Storing Long numbers in arduino like phone numbers...How?

Answers: 1

body:
    int GetNumber()

should be changed to

    long GetNumber()

It is because the function type is the type of value that returning. In this case you are returning a long so you have to change it. An int can handle a number from -32 768 to 32 767. A long on the other side can handle a number from -2,147,483,648 to 2,147,483,647.


body:
I'm trying to build a led equalizer using arduino and I want to light up with the frequencies.

And I need a little help on how I should do it cause Im a beginner.

Should I use pulsein() or analogin pin to measure the freqeuencies?

The input will be an audio cable.

title: Arduino sound equalizer

Answers: 2

body:
Use a MSGEQ7. This IC is a "Seven Band Graphic Equalizer".

Here is its datasheet:

https://www.sparkfun.com/datasheets/Components/General/MSGEQ7.pdf

This method is more efficient, accurate and easier then pulsein() or analogRead(). The IC is fairly cheap and there are many libraries for it.

https://github.com/NicoHood/MSGEQ7

Here is a nice project that I found and that uses that IC. It can be a good souce of inspiration for both your code and your electronics.

https://www.youtube.com/watch?v=InrQvtUuS2w

body:
There are three steps to doing what you want, and the Arduino is going to struggle with all of them.

First you need to sample a short block of audio into a buffer that is a power-of-two in size with at least double the number of samples that you want to have bars, and at double the frequency of the highest frequency band you are interested in.

Once you have that sample set you then need to perform a *Fast Fourier Transform (FFT)* on it. This is quite a heavy mathematical operation, but there are *integer only* implementations of it that work kind of OK on a little Arduino (though a floating point version running on a better chip with FPU, or a DSP version on a chip with a DSP, is more desirable).

Then the third step is to take the results of the FFT (or "buckets") and calculate the power magnitude of each one (basically the square root of the sum of the squares of the real and imaginary values of the bucket - just like Pythagoras with a triangle).

Finally you can plot those power values on your LED bars.


body:
millis() uses timer0 (linked to CPU clock) to count time, but ADC_sleep mode stops the CPU clock, therefore millis() will drift (lag behind) after each ADC conversion performed in ADC_sleep mode.

With the standard number of CPU cycles needed for the ADC conversion (ADC prescaler=128 multiplied by ADC clock cycles=13), and with the standard prescaler for timer0 (64), it would look like millis() loses 13.5 tics (about 0.1 ms) for every ADC conversion performed in ADC_sleep mode.

I could update the timer0 register (TCNT0) by increasing it manually by 14 but first of all I would still have a 0.5 ticks drift (or a bit less, since the update operation would take some cycles), second I would miss the overflow event (the one Arduino uses internally for time tracking) every time the ADC conversion is started with TCNT0 > 230.

How should I proceed to use ADC_sleep mode during ADC conversions but still keep millis() accurate?

title: How to keep accurate millis() while using ADC_sleep mode?

Answers: 4

body:
I won't tell you how to do what you ask as I don't really know how to do
it. But I have the gut feeling that it _can_ be done. Only it would be
_really, really hard_, so this brings the question: is it worth it?

To avoid posting a pure opinion-based answer, I'll try to give you some
leads:

* You can set the timer 0 with single-CPU-cycle resolution simply by
  resetting its prescaler whenever you set a new value.
* You can make very precise delays with the `_delay_us()` function. The
  argument should be a compile-time constant. `_delay_us(0.125)` does
  exactly what it says it does.
* Beware of the prescaler of the ADC clock: it will induce some jitter
  on the ADC timings unless you reset it as well. AFAIK, the only way to
  reset that prescaler is to start the ADC conversion using some trigger
  source in auto-trigger mode. This may cost you a timer.
* If you miss the overflow event, you can just manually call the
  relevant ISR (`TIMER0_OVF_vect()`, which you declare with
  `ISR(TIMER0_OVF_vect);`). Sounds silly, but it works, with the only
  caveat that it forcibly enables interrupts upon return.

To know how many tics _exactly_ you are loosing, you could spend a few
evenings carefully studying the timings in the datasheet, or you could
try to calibrate against a stable frequency source. I would recommend
the latter.

body:
Rather than trying to update TCNT0, it might be better to track the number of cycles lost to ADC conversions, and in an intermediate routine – eg, `omillis()` – compensate for those cycles. *[Edit:  See better alternative, below]*

In more detail:

• At each conversion, add about 128·13 cycles (or perhaps 128·13.5, to account for average prescaler delay) to a cycle counter:
 `long lostcycles; ...; lostcycles += ADCcycles;`

• Within each `omillis()` call, say `return millis()+lostcycles/16000`

• Or perhaps say `return millis()+lostcycles>>14` to avoid wasting time on a division.  This would be off by 2% on the correction, but I presume the correction is small, say 5% of total time, leading to about 0.1% error because of using a shift instead of a divide.

>Re: “I would miss the overflow event (the one Arduino uses internally for time tracking) every time the ADC conversion is started with TCNT0 > 230”

That's incorrect [if using suggested approach].  Even if the timer 0 overflow is handled a hundred microseconds late, it will be handled ok. [As noted in Edgar Bonet's comment, a method that just adds to TCNT0 without checking arithmetic overflow, as in original approach, could miss a timer tick.]

Note, the example code using `SLEEP_MODE_ADC` in the “Sleep during reading” section of [ADC conversion on the Arduino](https://www.gammon.com.au/adc) on Gammon Forum suggests that one should check for the case where a timer or other interrupt occurs during an ADC conversion.  While `SLEEP_MODE_ADC` stops clkI/O, clkCPU, and clkFLASH, it leaves Timer 2, WDT, and some other potential interrupt sources active.

**A better alternative:**

As Gerben points out, it's slightly cleaner to update the count variable maintained by `millis()`, rather than using an intermediate routine.  For background, refer to [his answer to an earlier question](https://arduino.stackexchange.com/questions/22994/resetting-millis-and-micros/22997#22997).  Here is an adaptation [untested] of the idea to the current case:

    unsigned int lostcycles=0;
    ...;
    void accountForADC() {
      enum { ADCcycles = 13*128 + 64;  ms_cycles=16000 }; // adjust appropriately
      extern volatile unsigned long timer0_millis;
      lostcycles += ADCcycles;
      while (lostcycles >= ms_cycles) { // This loop usually runs one pass only
        byte statusReg = SREG; // Save interrupt status
        cli();                 // Turn off interrupts
        ++timer0_millis;       // Need interrupts off for atomicity
        SREG = statusReg;      // Restore old status
        lostcycles -= ms_cycles;
      }
    }

After startup, on the tenth call to `accountForADC()` this code would add 1 to `timer0_millis` to account for a millisecond lost to ADC conversions. `lostcycles -= ms_cycles` would set `lostcycles` to 1280.  After another 9 calls we again add 1 to `timer0_millis` and reduce `lostcycles`; and so forth.

body:
I think you read the datasheet wrong. The conversion takes 13 ADC cycles (except for the first one), not 13.5.

Secondly; the conversion start at the next rising edge of the ADC clock, not directly. So because the prescaler is 128, it can take an additional 127 main clock cycles before the next ADC clock's rising edge. So that means and ADC conversion takes between 13 and 13.9921875 ADC clock cycles.

I'm also not sure how long it takes the uC to restart the CPU clock. So there might me more time "missed" here.

Though you must be aware that the crystal oscillator isn't that accurate to begin with.

body:
The time to start a conversion is not fixed. From [my page about timers](http://www.gammon.com.au/timers) we can see this:

> **Tip:**
>
> There is an extra time before a conversion starts. The conversion starts on the leading edge of the ADC clock, not the moment the code asks for it. In the case of a scaler of 128, there could be 127 extra (processor) clock cycles added, because the hardware has to wait for the next ADC clock cycle. This could add 7.938 µs to the conversion time.

It looks like the prescaler can be reset by writing 0 to ADEN. According to the datasheet:

> The prescaler starts counting from the moment the ADC is switched on by setting the ADEN bit in ADCSRA. The prescaler keeps running for as long as the ADEN bit is set, and is continuously reset when ADEN is low.

If you do that however then you add to the conversion time, as it will now take 25 ADC clock cycles rather than 13.

---

* As others have suggested, if accurate time is what you want, then an external clock chip could well be the answer. The chip and parts are likely to come to a dollar or so.

* An alternative would be to get an external ADC chip, thus moving the problem of noise-reduction to a chip which is (hopefully) designed to cope with it.

* <s>Another possibility would be to put an external clock input to Timer 1 and run that asynchronously. As I read the data sheet, that timer will keep running in ADC sleep mode, and thus you could use that for timing. (That wouldn't help with millis() and micros() but you could write something similar that used Timer 1).</s>

    *Edit* - as Edgar Bonet pointed out, I misread the datasheet. It is Timer 2 that can do this, not Timer 1. And the pins to run the timer asynchronously are not on the PDIP chip on the Uno, and are not brought out to board pins on the Mega.


body:
I want to have a line like this

    Serial.println(count*"B");

So if `count=6`, it would print `BBBBBB`, etc.

Is there anything like this for arduino?

title: How to multiply strings?

Answers: 3

body:
You can write a helper function to do it, like this:

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

    void printRepeat (Stream & device, const char * str, unsigned int count)
      {
      while (count-- > 0)
        device.print (str);
      }   // end of printRepeat

    void setup()
      {
      Serial.begin (115200);
      printRepeat (Serial, "-", 20);
      Serial.println ();
      } // end of setup

    void loop()
    {
      printRepeat (Serial, "Hello, World! ", 5);
      Serial.println ();
      delay (500);
    } // end of loop

The function `printRepeat` is passed a `Stream` argument, which can be something like Serial, Serial1, a SoftwareSerial instance, and so on.

body:
Just for fun, here is a version of Nick Gammon's answer reformulated
with some C++ magic:

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

    // A "repeated string" that has no use except for being printable.
    class RepeatedString : public Printable
    {
    public:
        RepeatedString(const char * str, unsigned int count)
        : _str(str), _count(count) {}
        size_t printTo(Print& p) const
        {
            size_t sz = 0;
            for (unsigned int i = 0; i < _count; i++)
                sz += p.print(_str);
            return sz;
        }
    private:
        const char * _str;
        unsigned int _count;
    };

    void setup()
    {
        Serial.begin(115200);
        Serial.println(RepeatedString("-", 20));
    }

    void loop()
    {
        Serial.println(RepeatedString("Hello, World! ", 5));
        delay(500);
    }

You can `.print()` and `.println()` the `RepeatedString`s on anything
that can print.

body:
A more simple "noob" way could also be:

    int count = 6

    for(int i=0; i<count; i++)
    {
      Serial.print("b");
    }

    Serial.println();


body:
I recently bought two lilypads USB, one works perfectly (it's recognized in my computer, but the other one it's never recognized, I even try in different computers and the same scenario with both devices)

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

So I think that maybe the second one doesn't have a bootloader installed. So I'm triying to "burn" a new bootloader. I have been triying following the guide on https://www.arduino.cc/en/Tutorial/ArduinoISP using as programmer an Arduino UNO but without luck. I ever get avrdude: Device signature = 0x000000 (retrying). Thanks for the help!

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

title: How Bootload an Lilypad Arduino USB using Arduino UNO

Answers: 2

body:
The Lilypad is an official Arduino board. If you did not get it from other continents, it should have the bootloader in so don't try to burn something else. Check the traces of your Lilypad. Some short might occur because of and accidental short.

Whatever you do, DON'T TRY TO BURN SOMETHING THAT DOESN'T NEED TO BE BURNED.

body:
If you try uploading to a LilyPad USB with the wrong board selected, you may end up in a condition where the bootloader can no longer respond normally.

You can get the LilyPad Arduino into bootloader mode by tapping the reset button twice in under a second. Once in bootloader mode, the LED should blink at about 1Hz for about 8 seconds. My advice is to load a blank sketch (i.e., nothing in loop() or setup()) and then double tap the reset button shortly after hitting the upload button. That should restore the LilyPad USB to a working state.


body:
I would like want to know why the bluetooth module has a plastic sleeve covering it?

Is it possible to remove it?

[![HC-06][1]][1]

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

title: Why is there a plastic sleeve on my HC-05 bluetooth module

Answers: 2

body:
To protect it against ham fisted newbies from causing short circuits.

Yes, you can remove it, as long as you're not a ham fisted newbie that is going to cause short circuits.

body:
It is to protect it. You should keep it so that the modules lasts longer.

If you remove it, just don't do anything stupid.


body:
I want to read ADC from the pin A0 and A1. I have written in this code, however.

I took this code came from Nick Gammon

Thank You
//////////////////////////////////////////////////////////////////////////////

this is code

    const byte adcPin = 0;  // A0

    const int MAX_RESULTS = 256;

    volatile int results [MAX_RESULTS];
    volatile int resultNumber;

    // ADC complete ISR
    ISR (ADC_vect)
      {
      if (resultNumber >= MAX_RESULTS)
        ADCSRA = 0;  // turn off ADC
      else
        results [resultNumber++] = ADC;
      }  // end of ADC_vect

    EMPTY_INTERRUPT (TIMER1_COMPB_vect);

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

      // reset Timer 1
      TCCR1A = 0;
      TCCR1B = 0;
      TCNT1 = 0;
      TCCR1B = bit (CS11) | bit (WGM12);  // CTC, prescaler of 8
      TIMSK1 = bit (OCIE1B);  // WTF?
      OCR1A = 39;
      OCR1B = 39;   // 20 uS - sampling frequency 50 kHz

      ADCSRA =  bit (ADEN) | bit (ADIE) | bit (ADIF);   // turn ADC on, want interrupt on completion
      ADCSRA |= bit (ADPS2);  // Prescaler of 16
      ADMUX = bit (REFS0) | (adcPin & 7);
      ADCSRB = bit (ADTS0) | bit (ADTS2);  // Timer/Counter1 Compare Match B
      ADCSRA |= bit (ADATE);   // turn on automatic triggering

      // wait for buffer to fill
      while (resultNumber < MAX_RESULTS)
        { }

      for (int i = 0; i < MAX_RESULTS; i++)
        Serial.println (results [i]);

      }  // end of setup

    void loop () { }

title: AC meter By ADC timer interrupt from Nick Gammon

Answers: 3

body:
You can read two analog channels like this:

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

    int first_reading = analogRead(A0);
    int second_reading = analogRead(A1);

If this does not fit your purpose, then your question was not asked
properly: rewrite it and clearly state your requirements. Explain why
the simple solution does not work for you.

If this _does_ work for you, then stop (for now) reading advanced
tutorials, like the one where you found your code, and focus on the very
basics: the Arduino examples in the 01.Basics section, then the
03.Analog section.

body:
    constexpr byte  adc_mux_setting = bit(REFS0) | bit(ADLAR); // Left alligment for ADC result, so ADCH contains 8b result.

    volatile uint16_t         sum_u = 0;
    volatile uint16_t         sum_i = 0;
    volatile uint8_t   resultNumber = 0;

    // ADC complete ISR
    ISR (ADC_vect) {
        if (resultNumber & 1) {
            sum_u += ADCH-(sum_u>>8);                  // 8bit resolution, something like floating average
        } else {
            sum_i += ADCH-(sum_i>>8);                  // 8bit resolution, something like floating average
        }
        ADMUX  = adc_mux_setting | (++resultNumber&1); // Expecting pins A0 and A1 (otherwise offset must be added)

        TIFR1 |= bit(OCF1B);                           // clear the flag otherwise it never starts ADC conversion (not without ISR)
                                                       // it's here because I don't want to ADC starts conversion before switching channel
    }

    void setup () {
        Serial.begin(115200);
        Serial.println("Start");

        // reset Timer 1
        TCCR1A  = 0;
        TCCR1B  = bit(CS11) | bit(WGM12);              // CTC, prescaler of 8
        TCNT1   = 0;
        //TIMSK1 = bit (OCIE1B);                       // it doesn't work without clearing OCF1B
        OCR1A   = 80;                                  // it never reaches 80 so it never sets interrupt flag
        OCR1B   = 79;                                  // 40 uS - sampling frequency 25kHz for both (15kHz for each)

        ADCSRA  = bit(ADEN)  | bit(ADIE) | bit (ADIF); // turn ADC on, want      interrupt on completion
        ADCSRA |= bit(ADPS2);                          // Prescaler of 16
        ADMUX   = adc_mux_setting;                     // A0 goes first
        ADCSRB  = bit(ADTS0) | bit(ADTS2);             // Timer/Counter1 Compare Match B
        ADCSRA |= bit(ADATE);                          // turn on automatic triggering
    }

    void loop () {
        if (resultNumber == 0) {                       // print results after 128 measures for both channels
            Serial.print(sum_u);
            Serial.print(' ');
            Serial.println(sum_i);
            while (resultNumber == 0);                 // I want to print it only once per iteration
        }
    }

body:
In the code you posted the first line is:

>     const byte adcPin = 0;  // A0

To read from A1 the change is simple:

    const byte adcPin = 1;  // A1

---

> i am sorry i come from thailand

Whatever country you are from does not excuse from you posting the same question many, many times.

I suggest you read the datasheet:

[ATmega48A-48PA-88A-88PA-168A-168PA-328-328P_datasheet](http://www.atmel.com/images/Atmel-8271-8-bit-AVR-Microcontroller-ATmega48A-48PA-88A-88PA-168A-168PA-328-328P_datasheet_Complete.pdf)

Scroll down to **24.9.1 ADMUX – ADC Multiplexer Selection Register**


body:
I have to code in arduino the logic gates based on the truth table with two inputs. I searched for some examples, however all that I found is using && to compared them using only onf if else condition. What I need is to do it using all the possible cases. This is what I have, however only the last condition is working. I ask you please clarify to me what concept I am not understanding well, or what is wrong in my logic. Thank you.

      const int p2  = 2;  //Ground G
      const int p13 = 13; //Input A
      const int p15 = 15; //Input B

      void setup() {
        // put your setup code here, to run once:
        pinMode(p2,   OUTPUT);
        pinMode(p13,  INPUT_PULLUP);
        pinMode(p15,  INPUT_PULLUP);
      }
    void loop() {
      // put your main code here, to run repeatedly:
      if ( digitalRead(p13) == 0 && digitalRead(p15) == 0 ){
        digitalWrite(p2, HIGH);
      }

      if( digitalRead(p13) == 0 && digitalRead(p15) == 1 ) {
        digitalWrite(p2, LOW);
      }

      if( digitalRead(p13) == 1 && digitalRead(p15) == 0 ) {
        digitalWrite(p2, LOW);
      }

      if( digitalRead(p13)== 1 && digitalRead(p15) == 1) {
        digitalWrite(p2, LOW);
      }

    }

title: and gate based on truth table

Answers: 3

body:
Your question title says "and", which means that if `input1` is `HIGH` ***AND*** `input2` is `HIGH`, then `output` should be `HIGH`. Your first line has

    (...==0 && ...=0) digitalWrite(..., HIGH);

Surely these should be `==1`?

Another thing is that every line of code in your program is re-reading the inputs. You should read them _once_, then decode the meaning behind them. So:

    int input1 = digitalRead(p13);
    int input2 = digitalRead(p15);

    if (input1==1 && input2==1) {
        digitalWrite(p2, HIGH);
    } // if
    else if (input1==0 && input2==0) {
        digitalWrite(p2, LOW);
    } // else if
    else if ...

But note that the last three options are all the same: the code simply writes `LOW`. So you can combine all the last three cases into one step.

In other words, there's a single special case (both inputs `==1`), and an everything-else case. In this code, I only read the inputs once, since I'm only looking for the special case. If it doesn't exist, then I simply do the alternative:

    if (digitalRead(p13)==1 && digitalRead(p15)==1) {
        digitalWrite(p2, HIGH);
    } // if
    else {
        digitalWrite(p2, LOW);
    } // else

body:
Let me give some feedback on your code, kind of a small code review:

    const int p2  = 2;  //Ground G
    const int p13 = 13; //Input A
    const int p15 = 15; //Input B

This is useless. The purpose of creating these constants is to give them
meaningful names, and `p2` is no more meaningful than just `2`. You
can remove these definitions and replace in the following `p2` with
`2`, etc. Or you could find better names:

    const int inputA_pin = 13;
    const int inputB_pin = 15;
    const int output_pin = 2;

Notice that the comments that you put next to the constants are not
needed anymore, as the names are now explicit enough.

    void setup() {
        // put your setup code here, to run once:

This comment is useless, better remove it. It is in BareMinimum.ino so
that you know what to put there, but now that you have done it, no need
to keep the comment.

    if (digitalRead(p13) == 0 && digitalRead(p15) == 0) {
        digitalWrite(p2, HIGH);
    }

I assume you are using negative logic: the user presses a button, and
makes the input LOW, to mean TRUE. If this is the case, you are not
being clear enough about it. You should at least have a comment to make
this explicit, e.g.:

    int inputA = !digitalRead(inputA_pin);  // negative logic

where `!` is the NOT logic operator.

Otherwise your program seems fine. If it does not work, check your
wirings. John Burger's suggestions on how to make it better are very
sound, and you should probably follow them. But I would like to show you
_another_ way of writing this that could be relevant to your course: you
can implement the truth table as an actual table, i.e. a C++ array. Here
is my version:

    const int inputA_pin = 13;
    const int inputB_pin = 15;
    const int output_pin = 2;

    const bool truth_table[2][2] = {
                /* false  true  */
    /* false */  { false, false },
    /* true  */  { false, true  }
    };

    void setup() {
        pinMode(inputA_pin, INPUT_PULLUP);
        pinMode(inputB_pin, INPUT_PULLUP);
        pinMode(output_pin, OUTPUT);
    }

    void loop() {
        int inputA = !digitalRead(inputA_pin);  // negative logic
        int inputB = !digitalRead(inputB_pin);  // ditto
        int output = truth_table[inputA][inputB];
        digitalWrite(output_pin, output);
    }

Notice that this uses the equivalence between false/true and 0/1.

In the case of the AND gate, this looks just like a silly classroom
exercise. However, for a complex gate with four inputs or more, and a
non-trivial truth-table, this technique may be the most straightforward
implementation.

------------------------------------------------------------------------

**Addendum** – You wrote in a comment:

> Not clear how your truth table works.

You are probably confused by the fact that I laid out the table in
compact form, with the first input in the row headings (comments on the
left edge) and the second input in the column headings (comments at the
top), just like a traditional [multiplication table][]. Incidentally, it
happens to be a 2×2 multiplication table.

I could have used the more common “flat” layout, where each combination
of inputs is represented as one line of the table:

    const bool truth_table[] = {
        /*   A     B     output  */
        /*-----------------------*/
        /* false false */ false,
        /* false true  */ false,
        /* true  false */ false,
        /* true  true  */ true
    };

But then, since it's now a 1D table, the table index has to be computed
from both inputs, as each input provides one bit of the index:

    int output = truth_table[inputA<<1 | inputB];

This is actually how I would do it if I had to simulate a gate with more
than two inputs. I've used this technique to make a [2-bit Gray code
adder][2-bit Gray code adder] (4 inputs, 2 outputs) which,
with [a little bit of optimization][direct port access], boils down to

    for (;;) PORTB = truth_table[PINB & 0x0f];

[multiplication table]: https://commons.wikimedia.org/wiki/File:Tpitagoras.gif
[2-bit Gray code adder]: https://www.logre.eu/wiki/Codeur_rotatif_incrémental#Solution_avec_un_microcontr.C3.B4leur
[direct port access]: https://www.arduino.cc/en/Reference/PortManipulation

body:
Your whole code can be replaced with one line:

    digitalWrite(output_pin, digitalRead(inputA_pin) && digitalRead(inputB_pin));

That is, write out the results of a boolean AND on the state of the two inputs.


body: Every time I connect the Arduino Uno to the Mac through USB port, the Mac restarts. Why is this happening? How can Arduino make such a sophisticated machine reset? This also happens with my ESP12E Node MCU.

title: Arduino resets my MacBook Pro

Answers: 3

body:
It is almost certainly a device-driver issue. Since Arduinos are probably a little way down the pecking order for things that Apple is interested in, they probably don't test as extensively as (say) printers.

> How can Arduino make such a sophisticated machine reset?

Device drivers would operate with elevated privileges, because they need to control, well, *devices*, like hard disks, printers, etc. If one has a programming error (like dereferencing a NULL pointer) then it could crash the whole operating system.

---

I suggest you look at this page: [IDE 1.6.12 released with Sierra support and more](https://blog.arduino.cc/2016/09/22/ide-1-6-12-released-with-sierra-support-and-more/)

It says there:

> A new version of the Arduino IDE (1.6.12) supporting OSX Sierra is available for download! All OSX users updating to Sierra are invited to also update the IDE to avoid crashes when uploading sketches.

This may or may not help. They seem to be suggesting that the *IDE* crashes rather than the Mac, but it could be worth trying.

---

There are some posts on [macOS Sierra Usb Serial Crash](https://forums.developer.apple.com/thread/61472) which seem relevant:

> I need to use a arduino nano and my Mac with mac os sierra is rebooted when i plug in the arduino

It sounds like the CH340 chip set used on **clone** Arduinos is causing this.

A suggested new device driver fix is at [ch340g-ch34g-ch34x-mac-os-x-driver](https://github.com/adrianmihalko/ch340g-ch34g-ch34x-mac-os-x-driver)

body:
i have had the same problem and found that the CH340 driver was at fault.  With the Arduino MEGA clone attached to the computer, it would throw a kernal panic at startup, then keep restarting over and over.

With the clone unhooked, the computer started normally.  Therefore the driver when trying to load at startup was cauing a panic.

I went back to the web site and found an “updated” driver that solved the panic problem.  It starts and runs OK, BUT -

1. Every print command prints twice. A simple “Hello World” prints twice.

I don't have a solution for the double print.

2. The program would compile, but never load in to the clone.  When I switched the USB cable from a 6ft one to the included 1 ft blue one, it worked.

body:
My MacOS is High Sierra 10.13.4 the simple solution is :

 1. Download CH341SER_MAC.zip from here
    https://github.com/awangga/NFCReader/raw/master/driver/CH341SER_MAC.zip

 2. remove old driver, please open terminal and run command:

    rm -rf /System/Library/Extensions/usbserial.kext

    rm -rf /Library/Extensions/usbserial.kext

 3. Unzip CH341SER_MAC and install CH34x_Install_V1.4.pkg then restart MAC,
 4. after rebooting login to your MAC and open terminal,
    Conect arduino into your Mac and Look at your serial folder :
    ls /dev/

 5. You can access your Arduino on /dev/cu.wchusbserialfa130 or /dev/tty.wchusbserialfa130 or just type : ls /dev/cu. then
    tab twice.


body:
I have 2 I2C devices that uses the same address. One of them is the DS3231 RTC. I use this library for the DS3231. I dont want to mess with the other one cause it is way more complicated then this one.:

    #include <DS3231.h>

http://www.rinkydinkelectronics.com/library.php?id=73

Then, there is an object declaration for the real time clock:

    DS3231  rtc(SDA, SCL);

I wounder if I can change that to:

    DS3231  rtc(A0, A1);

I've seen the library but I haven't understand it yet (duh... I'm so stupid!). But is it possible to use an other pair of pins for I2C communication.

Note that I've already tried to use the soft I2C library but I really want to avoid it because it is just too much. If it is the final solution then so be it.

title: I2C on non I2C pins, possible?

Answers: 2

body:
Ok, so I've realise that the anwser was somewhat on the page of the library (that I completly ignored). I can change the pins like I did because the library uses a "TWI-/I2C-like protocol".

> The library has not been tested in combination with the Wire library and I have no idea if they can share pins. Do not send me any questions about this. If you experience problems with pin-sharing you can move the DS3231/DS3232 SDA and SCL pins to any available pins on your development board. This library will in this case fall back to a software-based, TWI-/I2C-like protocol which will require exclusive access to the pins used.

body: You can change the address of the GY-521 by pulling the AD0 pin to Vcc. After that the address will be 0x69 instead of 0x68.


body:
I couldn't find anything on this topic.

**Task:** to connect sensors to Arduino board via Bluetooth module, process the received data and then send the data to server via GSM module.

**Question:** Is it possible to connect both of these modules to 1 Arduino board? If I'm not wrong, Arduino Uno has only one pair of Rx Tx pins, while for these two modules each has its own pairs on Rx Tx pins.

I need to know this before ordering them. So, please help

title: GSM and Bluetooth modules on 1 Arduino Uno board

Answers: 1

body:
Take a look at the `SoftwareSerial` library which allows other pins to be used for Serial at speeds <= `57600`

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


body:
I want to talk to an [ADS8698][1] over SPI (see page 36 for details on their SPI implementation) using a Teensy 3.2. Right now I'm only getting zeros back and I feel like (perhaps wrongly) that I've followed the datasheet correctly. I believe my SPI mode is correct and, given the clock rates I'm using, I should be observing the timing constraints properly.

(1) Is there a glaring error here? I haven't coded that many SPI interfaces, so I might have a novice mistake in there.

(2) Is there existing code for a product that uses a nearly identical SPI interface to the ADS8698 (any product that has a similar timing diagram would do)?

    #include <SPI.h>

    #define USB_RATE 19200//usb transfer rate
    #define SPI_CLOCK 10000000//spi clock frequency

    #define CS0 10

    SPISettings ADC_SPI(SPI_CLOCK, MSBFIRST, SPI_MODE1);

    void setup()
    {
      // disable both multiplexers
      pinMode(CS0, OUTPUT);
      digitalWrite(CS0, HIGH);
      // prepare serial protocols
      Serial.begin(USB_RATE);
      SPI.begin();
    }

    void read_ADC()
    {
      // begin the session by taking CS0 low
      SPI.beginTransaction(ADC_SPI);
      digitalWrite(CS0, LOW);// slave select disable
      // delayMicroseconds((int) (1e6 * 20/SPI_CLOCK));// wait > 16 clock cycles
      // transfer 16 bits while the ADC performs conversion
      SPI.transfer(0); // I'm not trying to set any registers, just waiting (zero is fine)
      SPI.transfer(0); // I'm not trying to set any registers, just waiting (zero is fine)
      // data should be ready, so try to read it
      Serial.println(SPI.transfer(0));
      Serial.println(SPI.transfer(0));
      // end the session by taking CS0 high
      digitalWrite(CS0, HIGH);// slave select enable
      SPI.endTransaction();
    }

    void loop()
    {
      delay(1000);
      read_ADC();
    }

The system is wired like this:

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

  [1]: https://www.google.com/url?sa=t&rct=j&q=&esrc=s&source=web&cd=3&cad=rja&uact=8&ved=0ahUKEwjts4iizdXPAhXRQD4KHSJIAdkQFggzMAI&url=http://www.ti.com/lit/gpn/ads8694&usg=AFQjCNHTqBXpOgQN4rywWXLk_59DA4_KnA&sig2=TlTguN5aNp0tPjQgqbdAcA&bvm=bv.135475266,d.cWw
  [2]: https://i.stack.imgur.com/ymQAV.png
  [3]: https://i.stack.imgur.com/ppVOQ.png

title: Talking to ADS8698 (18-bit ADC) over SPI

Answers: 1

body:
Per the Datasheet PG47

During power-up or reset, the default content of the command register is all 0's and the device waits for a command to
be written before being placed into any mode of operation.

If your still working with this I'm going to be tackling this same thing very soon, hopefully I can get it to work with DMA.
https://forum.pjrc.com/threads/34863-Teensy-CC-Dummy-Load-300W/page4


body:
I have a small project and I have some problems while working on that. The idea of the project is as below:
I have an LED which is operated by two "buttons". The buttons takes two values (1 or0) which I have to send from serial monitor.
One button is for LDR sensor, which lights up the LED when its value is below 300 (in my code). The other button turns it off (Value 0). The buttons are working together, so I have to consider both of them in my statements. The problem is that I cannot play with the serial monitor it's just looping continuously and I cant type anything as input.

Can anyone help me with this to find a solution to be able to input values for both buttons?

Here is the code:

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

    const int analogInPin = A0; //LDR PIN
    const int digitalOutPin = 13; // LED PIN
    int outputValue;

    int sensorValue = 0; //

    char Buton1; //LDR button
    char Buton2; //Blutooth button

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

    void loop()
    {
      while (Serial.available())
      {
        Serial.println("Button1 value: ");
        Buton1 = Serial.read();
        if (Buton1 == '1')
        {
          Buton2 = Serial.read();
          Serial.println("Button2 value: ");
          if (Buton1 == '1' and Buton2 == '0')
          {
            sensorValue = analogRead(analogInPin);
            outputValue = map(sensorValue, 0, 1023, 0, 255);
            Serial.print ("Sensor: ");
            Serial.println(sensorValue);
            if (sensorValue < 300);
            {
              digitalWrite(digitalOutPin, 255);
            }
          }
          else if (Buton1 == '1' and Buton2 == '1')
          {
            digitalWrite(digitalOutPin, 255);
            Serial.print("Both buttons are ON ! !");
          }
        }
        else if (Buton1 == '0')
        {
          Serial.println("Button2 value: ");
          Buton2 = Serial.read();
        }
        if (Buton1 == '0' and Buton2 == '1')
        {
          digitalWrite(digitalOutPin, 255);
        }
        else if (Buton1 == '0' and Buton2 == '0')
        {
          Serial.println("Both buttons are inactive ! Please reset");
          break;
        }
      }
    }

title: Serial Monitor "button" implementation

Answers: 5

body:
A simple approach would be to use bit 0 of serial data to control "button 1", and bit 1 of serial data to control "button 2".  As follows:

    char sd = Serial.read();
    byte button1 = sd & 1;
    byte button2 = sd & 2; // Or (sd & 2)>>1 if you prefer

With the above code, button 1 is true for odd-digit inputs, and button 2 is true when `(sd & 2)>>1` is odd.  For example, input 0 to turn off both buttons, 1 to turn on only button 1, 2 for only button 2, and 3 to turn on both.

You might also wish to button1 or button2 only when the input character represents a digit.  For this, you can say:

    char sd = Serial.read();
    byte button1, button2;
    ... ;
    if ('0' <= sd && sd <= '9') {
        button1 = sd & 1;
        button2 = (sd & 2)>>1;
    }

body:
Each button has a 1 state and a 0 state. The combination will always be something like this:

    if (button1 == '1' and button2 == '1')
    do something
    if (button1 == '1' and button2 == '0')
    do something
    if (button1 == '0' and button2 == '1')
    do something
    if (button1 == '0' and button2 == '0')
    do something

body:
The first problem is that your code does not wait for anything to be typed, so it loops very rapidly. Serial.read() returns -1 when there is nothing in the buffer, so I imagine your codes is printing something like:

    Button1 value:
    Button1 value:
    Button1 value:
    Button1 value:

Try inserting

    while( !Serial.available() )
       ;

before your serial.read() calls. This will force it to wait until you type something before it continues.

body:
as it has been pointed before you the read function returns a -1 when there are no information to access, what you can do is

    while( !Serial.available() )
    {
      //do nothing
    }
    Buton1=Serial.read();
    Serial.clear();   //for having the buffer clear for the next button

body:
See if this helps:

    const int analogInPin = A0; //LDR PIN
    const int digitalOutPin = 13; // LED PIN
    int outputValue;

    int sensorValue = 0; //

    byte Buton1; //LDR button
    byte Buton2; //Blutooth button

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

    void loop() {
      while (Serial.available() > 0) {
        char inChar = Serial.read();
        if (inChar == 'l' || inChar == 'L')
        {
          Buton1 = Serial.parseInt();
          Buton1 = constrain(Buton1,0,1);
        }
        else if (inChar == 'b' || inChar == 'B')
        {
          Buton2 = Serial.parseInt();
          Buton2 = constrain(Buton2,0,1);
        }
        else
        {
          Serial.println("invalid input");
          while (Serial.available() > 0)
            Serial.read();
        }
        Serial.print("Buton1 = ");
        Serial.println(Buton1);
        Serial.print("Buton2 = ");
        Serial.println(Buton2);
        Serial.println();
      }
    }


body:
I am using ESP12E Wifi module, using library based on Arduino. Is there any way I can upload hex file of the project to esp8266 using Arduino or any tool?
I need to send hex file instead of code to my client. Is there any way?

title: ESP8266 Upload hex file Arduino IDE

Answers: 2

body:
I see the main question you are asking is: "I need to send a hex file instead of code to my client. I want to keep my source code with me."

The mechanics of the final hardware solution aren't supplied but I will guess that your client is also using an Arduino or at least the same Atmel chip that you have in your Arduino, and will be using that chip to control the ESP8266.

When you build your sketch, there is a .hex file created that you can send to your client.

There are a few ways to keep the hex file around, and IDE 1.6.5 and up has a way to easily find this file:

Sketch > Export Compiled Binary
The sketch will compile.

Sketch > Show Sketch Folder
The .hex file will be in the sketch folder.

You can send this hex file to your customer.

If he is using an Arduino or ATMega-based solution to connect to the ESP8266, then the hex file can be loaded into his Arduino or to his Atmel chip. However, the Arduino IDE doesn't support *import* of hex files at this time.

Your client would have to load that hex file onto the Arduino with an ISP programmer of some sort. There are many ways to do this, and the best one for you will depend upon your circumstances and your client's skill set.

If the client is using an Arduino or has just embedded the same ATmel chip that is in your Arduino into his solution, you could also just program your Arduino, and then send him that chip.

body: Turn on `Show verbose output during compilation` in your Arduino IDE and press `Verify`. After compile you can examine the parameters sent to `esptool.exe` in the last line before `Sketch uses...`. You will see some `.elf`, `.bin` and `.text` files. These are the files you want to send.


body:
I have an Uno hooked up to a sparkfun 8 channel multiplexer (https://learn.sparkfun.com/tutorials/multiplexer-breakout-hookup-guide). I have it wired up like this:

    Arduino0 --> S0
    Arduino1 --> S1
    Arduino2 --> S2
    Arduino3 --> Z
    Arduino 5v --> VCC
    Arduino GND --> GND

I'm running a simple code to blink two different LED's, one attached to Y7, and one attached to Y6.

    //Define MUX pins
    int pin0 = 0;
    int pin1 = 1;
    int pin2 = 2;
    int zOutPut1 = 3;

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

        // Set controll pins
        pinMode(pin0, OUTPUT);
        pinMode(pin1, OUTPUT);
        pinMode(pin2, OUTPUT);
        pinMode(zOutPut1, OUTPUT);
    }

    void loop() {
        samplerStarter();
    }

    void samplerStarter() {
        sample(1); // Takes sample for 5 min
        delay(1000);
        sample(2);
        delay(1000);
    }

    void sample(int noidNum){
        //MUX 1
        if(noidNum == 1) {
            digitalWrite(pin0, HIGH);
            digitalWrite(pin1, HIGH);
            digitalWrite(pin2, HIGH);
            digitalWrite(zOutPut1, HIGH); //Y7
        }
        else if (noidNum == 2) {
            digitalWrite(pin0, LOW);
            digitalWrite(pin1, HIGH);
            digitalWrite(pin2, HIGH);
            digitalWrite(zOutPut1, HIGH); //Y6
        }
        delay(500);

        //Set everythign back to Low
        digitalWrite(pin0, LOW);
        digitalWrite(pin1, LOW);
        digitalWrite(pin2, LOW);
        digitalWrite(zOutPut1, LOW);

        delay(500);
    }

But when I run this code, only the first LED attached to Y7 blinks. But if I remove the `Serial.begin(9600)` line:

    //Serial.begin(9600);

Everything works fine. So I have no idea why this one line dealing with Serial Communication is affecting my multiplexor.

title: Why is Serial.begin(9600) interfering with my multiplexor functioning?

Answers: 1

body:
(Digital) Pins 0 and 1 are used by the hardware serial port you initialize with Serial.begin() on a classic Arduino like an Uno.

With this type of board it is generally best not to use those for any other purpose; if you do, you have to accept that you cannot use the hardware serial for input or debug/status output.

Even if you don't want to use serial during the operation of the your creation, having those pins connected to other functions can interefere with uploading sketches via the bootloader, or else the act of uploading a sketch can misoperate the functions connected to those pins.


body:
I am trying to use a NEO-6M GPS to datalog my current position on a Micro SD card with the help of an Arduino Pro Mini. It doesn't transmit anything. So do I need a SIM card?

> Caution:
>
>1. The GPS tracker must be worked with a SIM card which may cost data and SMS fee.
>
>2. No annual authorization fee for the first year. The coming annual fee details, please visit our company website.

title: Does a GPS need a sim card?

Answers: 1

body:
For use as a GPS device, the NEO-6M doesn't need a SIM card.  For use as part of a tracker that sends SMS / GSM messages, ie, that uses the cell telephone system to send messages, you need a SIM card.  The SIM card is used to authenticate your system to the phone system.

See examples at "[arduino gps and sms where are you arduino](https://bigdanzblog.wordpress.com/2015/03/18/arduino-gps-and-sms-where-are-you-arny-the-arduino/)" (bigdanzblog.wordpress.com) and "[vehicle tracking system using arduino gps and gsm](http://circuitdigest.com/microcontroller-projects/vehicle-tracking-system-using-arduino-gps-and-gsm)" at circuitdigest.com.


body:
I am using an UNO with a RTC to control a light board. I'm using a simple control structure to decide when to turn things off and on. It's my understanding that a `time_t` value is just a number (number of seconds since 1970), and that I should be able to compare these `time_t` values as I would any integer- in this case comparing two `time_t` values to see which one is larger.

    #include <Wire.h> // Needed for I2C protocol (RTC uses I2C)
    #include "RTClib.h" //Good Library for RTC functions
    #include <Time.h> // Needed for time_t variables and tmElements

    RTC_DS3231 rtcVM; // From the RTClib library for use with an DS3231 RTC. Creates an object called rtcVM

    DateTime nowVM; // Declare a Date Time object that will be used to hold the current time
    time_t nowUniVM;// Declare a time_t object (Unix time) which is a float value (good for straight comparisons) to hold current time
    time_t starter;// Declare a time_t object for the start time (time_t)
    tmElements_t MagStart; // Declare a tmElement_t object to manually input the start Time

    //FILL OUT START TIME AND DATE FOR FIRST SAMPLE (NO LEADIN ZEROS--"8" not "08")
    byte startHour = 17;
    byte startMin = 58;
    byte startSec = 0;

    byte startDay = 12;
    byte startMonth = 10;
    int twoDigYear = 16; // Enter last two digits of year

    byte startYear = twoDigYear + 30 ; // This is a little confusing. This is the year offset from 1970 (AKA 2016 should be input as 46. Or just add 30 to last two digits).

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

      Wire.begin();
      rtcVM.begin();

      // Creates a tmElement by putting together all of Maggies Start Time and Dates
      MagStart.Hour=startHour;
      MagStart.Minute = startMin;
      MagStart.Second = startSec;
      MagStart.Day = startDay;
      MagStart.Month = startMonth;
      MagStart.Year = startYear;

      // Takes the tmElement and converts it to a time_t variable. Which can now be compared to the current (now) unix time
      starter = makeTime(MagStart);

      // Start message
      Serial.println("Start time is: ");
      Serial.print(hour(starter));
      Serial.print(":");
      Serial.print(minute(starter));
      Serial.print(":");
      Serial.print(second(starter));
      Serial.print(" ");
      Serial.print(month(starter));
      Serial.print("/");
      Serial.print(day(starter));
      Serial.print("/");
      Serial.println(year(starter));
      Serial.println("****************************");
    }

    void loop() {
      nowVM = rtcVM.now(); // get current time and hold in "nowVM"
      time_t nowUniVM = nowVM.unixtime(); // Calculate current time in Unix time

      samplerStarter();

      // RTC Get and Display
      DateTime now = rtcVM.now();// Getting the current Time and storing it into a DateTime object

      Serial.print(now.year(), DEC);
      Serial.print('/');
      Serial.print(now.month(), DEC);
      Serial.print('/');
      Serial.print(now.day(), DEC);
      Serial.print(' ');
      Serial.print(now.hour(), DEC);
      Serial.print(':');
      Serial.print(now.minute(), DEC);
      Serial.print(':');
      Serial.print(now.second(), DEC);
      Serial.println();
      delay(3000);

      //Use these 2 to check the numerical values for comparisons
      Serial.println(starter);
      Serial.println(nowUniVM);
    }

    void samplerStarter() {
      if (starter < nowUniVM) {
        //if (1 < 2) {
        Serial.println("Start Time");
       }
    }

I've included my entire test code here, but it's the last if statement that puzzles me. The idea behind that last statement is that it should print out "Start Time" when the start time is reached. The statement works if I compare something simple like (1 < 2), and the statement gets printed. So I assumed it would work if I did the same thing but with two different `time_t` values.

But if I input an appropriate start time under the "Fill Out Start Time" section, the print statement is not triggered when the start time comes to pass (AKA- when the start time (starter) is less than the current time (`nowUniVM`).

Is there something about time_t values that does not allow them to be compared like this? Or is there something in the way I'm creating my values that is messing up the comparisons?

My output to the serial monitor shows the actual `time_t` values, and they look like normal integers to me when they print out, so I'm not sure whats going on here. Why doesn't that last if statement print out when the start time is reached?

title: Comparing time_t values within an if statement

Answers: 1

body:
You have _two_ variables called `nowUniVM`. The fist one is a global
declared at the top of your program, and implicitly initialized to zero
by the compiler. Since you never update it, it is always zero. The
second one is local to `loop()`: it shadows the global variable inside
`loop()` and is updated periodically.

The function `samplerStarter()` only sees the global variable, which is
zero. Thus, the comparison boils down to

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

    if (starter < 0)

But since `time_t` is an unsigned type, the test can never be
true.


body:
Okay. Basically I want the android app to be able to recognize that a coin was inserted into the coin collector before it allows the user to use certain functions of the app.

However I am unsure what would be the best way to pass the data from the coin collector to the Android app.  My currently train of thought is to have the coin collector connect to an Arduino board which would then connect to the android app and send the input through that connection.

I was wondering if anyone knows of a better way to achieve this, or whether this is an acceptable/standard solution.

Thank you in advance!

title: Using Arduino to pass data from a coin collector to android app

Answers: 2

body:
Here are a couple of opitions for you:

1- Bluetooth - if in close range, an HC-05 will work great.

2- Wifi - wifi can work good. It is a little more complex then bluetooth but its range can get further. For example, a Tweet can be sent each time a coin is detected.

3- GSM - it is pretty much texting. You can make it so the coin collector texts you or someone there is a coin.

All of these solutions work great with the MIT app creator. It makes the data you receive much easier to process.

body:
My take: use a nodeMCU (an ESP8266 based board) instead of Arduino.

nodeMCU have WiFi and you can run a minimal WebServer on it, so your Android app can communicate using simple HTTP GET commands. Using Bluetooth is not as convenient.

That's means the Android programming part will be easy and you can extend your solution to other platforms (iPhone).

And you only need a browser to develop and test the Android-Web Server interface on nodeMCU

Maybe you can even run your entire app in the nodeMCU, and use only a browser to interact with the coin collector.


body:
I am using a custom library for Arduino Mega which uses [AES library][1] for AES-128 encryption.

However, when I try to use that library in Intel Genuino 101 development board, it shows compilation error which is because the assembly language written in AES library was compatible with Atmel devices only.

And my question is whether there is a way, my code can automatically detect the GENUINO board by writing some sort of signature verification of this board and hence I can exclude the encryption part if it can successfully detect GENUINO 101.

For any queries, feel free to bug me, thanks.

  [1]: https://github.com/DavyLandman/AESLib

title: How to detect Genuino 101 from inside the code?

Answers: 1

body:
Arduino defines some macros so you can use [conditional compilation][1]. For example these are from boards.txt:

- use `ARDUINO_AVR_PROMICRO` if it's specific for board variant
- use `ARDUINO_ARCH_AVR` if it's specific for Arduino with AVR

Also avr-gcc defines macros according to cpu settings (this should be similar for other platforms too):

- use `__AVR_ATmega32U4__` if it's specific for only one MCU
- use `__AVR__` if it's compatible with all AVR based MCUs

And code examples:

    #if defined(__AVR_ATmega88__) || defined(__AVR_ATmega168__) || defined(__AVR_ATmega328__)
    // something for ATmegaXX8 family...
    #else
    // ...
    #endif

    #ifdef __AVR__
    // Code related to AVR
    #else
    // Code for other architectures
    #endif

More about [predefined macros in avr-gcc][2].

  [1]: https://en.wikipedia.org/wiki/Conditional_compilation
  [2]: http://www.atmel.com/webdoc/AVRLibcReferenceManual/using_tools_1using_avr_gcc_mach_opt.html


body:
I have coded arduino for DHT11 which used to print humidity in first and temperature in second line. But some times when I open SerialPort I get absurd data.[![enter image description here][1]][1]

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

title: How to clear output buffer of Arduino Uno?

Answers: 2

body:
You can't.

The data you are seeing has already been sent by the previous execution of the sketch before the main MCU was reset. That data resides in a small buffer within the USB interface chip (or even within the USB CDC/ACM / USB UART driver itself, depending on your OS) to which you have no access.

You just have to ignore that data. The simplest way is to put a marker at the start of your program to indicate that whatever is receiving the data should start its receiving from this point on. Something like:

    Serial.println();
    Serial.println("START");

body:
I've circumvented this issue by sending a byte to the Arduino whenever I'm ready to receive data using this quick-and-dirty method:
```C
if(Serial.available() > 0) {  // At least one byte is available
  Serial.println(millis());
  Serial.read();  // Read the (one) character to empty the buffer
}
```


body:
I found this pump:

https://www.aliexpress.com/item/Free-Shipping-Ultra-quiet-DC-12V-3M-240L-H-Brushless-Submersible-Water-Pump-High-Qualtiy-mini/32472119699.html

Now, I want to control it from an Arduino.

Is this a good relay to use?

https://www.pololu.com/product/2480?

I want to use a 12v battery for the pump.

title: How to switch 12V water pump

Answers: 2

body: I see people are recommending mosfets (which is the best option). Keep reading this if you still want to use relay. There are two kind of relays, mechanical and solid state. Mechanicals are cheap but they can be noisy (they make sound) also they have low life expectancy compared to solid state relays. On the other hand solid state relays are faster with everything else but they are expensive. Also you need to check voltage and max current rates before buying.

body:
About the relay, you can buy a low cost relay from aliexpress like the following one or other variant.

https://m.aliexpress.com/item/32392799916.html#autostay

It's well within your desired voltage and current  range and works readily with arduino.


body:
For a driving application I need the PWM mode to be phase correct and the prescaler to be 1. The issue is that the board I am working with has the load hooked up to a PWM pin reliant on timer0. The firmware running on this board makes use of the `delay()`, `delayMicroseconds()`, and `millis()` functions from wiring.c. The goal is to make the timer0 change, shown below, and then make small modifications where the firmware calls the wiring.c timing functions. My approach was to find a scaling factor to be applied to the call of these functions. The scaling factor I came to was **32.12549**, calculated by taking the wiring.c expected timer0 behavior: **prescaler=64** and **TOV0 flag every 256 counts**, and comparing it to the actual values after my change: **prescaler=1** and **TOV0 flag every 510 counts**

**Calculation:** 64*256/510=32.12549

**Timer0 change:**

    // Set timer0 to phase correct PWM
    TCCR0A = TCCR0A & 0b11111100 | 0x01;

    // Set prescaler for timer0 to 1
    TCCR0B = TCCR0B & 0b11111000 | 0x01;

The other timers are all configured in phase correct PWM mode, with a prescaler of 1.

...When I apply this scaling factor to a value returned from millis() to keep time it works well. For example the two pieces of code below proved to be equivalent through the timer0 change:

**Use of `millis()` before timer0 change:**

    //current time
    long unsigned now = millis();

    //delay for 1 second
    while(millis() - now < 1000){}

**Use of `millis()` after timer0 change:**

    //current time
    long unsigned now = millis();

    //delay for 1 second, with x32.125 scaling coefficient
    while(millis() - now < 32125){}

**The two snippets of code above both delayed for 1 second**

Now comes the problem: when I try to apply that same scaling factor to `delay()` or `delayMicroseconds()` it seems to give unreasonable delays...

**Use of `delayMicroseconds()` before timer0 change:**

    // wait 1.5ms for mux to switch
    delayMicroseconds(1500);

...this delays for 1.5ms

**Use of `delayMicroseconds()` after timer0 change:**

    // wait 1.5ms for mux to switch, with x32.125 scaling coefficient
    delayMicroseconds(48188);

 ...this delays for ~20ms.

Assuming this is still linearly scalable:
 if 48188 -> 20ms, therefore 1.5ms -> 3614

But when the following code is used...

    // wait 1.5ms for mux to switch, scaled
    delayMicroseconds(3614);

...this delays for ~4.5ms

Why is it that `delayMicroseconds()` and `delay()` cannot be linearly scaled to account for a timer0 change? Furthermore, is there any simple modification to how these functions are called or utilized that can account for the effect of changing timer0?

title: Help managing the fallout from timer0 mode and prescaler change on ATMega2560 without modifying wiring.c

Answers: 1

body:
## The millis() roll over

By making Timer 0 faster, your `millis()` will roll over much more
often than normal: every 37.1 hours instead of every 49.7 days. Thus,
when you “scale” `millis()`, you should be careful to do it in a
rollover-safe way. From the code you show, it appears that you are doing
_exactly the right thing_. Well done! Don't change anything. Don't be
tempted to scale the value returned by `millis()`.

## The overflow in delayMicroseconds()

As this function just burns cycles in a busy loop, it is not affected by
your configuration of Timer 0. You can just use it as is, with no
scaling. Beware however that it's argument should always be smaller than
16384 (on a 16 MHz board). Otherwise it will overflow when it is
multiplied by 4 in order to get a loop count.

For example, when you call `delayMicroseconds(48188);`, the function
computes the number of loop iterations to make as

48188 × 4 − 5 = 61675 (modulo 216)

Then, it burns about 15 ms of CPU time (0.25 µs per
iteration), which is close to the 20 ms you see. For the
difference, see below.

## The cycles burned by the Timer 0 ISR

This ISR, which keeps the millis() counter updated, is supposed to run
every 1024 µs. Each time it runs it burns a few cycles, but it's
usually not a big deal. With your new timer configuration, it is now
running far more often: every 31.875 µs.

From the numbers you give in the question, I would say the ISR is
eating about 20% of your CPU power: when you call
`delayMicroseconds(3614);`, that function burns 3614 µs of CPU
time, yet you measure a delay of about 4500 µs. The difference is
taken by the Timer 0 ISR.

## Use another timer for millis()

If you can spare a timer, you could both restore the normal behavior of
`millis()` and avoid wasting so much CPU in the Timer 0 ISR:

* configure Timer 0 to _not_ trigger interrupts
* configure your spare timer just like the Arduino core would normally
  configure Timer 0
* write an overflow ISR for your spare timer that just calls the Timer 0
  overflow ISR.

This way your spare timer is basically replacing Timer 0. Example using
Timer 2:

    // This Timer 2 overflow ISR simply forwards the call to the Timer 0
    // overflow ISR from Arduino core.
    ISR(TIMER0_OVF_vect);
    ISR(TIMER2_OVF_vect, ISR_NAKED) {
        TIMER0_OVF_vect();
        asm volatile("reti");

        // Alternatively, just:
        // asm volatile("jmp __vector_16");
    }

    void setup()
    {
        // Set timer0 to phase correct PWM
        TCCR0A = (TCCR0A & 0b11111100) | 0x01;

        // Set prescaler for timer0 to 1
        TCCR0B = (TCCR0B & 0b11111000) | 0x01;

        // Disable Timer 0 interrupts.
        TIMSK0 = 0;

        // Configure Timer 2 to replace Timer 0.
        TCCR2A = _BV(WGM20)   // fast PWM, TOP = 0xff
               | _BV(WGM21);  // ditto
        TCCR2B = _BV(CS22);   // clock at F_CPU / 64
        TIMSK2 = _BV(TOIE2);  // enable overflow interrupt

        pinMode(LED_BUILTIN, OUTPUT);
    }

    void loop()
    {
        // Blink the LED at 1 Hz.
        uint32_t now = millis();
        static uint32_t last_toggle;
        if (now - last_toggle >= 500) {
            last_toggle += 500;
            digitalWrite(LED_BUILTIN, !digitalRead(LED_BUILTIN));
        }
    }

I wrote a “naked” ISR to avoid having plenty of CPU registers saved and
restored _twice_ (once by each ISR in the call chain), but then I had to
put the return instruction explicitly in assembly (`ret` and `reti`
would be equivalent in this instance). The version with `jmp` is
slightly more efficient, but you have to know the “real” name of the
ISR, which is MCU-dependent (`__vector_16` on an Uno).

Notice that with this technique `micros()` will not work, as it reads
TCNT0 directly. And `delay()` will not work either because it relies on
`micros()`.


body:
While unplugging the usb cable from the Arduino, the plastic piece in the center of the port (the part that separates the pins) broke off and lodged into the end of the usb cable. I didn't notice that it broke off and when I plugged the cable back into the Arduino it bent one of the pins back onto itself.

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

How would you go about repairing this?

If I fail to repair it is there an alternate method to programming the board?

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

title: How to repair or work around a damaged usb port on the Arduino?

Answers: 3

body:
You would need to replace the whole socket in order to repair it. For that you would need:

* Soldering iron
* Solder sucker
* Solder wick
* Patience and experience

Or you just connect an FT232 breakout board to TX, RX and RESET as if you were making a breadboard arduino and program the board through that.

body:
You could try bending the pin back, removing the white part from your cable, and gluing it back in.

Second option is to replace the USB socket on the Arduino board. You might be able to salvage a socket from some old electronics you still have lying around.

Third option is to cut one end of a spare USB cable, and solder the 4 wires inside the cable directly to the corresponding pads on the bottom of the broken socket. Add some glue to provide some strain-relieve to the cable.

Fourth option is an external USB to serial converter, like @Majenko suggested.

body:
I would suggest to actually remove the whole thing and resolder it. There are many tutorials out there is you're new to soldering. This way, it is less probable that it creates a short or data loss during compilation.

If you don't want to solder, then you might be able to use an FTDI connector. FT232s are quite cheap.

Tx > Rx

Rx > Tx

Reset > Reset

Vcc > Vcc

GND > GND


body:
I bought an ATMEGA2560 on eBay and programmed it with Arduino IDE 1.6.9 using the USB cable, and the LED blinked as expected - All well and good.

Now I wanted to program the mega from my UNO as follows:

 1. Uploaded ArduinoISP to the UNO
 2. Changed the Board to Mega2560 and changed the Programmer to Arduio as ISP
 3. Connected the two ICPS sockets with a 6 wire cable, where pin 5 on the UNO ICPS is cut and instead connected to D10 on the UNO
 4. Upload the Blink sketch: IDE says Uploading for a minute, then some errors:

    avrdude: stk500v2_ReceiveMessage(): timeout
    avrdude: stk500v2_getsync(): timeout communicating with programmer

5) Upload Using Programmer: Activity on the UNO (RX/TX) and the LED on the mega lights constantly - And I can no longer program the mega using the IDE

Any pointers to what I did wrong and how to fix it?
Best regards

title: Did I just brick my ATMEGA 2560?

Answers: 0


body:
When i Connected Rx>Rx (Rx Of module To Pin 0 Of Arduino) And Tx>Tx ( Tx Of Module To Pin 1 Of Arduino), The AT Command Test shows The Following error With Scrambled Words, but when I Connect Rx>Tx (Rx Of Module To Pin 1 Of Arduino) And Tx>Rx(Tx Of Module To Pin 0 Of The arduino), The AT Command Test Shows a Blank Screen. I Connected VCC, CHPD and RST Of Module to 3v Of Arduino and GND Of Module To GND Of Arduino. So How Do I Connect Arduino To Wifi Module which passes the at command test, Btw i Have an Intermediate, ie Motor Shield, I Connected Motor Sheild To Arduino And Then I connected Wifi Module To Motor Shield. Listen So  I need To Connect Wifi Module To Arduino, such that there isnt any error. what do i do?[![RX>Rx and Tx>Tx Pair][1]][1]

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

title: Arduino Uno Wifi Module ESP8266 AT Command Test error

Answers: 1

body:
The first connection you made between arduino and esp which resulted in some random data means both are communicating whereas the second connection where the screen shows blank means communication hasnt been established on account of incorrect wiring. So your first connection tx>tx and rx>rx is **correct**.

 The only two area which you need to check is the baud rate and the mode of return. Some Esps work at 115200 with mode carriage return. So you can try different combinations of baud rate and mode to check which one does your Esp support.


body:
I'm using the [Keyes Infrared Receiver Module][1] on an Arduino Uno R3 with the [IRemote library][2] included and running the `IRrecvDemo` example sketch included in the library.

I wired the IR receiver incorrectly the first time I ran the program. I wired the data pin to 5V and wired the Vcc pin on the module to the digital I/O pin. The ground was wired correctly.

Did I destroy the IR receiver by doing this? There was no noticeable overheating.

I corrected the wiring and tried again but still nothing over the serial monitor while pushing buttons on the IR remote that came with it. I wondered if the issue was with the remote so I hooked up a IR LED to flash using the following code:

    #include <IRremote.h>

    int RECV_PIN = 11;
    IRrecv irrecv(RECV_PIN);
    decode_results results;

    IRsend irsend;

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

    void loop()
    {
      for (int i = 0; i < 3; i++) {   //// for statement controls IR LED
        irsend.sendSony(0xa90, 12);
        delay(40);
        if (irrecv.decode(&results))    //// if statement controls the receiver
        {
         Serial.println(results.value, HEX);
         irrecv.resume(); // Receive the next value
        }
      }
    }

Nothing showed up on the serial monitor. However, the LED on the IR receiver module began flashing when the receiver was exposed to the IR LED, leading me to believe that I did not destroy the module when I wired it incorrectly.

Update:

I took the IR led and simply lit it with a coin cell battery and the IR receiver detected it and sent data over serial monitor. The remote powered by that same coin cell battery will not trigger the IR receiver. Can I conclude that this is a problem with the remote?

  [1]: http://tinkbox.ph/sites/tinkbox.ph/files/downloads/Keyes - Infrared Receiver Module .pdf
  [2]: https://github.com/z3t0/Arduino-IRremote

title: Why am I not receiving codes from IR receiver over the serial monitor?

Answers: 0


body:
Newbe question - I'm thinking of creating a simple robot that heads to a signal source.

Ie, when you press a button on some remote control - the robot will head towards its source.

What would be the best choice of signal? A strength of a wifi, sound?

AD

title: The best signal source for a path-finding robot

Answers: 2

body:
IR sensor in combination with an ultrasonic distance sensor would work great.

You can mimic a radar with an IR sensor so that it can detect from where the IR source from your remote is comming from. Then from there, process the angles and make you robot go towards it.

The ultrasonic distance sensor can be used a "fail" prevention system. In the sense that if it detects an object in front of the robot, it will stop, go around it and then continue towards the target

body:
I like @Canadiancyborg's IR solution, but the same theory can be applied to any other emitter, and RF emitters may be preferable to an IR emitter since IR light can be blocked by intermediate objects. Also an omnidirectional RF transmitter is easier to arrange than an omnidirectional IR transmitter.

The basic theory is that you need to work out which direction a signal is coming from. In order to do that you need to "look around you" and find at which angle the signal is strongest.

A highly directional receiver (parabolic dish, IR receiver with lens, etc) will allow you to sense the signal strongest when the receiver is pointing directly at the source. By then rotating the receiver (either on its own independent rotational system, such as a servo motor, or by rotating the entire robot using the wheels) you can "lock on" to the direction where the signal is strongest and drive towards it.


body:
I made OLED timer/watch using Attiny85, but as internal clock isnt accurate i need external crystal. On Attiny85 im short on pins so i am switching to Attiny84 but i have problems to compile/upload same code to Attiny84. Even if i stay on Attiny84 8mhz internal clock as on Attiny85 i still cant compile.
Im using Arduino UNO as ISP.

Error what i have:

    WDT_Time.cpp: In function 'void setup_watchdog(uint8_t)':
    WDT_Time.cpp:272: error: 'WDTCR' was not declared in this scope
    WDTCR |= (1 << WDCE) | (1 << WDE);
    ^
    In file included from c:\program files (x86)\arduino\hardware\tools\avr\avr\include\avr\io.h:99:0,
                 from c:\program files (x86)\arduino\hardware\tools\avr\avr\include\avr\pgmspace.h:88,
                 from C:\Program Files (x86)\Arduino\hardware\arduino\avr\cores\arduino/Arduino.h:28,
                 from WDT_Time.cpp:12:
    WDT_Time.cpp:276: error: 'PCIE' was not declared in this scope
       sbi(GIMSK, PCIE); // Turn on Pin Change interrupts (Tell Attiny85 we want to use pin change interrupts (can be any pin))
                  ^
    WDT_Time.cpp:276:3: note: in expansion of macro 'sbi'
       sbi(GIMSK, PCIE); // Turn on Pin Change interrupts (Tell Attiny85 we want to use pin change interrupts (can be any pin))
       ^
    WDT_Time.cpp:277: error: 'PCMSK' was not declared in this scope
       sbi(PCMSK, PCINT3);
           ^
    WDT_Time.cpp:277:3: note: in expansion of macro 'sbi'
       sbi(PCMSK, PCINT3);
       ^
    'WDTCR' was not declared in this scope

title: Attiny85 code on Attiny84

Answers: 1

body:
There are slight differences between registers, register names and registers bit names:

- `WDTCR` is named `WDTCSR`
- `PCIE` doesn't exist in `GIMSK` as there are two IO ports, so there are two pin change channels: `PCIE0` and `PCIE1`
- and `PCMSK` is similar to `PCIE`. There'll be two of them too.

Basically you have to look into both datasheets and compare what you are using and check if it's correct.


body:
I am very new to Arduino. I wrote a program in order to read some registers in a I2C device. I receive HEX datas.

So the Arduino LEONARDO is connected to the external board using the 2-wires-bus.
Then informations are sent to my computer by using Serial.println.

My problem is my Arduino stops working after a while, maybe 25 or 30 loops. Sometimes I loose communication and I have to reboot the Arduino.

I guess it's an overflow issue or I'm loosing connection randomly :

    int dt = 500;
    int dt2 = 1000; // used for delay duration
    #include "Wire.h"
    #include <Process.h>
    #define pot_address 0x25 // each I2C object has a unique bus address, the MCP40

    void setup() {
      // put your setup code here, to run once:
      Wire.begin();
      Serial.begin(9600);

    }

    void loop() {
      // put your main code here, to run repeatedly:

      Wire.beginTransmission(pot_address);
      Wire.write(0); //
       Wire.endTransmission();
      Wire.requestFrom(pot_address,8);
      byte b = Wire.read();

      Wire.beginTransmission(pot_address);
      Wire.write(1); //
       Wire.endTransmission();
      Wire.requestFrom(pot_address,8);
     byte c = Wire.read();

       Wire.beginTransmission(pot_address);
      Wire.write(2); //
       Wire.endTransmission();
      Wire.requestFrom(pot_address,8);
     byte d = Wire.read();

      Wire.beginTransmission(pot_address);
      Wire.write(3); //
       Wire.endTransmission();
      Wire.requestFrom(pot_address,8);
     byte e = Wire.read();

      Wire.beginTransmission(pot_address);
      Wire.write(4); //
       Wire.endTransmission();
      Wire.requestFrom(pot_address,8);
     byte f = Wire.read();

      Serial.print("b");
      Serial.println(b, HEX);
      Serial.println("-");
      Serial.print("c");
      Serial.println(c, HEX);
      Serial.println("-");
      Serial.print("d");
      Serial.println(d, HEX);
      Serial.println("-");
      Serial.print("e");
      Serial.println(e, HEX);
      Serial.println("-");
      Serial.print("f");
      Serial.println(f, HEX);
      Serial.println("-");

     delay(dt2);

    }

title: Serial loop stopped after a while, I don't know why

Answers: 1

body:
Add:

    while(!Serial) ;

I'll make sure the Leonardo is in sync with the Serial communication.

It is the case because the Leonardo is USB native thus the Serial communication works differently.


body:
I am trying to amplify the signal from an Adafruit Small enclosed piezo.  The piezo is working using the Arduino Knock example but I want to increase the sensitivity using an amplifier.  The wiring shown below does not work using the Knock sketch and I am assuming it is a problem with the wetware and the wiring(NOOB here).
Any advice in amplifying the piezo is appreciated.[![enter image description here][1]][1]

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

title: Amplified piezo sensor wiring problem

Answers: 1

body:
You don't seem to understand how to wire an OP-AMP. Here is a quick tutorial on their basics:

https://www.youtube.com/watch?v=kqCV-HGJc6A

The thing is that you are missing a LOT of resistors. An usual OP-AMP circuit contains many resistors to determine the amount of amplification and more...

The tutorial explains quite well what resistor and where do you need to put them in order for your circuit.


body:
I have a function that needs to return 3 int values. I currently use an array declared in the global scope and I ask the function to write into them. Is there a way to make a function return an array?

Here is what I want to do:

    int function()
    {

    int array[3];

    array[0] = 19;  //these are just random numbers

    array[1] = 7;

    array[2] = 69;

    return array[]; //is this possible??

    }

title: Returning an int array from a function

Answers: 3

body:
There are 2 ways to do what you want in C. One relies on the function caller managing memory, the other on the "library" code managing the memory. If you go with the caller-managed memory, your function accepts a buffer and fills it. For "library" managed memory, you provide additional functions to allocate and release the buffer that the caller then calls

If you want to use C++ idioms, you can make a class (possibly static) that allocates the memory and provides access to the data.

body:
There are several ways to achieve what you want:

## The way that does not work

Did you try to compile the code you gave in the question? Then you
probably noticed it does not compile. I tried and got: “error: expected
primary-expression before ‘]’ token”, meaning the compiler expected
`return array[some_index];`.

## The way that almost works

Remove the brackets and just return `array`:

    int *function()
    {
        int array[3];
        array[0] = 19;
        array[1] = 7;
        array[2] = 69;
        return array;
    }

This may work, or not, depending on the surrounding code, on how the
optimizer processes your program, and on how lucky you are when you test
it. It is called “undefined behaviour” and is something you should
always avoid.

Here is what happens: in C (and C++) you cannot return an array. The
identifier `array` “decays” to a pointer pointing at its first element.
Then `return array` is essentially equivalent to `return &array[0]`. The
problem is that, since the array is allocated in the function's stack
frame, it ceases to exist when the function returns, thus the caller
gets a pointer to an area of memory that is not allocated anymore.
Likely memory corruption ahead. The compiler warned me when I tried to
do that: “warning: address of local variable ‘array’ returned”. It's a
very serious warning that should never be ignored.

## The simplest fix: make the array static

As suggested by Chris Stratton in a comment, you can make the array
static, so it will be allocated for the whole life of the program:

    int *function()
    {
        static int array[3];
        array[0] = 19;
        array[1] = 7;
        array[2] = 69;
        return array;
    }

The only catch is that the function is now not _reentrant_, meaning that
every time you call it it will clobber the same array it returned on the
previous calls. Depending on your use case, this may not be an issue,
but it's something you need to be aware of.

## Have the caller manage the allocation

A safer (reentrant) way is to have the caller provide the memory needed
for the array. This is a very common method in C, and is suggested both
by Harper Shelby's answer and Chris Stratton's comment:

    int *function(int array[3])
    {
        array[0] = 19;
        array[1] = 7;
        array[2] = 69;
        return array;
    }

The caller can allocate in static memory, or in it's own stack frame, or
on the heap... but you do not care, the allocation is the caller's
problem now.

A couple of things to note here:

* The prototype is equivalent to `int *function(int *array)`: the
  function receives only a pointer. Writing `array[3]` instead of
  `*array` has the sole effect of _documenting_ that the function
  expects the pointer to point to somewhere with room for 3 values. You
  could document that in a comment instead.
* The function could return `void`, since the caller presumably knows
  the address it is giving you. Returning that same address is just for
  convenience, as it can help you chain calls like
  `another_function(function(array))`.

## Return the array in a struct

One may wonder: why can't we return an array in the first place. I do
not know for sure why the authors of the language made this choice, but
one possible explanation is that it is expensive to return a big array
by value, as it involves copying the whole of it. Now, if your array is
_really_ only three ints, then that argument does not apply, and you may
reasonably want to really return the whole array by value. This can be
done by embedding it inside a struct:

    // Struct definition.
    struct Array3 {
        int array[3];
    };

    Array3 function()
    {
        Array3 a;
        a.array[0] = 19;
        a.array[1] = 7;
        a.array[2] = 69;
        return a;
    }

body:
> I have a function that needs to return 3 int values.

In the interests of completeness I'll suggest another method. Let's assume that you really need 3 values and not 300.

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

    void foo (int & a, int & b, int & c)
    {
      a = 19;  //these are just random numbers
      b = 7;
      c = 69;
    }

    void setup() {
      Serial.begin (115200);
      int x, y, z;
      foo (x, y, z);
      Serial.println (x);
      Serial.println (y);
      Serial.println (z);
    }

    void loop() {
    }

This conceivably will use less memory because the compiler may be able to optimize all 3 values into registers. In fact in that specific example, it has optimized away the entire function call:

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

    000000be <setup>:
      public:
        inline HardwareSerial(
          volatile uint8_t *ubrrh, volatile uint8_t *ubrrl,
          volatile uint8_t *ucsra, volatile uint8_t *ucsrb,
          volatile uint8_t *ucsrc, volatile uint8_t *udr);
        void begin(unsigned long baud) { begin(baud, SERIAL_8N1); }
      be: 26 e0        ldi r18, 0x06 ; 6
      c0: 40 e0        ldi r20, 0x00 ; 0
      c2: 52 ec        ldi r21, 0xC2 ; 194
      c4: 61 e0        ldi r22, 0x01 ; 1
      c6: 70 e0        ldi r23, 0x00 ; 0
      c8: 82 e2        ldi r24, 0x22 ; 34
      ca: 91 e0        ldi r25, 0x01 ; 1
      cc: 0e 94 64 01  call 0x2c8 ; 0x2c8 <_ZN14HardwareSerial5beginEmh>
      d0: 4a e0        ldi r20, 0x0A ; 10
      d2: 50 e0        ldi r21, 0x00 ; 0
      d4: 63 e1        ldi r22, 0x13 ; 19  <---------- x
      d6: 70 e0        ldi r23, 0x00 ; 0
      d8: 82 e2        ldi r24, 0x22 ; 34
      da: 91 e0        ldi r25, 0x01 ; 1
      dc: 0e 94 4d 03  call 0x69a ; 0x69a <_ZN5Print7printlnEii>
      e0: 4a e0        ldi r20, 0x0A ; 10
      e2: 50 e0        ldi r21, 0x00 ; 0
      e4: 67 e0        ldi r22, 0x07 ; 7   <---------- y
      e6: 70 e0        ldi r23, 0x00 ; 0
      e8: 82 e2        ldi r24, 0x22 ; 34
      ea: 91 e0        ldi r25, 0x01 ; 1
      ec: 0e 94 4d 03  call 0x69a ; 0x69a <_ZN5Print7printlnEii>
      f0: 4a e0        ldi r20, 0x0A ; 10
      f2: 50 e0        ldi r21, 0x00 ; 0
      f4: 65 e4        ldi r22, 0x45 ; 69  <---------- z
      f6: 70 e0        ldi r23, 0x00 ; 0
      f8: 82 e2        ldi r24, 0x22 ; 34
      fa: 91 e0        ldi r25, 0x01 ; 1
      fc: 0c 94 4d 03  jmp 0x69a ; 0x69a <_ZN5Print7printlnEii>

    00000100 <loop>:
     100: 08 95        ret