text:
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.

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.

Thanks you very much, I did not know the name. I searched and found the map to connect to my arduino.


text:
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.

You just need to set the fuses. You can do that using the command line, and the avrdude application. avrdude is somewhere inside the Arduino application folder. You'd run something like avrdude -v -patmega328 -cusbasp -B10 -Pusb -U lfuse:w:0xA4:m -U hfuse:w:0xD1:m  (those fuse values are most likely not the correct ones). Note the -B 10, is to slow down the USBasp programmer, as by default the ATMega328 runs at 1Mhz.

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.

The act of burning the bootloader doesn't burn the fuses. They are actually a completely separate command that is executed in sequence with burning the bootloader. You do not need to burn the bootloader to set the fuses, you can do them separately. Burning the bootloader is an "easy" way of doing it, however you should really learn how to control the fuses properly if you are going to work with bare chips.

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.

Okay. I will try it and will let you know.

source: Stack Exchange

license: Creative Commons - Attribution Share-Alike - https://creativecommons.org/licenses/by-sa/3.0/

sort: votes


text:
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

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

NOTE: Check your board version.  It could also be:
winc1500-uploader.exe --port COM9 --firmware m2m_aio_3a0.bin

all_licenses: Creative Commons - Attribution Share-Alike - https://creativecommons.org/licenses/by-sa/3.0/


text:
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:

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, it could be possible, but i am not definetly sure about that. Maybe you can give me some input about that.

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.

Thanks for the info :) Well i am sad about that, but it sounds plausible indeed.

You're welcome :-) You can search for Microchip's document an1149 (Designing A Li-Ion Battery Charger and Load Sharing System) to get an idea how to use the p-MOSFET and Schottky diode to make battery backup with one 18650. Just replace the MCP chip with cheap 1A Li-Ion charging board and put 5V step-up (boost) board from eBay between that circuit and NodeMCU and that's it. Both boards are very small and you can buy them for about $1 each.

Sounds great. Thanks for your help!

The internal wiring varies from case to case. Most power banks have a separate connector for input and output as in this picture. If you can use the same input/output to charge/use the power bank then it already has some internal circuitry similar to the circuit desciribed in an1149. If you can use the same connector for charging and powering some other device, then your connection will work - as that is NodeMCU in parallel with the power bank. But not many power banks are made that way.

Yes i guess your approach is the simplest one :) Thanks you helped me a lot!

And a question is if such power bank will, upon losing the input, switch to output mode fast enough to avoid reset of NodeMCU. Depending of the internal circuits you might need to add a capacitor. However, better way of powering NodeMCU is to bypass the 5V USB input and to connect 3.3V directly to one of the 3.3V pins. That way the battery will last much longer. You can use serial connection of two 18650s + step-down (buck) converter to get 3.3V.

Yes i guess it's more reliable then. I just didn't use that before, but i am excited to try it ;) And like you said, it doesn't seem to be that complicated. thx


text:
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.

As always, ~ in C++ is bitwise negation.


text:
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:

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?

Other than tying nRESET low?

@IgnacioVazquez-Abrams I'm new to this. What do you mean? Putting some resistor between reset and GND?

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.

I used 2KΩ since that's the smallest I found and it worked. I'll probably add resistors to the other lines too.

I think the Arduino uses 1KΩ between the USB and main MCUs for this same reason. For low(ish) frequencies the resistance isn't that critical. Higher frequencies though can be corrupted by too high a resistance since it acts as a low-pass filter with the gate capacitance of the input pin. 2KΩ should be perfectly fine for the low speeds of ICSP programming.

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.

The Arduino-as-ISP sketch will turn all the OUTPUT pins, connected to the ATTiny, back to INPUT. That way nothing bad can happen, when the ATTiny drives those pins HIGH of LOW.


text:
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?

According to the source code:
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;
};

Thanks, I hoped it is written somewhere in the library docs but this approach sounds very plausible too.

Maybe it even is written somewhere but I've never used Arduino and I don't even have one so I don't know :-) I've been using AVRs for years but only with AVR Studio and ISP programming. Now that you said, if you look at the source of the .h file, there is the: The actual frame put over the air consists of a header (8-bytes) and a message payload (Up to 24-bytes), line in the comments so it might have been picked by some doc generators.


text:
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?

Yes, you can. Both options are valid.

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

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:

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.
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.

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

Or use a USB cable.

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.

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.

all_licenses: Creative Commons - Attribution Share-Alike - https://creativecommons.org/licenses/by-sa/4.0/


text:
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

What is the output of while(serverClients[i].available()) Serial.write(serverClients[i].read());?

