text:
Arduino Uno serial communication using USB-to-TTL converter
How to send data (Hello World) from Arduino Uno to a PC using USB to TTL/UART (PL2303 4 wires)? Why do I need to press the reset button to upload a program using PL2303?

How to send data(Hello World) from Arduino Uno to PC using USB to TTL/UART(PL2303 4 wires)?

Serial.print("Hello World");

That is, assuming it's connected to pins 0/1. Otherwise you would have to use SoftwareSerial.

why I need to press the reset button during upload a program using PL2303?

Because it lacks a DTR signal to press the reset button for you (resetting runs the bootloader).

Thanks Majenko. I have tried that code and it works when I use normal USB. But when I am trying to upload sketch with PL2303 it doesn't work. I have pressed the reset button manually just before uploading the sketch. I have tried other way.. that is.. I have uploaded the sketch with normal usb and after uploading the sketch I have changed the serial port to Pl2303. but it still not working. I am really getting confused as well as frustrated.

How is the PL2303 wired? Why are you trying to upload a sketch using it when you already have a perfectly working USB connection?

I have connected arduino rx to pl2303 tx and arduino tx to pl2303 rx and the ground pin. It's a task of mine given by my tutor.

Are you powering the board from the normal USB connection? If so you may well find you have to remove that connection and power it from some other source, since the on-board USB to UART interface may well be interfering with what you are trying to do.

