message:
SPI conflict with two shields - IOREF?

**Update:**

I've refactored the code to be very resilient to boards missing or not being able to talk to them. Then I tinkered with a bunch of pins and learned that it all comes down to the IOREF pin being connected to the USB Host shield or not. If it's connected, the USB shield "takes over", allows communication with it, but the CAN shield does not work. If the USB shield IOREF pin is not connected, but the rest of the shield's pins are, CAN works. If I disable the IOREF pin going into the CAN shield (and thus the USB shield also since it's on top), the CAN shield works fine still, but the USB shield does not.

Something happens when the IOREF is powered into the USB board and if it's not powered, you can't talk to it.

**Original post:**

I have the following setup:

 1. Yourduino RoboRED board
 2. Seeed CAN Bus Shield v1.2 http://wiki.seeed.cc/CAN-BUS_Shield_V1.2/
 3. USB Host Shield https://www.arduino.cc/en/Main/ArduinoUSBHostShield

My issue is that if I connect only the CAN bus shield, I can initialize it without any problem, but when I connect the USB host shield on top of the CAN, the CAN shield becomes unresponsive.

I looked into the wiring and per the specs, the following is how the hardware is set up:

 - SPI bus runs on ICSP header for both shield, not on D11, D12 & D13. I could switch it for the CAN bus shield if I wanted/needed to, but I don't believe I shoudl be.
 - The trigger pin for the USB host is D10
 - The trigger pin for the CAN bus is D9 (since it's v1.2 of the board)
 - Both boards have power. USB board is on top since it does not have an ICSP male connector on the top side, only female on bottom.

I started to debug the code and traced down to this CAN bus function in mcp_can.cpp, which I've instrumented with debug:

    INT8U MCP_CAN::mcp2515_setCANCTRL_Mode(const INT8U newmode)
    {
        Serial.print("mcp2515_setCANCTRL_Mode with newmode = ");
        Serial.println(newmode);
        INT8U i;

        mcp2515_modifyRegister(MCP_CANCTRL, MODE_MASK, newmode);

        i = mcp2515_readRegister(MCP_CANCTRL);
        i &= MODE_MASK;
        Serial.println("i & MODE_MASK");
        Serial.println(i);
        Serial.println(MODE_MASK);

        if ( i == newmode )
        {
            return MCP2515_OK;
        }

        return MCP2515_FAIL;
    }

The output when it fails is:

    USB started ok
    past SPI begin
    mcp2515_init called
    mcp2515_setCANCTRL_Mode with newmode = 128
    i & MODE_MASK
    0
    224
    Enter setting mode fall
    res = 1

For reference, this is the mcp2515_modifyRegister function:

    void MCP_CAN::mcp2515_modifyRegister(const INT8U address, const INT8U mask, const INT8U data)
    {
        #ifdef SPI_HAS_TRANSACTION
         SPI_BEGIN();
        #endif
        MCP2515_SELECT();
        spi_readwrite(MCP_BITMOD);
        spi_readwrite(address);
        spi_readwrite(mask);
        spi_readwrite(data);
        MCP2515_UNSELECT();
        #ifdef SPI_HAS_TRANSACTION
         SPI_END();
        #endif
    }

The whole file is here: https://github.com/Seeed-Studio/CAN_BUS_Shield/blob/master/mcp_can.cpp. I've tried setting SPI_HAS_TRANSACTION to `true` with no change in the outcome, though I also don't know exactly what this does.

This is my init:

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

        // init can bus : baudrate = 500k

        if (Usb.Init() == -1)
            Serial.println("OSC did not start.");
        else
            Serial.println("USB started ok");

        delay( 200 );

        while (CAN_OK != CAN.begin(CAN_500KBPS)) {
            Serial.println("CAN BUS Shield init fail");
            Serial.println(" Init CAN BUS Shield again");
            delay(10000);
        }

        Serial.println("CANbus ready");
    }

It seems to have something to do with the registers available for write by the CAN bus library whenever the USB board is or isn't present. The write fails when the USB board is there. Any thoughts as to why or other things to try would be greatly appreciated.

body:
There's a hardware conflict between these two boards which seems to not be resolvable. The solution was to buy the Keyes USB shield, make sure only it has access to pins 9 and 10 from the Arduino and then wire pin 7 (or 8) into pin 9 of the CAN shield, while also properly initializing the CAN shield with that new pin.

Lastly, the Keyes USB shield's ICSP header isn't long enough, so you need to cut 2 mm off the male non-ICSP pins in order to seat it properly on the CAN shield.


sender: user

message:
Software PWM implementation on ATTiny44 screws up timing functions

I've came up with a poor man's implementation of software-based PWM for the ATTINY44 and I'm kinda stuck now. It works but it screws up the timing functions badly (delay, delayMicroseconds) no matter what timer I use for the ISR (timer 1 or 0). The delay in my example is more like 1 second than 100ms. Can somebody point out what I'm doing wrong? :)

    uint8_t pwmled[11] = {0};
    volatile uint8_t currentStep = 0;
    uint8_t p[11] = {PORTA0, PORTA1, PORTA2, PORTA3, PORTA4, PORTA5, PORTA6, PORTA7, PORTB0, PORTB1, PORTB2};

    void initTimer1() {
      cli();
      TCCR1B = (1 << WGM12) | (1 << CS10);
      OCR1A = 64;
      TIMSK1 = (1 << OCIE1A);
      sei();
    }

    ISR(TIM1_COMPA_vect) {
      if (currentStep < 100)
        currentStep += 1;
      else
        currentStep = 0;
      for (uint8_t x = 0; x <= 10; x++)
        (currentStep < pwmled[x]) ? (x < 8 ? PORTA |= (1 << p[x]) : PORTB |= (1 << p[x])) : (x < 8 ? PORTA &= ~(1 << p[x]) : PORTB &= ~(1 << p[x]));
    }

    void setup() {
      initTimer1();
      for (int i = 0; i <= 10; i++) {
        pinMode(i, OUTPUT);
        pwmled[i] = 1;
      }
    }

    void loop() {
      pwmled[random() % 11] = random() % 100;
      delay(100);
    }

sender: assistant

body:
What you are doing wrong is:

The problem is your interrupt handling routine **lasts too long**. Since inside ISR() interrupt flag is automatically cleared, timer0 interrupts are being missed and `delay()` depends upon timer0 interrupts.

To confirm the problem is ISR, **remove the for loop** and just toggle one pin instead. I bet the delay will then be as it should.

Try to put `sei()` at the beginning of your ISR to see what is going to happen with the timming of the delay - but **that is not the right way**.

Instead of using `delay()` (based on timer0) you can count the number of timer1 interrupts but **ISR routine must not last longer than the time between two interrupts** and your ISR spends **quite a few** T-states inside the for loop. A rule of a thumb is ISR has to be very short (**fast**) - unless you **really** know what you are doing. For example, in one of my devices I am using a very long ISR routine (in fact the firmware consists of only the ISR - there is only `sleep_mode();` in main) for which I know it **sometimes** lasts longer than the time window between interrupts and I know some of the interrupts are occasionally being missed. However, these few missed interrupts are not critical to that particular application and I am sure the interrupts are being missed rarely.

You could change `OCR1A` value to increase the time between interrupts but then you would have lower PWM frequency.


message:
How to fix 12V RGB LED Strip connection to NodeMCU?

I am trying to hook 12V RGB Led Strip (LTROP SMD 5050 RGB LED Light Strip) to a NodeMCU unit. I know there are many different tutorials on this and I am very new to wiring and electric circuits.

I used BUZ91A n-MOSFETs and 150 Ohm resistors for each of the RGB channels, and the board is using it's own power supply via usb.

[![my wiring][1]][1]

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

I use very simple code to check if the setup works:

    #define REDPIN D3
    #define GREENPIN D1
    #define BLUEPIN D2

    #define FADESPEED 5     // make this higher to slow down

    void setup() {
      pinMode(REDPIN, OUTPUT);
      pinMode(GREENPIN, OUTPUT);
      pinMode(BLUEPIN, OUTPUT);
      Serial.begin(115200);
      Serial.println("Finished setup");
    }

    void loop() {
        analogWrite(REDPIN, 800);
        analogWrite(BLUEPIN, 1020);
        analogWrite(GREENPIN, 400);
        delay(100);

      Serial.println("Finished loop");
    }

I suspect nothing works because NodeMCU and the LED are using different power sources and the fact they have common ground doesn't seem to be everything required.

body:
So now we finally know the reason is **MOSFET's threshold voltage is too high**. The solution is to drive the gate with NPN transistor (you can use BC547 or 2N5551 or similar). You have to connect it's collector to 5 V and it's emitter to GND. Put 10k or 100k resistor between 5 V and the collector, connect the collector to MOSFET's gate and GPIO to the base of NPN transistor. Put some resistor between GPIO and the base of the transistor, maybe 4k7 or similar.

Note:
**HIGH** from GPIO will switch **off** the LED strip and **LOW** will switch it **on**.

Another solution is to use MOSFET with lower threshold voltage.

**EDIT:**
If you want to avoid adding NPN transistor you can use **NTD5867NL** MOSFET which has max threshold voltage 2.5 V so it will for sure work with 3.3 V at the gate but is rather expensive (about $4). Much better solution is adding cheap NPN transistor.

**EDIT:**
Here is the schematic:

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

<!-- End schematic -->

**EDIT:**
Here is the correct wiring:
[![enter image description here][1]][1]

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


message:
Arduino leonardo. Encoder mouse movement

I want to connect my sensonrs to an arduino leonardo.

The principal idea is use it like a scratch (like dj hero or beatmania??), if I move the scratsh up, the mouse will go up ( y Axis ), and if it go down, the y Axis down.

The middle is for gnd and the other four to 0 to 3 pin in the arduino.

So my problem is I am not sure about the conecction and also the code to run my program, beacuse all the thing that i try to do, had no work in my computer.

[![Board][1]][1]

[![Sensors][2]][2]

  [1]: https://i.stack.imgur.com/ZKlTe.jpg
  [2]: https://i.stack.imgur.com/Sw9X7.jpg

body: That's a quadrature encoder implemented using photo interrupters. Use a DMM to suss out which half of each is the diode and which is the phototransistor, connect both halves as you would were they independent, and decode the quadrature output.


message:
Do we need to burn bootloader in new Atmega328p before uploading the arduino code

I have an arduino code which is working fine. Now I am planning to make a PCB out of it. But I do not want to use the complete Arduino board. I just want to use the `Atmega328p` microcontroller. So my plan is to connect the USBasp programmer to the new Atmega328p and upload the code. So before this code, do I need to upload the bootloader or uploading the code first will run fine.

body: The only thing the bootloader for the ATmega328P does is to enable UART programming. If you are only using ISP then there is no need to have the bootloader.


body:
**Tools > Burn Bootloader** in the Arduino IDE does two things:

- Set fuses according to the settings in boards.txt for the **Tools > Board** selection
- Install the bootloader.

The latter is pointless since when you do an **Upload Using Programmer** the bootloader will be overwritten but the former is very important to do the first time you use a new chip(or anytime you want to change the fuses) to be sure that the correct fuses are set, which likely will be different from the default settings of the chip when you get it. **Upload Using Programmer** does not set fuses, the only way to do this via the Arduino IDE is **Tools > Burn Bootloader**.

So yes, you should Burn Bootloader.


