text:
How is a long int stored in an 8 bit Arduino register
Assume the following code in C:
long int a = 262143;

which in binary will be 111111111111111111 (18 bits).
If an atmega328p register can hold 8 bits, how is the above represented in the register?
Compiled Assembly:
    .file   "a.c"
__SP_H__ = 0x3e
__SP_L__ = 0x3d
__SREG__ = 0x3f
__tmp_reg__ = 0
__zero_reg__ = 1
    .text
.global main
    .type   main, @function
main:
    push r28
    push r29
    rcall .
    rcall .
    in r28,__SP_L__
    in r29,__SP_H__
/* prologue: function */
/* frame size = 4 */
/* stack size = 6 */
.L__stack_usage = 6
    ldi r24,lo8(-1)
    ldi r25,lo8(-1)
    ldi r26,lo8(3)
    ldi r27,0
    std Y+1,r24
    std Y+2,r25
    std Y+3,r26
    std Y+4,r27
    ldi r24,0
    ldi r25,0
/* epilogue start */
    pop __tmp_reg__
    pop __tmp_reg__
    pop __tmp_reg__
    pop __tmp_reg__
    pop r29
    pop r28
    ret
    .size   main, .-main
    .ident  "GCC: (GNU) 8.2.0"

It isn't.  It's split into four 8-bit values, each representing a quarter of the bits.  Each value is stored in a separate register or memory location (depending on what is being done with it).
Software then combines them together to act as a single 32-bit value.

Then how would a single instruction look like? isn't an instruction supposed to be 8 bits in length in this case?

There is no "single instruction".  You should compile some code and look at the resultant assembly language - you'll find it's many instructions long.  This is why 32-bit CPUs are more efficient than 8 bit.

I added the assembly code above, so I guess ldi r24,lo8(-1)     ldi r25,lo8(-1) are doing that

and ldi r26,lo8(3) since you're working with 18 bits not 16.  0xFF is -1 in two's complement, so you have 0x03 ff ff which is 0b111111111111111111.

one last question, what does the above code do exactly? it populates 3 registers with 2  lower 8 bit of -1 = 111111 and 1 lower 8 bit of 3 = 000011 ?

Yes. "ldi" is "LoaD Immediate".  You end up with r24 = 0xFF, r25 = 0xFF and r26 = 0x03.

One more off topic question (hope I can ask it properly). instructions are stored in RAM right, in this case an 8 bit instruction is somewhere in RAM and CPU loads it. How does CPU know where the instruction ends given a RAM address? how does it know the different between an instruction and a small integer length which has lower bit counts? Basically how doesn't it keep reading the RAM and knows where to stop

Fun fact: the compiler supports int64_t and uint64_t on a arduino uno. That is a variable of 64 bits (8 bytes) on a 8 bit microcontroller.

@Joshl No - instructions are in flash, not RAM, and flash is 16 bits wide.  Each instruction either fits in one 16 bit word or two 16 bit words depending on the instruction. The CPU knows how "long" each instruction is by the fact that the instruction itself will contain information about what needs to be fetched from where.

It's actually 4 registers (r27:r24), and 4 bytes of stack: (SP+1 to SP+4). Not sure why the stack is used. Maybe the variable was volatile, or the code was compiled at -O0...

@EdgarBonet The stack is used because r24-r27 are in the "call clobbered" category. They're just used temporarily to place the values into memory since you can't LDI direct into memory. Registers 18-27, 30 and 31 can only be used for temporary storage since any function called is allowed to change the value and not restore it. 2 to 17, 28 and 29 are "call saved" - any function must restore them after use. Whether the compiler decides to use memory or "call saved" registers for its variables depends on what it's being used for and what else is going on.

https://gcc.gnu.org/wiki/avr-gcc#Call-Used_Registers

I am aware of the call saved / call clobbered distinction. My point is: if you don't make a volatile, then it is optimized away by the compiler at any optimization level other than -O0.

@EdgarBonet no it isn't.  It can be, but whether or not it is depends entirely on both what a is being used for, and what other variables are around. There's limited registers that can be used. If a is considered less important it won't waste a dedicated group of registers on it  You cannot second guess what the optimizer will do just on the strength of a single variable.

I can. I have read the compiler's generated assembly.

It probably was compiled with no optimization anyway. That assembly can't have been produced from Arduino code, so has no validity on this site anyway. So it's very much down to whatever the OP typed on the command line, and so is outside the scope of this site.


text:
LED on Arduino does not blink
I successful installed arduino, added me to uucp and lock and loaded cdc_acm module.
I use Arduino Uno R3, so I also installed arduino-avr-core.
I have Arduino on /dev/ttyUSB0.
I configured with:
stty -F /dev/ttyUSB0 cs8 9600 ignbrk -brkint -imaxbel -opost -onlcr -isig -icanon -iexten -echo -echoe -echok -echoctl -echoke noflsh -ixon -crtscts

I have this folder with these files:
~/Documents/Arduino
build.options.json
------------------------------------------------------------
{
    "fqbn": "archlinux-arduino:avr:uno",
    "hardwareFolders": "/usr/share/arduino/hardware",
    "toolsFolders": "/usr/bin"
}

sketch.ino
------------------------------------------------------------
void setup() {
    pinMode(13, OUTPUT);
}

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

After this commands I got output:
arduino-builder -build-options-file build.options.json sketch.ino

Sketch uses 914 bytes (2%) of program storage space. Maximum is 32256 bytes.
Global variables use 9 bytes (0%) of dynamic memory, leaving 2039 bytes for local variables. Maximum is 2048 bytes.

But nothing happened on my Arduino, what's my problem?
Thanks.
P.S. I don't have external LED, I try to use bultin LED.

did you try Arduino IDE?

I don't wanna use Arduino IDE. And when I tried it, I got error with avrdude.

there is no way around avrdude

You invoked the builder, but not an upload to the board. The builder created a hex file.You should use avrdude for upload.
Or use Arduino IDE which does it with a click on a button

I don't have hex file. I try to search, but I cannot find it.

turn on verbose output of the builder

source: Stack Exchange

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

sort: votes


text:
How to connect a SilentStepStick TMC2130 stepper driver?
please excuse the noob question
Am connecting a SilentStepStick to arduino with a stepper, for bench testing.
It requires 5V power, plus I have a 24V power supply for the steppers.
+5V connected to Vio, and +24V connection to VM.
Question: how to connect the grounds?  The device has two GND pins.  Should I just connect one ground, from the 5V power supply, to avoid ground loops?
Or should grounds from both power supplies be connected?
Thankyou for any advice.

Answer: (from Electrical Engineering), yes both grounds must be connected.
In this example, +5V and GND from the arduino would connect to the two top left pins in the diagram (Vio & GND).
The two 24v power lines would connect to the bottom left two pins, Vm & GND

Aren't the grounds connected to each other on the board, and so couldn't you connect either ground to either pin?

According to the .brd file found at Watterotts github, yes, both grounds are connected to the same ground plane on the PCB.

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


text:
Correlated signal from two sensors in one circuit
I have water level/humidity sensor and a LDR diode hooked to arduino like this (the resistor is 10k)

On A0 I can read signal from water sensor (blue)
On A1 I can read signal from light sensor (yellow)

The problem is that both signals seem to be correlated. When I dip the water sensor to water and keep the light levels the same, the signal from light goes up as well (dramatically).
I suspect that this is due to Ohm's law. The voltage in a circuit depends on the total resistance of the circuit. Both sensors act as a sort of resistors so when one's resistance changes the voltage in the circuit changes as well.
How can I wire the sensors such that the change in resistance of either sensor doesn't affect the second? Or do I need a separate power supply for each sensor?

is the light sensor wiring right? shouldn't the resistor connect to ground?

I get some signal, so I guess it is (row 37)

You can try to read another channel between them - connected to ground to discharge sampling capacitor.

@KIIV I am not sure if I follow (still learning the lingo). You mean like connecting a simple resistor to GND and A3 (same as the LDR is wired). and read A0 (water) -> A3 (discharge)  --> A1 (light)?

Yes, pretty much. But you can short A3 to the ground directly. And sequence would be:  A3 (discharge), A0 (water), A3 (discharge), A1 (light). Now it shouldn't be crosstalking between A0 and A1 as it starts the measure on completely discharged capacitor. Now it'll depend on output impedance of sensors only.

short A3 to the ground directly You mean a jumper from row 45 GND to A3 directly? just making sure

https://electronics.stackexchange.com/questions/213851/arduino-analogread-neighbor-pin-noise-on-adc-even-with-big-delay

I still think the problem is the pullup resistor

I've unplugged the whole thing and rebuilt from scratch. That didn't work initally, so I wired A3 to GND directly and read a value from that. Then I unplugged the A3-GND and it seems to be working just fine even without it. Thanks to both of you! @Juraj, if you compile the A3-GND tip to an answer I will happily accept it, since that seemed to help imo

@KIIV knew what to do, answer is his

of course (sorry @KIIV !) just swapped the two names. Thanks to both of you anyway

If I've found the same humidity sensor, it has pretty big output impedance and the maximum input impedance for the ADC input is 10kOhms. According the the datasheet the recommended minimum load for the sensor is about 80kOhms (?). That means readings of humidity sensor will be highly affected by sampling capacitor initial charge (= the value of previous reading).
Basically reading GND between sensor readings helps to separate the results from each other, but the humidity sensor won't be able to charge sampling capacitor to its output voltage without amplifying the current (you'll get values much lower than it should be).
Or you can repeat the readings on humidity sensor channel several times until the value is more "stable".


text:
Arduino Due ADC negative voltage
I’m trying to sample an AC signal on the Arduino Due. The AC signal will never exceed +-80mv across a frequency range of 6-833Hz. Current is negligible.
I believe there are clamping diodes to protect from this but cannot find any datasheets for the Due.
I understand that the Due cannot read negative voltage but can a negative voltage damage the ADC or it’s accuracy?

Add a DC offset to your signal. Make it all positive.

or add a diode to cut away the negative part

Can’t use a diode because I’ll lose 0.7v. I could add a DC offset but I need high accuracy, I’d like to avoid adding any extra noise.

It's not a datasheet for the Due you need, but a datasheet for the ATSAM3X8E microcontroller on the Due, which you can download here: https://www.microchip.com/wwwproducts/en/ATSAM3X8E

The best thing you can do is to simply add a DC offset to your signal.  Instead of having it be 0V ±80mV, have it 1.65V ±80mv.  All you need is a capacitor and two resistors:

simulate this circuit – Schematic created using CircuitLab
However, 80mV is not going to have much resolution unless you reduce your reference voltage considerably, and in that case you'd need to reduce the 3.3 down to the same (or around) the reference voltage you use.
But, just feeding your signal directly into the ADC will give you the positive 80mV signal which you can use a smaller reference voltage with directly with no problem - after all, the datasheet shows:

Voltage on Input Pins
  with Respect to Ground (except VBUS)...............-0.3V to +4.0V

So you can provide down to -300mV on an analog input before it potentially becomes a problem.
This is because all the IO pins have ESD protection diodes, which look like this:

simulate this circuit
Those diodes have a forward voltage of about 300mV, and so anything below -300mV will cause the lower diode to start conducting. When that happens too much current can flow and the diode risks burning out.  But you can add further protection by simply adding a small resistor (1kΩ is good) in series with the IO pin to limit the current in the case that the voltage goes below -300mV and protect the internal circuitry.