Ya. I have powered my board with normal USB connection. But before I used the VCC pin of PL2303. But in the datasheet of Pl2303 they warned to not use the VCC pin (exactly don't know why). So I powered the board by normal USB. If I assign the RX/TX  on a different pin (other than 0 and 1). It's also not working. But i never tried external voltage source.

You can't assign TX and RX anywhere. They are on 0 and 1 and that is fixed. You could use SoftwareSerial instead of Serial to (just about) use any other pins, but you certainly won't ever be able to upload firmware that way...

I think you have a PL2303 board that do not have DTR or RTS line. It is a signal from Arduino IDE to Arduino Board for reset. So you must press reset button before upload.


text:
Arduino UNO vs NANO or MICRO with RPi3
I'm currently using an Arduino UNO with a raspberry pi 3b. I'm using the USB connector for both power and comms, i.e. the arduino is powered by the RPI via the USB cable, and also i use the same cable for serial communication between the pi and the UNO.
My question is, could i use the same code, and wiring if i were to change the UNO with a NANO or MICRO?
So for example, on the RPI side of things, could i still simply setup the arduino in my python code as
arduino = serial.Serial('/dev/ttyACM0', 9600)

and send commands with something like
arduino.write('2')

and on the arduino side of things, just check if there is serial data coming in and read it, like
if (Serial.available()) {
    command = Serial.read();

I know this may be a very stupid question, but to wrap it up, would anything change other than number of analogues, digitals etc, if i were to switch from an UNO to a MICRO or NANO?

The Nano uses the same chip (ATMEGA 328P) that is on the Uno.  So putting the same code on the Nano should work the same as the Uno.
The Micro uses a different chip.  Whether or not the code from your Uno will work on your Micro depends on what is in the code.  You chose not to show anyone the code so that can't be answered yet.

Thanks for the answer. Would i still be able to communicate with serial libraries from both sides? From RPI to arduino and vice versa? and simply using just one USB cable for power and comms? That's my only worry regarding the code.

Let me say it one more time.  The UNO and the Nano use the same chip.  The difference is the shape of the board they are on.  Code for one should work on the other.  You haven't given enough information to answer about the micro.

The Raspberry Pi has to recognize the serial chip on the Arduino Uno. The Uno and Nano use both the Atmega328p microcontroller, but that chip has not to do with the usb-serial. The usb-serial chip could be different. Arduino clones could have yet another usb-serial chip. The Arduino Micro uses the Atmega32u4 itself as usb-serial chip. So far I have not encountered a problem, but I'm not sure that all three will work. Give it a try and tell us which usb-serial is on the Arduino board and if it is recogned !

source: Stack Exchange

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

sort: votes


text:
Getting current epoch time in seconds and milliseconds
Using Arduino Yun.
My code:
time_t today;
time_t now;
...
void setup() {
  time(now);
...
  Serial.println( asctime(gmtime(&now)));

What I get is:

Sat Jan 01 00:00:00 2000

I am expecting something like this:

1507572195.825

How do I get the number of seconds and milliseconds since the Linux Epoch?

I think that what you are looking for is the function now(); which returns the current time as seconds since 1 Jan 1970. Read more about the Arduino Time Library .

This may be of more interest - how to get the time from the Linux processor (which if you are online should be correct) rather than some random number the Arduino defaults to...

now(); is giving me the number of seconds from when the script started running rather than from Jan 1970.

Majenko - Getting very close. Using:
if (!date.running()) {
date.begin("date");
date.addParameter("%s");
date.run();
}
I get seconds. How would I get seconds and a partial second like :1507586961.159

You may try +%s.%N as a parameter. On a standard Linux distro this gives seconds and nanoseconds. I have no Yun to test that though.

@Edgar Bonet:
Unfortunately %N does not return nanoseconds on the Yun. It just gets echoed back like it is text %N. Using +%s.%N get me 1234567890.%N

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


text:
Wiring a RT314F12 latch relay to an Arduino
I want to automate the lights in my house. To do this, I want to use a latching relay, so it will only use current when switching. I found a quite cheap latching relay RT314F12 but I do not know how to wire it up to an Arduino. Can any one please give a wiring example?

It's a two-coil relay. Treat it exactly two normal relays. The middle coil pin is the common between the two coils.

you send it "turn on" and "turn off" pluses on different pins. instead of setting one pin to a constant state. those pins should go through an opto isolator since you're working with mains. latchers are neat, i played with the idea a lot for the same purpose, but now i use mostly DC lighting with mosfets (i need dimming)...


text:
Traffic lights: gpios against 5V or ground
I have 3 standard LEDs (red, yellow and green) connected in parallel to GPIO pins 10, 11 and 12. I also have one resistor, to which they are all three connected.
What's the difference between connecting the resistor to ground (so that the leds are high active) or to the 5V output pin of the arduino (so that the leds are low active)?
Moreover: how many ohms should the resistor have?
My understanding is: each of the 3 standard LEDs needs 20mA, so, if all three are lit, there is 60mA on the circuit. The 3 parallel LEDs need 2 V.
So, the resistor should be chosen such that it has a voltage drop of 3V at 60mA, hence 3V/60mA = 50 Ohm. If only one is lit, I need 3V/20mA = 150 Ohm.
But, if its possible that every possible subset of the LEDs is lit at once, wouldn't it be better, to place a resistor in front of every LED, so that I have 3 LED-resistor pairs in parallel? The value of each resistor is 50 Ohm then, allowing for a voltage drop of 3V in each of the 3 branches, so that each LED only gets the needed 2V?
Well, a lot of thoughts for 3 simple lights...
Thanks for any help.

different colors have different forward voltages, thus different resistor needs given the same source voltage.

I have 3 standard LEDs (red, yellow and green) connected in parallel to GPIO pins 10, 11 and 12. I also have one resistor, to which they are all three connected.

BAD BAD BAD!!!

What's the difference between connecting the resistor to ground (so that the leds are high active) or to the 5V output pin of the arduino (so that the leds are low active)?

Nothing, other than the reversed logic. AVR GPIOs (and most GPIOs in modern MCUs) are balanced - i.e., they have the same current limit for both sink and source.

Moreover: how many ohms should the resistor have? My understanding is: each of the 3 standard LEDs needs 20mA, so, if all three are lit, there is 60mA on the circuit. The 3 parallel LEDs need 2 V. So, the resistor should be chosen such that it has a voltage drop of 3V at 60mA, hence 3V/60mA = 50 Ohm. If only one is lit, I need 3V/20mA = 150 Ohm.
But, if its possible that every possible subset of the LEDs is lit at once, wouldn't it be better, to place a resistor in front of every LED, so that I have 3 LED-resistor pairs in parallel? The value of each resistor is 50 Ohm then, allowing for a voltage drop of 3V in each of the 3 branches, so that each LED only gets the needed 2V?

Yes. That is how you should wire LEDs - and you have already identified why.
For each LED calculate the resistance as R=(5-Vf)/0.02. You need to find the correct Vf for each LED from the datasheet to get the best results - but if you can't then a rule of thumb is: Red, Green and Yellow are about 2V, Blue and White are about 3V.


text:
Send Email through Cayenne serial connection
I have an Arduino Uno connected to Cayenne through the serial connection, currently i am reading the data from a sensor of temperature and humidity DHT12 and showing it in the Dashboard of Cayenne correctly.
I need to know if i can send emails from the Arduino using the connection that cayenne let me use, because i can't stay with the pre-defined alerts that the platform have.

I suspect you would be better off seeing if you can configure Cayenne to send the emails for you.  Imagine what a pain it would be getting the Arduino to generate the string that contains the email and the headers.

Yes, I can send emails with Cayenne, but I want to personalize the emails.

No, the Arduino cannot send emails directly through serial. The communication channel you have set up is a direct connection between the Arduino and Cayenne. It cannot be used for anything else other than communicating with Cayenne.
However that doesn't mean you can't try and see if there is some way of making Cayenne send emails for you. Having never used Cayenne I cannot comment on this aspect. You would be better off consulting directly with Cayenne and their users through their forums.


text:
Storing byte array from serial and converting to a floating point number
I have tried getting my Arduino to communicate with another device, to no avail. The command A, when sent via serial to the device, triggers it to respond with 8 binary bytes with the first 4 representing a floating point number, and the final 4 representing a floating point number. The command only has to be sent once a second, and the aim is to store the 8 incoming bytes in an array, and convert them into their respective floats.
unsigned long previousMillis = 0;
const long interval = 1000;
char incomingByteA[8];

void setup() {
  Serial.begin(9600);
  while(!Serial);
  Serial1.begin(9600);
  while(!Serial1);
}

void loop() {
  unsigned long currentMillis = millis();
  if(currentMillis - previousMillis >= interval){
    //1 second timer
    previousMillis = currentMillis;
    Serial1.write('O');
    //Send command 'A' to device *noting Serial1 not Serial
    for(int n = 0; Serial1.available() < 8; n++) {
    incomingByteA[n] = Serial1.read();
    //Add each consecutive byte to an array until all 8 bytes have been added
  }
  float x;
  float y;
  ((byte*)&x)[3] = incomingByteA[0];
  //Convert first four bytes into a float
  ((byte*)&x)[2] = incomingByteA[1];
  ((byte*)&x)[1] = incomingByteA[2];
  ((byte*)&x)[0] = incomingByteA[3];
  ((byte*)&y)[3] = incomingByteA[4];
  //Convert final four bytes into a float
  ((byte*)&y)[2] = incomingByteA[5];
  ((byte*)&y)[1] = incomingByteA[6];
  ((byte*)&y)[0] = incomingByteA[7];
  Serial.println(x, 4);
}
}

However, when I do Serial.println(x);, it returns "nan". And if I try to do Serial.println(incomingByteA[2]);, it returns "?".
The following is the floating point format as per the device protocol:
31: sign of mantissa, 1=negative.
30-23: exponent, biased by 128.
22-0: mantissa, 24 bits, MSB hidden and always=1.
The mantissa is normalized, 24 bits with the MSB hidden. The MSB is always
assumed to be 1, therefore only 23 bits are needed to store the mantissa. The exponent is biased by 128; i.e. a 128 value represents an exponent of zero. A 129 value is an exponent of 1. Example: if the exponent has a 131 value (+3), the number is 2^3 * (mantissa). The mantissa is always less than one, and greater than or equal to 1/2. The number zero is stored as four zero bytes.
I am confident that it is not a fault with the hardware and for what it's worth, I am using a Leonardo. I would like to get the code down pat before I stress about hardware issues. What is this code not doing properly, if at all?
Thanks in advance.

Why not read directly into the float's address?

Two things I see wrong:

Serial1.write('O');                                            //Send command 'A' to device *noting Serial1 not Serial

No, you send O not A... ???

for(int n = 0; Serial1.available() < 8; n++)

While there are less than 8 bytes available in the buffer read one.
Erm...  The buffer starts off empty - empty is less than 8. It remains empty (always less than 8) until a byte finally arrives. Then it's still less than 8. I can't really see this ever working, and your array will overflow instantly and clobber the entirety of the rest of your RAM. I guess it finally finished when the serial object itself gets clobbered and available() returns some garbage number. In the meantime your array is just full of nothingness.
You need to completely rewrite that whole section. The simplest way is to wait until there are 8 bytes in the buffer (which will take some time - serial is slooooow):
while (Serial1.available() < 8);

You now have 8 bytes available to read, so you can go ahead and read them.
A better way is to look to see if there is at least one byte available, then read it into the right place in your array - and keep count of how many bytes you have read:
int n = 0;
while (n < 8) {
    if (Serial1.available()) {
        incomingByteA[n++] = Serial1.read();
    }
}

Of course, it's better to add some form of timeout in there too - so if nothing arrives soon enough your program doesn't lock up - or if you miss a byte it doesn't get completely out of sync. Also purging your read buffer before sending the command can help to prevent sync issues:
// Purge any old data
while (Serial1.available()) {
    Serial1.read();
}

Serial1.write('A');

int n = 0;
uint32_t start = millis();
while (n < 8) {
    // 1 second timeout
    if (millis() - start > 1000) {
        break;
    }
    if (Serial1.available()) {
        incomingByteA[n++] = Serial1.read();
    }
}

if (n == 8) {
    // We got the data - do something with it
} else {
    // It timed out
}

Now when it comes to converting to a pair of floats there's better ways than your byte-wise manipulation.  For instance, you could use a union:
union FloatPair {
    struct {
        float a;
        float b;
    };
    char bytes[8];
} __attribute__((packed));

FloatPair data;

Now you can use:
data.bytes[n]

to access the memory directly, and
data.a;
data.b;

to access the float values.
You can also do something similar with casting:
struct FloatPair {
    float a;
    float b;
};

FloatPair data;

char *bytes = (char *)&data;

bytes is now a byte-wise view of the memory used by a pair of floats.
You can even work the other way around:
char data[8] __attribute__((aligned(4)));

The aligned attribute will force the address of the array to be on a 4-byte boundary. Not important for a little 8-bitter, but vital if you ever port to a 32-bit MCU since a float always has to be on a 4-byte boundary, so a good habit to get into.
Now you can map floats into that memory space:
float *a = (float *)(&data[0]);
float *b = (float *)(&data[4]);

and access the floats as *a and *b. The * dereferences the pointers back into real numbers.
One thing to note: these methods all depend on the endianness of your data matching the endianness of your MCU - if they differ then you will have no choice but to do it all with manual byte-wise mapping.

Thanks for the quick reply! I typoed 'O' I did mean to write 'A', I will implement your technique for obtaining and storing the bytes. Could you please elaborate on "endianness"? As far as I know, isn't it just the order in which the most significant bits are arranged? If so, as per the protocol manual, then it's are ordered from left to right as most significant,  to least significant. Cheers

That sounds like big-endian. I think the AVR CPU is little-endian. If they don't match then you will have to manually swap the bytes around and make sure they get in the right places in your floats.

This thread may help you understand.

Thanks again for the reply. I tried comprehending that thread. If the CPU is little-endian, doesn't that mean I just work from least significant to most significant instead?

Yep. That's right. 0->3, 1->2, 2->1 and 3->0 byte mapping

Does that mean I should keep my current code for that process so I can simply reverse the order?

Yes, your current code for the assigning of the values looks reasonable for swapping the bytes around (which it looks like it may already do). You can still use the union method though, since that gives you access to the individual bytes - just write them in reverse order (7-0 instead of 0-7).

Thank you Majenko for your fast help!
I believe that the code is now alright. I will look at using the union method this weekend. For now, however, this is the final code.
 byte incomingByteA[8];

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

 Serial.begin(9600);
 while(!Serial);
 Serial1.begin(9600);
 while(!Serial1);

 }

 void loop() {

 // Purge any old data
 while (Serial1.available()) {
 Serial1.read();
 }

 Serial1.write('A');

 int n = 0;
 uint32_t start = millis();
 while (n < 8) {
 // 1 second timeout
 if (millis() - start > 1000) {
    break;
 }
 if (Serial1.available()) {
    incomingByteA[n++] = Serial1.read();
 }
 }
 float x;
 float y;
 if (n == 8) {
 ((byte*)&x)[3] = incomingByteA[0];                             //Convert first four bytes into a float
 ((byte*)&x)[2] = incomingByteA[1];
 ((byte*)&x)[1] = incomingByteA[2];
 ((byte*)&x)[0] = incomingByteA[3];

 ((byte*)&y)[3] = incomingByteA[4];                             //Convert final four bytes into a float
 ((byte*)&y)[2] = incomingByteA[5];
 ((byte*)&y)[1] = incomingByteA[6];
 ((byte*)&y)[0] = incomingByteA[7];

 Serial.println(x);
 } else {
 // Some timeout response
 }

 }

What I find odd, is that Serial.println(x); returns "8.00" followed by several, random lines of "0.00". Yet Serial.println(x); returns just "0.00". I am simply putting this down to the device I am trying to communicate with though.
Harry


text:
Programing a Mini 05 without a USB-to-serial converter
I have an Arduino Mini 05 clone Wattuino, an Elegoo Mega, a Powerboost 1000c, but not access to a USB-to-serial converter. Is there any way to program the Arduino Mini with these devices?
I tried to search it but they only mention using an Arduino uno as the chip can be put out of the board. Discusion

You can use the Mega. The only reason for "removing the chip from the board" is to disable it so it doesn't respond to the serial data - you can also disable it by just connecting the RESET pin to GND.


text:
Leonardo clone being recognized by Windows as a broken Linino One - wtf?
I'm running a Velleman VMA103, which is advertised as a clone of the Leonardo. Both use the 32u4 chip, and the pinout is exactly the same. However, when I plug it in, the drivers do something weird.
For about 5 seconds after pressing reset, the Arduino IDE will recognize the Leonardo on COM9, and the Windows device manager will show "Arduino Leonardo bootloader" then, the COM9 device will disappear and a device will be shown in the Other Devices tab as a LININO ONE, with no drivers installed. How is this possible?
I've reinstalled the IDE, no help there.

How is this possible? The quick answer is "Windows". Obviously the plug-and-play manager is playing you a trick. If you really want to dig into this start by checking the USB signatures. The bootloader might be presenting an "illegal" signature which is owned by another company.

USB is a complex protocol.  There is a USB device and vendor ID used to tell the difference between a USB printer and USB camera.  Perhaps the clone is not setup correctly.  Connect the clone to a Linux computer and type "lsusb".  Or, you may have multiple drivers installed on your Windows machine all fighting to be used by the USB device.  You didn't say what Windows you are using - so search for how to deal with this on the internet.

Test it with another computer. If that is the same problem, then you should burn new firmware into it (the official Arduino Leonardo firmware). That should get rid of all the nonsense. Do you have a programmer or a Arduino Uno board that can be used as a programmer ? Once that is connected properly then you can use the Arduino IDE to burn new firmware.

USB associates a driver, and thus what it calls a device, with the VID and PID that the device announces. Arduino PIDs are in a horrible mess, and there are many different devices that use the same PID. On top of that you have other makers also using the same VID/PID pairs and providing their own re-named Arduino driver files for their devices.
And then of course you have the problem that it is down to the firmware ("sketch") installed on the Leonardo that determines what VID and PID is shown to the computer.
So you have a set of possible scenarios - the main two being:

You have a driver installed that identifies the VID/PID pair of the Leonardo as something else
You have firmware installed in the Leonardo that gives the wrong VID/PID pair for your drivers

Check 2 first by installing the Blink example into the Leonardo (you can still upload firmware since it goes to bootloader mode at first as you have seen). If it changes the shown driver then you had some broken firmware installed. If it doesn't then you may be running a patched installation of the Arduino AVR core that gives a different default VID/PID pair, or you may just have the wrong board selected in the menu.
If you still have trouble then uninstall whatever driver is associated with the detected device and reinstall the official Arduino drivers that come with the IDE.
You can also delete the IDE and its associated downloaded packages and reinstall the latest version to ensure that you don't have strange patches and settings in there corrupting things.

A Leonardo sketch can change the Leonardo's VIP/PID values?  I didn't know that.  Regardless, perhaps it would improve the answer if you made it clear that this is possible only on some Arduinos.  I'm thinking the old Arduino Uno's had an FTDI chip with fixed VIP/PID values.


text:
Reading 4 to 20ma pressure sensor using uno
I have a OsiSense™ XMLP pressure sensor that I want to read from my Arduino uno. This is the circuit I am looking at building for measure 4 to 20 milliamp.

I've read online to find out how to build the circuit.  Can you tell me if it is correct?
Also I dont understand why it works and I'm hoping you can correct my thinking.  Following ohms law we want to leave 5v when 20 milliamps goes through the circuit.  We know the voltage on the circuit is a constant 24 volts (short cable runs) and we know the maximum current is 20 milliamps so my maths says :
Resistance = Voltage  / I (current)
We need to leave 5 volts for the Arduino to read when the sensor is at maximum pressure so we subtract 5 from 24.
Resistance = 19  / 20 milliamp
So the resistor to select to give us a maximum of 5 volts is a 0.95 Kilohms resistor.  I dont see where the 250 ohm resistor comes in? please help.

To read a current with the Arduino you first have to convert that current to a voltage - and you do that by passing it through a resistance. The voltage dropped across that resistance as the current changes is what interests you.

simulate this circuit – Schematic created using CircuitLab
For a 4-20mA current you need to choose a resistance that gives voltages that are within the 5V range that an Arduino can read.
The biggest voltage drop across the resistor will occur when the current is at maximum (20mA) so you can use that to calculate a good resistor value to use:
R = V/I = 5 / 0.02 = 250

And for the same resistance at minimum current:
V=IR = 0.004 × 250 = 1

So across the resistor you would get between 1V (4mA) and 5V (20mA).
250Ω resistors aren't that common, so a more common value would be used instead - such as the commonly available 220Ω.  Substituting the 250Ω for a 220Ω would give voltages:
@20mA: V=IR = 0.02 × 220 = 4.4V
@4mA:  V=IR = 0.004 × 220 = 0.88V

Both comfortably within the Arduino's range and also gives a bit of wriggle room in case of any small over-current conditions.
It can also be good to protect the analog input of the Arduino with a resistor + zener diode to prevent damage in the case that the resistor fails / becomes disconnected and you get the full output voltage applied direct to the Arduino:

simulate this circuit

Thanks for getting back to me so quick.  I'm still not understanding correctly.  ill have another read tonight and let it sink in.  As you can tell, im fairly new to this so maybe missing some basic understanding.

In the second circuit R2 is just there to limit the current through the zener in the case of an over vintage situation. R1 is the same as in the first circuit and takes 99.9999% of the current through it to create a voltage drop.

@Majenko what is the leakage current of the 1N4733A at 5V ? When R1 got a loose leg, and 24V would be at R2, then a continuous voltage of 24V requires a resistor of 4W for R2. For basic protection making R2 10k and removing the zener will work as well.

You're fixated on 24V. Forget 24V. That is the maximum it could be when open circuit. It should never be more than 20mA, which is 40mW through a 100Ω resistor.

Sorry, I forgot that the current is maximum 20mA. The leakage of the zener diode is probably too small to have any influence. Even more so when you set the 20mA to 4.4V. Sorry again. I get it now.


text:
4 digit 7-segment display
What happends if I turn on all LEDs at the same time in an 4 digit 7 segment display? that would be 32 LEDs turned on at once, wouldn't that exceed the 200ma MAX for the arduino output?

Which 7-segment display? Different displays need different currents. The answer is in the datasheet for the display. Which Arduino? Different Arduinos can supply different amounts of current.

Arduino uno. the 7 segment display is YY3641AH which I can't find a datasheet for.

And since there is no GND connected to the display, are all 8 segments of a digit connected trough one I/O pin as ground? Doesen't that exceed the pin's 20mA recommended level?

The key point is that if you do that, you're doing it wrong.
Typically a multi digit display is time multiplexed, such that you use a common set of segment lines to activate the pattern on each digit in turn, therefore at any one time only at most 7 (or 8 counting the decimal point) segments should actually be on.
Then in terms of the common connection which selects a given digit, this will indeed typically have to source or sink more current than an MCU I/O pin is typically rated to handle, so it's best if the common connection is driven by an external transistor or FET.
Other options of course include mutli-digit LED display drivers, or lower power display technologies like LCDs.
That said, if a software bug briefly means everything is on, chances are the chip will survive.  But hopefully this only happens to "engineering units" - you do want to make sure that production units don't suffer this at some point in the programming process or something like that (though that's not all that likely, as typically all I/Os become inputs with at most a weak pullup).

These typically use 12 GPIO pins (4 for the digits, 8 for the segments/dot).
Each GPIO pin controls one digit and/or segment at a time.
The normal 'maximum' LED current is 20 mA. For the digits, 8 segments * 20 mA = 160 mA which is below 200 mA.
However, maybe there are LED displayed which use more current. In that case, you have yourself to make sure not all segments are lit at the same time (by fastly alternating the LEDs, or using less current).

but aren't all 7 (8 with dot) segments connected to one I/O pin which is used as ground? Doesen't that exceed the 20mA recommended for one pin?

True ... I'm updating my answer

Thats what I'm worried about. Exceeding the individual 20mA amount for each of the 4 I/O pins used as ground, and exceeding the 200mA max for all pins

when I light up 4 leds they seem to pull 40mA. What about all the 32 then?

Each digit has their own ground, so max 8 LEDs for the digit/ground GPIOs.

but 1 led still uses 10mA, times 8  thats too much

10 mA * 8 = 80 mA, which is less than 200 mA (?)

but all that goes trough one I/O pin which is used as GND for the digit. Thats double the max rating for the pin.

The max pin current is 200 mA right? And one LED is max 20 mA ... 20 mA * 8 LEDs = 160 mA. Each digit has its own ground GPIO.

well, for me each LED uses 10mA, so if I set one digit to show a "8." thats 8x10mA= 80mA that go trough one GND I/O pin.

You are right ... the max for a GPIO pin is 50 mA which is too high. As dannyf explains there is also some internal resistance.
You also can use multiplexing to not lit all LEDs at once.

They will turn on, likely with slightly uneven brightness - the LEDs internal resistance and the pins limited current drive will act like the current limiter.
The actual current will depend on the supply voltage, led used and the mcus drive capabilities.
For a red 4 digit 7 seg on an atmeha8, I got less than 10ma at 2,5v and 20ma at 3.3v, with the LEDs multiplexed.
Edit: some quick math.
Say that the current through each led segment is I. And the gpio resistance is R.
Each common digit has 8 I current through it, and each segment has 4 I. Some math later,
I = (Vcc - Vf) / (12 R) where Vcc is the supply voltage and Vf is the LEDs forward voltage (1.9v for a typical red led). The gpio resistance varies from 50+ ohm to 30+ ohm, higher at lower voltage.
Plus in 3.3v and 2.7v you get total current of 30 to 75ma for all digits.
I'm going to measure mine later.
edit: about 25ma (total current = mcu + led) at 2.5v and 50ma at 3.3v. the mcu consumes 2-3ma approximately.
the brightness is fairly even amongst the leds if you don't look too closely.


text:
3-5v micro stepper connected to A4988 driver does not move and makes whirring noise
I am kind of a newbie when it comes to stepper motors so I am hoping I am not asking any stupid questions.
I am trying to run a 3-5v micro stepper motor (PM15S-020-SKH4) using a Pololu A4988 stepper driver. I know the driver isn't originally meant for low-voltage stepper motors but I had some lying around and from what I understand it should not be a problem as long as the pot-value is set correctly.
Now I've identified the coils on the stepper motor and connected everything with an 12V power supply, Arduino Uno, 100uF capacitor as described in the Pololu schematic. I couldn't find the current specification for the stepper motor but if my calculations are correct with 5V / 30 Ohm it should be 160 mAmp so per another calculation I've set vRef value for the pot-meter to 0.160 * 0.4 = 0,064
The code I run on the Arduino is;
#define PIN_DIR 1
#define PIN_STEP 3
#define PIN_ENABLE 5

void setup()
{
    pinMode(PIN_DIR, OUTPUT);
    pinMode(PIN_STEP, OUTPUT);
    pinMode(PIN_ENABLE, OUTPUT);

    digitalWrite(PIN_ENABLE,LOW);
}

void loop()
{
    digitalWrite(PIN_DIR,HIGH);

    // 20 pulses of 18 degrees should make one full rotation
    for(int i = 0; i < 20; i++)
    {
        digitalWrite(PIN_STEP,HIGH);
        delayMicroseconds(500);

        digitalWrite(PIN_STEP,LOW);
        delayMicroseconds(500);
    }

    delay(1000);
}

When running the above code, the shaft is harder to move compared to a disconnected motor so there is resistance between the coils what should indicated that they are powered. But when running this the only thing the motor does is make a whirring noise and struggle/tick when I try to rotate it with my fingers.
I have tried multiple of the same type motors and drivers but all yield the same result.
I have a feeling I am overlooking something very obvious but I have no idea what, or am I being a complete idiot trying to combine the Pololu A4988 and the PM15S-020-SKH4?

Maybe your current is too low?

I have tried to increase the vRef on the pot-meter in ranges from 0.1 until even 1 (where to motor got really hot) but all with the same result.

Any chance you mixed up the pins and are toggle the direction or enable but not the step?  Are both coils truly connected?

I have given up on trying to get this to work and switched to a servo. I have hooked up the setup to a NEMA17 stepper motor (with alterations to the current) and it works fine. I have tried the small stepper motor in many, if not all configurations and I just can't get them to work.


text:
SD card fails to write when used with another SPI device
I have an ADXL355 accelerometer attached to an Adafruit Feather Adalogger.  I can configure and read the sensor.  I can also write binary values to the SD card.  The problem occurs when I try to read from the sensor and then write that data to the SD card.  The only thing I can think of is I'm somehow messing up the SPI communication but I can't see where.  I looked through pins_arduino.h for my board and the SD Card (pin 4) is on a different register than pin 10 so I don't see how I'm breaking things.
My operations proceed like this.  Global sensor creation, Serial.begin, SD.begin, SPI.begin, Test sensor connection, Create file for output on SD card, Initialize sensor, Read sensor FIFO, Write to file, repeat last 2 forever.
The file is created but remains at 0 file size, ie nothing is actually written to the card.
The sensor can operate at 4 kHz which was hard to achieve using the digitalWrite functions so I switched to using the port registers on the Feather.  I do it like this:
#include <SM_ADXL355_SPI_fast.h>
#include <SPI.h>
#include <SD.h>

#define cardSelect 4

ADXL355_SPIF adxl355(&DDRB, &PORTB, _BV(6)); // values taken from pins_arduino.h, tested and working on pin 10
void setup() {
  Serial.begin(57600);
  while(!Serial){
    // wait for Serial
  }
  SD.begin(cardSelect);
  SPI.begin();
  while(!adxl355.TestConnection()){
    delay(1000);
  }
  adxl355.OpenFile("TestSPI.bin");
  adxl355.Initialize(1, 10, 0); // set range to 2g's, frequency to 4 Hz and filter to off
}

void loop() {
  while(true){ // avoid Arduino overhead of their loop function
    adxl355.ReadFIFO();
    adxl355.WriteFIFOToFile();
  }
}

Here is the ADXL constructor
ADXL355_SPIF::ADXL355_SPIF(volatile uint8_t * outReg, volatile uint8_t * outPort, uint8_t bitValue) : sensorOutReg(outReg), sensorPort(outPort), sensorBitValue(bitValue){
    *sensorOutReg |= sensorBitValue;
    *sensorPort |= sensorBitValue;
    sensorWriteCount = 0;
}

TestConnection tests that the DeviceID reads 0xAD.  Initialize sets the G range, sample rate in Hz and filter.  I have tested these with serial output and they work properly.
OpenFile looks like this:
bool ADXL355_SPIF::OpenFile(const String& fileName){
    sensorFile = SD.open(fileName, FILE_WRITE);
    if (!sensorFile){
        Serial.print("Could not create file: ");
        Serial.println(fileName);
        return false;
    }
    return true;
}

After running this a file does get created on the SD card called "TESTSPI.BIN" with 0 file size.
ReadFIFO reads the numbers of entries in FIFO, stored as fifoCount and then populates a buffer (sensorFIFO[32][3]) with the values from the FIFO.  I've printed this buffer to Serial to show that it's working.  Here is that function
void ADXL355_SPIF::ReadFIFO(){
    ReadRegister(ADXL355_RA_FIFO_ENTRIES, 1);
    fifoCount = buffer[0];
    ReadFIFOInternal();
    return;
}

void ADXL355_SPIF::ReadFIFOInternal(){
    SPI.beginTransaction(SPISettings(10000000, MSBFIRST, SPI_MODE0));
    *sensorPort &= ~sensorBitValue;
    uint8_t spiCommand = ADXL355_RA_FIFO_DATA << 1 | ADXL355_READ;
    SPI.transfer(spiCommand);
    int i = 0;
    unsigned long tempV;
    unsigned long value;
    while(i < fifoCount){
        for (int ptr = 0; ptr < 3; ++ptr){
            buffer[0] = SPI.transfer(0x0);
            value = buffer[0];
            value <<= 12;
            tempV = SPI.transfer(0x0);
            tempV <<= 4;
            value |= tempV;
            tempV = SPI.transfer(0x0);
            tempV >>=4;
            value |= tempV;
            if (buffer[0] & 0x80) {
                value |= 0xFFF00000;
            }
            long lValue = static_cast<long>(value);
            sensorFIFO[i][ptr] = scaleFactor * lValue;
        }
        i += 3;
    }
    SPI.endTransaction();
    *sensorPort |= sensorBitValue;
    return;
}

Here is WriteFIFOToFile:
void ADXL355_SPIF::WriteFIFOToFile(){
    if (fifoCount > 0){
        sensorFile.write(reinterpret_cast<const char *>(&sensorFIFO), 4 * fifoCount);
    }
    sensorWriteCount += fifoCount;
    if (sensorWriteCount >= 100){
        sensorFile.flush();
        sensorWriteCount = 0;
    }
}

After allowing this to run for a while the file size is always 0.  I tried a simple binary write function just to test the card.  It looks like this and it worked.
#include <SD.h>

#define cardSelectPin 4

const float pi=3.14159;

File oFile;

void setup() {
  // put your setup code here, to run once:
  Serial.begin(9600);
  while(!Serial){
    // wait for serial
  }
  SD.begin(cardSelectPin);
  oFile = SD.open("Test.bin", FILE_WRITE);
  Serial.println(sizeof(int));
  Serial.println(sizeof(float));
  float testFloat[32][3];
  for (int i = 0; i < 32; ++i){
    for (int j = 0; j < 3; ++j){
      testFloat[i][j] = pi * (i + 1) + j;
    }
  }
  oFile.write(reinterpret_cast<const char *>(&testFloat), sizeof(float) * 96);
  oFile.close();
  Serial.println("Finished writing file.");
}

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

}

