message:
How can I tell what programmer to use?

I have a bunch of different dev boards for different projects. What I have been getting very confused about is what board needs what programmer from the Tools > Programmer menu.

I wish the selection had the option to be partially automated for the board selection. But it's evidently not. Part of my problem is that if you choose the wrong programmer, some boards seem to work. Others read but won't write, or will write to some spaces, but not others. Or, you might get other cryptic errors that sound a lot like failed hardware. Have a look at this message for an example:

[![Programmer Error?][1]][1]

OK, so let's say I have some random dev board. How can I know what programmer I should use? Assume the manufacturer's documentation mentions nothing about it...

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

body:
The clock and the timing signals and the voltage levels do not always match. And perhaps something is connected to the pins already which makes it harder for the programmer.

I use mostly the cheap USBasp version 2 (the text "version 2" is often written on the PCB). They are based on the [USBasp from Thomas Fischl][1].

Sometimes there is a timing conflict. Sometimes that can be corrected with options for avrdude or with the avrdude.conf file, sometimes I have to grab an older or newer USBasp programmer.

What do you mean by choosing the wrong programmer? If there is a programmer connected to the computer, then select that type of programmer. Do you have a programmer?

  [1]: http://www.fischl.de/usbasp/


sender: user

sender: assistant

body:
Generally the **Tools > Programmer** selection is only used for **Tools > Burn Bootloader** and **Sketch > Upload Using Programmer** and is not used for standard uploads. So for standard uploads you can set it to anything you like because it will have no effect.