It displays infos of the connected client like for putty it says SSH-Putty etc...

Does if(Serial.available()) { ... work as expected? Are the clients receiving the data read from the serial port?

You didn't say the non working block doesn't compile. If you had mentioned that I would've probably given you the solution a few minutes after I saw the question.

Replace the non working code with this and it will compile:
long randNumber = RANDOM_REG32 % 10000;
Serial.println(randNumber);
size_t length = 4;
char randomstr[length];
itoa(randNumber, randomstr, 10);
serverClients[i].write(randomstr, length);

I've just noticed and corrected a mistake in my code, it should be itoa(randNumber, randomstr, 10);, not itoa(i, randomstr, 10);.


text:
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
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.

Chances are there is something wrong with how you built your circuit. Using the same 5V pin for both buttons is perfectly acceptable.

Do I need different ground though? I'll edit with a circuit drawing in minute.

All the ground connections are identical and connected together. It makes no difference which ground pin your use.

There is only one ground. It may have multiple pins on it, but there is only one. Use whatever ground pin(s) you fancy, they are all the same.

@Majenko I edited the question with a circuit diagram, should that be ok?

I hope you don't expect characters '0' .. '3' in the Serial Monitor as you are sending characters: NUL, SOH, STX and ETX (ASCII values from 0 to 3) and they might not be visible.

I'm getting bytes \x00 through \x03 in python so that seems ok at the moment for my purposes.

Most people use a breadboard to easily spit the 5v into multiple wires.

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/


text:
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);
}

Have you confirmed that there is definitely nothing coming out of the TX pin at all?

As far as I can tell nothing comes out. The tx led does not come on. I also tried connecting the pin to an LED and outputting an array of 0b11111111 in a continual while loop figuring it would turn it on but nothing happened.

Serial looks like it works fine. I couldn't compile your program because it didn't like the char *s = { ... } bit. It wanted char s[5] = { ... } instead.

It compiles for me in atmel studio without any errors.

And data is being transmitted fine. It is probably something wrong with your receiver code then.

In UECIDE I get "‣ scalar object 's' requires one element in initializer" - What version of GCC are you using?

In your receiver your use of dynamic memory looks to be completely broken. You start with s undefined, then allocate in your concat routine, and then assign that allocated to s. You then pass that back to concat, allocating again, copying the data, and leaving the old allocation in place. By the end of it you have allocated (and lost) loads of memory - that is if it even starts, since the first pointer you pass to copy memory from is complete junk.

GCC AVR (8bit toolchain) - 3.4.5.1061

How would I fix the memory allocation in the receiver?

See the edit to my answer.

Thanks for the answer. I'll test it tomorrow when I get chance and hopefully it will work.

In the sender, you may want to write char *s = "Toets";. Then you have a properly terminated string (the compiler adds a NULL byte at the end) that you can safely pass to strlen().

I don't understand why no one else asked WHY "without using the software serial library".

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.

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:

Make sure s is initialized to NULL
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
Only do any copying of data if s actually points to some valid data (not NULL)
free() the old data pointer once you have finished copying the data (if it was pointing to real allocated memory)
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.

Thanks for the advice. I've just checked but it doesn't solve anything though.

I didn't think it would, since it is involved in reception not transmission.


text:
Encoder + Bounce2 Library
I am working towards debouncing my keyes rotary encoder using the Bounce2 library found here ( https://github.com/thomasfredericks/Bounce2 ).
I believe the problem lies in my code as there isn't much in terms of a circuit. The encoder is connected to my arduino as follows

5V : connected to 5v out on arduino
GND : connected to GND
SW : connected to pin A1
DT : connected to pin 3
CLK : connected to pin 2

I am trying to call an ISR from a CLK input. When the ISR is called it should increment or decrement a value based on the direction the encoder was turned. This encoder is tied to an ISR because it will be used for user input and I would like it to remain responsive throughout the sketch.
Previously, I was using millis() to debounce the encoder, but I was still having trouble receiving more than one input from the encoder. I was hoping that this libary would resolve this issue.
The current output of the code I have included never increments/decrements the starting value no matter which direction the encoder is turned. In short, it always outputs 0.
If someone could explain what I am doing wrong that would be wonderful! Then maybe, but just maybe, I can stop beating my head against my desk. :p
Thanks,
Kevin
#include <Bounce2.h>

#define sw A1
#define LED_PIN 9
#define clk 2
#define dt 3

int ledState = LOW;
int onOff = LOW;

volatile int virtualPosition = 0;
int lastCount = 0;

// Initiate bounce objects
Bounce debouncerSW = Bounce();
Bounce debouncerROT = Bounce();

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

  pinMode(sw, INPUT_PULLUP);
  pinMode(clk, INPUT);
  pinMode(dt, INPUT);
  pinMode(LED_PIN, OUTPUT);

  // set up button instace
  debouncerSW.attach(sw);
  debouncerSW.interval(100);

  // set up rotary encoder instance
  debouncerROT.attach(clk);
  debouncerROT.interval(10);

  // setup the LED
  digitalWrite(LED_PIN, ledState);

  // attach ISR
  attachInterrupt(digitalPinToInterrupt(clk), isr, LOW);

  Serial.println("Start"); // just to let me know sketch has finished setup
}

