body:
This Arduino sketch is a wonderful opportunity for you to learn the very basics of serial communication.
You should be very careful scaling the constants given in any baud rate program (whether using a hardware or software UART) as they are normally off by some small percentage, and without understanding the implications you may eventually introduce timing errors.
There is a great description of the timing sensitivities in this Picaxe [note][1].

The table below shows the actual bit times for various baud rates:
[![enter image description here][2]][2]

Notice here that for 9600 baud the sketch uses a constant which will use a 100 uS delay function for the bit times. From the table above you can see that this is slightly inaccurate, and the more correct delay would be 104 uS. This is an error of about 4%.

Would this error prevent successful reception of characters in the sketch?    Single characters with inter character spaces more than 1 character time, no ....but if you sent a string of characters end to end with no gaps this sketch would fail on receive.

Scaling the constant for 19200 baud --> 100/2 gives 50 but the bit time for 19200 is actually 52 uS, so again an error, this time of about 1%.
If we scaled the constant (100) for 115200 --> 100/12 gives 8.3 uS while 104/12 gives 8.7 uS for an error 4.5% or close to 0%.

There is IMO an error in this sketch for the serial receive routine, since it's hard wired to expect 2 stop bits. Any concatenated characters separated by only one stop bit will fail (you miss the second character start bit).

    int SWread()
    {
      byte val = 0;
      while (digitalRead(rx));
      //wait for start bit
      if (digitalRead(rx) == LOW) {
        delayMicroseconds(halfBit9600Delay);
        for (int offset = 0; offset < 8; offset++) {
         delayMicroseconds(bit9600Delay);
         val |= digitalRead(rx) << offset;
        }
        //wait for stop bit + extra
        delayMicroseconds(bit9600Delay);     ....hard wired two stop bits
        delayMicroseconds(bit9600Delay);     ....or 1 stop and 1 bit time gap
        return val;
      }
    }

  [1]: http://www.picaxe.com/docs/baudratetolerance.pdf
  [2]: https://i.stack.imgur.com/3jWuY.png


sender: user

message:
ArduCam ESP8266 and (Not-Mini) OV2640 Camera Module interface?

I bought ArduCam ESP8266 and a OV2640 Module. However it is not the mini-version. At the time it didn't seem like it was necessary.

I might have made a big mistake here.

The board has 8 female pins specifically for the camera module. But the OV2640 module has 20 male pins. A mini-version of the same camera leaves 8 pins, and has a nice interface.

I might have to send this back and get that one, but I want to know if it's possible to simply use this one and wire it up with certain pins instead?

Links to the two products to be specific:
http://www.arducam.com/camera-modules/2mp-ov2640/ (Camera)
http://www.arducam.com/arducam-esp8266-uno-board-arduino-camera/ (Board)

Thanks for your help,

Fred

sender: assistant

body:
No, you can't "mix and match" like that. The 8-pin header has I2C and SPI on it for a "cooked" video interface. The 20-pin interface has the "raw" camera CSI interface.

The difference is, the mini version has its own small video processor and FIFO chip on it which processes and buffers the video image allowing you to take a picture then slowly stream that data back through to the slow Arduino at a speed it is comfortable with. The non-mini version doesn't have that and relies on the host controller board having enough power to process a live CSI video signal, which the Arduino cannot do.


message:
Arduino as wireless network host

I have a rather simple question, which I cannot seem to find the answer to online.

I would like to host a wireless network using an arduino. Other devices could connect to and communicate with the arduino. Could I do that with a shield like this?

Also, once a device (say a phone) is connected, how would it go about requesting a web page, or other information?

Thank you!

body:
Yes!

You can absolutely do the above said task with the shield that you provided information about.

All you have to do is to connect the Shield to the Arduino and upload the WiFiWebServer sketch from the Arduino's examples in the WiFi library!

Then you'll have to replace the SSID and Password with your WiFi's password.