The most notable exception is the Adafruit Trinket, which does [require](https://learn.adafruit.com/introducing-trinket/setting-up-with-arduino-ide) you to select **Tools > Programmer > USBTinyISP** even though you are uploading through the USB socket on the Trinket board without a separate ISP programmer.

You will also find some 3rd party hardware packages that are not written for boards with an Arduino style serial bootloader and so treat a standard upload as an "Upload Using Programmer" for the sake of convenience. Examples are [MicroCore](https://github.com/MCUdude/MicroCore) and the ["Barebones ATmega Chips (no bootloader)"](https://github.com/carlosefr/atmega) hardware package. In this case the correct Programmer menu selection is dependent on which model of ISP programmer you are using.

So regarding the question "How can I tell what programmer to use?": If you're doing a standard upload, start by assuming it doesn't matter. If that doesn't work, read the documentation!

If you're doing a **Tools > Burn Bootloader** or **Sketch > Upload Using Programmer** (or holding shift while pressing the "Upload" button) then you should select the model of the ISP programmer you're using.


message:
How can I get additional Slave Select pins?

I have a project where I want to connect a number of SPI devices, and I'm running out of Slave Select pins (SPI) on the Arduino. So I thought that I could use something like an MCP23S17 to get additional pins and use those as SS pins, but most libraries require to pass the pins when initialising, and it seems that I can't pass the MCP's pins as a function/class argument (or can I?). For example:

    U8G2_SSD1306_128X64_NONAME_F_4W_HW_SPI u8g2(U8G2_R0, /*cs*/ 12, /*dc*/ 4, /*rst*/ 6);

So my question is: How can I get more SS pins? Thank you

body:
A maybe dirty solution is to change all the libraries. Everywhere the SS pin is used, instead call a function and set it yourself (by using the MCP23S17).

To make this a bit better, define a class that contains this functionality to abstract it from the changed library classes.

Example:

As initialization of the library a function or class constructor will be used, e.g.

    MCP23S17(void);

This you will use like:

    MCP23S17 my_component = MCP23S17();

You need to change this to:

    MCP23S17(int ss_pin);

And change the related code, store it in a class variable and use it everywhere in the library instead of the fixed SS pin number.

Than you can constructor your own instance by:

    MCP23S17 my_component = MCP23S17(4);

Where 4 is the SS pin number


body:
My solution would be to keep it simple. Use real pins for every SPI SS. Buy an other Arduino board with more pins if you need more pins.

What else is connected to your Arduino board ? Perhaps it is easier to reduce those pins. Almost all analog pins can be digital pins as well. You could use external ADC modules. Perhaps replacing 1-Wire or DHT11 or DTH22 with I2C sensors. Using a I2C display. There are many options to use buttons and leds with a few pins. And so on.


body:
I would suggest adding a layer of abstraction in your whole design.

Use the ESP8266 as the main system controller, then farm out sensor communications to one or more other "active" expansion devices.

Rather than just using an expander for the SS pins you are using the "expander" for all the communication.

By "expander" I basically mean some other microcontroller (maybe an ATMega328P for example) which receives an instruction to sample a sensor then goes off and gathers the data that is wanted and sends it back to the master ESP8266 controller.

How you arrange that communication is up to you, but maybe I2C would be a good way to go.  You could even make the sensor data gathering completely autonomous so that the ESP8266 just then requests the latest data from the slave(s).

It means:

* You don't have to change any libraries
* You get distributed processing, sharing the work out
* The ability to communicate with an almost infinite number of sensors


message:
Serial write skips on Arduino Due

I bought Feetech SCS09 smart servos (also known as SCS009 or SCS0009).

**Please note that these servos are not regular PWM servos, they are devices that communicate with board using Serial connection via device named TTLinker that converts UART to half duplex protocol. So the question is about the problem with serial communication only.**

The seller provided me Arduino library to work with the servos.

The simplest testing sketch looks as this:

    #include <SCServo.h>

    SCServo SERVO;

    void setup() {
      Serial2.begin(1000000);
      SERVO.pSerial = &Serial2;
      delay(500);
      SERVO.EnableTorque(1, 1);
      SERVO.EnableTorque(2, 1);
    }

    void loop() {
      SERVO.WritePos(1, 1023, 4000); // Servo ID:1, rotate to the position:0x2FF
      SERVO.WritePos(2, 1023, 1000); // Servo ID:2, rotate to the position:0x2FF
      delay(4000);
      SERVO.WritePos(1, 20, 3000); // Servo ID:1, rotate to the position:0x000
      SERVO.WritePos(2, 20, 1000); // Servo ID:1, rotate to the position:0x000
      delay(3000);
    }

**The code works perfectly on Arduino Mega** and allows to independently control servos.

But with Due I have problems: not all commands can be performed. So if compile the code for Due only servo ID1 works, but ID2 do not work at all.

When I add delays between commands the servos started to work

        SERVO.WritePos(1, 1023, 4000); // Servo ID:1, rotate to the position:0x2FF
        delay(10);
        SERVO.WritePos(2, 1023, 1000); // Servo ID:2, rotate to the position:0x2FF
        delay(4000);
        SERVO.WritePos(1, 20, 3000); // Servo ID:1, rotate to the position:0x000
        delay(10);
        SERVO.WritePos(2, 20, 1000); // Servo ID:1, rotate to the position:0x000
        delay(3000);

When I set delays between 1 and 9 the both servos can work but sometimes skip commands. Servos can skip 1-4 actions and then start to work again. The less delay I set the more random skips I get.

So I think here is some specialities regarding Serial connection on Arduino Due. What It can be? Why delays help to make it working?

By the way I read that Arduino Due can have problems with 1000000 baud rate and I tried different, even significntly less baud rates (for example 38400) with Arduino Due: the result is the same.

I need to explain how WritePos function works in the library

    int SCSProtocol::WritePos(u8 ID, u16 Position, u16 Time, u16 Speed)
    {
     return writePos(ID, Position, Time, Speed, INST_WRITE);
    }

    int SCSProtocol::writePos(u8 ID, u16 Position, u16 Time, u16 Speed, u8 Fun)
    {
     flushSCS();
     u8 buf[6];
     Host2SCS(buf+0, buf+1, Position);
     Host2SCS(buf+2, buf+3, Time);
     Host2SCS(buf+4, buf+5, Speed);
     writeBuf(ID, P_GOAL_POSITION_L, buf, 6, Fun);
     return Ack(ID);
    }

    void SCSProtocol::Host2SCS(u8 *DataL, u8* DataH, int Data)
    {
     if(End){
      *DataL = (Data>>8);
      *DataH = (Data&0xff);
     }else{
      *DataH = (Data>>8);
      *DataL = (Data&0xff);
     }
    }

    int SCSProtocol::Ack(u8 ID)
    {
     if(ID != 0xfe && Level){
      u8 buf[6];
      u8 Size = readSCS(buf, 6);
      if(Size!=6){
       return 0;
      }
     }
     return 1;
    }

    void SCSProtocol::writeBuf(u8 ID, u8 MemAddr, u8 *nDat, u8 nLen, u8 Fun)
    {
     u8 msgLen = 2;
     u8 bBuf[6];
     u8 CheckSum = 0;
     bBuf[0] = 0xff;
     bBuf[1] = 0xff;
     bBuf[2] = ID;
     bBuf[4] = Fun;
     if(nDat){
      msgLen += nLen + 1;
      bBuf[3] = msgLen;
      bBuf[5] = MemAddr;
      writeSCS(bBuf, 6);

     }else{
      bBuf[3] = msgLen;
      writeSCS(bBuf, 5);
     }
     CheckSum = ID + msgLen + Fun + MemAddr;
     u8 i = 0;
     if(nDat){
      for(i=0; i<nLen; i++){
       CheckSum += nDat[i];
      }
     }
     writeSCS(nDat, nLen);
     writeSCS(~CheckSum);
    }

    int SCServo::readSCS(unsigned char *nDat, int nLen)
    {
     int Size = 0;
     int ComData;
     unsigned long t_begin = millis();
     unsigned long t_user;
     while(1){
      ComData = pSerial->read();
      if(ComData!=-1){
       if(nDat){
        nDat[Size] = ComData;
       }
       Size++;
       t_begin = millis();
      }
      if(Size>=nLen){
       break;
      }
      t_user = millis() - t_begin;
      if(t_user>IOTimeOut){
       break;
      }
     }
     return Size;
    }

    int SCServo::writeSCS(unsigned char *nDat, int nLen)
    {
     if(nDat==NULL){
      return 0;
     }
     return pSerial->write(nDat, nLen);
    }

So the problem is somewhere here: **Arduino Mega works good**, but it seems like Arduino Due have no time for on of the operations.

You can see more info here:

[Servo][1]

[TTLinker device][2]

[Arduino library][3]

  [1]: http://ali.onl/Cd4 "Servo"
  [2]: http://ali.onl/Cd5
  [3]: http://ragra.ru/SCServo.zip

body:
I figured out that 250000 baud rate is the only choice for the Arduino Due with these servos. Less baud rates cause skips on Arduino Mega also, so this speed is not enough for fast data transfer.

Higher baud rates work good on Mega too but cause garbage on Due.

So let's summarize: these servos with TTLinker (TXS0108E) work good with Arduino Due at 250000 only and with Arduino Mega at 250000 and higher baud rates.


message:
My Arduino Ethernet shield is not working

Actually I'm using a W5100 Hanrun HR911105A 16/02 Ethernet shield with an Arduino Uno (original).

I tried this code from the examples:

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

    // Enter a MAC address and IP address for your controller below.
    // The IP address will be dependent on your local network.
    // gateway and subnet are optional:
    byte mac[] = {
      0x00, 0xAA, 0xBB, 0xCC, 0xDE, 0x02
    };
    IPAddress ip(192, 168, 1, 177);
    IPAddress myDns(192,168,1, 1);
    IPAddress gateway(192, 168, 1, 1);
    IPAddress subnet(255, 255, 255, 0);
    // telnet defaults to port 23
    EthernetServer server(23);
    boolean gotAMessage = false;
    // whether or not you got a message from the client yet

    void setup() {
      Serial.begin(9600);
      // this check is only needed on the Leonardo:
      while (!Serial) {
        ; // wait for serial port to connect. Needed for native USB port only
      }
      // start the Ethernet connection:
      Serial.println("Trying to get an IP address using DHCP");
      if (Ethernet.begin(mac) == 0) {
        Serial.println("Failed to configure Ethernet using DHCP");
        // initialize the Ethernet device not using DHCP:
        Ethernet.begin(mac, ip, myDns, gateway, subnet);
      }
      // print your local IP address:
      Serial.print("My IP address: ");
      ip = Ethernet.localIP();
      for (byte thisByte = 0; thisByte < 4; thisByte++) {
        // print the value of each byte of the IP address:
        Serial.print(ip[thisByte], DEC);
        Serial.print(".");
      }
      Serial.println();
      // start listening for clients
      server.begin();
    }

    void loop() {
      // wait for a new client:
      EthernetClient client = server.available();
      // when the client sends the first byte, say hello:
      if (client) {
        if (!gotAMessage) {
          Serial.println("We have a new client");
          client.println("Hello, client!");
          gotAMessage = true;
        }
        // read the bytes incoming from the client:
        char thisChar = client.read();
        // echo the bytes back to the client:
        server.write(thisChar);
        // echo the bytes to the server as well:
        Serial.print(thisChar);
        Ethernet.maintain();
      }
    }

That code prints the following on the serial monitor:

    Trying to get an IP address using DHCP
    Failed to configure Ethernet using DHCP
    My IP address: 192.168.1.177.

So what is the problem? Why it is not connecting? I tried all the ethernet examples, but not one works. I don't know, maybe the problem is that I don't have a sticker of MAC address on the shield and I'm using the MAC address of the examples. Or maybe I'm writing the IP address wrong? Here is the data from the network connection details.

    Connection-specific DNS Suffix: zte.com.cn
    Description: Intel(R) Dual Band Wireless-AC 3165
    Physical Address: 72-57-C5-BC-66-07
    DHCP Enabled: Yes
    IPv4 Address: 192.168.1.2
    IPv4 Subnet Mask: 255.255.255.0
    IPv4 Default Gateway: 192.168.1.1
    IPv4 DHCP Server: 192.168.1.1
    IPv4 DNS Server: 192.168.1.1
    IPv4 WINS Server:
    NetBIOS over Tcpip Enabled: Yes
    Link-local IPv6 Address: fe80::b523:b9f2:b43c:6a8a
    IPv6 Default Gateway:
    IPv6 DNS Server:

My router is a ZTE model ZXHNH108N.

body:
If your Arduino can not get an IP address, it could be because there is a problem with your code, your shield or your network.

There doesn't seem to be a problem with your code from a quick glance, so let's look at the network.

1. The cable. Are you using the right sort of cable? You should be using a Cat5e straight through cable. Cat5e is the type of cable for Ethernet, if it is plugged into the router and you didn't make it yourself, it is probably either a CAT5e or CAT6 cable, so it will be OK. There are two types of cable and they are almost impossible to tell apart, the normal sort is a "straight through" cable, which means the Transmit and Receive pins at one end go to the Transmit and Receive pins at the other end. The other sort is a "crossed" cable where the Transmit goes to the Receive, this is for connecting a computer to a computer.  Since you are plugging to a router you should have a straight cable, if in doubt test it with a working device, ie plug it into your PC.
2. DHCP - I see from your PC output DHCP is enabled on 192.168.1.1 and I guess this is your router. A DHCP server needs to know what addresses it can give out to devices, these addresses are called "the DHCP pool". If you have no more free addresses in the pool then you can't connect anymore devices. It sounds like you haven't restricted your pool, but it might be worth logging onto your router and seeing if you can see what addresses are in the pool or range.
3. MAC Filtering - For security some routers only allow certain MAC addresses to connect to the router and request a DHCP address. If you have it turned on then add your MAC address to the white list. If you don't have it turned on, don't worry.
4. Speed - I suspect that your shield has a maximum speed of 10MBs. Most modern networking equipment only supports 100/1000MBs so the shield just won't work with your router. Your router should have the numbers near the wired sockets to confirm or deny this.

If none of that works the you are going to need to see if you can read the data from the shield and see if you can work out what is going wrong. You will need a network snooper like WireShark and a _HUB_. An Ethernet switch will not work, it must be an Ethernet Hub, because switches don't rebroadcast the data on all ports. If your PC has two network cards you could set it up as a 'bridge' and you can snoop on the data as it passes across the bridge.

Sorry if some of these terms are confusing, but you should be able to Google them and get a better explanation than I can give you in the space here.

One final thought: are you running the Arduino from a battery? If so it might be worth using a mains supply, because the battery might not be able to support the Ethernet transmissions.


message:
Arduino UNO UART coding in pure C

Below is a simple `USART` code for `ARDUINO` written in `Pure C`.
But due to uknown(in reference to me) reasons, the code is not provicing desired output.

Can someone point out the error in the code.
I cannot use the `Arduino` built in function `Serial.begin` as i need to use USART receive `interrupts`.

    #include <avr/io.h>
    #define F_CPU 16000000
    #define BAUD 9600
    #include<util/setbaud.h>

    void UART_Init();

    void setup()
    {
        UART_Init();
    }

    void loop()
    {
        UART_Transmit('c');
    }

    void UART_Init()
    {
       UBRR0H = UBRRH_VALUE;
       UBRR0L = UBRRL_VALUE;
       UCSR0B = (1<<RXEN0) | (1<<TXEN0);
       UCSR0C = (3<<UCSZ00);
    }

    void UART_Transmit(unsigned char data)
    {
        while(!(UCSR0A & (1<<UDRE0)));
        UDR0 = data;
    }

body:
Finally I figured it out.

The `UBRR0` calculation was the mistake

For making the code work for baud rate 9600, we need to set the equation as:

> UBRR0 = (F_CPU / 4 / baud - 1) / 2;

and also double the USART speed by setting :
> UCSR0A = (1<< U2X0)

I hope someone will find this information helpful.


body:
> UBRR0 = (F_CPU / 4 / baud - 1) / 2;

you probably want to check the datasheet for that.

One way to code it is to change it based on the U2X bit, like this:

 UxBRR=F_UART / ((UxCSRA & (1<<U2X0))?8:16) / baud - 1;   //generate baud rate register

So the user can change the U2X bit freely and the software will take care of it.

there is one set of uart polling and interrupt-driven routines that I use: https://github.com/dannyf00/My-MCU-Library/tree/master/UART/UARTISR/ATMega328p

they have the same user interface so can be exchanged freely.


message:
Arduino chip family

This is a very basic question but I cannot find answer for this. I have a couple of Arduino Nano boards lying with me. With keen scrutinizing I found that a few chips on board where numbered as Atmega 328P-AU 1645 and some were numbered Atmega 328P-AU 1644. Can somebody please tell me the difference the number after AU makes ? I know the difference between an AU and PU chip.

body: Looks to me like a date code: YYWW, where YY are the last two digits of the year and WW is the ISO week number.


message:
Arduino digital pin reading string numbers

Using for example 433MHz RF Receiver modules, they are connected to a digital input pin with interrupt. Looking at the most basic meaning of digital readings (e.g. 1/0, on/off, HIGH/LOW), how does the Arduino convert the signal readings to a number/string?

From my limited understanding, I'm assuming it has something to do with the (external) libraries, or it might just be that my understanding about digital readings are too limited.

body:
From the official Arduino site, See [DigitalWrite][1] :

If the pin has been configured as an OUTPUT with pinMode(), its voltage will be set to the corresponding value: 5V (or 3.3V on 3.3V boards) for HIGH, 0V (ground) for LOW.

The exact definitions can be found here for reading a signal: [Constants][2]

When reading or writing to a digital pin there are only two possible values a pin can take/be-set-to: HIGH and LOW.

**HIGH**

The meaning of HIGH (in reference to a pin) is somewhat different depending on whether a pin is set to an INPUT or OUTPUT. When a pin is configured as an INPUT with pinMode(), and read with digitalRead(), the Arduino (Atmega) will report HIGH if:

-a voltage greater than 3.0V is present at the pin (5V boards);
-a voltage greater than 2.0V is present at the pin (3.3V boards);

A pin may also be configured as an INPUT with pinMode(), and subsequently made HIGH with digitalWrite(). This will enable the internal 20K pullup resistors, which will pull up the input pin to a HIGH reading unless it is pulled LOW by external circuitry. This is how INPUT_PULLUP works and is described below in more detail.

When a pin is configured to OUTPUT with pinMode(), and set to HIGH with digitalWrite(), the pin is at:
-5 volts (5V boards);
-3.3 volts (3.3V boards);

In this state it can source current, e.g. light an LED that is connected through a series resistor to ground.

**LOW**

The meaning of LOW also has a different meaning depending on whether a pin is set to INPUT or OUTPUT. When a pin is configured as an INPUT with pinMode(), and read with digitalRead(), the Arduino (Atmega) will report LOW if:

-a voltage less than 1.5V is present at the pin (5V boards);

-a voltage less than 1.0V (Approx) is present at the pin (3.3V boards);

When a pin is configured to OUTPUT with pinMode(), and set to LOW with digitalWrite(), the pin is at 0 volts (both 5V and 3.3V boards). In this state it can sink current, e.g. light an LED that is connected through a series resistor to +5 volts (or +3.3 volts).

Probably, HIGH is 1, LOW is 0, and ON is 1, OFF is 0.
Than 1 is mapped to 5V or 3.3V depending on the Arduino and 0 is mapped to 0V.
These mappings and the definitions of HIGH/LOW/ON/OFF are in the Arduino libraries.

  [1]: https://www.arduino.cc/en/Reference/DigitalWrite
  [2]: https://www.arduino.cc/en/Reference/Constants


body:
A digital pin can only tell you if a signal is HIGH or LOW at any instant in time. That itself isn't enough to transfer data (as in a stream of 1 and 0) since it's just the state at that moment.

To transfer data you need to introduce the extra parameter of *time*. That is, the amount of time a pin is HIGH or LOW and when exactly it changes.

UART data works this way. Both ends of the connection agree on a certain time for each "bit" of data (*symbol*) and read or set the pin at the agreed rate. That is the *baud rate* of the connection. Without that pre-arranged agreement on the time there is no way one end can know what the other is saying.

Other methods involve looking not at the current state of the pin but instead looking at how and when it changes from HIGH to LOW or LOW to HIGH. One example of this is *Manchester Coding* which encodes the different bits 0 and 1 as different sequences of transitions between HIGH and LOW or LOW and HIGH.

A third method, which is what SPI and I2C use, is to employ another pin to indicate to the receiver when it should look at the pin - this is sending the *clock* to the receiver.

Fourth, you get the way IR remote controls work. These use different length pulses of HIGH/LOW to indicate a 1 or a 0. A long HIGH and short LOW could be a 1, and a short HIGH and long LOW could be a 0.


message:
what is aref(analog reference)

what is the analog reference, I know that it can be used as a voltage reference, but not exactly what  it is all about please someone help.

body:
It is the reference voltage against which all other analog voltages (analog inputs) are measured against.

By default it is the same as the chip supply voltage (5V on most Arduino boards), so the analog inputs can measure between 0 and 5V.

If you connect the AREF pin to a lower voltage, say to the 3.3V pin (for convenience) and set the analog reference to EXTERNAL, you can then measure between 0 and 3.3V.

This is good if you are measuring a smaller voltage and want to get as much resolution in the analog reading. If you leave it at 5V and are measuring only up to, say, 3.3V, you're wasting all the analog reading values between 3.3V and 5V that could go to getting you more sensitivity.


message:
Can't upload any code to my Arduino board

I have an Arduino Uno R3 with an ATmega238 microchip. I can't upload any code to it: the green led and pin13 LED are always on (without flashing ) and the RX and TX LEDs don't flash when I upload code or press the reset button. Is the microchip malfunctioning?

And what happens when a reverse current returns to Arduino from a relay?

body:
You basically have 2 questions here.

1: Why is my Uno not uploading code.

2: How does back EMF effect a microcontroller. We'll address 2 first

When a relay module is activated, it energizes a coil to close a switch. This coil is an inductor, which is an energy storage device. When the signal to the relay tells it to turn off, your trying to de-energize the coil. Whereas before you let current run through the coil to establish a magnetic field, now you cut the current supply and let the magnetic field die out.
The problem this creates is back EMF. As [Faraday's law][1] will tell us, a change in a magnetic field causes a voltage (an EMF) in a coil. When we were charging the circuit, this was the voltage applied to the coil. When we discharge the inductor, this voltage is back EMF, and is in **the opposite direction as charging voltage**.

How does this affect your arduino? Well, it can be anything ranging from harmless to catastrophic. It may simply reset your arduino (as one I was working with did on a past project [where an occiliscope showed back EMF spikes in excess of -30V]) or it might straight-up burn the ATMega328p that acts as the Uno's brain. Or it might take out the voltage regulator, or cause a host of other problems.

The simplest fix for back EMF is to put a diode in parallel with the relay with cathode to your positive terminal and anode to your negetive terminal. This creates a short for the relay's coil to discharge through. Some better solutions (especially for sensitive digital equiptment) involve entirely isolating the relay's power supply form the rest of your circuit with an optoisolator.

Problem 1: Assuming that these problems were related to the use of a relay without the proper safeguards, you might try a few things to verify your chip is still alive. If  you have a second arduino you might try using it to [build an ISP][2], which will allow you to both reburn the bootloader and upload sketches independently of the uno's onboard usb com port programmer. If that works but the onboard programmer still does not, you may need to reflash the programmer (which I've read can also be done with an ISP, though I've never tried it.)

Hope that helps!

  [1]: https://en.wikipedia.org/wiki/Faraday's_law_of_induction
  [2]: https://www.arduino.cc/en/Tutorial/ArduinoISP


message:
How to connect a Pressure Sensor-MPX10DP to an Arduino?

I'm very new to Arduino, I'm trying to connect an air pressure Sensor without success.

I followed this tutorial:

[Arduino Air Pressure Measurement][1]

The values I'm getting are very weird and the variations when I blow in the sensor are not more than about `+/- 0.2`.

So, the tutorial does use the same model, is that why? I need something else?

Any help will be very appreciated.

  [1]: http://circuits4you.com/2016/05/13/arduino-pressure-measurement/

body:
The MPX10DP does not have an amplifier inside. The output is the output of the internal wheatstone bridge. It is not even compensated for temperature.

This is the manufacturers page about the MPX10 series: [nxp.com MPX10 series][1].

You need an instrumentation amplifier and perhaps a temperature compensation. The INA125 is an instrumentation amplifier. It was used in the past with the Arduino a lot. Nowadays, most sensors are digital, and the bare sensors with wheatstone bridge output are not used that often anymore.

When you connect both sensor outputs to two Arduino inputs (without amplifier), then the difference is 35mV for 10kPa. The resolution is in theory 5V / 1024. The overall accuracy for two analog inputs perhaps 9 bits, then you can measure the 10kPa in 3.5 steps (about 2 or 3 kPa resolution).
If you seriously want to use this specific sensor, and don't want to use extra hardware, then you might have a look at [my question about the differential mode and gain][2] that is possible with the Arduino Mega 2560 and Leonardo.

Or you could buy a pressure sensor with 0...5V output, that can be connected to the Arduino analog input. The tutorial you mentioned uses the MPX5010. That sensor has a amplifier inside and is temperature compensated. They are reliable and ratiometric with the 5V, therefor super easy to use. With a lot of averaging in the code, you can get a high (relative) accuracy.

  [1]: http://www.nxp.com/products/sensors/pressure-sensors/differential-gauge-up-to-10-kpa/differential-and-gauge-uncompensated-pressure-sensor-0-to-10kpa:MPXx10
  [2]: https://arduino.stackexchange.com/questions/39211/library-to-set-internal-analog-gain-of-the-arduino


message:
Custom board with ATMega32u4 having USB issues

I built a custom arduino based board (speciffically based off of Sparkfun's Pro Micro 3.3V 8Mhz and their Qduino mini boards) that uses the ATMega32u4-RC.

The board I built integrated an acceleromter (LSM6DS3) and a micro-SD card holder, and eleminated any uneeded GPIO. (This is basically a datalogger board for the LSM6DS3 accelerometer). It also inlcudes a usb-powered LIPO charging circuit, which is copied from the qduino mini.

A picture of the board I built,  with power LED indicating life.
[![My Board][1]][1]

The problem I am experiencing is that, after apparently sucessfull upload of the bootloader (I've tried the bootloader for the qduino mini, promicro 3.3v 8Mhz, even the Leonardo), my computer will not reconize the board. I've exauhsted all the information about driver installation from the sources for the boards my board is based on, and still can't make windows recognize my custom board.

Specifically, I've tried using a multitude of signed and unsigned drivers (on Windows 10 and 7), and can not get windows to pick anything other than usbfilt.sys as the driver.

Any advice would be greatly appreciated!

Edit: Added Eagle Schematic below

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

  [1]: https://i.stack.imgur.com/MDRyd.jpg
  [2]: https://i.stack.imgur.com/Z8I1o.png

body:
As Chris Stratton pointed out, I neglected to include the 1uF capacitor on UCap. This is absolutely necessary on a 3.3v board for the board to communicate with USB properly.

 Thanks!


message:
Read Audio Data in Real-time over 3.5mm Stereo Cable

# My Goal #

Have Arduino read audio output from a TRS stereo audio cable (coming from a computer, smartphone, etc.). *As motivation for this use-case*, once some audio data (depending on the sample rate) have been stored in a buffer, the Arduino will perform an FFT on the buffered data. The power contained in the FFT is mapped to the red, green, and blue frequency-bands of visible light to determine the color of an LED strip.

# My Set-up #

The obvious first step was to connect a [Right-Angle 3.5mm Stereo Plug to Pigtail Cable][1] to the Arduino. As is commonplace, this cable has a **T**ip, **R**ing, and **S**leeve connector; Adafruit labels the black wire as ground (sleeve). They further label the red wire as "left channel live" (tip) and the white wire as "right channel live" (ring), if I can trust [Wikipedia][2]:

> Stereo sockets commonly provide two such NC contacts, one for the **tip (left channel live)** and one for the **ring or collar (right channel live)**.

# My Question #

So, I've plugged the red wire into the `A0` pin and the white wire into the `A1` pin. However, I'm unsure of how to sample the actual audio signal from these analog pins.

I don't believe the `analogRead()` function solves the whole problem - it only converts a voltage reading at the pin into a value between 0 and 1023. Presumably, if I knew the bit rate (i.e., sample rate) & of each packet in the transmitted audio signal, I'd be able to construct signal from that. **Is it possible to extract the original audio's waveform from a simple voltage signal?** If not, what approach would enable the Arduino to read audio data from an audio cable?

*Note:* For those wondering, I have indeed heeded the advice from this [Electronics SE answer][3] to attach a DC-blocking/DC-bias circuit to the signal source before driving it into an analog pin on the Arduino.

  [1]: https://www.adafruit.com/product/1700
  [2]: https://en.wikipedia.org/wiki/Phone_connector_(audio)#Switch_contacts
  [3]: https://electronics.stackexchange.com/a/5321

body:
**The middle path**

Build the simple op-amp (or whatever) 70s-era color organ, but without all the LEDs. Then basically feed the organ's LED-driving lines into the Arduino's ADCs. Sampling that pre-processed/summarized data, you can define a wide variety of RGB interactions without complicated math or an EE background. The timing requirements will be well-within the Arduino's reach, unlike computing FFTs or other "difficult" processes. Besides, old/new hybrids are cool!


message:
Which Timer can I use on the Arduino/Genuino Micro?

I'm trying to implement charlieplexing with bit angle modulation on my Arduino Micro, and for that I need to use the internal timers.

Which timers of the Atmega32u4 are unused by the standard firmware? Ideally I'd like to use either Timer1 or Timer3 as they have the highest resolution.

body:
Only Timer0 is used for millis and micros, just as with the Arduino Uno and Mega 2560.

Timer0 is used in "[wiring.c][1]".
That same file is used for the Uno, Mega 2560, Leonardo and Micro. The differences for the Leonardo is the pin numbers in "[pins_arduino.h][2]".

If you don't use PWM output with analogWrite, then you can use all of the other timers. The timers are set to certain values in the function init (also in wiring.c). But you can ignore that if you never use analogWrite.

  [1]: https://github.com/arduino/Arduino/blob/master/hardware/arduino/avr/cores/arduino/wiring.c
  [2]: https://github.com/arduino/Arduino/blob/master/hardware/arduino/avr/variants/leonardo/pins_arduino.h


message:
Pressing reset button restarts program only seconds latter

I am wondering why after pressing the reset button on my Arduino, the latest program loaded runs but only after about 5seconds. The same thing happen when I run my arduino from the computer using the Arduino 1.6.9 software.

Is there any way to make this delay shorter?

Thanks,
IF

body:
The first thing that happens when you apply power to a board or press reset, is the bootloader executes. That waits for a short time to accept a new sketch over the serial port. If nothing arrives it terminates and executes the existing sketch.

On the Uno that delay is only 2 seconds. However on the Leonardo the delay is much longer (around 5-8 seconds) owing to how the serial port is implemented: it has to allow time for the host computer to re-enumerate the USB device after a reset, and that takes a second or two.

If you don't want that delay you will need to remove the bootloader (i.e., ignore it) and program the board through a hardware programmer and the ICSP pins (which will disable the bootloader for you). You lose the convenience of programming through the USB connection though.

Alternatively choose a different board that doesn't have such a delay for the bootloader - one that uses a different programming method.


body: Having had the same issue , I recently found out that the Leonardo/Micro jumps directly into the user application when it is powered up, either by inserting a USB cable connected to a cellphone charger i.e power only USB , or by connecting external power via the RAW power input.  So, if you need a quick restart after reset, just cut and reconnect the power supply.


message:
How to speed up Due ADC

I'm doing a project where in I'm using Arduino Due to measure the time difference of arrival of signals to four piezoelectric sensors. The piezo sensors where glued on a board and we want to localize the source of taps on the boards based from the TDOA of the vibration to the piezos.

Originally, we are using interrupts to raise flags once we have detected the signals (basically, we've set a threshold on the piezo voltage to say that we've 'detected' a signal) but that seems susceptible to noises especially when the environment has loud noises (music, voices on microphones, etc.).

So what we think as a solution is to perform signal processing. However, to do this, we need to measure the voltage of the incoming signal using the ADC.

So far, my target is to make the performance of this approach comparable to that of the one where we are using interrupts. As of now, the new approach is super sensitive to the difference on the taps giving it a high POE.

As I understand it, the main difference between the two approach is that the interrupt approach has a microsecond difference between counts making the difference of the taps to about 10 to 30 microsecond. However, the Analog approach has a 20 microsecond difference between each sample for each channel, making the count difference 20 second also. Even a count difference would make it 20 us.

Is there anyway to make this time faster? I know the ADC needs time to convert and push the data to the appropriate registers but I'm just trying to find ways to make this faster. I've read on the datasheet of the Due MCU that it has 14 ADC channels plus a temp sensor at the 15th. Maybe a way of doing this could be to reduce the number of channels? I don't know how.

Are there any way to make the ADC conversion of the Arduino Due faster?

body:
Yes, there is a possibility to configure `ADC` to run faster, as it can handle `1Msps`. For four `ADC` channels it means `250ksps` each (with `1us` time difference between samples). It's not possible with Arduino wrappers as they are way too slow and also waits for conversion end. You have to configure it directly in MCUs registers, so start with `SAM3X8` datasheet.

In short: free running mode, sequenced readings like: `0 1 2 3`, with interrupt on 4th sample, interrupt handler and some processing.


body:
> difference between each sample for each channel,

That's way too slow for any mcu made since the 1980s.

Look into the datasheet and compare it via your code to see where you can pick up the speed. Typically there is a clock prescaler for the adc that you can change.

In general, the fastest would be continuous adc into dma. If you need to add multiple channels turn on scanning.


body:
//Configure ADC
PMC->PMC_WPMR &= ~(PMC_WPMR_WPEN);    //Disable the Write Protect Mode
PMC->PMC_PCER1 |= PMC_PCER1_PID37;    //Enable ADC Peripheral Clock

PIOA->PIO_PDR |= PIO_PDR_P16;         //Disable PIO Controller

ADC->ADC_WPMR &= ~(ADC_WPMR_WPEN);    //Disable the Write Protect Mode
ADC->ADC_CHER |= ADC_CHER_CH7;        //Enable A0 pin
ADC->ADC_MR = 0;
//ADC->ADC_MR = ADC_MR_PRESCAL(2);    //ADC Clock set to 16MHz
ADC->ADC_MR = ADC_MR_PRESCAL(4);      //ADC Clock set to 8MHz
ADC->ADC_MR |= ADC_MR_TRACKTIM(3);
ADC->ADC_MR |= ADC_MR_STARTUP_SUT8;
ADC->ADC_EMR = 0;

//read ADC output
ADC->ADC_CR |= ADC_CR_START;           //Software Trigger
uint32_t adc_read = ADC->ADC_CDR[7];

you can change the parameters of prescaler to get the required speed


body:
You can set the ADC in freerun mode to get results as fast as they can be read.

Use [adc_configure_trigger][1] for this.

    adc_configure_trigger(ADC, ADC_TRIG_SW, ADC_MR_FREERUN_ON);

To enable freerun on the ADC or to configure as needed. No need anymore to set registers.

There was a bug with this function before if called more than once, but it is now fixed.
https://github.com/arduino/Arduino/issues/1819

  [1]: http://asf.atmel.com/docs/latest/sam.drivers.adc.adc_threshold_wakeup_example.arduino_due_x/html/group__sam__drivers__adc__group.html


message:
How to store incoming serial string in arduino?

In my recent project, I am working with serial data. Till now, I'm able to receive data and display on LCD. Now, suddenly I can't get any serial data. Nothing display on LCD.

My incoming string is:

    {"Action":"ONE","TPS":"0.40","MAP":"0.95","LOAD":"14"}

And my code is below:

    #include<LiquidCrystal.h>

    LiquidCrystal lcd(12, 11, 7, 6, 5, 4);

    String response = "";
    bool begin = false;

    void setup()
    {
      Serial.begin(9600);
      lcd.begin(16, 2);
    }

    void loop()
    {

      while(Serial.available() || !begin)
      {
        char in = Serial.read();

        if (in == '{')
        {
          begin = true;
        }

        if(begin)
        {
          response += (in);
        }

        if(in == '}')
        {
            break;
        }
        delay(1);
      }

      lcd.setCursor(0, 0);
      lcd.print(response);
    }

body:
Actually I can see what I think may be an issue with your code.

     while(Serial.available() || !begin)

This isn't right.  If there is no data available in the serial buffer but the first `{` hasn't been seen then go and read the non-existent data anyway?

Rather than try and explain what I mean in multiple comments I have put it all together and this is what I think your loop should be this:

    /// This is un-compiled code, so you might have to fix some little issues.
    /// bool begin = false;         // True when the initial { has been seen

    void loop()
    {
      while (finished == false)
      {
        if (Serial.available())
        {
          const char in = Serial.read();
          if (in == '{')
          {
            response = "";  // Blank the string
            begin = true;
          }
          if (begin)
          {
            response += (in); // Only write if within the {}
          }
          if (in == '}')
          {
            begin = false;   // Prevent any chars between } and { leaking through.
            lcd.setCursor(0, 0);
            lcd.print(response);
          }
        }
        delay(1);
      }

      delay(500); // Not sure what will happen if you send multiple {} to the LCD too fast.
    }


body: I just switch from Arduino UNO to Arduino MEGA. And everything works fine. I know this is not a proper answer but I want to know why this happens. I don't understand why this happens? Can anyone explain me?


message:
character input for an integer variable?

Im trying out the code found [here][1] , let me quote the section of code that bothers me.

    // set pin numbers for switch, joystick axes, and LED:
    const int switchPin = 2;      // switch to turn on and off mouse control
    const int mouseButton = 3;    // input pin for the mouse pushButton
    const int xAxis = A0;         // joystick X axis
    const int yAxis = A1;         // joystick Y axis
    const int ledPin = 5;         // Mouse control LED
xAxis is a variable that is defined as an integer , however, it is being assigned a character(A0), How is this possible? I tried to compile and run the code and everything works well. I'm quite surprised!

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

body:
A0 and A1 are not characters or what you mean probably: strings.
Because it would be written as "A0" and "A1".
The types of A0 and A1 are probably integers or another numeric type.

However, these are probably defined as (constant) integers, e.g.:

    const int A0 = 100;
    const int A1 = 101;

(note 100 and 101 are random numbers)

or defined by a macro. e.g.:

    #define A0  100
    #define A1  101

So the variables A0 and A1 are actually integers (or assigned as numeric values by a define).


body:
The clue is this comment:

    // set pin numbers for switch, joystick axes, and LED:

and the fact that xAxis is declared a `const int`. Because the declaration promises that this variable will not (must not) be changed once it has been initialized, it will not be assigned any memory at run time. The compiler will treat it much like the macro:

    #define xAxis A0

and do a compile-time replacement of `xAxis` with A0, wherever xAxis appears.

`A0` is an analog channel, defined in the board-specific Arduino libraries to the Arduino pin# corresponding to it.

It is a somewhat recent idiom in C and C++ - since the inclusion of "const" in the language - to use "const int" declarations for this purpose instead of "#define" statements. The intent is the same.


message:
How to extract latitude and longitude from GPS

I want to extract longitude and latitude from GSM/GPS module and then upload it to thingspeak. I am using sim808 GSM/GPS module and AT+CGPSINF=0 to get GPS location information sentence (CGPSINF: 0,6.823375,80.001038,36.300000,20170705124133.000,0,10,0.037040,47.410000
). I want to extract longitude and latitude from it. Does anyone know how to do it? I am not an expert in programming. someone told me to use strtok. But I don't know how to do it. Does anyone have any Arduino code to do this?

I tried DFRobot SIM808 library to collect GPS data. it works like charm. But the problem was, my upload code didn't work when i was using the library to collect longitude and latitude in the same code.

This is my web upload code.

    #include <SoftwareSerial.h>
    #include <String.h>

    SoftwareSerial mySerial(10, 11);//(2,3)

    void setup()
    {
      mySerial.begin(2400);   // the GPRS baud rate 9600
      Serial.begin(2400);    // the GPRS baud rate 9600

      delay(1000);

      ShowSerialData();

    }

    void loop()
    {
          Send2Pachube();
      if (mySerial.available())
        Serial.write(mySerial.read());
    }
    void Send2Pachube()
    {
      mySerial.println("AT");//start with attention
      delay(1000);

      mySerial.println("AT+CPIN?");//check for the sim card
      delay(1000);

      mySerial.println("AT+CREG?");//check for registration and access technology of cell
      delay(1000);

      mySerial.println("AT+CGATT?");//check whether the device is attached to GPRS.0Detch,1Attch
      delay(1000);

      mySerial.println("AT+CIPSHUT");//shut packet data protocol context
      delay(1000);

      mySerial.println("AT+CIPSTATUS");// returns the current connection status
      delay(2000);

      mySerial.println("AT+CIPMUX=0"); //create multi-IP connection(0=single connection)
      delay(2000);

      ShowSerialData();

      mySerial.println("AT+CSTT=\"hutch3g\"");//start task and setting the APN,
      delay(1000);

      ShowSerialData();

      mySerial.println("AT+CIICR");//bring up wireless connection
      delay(3000);
      ShowSerialData();

      mySerial.println("AT+CIFSR");//get local IP adress
      delay(2000);
      ShowSerialData();

      mySerial.println("AT+CGPSINF=0");//get GPS
      delay(2000);
      ShowSerialData();

      mySerial.println("AT+CIPSPRT=0");//starts a TCP or UDP connection
      delay(3000);

      ShowSerialData();

      mySerial.println("AT+CIPSTART=\"TCP\",\"api.thingspeak.com\",\"80\"");//start up the connection
      delay(6000);

      ShowSerialData();

      mySerial.println("AT+CIPSEND");//begin send data to remote server
      delay(4000);
      ShowSerialData();

      String str="GET https://api.thingspeak.com/update?api_key=FF19NVWMPZEWX0XK&field1=100";
      mySerial.println(str);//begin send data to remote server
      delay(4000);
      ShowSerialData();

      mySerial.println((char)26);//sending
      delay(5000);//waitting for reply, important! the time is base on the condition of internet
      mySerial.println();

      ShowSerialData();

      mySerial.println("AT+CIPSHUT");//close the connection
      delay(100);
      ShowSerialData();
    }
    void ShowSerialData()
    {
      while(mySerial.available()!=0)
        Serial.write(mySerial.read());
    }

body:
First rather than just dumping it to the screen store the data in a char array

    char dataBuffer[64];
    int dataCount=0;

    while ( (mySerial.available()!=0) && (dataCount<63) ) {
        dataBuffer[dataCount] = mySerial.read());
        dataCount++;
    }
    dataBuffer[dataCount] = 0;

then use strtok to split the string on the : and , characters

    char *output;
    output = strtok(dataBuffer,":");
    // output will now point to everything up to the first : so "CGPSINF" for gps
    int field = 0;
    while (output != null) {
      field++;
      output = strtok(null,",");
    // output will now point to each value in turn
    // for CGPSINF:0,6.823375,80.001038,36.300000,
    // when field == 1 output=="0"
    // when field == 2 output=="6.823375" etc...
    }


message:
How to create a simple TCP server with the analogRead value on Wemos D1 mini?

I want to create a TCP server on the Wemos that serves the analogRead value of the connected potentiometer.

The code below is based on [this][1] example.
The Wemos connects to the Wi-Fi and i'm able to ping it,
but the problem is that I **can't connect to the server**.
Also I don't really understand why the length of the data has to be passed with the data (`        serverClients[i].write(sbuf, len);`). Why can't the library figure that out?

    #include <ESP8266WiFi.h>

    //how many clients should be able to telnet to this ESP8266
    #define MAX_SRV_CLIENTS 2
    const char* ssid = "myWifi";
    const char* password = "myPassword";

    WiFiServer server(23);
    WiFiClient serverClients[MAX_SRV_CLIENTS];

    unsigned long previousMillis = 0;
    const long interval = 200;
    void setup() {
      Serial.begin(115200);
      Serial.print("\nConnecting to "); Serial.println(ssid);

      WiFi.mode(WIFI_STA);
      WiFi.begin(ssid, password);
      uint8_t i = 0;
      while (WiFi.status() != WL_CONNECTED && i++ < 20) delay(500);
      if (i == 21) {
        Serial.print("Could not connect to"); Serial.println(ssid);
        while (1) delay(500);
      }
      server.setNoDelay(true);
      Serial.print(WiFi.localIP());
    }

    void loop() {
      unsigned long currentMillis = millis();
      uint8_t i;
      //check if there are any new clients
      if (server.hasClient()) {
        for (i = 0; i < MAX_SRV_CLIENTS; i++) {
          //find free/disconnected spot
          if (!serverClients[i] || !serverClients[i].connected()) {
            if (serverClients[i]) serverClients[i].stop();
            serverClients[i] = server.available();
            continue;
          }
        }
        //no free/disconnected spot so reject
        WiFiClient serverClient = server.available();
        serverClient.stop();
      }

      //do every 200ms
      if (currentMillis - previousMillis >= interval) {
        previousMillis = currentMillis;

        int isensorValue = analogRead(A0); //analog read
        String sSensorValue = String(isensorValue); //int to string
        size_t len = sSensorValue.length();
        uint8_t sbuf[len];
        sSensorValue.getBytes(sbuf, len);
        for (i = 0; i < MAX_SRV_CLIENTS; i++) {
          if (serverClients[i] && serverClients[i].connected()) {
            serverClients[i].write(sbuf, len);
            delay(1);
          }
        }

      }
    }

  [1]: https://github.com/esp8266/Arduino/blob/master/libraries/ESP8266WiFi/examples/WiFiTelnetToSerial/WiFiTelnetToSerial.ino#L62

body:
So the problem was that I forgot the following line.
Thanks to @Johnny Mopp for pointing this out.

    server.begin()

**Correct code:**

    #include <ESP8266WiFi.h>

    //how many clients should be able to telnet to this ESP8266
    #define MAX_SRV_CLIENTS 2
    const char* ssid = "myWifi";
    const char* password = "myPassword";

    WiFiServer server(23);
    WiFiClient serverClients[MAX_SRV_CLIENTS];

    unsigned long previousMillis = 0;
    const long interval = 200;
    void setup() {
      WiFi.mode(WIFI_STA);
      WiFi.begin(ssid, password);
      uint8_t i = 0;
      while (WiFi.status() != WL_CONNECTED && i++ < 20) delay(500);
      if (i == 21) {
        Serial.print("Could not connect to"); Serial.println(ssid);
        while (1) delay(500);
      }
      server.begin();
      server.setNoDelay(true);
    }

    void loop() {
      unsigned long currentMillis = millis();
      uint8_t i;
      //check if there are any new clients
      if (server.hasClient()) {
        for (i = 0; i < MAX_SRV_CLIENTS; i++) {
          //find free/disconnected spot
          if (!serverClients[i] || !serverClients[i].connected()) {
            if (serverClients[i]) serverClients[i].stop();
            serverClients[i] = server.available();
            continue;
          }
        }
        //no free/disconnected spot so reject
        WiFiClient serverClient = server.available();
        serverClient.stop();
      }

      //do every 200ms
      if (currentMillis - previousMillis >= interval) {
        previousMillis = currentMillis;

        int isensorValue = analogRead(A0);
        String sSensorValue = String(isensorValue) + "\n\r";
        size_t len = sSensorValue.length();
        uint8_t sbuf[len];
        sSensorValue.getBytes(sbuf, len);
        for (i = 0; i < MAX_SRV_CLIENTS; i++) {
          if (serverClients[i] && serverClients[i].connected()) {
            serverClients[i].write(sbuf, len);
            delay(1);
          }
        }

      }
    }


message:
IR Remote code not activating ON/OFF states

The code below is for turning RGB lights on/off. The connections are as indicated in pin numbers. I found the resulting value of the buttons of the remote but when I used them in code it is not showing ON/OFF.

I assume there may be some practical errors. How to avoid such errors?

    #include <IRremote.h>

 int RECV_PIN = 3;
 int red = 13;
 int blue = 12;
 int green = 11;

 IRrecv irrecv(RECV_PIN);

 decode_results results;

    void setup() {
      Serial.begin(9600);
      irrecv.enableIRIn(); // Start the receiver
      pinMode(red, OUTPUT);
      pinMode(blue, OUTPUT);
      pinMode(green, OUTPUT);
    }

    void loop() {
      if (irrecv.decode(&results)) {
        long int getting = results.value;
        Serial.println(getting);
      }
      switch (results.value) {
        case 16582903:
          digitalWrite(red, HIGH);
          digitalWrite(blue, LOW);
          digitalWrite(green, LOW);
          break;
        case 16615543:
          digitalWrite(red, LOW);
          digitalWrite(blue, HIGH);
          digitalWrite(green, LOW);
          break;
        case 16599223:
          digitalWrite(red, LOW);
          digitalWrite(blue, LOW);
          digitalWrite(green, HIGH);
          break;
        default:
          Serial.println("Enter ;");
      }
      irrecv.resume(); // Receive the next value
      delay(100);
    }

body:
Assuming you wiring is correct, the only mistake I could see is that your variable named "getting" used in switch is inside the if, and it should be at least in the same level of switch. Also, your resume needs to be inside the if.

    #include <IRremote.h>

 int RECV_PIN = 3;
 int green = 11;
 int blue = 12;
 int red = 13;

 #define code1  16582903 // Must match exactly the code generated by the IR button, would be something like 0xFF906F
 #define code2  16615543
 #define code3  16599223

 IRrecv irrecv(RECV_PIN);
 decode_results results;

 void setup() {
      Serial.begin(9600);
      irrecv.enableIRIn(); // Start the receiver
      pinMode(red, OUTPUT);
      pinMode(blue, OUTPUT);
      pinMode(green, OUTPUT);
 }

 void loop() {
      if(irrecv.decode(&results)) {
        //this checks to see if a code has been received
        Serial.println(results.value, HEX);
        unsigned int getting = results.value;
        Serial.println(getting);
        switch (getting) {
          case code1:
            digitalWrite(red, HIGH);
            digitalWrite(blue, LOW);
            digitalWrite(green, LOW);
            break;
          case code2:
            digitalWrite(red, LOW);
            digitalWrite(blue, HIGH);
            digitalWrite(green, LOW);
            break;
          case code3:
            digitalWrite(red, LOW);
            digitalWrite(blue, LOW);
            digitalWrite(green, HIGH);
            break;
          default:
            Serial.println("Enter ;");
        }
        irrecv.resume(); //receive the next value
      }
      delay(100);
 }


body:
I would change "unsigned int getting = results.value;" to "unsigned long getting = results.value;" in Andrew's sketch and use it. I don't know what "type" of Arduino you are using, but I know on the Uno and other ATMEGA based boards, unsigned ints yield a useful range of 0 to 65,535. Unsigned long will give you a range from 0 to 4,294,967,295.

If you press ANY button and hold it down for a while on some IR remotes, code 4294967295 will be sent. This is true for the "Car" remotes: https://www.amazon.ca/dp/B00SMI1GZA/ref=pe_386430_126088100_TE_item, Apple TV (2nd generation) remote, and LG 50" TV remote.

One minor issue I found with both sketches is I could not get them to compile. I had to remove the space between "#" and "include" and the spaces between "<" and ">" in "# include < IRremote.h >". I am using an older version of the IDE which may explain it. Arduino UNO. IDE Version 1.0.6.2, GCC 4.2.1 on OSX 10.6.8.


message:
Connecting NodeMCU with OV7076 camera

I am trying to connect an OV7076 camera with a NodeMCU, but there are no pin diagram available for it. As NodeMCU has 4 MB storage and 128 KB  memory, is there any possibility to use it?

[AI thinker esp8266mod ](https://bennthomsen.files.wordpress.com/2015/12/nodemcu_pinout_700-2.png)

[Omnivision OV7076](http://i.ebayimg.com/00/s/NTAwWDUwMA==/z/fh0AAOxyUylTVi8n/$_3.JPG?set_id=2)

body:
You cannot connect an [OV7076][1] camera with NodeMCU because OV7076 got 4 analog pins (VGA) and on the other hand NodeMCU got only one analog pin.

  [1]: https://www.voti.nl/docs/OV7670.pdf


message:
How to control RC power switch with Arduino-/Adafruit-Board?

I want to control (switch on/off) a solenoid valve via an RC power switch and an Adafruit M0 Feather Bluefruit LE. The RC power switch is [this one][1], and this is the [Adafruit Board Pinout][2].

My assumption was that I have to wire up the servo wire connector of the power switch with the Adafruit board like I would do with an ESC and control it via PWM (my guide tells me that possible pulse widths are between 870 and 2,220 µs). I am connecting the white cable (I assume it's the impulse wire) of the power-switches' servo-connector with a PWM-capable GPIO pin and the black cable (I assume it's the minus wire) with the GND pin of the Adafruit Board, like I did with an ESC, which is working fine with the servo library of Arduino.

My problem is that the solenoid valve is showing no reaction. Am I thinking the right way or am I completely wrong?

Thank you and many thanks.

  [1]: http://shop.pichler.de/Power-Switch-c74-86-7486
  [2]: https://learn.adafruit.com/adafruit-feather-m0-bluefruit-le/pinouts

body:
I fixed the problem by myself. If you want to arm an RC power switch, do it like arming an ESC with your sketch. The servo connector wires have to be connected as follows:

- (white) PWM-capable GPIO
- (red) positive wire of your battery
- (black) negative wire of your battery

The simple solution was that the power switches got less/no power.


message:
Problem with tachometer using attachInterrupt and servo

So I am creating a tachometer using black/white detector sensor. Here's the code.

    unsigned long WaktuOLD;
    unsigned long WaktuNOW;
    int Detection = HIGH;
    int Counter = HIGH;
    float HitungWaktu;
    float HitungRPM;

    void setup() {
      Serial.begin(9600);
      attachInterrupt(digitalPinToInterrupt(3), rpm, RISING);
      WaktuNOW = millis();
    }

    void rpm() {
      Detection = digitalRead(3);
      if (Detection == HIGH && Counter == LOW) {
        WaktuNOW = millis();
        HitungWaktu = WaktuNOW - WaktuOLD;
        HitungRPM = 60 / (HitungWaktu / 1000);
        Counter = HIGH;
      } else if (Detection == HIGH && Counter == HIGH) {
        Counter = LOW;
        WaktuOLD = millis();
      }
    }

    void loop() {
      Serial.println(HitungRPM);
      delay(5000);
    }

The code works well and it can read RPM correctly. And then from the same arduino, I am controlling a servo motor, in this case I am using GWS03N/STD/F, with this code :

    #include <Servo.h>

    Servo myservo;
    int pos = 0;

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

    void loop() {
      myservo.write(90);
    }

And this code works well too.

But, when I am trying to combine both codes, only the servo code is working well. The tachometer reading is not correct (the reading must be around 1000-1500rpm, but now it reads 3000-30krpm). I am already trying to change my tachometer interrupt to pin 2 or 3, and servo to 3, 5, 6, and 9 but still the same.

So what is wrong in here. Thank you so much.

This is my code when combining both codes.

    #include <Servo.h>

    Servo myservo;
    int pos = 0;
    unsigned long WaktuOLD;
    unsigned long WaktuNOW;
    int Detection = HIGH;
    int Counter = HIGH;
    float HitungWaktu;
    float HitungRPM;

    void setup() {
      Serial.begin(9600);
      attachInterrupt(digitalPinToInterrupt(3), rpm, RISING);
      WaktuNOW = millis();
      myservo.attach(9);
    }

    void rpm() {
      Detection = digitalRead(3);
      if (Detection == HIGH && Counter == LOW) {
        WaktuNOW = millis();
        HitungWaktu = WaktuNOW - WaktuOLD;
        HitungRPM = 60 / (HitungWaktu / 1000);
        Counter = HIGH;
      } else if (Detection == HIGH && Counter == HIGH) {
        Counter = LOW;
        WaktuOLD = millis();
      }
    }

    void loop() {
      Serial.println(HitungRPM);
      myservo.write(90);
      delay(5000);
    }

body:
All of those variables that are accessed inside the ISR need to be declared as volatile.

You are using a RISING interrupt, so there should be no need to test the pin in the ISR.  You can be confident that it went HIGH for the interrupt to be run.


body:
Your problem is probably that of interrupt conflicts.

The 8-bit Arduinos don't have any concept of interrupt priorities. When one interrupt routine is running it is impossible for any other interrupt routine to run until that first one has finished.

Interrupts have a "natural call priority" in that lower numbered pending interrupts will be called in preference to higher numbered ones, however that doesn't mean that they can interrupt each other.

The problem here is that the servo library uses a timer (and its associated interrupt) to generate the waveform.  That uses a lot of interrupt calls running all the time - and while they are running your external interrupt can't be called - at least not until the currently executing timer interrupt completes, at which point your external interrupt handler will be called since it is the highest priority.

So the results you get with all that delaying are pretty meaningless.

So what can you do?  Well, there's a number of options - all of which involve *not* using interrupts.

* You could not use the Servo.h library and instead reconfigure the hardware PWM to the right frequency and use that for the servo
* You could use one of the timers with an external clock source to count your tacho pulses (I think Timer 1 has that ability on the Uno)

Or even better: do both.  That would give you the most efficient system whereby the main CPU is only involved in getting the count from the timer periodically, and adjusting the PWM value for your servo. The rest is then done by hardware completely asynchronously.

Of course, for this you will want to study [the datasheet](http://ww1.microchip.com/downloads/en/devicedoc/atmel-42735-8-bit-avr-microcontroller-atmega328-328p_datasheet.pdf) so you know how to configure the various hardware modules.


message:
Visual Studio integration with Arduino

I use Visual Studio 2015 extensively for work, so it would seem like a logical choice for getting started with Arduino programming (though my C/C++ is rusty, that may take some time to get back). From what I understand the [Visual Micro Plugin][1] is popular. Is that sort of the de facto choice for those who come from VS? Does it tie into everything so that I can handle debugging, breakpoints, deployment etc from Visual Studio? Much obliged!

  [1]: http://www.visualmicro.com/

body:
I think it is the *de facto* standard for VS (of course the default Arduino IDE is used most).

However, I think some advanced features (like breakpoint if I recall right) is only temporarily for free and you have to pay later for a subscription.

Note however, that debugging/breakpoints are not used often anyway since mostly it's more realtime controlled than PC applications.

If you need breakpoints etc. probably the easiest is to make stubs for some libraries and first develop the application not using Arduino and later use the Visual Micro plugin. [Update: it seems breakpoints are possible with vMirco, I never got them to work though].


body: Use Atmel's Atmel Studio 7. Uses the visual studio shell and is supported by Atmel. Also allows you to import your Arduino Sketches. Once I used it, I stopped using the Arduino IDE.


message:
ESP8266 send TCP HEX packet with 4 chars

I'm building a remote for my WiFi-RGB Lights. I have an ESP8266, which should send one TCP packet with 4 chars.

My code:

    #include <ESP8266WiFi.h>

    const char* ssid     = "Wifi";
    const char* password = "wifikey";

    void WiFiEvent(WiFiEvent_t event) {
      Serial.printf("[WiFi-event] event: %d\n", event);
    }

    void setup() {
      Serial.begin(115200);
      WiFi.disconnect(true);
      delay(1000);
      WiFi.onEvent(WiFiEvent);
      WiFi.begin(ssid, password);
    }

    void loop() {
      delay(1000);
      const uint16_t port = 5577;
      const char * host = "192.168.178.150";
      WiFiClient client;
      client.connect(host, port);
      client.print(char(0x71));
      client.print(char(0x24));
      client.print(char(0x0f));
      client.print(char(0xa4));
      client.flush();
      client.stop();
      delay(5000);
    }

The problem: I send 4 TCP packets, while I should send 1 TCP packet with all 4 chars.

Thanks for your help.

body:
After searching and experimenting on this, I believe the short answer to the question is that you need to send the command string like a buffer of characters AND put your Hex Coded command for the LED controller as an escaped string of characters.

Here is my code (it toggles the LED Controller between Green and Blue every 5 seconds, but you can extend this for other commands and colors as described at http://jpelectron.com/sample/Electronics/WiFi LED control/):

    /*
    Send Commands to LED Controller via Wifi Network and Wemos D1 Board
    */
    #include <ESP8266WiFi.h>

    const char* ssid     = "***yourWifiSSID***"; //Change this value for your network
    const char* password = "***yourWifiPassword***"; //Change this value for your network
    boolean connected = false;
    boolean colorToggle = false;

    void WiFiEvent(WiFiEvent_t event) {
        //Serial.printf("[WiFi-event] event: %d\n", event);

        switch(event) {
        case 3:
            Serial.println("WiFi connected");
            Serial.println("IP address: ");
            Serial.println(WiFi.localIP());
            connected = true;
            break;
        case 6:
            Serial.println("WiFi lost connection");
            connected = false;
            break;
        }

        // 0 : WL_IDLE_STATUS when Wi-Fi is in process of changing between statuses
        // 1 : WL_NO_SSID_AVAILin case configured SSID cannot be reached
        // 3 : WL_CONNECTED after successful connection is established
        // 4 : WL_CONNECT_FAILED if password is incorrect
        // 6 : WL_DISCONNECTED if module is not configured in station mode

    }

    void setup() {
      pinMode(LED_BUILTIN, OUTPUT);     // Initialize the LED_BUILTIN pin as an output
        Serial.begin(115200);
        WiFi.disconnect(true);
        delay(1000);
        WiFi.onEvent(WiFiEvent);
        WiFi.begin(ssid, password);
        Serial.println("");

        // Wait for connection
        while (WiFi.status() != WL_CONNECTED) {
          delay(500);
          Serial.print(".");
        }
        Serial.println("");
        Serial.print("Connected to ");
        Serial.println(ssid);
        Serial.print("IP address: ");
        Serial.println(WiFi.localIP());

    }

    // the loop function runs over and over again forever
    void loop() {
        //if we are connected
        if(connected){
          digitalWrite(LED_BUILTIN, LOW); //Turn on LED on the Board
          turnLEDSOn();
        }
        else
        {
          digitalWrite(LED_BUILTIN, HIGH); //Turn off LED on the Board
          setup();
        }
    }

    void turnLEDSOn() {
        const uint16_t port = 5577;
        const char * host = "192.168.10.2";  //Change to whatever your LED Controller IP is

         WiFiClient client;

         if (client.connect(host, port)) //Try to connect to TCP Server
         {
            Serial.println("Connected to LED Controller... ");
            if (colorToggle)
            { //Green
              char command[] = "\x31\x00\xff\x00\x00\x00\xf0\x0f\x2f";
              client.write((uint8_t *)command, sizeof(command));
              colorToggle = false;
              delay(5000);
            }
            else
            { //Blue
              char command[] = "\x31\x00\x00\xff\x00\x00\xf0\x0f\x2f";
              client.write((uint8_t *)command, sizeof(command));
              colorToggle = true;
              delay(5000);
            }

            Serial.println("Command sent ... "); // command is the color or animation sent to the LED controller
         }
         else
         {
            Serial.println("connection failed ... ");
         }

          if (client.available())
          {
            //Read from LED Controller
            char c = client.read();
            Serial.print(c);
          }

          if (!client.connected())
          {
            Serial.println();
            Serial.println("disconnecting ... ");
            client.stop();
            for(;;);
          }
    }


message:
Compilation Error: "cannot declare 'client' to be of abstract type 'Client'"

I know, it isn't my original code, but I'm using this for a larger project that I am currently working on. I keep getting this error message: "cannot declare 'client' to be of abstract type 'Client'".
here's the code:

    // RoboSapienServer.cpp
    // RobosapienServer - Web enable a RoboSapien
    // Kevin N. Haw
    // http://www.KevinHaw.com/RoboSapienServer.php

    // This project combines the default webserver example in the IDE distribution and Karl Castleton's(http://home.mesastate.edu/~kcastlet) RoboSapienIR (http://playground.arduino.cc/Main/RoboSapienIR).
    // Source code merged from those two sources.

    // Include files
    #include <Ethernet.h>
    #include <string.h>
    #include <WebServer.h>

    //////////////////////////////////////////////////////////////////
    // Begin Web Server specific variable deinitions
    //////////////////////////////////////////////////////////////////

    byte mac[] = { 0xDE, 0xAD, 0xBE, 0xEF, 0xFE, 0xED };

    // KNH, 02/09/2010 - Change IP address to use local subnet at home
    //byte ip[] = { 10, 0, 0, 177 };
    byte ip[] = { 192, 168, 1, 177 };

    // Server for web requests
    EthernetServer server(80);

    // Define field name in the submitted form
    #define SUBMIT_BUTTON_FIELDNAME "RSCmd"

    // String for HTTP request variables
    char pcHttpReqRsCmd[20] = {'\0'};

    volatile int viRobsapienUrlCmd = -1;  // A robosapien command sent over the URL of a webpage HTTP request

    //////////////////////////////////////////////////////////////////
    // Begin Robosapien specific variable deinitions
    //////////////////////////////////////////////////////////////////

    // Some but not all RS commands are defined
    #define RSTurnRight       0x80
    #define RSRightArmUp      0x81
    #define RSRightArmOut     0x82
    #define RSTiltBodyRight   0x83
    #define RSRightArmDown    0x84
    #define RSRightArmIn      0x85
    #define RSWalkForward     0x86
    #define RSWalkBackward    0x87
    #define RSTurnLeft        0x88
    #define RSLeftArmUp       0x89
    #define RSLeftArmOut      0x8A
    #define RSTiltBodyLeft    0x8B
    #define RSLeftArmDown     0x8C
    #define RSLeftArmIn       0x8D
    #define RSStop            0x8E
    #define RSWakeUp          0xB1
    #define RSBurp            0xC2
    #define RSRightHandStrike 0xC0
    #define RSNoOp            0xEF

    // Subset of additional codes pulled from http://www.contrib.andrew.cmu.edu/~ebuehl/robosapien-lirc/ir_codes.htm
    #define RSRightHandSweep  0xC1
    #define RSRightHandStrike2 0xC3
    #define RSHigh5           0xC4
    #define RSFart            0xC7
    #define RSLeftHandStrike  0xC8
    #define RSLeftHandSweep  0xC9

    #define RSWhistle         0xCA
    #define RSRoar            0xCE

    int IRIn = 2;            // We will use an interrupt
    int IROut = 3;           // Where the echoed command will be sent from

    boolean RSEcho = true;    // Should Arduino Echo RS commands
    boolean RSUsed = true;    // Has the last command been used
    volatile int RSBit = 9;   // Total bits of data
    volatile int RSCommand;   // Single byte command from IR
    int bitTime = 516;        // Bit time (Theoretically 833 but 516)
    // works for transmission and is faster
    int last;                 // Previous command from IR

    //////////////////////////////////////////////////////////////////
    // Begin Robosapien specific code
    //////////////////////////////////////////////////////////////////

    // Receive a bit at a time.
    //  NOTE: Unused in the RoboServer aplication
    void RSReadCommand() {
      delayMicroseconds(833 + 208); // about 1 1/4 bit times
      int bit = digitalRead(IRIn);
      if (RSBit == 9) { // Must be start of new command
        RSCommand = 0;
        RSBit = 0;
        RSUsed = true;
      }
      if (RSBit < 8) {
        RSCommand <<= 1;
        RSCommand |= bit;
      }
      RSBit++;
      if (RSBit == 9) RSUsed = false;
    }

    // send the whole 8 bits
    void RSSendCommand(int command) {
      digitalWrite(IROut, LOW);
      delayMicroseconds(8 * bitTime);
      for (int i = 0; i < 8; i++) {
        digitalWrite(IROut, HIGH);
        delayMicroseconds(bitTime);
        if ((command & 128) != 0) delayMicroseconds(3 * bitTime);
        digitalWrite(IROut, LOW);
        delayMicroseconds(bitTime);
        command <<= 1;
      }
      digitalWrite(IROut, HIGH);
      delay(250); // Give a 1/4 sec before next
    }

    // Set up RoboSpapien functionality
    void RSSetup()
    {
      pinMode(IRIn, INPUT);
      pinMode(IROut, OUTPUT);
      pinMode(10, OUTPUT);
      digitalWrite(IROut, HIGH);

      attachInterrupt(0, RSReadCommand, RISING);

      last = RSNoOp;

      // Make robot burp to indicate setup is complete
      RSSendCommand(RSBurp);

    }

    // Loop for RoboSapien functionality
    // Write only functionality - send the command from the web page to the robot, ignoring any input from the remote
    void RSLoop()
    {
      // Has a new command come in from the server?
      if (viRobsapienUrlCmd != -1)
      {
        // New command - send it to robot
        Serial.print("Sending command to RoboSapien: ");
        Serial.println(viRobsapienUrlCmd, HEX);
        RSSendCommand(viRobsapienUrlCmd);

        // Now clear command
        viRobsapienUrlCmd = -1;
      }
    }

    //////////////////////////////////////////////////////////////////
    // Begin Webserver Specific Code
    //////////////////////////////////////////////////////////////////

    // Print ourt MIME and HTML header at top of webpage
    void HtmlHeader(Client client)
    {
      client.println("HTTP/1.1 200 OK");
      client.println("Content-Type: text/html");
      client.println();
      client.println("\n");
      client.println("  <TITLE>Kevin's Arduino Webserver</TITLE>");//
      //  client.println("  <META HTTP-EQUIV=\"refresh\" CONTENT=\"5\">");
      client.println("");
    }

    // Print the footer at the bottom of the webpage
    void HtmlFooter(Client client)
    {
      client.println("");
    }

    // Print a submit button with the indicated label wrapped in a form for the indicated hex command
    void SubmitButton(Client &client, char *pcLabel, int iCmd)
    {
      client.print("<form method=post action=\"/?");
      client.print(iCmd, HEX);
      client.print("\"><input type=submit value=\"");
      client.print(pcLabel);
      client.print("\" name=\"" SUBMIT_BUTTON_FIELDNAME "\">");
      client.println("</form>");
    }

    // Parse an HTTP request header one character at a time, seeking string variables
    void ParseHttpHeader(Client &client)
    {
      char c;

      // Skip through until we hit a question mark (first one)
      while ((c = client.read()) != '?' && client.available())
      {
        // Debug - print data
        Serial.print(c);
      }

      // Are we here for a question mark or did we run out of data?
      if (client.available() > 2)
      {
        char pcUrlNum[3], *pc;

        // We have enough data for a hex number - read it
        for (int i = 0; i < 2; i++)
        {
          // Read and dump data to debug port
          Serial.print(c = pcUrlNum[i] = client.read());
        }
        // Null terminate string
        pcUrlNum[2] = '\0';

        // Get hex number
        viRobsapienUrlCmd = strtol(pcUrlNum, &pc, 0x10);
      }

      // Skip through and discard all remaining data
      while (client.available())
      {
        // Debug - print data
        Serial.print(c = client.read());
      }
    }

    // Set up webserver functionality
    void WebServerSetup()
    {
      Ethernet.begin(mac, ip);
      server.begin();
    }

    // Web server loop
    void WebServerLoop()
    {
      Client client = server.available();
      boolean bPendingHttpResponse = false; // True when we've received a whole HTTP request and need to output the webpage
      char c;  // For reading in HTTP request one character at a time

      if (client) {
        // Loop as long as there's a connection
        while (client.connected()) {
          // Do we have pending data (an HTTP request)?
          if (client.available()) {

            // Indicate we need to respond to the HTTP request as soon as we're done processing it
            bPendingHttpResponse = true;

            ParseHttpHeader(client);
          }
          else
          {
            // There's no data waiting to be read in on the client socket.  Do we have a pending HTTP request?
            if (bPendingHttpResponse)
            {
              // Yes, we have a pending request.  Clear the flag and then send the webpage to the client
              bPendingHttpResponse = false;

              // send a standard http response header and HTML header
              HtmlHeader(client);

              // Put out a text header
              client.println("
Kevin's RoboSapien Webserver
");

              client.println("

");
              client.println("");

              // Create buttons
              SubmitButton(client, "WakeUp", RSWakeUp);
              SubmitButton(client, "Roar", RSRoar);
              SubmitButton(client, "Whistle", RSWhistle);
              SubmitButton(client, "High5", RSHigh5);
              client.println("
");

              client.println("	");

              SubmitButton(client, "LeftArmUp", RSLeftArmUp);
              SubmitButton(client, "LeftArmIn", RSLeftArmIn);
              SubmitButton(client, "LeftArmOut", RSLeftArmOut);
              SubmitButton(client, "LeftArmDown", RSLeftArmDown);
              SubmitButton(client, "LeftArmSweep", RSLeftHandSweep);
              client.println("
");

              client.println("	");

              SubmitButton(client, "RightArmUp", RSRightArmUp);
              SubmitButton(client, "RightArmIn", RSRightArmIn);
              SubmitButton(client, "RightArmOut", RSRightArmOut);
              SubmitButton(client, "RightArmDown", RSRightArmDown);
              SubmitButton(client, "RightArmSweep", RSRightHandSweep);
              client.println("
");

              client.println("

");

              client.print("

URL Hex no: ");
              client.print(viRobsapienUrlCmd, HEX);
              client.println("
");

              // send HTML footer
              HtmlFooter(client);

              // give the web browser time to receive the data
              delay(1);
              client.stop();
            }
          }
        }  // End while(connected)
      }
    }

    //////////////////////////////////////////////////////////////////
    // Begin arduino entry points
    //////////////////////////////////////////////////////////////////

    void setup()
    {
      // open the serial port at 9600 bps:
      Serial.begin(9600);

      // Print greeting
      Serial.println("Kevin's RobSapien Server");

      RSSetup();
      WebServerSetup();
    }

    void loop()
    {
      RSLoop();
      WebServerLoop();
    }

body:
You can't use Client directly like that.  It's just an abstract class.  You have to use one of the classes like EthernetClient or WiFiClient that implements it.

Client is like a shell of a class.  It says that there will be classes that act as clients and will have this basic form.  But it doesn't have any code, just the outline.  The base classes that implement that abstract class like EthernetClient or WiFiClient actually have the code to actually BE a client.


body:
I would guess the problem lies here:

    void HtmlFooter(Client client) {
        client.println("");
    }

(Also the HtmlHeader function)

When you call that function you make a new Client object and copy the contents of your existing object into it. Since Client is pure virtual you can't do that. Instead you should be working with a reference as in the other functions:

    void HtmlFooter(Client &client) {
        client.println("");
    }


message:
Servo FS5106B does not work properly

I was testing out my new Servo FS5106B. Here is the code I used:

    #include <Servo.h>

    Servo servo;
    void setup()
    {
        servo.attach(10);
    }

    void loop()
    {
        servo.write(0);
        delay(1000);
        servo.write(180);
        delay(1000);
    }

After I upload the sketch, the console says:
>Sketch uses 2872 bytes (1%) of your device memory. Total available 253952 bytes. Global variables use 161 bytes (1%) of the dynamic memory, leaving 8031 bytes for local variables. Maximum 8192

The delay between the rotations wasn't 1 second (as I was expecting), but 13 seconds (when I connect *only* a LED and use the delay function, everything works perfectly). Why is that happening?

P.S The power source for the servo is my Arduino-Mega 2560, wich outputs 5V. The model I use for wiring is: [![enter image description here][1]][1]

*Edit 1*:
I tried to execute the program that @ChrisStratton suggested, here an updated code

    #include <Servo.h>
    #define led 22

    Servo servo;

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

        Serial.println("Start!");
        pinMode(led, OUTPUT);
        servo.attach(10);
    }

    void loop()
    {
        digitalWrite(led, HIGH);
        servo.write(0);
        delay(1000);
        digitalWrite(led, LOW);
        servo.write(180);
        delay(1000);
    }

When this program loads, servo does 2 rotations in 0.4 seconds and the LED goes high and low really fast, then anything changes for another 10 seconds, then again the LED goes high and low and the Servo does 2 rotations
  [1]: https://i.stack.imgur.com/nA2rp.jpg

body:
In the official Arduino examples, a servo motor is powered by the 5V pin of the Arduino board. In real life, that is a bad idea.
Your FS5106B has specified about 1A stall current. The average current is less than that, but the start peak current could indeed be 1A.
Could you try to use a seperate power supply of 5V (or 6V) for the servo motor ?

To check if the Arduino resets, you could do a `Serial.begin(9600);` in setup, directly followed by `Serial.println("the sketch has started");`

Some servo motors require different timing. That would not explain the 13 seconds delay, so I assume that your servo motor has normal timing.

Do you use a breadboard ? Sending a current peak through a breadboard (with bad contacts) can cause a lot of voltage spikes.

(*To the other problem solvers: I'm ignoring the 13 seconds and assume that once in a while the servo motor is able to start, just a guess, I could be wrong*).

[ADDED]
@ChrisStratton is trying to tell you this:

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

    void loop()
    {
      digitalWrite( LED_BUILTIN, HIGH);
      delay(1000);
      digitalWrite( LED_BUILTIN, LOW);
      delay(1000);
    }

The next step would be:

    #include <Servo.h>

    Servo servo;

    void setup()
    {
      Serial.begin(9600);
      Serial.println("The sketch has started");
      pinMode( LED_BUILTIN, OUTPUT);
      servo.attach(10);
    }

    void loop()
    {
      servo.write(0);
      digitalWrite( LED_BUILTIN, HIGH);
      delay(1000);

      servo.write(180);
      digitalWrite( LED_BUILTIN, LOW);
      delay(1000);
    }

[ADDED2]
Or even more fun, with a counter (as @ChrisStratton wrote):

    #include <Servo.h>

    Servo servo;

    unsigned int counter;

    void setup()
    {
      Serial.begin(9600);
      Serial.println("The sketch has started");
      pinMode( LED_BUILTIN, OUTPUT);
      servo.attach(10);
    }

    void loop()
    {
      servo.write(0);
      digitalWrite( LED_BUILTIN, HIGH);
      delay(1000);

      servo.write(180);
      digitalWrite( LED_BUILTIN, LOW);
      delay(1000);

      Serial.print("Still alive after ");
      Serial.print(counter);
      Serial.println(" seconds");
      counter += 2;   // two seconds per loop iteration
    }


message:
Interrupt problem...?

I am working on a code including interrupts. They, however, refuse to work, even in this simple code that could be the most basic example of interrupts.

In this simplified extract I have a momentary push button attached to an Arduino Pro Mini's PIN 2, with the other side grounded. I have this code uploaded:

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

    #include <Encoder.h>   // is this library the cause??...

    #define PIN_1 4
    #define PIN_2 3 //interrupt pin    //using these for a rotary encoder, not in this extract
    #define PIN_B 2 //interrupt pin    // the rotary encoder also works as a push-button

    void setup() {
      pinMode(PIN_B, INPUT_PULLUP);
      Serial.begin(9600);
      attachInterrupt(PIN_B, ButtonPressISR, FALLING);
      attachInterrupt(PIN_B, ButtonReleaseISR, RISING);
    }

    void loop() {
      Serial.println("Don't interrupt me");
      delay(10);
    }

    void ButtonPressISR() {
      Serial.println("Yay, I'm pressed!");
      delay(1000);
    }

    void ButtonReleaseISR() {
      Serial.println("Yay, I'm released!");
      delay(1000);
    }

One would expect that without action, the Arduino floods the serial console with "Don't interrupt me". And that's correct.

When I press the button, however, nothing on Earth happens, neither of the interrupt service routines starts. No matter how hard I try, "Yay, I'm pressed" and "Yay, I'm released" never appears on the console output, and the 1 s delay never happens.

The circuit, shown below, is tested with a multimeter, and is error-free. Pin 2 does get pulled down, and back, upon button press/release.

<!-- 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/8L7EY.png)

<!-- End schematic -->

body: Neither delay or print should be used in an interrupt routine as they use interrupts themselves, instead set a flag (usually a volatile variable) and test for that in the loop. Also be aware that due to contact bounce the interrupt will trigger multiple times for each button press.


body:
> They, however, refuse to work,

more accurately, you are unable to make them work.

1. don't delay large amount of time;
2. be careful with calling routines that are also called outside of the isr;
3. one isr for one pin.


message:
Why is the T2 transistor used in Arduino Micro?

I was about to design a small custom board using ATmega32U4, replicating the Arduino Micro. I know that T1 is used to block VUSB when VIN is connected.

But why T2? The gate is 5V, so it will be always OFF! Or does it act as a diode?

Schemtic https://www.arduino.cc/en/uploads/Main/arduino-micro-schematic.pdf

body:
It's known as a "zero drop-out diode". When the power is first applied the body diode of the MOSFET conducts and powers the system. That imposes a (roughly) 0.7V drop on the input voltage.

Once the power gets through the regulator and is regulated to 5V that is then fed back into the gate of the MOSFET, which turns it on (as long as -5V is above the source voltage less the diode drop, so -5.7V minimum [it's a P channel so thresholds etc are negative]). That then bypasses the internal body diode getting rid of the 0.7V drop.

If the input voltage is too low the 5V gate no longer turns the MOSFET on and the body diode blocks any reverse current.


body:
T1 and T2 implement a power supply ORing of the VUSB and VIN voltages. Read [this][1] for extended information.

The body diode of each MOSFET performs the basic ORing function. When the MOSFET is turned OFF it just behaves as a diode. But when the MOSFET is turned ON, the diode is shorted by the conduction channel, thus avoiding its voltage drop (and achieving a behaviour closer to an ideal diode).

So:

 1. When VUSB is present and VIN is not connected (but pulled down to ground by R9), T1 turns ON and the +5V rail is connected to VUSB. Also, T2 turns OFF and the regulator input is isolated from VIN and the regulator simply doesn't operate (thus, avoiding a potential conflict because its output +5V is being forced to VUSB).

 2. When VUSB is not connected and VIN is present, T1 turns OFF and VUSB is isolated from the +5V rail. Also T2 turns ON and VIN is connected to the regulator input, which then regulates the voltage down into the +5V rail.

 3. When both VUSB and VIN are connected, the behaviour is the same as in case 2 above. Because VIN is supposed to be >7V and VUSB approx 5V, T1 will isolate VUSB and avoid a conflict with the regulator output. Also, a VIN >7V will allow T2 to turn on hard enough to bypass the body diode and avoid its voltage drop.

  [1]: http://www.eetimes.com/document.asp?doc_id=1273175&page_number=3


message:
Can I power my shift register with a 12V external power supply and connect only the data, strobe and clear pins to the Arduino digital pins?

I'm using a CD4094 shift register to power my LEDs along with a ULN2003A darlington transistor array. I want to hook up the LEDs to an external power supply of 12V (common anode).

The cathodes of little groups of LEDs will be connected to the ULN2003A which is connected to the shift register which will get its data from the arduino (the digital pins which i assume work at 5V).

My question is, if I connect the Vdd pin of the shift register to the 12V external power supply, will it still function as intended through the Arduino?

body:
No. CD4k devices reference their high and low voltages to a (mostly) fixed ratio of Vdd, so there will be no way for the Arduino to operate the device.

Consider using a TPIC6C595 instead, which combines the shift register and the high-voltage driver into a single device.


message:
GPS Logger Error

I have created a GPS logger code using DFRobot SIM808 library. The tcp code and getGPS codes are working fine. but when integrating the both the code, it failed to upload GPS data to thingspeak. It gets the IP connect to the server, but the get command is not working; and also the GPS data shown as a string. Can anyone please tell me where the problem is?

    /*
    ### Connect TCP and send GET request.
    1. This example is used to test DFRobot_SIM808 GPS/GPRS/GSM Shield's connect TCP and send GET request.
    2. Open the SIM808_TCPConnection example or copy these code to your project
    3. Download and dial the function switch to Arduino
    4. Open serial helper
    5. Waiting for a few minutes, until serial has sent "Connect mbed.org success"
    6. Serial will send "Hello world!"

    create on 2016/09/23, version: 1.0
    by jason
    */
    #include <DFRobot_sim808.h>
    #include <SoftwareSerial.h>

    #define PIN_TX    10
    #define PIN_RX    11
    SoftwareSerial mySerial(PIN_TX,PIN_RX);
    DFRobot_SIM808 sim808(&mySerial);//Connect RX,TX,PWR,

    //make sure that the baud rate of SIM900 is 9600!
    //you can use the AT Command(AT+IPR=9600) to set it through SerialDebug

    //DFRobot_SIM808 sim808(&Serial);

    char buffer[512];

    void setup(){
      mySerial.begin(2400);
      Serial.begin(2400);

      //******** Initialize sim808 module *************
      while(!sim808.init()) {
          delay(1000);
          Serial.print("Sim808 init error\r\n");
      }
      delay(3000);

      //*********** Attempt DHCP *******************
      while(!sim808.join(F("hutch3g"))) {
          Serial.println("Sim808 join network error");
          delay(2000);
      }

      //************ Successful DHCP ****************
      Serial.print("IP Address is ");
      Serial.println(sim808.getIPAddress());

      //************* Turn on the GPS power************
      if( sim808.attachGPS())
          Serial.println("Open the GPS power success");
      else
          Serial.println("Open the GPS power failure");
      delay(2000);
    }

    void loop(){
    //  gps();
      delay(2000);
      tcp();
      delay(2000);
    }

    void tcp(){
        //*********** Establish a TCP connection ************
      if(!sim808.connect(TCP,"api.thingspeak.com", 80)) {
          Serial.println("Connect error");
      }else{
          Serial.println("Connect mbed.org success");
      }

      //*********** Send a GET request *****************
        float lati=sim808.GPSdata.lat;
        float longi=sim808.GPSdata.lon;

        char http_cmd[100];
        sprintf(http_cmd, "GET https://api.thingspeak.com/update?api_key=FF19NVWMPZEWX0XK&field2=%s&field3=%s HTTP/1.0\r\n\r\n\0", lati, longi);

        boolean retValue = true;
        sim808.send(http_cmd, strlen(http_cmd));
        int ret = sim808.recv(buffer, sizeof(buffer)-1);
        if (ret <= 0){
            Serial.println("error receiving");
            retValue = false;
        }
        buffer[ret] = '\0';
        Serial.print(buffer);

      //************* Close TCP or UDP connections **********
      sim808.close();

      //*** Disconnect wireless connection, Close Moving Scene *******
      sim808.disconnect();
    }

    //void gps() {
    //   //************** Get GPS data *******************
    //   if (sim808.getGPS()) {
    //    Serial.print(sim808.GPSdata.year);
    //    Serial.print("/");
    //    Serial.print(sim808.GPSdata.month);
    //    Serial.print("/");
    //    Serial.print(sim808.GPSdata.day);
    //    Serial.print(" ");
    //    Serial.print(sim808.GPSdata.hour);
    //    Serial.print(":");
    //    Serial.print(sim808.GPSdata.minute);
    //    Serial.print(":");
    //    Serial.print(sim808.GPSdata.second);
    //    Serial.print(":");
    //    Serial.println(sim808.GPSdata.centisecond);
    //    Serial.print("latitude :");
    //    Serial.println(sim808.GPSdata.lat, 6);
    //    Serial.print("longitude :");
    //    Serial.println(sim808.GPSdata.lon, 6);
    //    Serial.print("speed_kph :");
    //    Serial.println(sim808.GPSdata.speed_kph);
    //    Serial.print("heading :");
    //    Serial.println(sim808.GPSdata.heading);
    //    Serial.println();
    //
    //    //************* Turn off the GPS power ************
    //    sim808.detachGPS();
    //  }
    //}

body:
First, I would assume you need to call `sim808.getGPS()` to update the GPS data. Not sure why you commented that out.

Normally, when building a `GET` command, you don't include the url (unless going through a proxy).

Last, you need to use `%f` with `sprintf` to format a floating point value.

Something like this might work:

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

    void tcp()
    {
        // Update the GPS data
        float lati, longi;
        if (sim808.getGPS()) {
            lati = sim808.GPSdata.lat;
            longi = sim808.GPSdata.lon;
            sim808.detachGPS();
        }
        else {
            // No gps, abort
            return;
        }

        //*********** Establish a TCP connection ************

        if (!sim808.connect(TCP,"api.thingspeak.com", 80)) {
           Serial.println("Connect error");
           return;
        }
        else {
           Serial.println("Connect mbed.org success");
        }

       //*********** Send a GET request *****************

        char http_cmd[100];
        sprintf(http_cmd, "GET /update?api_key=FF19NVWMPZEWX0XK&field2=%f&field3=%f HTTP/1.0\r\n\r\n\0", lati, longi);
        sim808.send(http_cmd, strlen(http_cmd));
        int ret = sim808.recv(buffer, sizeof(buffer) - 1);
        if (ret <= 0){
            Serial.println("error receiving");
        }
        else {
            buffer[ret] = '\0';
            Serial.print(buffer);
        }

        //************* Close TCP or UDP connections **********
        sim808.close();

        //*** Disconnect wireless connection, Close Moving Scene *******
        sim808.disconnect();
    }