void loop() {

  debouncerSW.update();

  if ( debouncerSW.fell() ) {
    ledState = !ledState;
    onOff = !onOff;
    digitalWrite(LED_PIN, ledState);

    //read-outs
    Serial.print("onOff = ");
    Serial.println(onOff);
  }
  virtualPosition = lastCount;

  //read-outs
  Serial.print ("lastCount = ");
  Serial.println (lastCount);

  delay(1000); // for readability / simulates delay time for rest of main sketch
} // end main loop

void isr ()  {

  // Update the Bounce instance :
  debouncerROT.update();

  if (debouncerROT.fell()) {
    if (digitalRead(dt) == LOW)
    {
      virtualPosition -- ; // Could be -5 or -10
    }
    else {
      virtualPosition ++ ; // Could be +5 or +10
    }

    // Restrict value from 0 to 100
    virtualPosition = min(100, max(0, virtualPosition));
  }
} // end ISR

I also want to note that no form of hardware debouncing is in use. The rotary encoder is connected directly to the arduino with no passive components in place.

See my answer to How to read RPS for fast rotation with status change method in Arduino?.  Also see my comment to other answer there,  “Implemented with a state machine, quadrature coding does not need debouncing. Bounce can cause invalid states or extra states, but they cancel out.”  In other words, debouncing rotary encoder inputs is a wrongheaded approach.

@jwpat7 Thank you! I will take a look!

I’ve always found with encoders that hardware denouncing saves me a lot of trouble.  All you need is a couple of small caps.


text:
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 ?

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.


text:
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?

You know you don't need to use interrupts for this. You can instruct the timer to change the output pin when the counter overflow or reaches OCR1A. You do this with the COM1A1 COM1A0 bit in the TCCR1A register. Though you'd have to use pin 9 (or 10) instead of pin 8.

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() {

}

Thank you kindly, can you please update it to work on a timer0 intrerupt?

@adrya407 I wouldn't recommend it, as the Timer0 is used for millis(), delays and so on. If you change ticks from 1.024ms (overflow interrupt), to CTC with exactly 1s (compare match interrupt), then overflow will not work anymore at all.

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

On the UNO all three of these timers are involved in PWM timing. Where the claim about Timer1 come from?

license: Creative Commons - Attribution Share-Alike - https://creativecommons.org/licenses/by-sa/4.0/


text:
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 ?

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

Thank you. If that wouldn't be so sad it would be a joke...

http://forum.arduino.cc/index.php/topic,22737.0.html is the older discussion, with pics of early prototype boards.

Arguably, if shields could be plugged in either way around (and the wrong way damaging the Arduino and/or the shield) then that could be called bad design.

@NickGammon  That's the feature part.    Maybe a better way to key a protoboard/shield would be to block a pin or two.  I think I remember seeing a red plastic plug used to block/key a in the socket on a IDE disk drive connector.

That is probably a better idea. Ah well, it's like the old joke: "There's no reason for it, it's just always been done that way!"

It is a mistake that became a feature for polarizing the shields: forum.arduino.cc/index.php?topic=117441.0
In an 2008 discussion 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:


text:
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).

I'm voting to close this question as off-topic because it is about mobile network standards, not about Arduino.

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
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
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.
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 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.


text:
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:

#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?

That's really interesting, I'd like to know what exactly is going on too.

Sounds like the SD-FAT library is loading the directory structure, File-Allocation tables, building it's 'representation' of the SD cards usage/layout.  Do you experience the delay during the FILE0000.TXT opening?  The .Trash-1000 subdir likely triggered a full scan of the directory layout as SD-FAT looked for FILExxxx.TXT.  Remember you're on a memory constrained device, and the SD-FAT library must keep it's memory usage minimal, so blocks/sectors are repeatedly read and dumped instead of being cached as is done on (much) larger memory systems. This will slow access dramatically.

You would probably get a huge speed increase by splitting your files into directories, such as 3/6/FILE3672.TXT

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.