message:
Adafruit feather M0 wifi firmware update

I just noticed that the firmware on the m0 wifi might need updating but says not to use the provided updater, how do you update the firmware so ?

Thanks

body:
**USE AT YOUR OWN RISK**
Here's what I did... (maybe some steps not necessary, but this worked for me)

1) First run the "CheckWifi101FirmwareVersion" found in the Arduino WiFi 101 library.

 - NOTE: You need to add in the `WiFi.setPins(8,7,4,2);` after `void setup() {`
 - If it's backlevel (before 19.4.4), then

2) Download the Adafruit WiFi101 Updater on github (
   https://github.com/adafruit/WiFi101-FirmwareUpdater/archive/master.zip
   )

3) Install the "FirmwareUpdater" from the Arduino WiFi 101 Library

 - Add in the recommended changes (even if it's the defaults)

        #define WINC_CS 8
        #define WINC_IRQ 7
        #define WINC_RST 4
        #define WINC_EN 2

    and the usual `WiFi.setPins(8,7,4,2)` after void `setup() {`

4) Copy the firmware you wish to flash to same directory as "winc1500-uploader.exe"

5) Run the command:
> winc1500-uploader.exe --port [YourComPort] --firmware [YourFirmwareFileName].bin

So for example I did:
> winc1500-uploader.exe --port COM9 --firmware m2m_aio_2b0.bin


message:
Can i power Esp8266-Nodemcu with a solarpanel + usb-powerbank?

I was asking myself wether it's possible to power my nodemcu board (version 3) with a usb powerbank, like a smartphone, but the powerbank should then be recharged by a solar panel. So this is basically like it could look like:
[![enter image description here][1]][1]

I know, there should be some charge regulation, but i would just like to know, if that circuit would be able to charge the powerbank?
According to the [Hardware Layout][2], it could be possible, but i am not definetly sure about that. Maybe you can give me some input about that.

  [1]: https://i.stack.imgur.com/IGrkY.png
  [2]: https://raw.githubusercontent.com/nodemcu/nodemcu-devkit/master/Documents/NODEMCU_DEVKIT_SCH.png

body:
You can **not** connect a solar panel just like that. There is a voltage regulator at the output of the power bank to get 5V out of the some number of Li-Ion cells and you can not charge the power bank backwards through the output. You must charge Li-Ion cells directly, that is why there is a separate input used for charging the battery pack. If you want to have a battery backup for NodeMCU you have to use a charging board and a MOSFET to switch off the battery output whenever the battery is being charged. The charger must supply enough power for both charging the battery and supplying NodeMCU.

When there isn't voltage at the charger (and NodeMCU) input, MOSFET should switch on the output from the battery and you have to use a diode (in a similar way you used it in your schematics) to prevent beckfeeding when working on battery. It should be Schottky diode with low forward voltage.


message:
What means the ~ symbol in the code?

I'm learning Arduino (school and from myself).

We have the following code:

    temp = Wire.read();
    temp = ~temp;
    temp = temp - 1;

This code is made to read, then print positive and negative values from a temp sensor. If you need more parts of the code, let me know.

I don't understand what does the `~` symbol, can someone help me?

Thanks.

body: As always, `~` in C++ is bitwise negation.


message:
How to prevent ATTiny program from running after I flash it with Arduino?

I am making a simple voltage regulator. The whole idea is to just use ADC to read voltage on output side and based on the result, adjust PWM power. I am using PWM on physical pin 5. That's the same pin as the one connected to Arduino pin 10 on this image below:

![image description](https://i.stack.imgur.com/ggIkw.png)

This means that if I try to flash the program, ATTiny will start to put PWM power into my Arduino. I don't want that to happen. How can I flash the program safely? Can I do something to prevent it from starting?

body:
> This means that if I try to flash the program, ATTiny will start to put PWM power into my Arduino. I don't want that to happen.

Why do you think that is a problem? The "PWM power" cannot be any higher than the supply voltage, and that is 5V. The Arduino has no problem with you providing a 5V PWM signal to an input pin.

The only time it could be a problem is if the pin you are sending the PWM to is set to an output, in which case you could risk overloading the pin. To get around that you just need to insert a small resistor between the ATTiny's pin and the Arduino's pin. 330Ω or so should do it. Just enough to limit the current to a safe value (< 20mA) but small enough that it won't interfere with the programming communication.

A well design schematic for an Arduino ICSP programmer would have had these resistors in all the data communication lines anyway.


body: That isn't a problem but if you **really** want to prevent ATtiny generating the PWM signal right after flashing the firmware, then you might add a jumper to some free µC input and put the while loop at the beginning of the program which reads that input and waits until you remove the jumper. For example, you could enable internall pull-up on some free input and put the jumper from that pin to GND. Then in the code you can just wait for the input to become high and then proceed with the rest of the code. Then you can just insert the jumper, flash the firmware, remove the connections between ATtiny and Arduino and then remove the jumper.


body: The Arduino-as-ISP sketch will turn all the OUTPUT pins, connected to the ATTiny, [back to **INPUT**](https://github.com/arduino/Arduino/blob/2bfe164b9a5835e8cb6e194b928538a9093be333/build/shared/examples/11.ArduinoISP/ArduinoISP/ArduinoISP.ino#L433-L439). That way nothing bad can happen, when the ATTiny drives those pins HIGH of LOW.


message:
RF24 Network and Payload

i struggle to figure out the max payload for the RF24 Network library without payload fragmentation.
It uses a NetworkHeader with the Attributes from_node, to_node, id, type and reserved.
This must be send to and lowers the amount of Bytes of the payload.

Can any one tell me how many Bytes I can write without sending two packages?

body:
According to the source code:

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

    const static unsigned int max_frame_payload_size = MAX_FRAME_SIZE-sizeof(RF24NetworkHeader);

that would be `24 bytes`. Maximum lenght of payload for NRF24L01+ is 32 bytes and the `RF24NetworkHeader` seem to be 8 bytes long. So you can send up to 24 bytes in one package.

**EDIT:**
Here is the stripped `RF24NetworkHeader` declaration code from which can be seen `sizeof(RF24NetworkHeader)` is 8 bytes.

    struct RF24NetworkHeader {
      uint16_t from_node;   // 2 bytes
      uint16_t to_node;    // 2 bytes
      uint16_t id;     // 2 bytes
      unsigned char type;   // 1 byte
      unsigned char reserved;  // 1 byte
      static uint16_t next_id;  // static member doesn't count for sizeof()
      RF24NetworkHeader() {}
      RF24NetworkHeader(uint16_t _to, unsigned char _type = 0): to_node(_to), id(next_id++), type(_type) {}
      const char* toString(void) const;
    };


message:
Can I use a mobile charger (output 5V) to power an Arduino Uno?

I have made a home automation Arduino project using an HC-05 Bluetooth module. I want to power my Arduino from the main AC supply. Can I use a mobile charger/adapter to power it? Or should I buy a 12v adapter, and solder it to a barrel connector that fits the Arduino input?

body:
Yes you can, simply connect the 5V VCC wire directly to VCC and connect GND to GND.

If using a 12V charger, then connect VCC to Vin.

**DON'T FORGET GND TO GND**


body: Yes, you can. Both options are valid.


body: Yes you can use any options that you have mentioned in your question. One can say your question is your answer.


body:
> Can I use a mobile charger/adapter to power it?

The answer is almost yes: I use a phone charger myself.

Two reasons that it may not work out:

1. There are lots of unsafe, non-isolated, cheap phone chargers out there. Stay away from them. Use a brand name one that came with your phone.

2. Try to stay away from the QC2.0 or QC3.0. they are intelligent and negotiate the output voltage on the phone, up to 9 or 12v. They are compatible with non smart load but you don't want to run the risk.


body:
Yes you can,
I tried with a sony 5V 850mA batery, it works.

I recommend you a multimeter if you haven`t had one before.


body:
I am in the middle of this problem now and it seems the two out of three chargers I tried attempt to negotiate the voltage with my Arduino system. Those are Huawei and Meizu ones designed to be used with multiple devices of their respective brands. The multimeter reads solid 5.2V output before I flip the switch to Arduinos. Once I flip the switch the multimeter starts jumping hectically from 1.8 to 2.6v and all the LEDs on Arduinos and other components start flashing like a Christmas tree. Browning out, I assume. The adapter that works is a really cheap nameless one that I got for free in some package.

Plugging Arduinos into the battery bank and the charger into that battery bank seems to be a very stable and versatile solution that hasn't created any problems for me yet. Except that most battery banks have trouble producing over 2 amperes of current if your system needs that much.


message:
Arduino-ESP8266 socket

I am programming an ESP8266 module via Arduino IDE. I basically have to use it as a server that can light up a led when a client sends a request.

This is okay but I have to implement it with a NONCE and AES encryption system to prevent replay attacks. My problem is that my esp server has to send a value to a client but I only saw the ESP as a data receiver and I can't send custom strings.
This is my code but it does not work because I have problems with the `serverClients[i].write(randomstr,4);` function

I highlighted the non working part of the code

    #include <ESP8266WiFi.h>

    #define RANDOM_REG32  ESP8266_DREG(0x20E44)
    #define MAX_SRV_CLIENTS 3
    const char* ssid = "********";
    const char* password = "********";

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

    void setup() {
    Serial.begin(115200);
    WiFi.begin(ssid, password);
    delay(5000);
    Serial.print("\nConnecting to "); Serial1.println(ssid);
    server.begin();
    server.setNoDelay(true);
    Serial.print("Ready! Use 'port ");
    Serial.print(WiFi.localIP());
    Serial.println(" 7000' to connect");
    }

    void loop(){
    uint8_t i;
    if (server.hasClient()){
    for(i = 0; i < MAX_SRV_CLIENTS; i++){
    if (!serverClients[i] || !serverClients[i].connected()){
    if(serverClients[i]) serverClients[i].stop();
    serverClients[i] = server.available();
    continue;
    }
    }
    //no free spot
    WiFiClient serverClient = server.available();
    serverClient.stop();
    }
    for(i = 0; i < MAX_SRV_CLIENTS; i++){
    if (serverClients[i] && serverClients[i].connected()){
    if(serverClients[i].available()){
    while(serverClients[i].available()) Serial.write(serverClients[i].read());

    //THIS IS THE NON WORKING PART
    long randNumber = RANDOM_REG32 % 10000;
     Serial.println(randNumber);
    String randomstr = String(randNumber);
     serverClients[i].write(randomstr,4);
    }
    }
    }

    if(Serial.available()){
    size_t len = Serial.available();
    uint8_t sbuf[len];
    Serial.readBytes(sbuf, len);

    for(i = 0; i < MAX_SRV_CLIENTS; i++){
    if (serverClients[i] && serverClients[i].connected()){
    serverClients[i].write(sbuf, len);
    delay(1);
    }
    }
    }
    }

I guess I have some problems with char arrays, strings, etc... but I can't make it work

body:
Replace the non working code with this and it will compile:

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

    long randNumber = RANDOM_REG32 % 10000;
    Serial.println(randNumber);
    size_t length = 4;
    char randomstr[length];
    itoa(randNumber, randomstr, 10);
    serverClients[i].write(randomstr, length);


message:
Arduino with two (or more) push buttons

I am trying modify this setup for two push buttons https://www.arduino.cc/en/Tutorial/Button.

The code seems rather trivial

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

    int yellowButtonPin = 2;
    int blueButtonPin = 4;

    int yellowButtonState = 0;
    int blueButtonState = 0;

    void setup(){
      Serial.begin(9600);
      pinMode(yellowButtonPin,INPUT);
      pinMode(blueButtonPin,INPUT);
    }

    void loop(){
      yellowButtonState = digitalRead(yellowButtonPin);
      blueButtonState = digitalRead(blueButtonPin);
      if (yellowButtonState == HIGH && blueButtonState == HIGH){
        Serial.write(3);
      }
      else if (yellowButtonState == HIGH && blueButtonState == LOW){
        Serial.write(2);
      }
       else if (yellowButtonState == LOW && blueButtonState == HIGH){
        Serial.write(1);
      }
      else {
        Serial.write(0);
      }
    }

My problem is that there are several ground pins on the Arduino, but only one 5V pin, so I can't just simple double the circuits. Connecting the two circuits to different grounds but the same 5V didn't work out, although it seemed to be a good idea. How should I do this properly? To be honest, I actually would want to have three buttons, but I guess going from two to three will be trivial after going from one to two.

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

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

body:
Learn about:

Built-in pullup resistors in Arduino
Debouncing

and checks this code: https://blog.adafruit.com/2009/10/20/example-code-for-multi-button-checker-with-debouncing/


message:
Arduino to arduino serial communication without a library

So I'm trying to send an array from one arduino to another through serial communication, without using the software serial library. The arduinos are wired rx->tx, tx->rx and ground to ground. I have a struct which holds the array of data and 2 test characters. The entire struct is then sent 1 char at a time. The receiver then receives 1 char at a time, re-calculates the test chars and if the xor of the sent and calculated tests chars is 1 then we assume an error exists and turn on a red LED. If no error exists then we turn on a green LED. I'm having some issues with my code however. It never sends any data to the 2nd arduino. Can anyone see any reason why?

Sender:

    #include <avr/io.h>
    #include <util/delay.h>
    #include <string.h>

    #define F_CPU 16000000L
    #define BAUD_RATE 9600
    #define MYUBRR (F_CPU / 16 / BAUD_RATE) - 1
    #define END_OF_MESSAGE 47
    #define END_OF_SECTION 35
    #define START_OF_MESSAGE 2
    #define _BV(bit) (1<<(bit))

    struct packet{
     /*Packet to send a part of the message. */
     char *data;
     char vert_check;
     char horz_check;
    };

    void serialInit()
    {
     UBRR0H = (char) (MYUBRR>>8);
     UBRR0L = (char) MYUBRR;
     UCSR0C = (3 << UCSZ00);
     UCSR0B = (1 << RXEN0) | (1 << TXEN0);
    }

    unsigned char serialCheckTx()
    {
     return(UCSR0A & _BV(UDRE0));
    }

    void serial_send(unsigned char DataOut)
    {
     while(serialCheckTx() == 0){;}
     UDR0 = DataOut;
    }

    int isOddParity(unsigned char myChar) {
     int parity = 0;
      for (myChar &= ~0x80;  myChar != 0;  myChar >>= 1) {
            parity ^= (myChar & 1);   // Toggle parity on each '1' bit.
       }
       return parity;
    }

    int main(void)
    {
     serialInit();
     char hozcheck, vertcheck;
     /* Add message to array below to send
      * Initialised to toets.
      */
     char *s = {'T', 'o', 'e', 't', 's'};
     struct packet sendpacket;
     sendpacket.data = s;
     hozcheck = 0;
     for(int i=0; i<strlen(s); i++){
      hozcheck += s[i];
     }
     vertcheck = (isOddParity(s[0]) + '0');

     sendpacket.horz_check = hozcheck;
     sendpacket.vert_check = vertcheck;

     serial_send(START_OF_MESSAGE);
     serial_send(sendpacket.horz_check);
     serial_send(END_OF_SECTION);
     serial_send(sendpacket.vert_check);
     serial_send(END_OF_SECTION);
     for(int j=0; j<strlen(s); j++){
      serial_send(s[j]);
     }
     serial_send(END_OF_MESSAGE);
    }

Receiver:

    #include <avr/io.h>
    #include <util/delay.h>
    #include <string.h>

    #define END_OF_MESSAGE 47
    #define START_OF_MESSAGE 2
    #define F_CPU 20000000L
    #define BAUD_RATE 9600
    #define MYUBRR (F_CPU / 16 / BAUD_RATE) - 1
    #define _BV(bit) (1<<(bit))
    #define START_OF_MESSAGE 2
    #define END_OF_MESSAGE 47
    #define END_OF_SECTION 35

    struct packet{
     char *data;
     char vert_check;
     char horz_check;
    };

    void serialInit()
    {
     UBRR0H = (char) (MYUBRR>>8);
     UBRR0L = (unsigned) MYUBRR;
     UCSR0C = (3 << UCSZ00);
     UCSR0B = (1 << RXEN0) | (1 << TXEN0);
    }

    unsigned char serialCheckRx()
    {
     return(UCSR0A & _BV(RXC0));
    }

    unsigned char serialReceive()
    {
     while (serialCheckRx() == 0){;}
     return UDR0;
    }

    void *array_concat(char *a, int an, char b){
     int s = sizeof(char);
     char *p = malloc(s * (an + 1));
     memcpy(p, a, an*s);
     memcpy(p + an*s, b, s);
     return p;
    }

    int isOddParity(unsigned char myChar) {
     int parity = 0;

      for (myChar &= ~0x80;  myChar != 0;  myChar >>= 1) {
         parity ^= (myChar & 1);   // Toggle parity on each '1' bit.
       }
       return parity;
    }

    int main(void)
    {
     DDRB = 0b111111;
     serialInit();
     char tmp = 0, recvert = 0, rechoz = 0, *s, testhoz, testvert;
     int testbit = 0;
     /*to rebuild our packages*/
     struct packet packet1;
    wait:
     while((tmp = serialReceive()) != 2){
      goto wait;
     }

     while((tmp = serialReceive()) != 35){
      /*Should be a single char for horizontal*/
      rechoz = tmp;
     }
     while((tmp = serialReceive()) != 35){
      /*Should be a single char for "vert" parity*/
      recvert = tmp;
     }
     while((tmp = serialReceive()) != 47){
      /*While input is not end of message grow s*/
      s = array_concat(s, strlen(s), tmp);
     }

     packet1.data = s;
     packet1.vert_check = recvert;
     packet1.horz_check = rechoz;
     testhoz = 0;
     for(int i=0; i<strlen(s); i++){
      testhoz += s[i];
     }
     testvert = ((isOddParity(s[0])) + '0');
     if((packet1.vert_check ^ testvert) == 1)
      testbit = 1;
     if((packet1.horz_check ^ testhoz) == 1)
      testbit = 1;
     if(testbit == 1){
      /*RED LED*/
      PORTB = 0b100000;
     } else {
      PORTB = 0b010000;
     }
     free(s);
    }

body:
Not sure it has a bearing on your problem or not, but I can't help highlight this:

    wait:
        while((tmp = serialReceive()) != 2){
            goto wait;
        }

That has to be the the most evil piece of code ever written in the history of mankind. I'm sorry, but it is.

    while((tmp = serialReceive()) != 2);

is all you need. Or if you must be "pedantic":

    while((tmp = serialReceive()) != 2) {
        continue;
    }

There is never any call to use `goto` (I don't know why it was ever even included in C), and certainly not to re-run a `while` loop that is going to re-run itself anyway.

----

In your receiver you are using dynamic memory, and doing it extremely badly.

First you start out with a pointer

    char *s;

Then when you receive a data character you pass that pointer to your `array_concat()` routine as the source for where to copy data from:

    s = array_concat(s, strlen(s), tmp);

You are at that point asking it for the length of the string in an undefined pointer, which is itself undefined. It could be 0, it could be 65535, or it could be anywhere in between.

Then in array_concat you allocate memory to a pointer depending on that string length (the Uno doesn't have 65535 bytes of RAM, so anything more than the available memory will fail to allocate). And then you copy that number of bytes from the undefined source to the (possibly undefined) destination. That will then make all sorts of horrible things happen.

Then, assuming you even get that far, you return the new pointer and immediately give it to `s`.

Next iteration (assuming the first iteration worked) you do it all again, but now you have lost what `s` used to point to. That memory is gone for good. You have created a memory leak.

So you need to:

1. Make sure `s` is initialized to NULL
2. Do not use `strlen()` since you aren't working with a string but an array of data - instead maintain a count of the number of bytes received
3. Only do any copying of data if `s` actually points to some valid data (not NULL)
4. `free()` the old data pointer once you have finished copying the data (if it was pointing to real allocated memory)
5. Don't use `memcpy` to copy one byte - or if you must, then pass it the *address* of the byte to copy, not the byte itself - otherwise it will try and copy data from the location specified by the value of the byte, which really isn't what you want.

TBH I wouldn't use any dynamic memory at all. Instead I would stick to fixed size arrays that are big enough to hold the longest message you will send / receive. It's less fraught with danger, though it can be more wasteful of RAM.

Alternatively, if you do want to use dynamic memory, then send the length of the data with the header of your packet and allocate all the memory you need in one `malloc()` call before receiving all the data.


body:
One obvious problem with the code is that `s` is not 0-terminated. Taking `strlen` of such string techically is an __Undefined Behaviour__, and all bets are off.

I can only speculate that it does return something larger than the max value an integer may hold (keep in mind that it returns `size_t`). It means that the loop

    for(int i=0; i<strlen(s); i++){
        hozcheck += s[i];
    }

is in fact infinite, and the program neve got a chance to send _anything_.


message:
Measuring the distance covered by a car

I am currently working on developing an RC car that is controlled by an Arduino .

I would like to add a function that can calculate the distance covered by the car without using a GPS !

what are the available alternatives ?

body:
- The cheap and easy way. Doesn't work all the time though. This method uses an ultrasonic sensor (such as the HC-SR04). You mount it on the car's front bumper and calculate the distance from the car and the wall. Then from the start point, calculate how much distance has been covered. This method is flawed in the way that you cannot do this unless there is a wall in front of the car.

- Rotary encoder, put this on the wheel of your robot, then calculate the circonference of the wheels. Then calculate, with the number of rotation made and the circonference of the wheel, the distances that has been made. Some cars use this to calculate the cars speed. It is quite effective.


message:
Using timer0 on Arduino Uno

I am trying to find a simple timer0 interrupt example, but none of those work. Neither this code which I tried to run:

    boolean toggle0 =0;

    void setup() {
    pinMode(8, OUTPUT);
      cli();

      // Set timer1 interrupt at 1 Hz
      TCCR1A = 0; // Set entire TCCR1A register to 0
      TCCR1B = 0; // Same for TCCR1B
      TCNT1  = 0; // Initialize counter value to 0

      // Set compare match register for 1 Hz increments
      OCR1A = 15624;// = (16*10^6) / (1*1024) - 1 (must be <65536)

      // Turn on CTC mode
      TCCR1B |= (1 << WGM12);

      // Set CS12 and CS10 bits for 1024 prescaler
      TCCR1B |= (1 << CS12) | (1 << CS10);

      // Enable timer compare interrupt
      TIMSK1 |= (1 << OCIE1A);

      sei();
    }

    ISR(TIMER0_COMPA_vect){  // Change the 0 to 1 for timer1 and 2 for timer2
      if (toggle0){
        digitalWrite(8,HIGH);
        toggle0 = 0;
      }
      else{
        digitalWrite(8,LOW);
        toggle0 = 1;
      }
    }

    void loop() {

    }

What am I doing wrong?

body:
The main problem is you are using the wrong interrupt handler. You are setting up Timer1, but the interrupt handler is for Timer0:

    boolean toggle0 = 0;

    void setup() {
    pinMode(8, OUTPUT);
      cli();
    //set timer1 interrupt at 1Hz
      TCCR1A = 0;// set entire TCCR1A register to 0
      TCCR1B = 0;// same for TCCR1B
      TCNT1  = 0;//initialize counter value to 0
      // set compare match register for 1hz increments
      OCR1A = 15624;// = (16*10^6) / (1*1024) - 1 (must be <65536)
      // turn on CTC mode
      TCCR1B |= (1 << WGM12);
      // Set CS12 and CS10 bits for 1024 prescaler
      TCCR1B |= (1 << CS12) | (1 << CS10);
      // enable timer compare interrupt
      TIMSK1 |= (1 << OCIE1A);

      sei();
    }

    ISR(TIMER1_COMPA_vect){  //change the 0 to 1 for timer1 and 2 for timer2
      toggle0 = !toggle0;
      digitalWrite(8, toggle0);
    }

    void loop() {

    }


body:
Arduino timers are reserved for buid-in functions:

Timer0 is reserved fire a millisecond interrupt for the millisecond counter
Timer1 is reserved for measuring time passed since the last reboot
Timer2 is reserved for pwm timing

So, using these timers is not a good suggestion if you plan to use above options. For me, Timer0 seems a good choice, as microsecond timing is a bit of an overkill.

Here you may find your solution:
https://learn.adafruit.com/multi-tasking-the-arduino-part-2/timers


message:
Difference in Arduino pin distance

I have an Arduino Uno rev 3. Today i tried to mount a breadboard as a shield for my Arduino on top of it. I plugged in the pin headers i bought and was surprised that the breadboard won't fit. As you can see in the picture below the distance between Vin and A0 is exactly the size of a pin, but the distance between pin 7 and 8 is less than that and so the breadboard won't fit on this side. What's the reasoning behind this (in my eyes) bad design ?[![Arduino Uno rev3 with pin header][1]][1]

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

body:
It is a mistake that became a feature for polarizing the shields: forum.arduino.cc/index.php?topic=117441.0

In an [2008 discussion][1] Massimo says:

> "I made that mistake, when I made the first arduino board."

 at http://forum.arduino.cc/index.php?topic=22737.msg171839#msg171839
with: [![enter image description here][2]][2]

  [1]: http://forum.arduino.cc/index.php?topic=22737.msg171839#msg171839
  [2]: https://i.stack.imgur.com/wGgQT.jpg


message:
2G/3G vs 4G/LTE Cell Connectivity for Sensor Prototype?

Would love any advice on Arduino cell connectivity. From what I understand:

* **2G (GSM/GPRS)** is a dying technology. AT&T is shutting down its 2G network on Jan 1, 2017.
* **2G (CDMA)** will have a longer lifespan than GSM in the U.S., although the options for CDMA modules are much more limited than GSM.
* **3G** has poorer coverage than 2G and is no longer growing.
* **4G** is overkill but is also future-proofed.
* **4G LTE** ^ ditto

I am prototyping sensors that will send GPS/accel/gyro/temp data to a server every 30 seconds or so. They will be in the U.S., operate outside of wifi range, and likely not move very much (roaming isn't a factor).

Am I right in ruling out 2G GSM at this point? From what I've seen, the AT&T 4G LTE IoT Dev Kit looks like a decent option but this is the first time I've worked with IoT devices so any suggestions are welcome (http://cloudconnectkits.org/product/att-cellular-iot-starter-kit).

body:
2G GSM/GPRS are almost dead in the US. CDMA is still working and it would be supported atleast till 2020 becaasue it is used in M2M devices. 3G is still one of the most widely used networks and it has great coverage and it would not likely be phased out till 2024. 4G is widely deployed now and is the future.

Coming back to this from the perspective of developing hardware projects/products and availability of module for DIY use.

**2G chip-sets** are very cheap (~$10) and easily available with lots of documentation. Example 2g module [here][1]

**3G modules** have been in the market for a little while and there are a couple of modules at a good price-point with decent documentation. Example 3g module [here][1]

4g is still bleeding edge and there are not a lot of modules available for DIY users with great documentation and at a good price. I was able to find one with good documentation [here][2].

There are a couple of other factors that come in play when you are working on a project. One is just the support and documentation around the hardware. These modems usually need a good library built around them which can handle most of the functionality and most of the time, the manufacturer gives just a datasheet specifying what all the functionality is and the user is supposed to build the libraries for them in the platform of their choice. [Here is adafruit's][4] library for the cellular module to show you the complexity. Also, when you are just using a few of these then the modules are just building blocks and it usually makes sense to use the modules with the best possible support around them.

Tl;dr, use a 3G module with good software support for your platform.

  [1]: https://www.adafruit.com/products/3147
  [2]: https://www.cooking-hacks.com/4g-gps-3g-gprs-gsm-gps-lte-wcdma-hspa-shield-for-arduino
  [3]: https://www.cooking-hacks.com/4g-gps-3g-gprs-gsm-gps-lte-wcdma-hspa-shield-for-arduino
  [4]: https://github.com/adafruit/Adafruit_FONA/blob/master/Adafruit_FONA.cpp


message:
SdFat: Why does the first write to the file take so long?

I have tested this problem on 6 micro-SDHC cards of 3 different types. 3 are 32-GB Sandisk, 2 are 16-GB Kingston, and 1 is 16-GB Samsung. These cards are used in data loggers and typically contain hundreds or thousands of 5-MB text files whose names are formatted like FILE1234.TXT.

The problem is that when a logger containing such a card (containing data) is started, the first write takes a long time--from 7 to 30 seconds. Opening the file (the smallest available filename) doesn't take too long. Subsequent writes don't take long. Just the first write.

Now, the plot thickens: this delay can be eliminated by first opening FILE0000.TXT and immediately closing it. Further, once this is done, that disk is never affected by this delay again. This has happened with each of the disks.

Here is some minimal code demonstrating the issue:
<!-- language-all: lang-cpp -->

    #include <SdFat.h>
    SdFat sd;
    SdFile file;

    void setup(){
      Serial.begin(57600);
      sd.begin();
      int m = millis(); // just to time everything

      // critical line that prevents delays
      file.open("FILE0000.TXT", O_WRITE | O_TRUNC | O_CREAT); file.close();

      // file we actually want to write to
      file.open("FILE6005.TXT", O_WRITE | O_TRUNC | O_CREAT);
      Serial.println(millis()-m); // print how long it took to open

      file.println(F("test"));
      Serial.println(millis()-m); // print how long it took to write
      file.close();
    }
    void loop(){
    }

When the "critical line" in the code is commented out, I get a big delay in the first write to the file. When it's uncommented, there's no delay, and I never get a delay on that disk again even with the line commented. I saw this on all six disks.

One further bit of mystery: at first, this did not work on one of the cards. I checked and found that this card alone had a hidden ".Trash-1000" directory. I removed that directory and tried again, and this fix did work that time.

Does anyone have any idea what's going on here?

body: Most file systems exhibit poor performance if you store many files in one directory. 'Normal' desktop computers are perhaps so fast, that you don't notice the performance impact, but accessing the file system from a relatively slow micro-controller, which also have limited means of caching the file system data structures in RAM, you may have to consider for this and either write a smaller number of files or build a tree of directories, so that you only have a limited number of files in each directory.


body:
I have observed this as well, but with bare-metal programming rather than arduino. I use an STM32F7 chip to write to a class 10 SD card using block writes from the SD card standard. I use a custom file system rather than FAT. My first write to the SD card takes roughly 8-10 times longer than all of my other writes. This is each time I remove power and resupply power to the device. This doesn't happen if I reset the processor without removing the power supply. If I only reset the processor (which means I reconfigure and initialize the SD card) this write delay doesn't happen.

The only thing that doesn't happen to the SD card before the first write is the configuration of the data path state machine (DPSM). Could the DPSM being in a state that isn't conducive to writing on start-up be the culprit?


message:
Code won't read the first line from SD

**The general idea**

I would like to target a link with certain parameters, which would trigger a force download of a txt file, to an SD card. Next, I'd like to loop through that file, and read one line at a time, doing something with each of the lines (storing in a variable, using it to send an SMS, etc). I'm using Arduino Uno + Ethernet shield.

**Serverside script (PHP)**

The serverscript does a DB query, and packs the results (first row/line in txt file - message text consisting of max 159 characters, all the other rows/lines - preformatted phone numbers, consisting of max 16 characters each) into a txt file. Newline and carriage returns for both the message and the phone numbers are added at the very end of, via

    fwrite($txtFile,'+'.$cleanNum."\""."\r\n");

The plus sign and the escaped quote are there, because I'd like to have the numbers formatted like this

+389012345678"

because that prepares it for sending later on.

**The Code**

    /*
     Circuit:
     Ethernet shield attached to pins 10, 11, 12, 13
     */

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

    byte mac[] = {
      0x00, 0xAA, 0xBB, 0xCC, 0xDE, 0x02
    };
    String msg ="";
    String allTxt = "";
    int counter = 0;
    int testRead = 0;
    int testmsg = 1;

    char server[] = "myserver.dev";

    IPAddress ip(192, 168, 1, 200);
    EthernetClient client;

    File file;

    void setup() {
      pinMode(10, OUTPUT);
      digitalWrite(10, HIGH);

      Serial.begin(9600);
      while (!Serial) {}

      if (!SD.begin(4)) {
        return;
      }

      if (Ethernet.begin(mac) == 0) {
          Ethernet.begin(mac, ip);
      }
      delay(1000);

      if (client.connect(server, 80)) {
        client.println("GET /dl.php?param=pass HTTP/1.1");
        client.println("Host: myserver.dev");
        client.println("Connection: close");
        client.println();
      }

      if(SD.exists("numbers.txt"))
        SD.remove("numbers.txt");

      file = SD.open("numbers.txt", FILE_WRITE);

      if (!file)
        while (1);
    }

    String readLine() {
      String received = "";
      char ch;
      while(file.available()){
        ch = file.read();
        if(ch == '\n') {
          return String(received);
        } else {
          received+=ch;
        }
      }
      return "";
    }

    void loop() {
      if (client.available()) {
        char c = client.read();
        allTxt += c;
        if(c == (char)13) {
          counter++;
          if(counter > 13) {
            for(int i = 0; i < allTxt.length()-1; i++) {
              file.print(allTxt[i]);
            }
          }
          allTxt = "";
        }
      }

      if (!client.connected()) {
        client.stop();
        file.close();
        if(testRead < 1) {
          testRead++;
          file = SD.open("numbers.txt", FILE_READ);
          if(file) {
            Serial.println("File opened!");
            while(file.available()) {
              if(testmsg==1){
                msg += readLine();
                Serial.println(msg);
                testmsg++;
              } else {
                Serial.println(readLine());
              }
            }
          }
          file.close();
        }
        Serial.println("**********************************");
        Serial.println("end");
        while(true);
      }
    }

**The Problem**

Whenever the first row in the downloaded txt file has more than 110 characters, the code does not read it (although it IS present in the file). Since it's not being read, it's not being stored in the String msg variable.

**Things tried**

Breaking the message into two variables (on the server, inside the PHP script), via

    $msgOne = substr($msg,0,floor(strlen($msg)/2)-1);
 $msgTwo = substr($msg,floor(strlen($msg)/2)-1);
and then writing them as individual rows / lines of text into the txt file. The Arduino code is modified to include this change, with

    msg += readLine();
    msg += readLine();
This however, fills the msg variable with just the first part of the message.

Redeclaring msg as a chararray, and replacing msg+=readLine() with

    readLine().toCharArray(msg,159);

also gave no results.

I have also tried replacing readLine() with Serial.println(file.read()), and everything is printed to Serial, so I'm guessing that something's wrong with my readLine() function. Maybe it (or Arduino itself) can't handle 159 characters in the first row.

Any help is appreciated.

body:
The problem was in a newline character (I still haven't discovered where does it come from or why). I have resolved it by changing this part

        while(file.available()) {
          if(testmsg==1){
            msg += readLine();
            Serial.println(msg);
            testmsg++;
          } else {
            Serial.println(readLine());
          }
        }

into this

        while(file.available()) {
           while(testRead<3) {
            char c = file.read();
            if(c != '\n') {
              msg += c;
            } else {
              testRead++;
            }
          }
          Serial.println(readLine());
          }
        }


message:
ESP8266 Aes encryption using Arduino IDE

I'm trying to implement an AES encryption function on my ESP8266 controller, using Arduino ide and [this aes library][1].
I finally made it work after many attempts but the output i get from the encryption function is only numerical and it doesn't correspond to other encryptions made by other softwares.

This is the code part relative to the AES encryption:

     #include <AES.h>

    AES aes ;
    byte *key = (unsigned char*)"0123456789010123";
    unsigned long long int my_iv = 36753562;
     tempToken = RANDOM_REG32 % 10000;
        randomstr = String(tempToken);
        //answer = "{\"token\":\"" + randomstr + "\"}";
        byte plain[4];
        randomstr.getBytes(plain, 4);
        Serial.println(randomstr);
        Serial.println(plain[0]);
        Serial.println(plain[1]);
        Serial.println(plain[2]);
        Serial.println(plain[3]);
        byte cipher [48];
      //  aes.iv_inc();
        byte iv [N_BLOCK] ;
        aes.set_IV(my_iv);
        aes.do_aes_encrypt(plain, 48, cipher, key, 128, iv);
        String ciphertoken = "";
        for (int i = 0; i < 48; i++) {
          ciphertoken += cipher[i];
        }
        answer = "{\"token\":\"" + ciphertoken + "\"}";

It basically generates a random number between 0 - 9999, then converts it in a byte array (because aes function needs a byte array as input), then encrypt this byte array and prints the output, written in `cipher` byte array.

This is the output I get from it

    6188
    54
    49
    56
    0
    {"token":"521111513725521540120674957151112223103194250224197251261938514437131212302201813929189123134524113912554682501508415421130220"}

I can't understand if I did something wrong of if it is formatted in a strange way and if I can get the right encryption from it
  [1]: https://github.com/spaniakos/AES/

body:
I don't know whether this is the only problem, but the way you are building up the string is bad: you are appending the decimal value of each byte of the cipher - so if your cipher array were, say, `{ 0x52, 0x11, 0x115, 0x137, 0x255, 0x215, 0x40, 0x1, 0x20 .... }` you'd get the string you're getting: `521111513725521540120...`  That's probably not what you want.

Probably what you want for that part is to base64-encode `cipher`, which you can find out how to do, for example, [here][1].  (If you see encrypted stuff in printable format, usually it's base64 encoded.)

  [1]: https://stackoverflow.com/questions/180947/base64-decode-snippet-in-c


message:
What is happening in this basic push-button circuit?

In the example circuit below (Arduino Uno R3), what would the equation be to identify the amperage going into pin 2 when the button is pressed? What if I used the 3.3v on the arduino or a 9v battery instead?

What is happening to the input pin when the button is not being pressed? (I assume it's a guaranteed LOW state due to any current being sapped by the GND, yes?)

What would happen without the pull down resistor? A short when the button is pressed? What would happen without the ground being connected at all? Anything?

A tutorial for how to choose a pull down resistor I seen suggested a resistance value of 10 times the impedance of the pin. I'm not quite sure where to find this impedance value, but I have seen on an arduino tutorial "A 10K resistor is a good value for a pullup or pulldown resistor." Just not much of an explanation of why that value.

Sorry for so many little questions in this one question, but these are the kinds of things I'm not seeing addressed in most tutorials.

[![Simple button test][1]][1]

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

body:
> what would the equation be to identify the amperage going into pin 2 when the button is pressed?

Once the button has been pressed for more than a few nanoseconds the current will be 0 (or as near as).

Immediately the button is pressed the formula is  I(t) = dQ(t) / dt since the input pin is a MOSFET gate and as such is seen (in simple terms) as a capacitor.

> What if I used the 3.3v on the arduino or a 9v battery instead?

The same.

> What is happening to the input pin when the button is not being pressed? (I assume it's a guarangeed LOW state due to any current being sapped by the GND, yes?)

It is pulled down to ground by the resistor.

> What would happen without the pull down resistor? A short when the button is pressed? What would happen without the ground being connected at all? Anything?

The input will be HIGH when the button is pressed, and floating (initially HIGH) when released.

> A tutorial for how to choose a pull down resistor I seen suggested a resistance value of 10 times the impedance of the pin. I'm not quite sure where to find this impedance value, but I have seen on an arduino tutorial "A 10K resistor is a good value for a pullup or pulldown resistor." Just not much of an explanation of why that value.

The main concern with a pullup or pulldown resistor is the current it demands from the power supply when the button is pressed. If it's too low then you will be wasting current. If it's too high then the input may take a while to turn off when you release the button.  10K is a "good" value since it is a good balance between those two factors.

The current from the supply is calculated as I=V/R, so 5/10000 = 0.5mA.  Low power systems may choose a higher value (100kΩ, say) to reduce the current.


body:
> what would ... the amperage going into pin 2 when the button is
> pressed?

Virtually zero Amps, as pin 2 is set to an input. There is some input impedance, but according to the datasheet that is, at maximum, 1µA.

> What if I used the 3.3v on the arduino?

Same thing. 1µA.

>  or a 9v battery instead?

Then you will blow up your chip.

> What is happening to the input pin when the button is not being
> pressed? (I assume it's a guarangeed LOW state due to any current
> being sapped by the GND, yes?)

That's where the resistor in the circuit comes in. It's called a pull-down resistor. It will make sure the pin is LOW. Without it the pin is "floating", and could read as HIGH. e.g. due to some static in the air, or just having your hands nearby the pin.

> What would happen without the pull down resistor? A short when the
> button is pressed?

If you remove the resistor, you shouldn't connect GND to the other side of the switch. That would indeed cause a short between 5V and GND, possibly damaging your powersupply/PC or blow up your wires, or traces on the Arduino PCB

> What would happen without the ground being connected at all? Anything?

The pin would be floating and result in sometimes reading a HIGH even when the button isn't pressed.

> A tutorial for how to choose a pull down resistor I seen suggested a
> resistance value of 10 times the impedance of the pin. I'm not quite
> sure where to find this impedance value, but I have seen on an arduino
> tutorial "A 10K resistor is a good value for a pullup or pulldown
> resistor." Just not much of an explanation of why that value.

The value here isn't very critical. Somewhere between 1k and 100k will work.


message:
How do I control multiple LEDs strips with Arduino

I want to decorate my house with LEDs strips on each step of my stairs.
I will buy LEDs strips with a 12V power supply.

I want that if I put my foot on the first step, the first LEDs strip turn on, and after every second, the next step turn on too until the last step.
After 10 seconds on, the step must turn off.

To detect my foot, I'm thinking of using that kind of component : PIR (motion) sensor (product 189 on adafruit website). It act like a push button.

My first thought was to create two circuit loops.
One to supply the LEDs strips with a transistor between each strip.
And the second to control the transistor, so the turn on/off signal.

Thanks to your advices, I decided to use an Arduino to do the control loop.

I found this (http://www.zem.fr/decouverte-du-composant-74hc595-8-bit-shift-register/):
[![Control loop with Arduino][1]][1]
It's two 8-bit shift register, I have 16 steps on my stairs.
With a simple bit of code, I successed in writing a Arduino code that push ten HIGH(1) bits from the right then sixteen LOW(0) bits. So I have what I want with the LEDs.

The question is : how to connect the 16 LEDs strips with my circuit (instead of the single led) ?

English is not my native language, I tried to do my best.

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

body: Assuming your LED strips are essentially "always on" when they have power, you could replace the single LEDs in your diagram with transistors that sit between the power supply and the strip. Then, when your Arduino pin goes high, the transistor turns on the LED strip.


message:
I can't receive a letter using UART

I wrote a simple program where I transmit and receive a letter via UART. The transmit function works 100% but the receive interrupt function doesn't work at all... Can someone adjust the receive interrupt function so I can receive a string instead of a char?

    #define FOSC 16000000 // Clock Speed
    #define BAUD 9600
    #define MYUBRR FOSC/16/BAUD-1

    void setup() {
      USART_Init(MYUBRR);
      interrupts();
    }

    void loop() {
    }

    void USART_Init(unsigned int ubrr) {
      /*Set baud rate */
      UBRR0H = (unsigned char)(ubrr>>8);
      UBRR0L = (unsigned char)ubrr;
      UCSR0B = (1<<RXEN0)|(1<<TXEN0);
      //Enable receiver and transmitter */
      UCSR0C = (1<<USBS0)|(3<<UCSZ00);
      /* Set frame format: 8data, 2stop bit */
      UCSR0A |= (1 << RXCIE0);
      UCSR0C=0;
    }
    void USART_Transmit(unsigned char data) {
      /* Wait for empty transmit buffer */
      while(!( UCSR0A & (1<<UDRE0)));
      /* Put data into buffer, sends the data */
      UDR0 = data;
    }

    ISR(USART__RXC_vect) {
      char ReceivedByte;
      ReceivedByte = UDR0;
      // Fetch the received byte value into the variable "ByteReceived"
    }

body:
>     ISR(USART__RXC_vect)
    {
      char ReceivedByte;
      ReceivedByte = UDR0;
    // Fetch the received byte value into the variable "ByteReceived"
    }

`USART__RXC_vect` is not the name of the interrupt vector, `USART_RX_vect` is.

If you don't get the name right there is no compiler warning, however the interrupt routine is not called.

---

>     UCSR0A |= (1 << RXCIE0);

That line is wrong. `RXCIE0` is in `UCSR0B` not `UCSR0A`. If you set the bit in the correct register you will get an interrupt.


message:
Trouble using a TSSP77038 with an Arduino

I have a Vishay TSSP77038 IR receiver that I would like to read the output of. It is connected as shown in the picture - Vs to 5V, GND to GND and the output to a pin on the Arduino.

My problem is that the reading is constantly low (it is active low so says it is receiving a IR signal), even when i completely cover the sensor or I am in a dark room. Can someone please tell help? Thanks a lot in advance :) [![enter image description here][1]][1]

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

body:
Gerben is correct it looks like you need a pull up resistor so that the pin is high unless the receiver drives it low.

I found [this][1], which was the closest to useful information I found. Have a look at the proximity sensor section, it is similar to what you are using.

You'll want to know a value, I haven't got a clue.  I use 4.7K for I2C pull ups. It's probably easier to start high (weaker) and work your way down, because if you put a 100K resistor in and the signal is low, then the resistor is too strong and you need a smaller one.

  [1]: https://www.pololu.com/docs/0J63/all


body:
Because this part has an internal pull-up resistor, seeing the data line consistently low is most likely cause by one of:

 - Reversed installation on the circuit board.  This part can actually be installed in two orientations, with the lenses up or to the side, so there are more opportunities than usual to get the orientation of the contacts wrong.

 - Electrical damage from past misuse

 - A wiring problem, short, or additional device holding the data line low


message:
IDE does not create prototypes

I'm running Arduino IDE 1.6.10 on Mac OS X 10.12.1.
I read on the Arduino official sote that the IDE should create function prototypes for me, and it always did. But now I'm writing a 1500 lines program, with dozens of functions, and this tool wold be quite useful (although I obviously don't really need it)... and it doesn't work.
Is that a known issue?

body:
There are some times when it can't make prototypes, and some when it just gets it plain wrong. It struggles if you do fancy things with any of your functions, such as adding attributes or using anything that's even slightly out of the ordinary.

Also sometimes it places the prototypes in completely the wrong place, especially if you are working with structs, etc.


body:
Do yourself a favour and dont rely on those automatic tools.

Type your code and know every line you typed.

And give PlatformIO a try instead of the Arduino IDE. You will save yourself and coworkers a lot of grief.


body:
Unfortunately various things make the prototype generation fail. I think they run a regexp on the code which doesn't detect all cases. Examples are:

* Function definition split over multiple lines
* Use of templates
* Use of user-defined types in a function definition

Here is one bug report:

https://github.com/arduino/Arduino/issues/472

It's not that hard to take your function definition and make a prototype out of it. It's good practice anyway to get into the habit of it. If you get into larger projects where functions are in different files you need to do this anyway.


message:
Arduino Uno rev 3 - what are the additional 2x3 set of pins for?

I recently bought ``Arduino Uno rev 3`` board and I spent a lot of time trying to figure out the function of each individual pin. I googled all the fancy terms like ``IOREF``, ``SDA``, etc. and one by one I figured out the functional purpose for most of the pins.

However, there are few pins (actually pin groups) which have no labels around and I find it really difficult to figure out what these pins are supposed to do.

Again, I googled around and found [this schematic](http://pighixxx.com/unov3pdf.pdf) from which I figured out that the 6-pin group  at the bottom is about something called ``ICSP`` (or at least this is what is written there). When I googled this term, I found this excellent explanation about the [serial communication protocols](https://electronics.stackexchange.com/questions/37814/usart-uart-rs232-usb-spi-i2c-ttl-etc-what-are-all-of-these-and-how-do-th).

However, at this point I am really confused.

 - The explanation about the serial protocols doesn't mention at all ``ICSP``. By googling even further I only get more and more confused. Yes, I found the [ICSP wiki page](https://en.wikipedia.org/wiki/In-system_programming) but I am not 100% sure that the bottom 6 pins are related to ICSP.
 - From the same schematic which I found I see there are 4 additional soldered pads with label ``JP2`` right above them. Currently I have no clue about the function of these pads. **Question 1** - what are these soldered pads for?
 - Right next to the ``JP2`` stuff is a group of 6 pins (3 rows, 2 columns). The schematic is not clear about these pins. **Question 2** - what is the purpose of these pins? **Question 3** - where can I find the actual schematic (layout) about each individual pin?
 - I am not 100% sure that the bottom group of pins (2 rows, 3 columns) is related to ``ICSP``. Maybe that's the case, maybe it's not. **Question 4** - what is the purpose of these pins? **Question 5** - where can I find the actual schematic (layout) about each individual pin?

Thank you in advance for your help!

body:
The ICSP pins have two functions:

1. For programming the ATMega328P directly using a hardware programmer (In Circuit Serial Programmimg)
2. SPI connections for shields in a standard place.

They are used for SPI because different boards have the SPI pins on the main headers in different locations. All boards should have this 6-pin block in the same place though meaning that shields can then work with more boards.

On the Uno they share the same physical connections as digital pins 11-13 plus reset and power.

JP2 and the other 6-pin block are connected to the USB interface chip (ATMega16U2). The 6 pin block provide ICSP for programming that chip. The other 4 (unpopulated) pins connect to GPIO pins on that same chip. They can be used for anything you like if you replace the firmware on the USB chip.

For now ignore those two pin groups. They aren't really anything to do with the Arduino side of things, only the USB interface.

You can find all this on the official Uno schematic which is on the official Uno product page: https://www.arduino.cc/en/Main/ArduinoBoardUno


message:
Arduino (weird) ADC problem

I'm trying to read to voltage output of module ACS712. Here is my problem: The module outputs a voltage around 2.5V, however, arduino sends the value "1023" to the PC. (Gives a reading of 5V).

Arduino's analogRead function works, however, is slow so I used atmega registers to solve the issue. Which worked... Except only for the module. Here is the relevant part of my code:

Setup:

    void setup() {
      ADMUX = 0xC0;
      ADCSRA = 0x8E;           // prescaler = 64
      ADCSRB = 0x40;
      sei();
      bitWrite(ADCSRA, 6, 1);    //This starts single converion.
      Serial.begin(250000);
    }

Relevant ISR function:

    ISR(ADC_vect) {
      sensorValue = ADCL;        // read adcl first. locks adc bytes.
      sensorValue += ADCH << 8;
      Serial.println((int)sensorValue);
      bitWrite(ADCSRA, 6, 1); // Set high so another conversion starts.
    }

Now, this code runs as expected for another adc pin which is located at "A3", or in code:

    ADMUX = 0xC3;

However, does not work for:

    ADMUX = 0xC0;

Yes, I tried replacing the wires A0 and A3. This time "0xC0" works but "0xC3" doesn't. So my arduino somehow is resistant on reading the module output!

Also, this works on same hardware:

    sensorValue = analogRead(A0);
    Serial.println((int)sensorValue);

Arduino's analogRead runs as expected on same hardware.

So basically, the hardware seems okay, but there seems to be a problem with my code. I just can't read the modules output voltage and I'm all out of ideas. Can anyone help?

body:
> However, does not work for:
>
>      ADMUX = 0xC0;

See the datasheet:

[![ADMUX][1]][1]

An ADMUX of 0xC0 will be using a voltage reference of "Internal 1.1V Voltage Reference with external capacitor at AREF pin". Since you are supplying 2.5V that exceeds 1.1V and thus you get a reading of 1023.

---

>       Serial.println((int)sensorValue);

Also, don't do serial prints inside an ISR.

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


message:
ADXL345 accelerometer doesn't work

I just got the ADXL345 accelerometer module. I tried everything I could find online but I can't get it work. Here's how I connect the pins to the arduino uno:

    ADXL345    ->     ARDUINO
      VCC               3.3V
      CS                3.3V
      GND               GND
      SDA               SDA
      SCL               SCL

I also use 2 10kOhm resistors from SDA, SCL to 3.3V on arduino. I tried both Adafruit and SparkFun ADXL345 libraries but it doesn't work. Using Adafruit library it says that no adxl345 is connected. I tried to connect SDO to 3.3V pin and then it stopped saying no adxl345 is connected but still didn't work (no x,y,z values displayed). Then I tried SparkFun library without connecting SDO to 3.3V (because it failed) and all I got was 0, 0, 0. I literally tried everything I could find from videos, tutorials, etc. I don't know why it doesn't work. What am I doing wrong? I already ordered the MPU6050. Is it any better?

body:
SDO should be tied to ground, not 3.3V. That puts it into I2C mode.

VDDIO, VS and CS all need to be on 3.3V.

To communicate with an Arduino at 5V you really need a 5V -> 3.3V I2C level shifter. I use the PCA9306DCUR.


body:
As far as my experience goes you donot have to connect it to pulldown resistors. If using a 5v Arduino, simply connect it like:

VCC --> 5V  (Arduino)
GND --> GND (Arduino)
SDA --> A4 or SDA (Arduino Uno has dedicated I2C pins beside AREF pin)
SCL --> A5 or SCL

This is all you need. As although the ADXL345 is a 3.3v MEMS, its module comes with a 5v to 3.3v converter and also goes through its startup procedure ([Refer datasheet][1]) for you.
As for the library you can use this one [here][2]
Also you can refer this article for detailed usage [here][3]
And I hope next time you put in some more research and then buy a new part.

  [1]: https://www.analog.com/media/en/technical-documentation/data-sheets/ADXL345.pdf
  [2]: https://github.com/jarzebski/Arduino-ADXL345
  [3]: http://www.jarzebski.pl/arduino/czujniki-i-sensory/3-osiowy-akcelerometr-adxl345.html


message:
Arduino to ESP8266 SoftwareSerial communication

I have an Arduino Uno and an ESP8266, connected over serial through
ESP8266 pin GPIO_2 (which is set as RX over espsoftwareserial) and 11 on Uno (which is set as TX over SoftwareSerial). I am trying to send data (for now just random numbers from 0 to 1000) from Arduino Uno to ESP8266.
But ESP8266 shows messy chars.

I am using:

 - [espsoftwareserial library][1]
 - [Original SoftwareSerial library][2]

Arduino UNO code:

    #include <SoftwareSerial.h>

    SoftwareSerial mySerial(10, 11); // RX, TX
    int randnum;

    void setup() {
      // set the data rate for the SoftwareSerial port
      mySerial.begin(9600);
      Serial.begin(115200);
    }

    void loop() { // run over and over
      randnum = random(0,1000);
      mySerial.write(randnum);
      Serial.println(randnum);
      delay(2000);
    }

ESP8266 code: (it's programmed with Arduino IDE)

    #include <ESP8266WiFi.h>
    #include <SoftwareSerial.h>

    SoftwareSerial ARD_ESP(2, SW_SERIAL_UNUSED_PIN); // RX, TX  |||| RX = ESP8266 = GPIO_2

    const char* ssid     = "myssid";
    const char* password = "mypassword";

    const char* host = "www.myweb.com";
    const char* value2 = "986.458";
    const char* value1 = "150.0589";
    long previousMillis = 0;
    char indata;
    String incomingData_from_ARD = "";
    int i=0;

    void setup() {
      Serial.begin(115200);
      ARD_ESP.begin(9600);
      delay(10);
      // We start by connecting to a WiFi network
      Serial.println();
      Serial.println();
      Serial.print("connecting to wifi: ");
      Serial.print(ssid);
      WiFi.begin(ssid, password);
      while (WiFi.status() != WL_CONNECTED) {
        delay(500);
        Serial.print(".");
      }
      Serial.println("");
      Serial.println("WiFi connected");
      Serial.println("IP address: ");
      Serial.println(WiFi.localIP());
    }
    //int value = 0;

    void loop() {
      //delay(1000);
      //++value;
      if (ARD_ESP.available() > 0) {
        Serial.write(ARD_ESP.read());
        indata = ARD_ESP.read();
        incomingData_from_ARD += String(indata);
      }
      if ((millis() - previousMillis) > 10000) {
        Serial.println("---------------------------------------------------------------------------------------");
        Serial.print("Requesting URL: ");
        Serial.println(host);
        Serial.println("-------------------------------");
        // Use WiFiClient class to create TCP connections
        WiFiClient client;
        const int httpPort = 80;
        if (!client.connect(host, httpPort)) {
          Serial.println("Request failed");
          return;
        }
        // We now create a URI for the request
        String url = "/testesp.php";
        url += "?sensor_1_total_volume=";
        url += incomingData_from_ARD;
        url += "&sensor_2_total_volume=";
        url += value2;
        Serial.println("Sending data to URL: ");
        Serial.println(url);
        Serial.println("-------------------------------");
        client.print(String("GET ") + url + " HTTP/1.1\r\n" +
          "Host: " + host + "\r\n" +
          "Connection: close\r\n\r\n");
          unsigned long timeout = millis();
        while (client.available() == 0) {
          if (millis() - timeout > 5000) {
            Serial.println(">>> Server Timeout!");
            client.stop();
            return;
          }
        }
        while(client.available()) {
          String line = client.readStringUntil('\r');
          Serial.print(line);
        }
        Serial.println();
        Serial.println("Closing connection with web");
        Serial.println("-----------------------------------------------------------------------------------");
        previousMillis = millis();
        incomingData_from_ARD = "";
      }
    }

And this is the text that I am getting on Serial (on PC):

        -----------------------------------------------------------------------------------
            ›¸Ąě*Ű
     ---------------------------------------------------------------------------------------
    Requesting URL: www.myweb.com
    -------------------------------
    Sending data to URL:
    /testesp.php?sensor_1_total_volume=Ĺ˙˙˙˙˙&sensor_2_total_volume=986.458
    -------------------------------
    HTTP/1.1 200 OK
    Server: nginx
    Date: Tue, 13 Dec 2016 23:28:58 GMT
    Content-Type: text/html; charset=UTF-8
    Transfer-Encoding: chunked
    Connection: close
    X-Powered-By: PHP/7.0.10

    354

â€žÄŚas si vymysleli lidĂ©, aby vÄ›dÄ›li, od kdy do kdy a co za to.â€ś Jan Werich

<!DOCTYPE html>

       <meta charset="UTF-8">
       <meta name="description" content="TEST_ESP">
       <meta name="author" content="Vasekdvor">
       <meta name="robots" content="noindex">
       <title>TEST ESP 8266 POST A GET</title>

    0

    Closing connection with web
    -----------------------------------------------------------------------------------

These messy chars at the beginning are the random numbers that Arduino Uno sends:

 **›¸Ąě*Ű**

But Arduino sends real numbers, only the ESP8266 is interpreting them as this.

Can you please help me fix that? How can I receive numbers?

Thank you.

  [1]: https://github.com/plerup/espsoftwareserial
  [2]: https://www.arduino.cc/en/Reference/SoftwareSerialConstructor

**EDIT:**

So i have made some changes based on chupo_cro recommendations

Now its Arduino:

    void loop() { // run over and over

    randnum = random(0,1000);

    mySerial.write((byte*)&randnum, sizeof(randnum));
    Serial.println(randnum);

    delay(2000);
    }

And ESP8266:

    long previousMillis = millis();
    char indata;
    String incomingData_from_ARD = "";
    int i=0;

    void setup() {

.................................

    void loop() {
      //delay(1000);
      //++value;

      if (ARD_ESP.available() > 0) {
        //Serial.write(ARD_ESP.read());
        indata = ARD_ESP.read();
        incomingData_from_ARD += indata;
      }

      Serial.println(incomingData_from_ARD);

      if ((millis() - previousMillis) > 10000) {

Its still doesnt work.

body:
There are a few issues in your code.

First, you have `if (ARD_ESP.available() > 0)` to check if the data arrived but what is going to happen if the data still haven't arrived? Instead of waiting for the data to arrive the program will continue through the loop and it will send a request every 10 seconds **even if there is no data**.

Second, you initialized `previousMillis` to zero. You should initialize it to `millis()` so you can count from the present moment in time.

Third, in the loop where you are reading the input:

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

    if (ARD_ESP.available() > 0) {
     Serial.write(ARD_ESP.read());  // <-- 1st read
     indata = ARD_ESP.read();   // <-- 2nd read
     incomingData_from_ARD += String(indata);
    }

when something arrives, you are reading it **twice** so the second read `indata = ARD_ESP.read();` gets `-1` (no data available) when there is less than two chars in the buffer. Even if you sent more than one character there is no time for new data to arrive in the buffer and even if there is more than one character you miss every second one because of the 1st read.

Fourth, you cannot send the number greater than 255 (one byte) with `mySerial.write(randnum);` because `write()` sends only one **byte**. And even if you could in a such way send more than one byte, you cannot display these **bytes** as a **string representing the number**. You could send all bytes using:

    mySerial.write((byte*)&randnum, sizeof(randnum));

but, as I said, these bytes are **not** a string representing the number contained in a variable. For example, if `randnum = 1000`, that is `0xe8, 0x03` and `"1000"` is `0x31, 0x30, 0x30, 0x30`. `0x31` is ASCII for `1` and `0x30` is ASCII for `0`.

So, you have a lot of things to improve.

**EDIT:**
Try this, I don't have a time to check the code but it should work:

    int length = 4;
    char to_send[length];
    itoa(randnum, to_send, 10);
    mySerial.write((byte*)&to_send, sizeof(to_send));
    Serial.println(to_send);
**EDIT:**
Unfortunately I don't have Arduino (I've even never had one :-)) so you'll have to try the code and report back if it works. I have a few ESP8266s but they are all logging some data at the moment.

Now for the ESP8266 code:

You have at least two choices when deciding how to read the data. The first choice would be 'your way', something like:

    void loop() {

     char input;
     if(ARD_ESP.available()) {
      input = (char)ARD_ESP.read();  // you can try even without (char)
      Serial.print(input);    // send char to terminal
      incomingData_from_ARD += input;  // concatenate the new char
     }

     if ((millis() - previousMillis) > 10000) {
         // if there was something received until now
         if(incomingData_from_ARD.length()) {
          // ...
          incomingData_from_ARD = "";
         }
      previousMillis = millis();
        }
     // ...
    }

The second way could be:

    void loop() {
     char input;
       // wait for the data
     while(!ARD_ESP.available())
         yield();                          // to prevent WDT reset
       // read everything that has been sent
        while(ARD_ESP.available()) {
         input = (char)ARD_ESP.read();
         Serial.print(input);
         incomingData_from_ARD += input;
         delay(120);                       // 100 or a bit more for 9600 Bd
        }

        // remove 'if' to send immediately
        if ((millis() - previousMillis) > 10000) {
      // ...
      previousMillis = millis();
        }
     // ...
    }

There is a significant difference between these two ways of reading the incoming data. When reading the data as in the first example then in every pass through the loop you either read or don't read exactly one byte. Since there is a possibility 10 seconds will pass before we received some data, there has to be a check if the data in the meantime arrived or not. If there was some data then every 10 seconds everything received until that moment would be sent - **even if that was in the middle of the string**. You probably don't want to send just one part of the string to the server.

In the second example there is a `while` loop waiting for the data from serial port. When the data arrives there is another `while` loop to read all bytes one by one. Without `delay` the loop would end before receiving the second and all subsequent bytes so the received string would be cut in 1-character chunks. Now, when the whole string is received, we don't have to check if something arrived because we already know it did.

I've left 10 seconds delay between sending the GET requests but you have to decide if that is what you **really** want. You have to be aware that if the next data arrive in between sending the GET requests, the next string (number) will be concatenated with the previous one - and you do not want that to happen because such data wouldn't be meaningful. To avoid concatenation of the new with the old data, you have to remove `if` which is checking `millis()` to send the received data immediately.

Note:
As I said, I can't test the code so I cannot guarantee it is 100% error free but you can check if it works so I can correct the mistakes if there are any.


message:
2 if-else in one program

Hey guys i have made an automatic plant watering system. Its really basic. the code is:-

    char yo = 0;
    void setup() {
      pinMode(2, INPUT);//moisture sensor
      pinMode(3, OUTPUT);// pump
      Serial.begin(9600);
    }

    void loop() {
      yo = digitalRead(2);
      if(yo == 1){
          digitalWrite(3,HIGH);
          Serial.println("Plant is Being Watered as the soil is dry");
          delay(5000);
        }
      else{
          digitalWrite(3,LOW);
          delay(5000);
          Serial.println("the plant has sufficient water");
        }
    }
The thing that i want to add is.. i want to add a feature which can manually control it with bluetooth but the normal program should also be running. for eg. soil is wet but i want to add more water so i write 9 on the blueterm app which starts the pump for 2 seconds. I am using an HC-05 bluetooth module. can someone tell me how this can work on an arduino?

EDIT!
<br>
Sketch 2:

    char ha;
    void setup() {
      pinMode(3, OUTPUT); //pump
      Serial.begin(9600);
    }

    void loop() {
     ha = Serial.read();
     if(ha == 5){
        digitalWrite(3, HIGH);
        delay(2000);
      }
     else{
        digitalWrite(3,LOW);
      }
    }

body:
    char ha;
    void setup() {
      pinMode(3, OUTPUT); //pump
      Serial.begin(9600);
    }

    void loop()
    {

      //.:.bluetooth control block
      if (Serial.available()) //check serial data availability
      {
        ha = Serial.read();
        if(ha == '9') //received data is char '9'
        {
          digitalWrite(3, HIGH); //turn on
          delay(2000);
          digitalWrite(3, LOW); //turn off
        }
      }
      else
      {
        //.:.manual control block
        if(digitalRead(2)){
          digitalWrite(3,HIGH);
          Serial.println("Plant is Being Watered as the soil is dry");
          delay(5000);
          digitalWrite(3,LOW);
        }
      }
    }


message:
Arduino IDE automatic tools

I know that the Arduino IDE does some simple tasks automatically: for example it creates function prototypes, but this function sometimes fails.

Does that IDE run other hidden "pre-precompiler" tasks?

Is there a way to disable them? (this question refers especially to the function prototypes creator).

body:
The IDE runs a "preprocessing" routine. As well as adding prototypes it also:

* Adds `#include <Arduino.h>` to the start of your sketch
* Removes comments (or the older versions did, I am not sure about arduino-builder)
* Identifies the libraries #included in the sketch

The latter is used to build the list of `-I ...` directories to add to the command line. Removing of comments was chiefly to make finding functions easier for making function prototypes (though there are better ways of doing both those and arduino-builder might use them).

Can you disable it? No. Not for `.ino` files. However, any `.cpp` files added to your project are treated as vanilla C++ source code and aren't preprocessed in this way.


message:
Extracting bits from hex encoded binary

I've been using an Adafruit Huzzah ESP8266 Breakout to read data from an [OpenTherm Gateway][1] connected to my central heating unit, and publish that to MQTT. I'm programming the ESP8266 using the Arduino IDE.

The gateway publishes messages to the ESP8266 via serial. These messages look like this: `T901812F3` or `B501812F3`

The first letter indicates whether the message comes from the thermostat or the boiler, while the remaining characters represent four bytes, hexadecimally encoded.

These four bytes are structured as follows:

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

I'm trying to extract the MSG-TYPE, DATA-ID, and DATA-VALUE from the four bytes, but I'm getting weird (to me) results. I'm new to Arduino and C in general.

I'm familiar with PHP, and extracting the data using that is easy:

    $decimal = hexdec(substr("B501812F3", 1));      // 1343754995
    $messageType = (($decimal & 0x70000000) >> 28); // 5
    $dataId = (($decimal & 0x00FF0000) >> 16);      // 24
    $dataValue = ($decimal & 0x0000FFFF);           // 4851

However when I try something similar in the Arduino IDE, and upload it an Arduino, I get a different result:

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

        parseLine("B501812F3");
    }

    parseLine(char* message) {
        // Extract data
        char messageType;
        unsigned long data;
        int numberExtracted = sscanf(message, "%cx", &messageType, &data);

        // Decompose a single message
        int flag = (int) ((data & 0x70000000) >> 28);
        unsigned char openThermId = (unsigned char)((data & 0x00FF0000) >> 16);
        unsigned short openThermPayload = (unsigned short)(data & 0x0000FFFF);

        Serial.println(data);             // 4851
       Serial.println(flag);             // 0
       Serial.println(openThermId);      // 0
       Serial.println(openThermPayload); // 4851
    }

I (perhaps incorrectly) assume that the effect will be the same when I upload the code to an ESP8266.

What am I missing here? I suspect it has something to do with the different max integer value on the Arduino, but I'm not really sure how to proceed.

  [1]: http://otgw.tclcode.com
  [2]: https://i.stack.imgur.com/qPmrV.png

body:
You're best off using `strtoul()`:

    messageType = message[0];
    uint32_t data = strtoul(message + 1, NULL, 16);

The trick here is that `message` is just an array, so you can get the first letter with `message[0]`. Also, since C arrays are themselves just pointers to blocks of memory, `message + 1` actually points to the location in memory of `message[1]`, so you start processing the numbers from the second character in the string, thus omitting the first letter.

`strtoul()` takes a third parameter which is the *base* to decode from - 16 in this case for hexadecimal.

From there you can then use your bit shifting and masking to slice up your 32-bit value into your required sub values.


body:
A C/C++ struct with bit-fields can sometimes be an effective solution to this type of problem. The bit-field order depends on the endianness of the CPU. AVR uses little-endian order and thus the fields are from right to left.

    union msg_t {
      struct {
        uint16_t value;
        uint8_t id;
        uint8_t spare:4;
        uint8_t type:3;
        uint8_t parity:1;
      };
      uint32_t as_uint32;
    };

A simple test sketch to verify:

    void setup() {
      Serial.begin(9600);
      while (!Serial);
      msg_t msg;
      msg.uint32 = 0x501812f3;
      Serial.println(msg.parity); // 0
      Serial.println(msg.type);     // 5
      Serial.println(msg.spare); // 0
      Serial.println(msg.id);     // 24
      Serial.println(msg.value); // 4851
    }

    void loop() {
    }


message:
Arduino write/handle long programs

I'm writing a "sketch" in the Arduino IDE which has at this very moment 1500 lines and is going to become much longer. I splitted it in several tabs, but that's not very comfortable to use (I need to find the "precompiler" file in a temporary folder in order to have my program in a printable version, in the tabs bar I can't see all tabs, ...).

Are there any better alernatives to the Arduino IDE? Someone suggested me PlatformIO, is that a good IDE? (please note that I have a mac running OS X 10.12.1; I also have a (virtual) Windows 10 machine if absolutly needed, but I'd like to install the IDE on MAC OS X)

What are the best ways to create a long program? In general, for C++, what are the best practices? And is for Arduino the same?

body:
Have you tried Atmel Studio? Right now, it only supports Windows but is a great alternative to Arduino IDE.

If you're not comfortable using Windows virtual machine, I suggest you have a look at this: http://playground.arduino.cc/code/eclipse


body:
@Maximus suggested Atmel Studio. WHile this choice is not bad, the programming language, well at least if you are used to the "Arduino type" C, is different then Arduino. An easy way to get all of the things you are used with Arduino to an other IDE is Visual Micro.

This IDE is deffenetly an upgrade. It has code completition and is just more adapted for programming (thats in my opinion). A good thing that I like about it is that it will still pass by the Arduino IDE's compiler.

BTW, you'll need to have Visual Studio.


body:
I can't help but recommend [UECIDE](http://uecide.org), but then I wrote it. It's better than the Arduino IDE at working with large projects with multiple files, yet not as complex as things like Atmel Studio.

I would, however, recommend a re-think about how you arrange your project. A single long file (even if made from multiple files joined together) isn't good. Instead you should split your project into a number of modules. Consider writing libraries for some of the functionality of your program.

No one in the real world wants a massive program as one single file. All big projects are made out of multiple files, and those files are all separate units and compiled separately. The fact that the Arduino IDE joins them all together into one gargantufile is IMHO a bad idea. Keep things separate. Keep things modular. Keep things as they are in the real world of development.


body:
Give a try to Platformio. It's based on the Atom editor. It's great and multi platform (mac, windoze, linux)

As for splitting your program, it is a good idea but not any ways. Keep concepts in the same file, avoid using globals are just a few hints.


message:
PCA9685 seemingly no PWM output Arduino Uno when attempting to do LED dimming

Just for a quick test I've wired up the Arduino to a PCA9685 board (similar to http://www.ebay.com.au/itm/PCA9685-16-Channel-12-bit-PWM-Servo-motor-Driver-I2C-Module-For-Arduino-Robot-AU-/162059198475?hash=item25bb7b200b:g:S7IAAOSw9ZdXKa7h) as follows

 - 5v > Vcc & V+
 - GND > GND
 - A4 > SDA
 - A5 > DCL
 - OE > Not connected

I've wired a 1k resistor in series and an LED in between PWM0 and GND

The same LED dims fine when powered directly via PWM from the Arduino.

The power light on both boards come on and +5v is available at the V+ pins.

The library I'm attempting to use is https://github.com/kasperskaarhoj/PCA9685-Arduino-Library and from what I can tell the I2C address I've configured "works"

The sketch I'm trying to run is (which is one of the example sketches with the address I2C altered):

    #include <Wire.h>
    #include <PCA9685.h>

    PCA9685 ledDriver;

    void setup()
    {
      Serial.begin(9600); // set up serial
      Serial.println("Serial Started");

      Wire.begin();           // Wire must be started!
      ledDriver.begin(B000000);  // Address pins A5-A0 set to B111000
      Serial.println(ledDriver.init());

    }

    void loop()
    {
      // Notice: setLEDDimmed cannot be used in a loop to give you a pleasant
      // "turning-up" of the LED. This is because each time you set a level for a LED
      // it will calculate random timing intervals for the PWM function in the chip
      // This is done in order to distribute current consumptions of the full time period.
      for(int level=5;level>=0;level--)  {
        for(int i=0; i<16; i++)  {
          ledDriver.setLEDDimmed(i,level*20);
          delay(100);
        }
      }
      for(int level=0;level<=5;level++)  {
        for(int i=0; i<16; i++)  {
          ledDriver.setLEDDimmed(i,level*20);
          delay(100);
        }
      }
    }

Serial monitor outputs:
Serial Started
1

So it looks like the device is detected and I expect that the commands are sent but nothing happens.

I've also tried one other library and setting the duty cycle to 100% on/off just to see if I could get output with no luck. It just seems that all the PWM pins are dead. I also tried wiring up the OE pin and setting it high/low with no luck.

Any thoughts on how I might be able to get the board to output something or how I can test further would be appreciated. I'm beginning to think that maybe the IC is damaged as I've tried most the pins with no luck.

I'm out of ideas and haven't worked with I2C or PCA9685's before at all so any help would be appreciated :)

body: The LED should be (with its inline current limiting resistor) between VDD and the LED pin, not to ground - and then configure the pin for Open Collector mode.


message:
How to use get_properties to get RSSI in RF24?

As picture below, how to use get_properties ? I fail to understand [AN625][1], how to use get_properties to get RSSI ?

>[![enter image description here][2]][2]
>
> Adding source code based on RH_RF24 functions.

    #include <SPI.h>
    #include <RH_RF24.h>

    // Singleton instance of the radio driver
    RH_RF24 rf24;

    uint8_t Recieve_Data[20];

    uint8_t receive_buffer[RH_RF24_MAX_MESSAGE_LEN];
    uint8_t receive_buffer_length = sizeof(receive_buffer);

    uint8_t Rssi;

    unsigned long Micro_Time;

    uint8_t status[8];
    uint8_t buf[RH_RF24_MAX_MESSAGE_LEN];
    uint8_t len = sizeof(buf);

    void setup()
    {
      Serial.begin(115200);
      if (!rf24.init())
        Serial.println("init failed");
      // Defaults after init are 434.0MHz, modulation GFSK_Rb5Fd10, power 0x10
       while(!rf24.setFrequency(443));
      rf24.setModemConfig(rf24.GFSK_Rb50Fd100);  //设置成GFSK_Rb50Fd100
    }

    void loop()
    {
      rf24.setModeRx();
      delay(100);
      rf24.setModeIdle();
      rf24.command(RH_RF24_CMD_GET_INT_STATUS, NULL, 0, status, sizeof(status));
      Serial.print("Id   ");
      for (int i = 0; i <= 8; i++)
      {
        Serial.print((uint8_t)status[i]);
        Serial.print("   ");
      }
      Serial.println();
      /*
        if (status[2])
        {
          uint8_t modem_status[6];
          rf24.command(RH_RF24_CMD_GET_MODEM_STATUS, NULL, 0, modem_status, sizeof(modem_status));
          delay(100);
          for (int i = 0; i <= 6; i++)
          {
            Serial.print(modem_status[i]);
            Serial.print("   ");
          }
          Serial.println();
        }
      */
      delay(400);
    }

  [1]: http://community.silabs.com/mgrfq63796/attachments/mgrfq63796/BluetoothandWiFi/8086/1/Si446X API DESCRIPTIONS.pdf
  [2]: https://i.stack.imgur.com/i6j6w.png

body:
By using the `RH_RF24 rf24;`(Singleton instance of the radio driver), read a series of properties is really simple.

 - The properties shall be in the same GROUP,
 - Up to 16 properties could be read in the same request,

> Hereafter is a example to read from `SYNC_CONFIG` to `SYNC_BITS_7_0` (5
> properties).

**Step 1** - Declare your own `uint8_t sync_stat[5];` or use the still declared `uint8_t status[8];`.

     uint8_t sync_stat[5];

**Step 2** - The `firstProperty` is in fact the first property to be read and `count` is the number successive properties to be read (from `SYNC_CONFIG = 0x1100` to `SYNC_BITS_7_0 = 0x1104`.

    // And check the returned code
    if (rf24.get_properties(SYNC_CONFIG,sync_stat,5)) {
     // sync_stat[0]= SYNC_CONFIG
     // ...
     // sync_stat[4]= SYNC_BITS_7_0
    }

> Then, the equivalent `command()` is:

    uint8_t buf[3];
    buf[0] = SYNC_CONFIG >> 8;
    buf[1] = 5;
    buf[2] = SYNC_CONFIG & 0xff;
    if (rf24.command(RH_RF24_CMD_GET_PROPERTY, buf, sizeof(buf),sync_stat,5)) {
     // Same array
    }