SD cards are reportedly not fully compatible with shared SPI busses - though I'd been under the impression that it was usually the other devices impacted, since well-behaved SPI peripherals shouldn't be getting in the way of access to the card.

This is a Feather board?  Make sure your supporting software is up to date.  I had plenty of problems with a Feather board as they were new at the time.

@st2000 I use the Arduino IDE and I update everything it says it out of date when it opens.  Are you referencing another "supporting software"?  Yes it's the Feather 32u4 Adalogger.

Go to the Adafruit web site for information as to what is necessary to add to your Arduino IDE in order to program Adafruit Feather boards.  Remember, different Arduinos do not necessarily use the same processors.  The ARM core processors used on a Feather are likely orders of magnitudes more complex than that of the lowly Arduino Uno.

The problem here was caused by flush never being called within WriteFIFOToFile.  The variable sensorWriteCount was defined incorrectly.  Changing to call flush directly after each write statement fixed the problem.  This lead to the debugging of the if statement and variable.


text:
ADC pin shutting off on its own under certain condition
A0 pin not working when full PV system in use
I am using the DFRobot Leonardo with Xbee R3. I am using the A0 pin to read a 0-5V voltage from my voltage sensor, which samples and steps down 130VDC from a solar panel, in parallel to 0-5V for my Arduino to read.
Album with all relevant images
PV Array is 7 Panels in Series, Vpeak 18.7V Apeak: 11.23A