Why to change the file structure if, as stated in the question, the delay can be eliminated with just one line of the code?

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?

authors: محمد مثنى رحمان ابراهيم


text:
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.

Add code to check when String fails :)

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());
      }
    }


text:
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.
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

Could you replace your code with a minimal, complete and verifiable example (http://stackoverflow.com/help/mcve) please (remove the random part - use a well-defined input for this purpose), as well as the output you expect?

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.  (If you see encrypted stuff in printable format, usually it's base64 encoded.)


text:
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.

Have you heard of Ohm's Law?

@majenko I'm familiar enough with the concept for a typical series circuit or parallel circuit from a single tutorial or two, but that's about it. Branching off between the button and resistor is the bit that confuses me on how to calculate it here (I believe).

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.

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.


text:
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/):

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.

The easiest way to get these sort of timing signals is to use and Audino or similar. Put the sensor in as an input, and each step as its own output. Would give you the flexibility of time control as well, so you can tune the effect to whatever you want. Would also easily allow for expansion with a sensor at the top of the stairs.

motion activated LED's are annoying.  I prefer to leave them on always.  Using Blue or Red for effects and mounted directly under handrail.  You can drive from 12 to 14.2V to adjust brightness and feed with hidden phone wire. Les DEL activées par mouvement sont ennuyeuses. Je préfère les laisser toujours. Utilisation de bleu ou rouge pour les effets et monté directement sous la main courante. Vous pouvez conduire de 12 à 14.2V pour ajuster la luminosité et l'alimentation avec le fil téléphonique caché

You seriously want an Arduino for this. Software is easier and cheaper than hardware, and it's easier to change as you iterate (get experience, discover problems and find better ways).  You could also do cool things with colors if you had 3 outputs per LED strip.

Theoretically, you've got enough I/O to not use a shift register? You could also use a "digital led strip" which have individually controllable LED's. But aside from that, your option seems good.

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.

Yes, it is my first throught too, but I don't know which transistor I have to use. And Should I put the transistor before or after the LED strip ?

Take a look at my answer to similar question so you can get an idea how to use the transistors to light the LED strip.


text:
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"
}

How do you know you can't receive it since you aren't doing anything with it if you do receive it?

under ReceivedByte = UDR0;
i put USART_Transmit(ReceivedByte);
but still i didnt receive anything at the serial monitor

Does the serial monitor still work if you are intercepting the data via interrupts?

no it didnt work
i dont know whats wrong with my code
i using termite , but still i didnt receive anything
how can i receive a letter via uart by interrupt ? and how to receive a string via uart

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.

hey Nick .. i changed the name of the vector but still the interrupt function didnt work... ( i transmitted the received value )

Can you please edit your question to show the exact code you are currently using?  One thing you could do it turn on an LED (eg. digitalWrite (13, HIGH);) inside the ISR to test whether or not the ISR is called. Perhaps the transmitting of the received value is not working.

See amended reply.

thx a lot nick the code is now working ..
but whats the size of UDR0 because it can hold a whole string received via UART ,i thought it was 8 bits and can contain only a letter

UDR0 will hold one byte. I think the hardware has a double buffer (that is, it can receive the next byte while you are retrieving the most recently-received one).


text:
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 :)

All my IR receivers require a pull-up resistor on the OUT pin.

Are you sure you don't have it wired up backwards?  This package would be easy to turn around.   It can also be mounted with the lenses either upright or to the side, adding additionally possibilities for confusion.

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, 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.

From the datasheet, it looked like there was already a 33kOhm pull-up in the component itself. 4.7K is probably fine. The value doesn't really matter that much.

If there's a Pull up resistor inside it already, why does it need  another? Is there anyway to get around needing an extra one?

My first thoughts were its either to week or its disabled by some configuration option, but I doubt either of those would be the case here.
Is it possible that the internal one is suitable when VCC is at the lower end of the range (1.8V) and not suitable at the upper end of the range?

You should not need an external pullup resistor unless you have something else loading the line or are running the Arduino at a substantially higher voltage than the sensor.  In theory a very high data rate could cause that to be needed, but the sensor can only respond so fast to begin with, so that is probably not an issue.

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


text:
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?

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.

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.

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.


text:
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 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.
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 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!

The ICSP pins have two functions:

For programming the ATMega328P directly using a hardware programmer (In Circuit Serial Programmimg)
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


text:
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?

Please edit your question to include a Minimal, Complete, and Verifiable example of code, not just snippets.   For example, as is we've got no way to tell if sensorValue is volatile

Just a little precaution. Do not call Serial.print() on ISR. An Interrupt Routines should be completed and returned as soon as possible.