Once uploaded, then you'll get your Arduino's (Server's) IP Address on the Serial monitorl.

Note the IP Address and open any browser on any device of your choice.

**NOTE**-
Your device must be connected to the same WiFi network to which your Arduino is connected to. If you wish to access the Arduino server from outside your LAN then you'll have to forward/open a port on your WiFi router and direct it to the IP Address of your Arduino. But I am assuming that you just want to access it from your LAN therefore the port forwarding can be ignored.

You'll see the default webpage in the Sketch which you can change/edit as per your own wish by using HTML.

Here's the [link][1] to the detailed explanation from arduino.cc itself.

Coming to the Second part of your question: "Also, once a device (say a phone) is connected, how would it go about requesting a web page, or other information?"

Well once the server is started on the Arduino all you do is type the IP of Arduino in the browser of the device and then the browser sends a HTTP request to the server.(This is the same way in which the browser sends requests to any other website or server like google/youtube/stackexchange . It is same for all ).

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


message:
Motor shield for Arduino Nano ATmega328

I am looking for a cheap and not so space consuming motor shield for my Arduino Nano ATmega328. I would like to charge the whole thing with a 9V battery. The shield must have at least 2.1A of output current so I can run 3 brushed DC motors on it. There will also have to be some pins left for a Bluetooth card and 3 analog pins for sensors.

Do you know any shields that meet my requirements?

body:
**In short:**

Nano + Shield = no possible

---

>[...] 9V battery. The shield must have at least 2.1A of output [...]

You can't invent power out of nowhere.

---

**Options for the shield**

**Option 1:**

Use an other Arduino. It will simplify everything.

**Option 2:**

Use a Nano to Uno adapter.

**Option 3:**

By an Uno shield and connect it pin by pin to the Nano.

**Option 4:**

Use MOSFETs. They'll work fine for what you are trying to do.

---

**Options for powering**

**Option 1:**

Use a 2s lipo. Voltage is above 5V so you have to reduce it with a down converter, but you should have enough juice for the motors.

**Option 2:**

Use a *lot* of AA, some in series to augment the voltage and then in parallel to augment the current.

**Option 3: (just the the crazy minded)**

Use a lead-acid battery (aka car battery).


message:
Why is the loop() stopping?

I would like to move my servo motor (SM-S2309S) between random angles. In order to do so, I used this simple code:

    #include <Servo.h>
    Servo servoMain; // Define our Servo

    // SM-S2309S angular speed
    float speed = 0.12/60;

    void move(int from, int to)
    {
      // initiate the move to the new angle
      servoMain.write(to);
      // wait for the movement to actually happen over the actual angle to move through
      delay(1000 * speed * int(from-to));
    }

    void setup()
    {
       servoMain.attach(10); // servo on digital pin 10
       Serial.begin(115200);
       // move to center as a start
       servoMain.write(90);
       delay(1000);
    }

    void loop()
    {
      // the previous angle, initially set as center (per the setup() call)
      static int oldangle = 90;
      // apparently 15 to 165 deg is a safe range
      int newangle = random(15,165);
      Serial.println(newangle);
      move(oldangle,newangle);
      oldangle = newangle;
    }

It starts by placing the arm in the center (in the `setup()` function) and then should generate a random number (the new angle to go to), in a loop.

What I get is the initial position, then two moves (counterclockwise, then clockwise). The output on the serial console shows `22` and `64`, which is consistent with the two moves.

**Then everything stops.** There is no error message on the console (I do not expect one to be, but I am not sure if there could be any feedback from the Arduino, being a complete beginner). **What can be the reason for this stop, after two successful loops?**

body:
Just a **small** mistake! Not much big of a deal :D

In the move function

`void move(int from, int to)
{
  // initiate the move to the new angle
  servoMain.write(to);
  // wait for the movement to actually happen over the actual angle to move through
  delay(1000 * speed * int(from-to));
}`

suppose the values passed are 20, 35 then the last line would be 1000*speed*(-15) Which is negative therefore the arduino delay function converts the - signed bit to a very large unsigned number.

All you have to do is to take the magnitude of from - to ie |from - to | by calling the abs() function.

your move function would look like this:

  `  void move(int from, int to)
{
  // initiate the move to the new angle
  servoMain.write(to);
  // wait for the movement to actually happen over the actual angle to move through
  delay(1000 * speed * abs(int(from-to)));
}`

Just alter your move function or copy mine and you'll have no problem at all!


message:
Code is supposed To extract data between * ie *989*= 0989*; Runs only once then doesn't please help

void loop() {
           char *stptr=&string[0];
           if(Serial.available() > 0)
           {
              data = Serial.read();
              if(data=='*')
              {
                ib=1;jb=0;
                string[0]='0';
                //Serial.print("GOT INTO IF");
                while(string[ib-1]!='*')
                {
                  //Serial.print("Got into reading while");
                  //Serial.print(string[i]);
                  if(Serial.available() > 0)
                  {
                    if(string[ib]!='*')
                    {
                      string[ib]=Serial.read();
                      ib++;
                    }
                  }
                }
             }
          }
    }

body:
Something like this should work:

    void loop()
    {
        char *stptr = string;
        if (Serial.available()) {
            data = Serial.read();
            if (data == '*') {   // Check for starting *
                *stptr++ = '0';  // Copy '0' to string

                // Loop until: no data in port, or second * received
                while (Serial.available() && '*' != (data = Serial.read())) {
                    // Copy to string
                    *stptr++ = data;
                }
                // Terminate string
                *stptr = '\0';
            }
        }
    }


message:
Programming ATMega328p using VP812 programmer (for AVR/Atmel chips)

I bootloaded an ATMega328p (the one that uses the basic Arduino bootloader). Then, I used the VP812 for dumping other programs written in C (in Atmel Studio).

The process of erasing, blank test, programming and verification are all working fine and it seems that the program is actually being flashed. However, when I insert the same chip (controller) back in the Arduino Uno board, the controller doesn't function as programmed. Also, I am not able to dump any other example sketches.

1. Does this mean that the chip is damaged?
2. Does using the bootloaded chip with VP812 cause such problems?

Also, I used the "Write Fuse" option with the standard fuse configuration (all marks checked) in the VP812 configuration dialog box. Did this setting in any way create the problems I am facing now?

body:
Yes - the settings created this problem. You have erased and disabled (via default fuses) the bootloader. It means that your application will run perfectly fine on an Arduino board, but you will not be able to flash over USB.

If you want to use Arduino USB bootloader again then you have to [follow this guide][1]

  [1]: https://www.arduino.cc/en/Hacking/Bootloader


message:
Several Piezo contact mics with Arduino

I'd like to connect about 6 contact mics to my arduino and receive simultaneous signals to be used in my computer for an art installation.

Nonetheless, I don't know what's the ideal way to go. Shall I use Analog pins or Digital? How should I connect them - what schematics shall I follow? I read that ADC is CPU intensive, but I couldn't really find any viable alternative that explicitly shows the Digital deal.

Can I connect several contact mics to different analog pins and receive their input simultaneously as shown here? If this works, then it's perfect.

https://www.arduino.cc/en/Tutorial/Knock

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

A piezo element can be connected to an analog input (A0 for example) of your microcontroller, but extra resistors are advisable if you wish to have a digital sample that is linearly proportional to the element's alternating voltage.

Andy's caution about over-voltage is relevant too - these elements can produce voltages far greater than your Arduino's DC supply voltage. Such over-voltage can cause damage. Resistor R3 helps limit potential damage.

Each piezo element will require its own set of three resistors (duplicates of R1, R2, R3). Many microcontrollers have multiple analog inputs - you can have as many piezo circuits as there are analog inputs. You cannot sample them all simultaneously, since most microcontrollers usually have only one analog-to-digital converter, which is switched between its various analog inputs by program control. A piezo element would have to be sampled, then switched to the next element for sampling, then the next....etc.

Sampling can be done fast enough that "audio" (however you define it) is fairly represented by the digital sample stream. However, be aware that processing these audio samples may be beyond the speed capability of simple microcontrollers like Arduino. That part is up to you.

Be aware that piezo elements make poor microphones. Units mounted in plastic shells are designed to **output** audio tones, and have significant resonant peaks. Frequency response is not flat, as required by a proper microphone.


message:
Why does the serial monitor needs to be repeated a command?

I am experimenting with the serial monitor in an Arduino Uno. My project consists in a simple LED turning on and off at will with the commands "ON" and "OFF" respectively.

To achieve this, I use an HC-06 Bluetooth module, but because of the nature of the test I decided to disconnect it and 'debug' my project using the serial monitor as an equivalent.

The circuit has the following connection table:

**LED +:** Pin 12 on my Arduino.
**LED -:** GND on my Arduino.

...as you can see, I have tried to simplify as much as I can the circuit, as I wanted to make sure I didn't have wire problems.

Here's the code:

    char command;
    String string;
    #define led 12

    void LEDOn()
        {
              digitalWrite(led, HIGH);
        }

    void LEDOff()
        {
          digitalWrite(led, LOW);
        }

    void setup()
    {
          Serial.begin(9600);
          pinMode(led, OUTPUT);
    }

    void loop()
    {
         if (Serial.available() > 0)
               {string = "";}

         while(Serial.available() > 0)
        {
               command = ((byte)Serial.read());

               if(command == ':')
               {
                      break;
               }

               else
               {
                      string += command;
               }

               delay(1);
        }

        if(string == "LO")
        {
               LEDOn();
         }

       if(string == "LF")
        {
               LEDOff();
        }

The problem comes when I type the commands. Normally, an LED in the board will react (I think it's the RX one), but the LED in pin 12 will not react at all. After testing ten times with each command alternatively, I calculated the serial needs an average of 6 command repetitions in order to react. Exactly the same happens when the HC-06 is connected.

Is there a reason for this?

body:
It worked fine for me, _if_ I typed the entire command, "LO:" or LF:" (without the quotes of course). However, if I typed and sent one character at a time, it failed. The problem is quite likely the code:

>        if (Serial.available() > 0)
>              {string = "";}

If you send all of the characters at once, the `while( Serial.available() )` loop will get the whole line and match it. But if there is any pause between characters, what does that `if` statement do? (Hint: `loop()` executes way faster than you can type!)

I was using the serial terminal built into the Eclipse IDE. Different terminal software might behave differently when you type a string and send it. Remember, any gaps between characters, and that first `if` statement gets time to do its dirty work.


body:
Your problem is, amongst other things, that you are assuming that all the serial data arrives at once, which doesn't necessarily happen at all.

I have a [discussion about this sort of thing](http://www.gammon.com.au/serial).

Rewriting your sketch using the ideas presented there we get this:

    #define led 12

    void LEDOn()
    {
      digitalWrite(led, HIGH);
    }

    void LEDOff()
    {
      digitalWrite(led, LOW);
    }

    // how much serial data we expect before a newline
    const unsigned int MAX_INPUT = 50;

    void setup ()
    {
      Serial.begin (9600);
      pinMode(led, OUTPUT);
    } // end of setup

    // here to process incoming serial data after a terminator received
    void process_data (const char * data)
    {

      if (strcmp (data, "ON") == 0)
        LEDOn ();
      else if (strcmp (data, "OFF") == 0)
        LEDOff ();
      else
        {
        Serial.print (F("Unexpected command: "));
        Serial.println (data);
        }
    }  // end of process_data

    void processIncomingByte (const byte inByte)
    {
      static char input_line [MAX_INPUT];
      static unsigned int input_pos = 0;

      switch (inByte)
      {

        case '\n':   // end of text
          input_line [input_pos] = 0;  // terminating null byte

          // terminator reached! process input_line here ...
          process_data (input_line);

          // reset buffer for next time
          input_pos = 0;
          break;

        case '\r':   // discard carriage return
          break;

        default:
          // keep adding if not full ... allow for terminating null byte
          if (input_pos < (MAX_INPUT - 1))
            input_line [input_pos++] = inByte;
          break;

      }  // end of switch

    } // end of processIncomingByte

    void loop()
    {
      // if serial data available, process it
      while (Serial.available () > 0)
        processIncomingByte (Serial.read ());

      // do other stuff here like testing digital input (button presses) ...

    }  // end of loop

> with the commands "ON" and "OFF" respectively.

I changed the test to be for "ON" and "OFF" not "LO" and "LF" which seems a weird way of meeting your requirements.

For this to work you need a **delimiter** (which tells the Arduino when you have finished sending a command). I have used linefeed which you can automatically send in the IDE's serial monitor (see bottom RH corner).

[![Serial monitor][1]][1]

I also put in code to show "Unexpected command: " if you don't get ON or OFF (note that "on" is not the same as "ON").

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


message:
Hardware logic gates for a simple demo with LEDs

I need some logic gates for a simple demo like [this one][1]. I will use a regular breadboard and an Arduino UNO as a 5 V and GND supply.

I found these ICs from Texas Instruments SN74LSxxN (NOT, AND, OR, NAND, NOR, XOR). For my demo I only need two inputs (well obviously only one on NOT) and one output on each chip. I want to connect the output to a LED via resistor to demonstrate that for example 1 XOR 1 equals 0 (LED off), or NOT 0 equals 1 (LED on):

[![demo circuit][2]][2]

My LSs seem to work as expected without an LED connected:

[![works well][3]][3]

    int value;

    void setup() {
     pinMode(10, OUTPUT);
     pinMode(11, OUTPUT);
     Serial.begin(1200);
    }

    void loop() {
     digitalWrite(10, LOW);
     digitalWrite(11, LOW);
     value = digitalRead(5);
     Serial.println(value);
    }

…but it would be great to make an LED demo too.

These ICs are probably a better choice in my case?

 - SN74ACT04N (NOT)
 - SN74ACT08N (AND)
 - SN74ACT32N (OR)
 - SN74ACT00N (NAND)
 - CD74ACT02 (NOR)
 - SN74ACT86N (XOR)

For everyone who isn't happy with Arduino as power supply here an alternative circuit with the same question - which IC family should I use?

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

**Update:** Well, probably I should better use something like [LogicBlocks][5] for my demo.
There is no NOR, XOR or NAND in this set, but it should be much easier to handle.

  [1]: https://www.youtube.com/watch?v=IDf2vEcyDfs
  [2]: https://i.stack.imgur.com/qmSCh.png
  [3]: https://i.stack.imgur.com/5piLz.png
  [4]: https://i.stack.imgur.com/x51aG.png
  [5]: https://www.sparkfun.com/products/11006

body:
The SN74HC04 has a [documented](http://www.ti.com/lit/ds/symlink/sn74hc04.pdf) output driver capability of ±4 mA when running at 5V:

[![SN74HC04 datasheet][1]][1]

Assuming you are using red LEDs with a forward voltage of 1.6V (as I measured one of mine lying around on the bench to be), then to not exceed this you need to get a resistor of:

    (5 - 1.6) / 0.004 = 850 Ω

A reasonable (and safer) value would be a standard 1k resistor, which you are likely to have lying around (and if not, get a few hundred of them). That would give you 3.4 mA current through the output pin, which is in range.

---

> I found something very similar to my demo on YouTube ...

Yes, well, people on YouTube aren't always doing things exactly like they should. :)

See Mike Cook's tutorial [The care and feeding of LEDs](http://www.thebox.myzen.co.uk/Tutorial/LEDs.html). As he points out, a lot of people use the wrong, or no, resistors because "it seems to work".

It may well seem to work for a while, but if you want a design that will last for a long time, you work within the manufacturer's specifications.

The problem with people disseminating wrong information is that someone will then copy it, and repeat it, and before long you find people saying "everyone does it this way".

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


body:
The circuit I was looking for looks like this:

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

And the HC family seems to do the job. Thanks to **dlloyd** ([link][2]).

  [1]: https://i.stack.imgur.com/dzdjI.png
  [2]: http://forum.arduino.cc/index.php?topic=444853.45


message:
How to execute commands on Arduino (via PC) without touching the current sketch?

I am working on my first Arduino project. It's a [Reverse Geocache][1]. Basically, it's a puzzle where a battery-powered Arduino is mounted inside a locked box, and is able to unlock the box if the user brings the box to the correct GPS coordinates and presses a push-button (that activates the Arduino, that runs a sketch, that checks the GPS, and operates a servo to release the lock).

It's all working, but I am trying to build in a backdoor, so I can unlock the box when I need to.

I have made the Arduino USB port accessible, and my hope is that I could connect a PC, and execute the appropriate command to operate the servo to unlock the box. The command is:

    servo.write(OPEN_ANGLE);

The sketch that drives the whole puzzle depends on these libraries, but I am guessing the only one needed to operate the servo is PWMServo.h:

    #include <PWMServo.h>
    #include <SoftwareSerial.h>
    #include <TinyGPS.h>
    #include <EEPROM.h>
    #include <LiquidCrystal.h>

I would like to be able to operate the servo without altering/replacing the uploaded sketch.

Is it possible to execute code "command prompt" style? Or can I somehow detect from within the sketch code that there is a USB connection, and have that trigger the unlock?

Finally (not the main question, but I would appreciate clarification), I have been told that the power to the Arduino should be disconnected before uploading new sketches (not sure why or if this is true). If forcing an unlock via the backdoor required uploading a new sketch, I seem to have a problem... For the puzzle to work within the locked box, the battery must be permanently connected, and also connecting to a PC via the USB seems to immediately power up the Arduino too. Does this mean uploading a new sketch would be impossible?

  [1]: http://www.sundial.com/quest-box/notes-for-builders/

body:
The simple thing would be for your sketch to read from the serial port continuously. If it finds something it stores it and when a newline arrives it sees if that happens to be a password known only to you. So, for example, all you would have to do is plug in the USB cable, activate the Serial Monitor on your PC, type `swordfish` and the servo opens the box.

You would need to allow for garbage arriving, so make sure that you discard input if it exceeds the size of the buffer you allocate for this purpose.

---

>  I have been told that the power to the Arduino should be disconnected before uploading new sketches (not sure why or if this is true).

I don't see how that can be true as you have to reapply power to upload the sketch. I never do that.

---

> Is it possible to execute code "command prompt" style?

No, you upload compiled code.

---

> Or can I somehow detect from within the sketch code that there is a USB connection, and have that trigger the unlock?

Then all the person you give the box to has to notice the USB port, plug something in, and it unlocks. I think not.

---

An even simpler solution would be to have two locations that unlock the box. For example, your kitchen could be one, so to unlock it you just take the box to your kitchen. The other location would be the "real" one that you want your friend to have to find. All the stuff about "you are 200 km from your destination" would of course refer to the real destination. You just make the code check that if it happens to find itself in your kitchen it unlocks the box.


message:
Programming an ATmega328P by holding it on an Uno's

I was looking at this Uno clone, [the Nanino](https://github.com/robelix/nanino) and then happened to read [this article](http://www.sdmakersguild.org/the-art-of-manhattan-style-circuit-construction/) on "Manhattan style" circuit design. Anyway, that got me thinking...

If I borrowed someone's Arduino Uno, could I hold a blank ATmega328P on top of the identical chip on that Uno and load a bootloader onto the board's chip as well as my chip? The desired result would be to give my blank ATmega328P a bootloader.

body:
It's easy enough to use a Uno to program a bootloader onto another chip. I describe this process [here](http://www.gammon.com.au/bootloader).

The idea of holding one chip on top of another is likely to fail for various reasons. Both chips will try to respond to the programming attempt at slightly different times, probably making them both fail to be programmed.

See [my post about making a breadboard Arduino](http://www.gammon.com.au/breadboard). It only takes a few wires to program the target chip.

[![Programming bootloader][1]][1]

However this isn't just "paralleling the pins" - it is using one chip to program another, in the way it is designed to do.

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


body:
> If I borrowed someone's Arduino Uno, could I hold a blank ATmega328P on top of the identical chip on that Uno and load a bootloader onto the board's chip as well as my chip? The desired result would be to give my blank ATmega328P a bootloader.

Well burning a bootloader(over a SPI communication) is quite different than simply uploading code(Serial communication), therefore it requires a specific setup which is an AVR-ISP.(In-System Programmer).

So you can't burn a bootloader by simply holding it over the other because of the Uno design.

The IC socket for the Atmega chip on the Uno board is not set for SPI communication so you can't burn a bootloader onto it directly. Instead, you'll have to do a similar setup to Nick Gammon's. Use one arduino as an ISP to burn the bootloader onto another.

Therefore placing the 'raw' chip in the socket and trying to burn the bootloader won't even work.

**Note** that in this setup, the Uno is communicating as an ISP and *it* uploads the code to the 'raw' Atmega328 chip. The chip on the Uno already has the bootloader(in fact it is configured/programmed to be an ISP).

Hope it helps!
Best of luck!


message:
Servo/Motor for barrier gate

I am working on a small project that will need to check for proper UPC's then if validated, lift a barrier gate to move along cardboard boxes. The Arduino comes in with the gate lifting. I have this barrier gate working with a very small servo that came included with the Arduino Starter Kit, but this could not hold the weight that might be pushing up against it with a longer arm. Has anyone had any experience with something like this or could someone direct of a power supply/servo combo that would be up to the task? These boxes could weigh up to 20 pounds.

Thanks!

body: You could look at larger DC gearmotors such as automotive power window or power door motors and use limit switches for position sensing. To power this you would need a 12V power supply capable of at least 5 amps.


body:
You may **purchase a servo motor with greater torque**.

You may find both DC as well as AC servo's. If you are using it in a real industrial scenario I would suggest you to use the AC, as you may not have to convert the ac power to DC and these motors will need real high current. So it would be better if it works on the main voltage. I did find **[PANASONICs ac servo][1]** as google search result.

If you have problems with integrating the greater torque motor to your current system let me know i can help you out.

  [1]: https://industrial.panasonic.com/ww/products/motors-compressors/fa-motors/ac-servo-motors


message:
Implementing AT commands with Arduino and ESP8266

Being a newbie to Arduino, I'm trying to implement AT commands in the serial monitor, though in vain. After connecting the ESP8266 (01) module to an Arduino Uno, I tried to scan for the nearest network present [code link: https://github.com/esp8266/Arduino/blob/master/doc/esp8266wifi/scan-examples.md#simple-scan] and it worked perfectly.

But the moment I am trying to connect to send AT commands (even manually), it shows nothing. In addition, `if(Serial.available())` and `if(esp8266.available())<` both are giving **false** value.

What am I doing wrong?

body:
You don't give a circuit diagram or very much detail about what you've done, but if I guess correctly...

You have flashed the code in your link to the ESP-01 (perhaps using the Arduino as a serial port adapter). That code is now running on the ESP itself - it's *not* running on the Arduino and controlling the ESP.

Flashing the ESP erases the stock firmware, so the ESP can no longer respond to AT commands.

I don't know of a way to reprogram the 'AT' firmware into the ESP but perhaps Google will help.

If I've guessed incorrectly, please explain exactly what you have done - with circuit diagram, setup steps and code.


body:
Anyone who is new to using ESP8266 module should consider following before interfacing it with Arduino

1. Try [connecting ESP Module directly with your computer][1] and test out all the AT Commands you will be implementing with Arduino. This approach is better because (a) this will give you confidence that your communication works perfectly (b) you will figure out all the problems that people face when sending AT commands and receive reply (c) this is a more visual approach so you will know what is going on and where you are going wrong.

2. Use [Computer based communication tools][2] and [make a simple power adaptor][3] to solve communication and wiring problems once and for all.

  [1]: http://absaransari.com/2018/01/26/connecting-esp8266-wifi-mobile-with-computer-using-pl2303/
  [2]: http://absaransari.com/2018/01/27/esp8266-wifi-module-configuration-utility/
  [3]: http://absaransari.com/2018/01/25/how-to-power-esp8266-from-5v-supply/


message:
Port Manipulation and serial communication

i'm working on a laser timer using arduino and i saw that using direct port manipulation can have a really better time precision. My only concern is about serial communication, because i am using some pins for a software serial, and i don't know how to set them in the ports register. The pins are the 4 and 5, and the number 3 is the trigger output, unluckily this pinset cannot change. How should i set them in the DDRD? I'm using an Arduino Nano board

body:
You can modify a single or multiple bits in a register by using a Read-Modify-Write approach. Essentially something like this:

    byte temp = DDRD;
    temp = (temp & ~(bitmask)) | bits_to_set;
    DDRD = temp;

In the above code, `bitmask` is some value with the bit or bits you want to modify set - e.g. if you want to change bits 4 and 5, it would be `(_BV(4) | _BV(5))` or just `(0b00110000)`. `bits_to_set` is a value with all bits that you want to be one set - e.g. if you want bit 5 to be a 1, it would be `(_BV(5))` or `(0b00100000)`.

What the code does is to first get the current value of the register you want to manipulate. Then it will clear only the bits which you want to modify to 0 by using bitwise AND on the temp value. Next it will set only the bits you want to change to be set by using a bitwise OR. Finally it writes it back to the register.

If you are using interrupts which, you may wish to do this atomically (so that the register is not changed by an interrupt occurring before the new value is written back). You can do this by wrapping the above code in:

    byte oldSREG = SREG;
    cli();
    ...
    SREG = oldSREG;

Which will clear the global interrupt flag to pause any interrupts, and then will restore the value of it afterwards.

---

If you just want to change a single bit in a register you can optimise this code down to one of the following examples:

    DDRD |= _BV(4); //Set bit 4
    DDRD &= ~_BV(5); //Clear bit 5

Again you may want to do this atomically as it may compile to a Read-Modify-Write access.


message:
Making an automated watering system with Arduino

I am trying to make an automated watering system using an Arduino.

Here is my wiring diagram:
[![Wiring Diagram][1]][1]
And here is my circuit wired up:
[![Photo of wired circuit][2]][2]

Here is the code that I'm using with Arduino. The code seems alright and the wiring on the Arduino seems okay as well, but I don't know where to place a speaker on the Arduino. The biggest problem is that the program doesn't run like I coded. After I uploaded this code to Arduino, the water pump just keeps running forever. Can anyone check up my code to make this run properly?

    /**automated watering program **/

    #include <avr/sleep.h>
    #include <avr/wdt.h>
    #define BEAT 300 // define time for the tone.
    #define PINNO 12

    int led = 13;

    void setup() {
      // setup code to run once:
      pinMode(led, OUTPUT);
    }

    void loop() {
      // main code here, to run repeatedly:
      tone(PINNO,262,BEAT); // C(do)
      delay(BEAT);
      tone(PINNO,294,BEAT); // D(re)
      delay(BEAT);
      tone(PINNO,330,BEAT); // E(mi)
      delay(BEAT);
      tone(PINNO,262,BEAT); // C (do)
      delay(BEAT);
      tone(PINNO,294,BEAT); // D(re)
      delay(BEAT);
      tone(PINNO,330,BEAT); // E(mi)
      delay(BEAT);
      tone(PINNO,392,BEAT); // G(so)
      delay(BEAT);
      tone(PINNO,330,BEAT); // E(mi)
      delay(BEAT);
      tone(PINNO,294,BEAT); // D(re)
      delay(BEAT);
      tone(PINNO,262,BEAT); // C(do)
      delay(BEAT);
      tone(PINNO,294,BEAT); // D(re)
      delay(BEAT);
      tone(PINNO,330,BEAT); // E(mi)
      delay(BEAT);
      tone(PINNO,294,BEAT); // D(re)
      delay(BEAT);
      delay(1000); // Wait for 1 second
      digitalWrite(led,HIGH); //Make No. 11pin output HIGH = 5V
      delay(500); // Watering time
      digitalWrite(led,LOW); //Make No.11 pin output LOW = 0V
      // Shut down program to save battery using by watchdogtimer 24h standby mode
      int var = 0;
      while(var < 10800) {
        delayWDT(9); // 9seconds of shutdown
        var++; // 10800times repeat ＝24h
      }
    }

    void delayWDT(unsigned long t) {
      // delay excute while using powerdown mode
      delayWDT_setup(t); // watchdog timer setting
      ADCSRA &= ~(1 << ADEN); // ADEN bit clear and stop ADC
      set_sleep_mode(SLEEP_MODE_PWR_DOWN); // Powerdow mode
      sleep_enable();
      sleep_mode(); // sleep mode
      sleep_disable(); // WatchDog Timer times up and start working again
      ADCSRA |= (1 << ADEN); // turn on the ADC
    }

    void delayWDT_setup(unsigned int ii) {
      // setting up timer
      // 0=16ms, 1=32ms, 2=64ms, 3=128ms, 4=250ms, 5=500ms
      // 6=1sec, 7=2sec, 8=4sec, 9=8sec
      byte bb;
      if (ii > 9 ) {
        // get rid of strange numbers
        ii = 9;
      }
      bb =ii & 7;
      if (ii > 7) {
        bb |= (1 << 5);
      }
      bb |= ( 1 << WDCE );
      MCUSR &= ~(1 << WDRF); // MCU Status Reg. Watchdog Reset  Flag ->0
      // start timed sequence
      WDTCSR |= (1 << WDCE) | (1<<WDE); // allow to edit watchdog
      // set new watchdog timeout value
      WDTCSR = bb;
      WDTCSR |= _BV(WDIE);
    }
    ISR(WDT_vect) {
      // the work after time up, WDT
      //  wdt_cycle++;
    }

  [1]: https://i.stack.imgur.com/SSdqj.png
  [2]: https://i.stack.imgur.com/Qn18M.jpg

body:
Problems with your setup:

* Your pump is connected to pin 11 but you are controlling pin 13 (`int led = 13;`)
* You have an LED in line with your transistor base. That should be a resistor, and the LED should be in *parallel* with the base (with its own resistor).
* Your transistor is wired wrong. According to [the datasheet](https://www.farnell.com/datasheets/410427.pdf) the pins are C-B-E as viewed from the angle in your wiring diagram. You have the Arduino connected to E instead of B, the pump connected to B instead of C, and ground connected to C instead of E.
* You don't have a flyback diode across the motor.

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

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

<!-- End schematic -->


message:
Couldn't connect to local server using Ethernet Shield and Arduino Mega 2560

I'm trying to connect the arduino mega and ethernet shield and try to send some data to a php script. I have connect the ethernet shield to the laptop. Lap is connected to router through wi-fi. Any help in advance please.

    #include <SPI.h>
    #include <Ethernet.h>

    /******************** ETHERNET SETTINGS ********************/

    byte mac[] = { 0x90, 0xA2, 0xDA, 0x0D, 0x85, 0xD9 };   //physical mac address
    byte ip[] = { 192, 168, 1, 5 };                   // ip in lan
    byte subnet[] = { 255, 255, 255, 0 };              //subnet mask
    byte gateway[] = { 192, 168, 0, 1 };              // default gateway

    IPAddress server(192,168,1,2);
    EthernetClient client;

    void setup() {
        Serial.begin(9600);  // Initialize serial communications with the PC
        while (!Serial);     // Do nothing if no serial port is opened (added for Arduinos based on ATMEGA32U4)
        Ethernet.begin(mac,ip,gateway,subnet);     // initialize Ethernet device
        Serial.print("My IP address: ");
        for (byte thisByte = 0; thisByte < 4; thisByte++) {
          Serial.print(Ethernet.localIP()[thisByte], DEC);
          Serial.print(".");
        }
        Serial.println();
        Serial.println("connecting....");
    }

    void loop()
    {
      if (client.connect(server,1234)) { // REPLACE WITH YOUR SERVER ADDRESS
        Serial.println("Server connection OK");
        client.println("GET /add.php?temp1=10&hum1=20 HTTP/1.1");
        client.println("Host:" + server);// SERVER ADDRESS HERE TOO
        client.println("Content-Type: text/plain");
      } else {
        Serial.println("connection failure");
      }

      if (client.connected()) {
        client.stop();// DISCONNECT FROM THE SERVER
        Serial.println("disconnected");
      }

      delay(5000); // WAIT FIVE MINUTES BEFORE SENDING AGAIN
    }

Serial Out Put

    My IP address: 192.168.1.5.
    connecting....
    connection failure
    connection failure
    connection failure
    connection failure
    connection failure
    connection failure
    connection failure

body:
First your network config is wrong. The gateway is outside the scope of your netmask. This is invalid and may fail the tcpip stack depending on how the Arduino library is implemented.

Second, once you fix this, your laptop needs to be configured as a router to access resources on your network resources unless 192.168.1.2 is the laptop you are connected to.


body:
I had this problem for quite a long time and then I did a little bit of research!
Here it is in an easy explanation-

When you connect your Ethernet Shield to the Laptop the laptop takes the Ethernet Shield as a source of internet and tries to get an IP Address and other network stuff FROM the shield! BUT what we want is the other way round.

We want the Ethernet shield to take the laptop as a source of internet and get itself an IP assigned by the laptop!

What I do is I make a Laptop-Ethernet Shield network and a Laptop-WiFi network.(Simply means that I connect my laptop to WiFi and Ethernet shield)

Then I JOIN the two networks!

This joining of networks is called network bridging and is done easily, I'll tell you how-

If you're using linux then follow [this link here.][1]

else if you're running windows-

1) Connect your Ethernet Shield (With Arduino attached obviously) to the laptop and make sure that your laptop is connected to the WiFi.

2) Go to Network and Sharing Center.

3) Go to Change adapter settings.

4) Select your Wifi adapter and the Ethernet adapter together.

5) Right click on any of the selected adapter and click Bridge connections.

6) Wait till a new network bridge is connected and is done verifying after it's creation.

7) Upload the sketch again on Arduino and you'd be connected.

**NOTE**

DHCP may not always work as it's a feature of your router/WiFi and not your laptop so try assigning a mannual IP by calling Ethernet.begin(mac,ip) instead of using DHCP by caling Ethernet.begin(mc);

AND do change your ip to 192.168.1.XXX I mean change the last tuple so it does not clash with the ip of any other device.(XXX any number less than 255, generally 100-200)

Do let me know the outcome after trying this out! :D

  [1]: https://arduino.stackexchange.com/questions/24064/cannot-directly-connect-arduino-ethernet-to-pc/32770#32770


message:
ATtiny85 AC Phase Control for dimming a light bulb

I'm trying to dim a light bulb via an ATtiny85, which accepts commands sent over I2C. My problem is that the bulb is barely dimming and is flickering quite a bit.

My circuit can be seen here:

![ATtiny85 dimming circuit controlled over I2C][1]

The opto-isolator (and thus the triac) is controlled via pin 2 (AKA PB3, AKA PCINT3) and AC zero cross detection is done on pin 3 (AKA PB4, AKA PCINT4) on the ATtiny85.

The code uses Pin Change Interrupt Enable rather than the single External Interrupt Enable, because the External Interrupt pin is pin 7 (aka PB2), which is used as the SCL for the I2C communication.

The 8MHz internal clock is used and the timer/counter prescaler is 1024, which means that I have an effective input range (see `level` variable in the code) of roughly 0-65. My AC source is USA (60Hz).

<!-- language: c -->

    #include <avr/interrupt.h>
    #include <avr/io.h>
    #include <TinyWireS.h>

    #define PULSE 4       //trigger pulse width (counts)
    #define I2C_SLAVE_ADDR 0x4 // the 7-bit address (remember to change this when adapting this example)

    byte trigger = 3;
    byte detector = 4;
    byte level = 50;
    byte maxLevel = 65;
    byte minLevel = 0;

    void setup() {
     TinyWireS.begin(I2C_SLAVE_ADDR); // join i2c network
     TinyWireS.onRequest(requestEvent); //setup i2c requester
     digitalWrite(detector, HIGH);  //enable pull-up resistor
     pinMode(trigger, OUTPUT);// Set AC Load pin as output
     TCCR1 = 0;     //stop timer
     OCR1A = level;    //initialize the comparator
     TIMSK = _BV(OCIE1A) | _BV(TOIE1); //interrupt on Compare Match A and  enable timer overflow interrupt
     GIMSK = 0b00100000; //Enable pin change interrupt
     PCMSK = 0b00010000; //PB4, physical pin 3 PCINT4
     TCCR1 = B00001011; //Prescale the timer
     sei();  // Turn on interrupts
    }

    ISR(PCINT0_vect) {
        //interrupt looking for zero crossing
        TCNT1 = 0;   //reset timer - count from zero
        OCR1A = level;
        TCCR1 = B00001011;// prescaler on 1024, see table 12-5 of the tiny85 datasheet
    }
    ISR(TIMER1_COMPA_vect) {
        //comparator match
        digitalWrite(trigger,HIGH); //set triac gate to high
        TCNT1 = 255-PULSE;
        //trigger pulse width for a few cycles for triac to latch on. 255 bc the counter can only count up to 255
    }

    ISR(TIMER1_OVF_vect) {
        //timer1 overflow
        digitalWrite(trigger, LOW); //turn off triac gate
        TCCR1 = 0;  //disable timer stop unintended triggers
    }

    void loop() {}

    void requestEvent() {
        if (TinyWireS.available()) {
            level = TinyWireS.receive();
      if (level > maxLevel) {
       level = maxLevel;
       else if (level < minLevel){
       level = minLevel;
      }
     }
     TinyWireS.send(OCR1A);
    }

I have tried a variety of bulbs (incandescent and dimmable LED), with none working any better than another.

Here is a video showing the zero cross detection (yellow) and the ATtiny85 trigger (blue) on an oscilloscope as I send it different dimming levels [Bad phone video][2]

I've thought about the snubber, I just don't have the parts on hand right now. I think it will help but I don't think it will correct whatever my larger issue is.

I'd appreciate all and any help. Thanks.

(Note: I also posted this [here][3]. Apologies if crossposting is frowned upon).

  [1]: https://i.stack.imgur.com/L4zUj.png
  [2]: https://www.youtube.com/watch?v=KnAW94fWrkg
  [3]: https://stackoverflow.com/questions/41384498/attiny85-ac-phase-control-for-dimming-a-light-bulb

body:
So I think there were (was?) two issues.

1) Pin change interrupts on the Attiny85 are triggered on rising and falling edges which I think was causing the flickering.

I changed the code to rising edge only triggering:

    ISR(PCINT0_vect){ //interrupt looking for zero crossing
            if (digitalRead(4) == HIGH){
                    TCNT1 = 0;   //reset timer - count from zero
                    OCR1A = level;
                    TCCR1 = B00001011;// prescaler on 1024, see table 12-5 of the tiny85 datasheet
           }
    }

2) Attiny85 #reset pin. Pulled that guy high with a resistor.