When the PV system is in open circuit mode (not connected to the grid), A0 can read the voltage without any issues and output's it into my serial monitor.
When the PV system is connected to the grid, A0 seemly shut's itself off and i no longer get any serial output. Testing with multimeter shows that the A0 pin is still getting a voltage in the range of 0-5V.
My assumption is that when a load is applied to the system, either A0 shuts itself down to protect the board for some reason, or the current is not flowing through the voltage sensing circuit due to it's higher resistance.
Current sensor is a 0-20A ACS712 board.

The analog pin can not “shut down”. It makes no sense. What can happen is that your Arduino shuts down (e.g. for lack of power) or your program locks itself inside an infinite loop (a bug). You may want to blink the onboard LED in your main loop() just to confirm your program is still running. Also, the information you provide in the question is not enough to help you: everything looks correct. You should provide a complete schematic and post a Minimal, Complete, and Verifiable example for the software side.

Definitely not a lack of power as i am connected to my laptop's USB port for data and power.
Program is still running, data is being recorded, shown on serial monitor and sent to a datalogging server (ThingSpeak) https://gyazo.com/a17799f90fa1f17ad59848350a9c9183

Does the laptop and the circuit share a common ground?

You wrote in the question: “i no longer get any serial output” and then in your comment: “data is being [...] shown on serial monitor”. This seems like a contradiction. Please clarify.

Sorry for the confusion. My serial monitor prints both Voltage and Current readings from my sensors every 0.5secs. When the system is not connected to the grid (i assume no load) the serial monitor shows my voltage value e.g 130V, which is verified by multimeter testing. However, when i do connect the system to the grid, serial monitor will show the voltage value as 0V. When i disconnect the grid again (i assume removing load) serial monitor starts showing the correct voltage value again.

@Code Gorilla I'm not too sure, but the ground of my sensors is connected to the GND pins on the Arduino board, USB that connects Arduino to Laptop has GND as well

Please add more information to your question to clearly define the question you are asking.

If you remove the current circuit that goes into A0 and replace it with a potentiometer, does that then read the analog voltage correctly?

@sa_leinad A0 can successfully read analog voltage using a 1k pot. The issue i am facing is that A0 will stop reading analog voltage when the PV system that i am monitoring is connected to the grid.
When it is not connected to the grid, i have no issues with A0 reading analog voltage

Your wording is causing confusion. Your analog pin never shut off. Your Arduino never stopped reading the analog voltage. It is reading zero, which is very different from not taking any reading. 2) Yours looks like a ground problem. Your connection to the grid is linked to earth's ground. If your laptop is being powered from its PSU, it is linking the Arduino GND with earth's ground. Your circuit may end up having too many grounded nodes. You should post a complete and accurate schematic.

@EdgarBonet Your mention of grounding might be the issue at hand now that i think of it. Completely amateur when it comes to EEE so i may have got it wrong. I have updated the imgur ablum in the original post with a better schematic as you requested.
The voltage sensor design has the negative input connected to GND as denoted by the wire below the sensor in the diagram

Went through my designs again, noticed that i have my PV negative connected to common ground for all my sensor modules and arduino. Could this be the issue? Will test and report back as soon as i get back in the lab.


text:
Arduino analog pins not working
I am having a problem with pins of Arduino Uno. I have connected a LED to one of the analog pins (A0), and I want to light up the LED with different intensinty.
int ledPin = A0;
void setup() {
 // put your setup code here, to run once:
 pinMode(ledPin,OUTPUT);

}

void loop() {
 // put your main code here, to run repeatedly:
 analogWrite(ledPin,500);
}

The point is that even if I change the value of analogWrite, the LED lights up always with the same intensity.

analogWrite deals with PWM pins, those are digital pins. See https://www.arduino.cc/en/Reference/AnalogWrite
So connect the LED to one of the PWM pins and change the sketch accordingly. On the Uno those are pins 3, 5, 6, 9, 10, and 11.
The analog pins A0 - A5 are input pins. The value is read using the analogRead(pin) function.

Erik is right, but some LEDs don't have a very wide range of brightness, so you might also hit that issue.

And human light response is not linear.


text:
Merging arduino code
I have a project where we need to create a virtual cane for blind people and it will have 3 functions:

Pressure button when pressed will connect to an android phone through HC-06 Bluetooth modulo to an app that I developed and will
can to someone that I defined
Temperature sensor that is attached to a buzzer that will buzz if the
temperature is higher than 40 Degrees
Ultrasonic sensor attached to and vibration motor that will vibrate
if there is any object less than 70 cm from the person.

When I combine the code from the ultrasonic and the temperature sensor, everything works fine, when I add the bluetooth code, nothing works, anyone see the problem? Or could you show me the problem and solveit?
Code without Bluetooth:
int DHT11_PIN=8;
dht DHT;
int buzzer=6;
int trigPin=3;
int echoPin=2;
int motor=7;

void setup(){
  Serial.begin(115200);
  pinMode(DHT11_PIN,INPUT);
  pinMode(buzzer, OUTPUT);
  delay(5000);

  Serial.begin(9600);
  pinMode(trigPin, OUTPUT);
  pinMode(echoPin, INPUT);
  pinMode(motor, OUTPUT);
  delay(5000);
}

void loop(){
  Stemperature();
  Sultrassom();
}

// sensor de tempratura e Buzzer-------------------------------
void Stemperature(){
  digitalWrite(buzzer,LOW);
  DHT.read11(DHT11_PIN);
  float t=DHT.temperature;
  Serial.print("Temperature = ");
  Serial.println(t);

  if (t>40){
    digitalWrite(buzzer,HIGH);
    {tone(6,100,20);
    delay(1);
    noTone(1);
    delay(1);
    }
    delay(1000);
    Serial.print("ON T=");
  }else{
    digitalWrite(buzzer,LOW);
    Serial.print("OF T=");
  }
}

//Sensor de Ultrassom e Motor vibração-----------------
void Sultrassom(){
  long duration, distance;
  digitalWrite(trigPin, LOW);
  delayMicroseconds(2);
  digitalWrite(trigPin, HIGH);
  delayMicroseconds(10);
  digitalWrite(trigPin, LOW);

  duration = pulseIn(echoPin, HIGH);
  distance = (duration/2) * 0.0340;
  Serial.println(distance);

  if (distance < 70){ // se a distância for menor que 70 cm o motor vibra
    digitalWrite(motor,HIGH);// quando a distância for menor que 70 cm
    Serial.print("MOTOR ON=");
  }else{
    digitalWrite(motor,LOW);// quando a distância for maior que 70 cm
    Serial.print("MOTOR OFF=");
  }
  delay(5);
}

Bluetooth Code:
const int buttonPin = 4;     // the number of the pushbutton pin
boolean buttonState;         // variable for reading the pushbutton status

void setup(){
  Serial.begin(9600);
  // initialize the pushbutton pin as an input:
  pinMode(buttonPin, INPUT);
  buttonState = LOW;
}

void loop(){
  // read the state of the pushbutton value:
  buttonState = digitalRead(buttonPin);
  // check if the pushbutton is pressed. If it is, the buttonState is HIGH:
  if(buttonState == HIGH) {
    // send char 1 via Bluetooth:
    Serial.println("1");
    delay(20000);
    while (0);
  }
}

What have you done already? Have you traced the execution? What is the last statement executed?

In the bluetooth loop you use:
delay(20000);
while (0);

This means you first wait 20 seconds, and while(0) does not do anything (unuseful instruction).
Actually, this results when the button is pressed, it starts the loop again, but you have to merge both codes into one.
I would add the sending of the serial command in the code above, remove the while and see what happens. If you need some delay for debouncing reaons for the button, implement a decent deboucing algorithm instead of the delay of 20000.
And why there are two }} at the end?

while(1); means wait forever while(0); means never wait, which is pointless.

True ... I will change it

No - zero is false :)

Adapted it more clearly

The following code is not tested in any way. It should give you some help, to detect the problems. First you used the same Serial connection for your PC and the Bluetooth module, which leads to problems. Second, you had some delays, which seemed useless. Third your noTone() function didn't matched the right pin. Also I added an Interrupt for the Button. It could be, that your DHT reading need the same Interruptprotection, which I added to the Usonic measurment. Last but not least I replaced your Pin definitions to make it more readable.
// New Include for the bluetooth connection
#include <SoftwareSerial.h>
#include <dht.h>

#define DHT11PIN        8
#define BTRXPIN         10                    // Pay attention to your wiring
#define BTTXPIN         11
#define BUZZERPIN       6
#define TRIGGERPIN      5                     // Changed, to keep an interrupt Pin free !!!
#define ECHOPIN         4                     // Changed, to keep an interrupt Pin free !!!
#define MOTORPIN        7
#define BUTTONPIN       2                     // Changed to an interrupt Pin

dht DHT;
SoftwareSerial bluetooth(BTRXPIN, BTTXPIN);

void setup(){
  Serial.begin(9600);                         // Only once
  bluetooth.begin(9600);                      // Serial connection for the bluetooth module
                                              // Check your needed Baudrate
  pinMode(DHT11PIN,  INPUT);
  pinMode(BUTTONPIN, INPUT);
  pinMode(ECHOPIN,   INPUT);
  pinMode(TRIGGERPIN, OUTPUT);
  pinMode(BUZZERPIN,  OUTPUT);
  pinMode(MOTORPIN,   OUTPUT);
  digitalWrite(BUZZERPIN, LOW);

  attachInterrupt(digitalPinToInterrupt(BUTTONPIN), buttonISR, RISING); // I did not pay attention to bouncing here!!
  // I see no need for 5sec delay, so i cut it out
}