sensorValue is not changed on anywhere else on the code. I am aware that using    Serial.print()  on ISR is not a good idea. Serial print will be deleted from the code once the project is complete. Right now, I am using a high baud rate (actually 2000000 works best) to compensate.

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

See the datasheet:

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.

Thanks!! You were right. I forgot all about that! I changed admux to '0x40' and that solves the problem. Also thanks for the serial print issue. I'm aware it's bad and will remove that bit once development is complete. Right now, I am using high baud rate (2000000) so that isr is not affected that much.


text:
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?

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) for you.
As for the library you can use this one here
Also you can refer this article for detailed usage here
And I hope next time you put in some more research and then buy a new part.

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.

Comments are not for extended discussion; this conversation has been moved to chat.

The ADXL345 module already has a level shifter.

@SupragyMishra How do you know? No specific module has been specified, only the chip that is on the module.

Most modules ship with a shifter and note that he refered VCC not Vdd (digital supply) and Vs (supply voltage)

@SupragyMishra A module having a voltage regulator (common) does not mean that the module has a logic level translator (rare). The Adafruit one is the only one I have found that has a level translator. All the others don't. VCC and VDD don't imply any voltage. One is the collector voltage (from the old TTL days) and the other is the drain voltage (CMOS terminology). Nothing there implies any voltage.

@Majenko Okay. I did my research and yeah the pins DONOT imply any voltage... And the ADXLs I have with me do have a regulator not a SHIFTER. But the 5v logic works okay with the I2c Lines. So i just assumed it would work with Dimchtz's sensor

@SupragyMishra In general I2C is fairly tolerant of differing voltages as it's an open-drain bus system. Pull the bus up to the higher voltage and hope the current through the pullup resistors isn't too high for the ESD diodes in the lower-voltage device. The majority of times that's perfectly fine.


text:
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
Original SoftwareSerial library

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.
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.

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:
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.

Thanks for your reply, but first issue doesn´t solve the problem with serial data.
I have edited the code, but still it doesn´t work.

Of course it does not resolve the issue, as I explained you cannot send raw numbers and have string representation. When you send number 1000, that is 0xe8, 0x03 (232, 3) because 1000 = 3*256 + 232. 232 and 3 is not 0x31, 0x30, 0x30, 0x30 which is String("1000"). To have string "1000" you have to send 0x31, 0x30, 0x30, 0x30. I will give you the code in an hour or two as I don't have time at the moment.

Here you are the code to send the number as a string. I'll take a look at other things later when I have time.


text:
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!

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);
  }
}

How far have you got? Are you able to send data from the app and receive it in your sketch?

well i have completed both in 2 different sketches that is i can control it manually(send and recieve data from app) in one sketch and run the normal program in the other. when i tried to merge them only the normal program worked and when i entered one in serial nothing happens. @MarkSmith

Could you add the second sketch to your question, please?

There @MarkSmith

You should learn about finite state machines for this task.

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);
    }
  }
}

this wont allow the normal program to run(the automatic detection thing)i wanted both to run at the

@Dhruva you can simply add your former program after it. I edit my answer


text:
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).

You could place all your code in a separate .cpp file, and call that from your .ino file. That way your ino file will just be a few lines. You might even be able to just use a single include.

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.


text:
Extracting bits from hex encoded binary
I've been using an Adafruit Huzzah ESP8266 Breakout to read data from an OpenTherm Gateway 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:

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, "%c%08x", &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.

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.

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() {
}

I think you're missing the bit that mentions that the value is in a string prefixed with a character (B or T). msg.uint32 = 0xb501812f3; will overflow since you have 36 bits there, and 0xt501812f3 isn't valid hex.

@Majenko Missed that but I am addressing methods of extracting bit-fields :). I do not want to event approach the whole idea of going for text notations.


text:
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?

In the arduino IDE you can set the option "use external editor". Then you can use your own favorite editor, like Notepad++ or Sublime Text. You will then only use the Arduino IDE for compiling and uploading.

Instead of keeping all the 1500 lines in a single .ino, why not creating your own library with its .cpp and .h files ? It is quite easy when reading  that "Arduino Libraries - Manual installation".

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.

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

@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.

I can't help but recommend UECIDE, 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.

Yes, I personally experienced that a single file isn't good at all. What would be a good way to create separate units? Is the creation of libraries the only way to do that?

The creation of libraries is a good way to do it, though editing them can be more difficult than using the IDE. It's easier in UECIDE since you can have libraries embedded within your sketch and edit them in the IDE.  Just making C++ instead of INO files (.cpp instead of .ino) in the normal Arduino IDE keeps things separate too.

authors: Рынок Падает