Probably leaving the scope of this question but is the 3v3 pin noise free? Obviously any noise on the DC offset voltage will add noise to the AD conversion. Also, If I use say 1v as Vref, where is the best source for a noise free voltage... the DAC? Or external?

The 3.3V can be noisy, yes, since the main MCU is being powered from it.  For low-noise operation you need a low noise "precision voltage reference" chip.


text:
Arduino direction sensor
I am working on a school project for next week
And I need my Arduino to 'sense' at which direction it is moved is it possible? Are there any direction sensors that 'sense' at which direction the Arduino is moving?

Direction relative to itself or the absolute direction (like north or south)?

@chrisl  no I want the Arduino to sense that it goes up, down, right or left sry  that I didn't included in the question

https://playground.arduino.cc/Main/MPU-6050

@Juraj na not much help

it is, how it is done. study

As Juraj wrote, you need an MPU, which is a module, that consists of an 3-dimensional accelerometer and a 3-dimensional gyroscope. With the first you can sense acceleration in each of the 3 dimensions (up-down, left-right, forwards-backwards), with the seconds you can sense rotation around these three directions. Sometimes (depending on the module) there is also an magnetometer included, which can be used as a compass.
Note, that you cannot sense the actual speed of a device directly, without using some external reference. With an accelerometer you have to do some maths on the data to get the speed (basically integrating). But since you just want to sense the direction, without bothering about the exact speed, you don't have to think about this.
How exactly you have to program this is out of scope for this side, since it is a rather big topic. Also it depends on the module and library you use. The link, that was provided by Juraj, is a good starting point for reading about this. There are also some further links, for example to a library for controlling the MPU-6050 (if you have one of these) at this github site.
Basically you will have to regularly measure the acceleration in all three dimensions with the MPU. If for an axis the acceleration gets greater than a threshold value, you can count this as direction. To get a more precise direction (not only directly along the axis) you will have to combine the values of the dimensions as a vector. How this is to be solved depends greatly on what you want to achieve.


text:
how to connect 100 Leds and Blink them on Arduino
I am planning to connect 100 LEDs to an arduino in a parallel circuit.
The current limit exceed beyond the Arduino UNO board.
In want to blink all 100 LEDs at same time.  So how can I provide power source to 100 LEDs so they can blink with arduino programming.
Thanks in advance
Edit: As per discussion, MOSFET is required but which value MOSFET is required. There are many P- and N-channel MOSFETs available.

Arduino problem is only how to blink, not what to blink.

A relay, a mosfet, a (motor) driver, a transistor, and so on. Have you soldered 100 leds parallel? That was a bad idea, they will not have the same brightness, since they require a certain current, not a voltage. What kind of leds are they?

I little bit understand that Mosfet work as a switch of blinking function. What mosfet is better for lit 100 leds. i didn't connect 100 leds yet, but i will make circuit according to connectivity with arduino.

For 100 LEDs in parallel you will also need 100 resistors, and a transistor (MOSFET) that can handle the total current for all the LEDs.
For instance, at 20mA drive current you would be dealing with 2A - you'd need a (minimum) 2A power supply and a MOSFET that can handle 2A.
Or you can think a little differently.
If you use a higher voltage power supply you can group your LEDs together into chains.  For example with a 12V power supply you could (depending on the voltage of the LEDs) have up to 4 in a chain (red LEDs, 2V forward voltage, 2x4=8. White LEDs, 3V forward voltage, 3x4=12).  Each chain then has a single resistor, and you're working with a quarter of the current (500mA) - just 25 chains of 20mA but at a higher voltage.  So you can use a smaller MOSFET and you have only 25 resistors.
Another thing you could consider is to then further group those chains together. Maybe 5 groups of 5 chains, each with their own MOSFET. Then you switch just one group on at a time, but cycle through them very rapidly.  Each group only then uses 100mA (5 chains at 20mA = 100mA), and you can use a really small MOSFET, and your power supply needs only be able to provide a couple of hundred mA (give it some headroom) and can be smaller and cheaper.
The only down-side of that method is you can get flicker which may be noticeable if the LEDs are moving. It also means your Arduino is doing more work to light all the LEDs.

Thanks for valuable reply. I also have 10 RGB Common Anode. in this project i want to make different animations,effects. I am studying about mutiplexing. Is it necessary to use TLC5940NT IC for multiplexing?

No, you don't need the TLC5940NT. That doesn't multiplex, anyway, it's a shift register.  For simple multiplexing of 10 LEDs you want 10 P-channel FETs and 3 resistors. Or you can use 5 P-fets and 6 N-fets and 6 resistors, depending on how you want to arrange your multiplexing. If you only want to use low currents then you could probably get away without the fets - as long as the total curret through an IO pin at any moment in time doesn't exceed 25mA (or 40mA for brief periods).

ok could you please tell me the correct values for both p-channel FETS and 3 resistors and 5 p-fets and 6 n-fets, 6 resistors............................I little bit understand that Mosfet work as a switch of blinking function. What mosfet is better for lit 100 leds. i didn't connect 100 leds yet, but i will make circuit according to connectivity with arduino..........If you can share some tutorials, i will be very thankful to you.

A MOSFET is just a switch (in this situation), yes.  You need to make sure it can handle the peak current for your arrangement, and that the threshold voltage (VGS) is below about 4V - ideally below 2V (-4 and -2 for P FETs).  P FETs switch the anodes, and N FETs switch the cathodes. Multiplexing is just rapid switching on and off of LEDs so fast you can't see it.

thanks for reply. last thing could you provide p channel mosfet name (like IRFxxxxx)  for multiplexing RGB leds. i dont have enough knowledge about electronic components.

Please help only P-channel MOSFET value is required.

I do not know any suitable for hobbyists. All the ones I use are SMD components.  Use the parametric search of your favourite supplier to find one with enough current capacity, the right kind of threshold voltage, and a package suitable to your needs.


text:
Arduino YUN Rev. 2 power supply
I want to connect my YUN Rev. 2 to 7.4V.
I read that the older version only provides exactly 5 V at the Vin Pin. Is the Rev. 2 similar to it? I read that the power supply should be improved, but what does that mean?
I just tried to connect the Vin to regulated 5 V by a power supply board, but it didn't work. If I connect it to the 5V Pin the board is working, but I think this isn't recommended.
So has anybody experience with that board?
Thanks for your answers.

are you sure 5V pin is working and Vin is not for supplying power?

Yes, I just tried it several times. Even if I change the voltage.

For version 1 VIN is connected, through a Schottky diode, to the 5V rail.  That means you can only provide, at absolute most, 5V plus a little bit for the diode drop into VIN.  The 5V pin can only source power on the Yun, since it is also connected to the 5V rail through a Schottky diode.
In effect the two pins form the "In" and "Out" of the 5V power.
However in version 2 the 5V pin's diode has been removed, and the VIN's diode has been reversed.  VIN is now known as "5V_OUT".
So the 5V pin can be used for both in and out, and what was VIN can only be used for power out.
To provide more than 5V to the Yun you will have to first pass the voltage through a regulator of some form.  Since you want to use 7.4V it sounds like you are using 2S Li-Ion (or similar) batteries.  Because of that I'd recommend a switching regulator, rather than a linear one.  I commonly use 5V UBEC modules from my favourite RC model supplier.
For version 1 you will provide it to VIN.  For version 2 you will provide it to 5V.  Quite why they'd change something quite so fundamental as the power pin arrangement from one version to another is beyond me.  It would cause havoc with compatibility between versions with certain shields.

The regulator I just tried provides 4.9V. I just tried to use an transformer and it was the same, even when I changed the voltage. When it's connected to the 5V output the Yun is working fine...
I would try to use an other regulator, but I thought 4.9 V is in range or not?
Your right, I want to use two Li-Ion:

According to the schematics you should not be able to supply power through the 5V pin, and you should not be able to draw power from the VIN pin.  Maybe a mistake was made during manufacture and the diodes are backwards.

Hang on - yes, it's changed on V2 for some reason (why would they change something fundamental like that? Because they're idiots, that's why).

but it is good trick. if someone expects a build-in regulator, Vin would not work and supplying other then 5 V to 5V pin would be stupid

@Juraj Better would be to put an actual regulator on the board... That way VIN works like VIN on all the other boards with the same footprint...

I still didn't get the idea behind Yun and Tian

@Juraj I know, they make no sense. Why would you bother with such a thing when you can get a Pi for the same price, and get 200000x the oomph.


text:
Arduino Uno - MQTT message using PUBSUB on ESP8266
I'm trying to write code involving MQTT messages to operate an ESP8266 relay ( a Sonoff device ), using PubSub library.
For some, unknown for me, reason - messages larger than 99 chars are not sent. It this a known limitation ? can it be changed ?
void pub_msg(char *inmsg){
        char tmpmsg[255];
        // sprintf(tmpmsg,"[Cl:oc:k] [%s] %s",deviceTopic, inmsg);   ---> wish to add a time stamp
        sprintf(tmpmsg,"[][%s] %s",deviceTopic, inmsg);  ---> using this line just to find that 99 chars sent OK
        Serial.print("published MSG:");
        Serial.println(tmpmsg);
        Serial.print("Total chars:");
        Serial.println(strlen(tmpmsg));
        client.publish(msgTopic, tmpmsg);

}

The maximum MQTT packet size in PubSubClient is 128 bytes. After all the MQTT header information that leaves only 99 bytes for a message.
You can change it by editing the PubSubClient.h file:
#ifndef MQTT_MAX_PACKET_SIZE
#define MQTT_MAX_PACKET_SIZE 128
#endif

As it says in the PubSubClient README.md:

The maximum message size, including header, is 128 bytes by default. This is configurable via MQTT_MAX_PACKET_SIZE in PubSubClient.h.

Can you please refer to its location ?

The location of the file, or the location within the file?

sorry- location of the file

It's wherever you installed it to.

Is it part of pubsub library ?

If it's the same library I know of, yes.

what is valid value ?

Anything that will fit into available memory really. Work out how big you will need.


text:
Use MQTT to update internal clock
I write code to upload to ESP8266. I wish to use time stamp in order to log events. I found an NTP sketch, I can work with ( since it has a wifi connection ), but I wish to keep my code as simple as possible.
So I'm thinking to use my MQTT server to send time updates from time to time ( have a certain topic for that ), and in between updates, use millis() .
Since I'm new here, I want to know from experienced programmer if it makes sense ?
I would love to hear pros and cons ( before I start coding ).
Any help will be appreciated,
Guy

How important is it to you that the time is accurate?  NTP will do a more reliable job than getting the time via MQTT. NTP is designed to compensate for the time it takes to get an answer from the NTP server and to deal with clock drift.  With MQTT you won't be sure how long it's been since the MQTT server posted the time - which may be fine for your application, if you just need a timestamp that's roughly accurate.

@JohnRomkey -thank you for you answer. As I said, it is for a time stamp, meaning few minutes a day (say 2 ), will be acceptable. I'm sure that you are 100% correct but I wish to keep my code as lite as possible

Use the Time library a.k.a. TimeLib.h. It will keep time between calls to your source of time, if it is your MQTT call or NTP server.
In your code you will use the Time library to get time and the source of the current time is independent from the rest of the code.
The TimeLib has a function setTime to set the current time and then it keeps the time using millis(). You can update the time by calling setTime again. The timestamp value for setTime is 'Unix Epoch' - number of seconds from "1970-01-01 00:00:00".
If you decide to add NTP to your project, you can use NtpClientLib. It sets the time to TimeLib with one simple line of code in setup(). Example NTP.begin("pool.ntp.org", 1, false);.