void loop(){
  temperatureMeasure();
  ultraSonicMeasure();
  delay(2000);                                  // 2 sec delay, so it won't measure all the time.
}

float temperatureMeasure(){                     // Added return types
  DHT.read11(DHT11_PIN);
  float t = DHT.temperature;
  Serial.print("Temperature = ");
  Serial.println(t);

  if (t > 40){
    tone(BUZZERPIN,100);
    delay(20);
    noTone(BUZZERPIN);
    Serial.print("ON");
  }else{
    noTone(BUZZERPIN);
    Serial.print("OFF");
  }
  return temperatureMeasure;
}

long ultraSonicMeasure(){
  long duration{0};
  long distance{0};
  noInterrupts();
  digitalWrite(TRIGGERPIN, LOW);
  delayMicroseconds(2);
  digitalWrite(TRIGGERPIN, HIGH);
  delayMicroseconds(10);
  digitalWrite(TRIGGERPIN, LOW);

  duration = pulseIn(ECHOPIN, HIGH);
  interrupts();
  distance = (duration/2) * 0.0340;
  Serial.println(distance);

  if (distance < 70){
    digitalWrite(MOTORPIN, HIGH);
    Serial.print("MOTOR ON");
  }else{
    digitalWrite(MOTORPIN, LOW);
    Serial.print("MOTOR OFF");
  }
  return distance;
}

// Called when button is pressed
void buttonISR(){
  bluetooth.println("1");                         // Would be better, to put this outside of the ISR, but is is only on character.
}

It worked with some modifications!!!
Thank you :)


text:
ESP8266 Soft Access Point: Timeout of request of resource when not responded to in set undocumented time
I'm experimenting with the ESP8266 chip on a Wemos D1 R2 board. I'm trying to write some code which will allow the user to input a username and password in an HTML form then get a response as to what happened with trying to connect to the WiFi as either they connected or the password was wrong. After I've turned setup Access Point and Station mode on the device using:
    // The field here would be global so other functions can access it
    ESP8266WebServer server(80);
    server.on("/connect", handleConnect);
    server.begin();

In my handleConnect function, I check the body of the request and attempt to login:
    if(!server.hasArg("ssid") || !server.hasArg("password")) {
        server.send(200, "text/html", "You didn't submit a ssid and password");
        return;
    }

    auto ssid = server.arg("ssid");
    auto password = server.arg("password");

    WiFi.begin(ssid, password);

    auto status = WiFi.waitForConnectionResult();

    server.send(200, "text/html", String(status));

When the user inputs the correct password, the function returns the request in time and the request responds with 3 (the connection was successful). However, if the password is wrong, the request times out. I've also tried several approaches to either work-around or fix the problem such as:

Using a while loop and calling WiFi.status() and checking it and responding accordingly. This approach ends with the same request timeout if the password is wrong. An example of this would be:
while(true) {
  delay(1000);
  auto status = WiFi.status();

  if(status == WL_CONNECTED) {
    server.send(200, "text/html", "You're connected!");
  }

  if(status == WL_CONNECT_FAILED) {
        server.send(200, "text/html", "You inputted the wrong password! Try again!");
  }
}

Registering another resource to specifically only return what state the WiFi is in and in the original connect function to send back HTML with some javascript in it which calls this other resource and do the decision making of what text to display client-side but this approach always returns 0 (when the WiFi is in process of changing between statuses, quoted from the docs)
server.on("/checkConnection", checkConnection);

// other code

void checkConnection() {
  server.send(WiFi.status());
}

And finally, I have experimented with using a public field to save the state once it has finished in the main function where the original connection tried to be established and then use the checkConnection function to return this state and this SOMEWHAT works, however, the code is messy, hacky and there must be a better way of doing this otherwise this will have to be my solution until the libraries are updated to fix this or something like that:

// public field for the status
      int status = 0;

      // other code

      void handleConnect() {

        // checking ssid and password

        WiFi.begin(ssid, password);

        // use an interval with AJAX or this to get the connection state
        server.send(200, "text/html", "Go to to check the connection");

        while(true) {
          delay(1000);
          auto s = WiFi.status();
          status = s;
          if(s = WL_CONNECTED) break;
        }

      }

      void checkConnection() {
        server.send(200, "text/html", status);
      }

Has anyone encountered this problem and if so, is there a better way of solving it apart from using a public variable which just makes it a pain in the bum to work with? Thank you.

waitForConnectionResult probably doesn't handle errors like you want. 2. WL_CONNECT_FAILED means other things too, so wouldn't you just want to look for anything beside 'connected'? 3. The AP must use the same channel as the STA, so i don't see how this can keep an http connection open while/if that changes.

@dandavis Thanks for replying. Firstly, waitForConnectResult is documented as to wait for the final result of the network and then return the connection state. Secondly, thank you for heads up on the other meanings of the WL_CONNECT_FAILED. I sort of asummed that it may have had some other meanings but now I know but in this case we're assuming the ssid is correct and only the password is wrong. Finally, the esp8266 has a WiFi mode called WIFI_AP_STA which allows the device to be an access point and a station, very handy if you want to do something like this so I don't think that is the cause.

yes, in WIFI_AP_STA, the wifi channels must match between the two. if your AP booted a different channel than the STA you're connecting to, you (afaik) won't be able to keep an http connection open during the AP's (unexpected/undocumented) channel change, no matter the password validity.

WifiMulti wifiMulti;//declare global.
wifiMulti.addAP(ssid,pass);//instead of WiFi.begin();
int i = 0;
//add below to wait for connection.
while (i < 20)
  {
    if (wifiMulti.run() == WL_CONNECTED)
    {
      return (20);
    }
    delay(500);
    Serial.println(WiFi.status());
    i++;
  }

Make the WiFi.begin outside the WebServer handler. In the handler store the ssid and password into variables and send a response. In loop() then make the WiFi.begin. For the result, pool from the browser with javascript.
Example

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


text:
Arduino IDE lost board connection
Board: Arduino Leonardo
IDE version: 1.6.5(also tried with 1.8.3)
Try Arduino Web Editor as well
The problem: after connecting Arduino to PC via USB in 5-7 seconds IDE says that connection is losted.
Everything was OK, but after one deploy happened thing, that I described.
If it help: I connect OLED display and use it with OLED_I2C library. Sketch contains one cpp and one h file.
I'm already fully reinstall USB drivers with Arduino USB as well

The problem: after connecting Arduino to PC via USB in 5-7 seconds IDE says that connection is losted.

Yes, that's normal. That's the bootloader running, and it's during that 5-7 second window that you can upload a new sketch.
Under normal circumstances the IDE will automatically reboot the board for you so the upload time window coincides with the IDE's attempt to upload a new sketch. However under some circumstances it can't, so you have to do it manually by pressing the reset button at the right time.
Also on Windows you may find that you have a different COM port for programming as you do when a sketch is running (Windows is retarded like that, you see). The IDE tries to do some magic to identify the correct COM port to use, but you have to first have the correct "sketch mode" COM port selected so it can first reboot the board into the bootloader, at which point it tries to do its magic to work out the correct COM port to use by looking to see which COM port (if any) has just appeared since rebooting.
So, in short: if the IDE can't reboot the board for you then do it manually, but note that timing is vital. Press the reset button a few moments before avrdude runs. It may take practice.

Well, it's seems a little bit strange, but it's work. Thanks :D


text:
Is it possible to obtain %0.05 duty cycle at 1hz in arduino?(a 500us square pulse at 1 sec period)
I have a system which requires me to obtain different duty cycles at different frequencies. But using the analogWrite() does not allow me to obtain a value lower than 1/255 duty cycle. I need to obtain lower duty cycle values for 1Hz

Is it OK if, at 1 Hz, you are restricted to pulse widths which are multiples of 16 µs? E.g. you would have 496 µs instead of 500. If so, you can configure Timer 1 to generate the PWM signal on pins 9 or 10. A signal generated this way would have more consistent timing than a similar signal generated by software (e.g. using micros()).

@EdgarBonet - could you explain where are you getting the 16us from?  Several prescalar and count value possibilities will yield 500us, but I'm not immediately thinking of any that yield your numbers.

Prescaler = 256 → resolution = 16 us and maximum period = 1.048576 s.

Ok, the maximum interval is a point - but that doesn't have to come from the same timer.

Expanding from my comment. This is an attempt to generate that signal with Timer 1. No time to test it now... Edit: tested, works as advertised.
/*
 * Configure Timer 1 to generate a slow, low duty cycle PWM signal.
 * Output pin = digital 9 = PB1 = OC1A.
 */

const float PWM_PERIOD  = 1.0;     // 1 s
const float PULSE_WIDTH = 500e-6;  // 500 us

/*
 * With a 16 MHz clock and this prescaler, the resolution is 16 us and
 * the maximum period is 1.048576 s.
 */
const uint16_t TIMER_PRESCALER = 256;
const float F_TIMER = F_CPU / TIMER_PRESCALER;

void setup()
{
    // Configure Timer 1.
    DDRB  |= _BV(PB1);    // set PB1 = OC1A as output
    ICR1   = round(PWM_PERIOD * F_TIMER) - 1;
    OCR1A  = round(PULSE_WIDTH * F_TIMER) - 1;
    TCCR1A = _BV(COM1A1)  // non-inverting PWM on OC1A
           | _BV(WGM11);  // fast PWM mode, TOP = ICR1
    TCCR1B = _BV(WGM12)   // ditto
           | _BV(WGM13)   // ditto
           | _BV(CS12);   // clock at F_CPU/256 = 62.5 kHz
}

void loop() {}

Thank you for this, It works great but I would like to get the same thing for 2 different pins and I have no idea about registers. Can you tell me how can I make this code applicable for pin 10 and pin 8?

@allta: You can't. Hardware-based PWM only works on pins OCnA and OCnB, where n = 0, 1, or 2 is the index of the timer you use. The small duty cycle you want can only be achieved with a 16-bit timer, and you have only one such timer on the Uno: Timer 1. Thus you can only use pins 9 (OC1A) and 10 (OC1B). C.f. the Arduino Uno pinout. See also the tutorial Timers and counters by Nick Gammon.

Thank you again
It's ok we can use the pin10 we won't use the pin 9 and 10 simultaneously. Will changing OC1A with OC1B would work for pin 10? How can I modify this code for pin 10?

@allta: Yes. OCR1B controls pin 10 in the same way as OCR1A controls pin 9.

void setup()
{
// Configure Timer 1.
DDRB  |= _BV(PB2);    // set PB1 = OC1A as output
ICR1   = round(PWM_PERIOD * F_TIMER) - 1;
OCR1B  = round(PULSE_WIDTH * F_TIMER) - 1;
TCCR1A = _BV(COM1B1)  // non-inverting PWM on OC1B
| _BV(WGM11);  // fast PWM mode, TOP = ICR1
TCCR1B = _BV(WGM12)   // ditto
| _BV(WGM13)   // ditto
| _BV(CS12);   // clock at F_CPU/256 = 62.5 kHz
}
didn't work I don't get how can I modify the last part correctly

@allta: Your modified setup() works for me: I get the PWM signal on pin 10.

Now it worked for me too, thank you again

Sure - if you program it to.

Turn on an output.
Wait for 500µs less the amount of time it took to turn on the output
Turn off the output
Wait for 0.9995 seconds minus the amount of time it took to turn off the output
Go to 1.