Anyways, here's the oscilloscope and dimming led blub video: [youtube][1]

  [1]: https://youtu.be/0TM0iugDhyM


message:
Fatal Exception Error on ESP8266 + Arduino

When I was trying to blink an LED using ESP8266, I had an issue with it. After successfully uploaded the code (https://diyhacking.com/esp8266-tutorial/), the blue LED stayed on & when I opened the serial monitor using Arduino IDE 1.6.12, I only saw "Fatal Exception" error (showed in the picture). I couldn't see how the code works and the worst thing was I couldn't even try the AT command.

The connections:

Arduino <--->  ESP8266 (ESP-07)

 Tx <---> Tx
 Rx <---> Rx
 GND <---> GPIO0
 GND <---> GND
 3.3v<---> CH_PD
 3.3v<---> VCC
    GPIO2 -> LED

I have been trying to troubleshoot this issue but haven't got the solution yet. I am afraid there is an issue with the firmware or the worst situation, I spoiled my ESP8266.

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

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

body: Looking at your serial monitor window it shows "Geuino Uno". I think you forgot to change the target of the compiler to "Generic ESP8266" like shown in the how-to and you probably uploaded bad code to your module.


body:
If you are getting fatal error exception like this:

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

    Exception (3):
    epc1=0x401003e9 epc2=0x00000000 epc3=0x00000000 excvaddr=0x4000cbd9 depc=0x00000000

In infinite loop in your Serial Monitor of the Arduino IDE then go to this link, download the software, and follow the procedure and erase the flash memory to solve the error.

This does not solve fatal error that occurs due to your program but in case your device goes in such condition that it can't be able to access program memory then it will work and try at least one time to solve the problem.

This is the procedure to hard reset the NodeMCU (https://www.youtube.com/watch?v=MHrm7axsImI&t=146s):

1. Install latest Python version in your PC. (https://www.python.org/downloads)
2. Open cmd prompt as administrator.
3. Go to C:\Program Files or C:\Program Files (x86)->python (your version)->Script. For this type `cd c:\Program Files (x86)\python(your version)\Script` then press enter.
4. Type `pip install esptool`.
5. Download ESPlorer.zip (v 0.2.0-rc6) from https://esp8266.ru/esplorer
6. Extract the downloaded file.
7. Open the executable jar file.
8. Go to NodeMcu firmware site (https://github.com/nodemcu/nodemcu-firmware/releases) and download file (nodemcu_float_0.9.6-dev_20150704.bin) and copy this file into the C:\Program Files (x86)/python(your version)/Script folder.
9. Now in cmd prompt just type:

        esptool.py --port COM(your port no.) --baud 115200 erase_flash
  And press enter.

Note: you can see your NodeMCU board's port number in Device Manager .


message:
clear Arduino as a global variable in Matlab

I'm trying to use `Arduino` in `Matlab`. cause I used Arduino in some function I had to define `Arduino` as a global variable.

    clc,clear,close all;
    global a
    a = arduino();
    .
    some functions
    .
    clear a

at the end of my code I `clear` the variable but as I run the code again this error appear:

    Failed to open serial port (user COM) to communicate with board Uno. ...
     Make sure there is no other MATLAB arduino object for this board.
I guess the global function can't be clear by `clear` command so I tried `clear all` instead `clear` in the last line. It works perfect as I run it again and again but as you know this is `Matlab` tips for `clear all` command

    Using clear all causes MATLAB® to recompile previously cached code,
    and can decrease performance.
I've tried `delete(a)` so the result was:

    Error using arduino/delete
    Cannot access method 'delete' in class 'arduino'.

any help would be appreciated.

body:
In the MatLab Help Center they had nice description of how to clear a variable from memory. Check it here: [https://www.mathworks.com/help/matlab/ref/clearvars.html][1]

In your case should be: `clearvars -global a;`

  [1]: https://www.mathworks.com/help/matlab/ref/clearvars.html


message:
Best way to power an Arduino using the Vin pin

I have a powerbank rated 5v. The battery is actually 3.6v, powering the built-in SMPS to give out 5v. I have stripped one end of the USB cable coming from the power bank, powering a motor driver and the Arduino in parallel. The positive end of the power bank, which is 5v, is going into the Arduino and the motor driver IC's Vcc.

I heard that 5v is not enough to drive the Arduino from the Vin pin. And there is only one power out from the powerbank, so directly connecting the Arduino through the USB would leave nothing to drive the motor driver IC.

A USB splitter would be the obvious solution, but is there anything else I can do? The power source has to be mobile. Can I power the Arduino through the Vin with those 9v batteries commonly used in electronics hobby projects?

body:
That is true, you can't power the Arduino with 5V ***from VIn***.

If you have a constant 5V and you are confident that no major spikes are going to happen, then you might as well connect it to the Arduino's 5V pin.

Other wise, you need at least 7V power the Arduino from the VIn pin. Some say you can put in 6V, but that is just from test. The 7V is more reliable. Thus, you can power the Arduino with a 9V battery is you wish.


body:
You have a powerbank which has a USB output, right? Why not just plug a cable from that into the Arduino USB port? That will connect the 5V directly into the 5V pin of the Arduino (probably via a switching MOSFET). Then you can connect to your motor driver from the 5V pin on the Arduino (and Gnd of course). There may be some limitations on how large a motor you can drive (based on the capacity of the power bank, and to an extent also the thickness of the traces on the Arduino board).

As others have commented, Vin is not intended for that purpose (ie. to supply 5V). You should supply 7V or more to Vin to force the switching MOSFET to disconnect the USB input. In your case you don't have 7V from the powerbank.

---

Here is how the Uno Rev3 power system works:

[![Uno power switching][1]][1]

The input jack (circled in blue) goes through a diode (D1) to the Vin line.

Vin then goes through the 5V voltage regulator (U1) to provide +5V.

However on the top left you see 2 x 10K resistors (RN1A and RN1B) which make a voltage divider from Vin to Gnd. This is compared to the output of the 3.3V voltage regulator by U5A op-amp (circled in red). If higher, then T1 (circled in green) will turn off, disconnecting USBVCC from the +5V line. If lower, then USBVCC is connected to +5V. The nett effect is that if Vin in greater than 6.6V (because of the voltage divider) then the circuit chooses to use Vin, otherwises it uses USBVCC (USB power).

That's why they recommend to use 7V or more into Vin.

Note that you lose around 0.7V through the diode, which is why you need something like 7.3V at the input jack to allow for the loss of the 0.7V before the op-amp compares it to 6.6V.

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


body:
I had this problem last year when I needed to power a prototype using a LiPo battery which supplies only 3,2 up to 3,7V (and up to 4,2V when charging).

My way of solving the problem was to use a voltage boost module. Boost circuits are a kind of circuit where you the inertial properties of passive components to elevate (or attenuate) DC voltage levels.

But you don't need to worry about the math behind use, there is modules like the MT3608 which will supply your circuit up to 28V starting from as little 2V, check the [datasheet][1].

  [1]: https://www.olimex.com/Products/Breadboarding/BB-PWR-3608/resources/MT3608.pdf


message:
DFPlayer library using RT TX pins

I am using the DFRobotDFPlayerMini-1.0.1 library by Angelo. I am trying to use the actual RX TX pins on a Uno R3, but it doesn't connect unless I type in an alternate digital pin number. This is no good for my application as I have a major pin shortage. I have tried typing in `(0,1)` but that is not being accepted.

The reason for using this library is because it provides a LOOP function that works well.

1. How do I use the RX TX pins with this library?
2. Is there another library that has a good LOOP function in it?

Thanks.

Doug

body:
On a classic Arduino pins 0 and 1 are used for serial communication with the host PC, so you cannot use them to talk to a peripheral without conflicting with that.  The library may well be coded to trap and reject such an attempt.

On various alternate (ARM, Atmega32u4, etc) boards these pins may be usable, though the library may not be aware of that.  Also on such boards you would generally want to use an available hardware UART rather than a software simulation of one, which may be fairly ATmega-specific anyway - the end result of which is that library code may well need modification to work on a non-traditional device.


body:
When you say "type in `(0, 1)`" I suppose you mean this:

    #include "Arduino.h"
    #include "SoftwareSerial.h"
    #include "DFRobotDFPlayerMini.h"

    SoftwareSerial mySoftwareSerial(10, 11); // RX, TX
    DFRobotDFPlayerMini myDFPlayer;

[Reference][1]

You cannot use (0, 1) in SoftwareSerial. However, what you could do is pass `Serial` to the init string:

    void setup() {
      // mySoftwareSerial.begin(9600);
      Serial.begin(9600);
      // if (!myDFPlayer.begin(mySoftwareSerial)) {
      if (!myDFPlayer.begin(Serial)) {
        //Use softwareSerial to communicate with mp3.
      }

However that means you cannot use Serial for debugging. You'll have to find another way to log errors and messages.

  [1]: https://github.com/DFRobot/DFRobotDFPlayerMini/blob/master/examples/GetStarted/getStarted.ino


message:
How to send information from a web-site to the arduino?

I currently have an Arduino Mega + an Arduino Ethernet shield, I would like to know if it's possible to send data to the arduino from a web-site hosted on the shield itself. So that when someone press a Button on the web-site it sends a signal to the arduino to trigger an action. Could anyone kindly help me.

body:
Yes of course!

First things first - Yes, it is possible to accomplish what you're thinking.

The idea is to create a server on the Ethernet Shield and open the webpage hosted by it on any device and based on the options selected on the web page we can trigger desired actions on the Arduino.

I've modified the web server code of Arduino built-in examples to match your requirements, just upload it and make necessary changes as required, here it is-

    #include<SPI.h>
    #include<Ethernet.h>

    byte mac[] = {
       0x00, 0xAA, 0xBB, 0xCC, 0xDE, 0x02
     };

     IPAddress ip(192,168,1,199); // Any ip address not on your network.
     EthernetServer server(80);   // Port 80 is default for http.

      int led=2;

      String request;

      void setup(){
        Ethernet.begin(mac,ip);
        pinMode(led,OUTPUT);
        Serial.begin(9600);
       }

      void loop(){

          EthernetClient client = server.available();
      if(client)
             {
           Serial.println("Client is trying to connect......");
           while(client.connected())
           {
      if(client.available())
      {
        char c = client.read();
        request.concat(c);
        if(c=='\n'){
        Serial.print(request);
        if(request.indexOf("ON")>0){
          digitalWrite(led,HIGH);
          Serial.println("ON");
          }

          else if(request.indexOf("OFF")>0){
            digitalWrite(led,LOW);
            Serial.println("OFF");
            }
        client.println("HTTP/1.1 200 OK");
        client.println("Content-Type: text/html");
        //client.println("Refresh: 5");  // refresh the page automatically every 5 sec
        client.println();

        client.println("<!doctype html>");
        client.println("");
        client.println("<title>LED</title>");
        client.print("<!DOCTYPE HTML>
LED ON

LED OFF

" );
        client.println("");
        client.stop();
        request="";

      }
      }
     }

        }

       }

This sketch will turn an LED on or off attached to digital pin 2.

You have to go to the IP address that you provide to the shield (192.168.1.199 in my case). You'll see 2 hyperlinks to switch on or off the led and that would pass a query which the Arduino looks for again and again in the loop and takes action accordingly.

Hope this helps, try this out, and do let me know the result.

**NOTE**

Make sure that you access the Ethernet Shield from a device within your LAN only otherwise you'll have to use port forwarding.


message:
while(1) loop blocks program to enter interrupt

I want to build a program in C that enables / disables a passive matrix display. But my problem occurs before I can even implement one function of this display.

I have a simple switch connected to Port C pin 24, which is configured as INPUT with a pull-up resistor and debouncing input filter. When I toggle the switch the code enters an interrupt and toggles the "display" on or of depending on the state of the switch.

Everything works fine until I introduce a simple `while(1)` loop, which should handle everything I want to do. But every time I write the function called `run`, which only contains one `while(1)` loop and a single dummy operation `__asm__("nop")`, the while loop prevents the code from entering the interrupt.

This is my code:

    void display_init(void) {
     sysclk_init();
     delay_init(sysclk_get_cpu_hz());
     pmc_set_writeprotect(false);
     pmc_enable_periph_clk(ID_PIOC);
     NVIC_EnableIRQ(PIOC_IRQn);
     REG_PIOC_PER = SWITCH;
     REG_PIOC_ODR = SWITCH;
     REG_PIOC_OWDR = SWITCH;
     REG_PIOC_PUER = SWITCH;
     REG_PIOC_IFER = SWITCH;
     REG_PIOC_DIFSR = SWITCH;
     REG_PIOC_LSR = SWITCH;
     REG_PIOC_REHLSR = SWITCH;

     //Clear input change register to avoid immediate interrupt
     REG_PIOC_ISR;
        REG_PIOC_IER = SWITCH;
        run();
    }

    void run() {
        while(1) {
            __asm__("nop"); //Dummy operation for debugging
        }
    }

    void PIOC_Handler(void) {
     REG_PIOC_ISR;
     if(REG_PIOC_PDSR & PIO_PC24) {
      __asm__("nop"); //Breakpoint
     } else {
      __asm__("nop"); //Breakpoint
     }
    }

As far as I know, an interrupt stops everything executed at the current time and starts working on the interrupt code. My question is now: Why is the interrupt not stopping the while loop?

Before I recognized this problem, I had a simple condition in the while loop that checks whether 1 or 0 to equals 1 when I set this state to 0, so the condition was `1 == 0` which should equal `false`. The loop did not stop and continued to run even if the condition for this loop was false... Is it possible that while loops do not like to be used in parallel with interrupts?

__EDIT:__

    void main(void) {
        board_init();
        display_init();
    }

I don't have an Arduino setup() function because I'm using Atmel Studio to ensure working at low Level, to avoid unnecessary code and to keep memory usage as low as possible.

body:
The while loop should have no effect on interrupts. Where does `run()` get called? We'll need to see the code that sets up and calls the code you've shown. But as a sanity check, you could try replacing the entire contents of run() with a `;`, that is make it an empty function. Then add in an empty while loop (contains only a `;`, no \__asm__ code) and try again. Then replace the body of the while loop with \__asm("nop")__ and try again. At which of the above steps does your interrupt fail? That should lead you in the right direction.

Update:

What does your main() function do after display_init() returns? Because that won't ever happen when run() runs forever.

The job of main() is to create the C/C++ run-time environment. That may not have been completed (enabling interrupts, for instance) when display_init() and run() get called, but gets completed shortly after they returns - _if_ run() is allowed to end.

Without seeing your main(), we can't know enough to be more specific, but I'd suggest you move all of your code out of main() and down into the Arduino setup() function because, by the time it gets called, the run-time environment will be complete.

Update 2:

> to avoid unnecessary code

If that is your entire main() function, you've left out the run-time environment setup and it's little wonder that your code behaves strangely. You've asked for help and we've made some suggestions: to show your entire code, not just selected pieces of it; and run your code in a standard way and let us know the result. Then you can optimize your code if you feel it's worth it to you. When you've done that test, and you still have questions, ask again. Until then, you're just asking us to guess. We did that. Once.


message:
MFRC522 not scanning card

So I have an Arduino Uno and an MFRC-522 reader, using a breadboard I've wired it up according to the example sketch which is the mfrc522 DumpInfo sketch.

    /*Typical pin layout used:
     *
     *             MFRC522      Arduino
     *             Reader/PCD   Uno/101
     * Signal      Pin          Pin
     * -------------------------------
     * RST/Reset   RST          9
     * SPI SS      SDA(SS)      10
     * SPI MOSI    MOSI         11 / ICSP-4
     * SPI MISO    MISO         12 / ICSP-1
     * SPI SCK     SCK          13 / ICSP-3
     */

I've checked the wiring hundreds of times. The console shows
    Firmware Version: 0x92 = v2.0
    Scan PICC to see UID, SAK, type, and data blocks...

but getting a card near the chip, will not scan or dump any info no other information appears on the serial monitor.

I've tried with mifare classic 1k  cards
a Nexus 6
and a Samsung Galaxy S7

Edit: Everything

        /*
        * ------------------------------------------------------------------------------------------------------------------
        * Example sketch/program showing how to read data from a PICC to serial.
        * --------------------------------------------------------------------------------------------------------------------
        * This is a MFRC522 library example; for further details and other examples see: https://github.com/miguelbalboa/rfid
        *
        * Example sketch/program showing how to read data from a PICC (that is: a RFID Tag or Card) using a MFRC522 based RFID
        * Reader on the Arduino SPI interface.
        *
        * When the Arduino and the MFRC522 module are connected (see the pin layout below), load this sketch into Arduino IDE
        * then verify/compile and upload it. To see the output: use Tools, Serial Monitor of the IDE (hit Ctrl+Shft+M). When
        * you present a PICC (that is: a RFID Tag or Card) at reading distance of the MFRC522 Reader/PCD, the serial output
        * will show the ID/UID, type and any data blocks it can read. Note: you may see "Timeout in communication" messages
        * when removing the PICC from reading distance too early.
        *
        * If your reader supports it, this sketch/program will read all the PICCs presented (that is: multiple tag reading).
     * So if you stack two or more PICCs on top of each other and present them to the reader, it will first output all
     * details of the first and then the next PICC. Note that this may take some time as all data blocks are dumped, so
     * keep the PICCs at reading distance until complete.
     *
     * @license Released into the public domain.
     *
     * Typical pin layout used:
     * -----------------------------------------------------------------------------------------
     *             MFRC522      Arduino       Arduino   Arduino    Arduino          Arduino
     *             Reader/PCD   Uno/101       Mega      Nano v3    Leonardo/Micro   Pro Micro
     * Signal      Pin          Pin           Pin       Pin        Pin              Pin
     * -----------------------------------------------------------------------------------------
     * RST/Reset   RST          9             5         D9         RESET/ICSP-5     RST
     * SPI SS      SDA(SS)      10            53        D10        10               10
     * SPI MOSI    MOSI         11 / ICSP-4   51        D11        ICSP-4           16
     * SPI MISO    MISO         12 / ICSP-1   50        D12        ICSP-1           14
     * SPI SCK     SCK          13 / ICSP-3   52        D13        ICSP-3           15
     */

    #include <SPI.h>
    #include <MFRC522.h>

    #define RST_PIN         9          // Configurable, see typical pin layout above
    #define SS_PIN          10         // Configurable, see typical pin layout above

    MFRC522 mfrc522(SS_PIN, RST_PIN);  // Create MFRC522 instance

    void setup() {
     Serial.begin(9600);  // Initialize serial communications with the PC
     while (!Serial);  // Do nothing if no serial port is opened (added for Arduinos based on ATMEGA32U4)
     SPI.begin();   // Init SPI bus
     mfrc522.PCD_Init();  // Init MFRC522
     mfrc522.PCD_DumpVersionToSerial(); // Show details of PCD - MFRC522 Card Reader details
     Serial.println(F("Scan PICC to see UID, SAK, type, and data blocks..."));
    }

    void loop() {
     // Look for new cards
     if ( ! mfrc522.PICC_IsNewCardPresent()) {
      return;
     }

     // Select one of the cards
     if ( ! mfrc522.PICC_ReadCardSerial()) {
      return;
     }

     // Dump debug info about the card; PICC_HaltA() is automatically called
     mfrc522.PICC_DumpToSerial(&(mfrc522.uid));
    }

datasheet Nxp website /documents/data_sheet/MFRC522.pdf

[![When arduino starts and nothing changes when card is tapped][1]][1]

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

body:
Maybe you need a function **TO PRINT THE READINGS!!!**

This is the loop and a function to print it:

    void loop() {
      if ( ! rfid.PICC_IsNewCardPresent())
        return;
      if ( ! rfid.PICC_ReadCardSerial())
        return;

        for (byte i = 0; i < 4; i++) {
          nuidPICC[i] = rfid.uid.uidByte[i];
        }

        Serial.println(F("The NUID tag is:"));
        Serial.print(F("In hex: "));
        printHex(rfid.uid.uidByte, rfid.uid.size);

      rfid.PICC_HaltA();
      rfid.PCD_StopCrypto1();
    }

    void printHex(byte *buffer, byte bufferSize) {
      for (byte i = 0; i < bufferSize; i++) {
        Serial.print(buffer[i] < 0x10 ? " 0" : " ");
        Serial.print(buffer[i], HEX);
      }

    }


body:
your breadboard can be buggy. In addition, are you connected VCC to 3V or 5V?
As I remember, you need to connect it to 3V.


body:
    #include <SPI.h>
    #include <MFRC522.h>

    void setup() {
      Serial.begin(9600);
      SPI.begin();
      RFID.PCD_Init();      // MFRC522
    }
    #define SS_PIN 10
    #define RST_PIN 9

    MFRC522 RFID(SS_PIN, RST_PIN);

    void loop() {
      if (!RFID.PICC_IsNewCardPresent() || !RFID.PICC_ReadCardSerial())
        return;

      String buffer;
      for (byte byte = 0 ; byte < RFID.uid.size ; byte++)
        buffer += String(RFID.uid.uidByte[byte] < 0x10 ? " 0" : " ") + String(RFID.uid.uidByte[byte], HEX);
      Serial.println("NUID: " + buffer);

      RFID.PICC_HaltA();
      RFID.PCD_StopCrypto1();
    }


body: I had a similar problem. I used I2C to check if the board can see the reader. If I2C Bus doesn't detect your reader, then one of your soldering must be faulty... check with a meter and carefully re-solder the erring pin.


body: I have several of this board with this condition. As I checked ,they all return the same thing as you send in SPI . I think all of them have hardware problem. Common thing for all of them is In past I supplied them with switching supply and I think this is why they got broken(this chip is very sensitive with supply voltage and **YOU MUST NOT CONNECT THEM TO MORE THAN 3.3V EVEN FOR VERY SHORT TIME**) . I highly recommend use of Linear regulator for them


body: Same problem as above. Three card readers. Two worked. One didn't. All three  readers had two pins bridged on the reader chip. The bridged pins were close to the pin 1 corner. I left the bridge alone as all three readers had the same bridge and one of the pins did not have a trace to it. The faulty card reader also had two pins bridged with solder in a different location. Both pins had separate traces. I removed the solder bridge and the faulty card reader was no longer faulty.


body: I figured out that one get these kind of problems (reader get´s firmware version but can not read tags) are related to power consumption. I tried to power the reader with Heltec Lora 32 Dev board and it schowed exactly this behaviour. Now, connected to another 3,3V source everything works as it should :)


message:
IR communication not consistent

I have an IR Receiver hooked up to my arduino and a remote with an IR Trasmitter in it. I have some code to decode the values that are received but the values change even when I am pressing the same button!

Here is the code I am using:

    #include <IRremote.h>

    int IRpin = 8;
    IRrecv irrecv(IRpin);
    decode_results results;

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

    void loop()
    {
      if (irrecv.decode(&results))
        {
          Serial.println(results.value, HEX);
          irrecv.resume();
        }
    }

and here is me pressing the same button 10 times and the output for it:

> 9C01C8E1
FFFFFFFF
82A6A14C
FFFFFFFF
FFFFFFFF
70D67871
FFFFFFFF
BCB5C227
FFFFFFFF
B358F5ED
FFFFFFFF
FFFFFFFF
FFFFFFFF
FFFFFFFF
FFFFFFFF
FFFFFFFF
58EE9A27
FFFFFFFF
90750A0D
FFFFFFFF
FFFFFFFF
FFFFFFFF

body:
Get TSOP1738 or any good IR receiver to decode. Above code is appropriate and does not need any changes. you will surely get some fluctuations and different decoded hex codes but it would provide only 2 different values for single button so that while controlling any device using ir , you can use 'or' operator in conditional statement and hence you will get desired results.
Getting absolute results from a cheap IR receiver is a myth.But it will work well for your project at lower level.I had worked with that and my device is working in my room with no difficulty.


body: I eventually figured it out. The IR Receiver that I had was made by a company called Sharp. Every company has different methods of encoding and decoding IR signals, and it just so happens that decoding Sharp messages is not yet supported in the IRremote library, the library I was using for IR communication. I found a different IR receiver from an old electronic device that I had, I tried that and it worked perfectly.


message:
Arduino pins LCD and motor controller

I am using an L298N motor control. I want to use my 2*16 LCD. Can I use the code like this?

    // include the library code:
    #include <LiquidCrystal.h>

    // initialize the library with the numbers of the interface pins
    LiquidCrystal lcd(RS, E, D4, D5, D6, D7);
    LiquidCrystal lcd(12, 9, 4, 5, 6, 7);

    // Motor Control
    #define enableA  3
    #define enableB  11
    #define in1 4
    #define in2 5
    #define in3 6
    #define in4 7

body: You cannot use same pins for LCD and motor. Data transfer through pins 4,5,6,7(being data pins for LCD) will effect your motor state. You should use different pins and if you does not have sufficient digital pins so you can use analog pins as digital pins (0-LOW,255-HIGH).


body:
You can use the same pins for both the motor and the LCD.

A condition is that the **enable** pin decides when the LCD or the motor is accepting inputs from the data pins. This is a normal bus configuration, several devices share data pins and have a **enable** pin to tell the device when they owns the data bus.


body:
Using that pin configuration you'll have several problems despite you'll use enable pin.

I would use a I2C module for 16x2 lcd like this https://www.amazon.com/SainSmart-Serial-Module-Display-Arduino/dp/B00813HBEQ

Control 16x2 lcd with I2C.


message:
Removing Robot IR Arduino Library on Macbook

I'm trying to use my IR receiver on my Arduino Uno Board.  First I need to remove my IR Robot library because it interferes with the IRremote library. On my Mac, I have gone into the Arduino/library folder, but the name of the library I have to remove is not there.

I cannot figure out how to remove this. Please help!!

body:
The folder name is **RobotIRremote**.

It's actually not necessary to remove that folder, though that will solve your problem. A better solution is to change the folder name of the IRremote remote library so that the file named IRremote.h found in that library will be given include priority over the one found in the RobotIRremote library. This is better because you would need to remove the RobotIRremote library every time you update to a new version of the Arduino IDE. The Arduino IDE gives include priority to files that match the name of the library folder but unfortunately if you install the IRremote library manually it will tend to have the folder name **Arduino-IRremote-master** which causes the wrong file to have priority. So you just need to find that folder and rename it **IRremote**.

If you don't know where it is the library folder can be found by:

1. File > Examples > IRremote > AiwaRCT501SendDemo
1. Sketch > Show Sketch
    Folder


message:
Controlling DC motor using the Servo pins

I have a L293D motor shield for arduino uno. It has capability of controlling 2 servo motors and 4 DC motors. But I want to control 5 DC motors for my project. So my question is can I use the 3 pins that are there in motor shield ( to control servo motors) for controlling a DC motor? Or any other solution if any without using any other hardware?

body:
No. A servo motor has its own built-in driver and you just send a low-level PWM signal to control it. That cannot directly drive a DC motor.

If you want more DC motors you will need more DC motor driving hardware.  For simple speed control in one direction that could be as simple as a NPN transistor (or N-channel FET), a base resistor, and a flyback diode (just like driving a relay). For direction control you will need a H-bridge like the L293D (which incidentally is a very poor choice of driver by today's standards - very inefficient and lossy. I wish people wouldn't persist in selling it.)


message:
Adapt a differently pin-interspaced chip to be used with an Arduino

Happy new year to everyone!

This is how my chip looks like:

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

Those numbers are millimeters. Both the pin spacing and pin width are different from what Arduino uses.

Is there any quick (or less quick) and reliable way to connect this chip to an Arduino Uno ?

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

body:
Adapters from 2mm to 2.54mm (0.1") spacing exist.

Here is
[an example][1] and [another example][2].

Alternatively you could make up a little PCB or, as suggested by @jfpoilpret, solder wires on.

A further option is to cut a piece of stripboard, score down the middle to break the tracks, stick your chip on, and run wires from the 2mm-spaced pins to the 2.54mm-spaced pins.  Off-cut resistor legs work fairly well, in my experience.  Here's one I made (fairly clumsily) earlier.  Your soldering skill may be better than mine. [![Here's one I made earlier][3]][3].

  [1]: https://www.adafruit.com/product/1919
  [2]: http://www.proto-advantage.com/store/product_info.php?products_id=3800083
  [3]: https://i.stack.imgur.com/e1fH7.jpg


body:
The simplest option is to buy a pre-made ribbon cable with 2mm pitch (7x2) IDC connector on it.

Solder the free end (or cut the second connector off and strip it if you have a two-ended cable) and solder it to strip-board on which you have already soldered a 14-pin header for breadboard use.

* [An example of the cable I mean.](http://uk.farnell.com/samtec/tcsd-07-s-06-00-01/cable-assembly-idc-14way-6-grey/dp/2493377)


message:
Arduino - Windows can't find the drivers

I bought an Arduino UNO R3 Yesterday. It's a Chinese clone. But it has the Atmega328p and MEGA16U2 both.
I've installed the IDE fully. But it can't find the ports. The Tools > Ports option is greyd out, Cannot find The options Named "Ports (COM & LPT)" or "Other Devices" in device manager. Can't upload any sketch to board.
I tried this on my both Win7 SP1(32 BIT) & Win10, which are installed in the same pc but in different partitions. I've roamed accross stackexchange but no successful result.

body:
You may not have installed the drivers when installing the IDE. The only way I know to reinstall the drivers is to reinstall the IDE and make sure when you get to this screen you tick every box:

[![Install Arduino][1]][1]

Otherwise you may not have selected your board correctly. To select your board in the IDE, go to Tools > Board > Arduino Uno/Genuino Uno

Your port select may then appear, it should be COM1 or something similar. If you have multiple, just try them all by selecting one and then upload a sketch to it. The Arduino Uno should flash some lights if it worked correctly.

[![Board][2]][2]

  [1]: https://i.stack.imgur.com/XZnOo.png
  [2]: https://i.stack.imgur.com/THbiI.png


message:
Arduino with 2 echo sensors

For a project I'm doing I need the Arduino to be connected to two echo sensors (I have the HC-SR04). Currently I have 4 sensors that I can use, but I will need only 2 or 3.

I have almost no knowledge of coding and the Arduino, but I figured out how to connect it to one echo sensor, and that is working, which is great.

But now I need it to connect to two. I found example code with 3 echo sensors, but whenever I connect them my Arduino shuts down. I guess it is because it takes up too much power, my teacher said something like that. All lights turn off all of the sudden, and it doesn't reset. Only when I remove some the wires for the power, it works again.

So 3 isn't going to work. I figured I'd stick to two. Now the problem: Whenever I try to edit the code to two echo sensors (I basically just removed the `trigPin3` and `echoPin3` in the first part of the code, and the `SonarSensor(trigPin3, echoPin3))`, it doesn't work anymore. The monitor doesn't show any values anymore, while it did with the first code. It just shows zeroes now.

So my question is, how can I edit the example code so that it works with 2 echo sensors?

This is the code I found for the 3 echo sensors:

    #define trigPin1 3
    #define echoPin1 2
    #define trigPin2 4
    #define echoPin2 5
    #define trigPin3 7
    #define echoPin3 8

    long duration, distance, RightSensor,BackSensor,FrontSensor,LeftSensor;

    void setup() {
      Serial.begin (9600);
      pinMode(trigPin1, OUTPUT);
      pinMode(echoPin1, INPUT);
      pinMode(trigPin2, OUTPUT);
      pinMode(echoPin2, INPUT);
      pinMode(trigPin3, OUTPUT);
      pinMode(echoPin3, INPUT);
    }

    void loop() {
      SonarSensor(trigPin1, echoPin1);
      RightSensor = distance;
      SonarSensor(trigPin2, echoPin2);
      LeftSensor = distance;
      SonarSensor(trigPin3, echoPin3);
      FrontSensor = distance;
      Serial.print(LeftSensor);
      Serial.print(” – “);
      Serial.print(FrontSensor);
      Serial.print(” – “);
      Serial.println(RightSensor);
    }

    void SonarSensor(int trigPin,int echoPin) {
      digitalWrite(trigPin, LOW);
      delayMicroseconds(2);
      digitalWrite(trigPin, HIGH);
      delayMicroseconds(10);
      digitalWrite(trigPin, LOW);
      duration = pulseIn(echoPin, HIGH);
      distance = (duration/2) / 29.1;
    }

And this is the one that IS working, but with 1 echo sensor:

    #define echoPin 7 // Echo Pin
    #define trigPin 8 // Trigger Pin
    #define LEDPin 13 // Onboard LED

    int maximumRange = 200;
    int minimumRange = 0;
    long duration, distance;

    void setup() {
      Serial.begin (9600);
      pinMode(trigPin, OUTPUT);
      pinMode(echoPin, INPUT);
      pinMode(LEDPin, OUTPUT); // Use LED indicator (if required)
    }

    void loop() {
      digitalWrite(trigPin, LOW);
      delayMicroseconds(2);
      digitalWrite(trigPin, HIGH);
      delayMicroseconds(10);
      digitalWrite(trigPin, LOW);
      duration = pulseIn(echoPin, HIGH);
      if (distance >= maximumRange || distance <= minimumRange) {
        /* Send a negative number to computer and Turn LED ON
        to indicate "out of range" */
        Serial.println("-1");
        digitalWrite(LEDPin, HIGH);
      } else {
        /* Send the distance to the computer using Serial protocol, and
        turn LED OFF to indicate successful reading. */
        Serial.println(distance);
        digitalWrite(LEDPin, LOW);
      }
      //Delay 50ms before next reading.
      delay(50);
    }

I hope someone can help me!

Many thanks, Leah.

body:
 - In the 1 sensor program all the delays added together account for
   62ms between samples.
 - In the 3 sensor program the sample code contains delays which likely
   exceed 12ms (delays plus code execution).  So each sensor will not be
   sampled faster than once every 36ms.
 - After you removed 1 sensor from the 3 sensor program, you increased
   the sampling rate to about every 23ms.
 - It is likely a minimum amount of time is necessary between samples in
   order for the HC-SR04 to recover.


body:
Try this:

    void loop() {

    RightSensor = SonarSensor(trigPin1, echoPin1);

    LeftSensor = SonarSensor(trigPin2, echoPin2);

    FrontSensor = SonarSensor(trigPin3, echoPin3);

    Serial.print(LeftSensor);

    Serial.print(” – “);

    Serial.print(FrontSensor);

    Serial.print(” – “);

    Serial.println(RightSensor);

    }

    long SonarSensor(int trigPin,int echoPin)
    {

    digitalWrite(trigPin, LOW);

    delayMicroseconds(2);

    digitalWrite(trigPin, HIGH);

    delayMicroseconds(10);

    digitalWrite(trigPin, LOW);

    duration = pulseIn(echoPin, HIGH);

    distance = (duration/2) / 29.1;

    return distance;

    }


body:
Try this one. I hope this will work for you.

    int trigPin1 = 2;                        //Sensor Trip pin connected to Arduino pin 2
    int echoPin1 = 3;                        //Sensor Echo pin connected to Arduino pin 3

    int trigPin2 = 4;                        //Sensor Trip pin connected to Arduino pin 4
    int echoPin2 = 5;                        //Sensor Echo pin connected to Arduino pin 5

    float pingTime1;                         //time for ping to travel from sensor to target and return
    float targetDistance1;                   //Distance to Target in centi meters

    float pingTime2;                         //time for ping to travel from sensor to target and return
    float targetDistance2;                   //Distance to Target in centi meters

    float speedOfSound = 760.5583392985;     //Speed of sound in miles per hour.

    void setup()
    {
      pinMode(trigPin1, OUTPUT);
      pinMode(echoPin1, INPUT);

      pinMode(trigPin2, OUTPUT);
      pinMode(echoPin2, INPUT);
    }

    void loop()
    {
      ultrasonicFun1();
      ultrasonicFun2();
    }

    void ultrasonicFun1()
    {
      digitalWrite(trigPin1, LOW);         //Set trigger pin low
      delayMicroseconds(2000);             //Let signal settle
      digitalWrite(trigPin1, HIGH);        //Set trigPin high
      delayMicroseconds(15);               //Delay in high state
      digitalWrite(trigPin1, LOW);         //ping has now been sent
      delayMicroseconds(10);               //Delay in high state

      pingTime1 = pulseIn(echoPin1, HIGH);             //pingTime is presented in microceconds
      pingTime1 = pingTime1 / 1000000;                 //convert pingTime to seconds by dividing by 1000000 (microseconds in a second)
      pingTime1 = pingTime1 / 3600;                    //convert pingtime to hourse by dividing by 3600 (seconds in an hour)
      targetDistance1 = speedOfSound * pingTime1;      //This will be in miles, since speed of sound was miles per hour
      targetDistance1 = targetDistance1 / 2;           //Remember ping travels to target and back from target, so you must divide by 2 for actual target distance.
      targetDistance1 = targetDistance1 * 160934.4;    //Convert miles to inches by multipling by 160934.4 (centi meters per mile)
    }

    void ultrasonicFun2()
    {
      digitalWrite(trigPin2, LOW);          //Set trigger pin low
      delayMicroseconds(2000);              //Let signal settle
      digitalWrite(trigPin2, HIGH);         //Set trigPin high
      delayMicroseconds(15);                //Delay in high state
      digitalWrite(trigPin2, LOW);          //ping has now been sent
      delayMicroseconds(10);                //Delay in high state

      pingTime2 = pulseIn(echoPin2, HIGH);             //pingTime is presented in microceconds
      pingTime2 = pingTime2 / 1000000;                 //convert pingTime to seconds by dividing by 1000000 (microseconds in a second)
      pingTime2 = pingTime2 / 3600;                    //convert pingtime to hourse by dividing by 3600 (seconds in an hour)
      targetDistance2 = speedOfSound * pingTime2;      //This will be in miles, since speed of sound was miles per hour
      targetDistance2 = targetDistance2 / 2;           //Remember ping travels to target and back from target, so you must divide by 2 for actual target distance.
      targetDistance2 = targetDistance2 * 160934.4;    //Convert miles to inches by multipling by 160934.4 (centi meters per mile)
    }


message:
Can't read two bytes through Serial.read - Arduino

I'm sending via Bluetooth with an Android App two bytes like this:

    private void _sendCommand(byte command, byte arg)
    {
        if (CONNECTED)
        {
            try
            {
                os.write(new byte[]{command, arg});
                os.flush();

            } catch (IOException e) {
                Log.e(TAG, "Error sending command: " + e.getMessage());

            }
        }
    }

And this is the code I'm using to receive them with Arduino:

    byte _instruction;
    byte _arg;

    void loop()
    {
      while(Serial.available() < 2)
      {
        digitalWrite(LED_BUILTIN, HIGH);
      }

      digitalWrite(LED_BUILTIN, LOW);

      _instruction = Serial.read();
      _arg = Serial.read();
      Serial.flush();

      switch (_instruction)
      {

         ...

      }
    }

I don't have any problems sending just one byte (modifying the code to receive just one), but I can't do the same with two bytes. It's always stuck in the while. Any idea of what I'm doing wrong?

----------

EDIT: As ST2000 pointed out, there was a problem of syncronization, so this is the code working properly:

    void loop()
    {
      // Wait until instruction byte has been received.
      while (!Serial.available());
      // Instruction should be read. MSB is set to 1
      _instruction = (short) Serial.read();

      if (_instruction & 0x80)
      {
        // Wait until arg byte has been received.
        while (!Serial.available());
        // Read the argument.
        _arg = (short) Serial.read();

        switch (_instruction)
        {
          ...
        }
      }

      Serial.flush();
    }

Thanks,

body:
There may be a underlying problem with synchronizing the transmitter and receiver.  They both have to agree / know which is a command byte and which is a data byte.

In order to do this, some protocols sacrifice a bit. For example you could set the most significant bit for commands and not set the most significant bit for data. However, that does mean you can only send data in the range of 0 to 127. And it does restrict you to only 128 commands. If you need more, and want to stick to this "most significant bit" approach, you could break your data into chunks and only send 7 bits at a time. The possibilities are many. Use this one or make one up that fits your needs better.

In order to implement this approach, you will need to read and process each byte as it arrives.  You can not wait until you accumulate the expected number of bytes as this assume you are always in sync with the transmitter. Which may not be the case.


message:
ESP8266MOD does not respond to my Uno (Custom board) AT+RST command

This is my very first project with a Uno board and ESP module. I have some experience with 8051 uP. I'd like some guidance in addressing my issue.

Objective:

To connect ESP8266MOD to my wifi network and send a TCP message to my HOME_SERVER whenever required.

Hardware Module:
UNO ([Induino R5 Arduino R3 USB Clone Board][1]) --> level shifter  --> ESP8266MOD

As a first step, I am trying to send AT+RST command from the Uno to the connected ESP. But there is no response from the ESP. However, I am able to notice a LED blink on the ESP, whenever there is TXD operation in my Uno.

Hardware Connection:

 UNO - Uses USB Power supply from laptop
 ESP8266MOD- Uses 3 1.5V AA Batteries

                     ||
        UNO PINS    TXD   RXD   5V GND
      ||  ||  ||
  LEVELSHIFTER     >>RXI   <<TXO HV,GND
       ||  ||
      RXO<<  TXI>>  LV,GND
      ||  ||  ||
  ESP8266MOD  RXD  TXD  3.3V,GND

 ESP8266MOD Settings:
  CH_PD ->> 3.3V
  GPIO2 ->> 3.3V
  GPIO0 ->> GND
  GPIO15->> GND

Uno Code:

 #include <SoftwareSerial.h>

 const byte rxPin = 2; // Wire this to Tx Pin of ESP8266
 const byte txPin = 3; // Wire this to Rx Pin of ESP8266

 // We'll use a software serial interface to connect to ESP8266
 SoftwareSerial ESP8266 (rxPin, txPin);

 void setup() {
   Serial.begin(9600);
   ESP8266.begin(9600); // Change this to the baudrate used by ESP8266
   delay(3000); // Let the module self-initialize
 }

    void loop() {
      Serial.println("Sending an AT command...");
      delay(3000);
      ESP8266.println("AT+RST");
      delay(30);
      String response = "";
      while(ESP8266.available()) {
        char c = ESP8266.read();
        response+=c;
      }
      if(response != "") {
        Serial.println(response);
      } else {
        Serial.println("Empty\r\n");
      }
    }

Output Video: [Output video view][2]

 [![logic level converter][3]][3]  --> [![ESP8266MOD][4]][4]

  [1]: http://www.simplelabs.co.in/content/induino-r5-arduino-r3-usb-clone-board
  [2]: https://drive.google.com/open?id=0B60pejPe6yiSelVtQmV0dGI5M00
  [3]: https://i.stack.imgur.com/qACko.jpg
  [4]: https://i.stack.imgur.com/F9Wzg.jpg

body:
If it is a new ESP module, your problem is quite likely a baud rate mismatch, since you are seeing an LED response but getting no reply.

The last batch of ESP-01s I received defaulted to 115200 baud, but that is too fast for SoftwareSerial (SS). You'll need to change it to 9600. [My answer to a related question][1] describes one way to change it.

You could also change it with SS. You'd have to start off SS at 115200 baud, which will usually transmit OK; just ignore the apparent garbage that comes back. Then change SS's baud rate to 9600 to match, and you should have solid communication.

These are the three commands you need to send the ESP to accomplish the change:

    AT                             # ESP should respond "OK"
    AT+RST                         # Resets the ESP
    AT+UART_DEF=9600,8,1,0,0       # Sets ESP UART: 9600,N,8,1,no flow ctl

Note: Your module might have been preset to some other rate than 115200, in which case you'll have to try various rates until you can get an intelligible reply. Once you do, set the default rate to 9600.

  [1]: https://arduino.stackexchange.com/questions/18647/linking-arduino-nano-with-esp8266-wifi-module/24961#24961


message:
LCD5110 - How to make Direct Draw via 2D-array of boolean?

How to draw 2D-array directly on LCD 5110 (PCD8544)?

I have tried libraries like AdaFruit and several others.

But I need draw there via pixel 2D-array, something like this:

    bool picture[48][84] = {
     {0,1,0,0, ... to 84 elements},
     {1,0,1,0,0, ...},
     ... to 48 elements
    };

I haven't used charset table or geometry figures drawing library functions. Simplest and smallest drawing by pixel - 0 - not draw, 1 - draw pixel.

The "picture bitmap" will generate on the mini-pc board via Python and send to Arduino, which will draw it as "video card".

What is the simplest way to draw pixel in any site of the display without using powerful libraries?

Something about this:

    // Send boolean bitmap 48x84 to LCD 5110
    // Rows
    for (int i=0; i<48; i++) {
     // Columns
     for (int j=0; j<84; j++) {
      // PIN 5 is Din on the 5110 module
      digitalWrite(5, picture[i][j]);
     }
    }

body:
For a start the Arduino Uno is incapable of storing that array in RAM. You're using twice as much memory for that array as the Arduino has in total. You will have to place it in PROGMEM and use the right functions to access it.

Secondly, you have to use a special library to control the display properly. That library will contain functions to draw on the screen. So your function to draw it would look something (though not exactly) like this:

    const bool picture[] PROGMEM = {
        1, 1, 1, 0, 0, 0, 1, 0, 0, 0, 1, 1, 0, 0, 0, 0, 0,
        ... etc ... ... 4032 numbers in total ...
    };

    for (int i=0; i<48; i++) {
        for (int j=0; j<84; j++) {
            lcd.setPixel(j, i, pgm_read_byte_near(picture + (i * 84 + j));
        }
    }

Refer to the manual for the library for the actual function to run and how to configure and set up the LCD screen.


body:
    // PIN 5 is Din on the 5110 module
    digitalWrite(5, picture[i][j]);

with that kind of code, I would suggest that you spend a little bit more time on understanding the libraries you are trying to use, or the datasheet if you aren't using any libraries and ask more directed questions.

embedded engineering is one that ties software with hardware and it is not possible for you to understand software without understanding, very well, the hardware first.