down-voter, what is wrong?

Maybe he downvoted because the question was aimed at pros and cons of getting the time through MQTT in relation to other methods of time sync instead of how to manage this time in the program.

I was thinking the same- why the down vote ? I did asked for some guidance of assistance. I UP VOTE. thank you ( i'll be happy for more explain/ code if you have )

@Juraj - thank you, i'll try using NTP as well. GUY

@Juraj - there is another function to set time interval- should I need to use it? what is the default time if I don't define?

the time starts from 1970-01-01


text:
Unable to receive data when using multiple SoftSerial on Arduino Nano
I am trying to use several (four) software-based serial ports to talk to different peripheral hardware. However, I am unable to receive data through the SoftSerial when using more than one software serial port.
I tested each pair of pins be defining it to the first port. All pairs are working as desired. In addition, I am only interested in bridging/piping from a software serial port to the hardware serial (for debugging reasons).
My code is as follows:
#include <stdint.h>
#include <SoftwareSerial.h>

#define SOFT_SERIAL_A_RX        5
#define SOFT_SERIAL_A_TX        6
#define SOFT_SERIAL_B_RX        7
#define SOFT_SERIAL_B_TX        8
#define SOFT_SERIAL_C_RX        9
#define SOFT_SERIAL_C_TX        10
#define SOFT_SERIAL_D_RX        11
#define SOFT_SERIAL_D_TX        12

#define SERIAL_BAUD_RATE        9600

SoftwareSerial softwareSerials[] = {
    SoftwareSerial(SOFT_SERIAL_A_RX, SOFT_SERIAL_A_TX),
    // Unable to receive data on first software serial when un-commenting following lines.
    // All pins are working when declaring each pair for first software serial (tested pins by doing this)
    // SoftwareSerial(SOFT_SERIAL_B_RX, SOFT_SERIAL_B_TX),
    // SoftwareSerial(SOFT_SERIAL_C_RX, SOFT_SERIAL_C_TX),
    // SoftwareSerial(SOFT_SERIAL_D_RX, SOFT_SERIAL_D_TX)
};
const uint8_t numberSoftwareSerials = sizeof(softwareSerials)/sizeof(*softwareSerials);

void initHardwareSerial()
{
  Serial.begin(SERIAL_BAUD_RATE);
}

void initSoftwareSerials()
{
    for(uint8_t i=0; i<numberSoftwareSerials; i++) {
        softwareSerials[i].begin(SERIAL_BAUD_RATE);
    }
}

void setup()
{
    initHardwareSerial();
    initSoftwareSerials();
}

void loop()
{
  // Only one software serial can be used (receive/transmit) at once.
  // So just using a single software serial port (first element from array)
  if (softwareSerials[0].available()) {
    Serial.write(softwareSerials[0].read());
  }
  if (Serial.available()) {
    softwareSerials[0].write(Serial.read());
  }

}

How can I narrow down the issue of being unable to receive when defining several serial ports? If there is no suitable solution I might switch to an Arduino Mega with its four hardware ports (would need only one additional software serial in that case), but an Arduino Nano is strongly preferred due to smaller footprint.

You cannot receive on more than one SoftwareSerial port. It's sad, but that's the way it is.
You can manually select which port you are listening to at any time with the softwareSerials[x].listen() function, but only one can ever listen at a time.
SoftwareSerial is a fudge at best and should only be used for one port and even then only if you really have to.

Thanks for this hint. After some more searching around the Internet in the meantime, I finally found a link to the docs where '.listen()' is used: https://www.arduino.cc/en/Tutorial/TwoPortReceive


text:
Arduino UNO LED half brightness when connected to digital GND but not analog
I am using an Arduino UNO. When lighting an LED with the switch button on a joystick module, I have two situations:

If the LED's cathode is connected to GND on the digital pin side of the Uno, the LED only dimly lights up on button press.
If the LED's cathode is connected to GND on the analog pin side of the Uno, the LED fully lights up on button press.

The device is receiving power from my laptop, and I am writing a digital HIGH/LOW to the LED pin (on press/release).
Is this a fault in my board, or is there a (perhaps more enlightening) reason why this is happening?

Despite double checking my cables before asking this question, it seems I had connected the LED's cathode to digital pin 13, and not GND. The issue is now resolved. Takeaway: Triple check your cables :)


text:
How is it possible to access the CPU registers using memory addresses?
The following is taken from ATmega328-328P Data sheet.

According to this, I can access all the 32 registers in CPU using memory addresses. For example:
 unsigned char *register = 0x0;

will access the first register. Is this true? if so, then is this also possible to do on regular CPUs (like my laptop), since I thought you can only use a pointer to access memory and not CPU registers.
Is the register mapped into the SRAM in this case?

I figured it out, they are mapped. explained here: https://stackoverflow.com/questions/3022046/is-it-possible-to-access-32-bit-registers-in-c

Microcontrollers tend to be simple compared to processors like you would find in your laptop. Most operating system make use of the higher security features that can prevent user programs from straying where they shouldn't be.
As far as registers being memory mapped, it really depends on the particular architecture, each CPU. They are not all the same.

Is the register mapped into the SRAM in this case?

The data address space maps the 32 general-purpose registers, all the I/O registers (including those also accessible through the I/O address space), and the RAM


text:
Could I Connect many Arduino Nano boards together?
I want to know if I could connect many Arduino Nano  boards together (Example : 10 boards ) , Also i want to know  if there is any problem in Communication between them  using I2C , could this affects processing speed on every board ,  and  if there's going to be any kind of delay when communicating?

It is a good (but broad) question. Can you add more information to your question? Do you really need arduino nano boards? Other boards have a extra serial port to be able to connect all boards with serial ports. How far is the distance? What kind of cable do you want to use? Is is okay to use wireless communication? Why do you worry about processing speed and delay? What else do you want to run on the arduino board? The i2c bus might work for short distances, but requires good programming skills. Using the i2c does not work very well with libraries that turn off the interrupts.

I want to know if I could connect many Arduino Nano boards together...

Yes, you can read about it here at arduino.cc. Where is says: "...it can be helpful to set up two (or more!) Arduino ... boards to share information with each other..."

... i want to know if there is any problem in Communication between
  them using I2C ...

This feature, according to the above link, is expected to work.  (Can you explain the type of problems you are avoiding?)

...could [i2c communication] affect processing speed on every board ...

Most likely it will.  Most Arduino platforms do not run operating systems.  So your program is all that is running.  If your program is busy sampling sensors, it will be difficult (not impossible) to concurrently handle i2c communications.

I am going to connect 4 DC motors  encoders and some other sensors but the encoders must be on interrupt pins for best performance , I tried to connect them on an Arduino Mega but it has only 3 pairs of interrupt pins and I need 4 pairs , so the problem I am trying to Avoid is : The interruption of every encoder to the other one .

Consider what your objective is.  Can you process the interrupt on an individual embedded processor in such a way as to contain the burden of timing to within that processor?  Sometimes the answer is clearer when you refactor the question instead of looking for hard to find hardware.

Yes it certainly is possible. And can work well if done properly. The concern that I have is when longer wiring lengths are used. I2C is not intended for extended distributions. And if that were the plan then I STRONGLY advise using proper I2C buffer chips designed for that purpose.
The more devices, the more wire, all adds to the capacitance on the lines. Because I2C uses pull up resistors to produce a high the added capacitance limits either the length of wire that can be used, or the transmission frequency. I have used I2C buffers in may products and it is very useful when extended length is required. I use both I2C buffers, and also I2C isolated buffers. The company I work for manufactures distributed control electronics. I am one of the hardware designers. I have been using I2C like this for about 15 years.
For now have a look at this web page.  http://www.techbitar.com/how-to-network-many-arduinos-with-sensors-using-i2c.html
I'm sure it will spur some questions. It makes things simpler if there is only one master controlling the communications bus. Multimast is possible but can have more conflicts and you then need to deal with that issue. Best not to go there.
I2C is not a very robust protocol but still can be usable between processors if handled carefully. Keep it simple.


text:
Waveshare 1.54 inch ePaper display requires 5Vs from Arduino Uno
I have an Arduino Uno and I would like to attach a Waveshare 1.54“ display (red, black & white) to it.
All the specs tell me that it consumes 3.3 V which I have readily available on the Arduino Uno.
I could not get the display to work until I attached the Power pin to 5V instead of 3.3V.
I did try this with two different ePaper displays and the situation was the same.
I also tried to power the display with a Raspberry Pi‘s 3.3V (with the GNDs connected). But this did not work either.
So I am wondering what I am missing here, is it simply a power issue and my Arduino can‘t deliver the necessary current?

The answer lies in the FAQ for that display:

Why the e-Paper cant work with Arduino?
Answer:
The I/O level of Arduino is 5V, and the e-Paper should be driven with 3V3. If your Arduino cant drive the e-Paper successfully, please try to convert the level to 3.3V
You can also try to connect the Vcc pin to the 5V of Arduino to see whether the e-Paper works, but we recommend you not to use 5V for a long time.

So while you can run it from 5V, you really shouldn't, since you run the risk of breaking it.
Instead, you should employ proper logic level shifting to reduce the Arduino's outgoing signals to 3.3V and, more importantly, boost the incoming signals from the display to 5V.

https://www.instructables.com/id/A-Quick-Guide-on-Logic-Level-Shifting/

Thanks for your Reply. I was only thinking VCC but not the output levels of the Arduino. So I need a logic level shifter or a voltage divider for each output of the Arduino

Yep.  The Arduino expects minimum 3.3V on an input to recognise a HIGH.  If you're running the display at 3.3V chances are the signals coming from the display will be slightly under that, and will want to be boosted slightly for the Arduino to recognise them. Running at 5V the signals will be proportionally higher and will register, but you can damage the display.  For signals from the Arduino to the display they will be above the upper limit allowed, and could risk damaging the display, so they need reducing to around 3.3V.

Update to those who have bought the display module recently (doesn't apply to bare displays). There has been a change and the new modules support 5V. From the display's user manual:

For raw panel, its working voltage is 3.3V, note that when you designed you own driver board, level convert circuit is required if
  the working voltage of your board is 5V. Module/HAT version can
  support 5V voltage if the Module you buy is the new version which has
  been integrated convert circuit.


text:
"undefined reference to SD" with SdFat library
is there any way to rename a file in sd card without using SdFat? Thank you
im getting error when inclung the
    #include <SPI.h>
    //#include <SD.h>
    #include <SdFat.h>
    extern SdFat SD;

the error msg was "Error compiling for board Arduino/Genuino Uno.
"
Local\Temp\ccZn9IeW.ltrans2.ltrans.o: In function FatVolume::init(unsigned char) [clone .constprop.18]': \Arduino\libraries\SdFat\src/FatLib/FatVolume.cpp:439: undefined reference to SD' \Arduino\libraries\SdFat\src/FatLib/FatVolume.cpp:440: undefined reference to `SD'

Looks like you did not add this library the correct way. Please give more information: your IDE, your board, your settings and folder structure of your SdFat library.

The standard arduino sd library can not rename a file. The sdfat library can rename a file. If you want to rename a file, then you have to use the sdfat library.

Remove the extern keyword from SdFat SD; because it tels the compiler that the variable is defined elsewhere and it is not and the linker then can't find it.


text:
Hex output although I always define integer
Code below is to read 4 thermometers and use values to turn on or off the heaters (I'm stuck at reading).
I'm reading and displaying temperature very well, but it comes to the problem, where I want to set the limit of heating, a value of 37 degrees. It comes to the problem, when I want to read the value of "tempa", but the Arduino doesn't respond properly: it somehow reads the value as char or I get the output in hex instead of integer (although I never declared a character in whole program).
It can be seen in last 2 lines before "CHANNEL_2".
Lines are:
lcd.setCursor(10, 0);    //termometer
lcd.write(tempa);    //termometer

absoluta, absolutb, absolutc and absolutd are variables, which are technically values of temperature in Kelvin.
tempa, temb, tempc and tempd are variables, the temperature in celsius.
#include <LiquidCrystal.h>
#define  LM335_pin  0                          // LM335 output pin is connected to Arduino A0 pin
#define  LM335_pio  1                          // LM335 output pin is connected to Arduino A0 pin
#define  LM335_pip  2                          // LM335 output pin is connected to Arduino A0 pin
#define  LM335_pir  3                          // LM335 output pin is connected to Arduino A0 pin

const int rs = 7, en = 8, d4 = 5, d5 = 4, d6 = 3, d7 = 2; // LCD module connections (RS, E, D4, D5, D6, D7)
LiquidCrystal lcd(rs, en, d4, d5, d6, d7);

  //-----------------------HEATERS----------------------------------------
//int grelea = 11;  //heater_1
//int greleb = 10;  //heater_2
//int grelec = 9;   //heater_3

void setup() {
  lcd.begin(20, 4);

//  pinMode(grelea, OUTPUT);
//  pinMode(greleb, OUTPUT);
//  pinMode(grelec, OUTPUT);

}
int  absoluta, tempa; //sensor_1
int  absolutb, tempb; //sensor_2
int  absolutc, tempc; //sensor_3
int  absolutd, tempd; //sensor_4

void loop() {

  delay(1000);

  //-----------------------CHANNEL_1----------------------------------------
  absoluta = analogRead(LM335_pin) * 0.489;
  tempa = absoluta - 273;

  lcd.setCursor(0, 0);    //termometer

  lcd.setCursor(0, 0);    //termometer
  lcd.write("Temp1=");    //termometer

  lcd.setCursor(8, 0);    //termometer
  lcd.write((tempa / 10)% 10  + 48);    //termometer

  lcd.setCursor(9, 0);    //termometer
  lcd.write(tempa % 10  + 48);    //termometer

  lcd.setCursor(10, 0);    //termometer
  lcd.write(char(223));    //termometer

  lcd.setCursor(11, 0);    //termometer
  lcd.write("C");    //termometer

  lcd.setCursor(15, 0);    //termometer
  lcd.write(tempa);    //termometer

  //---------------------------------------------------------------

  //-----------------------CHANNEL_2----------------------------------------
  absolutb = analogRead(LM335_pio) * 0.489;
  tempb = absolutb - 273;

  lcd.setCursor(0, 1);    //termometer
  lcd.write("Temp2=");    //termometer

  lcd.setCursor(8, 1);    //termometer
  lcd.write((tempb / 10) % 10  + 48);    //termometer

  lcd.setCursor(9, 1);    //termometer
  lcd.write(tempb % 10  + 48);    //termometer

  lcd.setCursor(10, 1);    //termometer
  lcd.write(char(223));    //termometer

  lcd.setCursor(11, 1);    //termometer
  lcd.write("C");    //termometer
  //---------------------------------------------------------------

  //-----------------------CHANNEL_3----------------------------------------
  absolutc = analogRead(LM335_pip) * 0.489;
  tempc = absolutc - 273;

  lcd.setCursor(0, 2);    //termometer
  lcd.write("Temp3=");    //termometer

  lcd.setCursor(8, 2);    //termometer
  lcd.write((tempc / 10) % 10  + 48);    //termometer

  lcd.setCursor(9, 2);    //termometer
  lcd.write(tempc % 10  + 48);    //termometer

  lcd.setCursor(10, 2);    //termometer
  lcd.write(char(223));    //termometer

  lcd.setCursor(11, 2);    //termometer
  lcd.write("C");    //termometer
  //---------------------------------------------------------------

  //-----------------------CHANNEL_4----------------------------------------
  absolutd = analogRead(LM335_pir) * 0.489;
  tempd = absolutd - 273;

  lcd.setCursor(0, 3);    //termometer
  lcd.write("Temp4=");    //termometer

  lcd.setCursor(8, 3);    //termometer
  lcd.write((tempd / 10) % 10  + 48);    //termometer

  lcd.setCursor(9, 3);    //termometer
  lcd.write(tempd % 10  + 48);    //termometer

  lcd.setCursor(10, 3);    //termometer
  lcd.write(char(223));    //termometer

  lcd.setCursor(11, 3);    //termometer
  lcd.write("C");    //termometer
  //---------------------------------------------------------------
}

try lcd.print(tempa);

btw: it is not hex, only your calculated ascii values run out of digits section of ascii codes

lcd.write() will write one byte to the LCD. It makes no attempt to try to interpret the data type of the input parameter. You can think of it like sending "raw data" to the LCD.
lcd.print() can be called with many types as input and will interpret that the user wishes to print a human-readable expression of the data. Also, it can print more than one byte.
As an example, the char variable with content 'A' is represented in RAM by the byte with value 65 (the ASCII code for 'A'). If you call lcd.print('A'), it will see that 'A' is a char and will send whatever raw data to the LCD to get an "A" on the screen. It just so happens that sending a raw byte 65 will accomplish this, but that is a coincidence; the LCD driver understands ASCII for getting characters to print on the screen.
If you call lcd.write(125), then the actual byte 125 (in binary, 01111101) is sent to the LCD. If you wanted to actually print the 3-digit number 125, lcd.print(125) would end up sending 3 bytes to the LCD: The ASCII values for '1', '2', and '5' (which are 49, 50, and 53). The print() function takes care of this interpretation for you.

she has v / 10 + 48 in code. I don"t think she needs to explain binary and ascii


text:
Hibernate Arduino for 12hrs with rtc1302 module
ok, Good morning, guys, with a data acquisition project, in this, I get data every 12 hours, even if it's only 12 hours, the arduino gets connected directly, and it's being powered by a 9v battery, for longer life of this battery, to try to hibernate the arduino with real time, using the real time clock 1302, you could help me to make a code for this clock, for I have never used it before! thank you

Arduino SE is only in English. Would you understand an answer in English?

Yes, I understand perfectly.

the translate the question to English with Google translate

ok,
Good morning, guys, with a data acquisition project, in this, I get data every 12 hours, even if it's only 12 hours, the arduino gets connected directly, and it's being powered by a 9v battery, for longer life of this battery, to try to hibernate the arduino with real time, using the real time clock 1302, you could help me to make a code for this crock, for I have never used it before! thank you

When you have never used the ds1302, then keep it that way. Don't use it. The ds3231 is a lot better. Which arduino board do you use? For the ds1302, you can start here: https://playground.arduino.cc/Main/DS1302RTC Setting the arduino uno in sleep mode might not help, there are other components that use current. For sleep mode, you can start here: https://www.gammon.com.au/power

I have a sleep_pwr_down ready, I was just thinking of adding a few lines of code to configure the ds1302 time, and to do a conditional, to wake up when it's 20 hours and sleep when it's 8 hours, without much complication, it's possible to do that way?

That is possible. You can even wake up every minute to check the time. Being active for 1% of the time requires little power. If you want to power an arduino uno with a 9v battery, then the sleep mode for the atmega chip has little effect. Did you take a good look at https://www.gammon.com.au/power ? everything you need to know is there. Which arduino board do you use.

For really low-power consider using a MOS transistor, skip the "sleep-mode" handling and power off the Arduino "completely". https://sites.google.com/site/wayneholder/low-power-techniques-for-arduino

Hello, sorry for missing out, many jobs in college.
so I'll send you a sleep code, you could take a look and explain to me how to put the conditionals so he wakes up at 8 o'clock to work and when he gets 8 o'clock he goes back to sleep! would help me a lot! thanks for listening.

You need 3 pieces of code and one replacement:
1) Ditch ds1302 and get yourself an RTC with an interrupt pin (like DS3231 which Jot suggests). It will make your life easier.
2) Setup your RTC to fire an interrupt every 12 hours.
3) Since you have successfully implemented a sleep mode, try to wake your Arduino up using a hardware interrupt. See Nick Gammon's guide for interrupts, and read carefully about waking your micro with an external interrupt. You can prototype it using a pushbutton, which will either connect your interrupt pin to GND or Vcc. Use an appropriate resistor as well. This guide has good information for starters.
To sum up: you'll have your Arduino sleep at all times and your RTC set to fire a hardware interrupt. When fired, the interrupt wakes Arduino, and the interrupt code will handle your measurements.


text:
ESP-01S Relay V1.0 connection with Arduino
I am new to Arduino
Let me ask you about IOT(internet of things).
I want to connect ESP-01S Relay v1.0
Where does the NC port goes on Arduino? Is it TX or RX?
Also, where does the NO goes on Arduino? Is it TX or RX?

Could you please edit and improve your question:  See How to ask and How to ask a good question for Arduino Stack Exchange

The 2 connections you refer to (NC and NO) are connections to the relay switch.

NO stands for normally open
NC stands for normally closed
C or COM stands for common

When the relay is unenergised, the common is connected to the NC terminal. When power is applied to the relay, the coil energises and switches, so now common is connected to the NO terminal.
From my reading of the usage document located on the GitHub repository, you are supposed to program the ESP module before plugging it into the relay board. There are no terminals broken out for you to connect to the Tx and Rx on the relay board.
However, the following board from AUS-eParts has a header to connect a 3V TTL cable. This can be used to program the ESP module.

the RX/TX header is good, but you need io 0 LOW at boot to put the esp8266 into flashing mode

Common, Normally Connected and Normally Open are terminals switched by the relay. There you connect what should be switched. Common is input and the two other terminals are connected, one if the coil is powered and the other when the coils is without power. The relay is controlled by the esp-01. No Arduino should be connected to this.
Disconnect the esp-01 from the relay board and use an 3.3 V USB-to-TTL Serial adapter to program the esp-01 with Arduino IDE
Add Over The Air support to your esp8266 sketch with ArduinoOTA library and then you can upload new versions of your sketch over WiFi. To debug the sketch with print use Telnet server or my TelnetStream library.

How to communicate with server? I have no RX or TX port

what server? with network server you should communicate over WiFi

I mean how i can access server via wifi? This module doesnt have RX and TX pins. Only NC, COM and NO

as I can see on the picture in the question, there is an esp-01 connected to the 2x3 header

esp is connected but this relay what i got, got no RX and TX pins

the esp-01 has RX TX. you must disconnect it from the relay to flash a sketch to it


text:
Midi controlled LED by USB
I am trying to create something that will allow me to control an individually adressable LED strip using an electric piano using its midi output.
Some things to note:

The piano can output midi either via USB or via standard midi connectors.
I have an Arduino Uno and an Arduino Mega available
I'm using a WS2812B strip with +ve, ground and data cables

I don't believe there's a way to read midi from my piano direct to the arduinos without reflashing the USB controller. For this reason I'm connecting via USB to my mac.  On my mac I've written a program which reads the midi input and can understand it and send it on to somewhere else.
The arduino for the light strip I think I can program pretty easily but I have some questions:

If I need to power the LED strip, should I be powering it from the arduino power or giving it its own power source with common ground?
Is splitting it up into midi -> computer, computer -> arduino, arduino -> LED strip sensible? If not how should I be going about it?
Am I making life difficult by going the USB route for Midi or should I switch to midi connectors and connect direct to the arduino somehow?

the Internet is full of Arduino and MIDI. you can connect it directly. the MIDI protocol is very simple. https://www.arduino.cc/en/Tutorial/Midi

@Juraj you'd suggest going the route of using 5 pole MIDI cables then rather than USB?

of course. you glue the LED strip to a Jan Hammer style piano and where do you put then the MacBook?

@Juraj Little bit confused.  As I said in the question I'm currently connecting the piano via USB to the macbook and using software I've written on there to read the MIDI data.  Just trying to figure out the best way to connect it all up given I have very little knowledge of electronics.  I'm normally just a software developer.

but you know the Keytar? if you programmed the midi for computer, it will be simpler to write it for Arduino

I did some time ago something very similar, except not using USB, and on an STM32 (Arduino compatible STM32F103C8T6), but the principle is similar.
Regarding another MIDI test I did on an Arduino, I used the 47 Effects library and for the WS2813 (software-compatible with WS2812B) the FastLed library.
One MIDI port is easy to use (supported by 47 Effects), which uses the single UART of the Arduino UNO.
You have to write a small program to convert the MIDI notes to WS2812 LED data, which is not much more than filling in a structure. Mapping 61 or 88 notes to 30, 60 or 144 LED notes is not so easy, just clip the notes, or use some mapping factor.
You cannot use the Arduino for powering the LED strip, use a separate adapter for that. Only the line signal comes from the Arduino, and connect GNDs together.
The Arduino should be fast enough to both read MIDI, translate it to LED data (unless you make some very time consuming algorithm) and send the data.


text:
How to set CS pin on Beetle BLE/Bluno Beetle to Adafruit SD Card Breakout - Initialization Failed!
Hi I have a Beetle BLE (https://www.dfrobot.com/wiki/index.php/Bluno_Beetle_SKU:DFR0339) and I am trying to connect an Adafruit MicroSD card breakout board+ (https://www.adafruit.com/product/254) via SPI connections. I am trying the following code, but I am having trouble selecting the CS pin using D4 since the Beetle has no D10. Does anyone know if I am selecting D4 correctly, while keeping pin 10 as an output. I keep getting initialization failed! My setup is on the ICSP 6 pin configuration:
5V --> 5V
MISO --> DO
SCK -->CLK
GND --> GND
MOSI --> DI
D4 --> CS
RST is left out
Here is my code:
#include <SPI.h>

#include <SD.h>

File myFile;

void setup()
{
  Serial.begin(9600);
  Serial.print("Initializing SD card...");
  // On the Ethernet Shield, CS is pin 4. It's set as an output by default.
  // Note that even if it's not used as the CS pin, the hardware SS pin
  // (10 on most Arduino boards, 53 on the Mega) must be left as an output
  // or the SD library functions will not work.
//   pinMode(4, OUTPUT);
   pinMode(10, OUTPUT);
//   digitalWrite(4, HIGH); // Add this line

  if (!SD.begin(4)) {
    Serial.println("initialization failed!");
    return;
  }
  Serial.println("initialization done.");

  // open the file. note that only one file can be open at a time,
  // so you have to close this one before opening another.

  myFile = SD.open("test.txt", FILE_WRITE);

  // if the file opened okay, write to it:
  if (myFile) {
    Serial.print("Writing to test.txt...");
    myFile.println("testing 1, 2, 3.");
  // close the file:
    myFile.close();
    Serial.println("done.");
  } else {
    // if the file didn't open, print an error:
    Serial.println("error opening test.txt");
  }
}

void loop()
{
  // nothing happens after setup
}

Schematic of the Bluno beetle can be found here: https://www.dfrobot.com/product-1259.html The atmega is connected with rx and tx via 4k7 resistor to the bluetooth chip and the bluetooth chip is connected to usb. The spi bus is not used on the module, so there is no problem with other chips. Setting pin 10 as output and use pin 4 as chip select should work.

The correct ICSP was on the right, ICSP1. However, the orientation of those pins were from left to right on the TOP: SCK, 5V, MISO; left to right on the BOTTOM: MOSI, RESET, GND. In the Wiki they had the ICSP labels 1 and 2 reversed, but correct in the text below. https://www.dfrobot.com/wiki/index.php/Bluno_Beetle_SKU:DFR0339
Therefore, there was nothing wrong with the code, only the wiring to the correct pins!

The ICSP header labels on the Wiki page are wrong. In the schematic here the ICSP header has the same pinout as other Arduinos. The legend doesn't match the picture on the Wiki page but is true:

ICSP1: Atmega 328P
ICSP2: CC2540

The ICSP header is the inner one. Is right on the pictures.
At pin 1 on board the corner of the white square around pins is skewed. The pins are from left to right first row Eeset, CLK, MISO, second row Ground, MOSI, 5 V.
pdf schematic for the board

Hi Juraj, thanks for your reply. There are many links on that page link including the one I sent you. Could you please send a direct link to the correct ICSP diagram? Appreciate it.

added to the answer

Juraj and @Jot how does that correspond to the pins on the board in this picture? I'm not sure how to tell: ICSP Pin Pic

one corner is marked. it is pin 1 MISO

Sorry Juraj, I don't see it. Can you be more specific as to the order and orientation?

I edited the answer

Hi @Juraj. I soldered the wires this evening, but I'm still getting "initialization failed".   For the pins, how did you figure out that the diagram on the Wiki page was incorrect to begin with? PS - the same setup works on my Arduino Pro Mini, but I definitely want to get it working on the Beetle for my project.

I connected AVR ICSP header with dupont jumper wires so many times that I know the pinout without a diagram. And an Atmega 328 board can't have a different pinout of ICSP header because the AVR programmer connector would not match.

I'm still getting initialization failed. Any ideas as to what could be the problem? I checked my wires and they're as you said.

it is a question which of the two headers is Atmega. that with 3.3 V is not ICSP. in schema it is JP2. so it is possible that the right header is the right header

I edited the answer. https://github.com/Arduinolibrary/DFRobot_Bluno_Bettle/raw/master/Bluno%20beetle%20V1.0%20layout%20ground.pdf

Yes, I am already connecting to the correct one which is on the left (ICSP2), so that doesn't seem to be the issue here. Would the orientation and order of ICSP2 be the same as your AVR or could they be different?

Maybe the issue is something in the code which I'm not doing?

the right is right. ICSP1. ICSP2 is not ICSP.

Tested with the other pins  on ICSP1. That definitely didn't work as the sketch didn't even enter setup() because "Initializing SD card..." didn't print. Thanks for your continued help.

if the board doesn't boot, reset is connected to ground. or a short is somewhere

Hi Juraj, the correct ICSP was on the right, ICSP1. However, the orientation of those pins were from left to right on the TOP: SCK, 5V, MISO; left to right on the BOTTOM: MOSI, RESET, GND. In the Wiki they had the ICSP labels 1 and 2 reversed, but correct in the text below. https://www.dfrobot.com/wiki/index.php/Bluno_Beetle_SKU:DFR0339

then they should not call it ICSP header, because you cant use an ICSP AVR programmer with it https://www.olimex.com/Products/AVR/Programmers/AVR-ISP-MK2/open-source-hardware

I thought that ICSP is just a protocol and doesn't really have anything to do with a certain AVR programmer.

programmers have a cable with 2x3 connector

lol, I'll verify your findings on my device later, but thanks for this post. Wow, their documentation is not only useless but f'd up on top of it!

This is what I'm seeing with my multitester:

The cc2540 is the SMD chip on the same side as the ICSP pads. The atmega328p is on the opposite side of the PCB


text:
Question regarding Servo including Serial monitor display
I tried to make code following your instruction about mills,
and it looks like this. Unfortunately, it is not working. Is there problem with my code?
Here is my code:

#include <LiquidCrystal.h>
#include<Servo.h>

Servo myservo;  // create servo object to control a servo

// These constants won't change. They're used to give names to the pins used:
const int analogInPin1 = A0;  // Analog input pin that the photosensor is attached to
const int analogInPin2 = A1;  // Analog input pin that the photosensor is attached to
const int analogInPin3 = A2;  // Analog input pin that the photosensor is attached to
const int analogInPin4 = A3;  // Analog input pin that the photosensor is attached to
int sensorValue1;
int sensorValue2;
int sensorValue3;
int sensorValue4;
unsigned long m;

//declare counter as an input
int Chactr =0;
int Disctr =0;

byte state;

const int rs = 12, en = 11, d4 = 5, d5 = 4, d6 = 3, d7 = 2;
LiquidCrystal lcd(rs, en, d4, d5, d6, d7);

void setup() {
  myservo.attach(9);  // attaches the servo on pin 9 to the servo object
  myservo.write(0);  // back to 0 degrees.
  delay(1000); // wait for a second.
  pinMode(13, OUTPUT); // initialize digital pin 13 as an output.
  Serial.begin(9600);  // initialize serial communications at 9600 bps:
  lcd.begin(16,2);

  delay(5000);
}

void loop() {

  // read the analog in value:
  sensorValue1 = analogRead(analogInPin1);
  sensorValue2 = analogRead(analogInPin2);
  sensorValue3 = analogRead(analogInPin3);
  sensorValue4 = analogRead(analogInPin4);

  delay(3000);

  // print the results to the Serial Monitor:
  Serial.print("sensor1 = ");
  Serial.print(sensorValue1);
  Serial.print("\n");

  Serial.print("sensor2 = ");
  Serial.print(sensorValue2);
  Serial.print("\n");

  Serial.print("sensor3 = ");
  Serial.print(sensorValue3);
  Serial.print("\n");

  Serial.print("sensor4 = ");
  Serial.print(sensorValue4);
  Serial.print("\n");

  Serial.print("Led State:  ");
  Serial.println(state);
  Serial.print("\n");

  if (sensorValue1 >=569 && sensorValue2 >=520 && sensorValue3 >=419 && sensorValue4 >=250)
  {
    m=(millis()+60000);
  }

  if(sensorValue1 <=568 && sensorValue2 <=519 &&sensorValue3 <=418 && sensorValue4 <=249)
  {
    m=0;
  }

  if (sensorValue1 >=569 && sensorValue2 >=520 && sensorValue3 >=419 && sensorValue4 >=250 && m==millis())
  {
    state=1;
    delay(5000);
    digitalWrite(13, LOW); // turn the LED off by making the voltage LOW
    delay(5000); // wait for a second

    myservo.attach (9);
    myservo.write(30);
    delay(3000);
    myservo.write(0);
    delay(3000);

    myservo.detach ();
    delay (1000);

    Disctr = Disctr + 1;

    delay(900);

    Serial.print("Battery Full: Discharge ON");
    Serial.print("\n");
  }
  else if (sensorValue1 ==0 && sensorValue2 ==0 && sensorValue3 ==0 && sensorValue4 ==0 )
  {
    m=(millis()+60000);
  }

  if(sensorValue1 >=1 && sensorValue2 >=1 && sensorValue3 >=1 && sensorValue4 >=1)
  {
    m=0;
  }

  if(sensorValue1 ==0 && sensorValue2 ==0 && sensorValue3 ==0 && sensorValue4  ==0 && m==millis())
  {
    state=0;
    delay(5000);
    digitalWrite(13, HIGH ); // turn the LED On by making the voltage high
    delay(5000); // wait for a second

    Chactr = Chactr + 1;
    delay(900);

    Serial.print("Battery Empty: Charging ON");
    Serial.print("\n");
  }
  {
    lcd.setCursor(0,0);
    lcd.print("Charge Cycle: ");

    lcd.setCursor(13,0);
    lcd.print(Chactr);

    lcd.setCursor(0,1);
    lcd.print("Discha Cycle: ");

    lcd.setCursor(13,1);
    lcd.print(Disctr);

    delay(1000);
  }
}

What exactly is your problem with your sketch? What code have you written until now? How does your circuit look like (schematic)? Please give us more information. You can edit your question for that.

The point of using millis is to get rid of all of the delay calls.  You can't leave any of them.  While those delay calls are running your millis code isn't and will still miss doing what you want it to do.

So what you want to do is be able to activate the servo when 4 green bars appear over the course of one minute correct?
I think you would need to create three if statements and one new variable. The first if statement will be, if it detects four green bar, then m=(millis() + 60000). Then you will need to nest another if statement in here to say if it detects ONLY three bar, then m = 0.
Your third if the statement is if it detects the four green bars AND m == millis() then the servo will activate.
This is how I would do it, but I am not very experienced. I'm pretty sure others will have a cleaner and simpler code but this should work.

Thank you for the help.But one more question. Even there are only three bars, the LED sensor ckt still senses the 4th bar because the 4th bar is blinking and the servo will activate. The LED sensor ckt shoud ignore the blinking bars of the battery in order for the servo not to move. The servo should activate once the 4bars appear steadily and no more blinking.any idea?Thank you.

I understand that even with only three bars, the 4th one will blink. In terms of the logic of how this code will work it will be like this:
Once the fourth bar appears for less than a second, m = miillis() + 60000. Then it will disappear and only three bars will appear. This will then set m = 0 and the process will repeat UNTIL the fourth bar stays on. When the fourth bar stays on,  then m will not equal 0 anymore and m will be millis() + 600000.
As milis() continue to increase for up to a minute (at which m == millis()), then the servo will activate.

You've got a bug in this answer code if it runs past rollover.  Always handle millis by using subtraction to see how long it has been.  Never use addition to try to predict the time in the future.  Save the old timestamp and compare to that.


text:
Using two sensors with delay concurrently
I want to use an ultra-sonic sensor and the led concurrently. I want the led to blink every 0.2 seconds and the ultra-sonic to measure distance without regard to the blinking.
The problem is I have the following code for blinking:

digitalWrite(13, HIGH);
delay(1000);
digitalWrite(13, LOW);
delay(200);

which makes the ultra-sonic sensor to be delayed as well, but I want it to keep measuring distance.
Any tips?

look up blink without delay. Which will tell you how to do things concurrently.

The NewPing library does not use pulseIn. With the blink-without-delay ( https://www.arduino.cc/en/Tutorial/BlinkWithoutDelay ) for the led and the NewPing (it is in the library manager) for the ultra-sonic sensor, you can do many other things as well, but don't use delay in the sketch anymore.

There is a non-blocking library that works similar to delay() Virtual Delay. This sketch turns your Uno's built-in LED ON for 1 second, then OFF for 200ms, repeatedly.
#include <Arduino.h>
#include "avdweb_VirtualDelay.h"

VirtualDelay delay1, delay2;

void setup(){

  pinMode(LED_BUILTIN, OUTPUT);
  digitalWrite(LED_BUILTIN, LOW);

}

void loop(){

  // This sequence has a deadlock.
  if(delay1.elapsed()){
    digitalWrite(LED_BUILTIN, LOW);
    delay2.start(200);
  }

  if(delay2.elapsed()){
    digitalWrite(LED_BUILTIN, HIGH);
    delay1.start(1000);
  }

  // This breaks the deadlock. You can start with any
  // delay object you want e.g. delay2.start(0);
  DO_ONCE(delay1.start(0));

  // Your code here.

}

The library's author has an excellent tutorial on their website: avdweb Virtual Delay timer for Arduino.

You could try to use millis(). It is a timer that measures how long your program has been running. With some math, you could use millis to let your LED blink without delaying the ultra sonic sensor.


text:
Using MQTT to send time stamp - to Arduino
In previous question in this forum - I asked about updating clock on an ESP8266, using MQTT broker to send a time stamp on demand, in following manner:
1) ESP8266 sends a publish containing the payload :"sync",
2) broker answers in string format ( this part is python )
def on_message(self, client, obj, msg):
    self.arrived_msg = msg.payload.decode()
    if self.arrived_msg == "sync":
        a = datetime.datetime.now()
        b = "%d,%d,%d,%d,%d,%d,%d" % (a.year, a.month, a.day, a.hour, a.minute, a.second, a.microsecond) .  <------ here a string time format is created
        self.client.publish(topic=self.topics[0], payload=b, qos=self.topic_qos)

3) on a terminal (MAC OS), subscribed to relevant topic- cant see publish results. which are OK:
sync                           <----- ESP sends request
2018,9,18,12,44,18,903242      <----- string answer from broker

4) BUT when Arduino code get this time stamp:
void callback(char* topic, byte* payload, unsigned int length) {
        char incoming_msg[50];
        // ledBlink(30, 5);
        Serial.print("Message arrived [");
        Serial.print(topic);
        Serial.print("] ");
        for (int i = 0; i < length; i++) {
                Serial.print((char)payload[i]);  <----- print #1
                incoming_msg[i] = (char)payload[i];  <----- generate incoming msg
        }
        Serial.println("");

        if (strcmp(topic,clockTopic)==0) {       <------- detect relvant topic for clock sync
                Serial.print(incoming_msg);  <------ Print #2
        }

5) I get this result on serial monitor :
Message arrived [HomePi/Dvir/Clock] 2018,9,18,13,48,5,230009 <---- here time stamp is OK , Print #1
2018,9,18,13,48,5,230009$��?O: @ . <----- Print #2

EDIT1:
6) I tried adding a null termination in time stamp, but it just added \0 to time stamp
Appreciate any help
Guy

You forgot to set the terminating zero of the c-ctring incoming_msg.
add incoming_msg[length] = 0;

please see my comment in Majenko's answer

incoming_msg[length] = 0;

got it the first time :)

OK- it works. Can you please explain why last char does not regarded as a plain 0 ? and regarded as \0 ?

the 0 is valid only in memory as a terminator for the c-string. it is not valid for transport over a network. you get the payload bytes and the length. you convert the payload to a string of length length so you must set the terminating zero at the right position of the char array

In C a string is "null terminated".  That means that the very last character of every string must be character 0 (or NULL).
You need to ensure that you add that NULL character to the end of your incoming_msg string to terminate it, or force the entire string to be cleared to NULLs before you populate it.
The simplest way is to zero the string:
bzero(incoming_string, 50);

Or you can force a 0 to be appended after each byte is added:
incoming_msg[i] = (char)payload[i];
incoming_msg[i+1] = 0;

Or just add one at the end:
incoming_msg[length] = 0;

There's many ways of doing it - as long as you get that NULL in there somehow.

thank you for your answer, as a matter of fct I tried to send time stamp with null termination ( but with no luck ), I did like : ('%d,%d,%d,%d,%d,%d,%d,%s) which last parameter was '\0'. perhaps I didn;t do it right ? or this is impossible ?

It's not the sending. It's the copying into your internal array. You discard the null.

OK, what is the pupose of adding 0 every loop ( as you wrote ) ?

It's just one of the many ways of ensuring that there is a null after the last character.


text:
How can you have two blinking leds and a fading one
I am trying to make a alarm and I have two blinking leds (red and blue). They work fine but I want two more that fade in and out.
I have a buzzer on it too.
I am very new to programming. By the way, the code below runs with no errors; just does not do what its intended to.
int led = 9;
int brightness = 0;
int fadeAmount = 5;

void setup() {
  pinMode(11,OUTPUT);
   pinMode(12,OUTPUT);
    pinMode(led, OUTPUT);
}

void loop() {
  digitalWrite(11, HIGH);
  delay(200);
  digitalWrite(11, LOW);
  delay(200);

  digitalWrite(12, HIGH);
  delay(200);
  digitalWrite(12, LOW);
  delay(200);

 digitalWrite(led, brightness);

 brightness = brightness + fadeAmount;

if (brightness <= 0 || brightness >= 255) {
  fadeAmount = -fadeAmount;
}
 delay(30);
}

see the BlinkWithoutDelay example in IDE

ive done that i cant find anything wrong with my code

your code has delays

Delay = The execution of the program STOP during the delay time! So to continue to execute it is recommended to use 'millis();' as described in the BlinkWithoutDelay!

While there are better ways to do this, as pointed out by other posters, for what you're trying to learn right now, your program (almost!) works just fine. You'll need the more advanced techniques as you progress to more complex programs. But for now, I made a couple of edits to your program to get you going:

The most important one was to use analogWrite() for the PWM LED (LED 9). That makes it fade in and out instead of turn on and off (with a long period).
I turned one LED on and one off at the same time, getting rid of the dark periods and 400ms of combined delay.
I doubled the fadeAmount to fade in and out a little faster; it wasn't very visible with an increment of 5.

Here it is with those changes:
int led = 9;
int brightness = 0;
int fadeAmount = 10;

void setup() {
  pinMode(11,OUTPUT);
   pinMode(12,OUTPUT);
    pinMode(led, OUTPUT);
}

void loop() {
  digitalWrite(11, HIGH);
  digitalWrite(12, LOW);
  delay(200);
  digitalWrite(11, LOW);
  digitalWrite(12, HIGH);
  delay(200);

 analogWrite(led, brightness);

 brightness = brightness + fadeAmount;

if (brightness <= 0 || brightness >= 255) {
  fadeAmount = -fadeAmount;
}
 delay(30);

}
Update:

what if i wanted to add a a second led

I'm assuming you mean a fading LED, that it's pretty clear where you'd a blinking one?
Blinking in-phase is easy - write the same brightness to both. To fade them out of phase, you'll need a second brightness-variable (and possibly a second fade-amount), and an increment/decrement and limit test for each LED.
But note how your code starts getting more complex as you add components and try to manage them in a single loop, with delay()s? That's when you'll want to try the Blink Without Delay example, and compare adding new LEDs that way, to adding new LEDs to your current program.

so if i just delete my old program and copy this is in theory it should work or just change the other values

It did, on my board. Though, you might want to run my code in a new sketch and save yours to compare the two.

what if i wanted to add a a second led

You have 2 problems:

You are using digitalWrite() with an analog value. digitalWrite() will interpret a value of 0 as LOW and any other value as HIGH. So the LED will mostly be on and only off in the time, when the brightness value becomes zero. You will have to use analogWrite() to get a fading effect.
Currently your fading effect will be very very slow, since the value is only updated once every 830 ms. You should ditch all the delay() calls and instead use the principle, that is shown in the BlinkWithoutDelay example of the Arduino IDE. Think of the blinking as being like baking a pizza. When you want to bake a pizza in your oven, you wouldn't want to sit in front of the oven, staring at the pizza and waiting for it to be ready. This is basically, what you are doing with LED blinking in your sketch. With the pizza you would look at the clock, when you put the pizza in. Then you would go away doing other things and regularly check the clock for how much time has gone by. And then, when it is finally the time to take the pizza out, you would go back to the oven. There are plenty explanations and tutorials on the web, what exactly is done there.

Here at the Arduino documentation you can find the example with explaining text.


text:
Arduino - Playing WAV files with a buzzer
I have developed an Arduino program that plays a WAV file from the SD card using a speaker.
This is the circuit schematic

The sketch I'm using is based on TMRpcm library and PWM output
#include <TMRpcm.h>
#include <SD.h>
#include <SPI.h>
int sdpin=10;
TMRpcm tmrpcm;

void setup()
{
    Serial.begin(9600);
    pinMode(sdpin, OUTPUT);
    tmrpcm.speakerPin=9;
    tmrpcm.setVolume(3);
    SD.begin();
}

void loop()
{
    if(Serial.available()>0)
    {
        String data=Serial.readString();
        if(data=="pause")
        {
            if(tmrpcm.isPlaying()==1)
            {
                tmrpcm.pause();
            }
        }
        else if(data=="stop")
        {
            if(tmrpcm.isPlaying()==1)
            {
                tmrpcm.stopPlayback();
            }
        }
        else
        {
            String path="/Music/"+data;
            if(tmrpcm.isPlaying()==1)
            {
                tmrpcm.stopPlayback();
            }
            tmrpcm.play(path.c_str());
        }
    }
}

At first I could play the music with the speaker but then it stopped working and because I don't have enough skill to make one myself, I would like to know if I can use a buzzer for that.
I know that buzzers can be used to generate melody using the tone() function but I'm not sure if I can use them to play wav files using PWM output.
Any help will be appreciated.

I don't have enough skill to make one myself ... skill to make what?  .... the speaker stopped working probably because the output pin on the Arduino blew out

you forgot to ask a question

When driving a passive buzzer, you should always have the signal output from the Arduino go to a transistor tied between the ground and the (-) negative side of the buzzer. Also, if you use a regular NPN transistor, you should also have a small resistor between the Arduino and the transistor base.

The transistor is providing two functions; it's potentially amplifying the signal (if the (+) positive side of the buzzer is at a higher voltage than the Arduino) and it's also isolating (partially) that voltage from the Arduino. This helps save pins!
The resistor is to limit the current going through the transistor and helps keep both your Arduino and the transistor healthy. Voltage thrills, current kills and resistors limit current. If you use a MOSFET you want to change this from a low-ohm series resistor to a high-ohm pull-down resistor -- 4.75K or 10K is fine. A MOSFET is much higher impedance than an NPN transistor and should not be left floating.
Additionally, you want to add a diode between the (+) and (-) terminals on the buzzer. This may be the most important part of the circuit! When oscillating, the buzzer (whether magnetic or piezo) acts like an inductor and will accumulate a charge over time. This will be heard as a slowly diminishing volume from the buzzer. This charge will eventually overcome the protection diodes built into the GPIO pin (or any transistor) and destroy it! The diode blocks that charge loop and saves your chips.

There are different kinds of buzzers. The simplest one is just a piezoelectric transducer in a plastic casing. You can drive it directly by an arduino pin since its impedance is high. It will work fairly well for high frequencies, but don't expect any bass from it.
Another type of buzzer is a piezoelectric transducer connected to a simple oscillator circuit that will generate a waveform with a frequency typically between 1 and 4 kHz. This type of buzzer most likely won't work since the signal produced by your Arduino will be used to power the oscillator circuit rather than drive the piezoelectric transducer.
Please note that the pin you used to drive the speaker is possibly no longer operational. The impedance of the speaker was likely low enough to draw more current than what the pin of the microcontroller is rated for which probably caused damage to it. A non-piezoelectric speaker should never be connected to an Arduino without an amplifier in between.


text:
ESP8266 not accessing PHP file
I'm trying to control NodeMCU via Android application and I can control NodeMCU easily but when I added the URL to hit the PHP code to enter data in MYSQL, neither NodeMCU is controllable nor NodeMCU is hitting the PHP code. I'm confused with content type: text/html - I'm not sure where to set this piece. Is there any mistake I'm doing or anything I'm missing?
Following is the ESP8266 code on Arduino IDE:
#include <ESP8266WiFi.h>

const char* ssid = "ssid";
const char* password = "password";
const char* host = "aoatech.ml";

WiFiServer server(3000);
int light1 = 13;
int light2 = 15;
int fan = 12;
int socket = 14;
String what;
int which;
String mac;

void setup() {
  Serial.begin(115200);
  delay(10);
  pinMode(light1, OUTPUT);
  pinMode(light2, OUTPUT);
  pinMode(fan, OUTPUT);
  pinMode(socket, OUTPUT);
  digitalWrite(light1, 0);
  digitalWrite(light2, 0);
  digitalWrite(fan, 0);
  digitalWrite(socket, 0);
  Serial.print("Connecting to: ");
  Serial.print(ssid);
  WiFi.begin(ssid, password);
  Serial.println("Connecting");
  while (WiFi.status() != WL_CONNECTED) {
    delay(500);
    Serial.print(".");
  }
  Serial.println("");
  Serial.println("WiFi connected");
  server.begin();
  Serial.println("Server started");
  Serial.println(WiFi.localIP());
}

void loop() {
  WiFiClient client = server.available();
  if (!client) {
    return;
  }
  Serial.print("Connecting to ");
  Serial.println(host);
  //  const int httpPort = 3000;
  //  if (!client.connect(host, httpPort)) {
  //    Serial.println("Connection failed!");
  //    return;
  //  }
  mac = WiFi.macAddress();
  Serial.println("new client");
  while(!client.available()){
    delay(1);
  }
  String req = client.readStringUntil('\r');
  Serial.println(req);
  client.flush();
  int val;
  if (req.indexOf("/light1/1") != -1){
    val = 1;
    what = "Light_1";
    which = light1;
  }
  else if (req.indexOf("/light1/0") != -1){
    val = 0;
    what = "Light_1";
    which = light1;
  }
  else if (req.indexOf("/light2/1") != -1){
    val = 1;
    what = "Light_2";
    which = light2;
  }
  else if (req.indexOf("/light2/0") != -1){
    val = 0;
    what = "Light_2";
    which = light2;
  }
  else if (req.indexOf("/fan/1") != -1){
    val = 1;
    what = "Fan";
    which = fan;
  }
  else if (req.indexOf("/fan/0") != -1){
    val = 0;
    what = "Fan";
    which = fan;
  }
  else if (req.indexOf("/socket/1") != -1){
    val = 1;
    what = "Socket";
    which = socket;
  }
  else if (req.indexOf("/socket/0") != -1){
    val = 0;
    what = "Socket";
    which = socket;
  }
  else {
    Serial.println("invalid request");
    client.stop();
    return;
  }

  digitalWrite(which, val);

  String url = "http://aoatech.ml/hitthis.php?room=Bed%20Room%201";
  url += "&state=";
  url += val;
  url += "&button=";
  url += what;
  url += "&mac=";
  url += mac;

  Serial.print("Requesting URL: ");
  Serial.println(url);

  client.flush();
  //  client.println("HTTP/1.1 200 OK");
  //  client.println("Content-Type: text/html");
      client.print(String("GET ") + url + " HTTP/1.1\r\n" +
           "Host: " + host + "\r\n" +
           "Connection: close\r\n\r\n");
  unsigned long timeout = millis();
  while (client.available() == 0) {
    if (millis() - timeout > 5000) {
      Serial.println(">>> Client Timeout !");
      client.stop();
      return;
    }
  }
  client.println("");
  client.print(what + " is now: ");

  if(val == 0) {
    client.print("Off");
  } else {
    client.print("On");
  }
  Serial.println("Client disonnected");
}

Don't cross post. You already asked this on SO.

i need urgent answer for this post no one is responding.

Doesn't matter. This isn't the place to get urgent answers.

what does hit the php code mean?

I mean here my esp is not accessing the url so that it is not accessing my php file on server.

Your PHP server has a certain content type it can receive to process your requests from the ESP8266. The two most generic content-types used for php are either application/x-www-form-urlencoded or multipart/form-data. Try to play with those two and see if that solves it for you.

you don't see that the code in question is a mess?

You mixed WiFiServer and client request examples by replacing servers HTTP response text with a HTTP request text. A client object returned by WiFiServer's available function is a counterpart of requesting client (for example web browser).
See WebClient example for a client connecting to some server.


text:
not able to resolve "a function-definition is not allowed here before '{' token "
I, being new to Arduino started off by making a simple lcd watch which also shows the temperature.
Everything was working fine untill this error came up
"a function-definition is not allowed here before '{' token
"
And I have done everything to resolve the problem. I wrote the function from scratch. I read somewhere that a function definition can't come within  a function, so I made it a Global function(though, personally I somehow don't feel that it's true). But even then the error managed to survive.
Being completely frustrated I don't know what to do. Can anyone please help me out ?
here's my code :-
#include < LiquidCrystal.h >

  const int rs = 12,
    en = 11,
    d4 = 5,
    d5 = 4,
    d6 = 3,
    d7 = 2,
    lm = A0;
int input;
float temp;
LiquidCrystal lcd(rs, en, d4, d5, d6, d7);

void tem() //Calculates Temperature
{
  int i = analogRead(lm);
  float temp = 500.0 * i / 1024;

  lcd.print("Temp : ");
  lcd.print(temp);
  lcd.print(" ^C");

}

void Clock(int h = 0, int m = 0, int s = 0, char ch = 'A') {
  int H = h;

  char ampm = ch;

  void mornight(char ampm) //changes am to am to pm and vice versa
  { //THE RED HIGHLIGHTED ERROR LINE
    String AMPM;
    if (ampm == 'A')
      AMPM = "PM";
    else
      AMPM = "AM";

  }
  while (H != 12) //HOUR'S LOOP
  {
    for (int M = m; M <= 59; M++) //MINUTE'S LOOP
    {
      for (int S = s; S <= 59; S++) //SECOND'S LOOP
      {
        delay(1000);
        lcd.clear();

        if (H < 10) {
          lcd.print('0');
          lcd.print(H);
          lcd.print(':');
        } else {
          lcd.print(H);
          lcd.print(":");
        }
        if (M < 10) {
          lcd.print('0');
          lcd.print(M);
          lcd.print(':');
        } else {
          lcd.print(M);
          lcd.print(":");
        }
        if (S < 10) {
          lcd.print('0');
          lcd.print(S);
          lcd.print(AMPM);
        } else {
          lcd.print(S);
          lcd.print(AMPM);
        }
        lcd.setCursor(0, 1);
        tem(); // shows temperature

      }
      s = 0;
    }
    m = 0;
    if (H == 23) {
      H = 1;
      mornight(ampm);
    } else
      H++;
  }
}

void setup() {
  lcd.begin(16, 2);
  lcd.setCursor(0, 1);
  Clock(10, 1, 20);

}
void loop() {

}

Your line:
void mornight(char ampm)

Is trying to define a function called mornight() inside of Clock().
Functions are "global" if they are defined outside of any other function. I can't see what you tried in order to make this function global, but besides object-oriented programming, plain functions are always global.
A "non-global" function would mean defining a class and declaring the function inside the class definition; but even then you have to define the function (that is, the actual instructions in the function) outside of any other class or function definition.

Move function void mornight(char ampm) outside of function void Clock(int h = 0, int m = 0, int s = 0, char ch = 'A') {
as the error message says, function can't be defined inside functions


text:
Writing and reading an ID to/from an Arduino reliably
I need a way to both ID (a sketch/compiled hex) and later on, identify based on this ID the project that got uploaded to my Arduino microcontroller. As of right now, I have explored multiple options for storing the ID and reading the ID from the Arduino. The ID would be a custom string or later on multiple strings. Here are the 3 options I have been thinking about with their pros and cons:

Option 1:
Writing: A custom function that would be added to every sketch before compilation, containing the ID information and a serial connection setup
Reading: The function would dump the ID over the serial connection using a fixed baud, after this, the projects original serial and baud would be initialized. The microcontroller would need to be rebooted in order for the user to be able to read the ID from it.
Pros: Easy to implement.
Cons: Would require manual or software restart of the microcontroller in order to read the ID

Option 2:
Writing: writing the ID to the EEPROM
Reading: reading the ID from the EEPROM over the serial connection.
Pros: Would probably not interference with the original code
Cons: it wears the EEPROM, it might need its own function in the sketch to read the ID from the EEPROM thus making it a complicated Option1.

Option 3: Editing the HEX file to include a signature
Writing: add the ID to the hex file itself (hex editing), after compiling it.
Reading: dumping the hex file and decoding the string.
Pros: No baud or serial needed to be set?
Cons: Probably slow, can end up producing a bad hex file, hard to implement properly with larger ID-s and structures

Example data:
project="marlin2.1",
config="prusa",
version="8.80",
env1="pin2"
As said, the basic idea is storing an ID but I would late want to expand this and store more information like a struct.  This solution should be able to Target as many Arduino models as possible. I am looking for the best way that I might have missed to achieve this task or any recommendations.

Which Arduino...?

Please tell what the ID is for (add the extra information to your question). Reading the eeprom does not wear it. With Option 1, the arduino dumps data by itself. That is odd. There are at least 10 other options. An other option is to include a .h file that has a generated ID. The compiler can put the compilation date and time in the sketch. The smallest arduino board can still do some decrypting, so you might put an encrypted ID in the arduino. Some arduino boards have a microcontroller that has an ID of its own. All the 1-Wire devices have an ID, just add a 1 dollar 1-Wire device. and so on.

I have added some examples to the top post. And about the eeprom I was talking about constantly rewriting the eeprom that it might wear it, every new sketch would have its own data set that would be readable from the Arduino using the computer.

Option 1 and 3 are kind of identical.

Option 3 would eliminate the need to setup a serial connection in every sketch. And I don't know if its possible to dump the hex file from every Arduino model. But beyond these points yes, option 1 and 3 are almost identical. I did not try option 3 in practice yet, but I think that it is possible to achieve a working edit/write/read/decode process.

I'd go with #2. If you are concerned that you will eventually burn-out your EEPROM (100.000 write cycles per ATmega328 ds), try writing a macro, which will dictate at which upload you want new ID to be written in EEPROM.
Heck, instead of writing all of these onboard, why don't you maintain an offline lookup database and encode things yourself? It would still require writing to EEPROM but you could encode your information in a couple of ints.


text:
Getting FFT arduino code to run over 9+ hours, utilizing micros()
I am a beginner in Arduino, coding, and electrical engineering (learning on my own time) and am working on creating an EEG. I've got the hardware down and have managed to get numerical data output from the analog (A0) of Arduino. The next step is transforming these numbers to outputting dominant frequency and I have managed to find a code that uses FFT to find the dominant frequency from the input of A0. The following is the code:
#include "arduinoFFT.h"

#define SAMPLES 128             //Must be a power of 2
#define SAMPLING_FREQUENCY 1000 //Hz, must be less than 10000 due to ADC

arduinoFFT FFT = arduinoFFT();

unsigned int sampling_period_us;
unsigned long microseconds;

double vReal[SAMPLES];
double vImag[SAMPLES];

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

sampling_period_us = round(1000000*(1.0/SAMPLING_FREQUENCY));
}

void loop() {

/*SAMPLING*/
for(int i=0; i<SAMPLES; i++)
{
    microseconds = micros();    //Overflows after around 70 minutes!

    vReal[i] = analogRead(0);
    vImag[i] = 0;

    while(micros() < (microseconds + sampling_period_us)){
    }
}

/*FFT*/
FFT.Windowing(vReal, SAMPLES, FFT_WIN_TYP_HAMMING, FFT_FORWARD);
FFT.Compute(vReal, vImag, SAMPLES, FFT_FORWARD);
FFT.ComplexToMagnitude(vReal, vImag, SAMPLES);
double peak = FFT.MajorPeak(vReal, SAMPLES, SAMPLING_FREQUENCY);

/*PRINT RESULTS*/
Serial.println(peak);     //Print out what frequency is the most dominant.

for(int i=0; i<(SAMPLES/2); i++)
{
    /*View all these three lines in serial terminal to see which frequencies has which amplitudes*/

    //Serial.print((i * 1.0 * SAMPLING_FREQUENCY) / SAMPLES, 1);
    //Serial.print(" ");
    //Serial.println(vReal[i], 1);    //View only this line in serial plotter to visualize the bins
}

delay(1000);  //Repeat the process every second OR:
//while(1);       //Run code once

}
The problem I have is with the line microseconds = micros(). The comment state that this will overflow after 70 minutes and after some days of research, I sorta understand what is meant by this. However, I need this program to run over 9 hours, so I can log the dominant frequency of the brainwave throughout the night. Is that possible?

Hi, interesting project. How much memory is necessary?

I apologize, but I'm not sure what you mean by that. If I understand correctly, I am attempting to take the dominant frequency every ten minutes within the course of ~9 hours. That would mean the COM output would be displaying 54 different data or memorizing it. (6 data every hour * 9hours).

Chris Do, there is indeed a rollover problem when micros is used that way. When that happens, the samples are taken at full speed without interval. That will create bad data for the FFT.
The solution is in the Blink Without Delay example. The magic to avoid a rollover problem is the substraction with two unsigned long values.
The arduinoFFT library is in the Library Manager of the Arduino IDE.
The example "FFT_03.ino" uses micros in the wrong way.
The next sketch shows how to avoid the rollover problem:
// Use micros() without rollover problem for a fixed sample rate
// for a certain amount of samples.

#define SAMPLES 128

unsigned long previousMicros;
const unsigned long intervalMicros = 1000UL;   // 1000 Hz is 1000 us

float vReal[SAMPLES];
float vImag[SAMPLES];

void setup() {
}

void loop() {

  previousMicros = micros();  // set the previousMicros just before entering the for-statement
  for(int i=0; i<SAMPLES; i++) {

    // A while-statement to wait.
    // Note that the ';' at the end means 'do nothing'.
    while( micros() - previousMicros < intervalMicros);

    // The 'previousMicros' is increased with a fixed number, for a fixed sample rate.
    previousMicros += intervalMicros;  // for next interval

    vReal[i] = float(analogRead(0));
    vImag[i] = 0.0;
  }

  delay(1000);
}

Take the current value of micros and substract the previous value of micros. The result of that substraction is a valid number, even during a rollover. It is the only way that always works.
The line to calculate the sample period has too many things in it that can go wrong. These lines:
unsigned int sampling_period_us;
sampling_period_us = round(1000000*(1.0/SAMPLING_FREQUENCY));

In my example, I set the intervalMicros to a certain number. Could you do that as well? When everything works, you can try to calculate it.
Added: The answer by Edgar Bonet is exactly the same. That is no surprise because there is no other way.

Re “The example "FFT_03.ino" uses micros in the wrong way”: I wasn't aware that the OP copied the bad example from the library itself. Good catch! I just submitted a pull request to the author of arduinoFFT. Hopefully he will get this fixed upstream.

As long as you never compare timestamps, the rollover is not an
issue. The idiom you used:
while (micros() < previous_timestamp + period) ...

is comparing two timestamps. This is incorrect, and it fails whenever
micros() rolls over. However, subtracting timestamps to get a duration
does work fine across rollover events. And comparing durations does
always work. So the correct idiom is:
while (micros() - previous_timestamp < period) ...

Note also that the way you update microseconds is incorrect. You are
incrementing it by the period you want plus the time taken by the
CPU to execute some of the code in the loop. You should instead
increment it by the requested period and no more. Here is my take at
what you are trying to accomplish:
/* SAMPLING */
microseconds = micros();  // record initial time
for (int i = 0; i < SAMPLES; i++) {
    while (micros() - microseconds < sampling_period_us)
        ;  // wait for the right time to take the sample
    microseconds += sampling_period_us;  // update as per the period
    vReal[i] = analogRead(0);
    vImag[i] = 0;
}

Edgar bonet and jot, I greatly appreciate your answers. I believe I did come over the rollover topic while researching and saw the solution but never comprehended until now. Just to be clear however, the problem with using micros is that it will rollover (In other words, after approximately 4.26*10^9 microseconds, it will rollover back to 0 and restart counting upward again). The solution is to use interval because the numerical value of theinterval will be the same even if micros() rollover. Is that correct? I will try this approach. Thank you very much for your help!

@ChrisDo: That's correct. See also millis() overflow ... a bad thing?

Hey Edgar, after experimenting with the code that you provided for a few days, it seems that the output of the FFT gets very sporadic after a while. Compared to the original code that I found, the output of that original code would be something like 23, 22, 23, 24, 25, 26, 30, 27, 25.
With the code that you have provided, it would output something like 23, 22, 65, 102, 300, 450, 23, 34, 46, 89.
By any chance do you happen to know why this would be?

@ChrisDo: This is unrelated to the rollover issue. I have no idea why your data looks like that.


text:
Switch two or more digital outputs of ESP8266 at the same time
I'd like to control some digital ICs with a ESP8266-12.

How can I switch 2 pins to HIGH in the same moment?
How can I switch one to LOW and the other to HIGH in the same moment?
Is it possible with every port or only with grouped ports and how are the groups?

Maybe have a look in this direction

See the datasheet: esp8266-technical_reference_en
Paragraph 2.2.2 shows how to use the output registers.
With the registers GPIO_OUT, GPIO_OUT_W1TS and GPIO_OUT_W1TC you can set or clear multiple GPIOs.


text:
Powering arduino and node mcu
I want to power up my Arduino and my Nodemcu via 12 V , 1 A power adapter (it's an AC to DC power Adapter).
Recently I have two voltages regulators: a 5 V for nodemcu and 9 V for Arduino Uno.
The question is does the 1A affect both boards or not?

In principle not. However, the voltage regulators may become quite hot, since you are going down from 12 V to 9 V and 5 V (especially the step from 9 V to 5 V is quite a lot). It depends on the current (in (milli)Amps) how hot they get.
For the adapter it does not matter, if it is 1 A or 10 A, the microcontrollers will only take whatever they need. Only if the adapter can deliver less than needed by both microcontrollers there is a problem.
The voltage regulators are not of switching type I guess, so they will use the same amount of amperes. Assuming the Arduino Uno takes 300 mA (at 5 V) and the NodeMCU 200 mA (at 12 V), you can add them together: 200 mA + 300 mA = 500 mA. Since this is less than 1 A the adapter can deliver, you are ok.