You would probably find using the micros() function easiest to get the timing right - in exactly the same way as the BlinkWithoutDelay example in the IDE.
Also direct port manipulation may be of benefit to make things as fast as possible.

You must also account for the time spent outside loop. There is some conditional code executed out there (plus calls, returns and interrupts), so execution time is variable from pass to pass. That's the problem with delay: you don't know how much time will pass before the next execution of loop. Better use micros.

Yes, hence my instruction to use micros.

Sorry. I was aware of your original micro recomendation. I was just adding reasons for it. I didn't express myself correctly.

Sure. Two easy way to do it.

0,05 percent is 1:2000. So modify timer settings to produce a pen of the desired frequency and duty cycle.
Use timer interrupt: either the overflow or compare match interrupt. In the first case, load the timer with -duty cycle and -(period - duty) to produce a wave form of duty cycle / period.

The same can be done using compare match as well: just advance the match point alternately.
edit: to show how it can be done with compare match, here is what I have:
#define PR_PWM          (F_CPU / 256 / 10)      //period for the pwm waveform
#define PR_ON           (PR_PWM * 25 / 100)         //prescaler at 256:1, 25% duty cycle
#define PR_OFF          (PR_PWM - PR_ON)            //pin off period, to achieve 1Hz
//end hardware configuration

//global defines

//global variables

//timer1 ch a compare match isr
ISR(TIMER1_COMPA_vect) {
    static char pr_index=0;     //0->PR_ON, 1->PR_OFF

    //clear the flag  -  done automatically
    //advance to the next match point
    if ((pr_index++ & 0x01) == 0) {
        OCR1A += PR_ON;
        IO_SET(PWM_PORT, PWM);  //set the pin on
    } else {
        OCR1A += PR_OFF;
        IO_CLR(PWM_PORT, PWM);  //clear the pin
    }

}

for this demo, we tried to generate a 25% duty cycle pwm with a period of 100ms. Here is the output of that code.

The follow changes the duty cycle to 0.05%:
#define PR_ON           (PR_PWM * 0.05 / 100)           //prescaler at 256:1, 0.05% duty cycle

and the corresponding output is:

Now, there are other ways to do it, for example, with higher resolution, or more precision, ..., but at the cost of more coding.
But the basic concept is the same.
hope it helps.
edit2: for those brave souls, the isr can be simplified to:
OCR1A += (pr_index++&0x01)?PR_OFF:PR_ON;  //advance the match point
IO_FLP(PWM_PORT, PWM);  //flip the pwm pin

A pen? It must be a typo

@LookAlterno Unless he means to draw the waveform on a piece of paper...?!


text:
Arduino Yún as ISP to program Attiny - why is the sketch not working after successful upload?
I want to use an Arduino Yun as ISP to program an Attiny85. I have soldered a shield following the circuit that is depicted in many sites. You can see it in this page.
I have included a LED with a 1k resistor in series connected between pin 5 (PB0) and ground so that I can monitor.
I have setup my sketch environment (Arduino 1.6.12) with the definitions of the Attiny so that I can select this board (Attiny85) with it's associated parameters.
I have defined in Arduino 1.6.12 the board in this way:

Board: "ATtiny25/45/85"
Processor: "ATtiny85"
Clock: "Internal 1MHz"
Port: "192.168.1.109 (Arduino Yún)"

I use this port instead of the serial USB port as I had many issues with the serial USB port.
I have started with the Blink sketch modifying it to use pin0
The sketch is this one:
// the setup function runs once when you press reset or power the board
int LED = 0;  //0 para Attiny
void setup() {
  // initialize digital pin LED_BUILTIN as an output.
  pinMode(LED, OUTPUT);
}

// the loop function runs over and over again forever
void loop() {
  digitalWrite(LED, HIGH);   // turn the LED on (HIGH is the voltage level)
  delay(1000);                       // wait for a second
  digitalWrite(LED, HIGH);    // turn the LED off by making the voltage LOW
  delay(1000);                       // wait for a second
}

The output of the sketch loading in verbose mode is this one:
El Sketch usa 672 bytes (8%) del espacio de almacenamiento de programa. El máximo es 8.192 bytes.
Las variables Globales usan 9 bytes (1%) de la memoria dinámica, dejando 503 bytes para las variables locales. El máximo es 512 bytes.
/usr/bin/run-avrdude /tmp/sketch.hex -v -pattiny85

avrdude: Version 6.1, compiled on Apr  8 2016 at 15:56:17
         Copyright (c) 2000-2005 Brian Dean, http://www.bdmicro.com/
         Copyright (c) 2007-2014 Joerg Wunsch

         System wide configuration file is "/etc/avrdude.conf"
         User configuration file is "/root/.avrduderc"
         User configuration file does not exist or is not a regular file, skipping

         Using Port                    : unknown
         Using Programmer              : linuxgpio
         AVR Part                      : ATmega32U4
         Chip Erase delay              : 9000 us
         PAGEL                         : PD7
         BS2                           : PA0
         RESET disposition             : dedicated
         RETRY pulse                   : SCK
         serial program mode           : yes
         parallel program mode         : yes
         Timeout                       : 200
         StabDelay                     : 100
         CmdexeDelay                   : 25
         SyncLoops                     : 32
         ByteDelay                     : 0
         PollIndex                     : 3
         PollValue                     : 0x53
         Memory Detail                 :

                                  Block Poll               Page                       Polled
           Memory Type Mode Delay Size  Indx Paged  Size   Size #Pages MinW  MaxW   ReadBack
           ----------- ---- ----- ----- ---- ------ ------ ---- ------ ----- ----- ---------
           eeprom        65    10     8    0 no       1024    8      0  9000  9000 0x00 0x00
           flash         65     6   128    0 yes     32768  128    256  4500  4500 0x00 0x00
           lfuse          0     0     0    0 no          1    0      0  9000  9000 0x00 0x00
           hfuse          0     0     0    0 no          1    0      0  9000  9000 0x00 0x00
           efuse          0     0     0    0 no          1    0      0  9000  9000 0x00 0x00
           lock           0     0     0    0 no          1    0      0  9000  9000 0x00 0x00
           calibration    0     0     0    0 no          1    0      0     0     0 0x00 0x00
           signature      0     0     0    0 no          3    0      0     0     0 0x00 0x00

         Programmer Type : linuxgpio
         Description     : Use the Linux sysfs interface to bitbang GPIO lines
         Pin assignment  : /sys/class/gpio/gpio{n}
           RESET   = ~18
           SCK     =  11
           MOSI    =  27
           MISO    =  8

avrdude: AVR device initialized and ready to accept instructions

Reading | ################################################## | 100% 0.00s

avrdude: Device signature = 0x1e9587
avrdude: NOTE: "flash" memory has been specified, an erase cycle will be performed
         To disable this feature, specify the -D option.
avrdude: erasing chip
avrdude: reading input file "0xFF"
avrdude: writing lfuse (1 bytes):

Writing | ################################################## | 100% 0.00s

avrdude: 1 bytes of lfuse written
avrdude: verifying lfuse memory against 0xFF:
avrdude: load data lfuse data from input file 0xFF:
avrdude: input file 0xFF contains 1 bytes
avrdude: reading on-chip lfuse data:

Reading | ################################################## | 100% 0.00s

avrdude: verifying ...
avrdude: 1 bytes of lfuse verified
avrdude: reading input file "0xD8"
avrdude: writing hfuse (1 bytes):

Writing | ################################################## | 100% 0.00s

avrdude: 1 bytes of hfuse written
avrdude: verifying hfuse memory against 0xD8:
avrdude: load data hfuse data from input file 0xD8:
avrdude: input file 0xD8 contains 1 bytes
avrdude: reading on-chip hfuse data:

Reading | ################################################## | 100% 0.00s

avrdude: verifying ...
avrdude: 1 bytes of hfuse verified
avrdude: reading input file "0xFB"
avrdude: writing efuse (1 bytes):

Writing | ################################################## | 100% 0.00s

avrdude: 1 bytes of efuse written
avrdude: verifying efuse memory against 0xFB:
avrdude: load data efuse data from input file 0xFB:
avrdude: input file 0xFB contains 1 bytes
avrdude: reading on-chip efuse data:

Reading | ################################################## | 100% 0.00s

avrdude: verifying ...
avrdude: 1 bytes of efuse verified
avrdude: reading input file "/tmp/sketch.hex"
avrdude: writing flash (672 bytes):

Writing | ################################################## | 100% 0.40s

avrdude: 672 bytes of flash written
avrdude: verifying flash memory against /tmp/sketch.hex:
avrdude: load data flash data from input file /tmp/sketch.hex:
avrdude: input file /tmp/sketch.hex contains 672 bytes
avrdude: reading on-chip flash data:

Reading | ################################################## | 100% 0.57s

avrdude: verifying ...
avrdude: 672 bytes of flash verified

avrdude done.  Thank you.

What looks pretty normal for me. When the load is ongoing, I see the 1st thing that puzzles me: LED connected to pin 5 (PWM0) doesn't blink quickly. I have tested the polarity of the LED with a +5V connected to the physical pin of the chip and 0V connected to GND and it lights.
The second thing that puzzles me is that I get exactly the same output when I remove the programming shield (no Attiny at all) and I click on upload and the output is the same.  Is the Arduino IDE caching this output?
When I put the "programmed" Attiny in a breadboard and I power it and connect one LED to port 5, it doesn't blink as per the Blink sketch.
I am quite a newby with Arduino and ATtiny85. I only wan to be able to program this ATtiny85 with my Arduino Yún
What am I doing wrong?
Could you give some light to this darkness?

Your link location is incorrect, and takes you to a PIR sensor board.

Thanks for the comment... it's somewhat strange, when I follow the link it leads to a page with this title: "Program an ATtiny with an Arduino Nano"

The link is fine - it goes to something that seems like it should be relevant, but actually isn't because of the differences between the Nano and the more Leonardo-like Yun, and then because the asker has ignored the serial interface used and mistakenly substituted the Yun's method of ISPing it's captive Arduino - which isn't going to work for an external target.

It's not programming a non-existent ATtiny, it's quite explicitly stating in the output that it is programming an ATmega32u4 - and that would be the "Arduino" part of the YUN.
It's not clear that the YUN is really intended to ISP other targets.
If you can get serial communication to the ATmega32U4, you could try to find a compatible variation of the ISP sketch to load on that, and in turn use it to program an ATtiny.
Or you could try to define a different set of programming pins, but this may be tricky.
Essentially, what you are trying to do is a bit unusual, and will likely require investing some real time in understanding the existing / available mechanisms enough to adapt them to a fairly unique goal.
Otherwise, just get an Uno or similar and use that to ISP your ATtiny.

I have followed your advice, Chris. I've got an Arduino UNO and the shield that I have created worked like a breeze! Now I can program my ATtiny85 / 85... :)
Thanks a lot for your answer.


text:
Arduino Serial Communication Between 2 Uno
I'm trying to get two arduino uno to communicate. The slave reads a temp sensor as an analog value, then converts it to degrees C, then sends that value to the master, the master then prints the value to the serial monitor. This is the code I have thus far.
for the slave
const int tempPin = A0;

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

  void loop() {

   //read sensor data to a variable
   float volt = analogRead(tempPin) * 0.004882814;
   float degC = (volt - 0.5) * 100.0;
   Serial.println(degC);

   delay(2000); //Not to flood serial port
  }

this is the code for the master
float tempC;
void setup(){
  Serial.begin(9600);
  delay(2000);
 }

  void loop() {
 /**  check if data has been sent from the computer: */
 while (Serial.available()) {
 /* read the most recent byte */
    tempC = Serial.read();     //now byteRead will have latest sensor
                              // data sent from Arduino1

    Serial.println(tempC);
  }
}

My issue is that I am reading on the serial monitor 4 different 2 integer values

What exactly are you seeing in the serial monitor? What does "4 different 2 integer values" mean?

The code comes from this: https://arduino.stackexchange.com/questions/16227/sending-a-value-from-one-arduino-to-another That example for sending and receiving a single byte. You want to send a text (a text that shows a floating point number), so you will have to read that complete text.

Your slave is sending an array of characters and your master is reading the ASCII values of those characters.
If you send 25.43, Serial.println will send 7 characters 2, 5, ., 4, 3, carriage return and a newline.
The master will read them as 50, 53, 46, 52, 51, 13 and 10. Your code then prints:
50.00
53.00
46.00
52.00
51.00
13.00
10.00

On your master, the loop() should look like:
void loop() {
  if (Serial.available()) {
    char c = Serial.peek(); // just look at the next character on the serial buffer
    if (c == '\r' || c == '\n') // ignore the carriage return and newline characters
      Serial.read(); // remove the character from serial buffer by reading it
    else {
      tempC = Serial.parseFloat(); // read and parse the string representing the float value
      Serial.println(tempC);
    }
  }
}

The value is floating point, not integer.  Reading the integer part would be a start, though that will truncate rather than round.  Possible solutions are parsing the float, rounding to an integer on the sender, or something like multiplying by 100, rounding, sending that, and then on the receiver copying the multiplied value to a float and dividing it back.

I fixed it, so it properly reads the floating point value.


text:
How to Jump from one loop to another while executing
For my program I have to sense 3 inputs (A1, A2 and A3 in Arduino). If any one or two or more signals become zero (low), it goes in different case as per below program.
However, I want to reset the Arduino when all signals become high again. Therefore I have to again write another program loop2().
So how can I exit from one loop and get into another loop. If I have to use goto, please tell me how to use it?
The Arduino program given below.
const int analogPin1 = A1;
const int analogPin2 = A2;
const int analogPin3 = A3;
const int ledPin = 13;
const int ledPin2 = 7;
const int  thresold = 400;
unsigned int x1,x2,x3,fault = 0;

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

void Config()
{
    delay(1000);
    Serial.print("ATE0r");
    Response();
    Serial.print("ATr");
    Response();
    Serial.print("AT+CMGF=1r");
    Response();
    Serial.print("AT+CNMI=1,2,0,0,0r");
    Response();
}

void Response()
{
    int count = 0;
    Serial.println();
    while(1)
    {
        if(Serial.available())
        {
            char data =Serial.read();
            if(data == 'K'){Serial.println("OK");break;}
            if(data == 'R'){Serial.println("GSM Not Working");break;}
        }
        count++;
        delay(10);
        if(count == 1000){Serial.println("GSM not Found");break;}

    }
}

void loop()
{
    int analogValue1 = analogRead(analogPin1);
    int analogValue2 = analogRead(analogPin2);
    int analogValue3 = analogRead(analogPin3);

    if (analogValue1 < thresold)
    { x1=1;
        fault=x1;
    }
    if (analogValue2 < thresold)
    {  x2=x1+3;
        fault=x2;
    }
    if (analogValue3 < thresold)
    {  x3=x1+x2+5;
        fault=x3;
    }

    switch(fault)
    {
    case 1:

        digitalWrite(ledPin, HIGH);
        Serial.print("AT+CMGF=1\r");
        delay(1000);
        Serial.print("AT+CMGS=\"+919512700997\"\r");
        delay(1000);
        Serial.print("PHASE 1 HAS GONE");
        delay(1000);
        Serial.write(0x1A);
        delay(1000);
        loop2();
        break;

    case 3:

        digitalWrite(ledPin, HIGH);
        Serial.print("AT+CMGF=1\r");
        delay(1000);
        Serial.print("AT+CMGS=\"+919512700997\"\r");
        delay(1000);
        Serial.print("2 HAS GONE");
        delay(1000);
        Serial.write(0x1A);
        delay(1000);
        break;

    case 4:
        digitalWrite(ledPin, HIGH);
        Serial.print("AT+CMGF=1\r");
        delay(1000);
        Serial.print("AT+CMGS=\"+919512700997\"\r");
        delay(1000);
        Serial.print("1 AND 2 HAS GONE");
        delay(1000);
        Serial.write(0x1A);
        delay(1000);
        break;

    case 5:

        digitalWrite(ledPin, HIGH);
        Serial.print("AT+CMGF=1\r");
        delay(1000);
        Serial.print("AT+CMGS=\"+919512700997\"\r");
        delay(1000);
        Serial.print("3 HAS GONE");
        delay(1000);
        Serial.write(0x1A);
        delay(1000);
        Serial.print("AT+CNMI=2,2,0,0,0");
        break;

    case 6:

        digitalWrite(ledPin, HIGH);
        Serial.print("AT+CMGF=1\r");
        delay(1000);
        Serial.print("AT+CMGS=\"+919512700997\"\r");
        delay(1000);
        Serial.print("1 AND 3 HAS GONE");
        delay(1000);
        Serial.write(0x1A);
        delay(1000);
        break;

    case 8:

        digitalWrite(ledPin, HIGH);
        Serial.print("AT+CMGF=1\r");
        delay(1000);
        Serial.print("AT+CMGS=\"+919512700997\"\r");
        delay(1000);
        Serial.print("2 AND 3 HAS GONE");
        delay(1000);
        Serial.write(0x1A);
        delay(1000);
        break;

    case 10:

        digitalWrite(ledPin, HIGH);
        Serial.print("AT+CMGF=1\r");
        delay(1000);
        Serial.print("AT+CMGS=\"+919512700997\"\r");
        delay(1000);
        Serial.print("ALL 3 HAS GONE");
        delay(1000);
        Serial.write(0x1A);
        delay(1000);
        break;

    default:
        x1,x2,x3,fault=0;
        digitalWrite(ledPin, LOW);
        break;

    }

    x1,x2,x3,fault=0;
    digitalWrite(ledPin, LOW);
    do
    {
        int analogValue1 = analogRead(analogPin1);
        int analogValue2 = analogRead(analogPin2);
        int analogValue3 = analogRead(analogPin3);
    }
    while ( analogValue1 < thresold || analogValue2 < thresold || analogValue3 < thresold );

}

do
{
    int analogValue1 = analogRead(analogPin1);
    int analogValue2 = analogRead(analogPin2);
    int analogValue3 = analogRead(analogPin3);
}
while (( analogValue1 > th) && (analogValue2 > th) && (analogValue3 > th));

}

void loop2()
{
    if (( analogValue1 > th) && (analogValue2 > th) && (analogValue3 > th))
    {

        digitalWrite(ledPin, HIGH);
        Serial.begin(9600);
        Serial.print("\r");
        delay(1000);
        Serial.print("AT+CMGF=1\r");
        delay(1000);
        Serial.print("AT+CMGS=\"+919512700997\"\r");
        delay(1000);
        Serial.print("Nikunjsinh2");
        delay(1000);
        Serial.write(0x1A);
        delay(1000);
        Serial.print("\r");
        delay(1000);
        Serial.print("AT+CMGF=1\r");
        delay(1000);
        Serial.print("AT+CMGS=\"+919712554766\"\r");
        delay(1000);
        Serial.print("Nikunjsinh2");
        delay(1000);
        Serial.write(0x1A);
        delay(1000);

        do
        {
            int analogValue1 = analogRead(analogPin1);
            int analogValue2 = analogRead(analogPin2);
            int analogValue3 = analogRead(analogPin3);
        }
        while (( analogValue1 > th) && (analogValue2 > th) && (analogValue3 > th));
    }
}

x1,x2,x3,fault=0; doesn't do what you think it does.

Also, with do  { int analogValue1 = ...} you are creating new variables that only exist inside the loop body. Remove the int s.

you can use goto in arduino to hop around labels. serious/team programmers might cringe, but it works.

It is clear from your question you intuitively know this program will not perform as desired.  Simply put, if you do not check all states during every loop, you can not possibly react to all possibilities.  Therefore you can only have 1 loop.  Get rid of the other loops.

...but i want to reset arduino when all signal becomes again high...

This statement identifies what is missing.  You need a temporal aspect to the loop in order to "remember" that all signal(s) were not high on the previous loop and now in the current loop they are all high.
Programmers commonly refer to this feature as a Finite State Machine.  A way to "remember" what state the loop was in the last time it was executed.  And a way to know what state(s) is(are) next possible.
If all you need to remember is that not all 3 inputs were high the last time through the loop, your state machine only needs the one value.  And that value only needs to be a zero or one.


text:
I2C requesting more than one byte
I got an Arduino Uno set up as an I2C master to an ATtiny85 slave, using the Wire (Master) and TinyWireS (Slave) libraries.
Communication works well. I have been able to keep the network running correctly for hours. However, I have not been able to let the master request more than a single byte from the slave.
Using the code below the master asks for 4 bytes from the slave, but in my serial console I get only an actual value for the first bytes. The next three bytes read 255.
How can I request multiple bytes from the slave, using the Wire library?

Master (Arduino Uno)
#include <Wire.h>

#define I2C_MASTER_ADDR 0x04
#define I2C_SLAVE_ADDR 0x05

int pollInterval = 700;//Milliseconds
unsigned long lastPoll = 0;

void setup()
{
  Wire.begin(I2C_MASTER_ADDR);  // join i2c bus
  Serial.begin(115200);
  Serial.println("Setup complete");
}

/*
 * The main loop
 */
int i = 0;

void loop()
{

  //Writing to the slave
  if( (millis()-lastPoll) > pollInterval)
  {
    Wire.beginTransmission(I2C_SLAVE_ADDR);
    Wire.write(0x01);//Register to start at
    switch(i)
    {
      case 0:
        Wire.write(255);
        Wire.write(0);
        Wire.write(0);
        i++;
        break;
      case 1:
        Wire.write(0);
        Wire.write(255);
        Wire.write(0);
        i++;
        break;
      case 2:
        Wire.write(0);
        Wire.write(0);
        Wire.write(255);
        i = 0;
        break;
    }
    Wire.endTransmission();

    delay(1);//Dont let the slave panic

    //Set the register pointer back to 0x01, preparing for a read
    Wire.beginTransmission(I2C_SLAVE_ADDR);
    Wire.write(0x00);//Register to start at
    Wire.endTransmission();
    delay(1);//Dont let the slave panic

    //Get values from the three registers up from 0x01
    Wire.requestFrom(I2C_SLAVE_ADDR, 4);//Request N bytes
    while (Wire.available())
    {
      uint8_t next_byte = Wire.read();
      Serial.print(next_byte);Serial.print(" ");
    }
    Serial.println("\n");

    lastPoll = millis();
  }//End if time to poll again

}//End loop

Slave - ATTiny85
#include <EEPROM.h>
#include <TinyWireS.h>
#include <Bounce2.h>
#include <WS2812.h>
#ifdef __AVR__ //Which will be true for ATtiny85
  #include <avr/power.h>
#endif

#define I2C_SLAVE_DEFAULT_ADDR 0x05
#define BUTTON_DEBOUNCE 5//Debounce milliseconds

#define NEOPIXEL_PIN  1
#define BUTTON_PIN    3

#define NUMPIXELS     1

/*
 * I2C Registers
 *
 * Register map:
 * 0x00 - Button state
 * 0x01 - led value red
 * 0x02 - led value green
 * 0x03 - led value blue
 *
 * Total size: 4
 */
const byte reg_size = 4;
volatile uint16_t i2c_regs[reg_size];

/*
 * Internal variables
 */
cRGB value;
volatile boolean led_needs_update = false;
volatile byte reg_position;

/*
 * Initialize instances/classes
 */
Bounce button = Bounce();
WS2812 led(NUMPIXELS);

void setup()
{
  //Start I2C
  //uint8_t _device_addr = EEPROM_DATA::get_device_addr();
  TinyWireS.begin(I2C_SLAVE_DEFAULT_ADDR);
  TinyWireS.onReceive(i2cReceiveEvent);
  TinyWireS.onRequest(i2cRequestEvent);

  //Start Led
  led.setOutput(NEOPIXEL_PIN);
  value.b = 255; value.g = 0; value.r = 0;
  led.set_crgb_at(0, value); //Set value at LED found at index 0
  led.sync(); // Sends the value to the LED

  //Start Button
  pinMode(BUTTON_PIN, INPUT_PULLUP);
  button.attach(BUTTON_PIN);
  button.interval(BUTTON_DEBOUNCE);

}

void loop()
{
  button.update();

  if(led_needs_update)
  {
    led_update();
    led_needs_update = false;
  }

  if(button.fell())
  {
    i2c_regs[0x00] = true;
  }
  if(button.rose())
  {
    i2c_regs[0x00] = false;
  }

  // This needs to be here for the TinyWireS lib
  TinyWireS_stop_check();

}

/*
 * I2C Handelers
 */
void i2cReceiveEvent(uint8_t howMany)
{
    if (howMany < 1)
    {
        return;// Sanity-check
    }

    reg_position = TinyWireS.receive();
    howMany--;
    if (!howMany)
    {
        return;// This write was only to set the buffer for next read
    }

    while(howMany--)
    {
        //Store the recieved data in the currently selected register
        i2c_regs[reg_position] = TinyWireS.receive();

        //Proceed to the next register
        reg_position++;
        if (reg_position >= reg_size)
        {
            reg_position = 0;
        }
    }
    led_needs_update = true;
}//End i2cReceiveEvent()

void i2cRequestEvent()
{
    //Send the value on the current register position
    TinyWireS.send(i2c_regs[reg_position]);

    // Increment the reg position on each read, and loop back to zero
    reg_position++;
    if (reg_position >= reg_size)
    {
        reg_position = 0;
    }
}//End i2cRequestEvent

/*
 * Helper functions
 */
void led_update()
{
  cRGB val;
  val.r = i2c_regs[0x01];
  val.g = i2c_regs[0x02];
  val.b = i2c_regs[0x03];
  led.set_crgb_at(0, val);
  led.sync(); // Sends the value to the LED
}

This is another case where the Arduino documentation is horribly incomplete to the point of being useless, and you must refer to the source code itself.
Presuming your TinyWire library works like the ordinary Arduino Wire, you need to use the two-argument form of the write method:
size_t TwoWire::write(const uint8_t *data, size_t quantity)

So your handler would probably look like this
void i2cRequestEvent()
{
    TinyWireS.write(i2c_regs, sizeof(i2c_regs));
}

However, you're also going to need to change your definition to an 8-bit type, rather than the 16-bit one you surprisingly had
volatile uint8_t i2c_regs[reg_size];

If you really do need to use a 16-bit type, then you'll need to either double the transfer size (since both processors are AVRs you won't hit any byte order issues) or first copy the values that you care about to a byte buffer.

Thanks for your answer. I updated uint16_t to uint8_t, my mistake.
The TinyWireS uses the following write command, accepting only a single argument:
void USI_TWI_S::send(uint8_t data){  // send it back to master
usiTwiTransmitByte(data);
}
But as far as I understand that's actually normal I2C convention: the Wire library should request multiple bytes, one at a time. The slave responds with one byte to each request, jumping to the next register afterwards so the next requested byte comes from the next register.

It may offer a single argument write, but that won't work for you.  Check its source code and see if it also offers a two argument write - the normal Wire library offers both.  If not, you'll probably have to modify the library.  And no, i2c convention is to request multiple bytes at once, which is what you are doing.   However, if you write a starting register in the preceding write, then you could I guess do distinct one-byte requests for each register in turn.

Hi @Chris, thanks again. I could only find a single argument write. In terms of performance, would making multiple one-byte requests slow things down (compared to a wire.request N bytes request)? Just figuring out my options, based on your answer/comment.

Yes, multiple one byte requests would be slower.  Also, it might yield values that aren't consistent with one another but come from different data points.   You should be able to create a multi-byte write by comparing the source of the usual Wire library which has it with yours which apparently does not, and using that to write one - ie, figure out the differences between the two for the single byte case, and then apply those to the multi-byte code.

The master uses the 'normal' Wire library, but the TinyWireS is not normal at all. The master defines how many bytes are read. The slave can send a byte or not. If the slave does nothing, then the data will become 255. Could you try a requestEvent with four calls to TinyWireS.send with fixed numbers. For example TinyWireS.send('A') and 'B', and 'C' and 'D', or with numbers.

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


text:
Sending data by nRF24L01 with Arduino
Can I send data using nRF24L01 with Arduino through multiple pipes?
As by using the RF24 library, I can send data through just one pipe and receive on the 6 pipes that nRF24L01 has.

Yes, but the nRF24L01 can only transmit one message at at time, since it only has one buffer.
So roughly speaking, for each message

Set the transmit pipe address (if different than the last one)
Send data
Wait for completion (and ack or failure, if in that mode)


text:
Help with arduino float
I am having trouble with this code:
#include <Wire.h>
#include <MPU6050.h>

MPU6050 mpu;

// Timers
unsigned long timer = 0;
float timeStep = 0.01;

// Pitch, Roll and Yaw values
float pitch = 0;
float roll = 0;
float yaw = 0;

int button_pin=5;
int button_state;
void setup()
{
  Serial.begin(115200);

  // Initialize MPU605
  while(mpu.begin(MPU6050_SCALE_2000DPS, MPU6050_RANGE_2G))
  {
    Serial.println("Could not find a valid MPU6050 sensor, check wiring!");
    delay(500);
  }

  // Calibrate gyroscope. The calibration must be at rest.
  // If you don't want calibrate, comment this line.
  mpu.calibrateGyro();

  // Set threshold sensivty. Default 3.
  // If you don't want use threshold, comment this line or set 0.
  mpu.setThreshold(3);

  pinmode(button_pin,INPUT)
}

void loop()
{
  int button_state=digitalRead(button_pin)

  timer = millis();

  // Read normalized values
  Vector norm = mpu.readNormalizeGyro();

  // Calculate Pitch, Roll and Yaw
  pitch = pitch + norm.YAxis * timeStep;
  roll = roll + norm.XAxis * timeStep;
  yaw = yaw + norm.ZAxis * timeStep;

  // Output raw
  Serial.print(" Pitch = ");
  Serial.print(pitch);
  Serial.print(" Roll = ");
  Serial.print(roll);
  Serial.print(" Yaw = ");
  Serial.println(yaw);

  // Wait to full timeStep period
  delay((timeStep*1000) - (millis() - timer));
}

But when I add this code at the end:
If (pitch <=90 && pitch => 15 && button_state =(HIGH))
{
}

I keep getting this error:

error: lvalue required as left operand of assignment

I know the issue is about the pitch part of the if. I just need to know how to fix it.

The if-statement should be if not If

Could you please post the error that you are getting.

also button_state =(HIGH) should be button_state == HIGH or more simply button_state

@sa_leinad I get this error (error: lvalue required as left operand of assignment) this iş the error I am getting

You have two declarations of button_state.  This won't cause a problem because the scoping rules will mean inside loop you are using the local one and everywhere else you are using the global one.  Personally I would remove the global one since you aren't using it.
As mentioned in the comments you have mistyped the If keyword (but I think this is just on here not in you code) and you have used an assignment statement rather than a equivalence (= instead of ==).
Since you have tagged it as code review here are some minor points you might want to consider.
If a value doesn't change then you could mark it as const, this doesn't make much difference to the compiler, it already knows, but it will help you when you come back to the code next week.
  So: const int button_pin = 5;
If you only use a const int value once you might be better #defining it (more than once a const value should produce smaller code).  The pre-processor (part of the compile process) will replace the defined name with the value, but you have easier to read and maintain code.
  So: #define button_pin 5
If you #define an int then always enclose the value in brackets to protect it from "arithmetic issues" (I can't think of a better way of describing it).
  So: #define button_pin (5)

thanks for your suggestions, but still you haven't told me how to fix the error

The solution to your problem was answered by sa_leinad in the comments on you post and is covered in the second paragraph of my answer.  "you have used an assignment statement rather than a equivalence".  If you tell me you IP address I'll remote into your machine and fix your code for you if you like.

The first thing I noticed was that you had a capital I in your if-statement.
Secondly, button_state =(HIGH) should be button_state == HIGH. A single = sign means that you are assigning a value to the variable on the left - in this case button_state. It is a common mistake that I have made many times.
Also, because it is a boolean comparison, you can simplify the statement by removing the == HIGH leaving just button_state.
This would then change the if-statement to the following:
if ((pitch <= 90) && (pitch => 15) && button_state)

I have added extra parentheses for clarity/readability but they're technically not needed.

In addition to what Code Gorilla has already stated in his answer and a few additional semi-colons, your code should look something like this:
#include <Wire.h>
#include <MPU6050.h>

MPU6050 mpu;

// Timers
unsigned long timer = 0;
float timeStep = 0.01;

// Pitch, Roll and Yaw values
float pitch = 0;
float roll = 0;
float yaw = 0;

const int button_pin = 5;

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

  // Initialize MPU605
  while(mpu.begin(MPU6050_SCALE_2000DPS, MPU6050_RANGE_2G))
  {
    Serial.println("Could not find a valid MPU6050 sensor, check wiring!");
    delay(500);
  }

  // Calibrate gyroscope. The calibration must be at rest.
  // If you don't want calibrate, comment this line.
  mpu.calibrateGyro();

  // Set threshold sensivty. Default 3.
  // If you don't want use threshold, comment this line or set 0.
  mpu.setThreshold(3);

  pinmode(button_pin,INPUT);
}

void loop()
{
  int button_state = digitalRead(button_pin);

  timer = millis();

  // Read normalized values
  Vector norm = mpu.readNormalizeGyro();

  // Calculate Pitch, Roll and Yaw
  pitch = pitch + norm.YAxis * timeStep;
  roll = roll + norm.XAxis * timeStep;
  yaw = yaw + norm.ZAxis * timeStep;

  // Output raw
  Serial.print(" Pitch = ");
  Serial.print(pitch);
  Serial.print(" Roll = ");
  Serial.print(roll);
  Serial.print(" Yaw = ");
  Serial.println(yaw);

  if ((pitch <= 90) && (pitch => 15) && button_state)
  {
      // Code goes here
  }

  // Wait to full timeStep period
  delay((timeStep*1000) - (millis() - timer));
}

In the if statement:
if (pitch <=90 && pitch => 15 && button_state =(HIGH))

you assign a new value to button_state, which is illegal.
This should read:
if (pitch <=90 && pitch => 15 && button_state == HIGH)

Your first statement is incorrect. The condition in the first if is parsed as (pitch <= 90 && pitch => 15 && button_state) = HIGH (which does not compile), not as pitch <= 90 && pitch => 15 && (button_state = HIGH) (which would compile and is what your answer implies). Hence the compile error “lvalue required as left operand of assignment”.