text:
How much current can arduino ground absorb?
I am currently working on an LED 4x4 cube, so here is my pre planned circuit diagram.
https://easyeda.com/editor-mobile/#id=ffca9f3303f242a185b950b0bee4fa29|

I am to connect 220ohm to each positive terminals.(16)

I am to use 4 transistors(2n2222) for 4 negative layers of which, collector terminal will be connected to the negative terminal layers , base will be connected to 4 analog pins through 1k ohm, and emitter to be connected to the GND pin of arduino. Using transistor as a switch.

Can my studio ground get damaged if connected directly without a resistor.
If no?
Is there any way to make it?
Explanation with circuit diagram will highly be preferred...
Thanks for your precious time...

Ordinary LEDs take 20 mA at most, and they are already bright enough (to my taste at least) at 10 mA or even less. If you get 1 A for 16 LEDs there is probably something wrong with your current-limiting resistors.

But if I connect resistor with higher ohm, the cube won't be able to run a single LED when needed as resistance will be too high for a single one, or if I connect low resistors that might either burn my LEDs or produce amps, btw, let's head to the main discussion point, can arduino ground tolerate 5 amps at max? If u have an idea please do share with me via sending a diagram. Thanks.

Since you are going to multiplex your LEDs, first you will design the DC current to a brightness of your linking. Second, you will multiply this current with the number of multiplexing steps. This results in a peak current for each LED, with breaks in between. Practically all LEDs withstand such a driving. Finally, you will multiply this current with the number of LEDs switched on at the same time. This is the expected maximum current that your circuit shall handle.

The best approach in my experience is to let that high current not on the Arduino. Design your driver's circuit separated, and just connect the grounds.

That's right @busybee but, I am to make driver for sure , but before it, I wd like to test it connecting it bare (maybe resistors)on arduino pins.

Those measurements don't make any sense. You can't get 1A of current with 16 x 220Ohm resistors, even if the forward voltage of the LEDs is 0V. I'd expect at most 200mA. So something is wrong. Either you have a short, or you multimeter is of. If your UNO is connected via USB, you can (theoretically) only get 500mA before the polyfuse cuts out the power.

Since you will be multiplexing you don't have to worry about the other layers, as only a single layer will be on at the same time. So you don't also multiply the current, of the one layer, by four.

@Gerben yeah I recently spotted my mistake thanks for the advice, but if I make a voltage amplifier using transistor and then, I guess I will be able to run all the LEDs together right?

there is no reason why the LED current should run through any part of the arduino

Not sure what you mean with "voltage amplifier". But running 16 leds with 220Ohm resistors will only give you 200mA, so I don't see any problem here. The only problem I see is with the columns. The Arduino pins can source the ±14mA, but the ATMega has some limitations on the total amount of current, total current for certain groups of pins. The maximum total current the ATMega328P can supply to all pins combined is 200mA. Ports C0 - C5, D0- D4, ADC7, should not exceed 150mA. Ports B0 - B5, D5 - D7, ADC6, XTAL1, XTAL2 should not exceed 150mA.

PS could you share what the mistake was?

@Gerben , my mistake was R=1/R + 1/R , as resistance of a standard LED is almost 48 ohm and they were in parallel connection,  (tried to pick a paralled connection of the LEDs row from layer 1)  R = 1/48*4 (because there are 4 LEDs in a row of a layer) , so answer is 0.0833, let's inverse it , 1 / 0.0833 = 12ohm for each row in a layer. Now, as I = V/R , 3 / 12 = 0.25 ,  =25, something like this....

What should be the delay() time of blinking those LEDs? delay(10) will be enough I guess

You want an update rate of at least 50-100Hz, so your eyes don't perceived flicker. So let's go with 100Hz here. Since you have 4 layers, you need to change layers at a rate of 4*100 = 400Hz. Which is every 2.5ms. In my project I'd setup one of the timers to call my ISR every 2.5ms. Then have to ISR update the leds and layer transistors based on a global (volatile) array of all led states. This way the display is updated at a fixed rate, even if some code takes a bit longer. Then the main loop only have to change the led state array to show some nice animation.

You can even add some grayscale to the leds, instead of only ON and OFF. You'd have the multiply the update rate, with the number of grayscale levels.

@Gerben, I am not only including ON OFF but also dimming and other animations too and for that, as per my calculations, '''delaymicroseconds(2);''' should work fine so that human eye can't recognize it and also I can do as much animations as I like in a single layer at a time.

2µs is only 32 clock cycles. You can't do a whole lot in 32 clock cycles. My last project updated it's leds every 52µs, and just the code updating the display used around 30µs of that. The other 20µs where to run the animations. I a bit doubtful if you can run all your code in under 2µs. Also, don't use delay, as you code will take various amounts of time, depending on branching (if-statements etc.). Store the micros() value, do your calculations, then wait till there is a 2µs difference between the current value of micros() and the stored value.

@Gerben OK got it!

No your gnd won't get damaged if you source current through it. If u need explanation let me know

You are asking the wrong question. It does not matter how much current the arduino ground can adsorb, it was designed for what it needs not what other devices may need. What you want to do is connect all the grounds at the power supply (please tell me you are not using the arduino 5v for this). You might look as MOSFETs as you will have a lower voltage drop and much easier to drive.

I am connecting all 16 positive pins to arduino pins 0 - 16 through 220ohm resistor and then I am gonna connect the negative layers to the ground using transistor and transistor's base will be connected to the rest of the 4 pins

None of the power output pins were used


text:
Why should I connect the l289n motor driver wires to specific arduino pins only?
So, I am new with arduino and am to build a robot using motors, for that I have bought l298n H bridge motor driver. I have watched various site and videos ,to make sure not to make a mistake but, in every video and sites
I have found their connecting the motor direction controller to

IN1 -> Arduino Pin 8 (digital) and IN2 -> Arduino Pin 7 (digital)
Till then it was fine ... Now the fishy thing for me is
IN3 -> Arduino Pin 5 (PWM) and IN4 -> Arduino Pin 4 (Digital)
Why connect to a Digital and a PWM?
For E1 and E2 I am sure that the wires should be connected to the PWM (~) pins for arduino, to control speed of the motor..
But, Should not I be able to connect IN3 and IN4 both to rest of the digital pins 12, 13 or 2,4 Just Like IN1 and IN2 is connected to 7 and 8.
But the IN3 and IN4 is connected to a PWM and a Digital pin.
Conclusion,
So can I use all the unused non PWM digital pins to connect the motor direction control?
Thanks for your precious time..!

PWM is a digital output ... it is pulsed ... the pulse timing is variable

I know that but , can we use a non PWM pin for it?

Because , we don't need PWM to just change the polarity of the motor, so , as per my logic, we should be able to use non PWM pins for motor direction changing purpose, So , am I right or wrong?

I think that you are missing important information ... the pins on the arduino are PWM only when you use analog out ... they are same as the other pins if you use digital out ... the reason to use PWM on the motor driver is not direction, but speed

what are the signal polarities for forward and what are they for reverse?

Here we are talking about Direction , not Speed , don't get confused @jsotola so , we can use only digital pins to do that and keep our rest pins reserved for other options.

i am not confused ... the motor driver uses two input pins ... the two pins have to be set to opposite values to run the motor ... if you use PWM on one of the pins and only digital on the other pin, then you can control direction and speed at the same time

Pwm is just a digital out with extra fancy on off controls.  You can use any digital out if you do not need those extra features.
To just signal a single H bridge (1 motor of your l289n) for forward, reverse, stop, one only needs two digital outs.
I recommend you get the hang of your h bridge first - signaling it on a bread board with vcc (usually 5v but can be 3.3) and ground rather than the arduino.  Then once you understand the motor directions that result from your wiring, write the code accordingly.  This tends to result in:

fewer fried arduinos
code with functions and signals named after their intent (rather than having to mix forward and reverse)

I know, my connection would be , Common Ground for 9v battery and arduino, Then , power the motor driver GND and +12 volt terminals, connect arduino VIN pin to the +5v output of the driver and bingo!  It shouldn't burn my board.

If you mean one of those square 9V battery like in a smoke detector then I think you will be disappointed.  They’re not much good for motors.  Try a handful of AA or AAA would be much better.  9V pp3 batteries can’t produce much current at one time.

Also don’t connect Vin to 5V.  Vin needs at least 7V.  If you have regulated 5V then put it on the 5V pin.

Will Duracell 9v batteries work? And also, the 5 volt is going to be regulated from the 9 volt battery by a resistor.

yes the 9v will run the arduino over vin.  It will produce 5V for you.  Both your arduino and l298n have proper regulators for producing 5V so you shouldnt have to do anything but hook the 9V to them (correctly) to produce 5V.

source: Stack Exchange

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

sort: votes


text:
What is the principle of scanner
I find a 2.4GHz scanner in this web . I want to do same thing in 433 Mhz with SI4463. But I fail to understand it's principle. Who can explain it ? Thanks.

This might help; http://www.silabs.com/Support%20Documents/TechnicalDocs/AN633.pdf

But I fail to understand it's principle. - what principle do you want explained exactly? I don't see what this is to do with Arduinos.

@NickGammon  I don't know the algorithm i.e how does it work.

@MikaelPatel  It's too hard for me ....

I find a 2.4GHz scanner in this web . I want to do same thing in 433
  Mhz with SI4463. But I fail to understand it's principle. Who can
  explain it ?

The scanner you found loops through the channels looking for activity. The channels are defined by the NRF24L01. And activity is received signal within the channel above threshold (RSSI). For this device this is a single bit.
Other devices define RSSI as the signal quality/level for the latest received package. This is the case for the SI4463.
Cheers!

I use http://www.airspayce.com/mikem/arduino/RadioHead/classRH__RF24.html   to control SI4463, but the RSSI is zero although there is a interference at same frequency . Do you know how to do it ?

Please post your test program/code.

BW: The RSSI value from SI4463 is for the latest received package. Interference is not detected by the RSSI in this case.

Yes, so ,I don't know how to do the same thing. And I have add my code in my question. Thanks very much.

@MikaelPatel - What the 446x RSSI means depends on what mode it is operating in.  If the poster wants to measure things that are not compatible signals, they probably do not want to be operating in packet mode.

@MikaelPatel  I think you are right. But I can't find a suitable mode in RH_RF24.

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


text:
Does ADC conversion to a voltage rely on the actual value of the +5 V pin?
Questions:

Does the conversion of the ADC count to voltage depend on the actual voltage of the +5 V pin?
If yes, what is the accepted method of getting that voltage from the board?

Background/Detail:
I have a circuit in which I have an Arduino Nano (clone) running from a USB connector (from a hub). The job of the Arduino is to measure the voltage on a battery which will drive a second circuit switched on/off by the Nano. For reference it is a battery tester.

There is a Nokia 5110 screen which displays the voltage from the very simple sketch below.
void setup() {
  Serial.begin(9600);
  display.begin();
  // Init done

  // You can change the contrast around to adapt the display
  // for the best viewing!
  display.setContrast(50);

  // Text display tests
  display.setTextSize(1);
  display.setTextColor(BLACK);
}

void loop() {
  display.clearDisplay();   // Clears the screen and buffer
  display.setCursor(0,0);
  display.print("Vin=");
  int rawVIN = analogRead(VIN);
  float floatVin = (rawVIN*4.75)/1023.0;
  display.println(floatVin);
  Serial.println(rawVIN);
  display.display();
  delay(1000);
}

I measured the voltage of the battery using a DVM and it is 4.13 V, yet
the Nano reports 4.35 V.
I have a common ground between the battery and Arduino.
Because the connection to test the voltage can float, I have a pulldown resistor to stop wild fluctuations (>10 kΩ)

After some investigation I found that the +5 V was actually outputting 4.75 V and changed my sketch from
float v = (rawVIN*5.0)/1024.0;

to
float v = (rawVIN*4.75)/1024.0;

and the voltage reading on the Arduino was now correct. I did this not because I understand what I did, I did it because I had a hunch it might change the value to the correct one.

As a side not you should be dividing by 1024, not 1023. This is a mistake which gets repeated over an over again, presumably stemming from the mistake being in the Arduino examples. Source? The datasheet for the AVR.

@TomCarpenter I think this is a result of my fumbling around with the calculation and reading something after quite a long time of banging my head against the desk - I started with 1024 but as you see ended up with 1023 - I'll correct my question.

The ADC inside the Arduino does not measure voltage, but rather a
voltage ratio. Namely the ratio from the voltage at the analog input
to the voltage at the Vref pin.
In the default configuration, the Vref pin is internally tied to the
+5 V line. You can select to use instead an internal reference as
Vref:
analogReference(INTERNAL);

This reference  is about 1.1 V, and is is quite immune to
fluctuations on the +5 V. The problem is that you cannot measure
voltages higher than the reference.
For your battery tester, if you want some sort of “absolute”
measurement, you could use the internal reference and a voltage divider
to ensure the measured voltage is below 1.1 V.
Edit: Another option which does not require a voltage divider is to
use Vcc as a reference to measure both the analog input and the
internal 1.1 V “bandgap“ reference. Measuring the 1.1 V
against Vcc is an indirect way to measure Vcc. This is not supported by
the Arduino core library, but you can do it by programming directly the
control registers of the ADC:
// Return the supply voltage in volts.
float read_vcc()
{
    const float V_BAND_GAP = 1.1;     // typical
    ADMUX  = _BV(REFS0)    // ref = Vcc
           | 14;           // channel 14 is the bandgap reference
    ADCSRA |= _BV(ADSC);   // start conversion
    loop_until_bit_is_clear(ADCSRA, ADSC);  // wait until complete
    return V_BAND_GAP * 1024 / ADC;
}

Beware that the very first reading after boot may be bogus.

Thanks for the prompt reply :) this makes perfect sense now and explains why by my code (fudge) adjustment I get the right answer. This combined with enrics answer give me all I need to continue.

A USB-powered Arduino Nano will have an ADC voltage reference which can't be relied on, due to the +/- 5% tolerance of the incoming USB voltage. On top of that, the Nano has an MBR0520 Schottky diode (D1) that will drop between 0.1 and 0.5 V depending on its own manufacturing tolerances, its temperature, and the current draw of your board.
What can you do about it?
The MCU on-board the Arduino Nano is an ATmega328P. The Nano's ADC can scale its analog voltage readings according to several available references (and you can choose the one that suits you better). You can do this through the analogReference (type) function, and chose among the following reference types:

DEFAULT: the default analog reference of 5 volts (on 5 V Arduino boards) or 3.3 volts (on 3.3 V Arduino boards)
INTERNAL: An built-in reference, equal to 1.1 volts on the ATmega168 or ATmega328 and 2.56 volts on the ATmega8 (not available on
  the Arduino Mega)
  [...]
EXTERNAL: the voltage applied to the AREF pin (0 to 5 V only) is used as the reference.

Source: analogReference
This is the ADC schematic for what's inside the ATmega328 so you can see what's going on there:

Source: ATmega328 datasheet
So the straightforward solution is building a weak voltage divider to get the voltage you want to measure below the INTERNAL 1.1 V reference, and then configure analogReference accordingly.
The voltage divider needs to be weak (high R values) so you don't draw too much current out of the battery, but not too weak as to be loaded by the ADC input impedance.
Bonus
However, if you need a voltage reference higher that the internal 1.1 V bandgap reference of the ATmega328 you're still out of luck. A option would be to use the 3.3 V LDO regulator output from the on-board FT232RL, which is available to you at pin 14 of the header, but I don't think it's reliable either. The FT232RL datasheet specifies it at 3.0 - 3.6 V (nominal 3.3 V)
So a universal solution would be to build an external voltage reference based on a cheap TL431. That could give you a reliable reference up to 4.0 - 4.25 V with a +/-1% accuracy.
The external voltage reference circuit would be something as easy as this, (and the TL431 is available in the breadboard friendly TO-92 package!):

Thanks for this comprehensive answer and all the alternatives I could take up - I will probably go simple and do a voltage divider to scale my input between 0 and 1.1. The hint about resisteor values was valuable to me - thanks

I have a page about the ADC converter on the Atmega328P. Somewhat down the page I describe voltage references. You can use the TL431 chip to provide assorted reference voltages, for example 4V:

By changing the resistors you can get other voltages (it looks like you want around 4.2V).
The output voltage is not influenced by the input voltage (5V in this case).
The linked page describes how you might choose resistor values.

Does the conversion of adc count to voltage depend on the actual voltage of the +5v pin?

yes and no: the adc module cares about Vref, which can be supply via Vdd, internally, or externally.

If yes what is the accepted method of getting that voltage from the board?

by configuring the adc module. the device datasheet should have registers / bits that need to be set up for that.

authors: Юрий Колесников

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


text:
Test level shifter with Arduino and some data
Below is a reference to a logical level bi-directional converter (aka level shifter) I purchased on Ebay.  I've soldered the 12 pins (6 for each piece) to the level shifter so that it fits on my bread board.
http://www.ebay.com/itm/121868205078?_trksid=p2057872.m2749.l2649&ssPageName=STRK%3AMEBIDX%3AIT
This may sound trivial, but I'd like to troubleshoot the level shifter with communication both ways (Rx and Tx) to make sure it's working properly.  I've got a constant 4.85v (5V) going to the HV pin, and a constant regulated 3.24V (3.3V) going to the LV pin, along with ground to both GND pins.  Right now, I'm using pin0 (Rx) and pin1 (Tx) on the Arduino Mega 2560.
void setup() {
  Serial.begin(9600);
}

void loop() {
  delay(1000);
  Serial.println("Test");
}

How can I test this level shifter without any fancy components?  How could I write a program to toggle an LED both on LV1 and HV1 pins, by modifying the program above?  Please note, that even though the Arduino runs on 5V, I am not using the Arduino as my HV power source.
EDIT (per comment 3 by @Paul):
Test:

Burn blank sketch into Arduino
Connect 5V (Arduino 5V) to HV pin
Connect GND (Arduino GND) to GND pin on same side as HV pin
Connect 3.3V to LV pin
Connect GND (from 3.3V power source) to GND pin on same side as LV
pin
Connect Arduino Tx pin to channel 1 (HV1)
Connect Arduino Rx pin to channel 2 (HV2)
Short channel 1 to channel 2 with jumper wire

When all of this is connected, and I open the Serial Monitor on Arduino IDE, anything I type will echo back exactly what I typed.  And when I disconnect one of these jumpers, it doesn't echo back.  So it seems to work.

Try to perform a "loop-back test" simply send a character over the Tx line through the converter (and back through the converter) into the Rx line. And check if you receive back what you send.

@Paul - I've connected HV1 (channel 1) to pin 0 (Rx) on the Arduino, and HV2 (channel 2) to pin 1 (Tx) on the Arduino.  What hardare do I put between LV1 and LV2 on the low voltage side of the level shifter to ensure the ASCII character comes back?

an 0 Ohm resistor ;)
Basically anything that is conductive, a wire preferably. The bits will then travel from output Tx -> HV1 (high) -> shifter LV1 (to low) -> wire -> shifter LV2 (to high) ->HV2 -> input Rx if that succeeds, you can safely assume it's working for UART and that it's bi-directional.

Haha!  I guess the saying goes "Keep It Simple Steve" .. or is that last word incorrect?

A 0 Ohm's resistor is a resistor that has "no resistance". Which is basically a (short) wire. Check this "tutorial" (http://www.instructables.com/id/Loopback-Test-For-Arduino-Uno/?ALLSTEPS)

One note here.  I'm using the Arduino, rather than a UART (as in comment by @Paul).  Hopefully your comment holds true when using the Arduino.  Is the Arduino and UART both 5V, which would connect in the same way to the HV pin on the level shifter?

I'm sorry, UART or USART is the "low level hardware" behind the hardware serial port (Rx and Tx pins). So yes, we're on the same line (:

@Paul - shorting channel 1 to channel 2 worked!  Does my "Test" in my EDIT look accurate to you?

if the signal goes from Tx to HV1 to LV1 to jumper to LV2 to HV2 to rx, you can safely assume that the component works. You might want to check the voltages, if they really are around 5V and around 3.3V.
But yes, you've tested/proven that this component will work for serial communication.

So, yes it seems right to me. You are shorting channel 1 LV and channel 2 LV? From your notes it could also be HV. But both should work neverthless.

Yes, I basically made a short circuit from LV1 to LV2 with a short jumper wire/cable on my breadboard.  I typed "Hello" and the Serial Monitor echoed back "Hello".  When I removed the short, it didn't echo back "Hello".

You don't need to write any program.
First, note that this is (or at least purports to be) an I2C level shifter. This means that it does not actively pull up anything; it only actively pulls down. You are supposed to provide pull-ups somewhere in your circuit.
To test it, pull up HV1 and LV1 with 10K resistors to HV and LV respectively; measure the voltage on both sides to verify you are pulling to ~5V and ~3.3V respectively.
Ground HV1, check that LV1 is low.
Ground LV1, check that HV1 is low.
Ta-dah!

The pull-ups are already on the board, as far as I can see. Though, I'm not entirely sure if you can use an I2C level shifter for UART.

@Gerben the resistors, are used for the (bi-directional) voltage conversion. I've got a similiar board (https://www.sparkfun.com/products/12009) which works for uart, logic and spi (haven't tried I2C but it should be fine).

@JayEye - When you say "pull up HV1 and LV1 with 10K resisters" do I put a 10K ohm resister between the HV1 pin and some something else, and another 10K ohm resister between the LV1 pin and something else?  Do I need a "something else" or am I just measuring the voltage drop where the "something else" is on the low voltage side and high voltage side of channel 1?

In addition to testing the voltage, I'd also like to ensure data is passed back and forth.  That's ultimately what I'm after here.  I've updated the title of the question to reflect that.

@MacGyver edited the answer to make that clear

if you wan to use this for anything other than i2c, get a proper level converter.

why would it not pass data? if you make sure that a high and a low on either side results in the corresponding signal, you're good to go.

What applications should one use an i2c for?  What is a better level shifter for other applications, that this would not work for?  Two days ago, I didn't know what a level shifter was.  :-)

at the risk of angering the moderators, I'll point to actual products:
https://www.adafruit.com/products/1875 for general-puprose shifting, and
https://www.adafruit.com/products/757 for I2C level shifting.
Read the documentation they provide, they'll explain everything you need to know.
I am not affiliated with Adafruit; I just find them convenient, as we are both in NYC and even the cheapest shipping results in two-day delivery!!

@JayEye - does "pull up" mean to go from a low voltage to high voltage, and "pull down" mean go from high voltage to low voltage?

No, "pull up" means that it's connected through a resistor to "postive" so that, if no device is driving it low, it will be defaulted to postive. You might want to check some tutorials on it. But, it's not required for communication with Rx/Tx lines.

@paul i have done some but when i connect channel1 to channe2 via jumper wire arduino stop working and text stop coming on serial monitor.

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


text:
Erasing all flash on boards with over 64kb of program memory
I'm using a Mega2560 board.
My project needs to store some large constant data. To preserve the first 64kb flash chunk, I write these data on addresses beyond this limit.
But there is either an issue doing that or I'm doing something wrong...
After writing data the first time, I can read all bytes without no problem, but if I rewrite these data with new ones, the new data are not written correctly. It seems that, before reprogramming, the flash over 64kb are not erased.
Is this correct? How can I resolve this issue?

Note that, to access the data over 64kb, I use a far address.
Reading inside the bootloader source (stk500v2) code, I found that it doesn't erase pages whose addresse falls over 64kb to preserve the bootloader area. It seems that the bootloader is placed at the boundary of the first 64kb.
The following is the relevant the portion of the bootloader source:

// erase only main section (bootloader protection)
// APP_END is below 64KB
if (eraseAddress < APP_END )
{
    boot_page_erase(eraseAddress);  // Perform page erase
    boot_spm_busy_wait();       // Wait until the memory is erased.
    eraseAddress += SPM_PAGESIZE;   // point to next page to be erase
}

/* Write FLASH */
do {
    lowByte     =   *p++;
    highByte    =   *p++;

    data        =   (highByte << 8) | lowByte;
    boot_page_fill(address,data);

    address =   address + 2;    // Select next word in memory
    size    -=  2;              // Reduce number of bytes to write by two
} while (size);                 // Loop until all bytes written

boot_page_write(tempaddress);
boot_spm_busy_wait();
boot_rww_enable();


text:
ESP8266 Websockets problem
I am trying to set up a network of 4 esp8266 programmed via the Arduino IDE. The Network will have 1 server (esp8266 running in AP mode) and 3 clients (esp8266 running in STA mode). I would like to do two things on the network.

Each client signals the server when a certain event happens (event is different for each client) and
Server broadcasts a byte of data to ALL clients on a regular basis (e.g. 1 second)

I have adapted various code to come up with the following (most examples I have seen do not use a standalone server).

#include <Arduino.h>

#include <ESP8266WiFi.h>
#include <ESP8266WiFiMulti.h>
#include <WebSocketsServer.h>
#include <ESP8266WebServer.h>
#include <ESP8266mDNS.h>
#include <Hash.h>

#define USE_SERIAL Serial

const char *ssid = "MyNetwork";
const char *password = "MyPassword";

unsigned long last_10sec = 0;
unsigned int counter = 0;

ESP8266WebServer server(80);

WebSocketsServer webSocket = WebSocketsServer(81);

void webSocketEvent(uint8_t num, WStype_t type, uint8_t * payload, size_t length) {

    switch(type) {
        case WStype_DISCONNECTED:
            USE_SERIAL.printf("[%u] Disconnected!\n", num);
            break;
        case WStype_CONNECTED: {
            IPAddress ip = webSocket.remoteIP(num);
            USE_SERIAL.printf("[%u] Connected from %d.%d.%d.%d url: %s\n", num, ip[0], ip[1], ip[2], ip[3], payload);
            // send message to client
            webSocket.sendTXT(num, "Connected");
            }
            break;
        case WStype_TEXT:
            USE_SERIAL.printf("[%u] get Text: %s\n", num, payload);
            break;
    }

}

void setup() {
    WiFi.disconnect();
    USE_SERIAL.begin(115200);
    USE_SERIAL.println();

    for(uint8_t t = 4; t > 0; t--) {
        USE_SERIAL.printf("[SETUP] BOOT WAIT %d...\n", t);
        USE_SERIAL.flush();
        delay(1000);
    }

    WiFi.softAP(ssid, password,10,false,8); // setup AP on channel 10 and set 8 possible connections

    IPAddress myIP = WiFi.softAPIP();
    USE_SERIAL.print("AP IP address: ");
    USE_SERIAL.println(myIP);

    // start webSocket server
    USE_SERIAL.println("start websockets");
    webSocket.begin();
    webSocket.onEvent(webSocketEvent);
    USE_SERIAL.println("websockets started");

    server.on("/", []() {
      // send index.html
        server.send(200, "text/html", "LED Control:

R: <input id=\"r\" type=\"range\" min=\"0\" max=\"255\" step=\"1\" oninput=\"sendRGB();\" />
G: <input id=\"g\" type=\"range\" min=\"0\" max=\"255\" step=\"1\" oninput=\"sendRGB();\" />
B: <input id=\"b\" type=\"range\" min=\"0\" max=\"255\" step=\"1\" oninput=\"sendRGB();\" />
");
    });
    USE_SERIAL.println("start server");
    server.begin();

    USE_SERIAL.println("end setup and goto main loop");
}

void loop() {
    unsigned long t = millis();
   //;
    server.handleClient();

    if((t - last_10sec) > 30000) {
        counter++;
        bool ping = (counter % 2);
        int i = webSocket.connectedClients(ping);
        USE_SERIAL.printf("%d Connected websocket clients ping: %d\n", i, ping);
        last_10sec = millis();
    }
}

client code is
#include <Arduino.h>

#include <ESP8266WiFi.h>
#include <ESP8266WiFiMulti.h>

#include <WebSocketsClient.h>

#include <Hash.h>

const char *ssid = "MyNetwork";
const char *password = "MyPassword";
bool isConnected = false;

ESP8266WiFiMulti WiFiMulti;
WebSocketsClient webSocket;

#define USE_SERIAL Serial
#define MESSAGE_INTERVAL 10000
#define HEARTBEAT_INTERVAL 15000
uint64_t messageTimestamp = 0;
uint64_t heartbeatTimestamp = 0;

void webSocketEvent(WStype_t type, uint8_t * payload, size_t length) {

  switch(type) {
    case WStype_DISCONNECTED:
      USE_SERIAL.printf("[WSc] Disconnected!\n");
      isConnected=false;
      break;
    case WStype_CONNECTED: {
      USE_SERIAL.printf("[WSc] Connected to url: %s\n", payload);
      isConnected = true;
      // send message to server when Connected
      webSocket.sendTXT("Connected");
    }
      break;
    case WStype_TEXT:
      USE_SERIAL.printf("[WSc] get text: %s\n", payload);

      // send message to server
      // webSocket.sendTXT("message here");
      break;
    case WStype_BIN:
      USE_SERIAL.printf("[WSc] get binary length: %u\n", length);
      hexdump(payload, length);

      // send data to server
      // webSocket.sendBIN(payload, length);
      break;
/*        case WStype_PING:
            // pong will be send automatically
            USE_SERIAL.printf("[WSc] get ping\n");
            break;
        case WStype_PONG:
            // answer to a ping we send
            USE_SERIAL.printf("[WSc] get pong\n");
            break;
    }*/
  }
}

void setup() {

  USE_SERIAL.begin(115200);

  //Serial.setDebugOutput(true);
  USE_SERIAL.setDebugOutput(true);

  USE_SERIAL.println();
  USE_SERIAL.println();
  USE_SERIAL.println();

  for(uint8_t t = 4; t > 0; t--) {
    USE_SERIAL.printf("[SETUP] BOOT WAIT %d...\n", t);
    USE_SERIAL.flush();
    delay(1000);
  }
  WiFi.mode(WIFI_STA);
  WiFi.begin(ssid, password);
 // was WiFiMulti.addAP("SSID", "passpasspass");

  while (WiFi.status() != WL_CONNECTED) {
    delay(500);
    USE_SERIAL.printf(".");
  }

  USE_SERIAL.println("start websocket");
  // server address, port and URL
  webSocket.begin("192.168.4.1", 81, "/");

  // event handler
  webSocket.onEvent(webSocketEvent);
  delay(10000);
  // try ever 5000 again if connection has failed
  webSocket.setReconnectInterval(5000);
  USE_SERIAL.println("end of setup. Goto Main loop");
}

void loop() {
  webSocket.loop();
    if(isConnected) {
        USE_SERIAL.printf("Connected\n");
        uint64_t now = millis();

        if(now - messageTimestamp > MESSAGE_INTERVAL) {
            messageTimestamp = now;
            USE_SERIAL.printf("send message\n");
            // example socket.io message with type "messageType" and JSON payload
            webSocket.sendTXT("42[\"messageType\",{\"greeting\":\"hello\"}]");
        }
        if((now - heartbeatTimestamp) > HEARTBEAT_INTERVAL) {
            heartbeatTimestamp = now;
             USE_SERIAL.printf("heartbeat\n");
            // socket.io heartbeat message
            webSocket.sendTXT("2");
        }
    }
    else
    {
      USE_SERIAL.printf("not connected\n");
      delay(10000);
    }
}

The debug output for server is
19:38:30.671 -> SDK:2.2.1(cfd48f3)/Core:2.5.2=20502000/lwIP:STABLE-2_1_2_RELEASE/glue:1.1-7-g82abda3/BearSSL:a143020
19:38:30.671 ->
19:38:30.671 -> [SETUP] BOOT WAIT 4...
19:38:31.657 -> [SETUP] BOOT WAIT 3...
19:38:32.689 -> [SETUP] BOOT WAIT 2...
19:38:33.673 -> [SETUP] BOOT WAIT 1...
19:38:34.657 -> [AP] softap config unchanged
19:38:34.704 -> AP IP address: 192.168.4.1
19:38:34.704 -> start websockets
19:38:34.704 -> [WS-Server] Server Started.
19:38:34.704 -> websockets started
19:38:34.704 -> start server
19:38:34.704 -> end setup and goto main loop
19:38:58.354 -> wifi evt: 7
19:38:58.495 -> wifi evt: 7
19:38:58.635 -> wifi evt: 7
19:39:00.606 -> 0 Connected websocket clients ping: 1
19:39:00.935 -> add 1
19:39:00.935 -> aid 1
19:39:00.935 -> station: xx:xx:xx:xx:xx:xx join, AID = 1
19:39:00.935 -> wifi evt: 5
19:39:01.075 -> wifi evt: 9
19:39:03.102 -> wifi evt: 7
19:39:03.257 -> wifi evt: 7
19:39:03.377 -> wifi evt: 7
19:39:03.527 -> wifi evt: 7
19:39:03.837 -> wifi evt: 7
19:39:30.567 -> 0 Connected websocket clients ping: 0
19:40:00.595 -> 0 Connected websocket clients ping: 1
19:40:30.573 -> 0 Connected websocket clients ping: 0
19:41:00.577 -> 0 Connected websocket clients ping: 1

and debug output for client is
19:13:45.235 -> SDK:2.2.1(cfd48f3)/Core:2.5.2=20502000/lwIP:STABLE-2_1_2_RELEASE/glue:1.1-7-g82abda3/BearSSL:a143020
19:13:45.235 ->
19:13:45.235 ->
19:13:45.235 ->
19:13:45.235 -> [SETUP] BOOT WAIT 4...
19:13:46.267 -> [SETUP] BOOT WAIT 3...
19:13:46.642 -> wifi evt: 2
19:13:47.251 -> [SETUP] BOOT WAIT 2...
19:13:48.095 -> scandone
19:13:49.032 -> state: 0 -> 2 (b0)
19:13:49.032 -> [SETUP] BOOT WAIT 1...
19:13:49.032 -> state: 2 -> 3 (0)
19:13:49.079 -> state: 3 -> 5 (10)
19:13:49.079 -> add 0
19:13:49.079 -> aid 1
19:13:49.079 -> cnt
19:13:49.079 ->
19:13:49.079 -> connected with MyNetwork, channel 10
19:13:49.079 -> dhcp client start...
19:13:49.079 -> wifi evt: 0
19:13:49.219 -> ip:192.168.4.2,mask:255.255.255.0,gw:192.168.4.1
19:13:49.219 -> wifi evt: 3
19:13:50.626 -> ....scandone
19:13:52.641 -> .start websocket
19:13:59.062 -> pm open,type:2 0
19:14:02.624 -> end of setup. Goto Main loop
19:14:02.624 -> [WS-Client] connect ws...
19:14:02.624 -> [hostByName] Host: 192.168.4.1 is a IP!
19:14:02.671 -> [WS-Client] connected to 192.168.4.1:81.
19:14:02.671 -> [WS-Client][sendHeader] sending header...
19:14:02.671 -> [WS-Client][sendHeader] handshake GET / HTTP/1.1
19:14:02.671 -> Host: 192.168.4.1:81
19:14:02.671 -> Connection: Upgrade
19:14:02.671 -> Upgrade: websocket
19:14:02.671 -> Sec-WebSocket-Version: 13
19:14:02.671 -> Sec-WebSocket-Key: 8L/m+WcjssjBS/Sa8a0Qvg==
19:14:02.671 -> Sec-WebSocket-Protocol: arduino
19:14:02.671 -> Origin: file://
19:14:02.671 -> User-Agent: arduino-WebSocket-Client
19:14:02.671 ->
19:14:02.671 -> [write] n: 241 t: 17509
19:14:02.671 -> [WS-Client][sendHeader] sending header... Done (23209us).
19:14:02.671 -> not connected
19:14:12.661 -> not connected
19:14:22.659 -> not connected
19:14:32.664 -> not connected
19:14:42.687 -> not connected
19:14:52.671 -> not connected
19:15:02.657 -> not connected
19:15:12.692 -> not connected
19:15:22.677 -> not connected
19:15:32.674 -> not connected

I am reading this as the client connecting to the AP but not connecting via websockets. Can anyone assist?

The server you set as server(80) and the client you set as webSocket.begin(ip, 81,...) .why you do that? Try to use same port.


text:
Trouble operating Servo and GPS at the same time
I have a problem using a servo and a GPS board at the same time on an Arduino Uno.
For the servo, I use the following code:

Servo myservo;  // create servo object to control a servo
// twelve servo objects can be created on most boards

int pos = 0;    // variable to store the servo position

void setup() {
  myservo.attach(9);  // attaches the servo on pin 9 to the servo object
}
void loop() {
  for (pos = 0; pos <= 180; pos += 1) { // goes from 0 degrees to 180 degrees
    // in steps of 1 degree
    myservo.write(pos);              // tell servo to go to position in variable 'pos'
    delay(15);                       // waits 15ms for the servo to reach the position
  }
  for (pos = 180; pos >= 0; pos -= 1) { // goes from 180 degrees to 0 degrees
    myservo.write(pos);              // tell servo to go to position in variable 'pos'
    delay(15);                       // waits 15ms for the servo to reach the position
  }
}

For the GPS module, I follow the guidance on this webpage describing the NEO-6M GPS Module
#include <SoftwareSerial.h>

// The serial connection to the GPS module
SoftwareSerial ss(4, 3);

void setup(){
  Serial.begin(9600);
  ss.begin(9600);
}

void loop(){
  while (ss.available() > 0){
    // get the byte data from the GPS
    byte gpsData = ss.read();
    Serial.write(gpsData);
  }
}

I combine these two code blocks into one *.ino file (combining the declarations, placing all the setup portions in the void setup(){...} function and the rest in the void loop(){...} part).
Here is the problem:
Each block by itself runs fine. The "GPS block" returns GPS messages and the "Servo block" runs smoothly through its position sweep. However, when this code is combined the servo starts to act erratically and "jerks" back and forth.
After some testing, it appears that starting the serial connection (ss.begin(9600);) changes the behavior of the servo control pin (here 9) and it looses its pulse width modulating (PWM) capability. The servo then starts to "jerk" to random positions.
Does anybody have insight into this phenomenon? Is there a way to operate the servo and the GPS module together?
Here is a functional code block that sweeps through the servo positions smoothly, by commenting out the line //ss.begin(GPSBaud); and replicates the erratic behavior by uncommenting the same line ss.begin(GPSBaud);.
#include <Servo.h>
#include <TinyGPS++.h>
#include <SoftwareSerial.h>

Servo myservo;  // create servo object to control a servo
// twelve servo objects can be created on most boards

int pos = 0;    // variable to store the servo position

static const int RXPin = 4, TXPin = 3;
static const uint32_t GPSBaud = 9600;

// The TinyGPS++ object
TinyGPSPlus gps;

// The serial connection to the GPS device
SoftwareSerial ss(RXPin, TXPin);

void setup() {
  myservo.attach(9);  // attaches the servo on pin 9 to the servo object
  Serial.begin(GPSBaud);
  //ss.begin(GPSBaud);
}

void loop() {
  for (pos = 20; pos <= 160; pos += 1) { // goes from 0 degrees to 180 degrees
    // in steps of 1 degree
    myservo.write(pos);              // tell servo to go to position in variable 'pos'
    delay(15);                       // waits 15ms for the servo to reach the position
  }
  for (pos = 160; pos >= 20; pos -= 1) { // goes from 180 degrees to 0 degrees
    myservo.write(pos);              // tell servo to go to position in variable 'pos'
    delay(15);                       // waits 15ms for the servo to reach the position
  }
}

Would really help if you said why the system acted unexpectedly.  Guessing, I would first disconnect the servos to see if you have a power supply problem.

Thanks for editing your question.

Usually it is never a good idea to use a software implemented serial communications port. Especially when combining multiple Arduino libraries.  Likely you will have to graduate to a more capable embedded processor to get around this problem.   (You may be the 1st to combine these 2 libraries.)  I still am concerned about the power (are you supplying power to the servos separately from the Arduino and GPS module?).

@st2000, thanks for your comments.

I only use the USB connection for power. I will check if I have an external power supply available.
You recommend using a more capable embedded processor. Do you have a suggestion on which one might be suitable?

@st2000 I connected a 9V battery as external power source in addition to the USB connection. This does not change the behavior.

For 1, USB 2.0 is only obliged to deliver 0.5Amps.  More current than that and the port can rightfully drop the voltage on you.  For 2, there are many platforms in which the Arduino development environment has been ported to.  An Arduino Uno uses an Atmel  ATmega328P.  An Arduino Mega uses an Atmel  ATmega2560.   A processor with many more peripheral features.

FYI, a common Alkaline 9 volt battery does not have the current capacity to drive much of anything.   About 1/2A/h.  A stack of Alkaline D cells could hold as much as 30 times the power.

Should add, in the end you may still have some sort of hardware contention.  And it may not be the processor.  The libraries may not take advantage of all that any given processor has to offer.  Also, you may have to dive deeper into the library options.  You may have to select alternate peripherals (i.e. the second serial port) rather than accept the default (which may be the first serial port).  In the worst case you may have to rewrite one or both of the libraries.  Or, if that's not to your liking, run the Servos and GPS on different Arduino's which talk to each other.


text:
MPU6050/DMP Intermittent bad data output?
I have a DFRobots MPU6050 module wired to SCL/SDA/Pin 2 on a Mega 2560 board, using Jeff Rowberg's I2CDev/MPU6050_6Axis_MotionApps libraries.  I have 2.2K pullups on the MPU6050 module, tied to +5V, as shown in the following photo.

I used a modified version of the code from Jeff's example to retrieve heading values from the MPU6050, as shown below

bool GetIMUHeadingDeg() //08/28/18 chg to bool return

{
//Purpose:  Encapsulate everything needed to acquire a yaw value
//Inputs:
//  global_yawval = float variable defined at global scope
//  fifocount = uint8_t variable defined at global scope
//  packetsize = uint8_t variable defined at global scope
//  mpuIntStatus = uint8_t variable defined at global scope
//  whilecount = long variable defined at global scope
//  resetcount = int variable defined at global scope
//Outputs:
//  global_yawval filled with latest yaw value from sensor
//  true = success, false = failure
//Notes:
//  08/13/18 now returns global_yawval to calling routine
//  08/28/18 chg return to bool so can return success/failure

// if programming failed, don't try to do anything
//if (!dmpReady) return;
//if (!dmpReady) false;

bool result = false; //added 01/16/19 to supress warnings

// wait for MPU interrupt or extra packet(s) available
while (!mpuInterrupt && fifoCount < DMPpacketSize)
{
    whilecount++;
    delay(10);
    delay(10);

    if (mpuInterrupt)
    {
        fifoCount = mpu.getFIFOCount();
        mySerial.printf("%ld\t%d\n", whilecount, fifoCount);
        whilecount = 0;
        break;
    }
}

// reset interrupt flag and get INT_STATUS byte
mpuIntStatus = mpu.getIntStatus();
mpuInterrupt = false;

// get current FIFO count
fifoCount = mpu.getFIFOCount();

// check for overflow (this should never happen unless our code is too inefficient)
if ((mpuIntStatus & 0x10) || fifoCount == 1024)//0x10 is mask for MPU6050_INTERRUPT_FIFO_OFLOW_BIT
{
    // reset so we can continue cleanly
    mpu.resetFIFO();
    Serial.println(F("FIFO overflow!"));
    result = false; //added 01/16/19 to supress warnings

    // otherwise, check for DMP data ready interrupt (this should happen frequently)
}
else if (mpuIntStatus & 0x02)//0x02 is mask for MPU6050_INTERRUPT_DMP_INT_BIT
{
    // wait for correct available data length, should be a VERY short wait
    while (fifoCount < DMPpacketSize)
    {
        fifoCount = mpu.getFIFOCount();
        //mySerial.printf("fifo count = %d\n", fifoCount);
    }

    //07/08/18 added to watch for non-modulo FIFO counts
    if (fifoCount == 0 || fifoCount % DMPpacketSize != 0)
    {
        mpu.resetFIFO();
        FIFO_resetcount++;
    }
    else
    {
        //07/07/18 modified to read all outstanding packets
        // read a packet from FIFO
        while (fifoCount >= DMPpacketSize)
        {
            //mySerial.printf("fifo count = %d\n", fifoCount);
            mpu.getFIFOBytes(fifoBuffer, DMPpacketSize);
            fifoCount -= DMPpacketSize;
        }

        // display Euler angles in degrees
        mpu.dmpGetQuaternion(&q, fifoBuffer);
        mpu.dmpGetGravity(&gravity, &q);
        mpu.dmpGetYawPitchRoll(ypr, &q, &gravity);

        global_yawval = ypr[0] * 180 / M_PI;
        result = true; //added 01/16/19 to supress warnings
    }

    ////DEBUG!!
    //      mySerial.printf("yawdeg = %4.2f\n", global_yawval);
    //      mySerial.printf("time = %ld\tyawdeg = %6.2f\n", millis(), global_yawval);
    ////DEBUG!!
}

return result; //added 01/16/19 to surpress warnings

}
I have noticed occasional bad data points in the computed Heading values retrieved from the MPU6050, as shown in the attached plot. Any ideas what I can do about this?  Is bad value detection/removal an expected issue when dealing with IMU products like the MPU6050?

As an experiment, I excluded all points for which the rotation rate was unrealistically high, resulting in the 'Adj Hdg' line (gray line) in the plot below.  This (mostly) works, except for one instance where there were two bad values in a row.

TIA,
Frank

Looks like the major driver in the data 'noise' was the FIFO data rate, set via the MPU6050_DMP_FIFO_RATE_DIVISOR constant in MPU6050_6Axis_MotionApps20.h.  I changed the rate from 100Hz (0x01) to 20Hz (0x09) and got the following almost completely noiseless plot under the same conditions as before.  Note the vertical scale - only 6 deg total, and the one 'excursion' is only a 4 deg change. I also plotted the 3-point running average, which further reduces the excursion to less than 2 deg.
So, if you are looking for clean yaw (Heading) data from the MPU6050 DMP, consider changing the FIFO rate.
Frank


text:
Arduino Nano LED not working
I am just starting with Arduino and was trying to make the LED example work. I changed the script as follows to keep the LED on:

#define LED_PIN 12
#define LED_RX_SIG LED_BUILTIN

void setup() {
  // initialize digital pin LED_BUILTIN as an output.
  pinMode(LED_PIN, OUTPUT);
  pinMode(LED_RX_SIG, OUTPUT);
}

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

I setup the Nano board, LED and a 220ohm resistor on a breadboard. The D12 port on Nano is connected to one end of the 220ohm resistor using a jumper cable. The other end of the resistor is connected to the positive (longer end) of the LED. The negative end of the LED is connected to the GND pin on Nano. The setup is shown in the image below:

What's wrong with the setup and why the LED is not lit?
Sorry in advance for such novice question and any help will be greatly appreciated. Thanks

You didn't ask any question. What is the problem with this circuit?

Try and connect the red wire to VCC (instead of D12), to verify that the led works. The code looks fine to me. You can also try a different pin than D12. There might be a bad solder connection on D12. There's a lot of trial and error involved with Arduino.

@chirsl thanks for pointing it out; edited my post and added the relevant question

As your program is currently written, you should see your LED light. I see nothing wrong with your program or your wiring. I am also assuming that you had no errors while compiling and downloading the program.
With the rest of the lines uncommented, what you should see is your LED light up for 1.5 seconds and then off. Then after another 1.5 seconds, the on-board LED should turn on and then off (both 1 second).
If you have wired up the LED wrong (or a bad connection), you should at least still see the on-board LED flash about once every 5 seconds. If you don't see this then something else is wrong.
One thing I notice from the photos is that you have no way of powering your circuit. (I realise this may just be while you took the photo). Plug a USB cable into the Arduino and the other end into the computer. You should see the LED called "POW" light up.
To verify your LED circuit, try disconnecting the jumper at D12 and connecting it to 5V and you should see the LED light. If this works then your circuit is OK so replace the jumper back at D12.
If the LED still does not light up when the jumper is connected to 5V then we need to dive into that circuit. Possible reasons include:

The LED is dead -> replace the LED
The breadboard is not making good connection -> wiggle the leads (to scratch away any corrosion) or twist together the wires where possible or even solder them together.
The jumper wires are manufactured poorly (eg. the plastic wasn't stripped before crimping) -> check the jumper crimps.
The LED has been manufactured wrong and what should be the anode is actually the cathode (I have seen this) -> reverse the polarity of the LED.
The resistor is burnt out -> replace the resistor.

Thanks for the answer. With the lines uncommented,I do see the on-board LED flash roughly about every 5 seconds. I added that earlier to check if the circuit is receiving code. Also, it compiles successfully and also uploads without error. I tried the 3V pin, 5V pin. Still no LED. What can be wrong with the circuit? I watched a lot of videos on Youtube that used a similar circuit. I am not sure how to troubleshoot these problems. FYI, also tried D11, D10 and D9. Didn't work.

@AbrarHossain I have edited my answer and included more information to the end.

Did the extra information help? Did you get a solution to you problem?

@sa_leinard Here's what I have done so far. I bought a new Nano board, used new jumper cables and a new 220ohm resistor. Finally, the LED is blinking. Thanks for all your help. I believe the problem may have been with any of the components I replaced. I will try to debug exactly which caused the problem and update the question.

If your led does not turn on after you directly connect it to the VCC and the GND (as you mentioned in a comment) , it means that your led is most likely broken. Simply try using another Led as your circuit and code look fine.


text:
How to control baby swing?
I am starting an intresting DIY project of baby swing. My son is 3 month old and we have swing made with ropes in our house where he sleeps. I am looking for any electronic component controlled with arduino to swing it in controlled manner. I thought of servo motor but not sure how will it work. Any suggestions please ?
swing is similer to below

your question is not related to the arduino ... you may get better results elsewhere ... try this for a proof of concept ... tie a length of string to one of the ropes about 30 cm from the ceiling ... gently pull the string repeatedly using small motion ... think about how much a hobby servo would pull the string ... doing that will give you an idea about how much force is needed to get the swing going and what is needed to keep it at a steady swing

sure! Thanks @jsotola

Have you considered a solenoid? The one we used many years ago used a solenoid and a few "D" batteries, a magnet and a reed switch.

A simple DC motor would work. you have to pulse it in the right moment. for finding out the right moment and the pulse length (you don't want to push it so hard !) you need a simple accelerometer sensor to measure acceleration in specific axis.


text:
Relay starts trigger about 6 times when connecting arduino to laptop
I have a fairly simple code to turn a relay on-off every 2 seconds
When i attach the USB of the arduino Uno to the laptop, it goes into a frenzy and the relay triggers on off for 6 times within 3-4 seconds and then it settles down.
This however doesnt happen when connecting directly to the power output.
Is there something that needs to be wired to stop this happening ?
I am using an arduino Uno with a relay JQC-3FF-S-Z connected directly to the arduino pins.
const int ONOFF_TRIGGER_PIN = 2;

void setup() {
  // put your setup code here, to run once:
  pinMode(ONOFF_TRIGGER_PIN, OUTPUT);
}

void loop() {
  // put your main code here, to run repeatedly:
  digitalWrite(ONOFF_TRIGGER_PIN, LOW);
  delay(2000);
  digitalWrite(ONOFF_TRIGGER_PIN, HIGH);
  delay(2000);
}

The code is so simple, this has to be a hardware problem. Please add a schematic or  a wiring diagram to your question.

Thanks @Jrobert ive added a fritzing image. Couldnt find the the exact same relay component i have JQC-3FF-S-Z

Put a voltmeter on the pin and to ground while the Uno is starting up with the relay detached. Note any fluctuations. Now, connect the relay with the voltmeter still attached, and restart the Uno. Do you see any difference with the voltage behaviour of the pin?

Are you sure your relay works on 3V supply? JQC-3FF-S-Z operates on 5VDC.

@stevieb - i dont have a voltmeter :(
So this issue only happens when connecting it to the computer. Not when its connected to just a power supply. Means that i have to connect pin 2 after the arduino has "booted"

@hcheung - Ive tried it on both 5v and 3v. it works on both.

The thing is that if you see your relay flicking on and off, it suggesting that you are not having enough power or current supply. So if it is 5V, uses 5V. The 3V on Arduino Uno is weak and not support to be used for supplying a relay....

@hcheung but after the first 3-4 seconds (which i assume is the arduino booting up or something), it starts to work as per the program, So its just the initial phase.
Also, when hooking the arduno to a powersupply, the relay pins are still connected to the arduino. So maybe the arduino i have is corrupted somehow

Well, this is all "poking in the fog" as we say over here. Without measuring the supply voltage, you can't be sure. -- If you can't afford a multimeter (a simple one will do), you might try to use an LED and a series resistor and give it just enough current to be dimmed. You might be able to see fluctuations.

The markings on your relay suggest the coil is for 5VDC. But you have the coil supply wired to 3V3. Move the coil supply to 5V, and try again.

I agree with @Seamus. We don't know what might be going on with the 3v supply during boot up, but going to be marginal for a 5v even at steady state. At least try this and find out.


text:
Arduino led not blinking
#include <Arduino.h>

void setup()
 {
  pinMode(13, OUTPUT);
 }
void loop()
{
 digitalWrite(13, HIGH);
 delay(1);
 digitalWrite(13, LOW);
 delay(1);
}

I am trying to make an led glow for one second to glow and then go off but nothing happens

how did produce a wrong version of the most basic Arduino example? https://www.arduino.cc/en/Tutorial/BuiltInExamples/Blink

Your first step when facing such a problem is to read the documentation. You have 3 functions in your code, which as read in a short time, less than 5 minutes. You would have found the delay() expects the interval in milliseconds. Please do so the enxt time.

#include <Arduino.h>

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

The problem with your code is that the delay function works in milliseconds and not seconds . 1sec = 1000ms .

thanks it is working now

what is next? The "Bare Minimum" example without loop()?

True but just go a little easy in the newbie

@Juraj: The Bare Minimum Blink (https://www.arduino.cc/en/Guide/ArduinoUno#open-your-first-sketch ) works without the line #include <Arduino.h>

I use platform io for programing so in that it is important to include arduino.h maybe the person who asked is also using platform io or something similar

by increasing the delay value, you can visualize it better.
{

 digitalWrite(13, HIGH);

 delay(2000);

 digitalWrite(13, LOW);

 delay(1000);

}


text:
Can a 9V battery be used as a backup power supply (to Arduino Uno) while plugged directly into Vin and ground?
Sorry if this has been asked before, but I've read tons of threads and it seems the answer is only implied on a couple of occasions.
I'm an electrical noob, but I understand that a 9v battery plugged into a wall wort with a diode would serve as a battery backup if the power was cut from the wall wort.  I also understand that Vin on an arduino already has a diode to do this.
I'm currently powering a temp/humidity that is dumping data into MySQL using a standard A-B USB cable and 5V DC USB power supply.  I'd like to incorporate a 9V battery plugged into Vin and ground, so that if DC power turns off, I can dump the data onto the SD card instead (since my MySQL server may or not be running during an outage).

A few questions: 1) How much current does the board take when active? That helps size the battery. I doubt a standard 9V battery is large enough. 2) Is it acceptable for there to be a brief interruption? (eg. while switching supplies) 3) How long an outage are you planning for? Minutes? Hours? That helps size the backup battery.

Another question: Are you powering from USB for any reason? Except simplicity? If you powered from a wall-wart and put 12V into the power jack, then the simple solution of using a diode to Vin from a suitably-sized battery should work. (The battery would need to be 10V or less to allow for the diode voltage drops).

@Nick Gammon 1) I haven't tested this yet, but I'm sure it will be quite a bit.  The completed project will include the Uno, ethernet shield, sd card, and 2X16 LCD display.  2) A brief interruption (anything less than a few minutes should be fine) 3) Hours, most likely.  If an outage is more than a couple hours, the freezers will be emptied to reefer trucks.

@Nick Gammon  No, there's no reason I'm using USB.  I guess that's part of my question.  Is the 9V solution possible with the wall wart, because if so, I can use that.  I'm only powering off USB because that's what the uno usually comes with.  I'm not doing any data transfer with it or anything.

I doubt that the 9V battery will last hours. It might last long enough to send out a cry for help. Presumably one would be enough. But if the power goes off it might take a while for the temperature to drop enough to send an alert. You could try 6 x AA batteries - that would give you 9V and hopefully last a while. You could also test if the batteries are low with a voltage divider and an analog read. If the power goes, will you be able to use the Ethernet shield? Won't the router also be off?

Ah, right.  No, I wouldn't be able to use the shield, but that's where I would want to dump to SD.  I don't need the SD card unless the power is out and our server is down.  At that point, I could turn off the LCD and stop hooking up to the server.

I don't see how dumping to SD will save the frozen food. Anyway, with a larger battery at least it will keep going for a while.

Haha, definitely not food in the freezers!  It's adhesives/sealants that have shelf lives and need to be frozen or cooled.  We don't need to "save" them, but we need to know exactly what temp they're at at all times.  I guess my the only question left is, how do I determine what size diode I need going into Vin?

Probably any old "rectifier" diode rated for an amp or more. For example 1N4004 or similar. Once you get it all set up, make sure you test that things are happening the way you expect.

My problem with that is that the other side of the diode on the Arduino is normally powered up. So for example if you have a 12V supply in the power jack you'll have 11.3V at Vin (because of the diode drop). Thus you are pumping 11.3V into your 9V battery which won't be designed to handle it. It will probably get hot and explode.
You would need another diode specifically between the battery and Vin. And make sure that Vin is at least 10V so that the normal mains power does not charge the battery.
Bear in mind a 9V battery doesn't have much capacity. With the power LED on,  taking sensor readings, and sending data via Ethernet (if that is what you are doing) you may have only bought yourself 15 minutes.
I have a post about a temperature and humidity sensor which runs all the time from 3 x AA batteries. I think the batteries need replacing about every two years. The data is written to an SD card which you remove and plug into your computer when you want to.

when you have 9V hooked up to Vin and 5V coming in from the USB, it will use power from the 9V battery

Looks like I misread the question. @mwwalk is quite right. If you supply more than 6.6V through Vin then the circuitry switches the USB off. See here:

Vin is provided by the power jack (after a diode which drops it by 0.7V) - see blue ellipse. In any case (power jack or not) Vin goes through a voltage divider (two 10k resistors to the left of the red circle). This is compared to the output of the 3.3V voltage regulator. Therefore GATE_CMD is HIGH if Vin exceeds 6.6V. This turns off the MOSFET (green circle) and disconnects the USB power.

You're project looks pretty sweet, but unfortunately SD writing won't work for me.  I'm trying to develop a temp and humidity sensor that can be used for monitoring environmentally controlled rooms, areas, and freezers in a manufacturing facility.
I'm putting the data into MySQL so that current temp/humidity can be shown on large TVs live, as well as pulled up from anywhere in the shop via browser.

Well, you did say I can dump the data onto the SD card instead. I thought you were actively considering this.

No, when you have 9V hooked up to Vin and 5V coming in from the USB, it will use power from the 9V battery, not usb and the battery will quickly be depleted.

You are right. I misread the question as being about something plugged into the power jack.


text:
Accelerometer fix values
I use Arduino Uno with an Accelerometer ADXL345-gy-291 (the full name of the ship) i did hook it up like this

Note I'm using SPI Communication, that was the right one to use in my case.
when I plug in my Arduino here what does my serial monitor give me

as you can see, it sends back fixed values no matter the movement of the ship is.
the code I use is :
#include <SparkFun_ADXL345.h>
ADXL345 adxl = ADXL345(10);

void setup(){

  Serial.begin(9600);
  Serial.println("SparkFun ADXL345 Accelerometer Hook Up Guide Example");
  Serial.println();
  adxl.powerOn();
  adxl.setRangeSetting(16);
  adxl.setSpiBit(0);
  adxl.setActivityXYZ(1, 0, 0);
  adxl.setActivityThreshold(75);
  adxl.setInactivityXYZ(1, 0, 0);
  adxl.setInactivityThreshold(75);
  adxl.setTimeInactivity(10);
  adxl.setTapDetectionOnXYZ(0, 0, 1);
  adxl.setTapThreshold(50);
  adxl.setTapDuration(15);
  adxl.setDoubleTapLatency(80);
  adxl.setDoubleTapWindow(200);
  adxl.setFreeFallThreshold(7);
  adxl.setFreeFallDuration(30);
  adxl.InactivityINT(1);
  adxl.ActivityINT(1);
  adxl.FreeFallINT(1);
  adxl.doubleTapINT(1);
  adxl.singleTapINT(1);
}
void loop(){
  int x,y,z;
  adxl.readAccel(&x, &y, &z);
  Serial.print(x);
  Serial.print(", ");
  Serial.print(y);
  Serial.print(", ");
  Serial.println(z);
  ADXL_ISR();
}
void ADXL_ISR() {
  byte interrupts = adxl.getInterruptSource();

  if(adxl.triggered(interrupts, ADXL345_FREE_FALL)){
    Serial.println("*** FREE FALL ***");
  }

  if(adxl.triggered(interrupts, ADXL345_INACTIVITY)){
    Serial.println("*** INACTIVITY ***");
  }

  if(adxl.triggered(interrupts, ADXL345_ACTIVITY)){
    Serial.println("*** ACTIVITY ***");
  }

  if(adxl.triggered(interrupts, ADXL345_DOUBLE_TAP)){
    Serial.println("*** DOUBLE TAP ***");
  }

  if(adxl.triggered(interrupts, ADXL345_SINGLE_TAP)){
    Serial.println("*** TAP ***");
  }
}

so I wonder what was the mistake I made there?

You need to level-shift the Arduino's 5V signals to the module's I/O range of 1.7 - 3.6 V if you want to use SPI; that is, if you haven't damaged it already. I suggest you follow the tutorial here though. It employs I2C instead of SPI but is specific to your particular module. There are no level-shifters needed in this case. Simply connect VCC and CS to 3.3 V, the I2C pins to 3.3 V through 4.7k pull-ups and the GNDs together.

Those modules from Sparkfun and from Chinese suppliers already include a voltage regulator, accepting from 2.0-2.5V to 5-6V Vcc.


text:
Can you create an array for functions?
Let's say I want to create 10 functions, named Function1, Function2 until 10. Each function is used if a certain variable is equal to its number. Rather than using individual functions, I was wondering if its possible to use some sort of array concept for functions when it comes to naming? I tried reading about it and saw pointers but I honestly didn't understand what I saw about it because I'm not that adept to the language yet.

Of course this is possible, you can make an array of any data type you like. And a function pointer is a data type. But this is a broad issue, so you rather get a good book or online resource on C++ and start to learn.

Here's an example of how to do it:
jump_table.ino
int func1(int arg)  { return arg + 1; }
int func2(int arg)  { return arg + 2; }
int func3(int arg)  { return arg + 3; }
int func4(int arg)  { return arg + 4; }
int func5(int arg)  { return arg + 5; }
int func6(int arg)  { return arg + 6; }
int func7(int arg)  { return arg + 7; }
int func8(int arg)  { return arg + 8; }
int func9(int arg)  { return arg + 9; }
int func10(int arg) { return arg + 10; }

int (*jump_table[10])(int) = { func1, func2, func3, func4, func5,
                               func6, func7, func8, func9, func10 };

void setup() {
}

void loop() {
  int index = 2;
  int argument = 42;
  int result = (*jump_table[index])(argument);
  // result is 45
}

All functions stored in the array must have the same signature.  This simply means that they must return the same type (e.g. int) and have the same arguments (a single int in the example above).

You can do the same with static class methods (but not instance methods).  For example you could use MyClass::myStaticMethod in the array above but not MyClass::myInstanceMethod nor instance.myInstanceMethod:
class MyClass {
public:
  static int myStaticMethod(int foo)   { return foo + 17; }
  int        myInstanceMethod(int bar) { return bar + 17; }
}

MyClass instance;

There's a similar question over on stackoverflow.

Hi, is argument different from arg? But it seems like your code is correct.

@AndroidV11 The value of argument gets passed to the appropriate function where it available as arg (or foo in the class example).  BTW, based on your comment it sounds like you're pretty new to programming.  If that's the case I'd recommend learning more of the basics of C++ before you use this technique; it's fairly advanced and really only makes sense to use in specialized situations (e.g. remote procedure call handlers).

@AndroidV11 I just fixed a rather nasty typo in the code.  C++ uses zero-based array indices so to call the third function index needs to be 2, not 3.


text:
Arduino UPS without reset
I’m trying to figure out how to make arduino UPS (when the power goes down it should not reset the arduino). Or preferably buy something that will do that for me. I found this, but Im not sure of it will work. I will normally be using power from the outlet, but in case of power outage, I want it to run on the 3,7V li-pol battery (best would be if arduino could somehow know that its running on battery) What solution would you recommend to me?

There are charger modules, which provide power passthrough. I'm not sure if they can provide uninterrupted power during switching, but a large capacitor may help with that depending on the needed current

@chrisl and could the arduino somehow know if its running on battery or from the outlet?

@chrisl well i guess i could just power up radio transciever “directly” from the outlet

That unit does not properly charge a li-pol battery and it states that. It appears it probably would work for Ni-Cad or Pb-Acid batteries. My recommendation is get a unit designed for the batteries you are using with power pass through. Also how do you regulate it for your arduino, a boost module of some type? Showing a schematic, not a frizzy thing would help a lot.


text:
ESP32 powered for atleast a year
How to power esp32 board this one with soil humidity sensor that sends data to server via wifi every 30 minutes for something around a year on battery? What battery type and capacity should I use for that? Or is there any better board you would recommend for this pourpouse? The setup will be indoors.

There's no generic answer, it depends on the actual circuit and its power consumption. If outdoors (and some indoor setups) I'd say solar + battery.

Your question is too broad without experimental, for example, have you done the measurement of your board when it is in operation, and when it is in sleep mode? Only when you have those values, you can then decided on whether it is a suitable board or not (e.g. does it cut off the USB chip when in sleep mode)? Choosing the battery depend on your form factor and application, as well as your circuit design. You can only decide that once you done the measurement an calculation.

Okay, let's do some calculations.
Assume that device sends data for 5 seconds (turn on, connect to the Wi-Fi, and so on) and drains (according to the docs) about 0.2A.
So, it works for 5 (secs) * 48 (turn-on's) / 60 minutes per day for 365 days.
So, it works for 5 * 48 / 3600 hours per day for 365 days.
So, it works about 24 hours per year.
0.2A for 24 hours is 4.8A for 1 hour.
Assume that efficiency of the power regulator is 80%
4.8  - 80 %
X    - 100%
X = 6 A*h
So, take three (to compensate self discharge and have some headroom) standard Li-Ion cells, or mid-size (about 8000 mAh) power bank, and you well be fine.
But you shall add some external clock (powered by own CR2032 cell), that will be turn power regulator and esp-device ON every 30 minutes.

I would use ESP-NOW instead of wifi. It can boot, read, and publish in well under 500ms instead of 5 seconds. On the 32, you could also probably craft a ULP routine that would only bother to fully wakeup+report if the moisture level changes.


text:
LoRa recieves only 2-4 packets, then stops working
I'm working on LoRa project using [Ai-Thinker RA-01 SX1278 433MHz LoRa][1] with [sandeepmistry/arduino-LoRa][2] library. I modified LoRaReciever example so it looks like this
#include <SPI.h>
#include <LoRa.h>

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

  Serial.println("LoRa Receiver");

  if (!LoRa.begin(433E6)) {
    Serial.println("Starting LoRa failed!");
    while (1);
  }
}

void loop() {
  // try to parse packet
  int packetSize = LoRa.parsePacket();
  LoRa.onReceive(onReceive);
}
void onReceive(int packetSize) {

  if (packetSize) {
    // received a packet
    Serial.print("Received packet '");

    // read packet
    while (LoRa.available()) {
      Serial.print((char)LoRa.read());
    }

    // print RSSI of packet
    Serial.print("' with RSSI ");
    Serial.println(LoRa.packetRssi());
  }
}

I receive 2-4 packets successfully, but then I don't receive any, even though the transmitter is still transmitting. (If I restart my Arduino it receives 2-4 packets again).
I have both LoRa modules really close to each other (about 10 cm) could it cause the problem? - Even when I tried like 15m with walls, problem stayed.
Sometimes, the receiver gets bugged and starts receiving packets all the time (one packet like 50 times), when it's bugged like this, it doesn't stop receiving (unique) packets after any number.
Do you know where the problem could be? Thanks.
I use Arduino Mega
#include <SPI.h>
#include <LoRa.h>

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

  Serial.println("LoRa Receiver");

  if (!LoRa.begin(915E6)) {
    Serial.println("Starting LoRa failed!");
    while (1);
  }
}

void loop() {
  // try to parse packet
  int packetSize = LoRa.parsePacket();
  if (packetSize) {
    // received a packet
    Serial.print("Received packet '");

    // read packet
    while (LoRa.available()) {
      Serial.print((char)LoRa.read());
    }

    // print RSSI of packet
    Serial.print("' with RSSI ");
    Serial.println(LoRa.packetRssi());
  }
}

This is original LoRaReciever example, but I don't receive anything using it.
[1]: https://www.laskarduino.cz/ai-thinker-ra-01-sx1278-433mhz-lora-modul/
[2]: https://github.com/sandeepmistry/arduino-LoRa

start with the example code ... it seems that you made questionable changes to the example code

When using the default example code, I don’t get anything recieved at all.

I found the solution.
The problem was with calling onRecieve in loop not in setup
It should have looked like this...
#include <SPI.h>
#include <LoRa.h>

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

  Serial.println("LoRa Receiver");

  if (!LoRa.begin(433E6)) {
    Serial.println("Starting LoRa failed!");
    while (1);
  }
  LoRa.onReceive(onReceive);
  LoRa.receive();
}

void loop() {
  //do nothing
}
void onReceive(int packetSize) {

  if (packetSize) {
    // received a packet
    Serial.print("Received packet '");

    // read packet
    while (LoRa.available()) {
      Serial.print((char)LoRa.read());
    }

    // print RSSI of packet
    Serial.print("' with RSSI ");
    Serial.println(LoRa.packetRssi());
  }
}


text:
Problem with data logging in arduino environment
iam recently making a projects that include arduino, mpu6050 and bmp280 and finally i have to log that data so, iam using a microSD card module
info of the the microSD card:
Initializing SD card...Wiring is correct and a card is present.

Card type: SDHC
Clusters: 1914880
Blocks x Cluster: 8
Total Blocks: 15319040

Volume type is: FAT32
Volume size (Kb): 7659520
Volume size (Mb): 7480
Volume size (Gb): 7.30

Files found on the card (name, date and size in bytes):

first i always try to test every modules one by one to find whether they are working good and i will do that with the help Arduibo IDE example codes and my every modules including microSD card module is working well and for microSD card first used cardinfo and it works perfectly and then i used datalogger code and i also logged the data perfectly and it is actually working very very well. Then i started to write my code first for mpu6050 and bmp280 and there is no mistakes in that code and i also so got good values and then i just included the datalogger code from example in my code and after that also there is no mistakes, actually everything is perfect and i just uploaded that code to my arduino nano and see the serial monitor and it shows :
⸮?>8>?⸮8⸮>>⸮>⸮⸮?8⸮?⸮??⸮?⸮⸮?⸮

and this is the only thing that serial monitor shows !!
iam also posting last lines of upload pane, the ones that say how much program and RAM memory iam using so it will help u :
Sketch uses 27078 bytes (88%) of program storage space. Maximum is 30720 bytes.
Global variables use 1924 bytes (93%) of dynamic memory, leaving 124 bytes for local variables. Maximum is 2048 bytes.
Low memory available, stability problems may occur.
and i also screenshot that so this will help u :

and the baud rate in serial monitor is equal to baud rate in Serial.begin() and i choosed the baud rate 9600
and if i delete the data logging code from my main code then it works perfectly but if i include the data logging code in my main code then only it is not working and it shows ⸮?>8>?⸮8⸮>>⸮>⸮⸮?8⸮?⸮??⸮?⸮⸮?⸮ in serial monitor
and main thing is, this problem comes after iam adding a countdown code(basically if a press a button then for loop starts) in my main code after that only the serial shows ⸮?>8>?⸮8⸮>>⸮>⸮⸮?8⸮?⸮??⸮?⸮⸮?⸮ but my countdown code doesn't have any mistakes in it and i also checked it with out adding in my main code and it works well but when i add that in my main code it shows like that and if i delete the data logging code from my main code then everything works well including countdown and if i delete countdown code from my main code then everything works well including data logging and if i add both(data logging and countdown) in my main code then only it serial monitor shows like ⸮?>8>?⸮8⸮>>⸮>⸮⸮?8⸮?⸮??⸮?⸮⸮?⸮ and then it is not working properly
and code :
void setup() {

  Serial.begin(9600);

  pinMode(led1, OUTPUT);
  pinMode(led2, OUTPUT);
  pinMode(buzz, OUTPUT);
  pinMode(chipSelect, OUTPUT);
  pinMode(but, INPUT_PULLUP);

  s.attach(6);

  imuconfig();

  checking();

  countdown();

  delay(1000);

}

void loop() {

  oldtime = newtime;
  newtime = millis();
  elapsedTime = (newtime - oldtime) / 1000 ;

  imu();

  Serial.print(" X axis = ");
  Serial.print(totalX);
  Serial.print(" | ");
  Serial.print(" Y axis = ");
  Serial.print(totalY);
  Serial.print(" | ");

  Serial.print(F("Temperature = "));
  Serial.print(bmp.readTemperature());
  Serial.print(" *C");
  Serial.print(" | ");

  Serial.print(F("Pressure = "));
  Serial.print(bmp.readPressure());
  Serial.print(" Pa");
  Serial.print(" | ");

  Serial.print(F("Approx altitude = "));
  Serial.print(bmp.readAltitude(1011.7));// Adjusted to local forecast!
  Serial.print(" m");
  Serial.print(" | ");

  Serial.println("");

  data();
}

void countdown() {

  v = digitalRead(but);

  if (v == 0) {
    for (int b = 0; b < 6; b++) {
      int buz;
      buz = buz + 1000;
      tone(buzz, buz);
      delay(100);
      noTone(buzz);
      delay(100);
    }

    Serial.println("COUNTDOWN STARTS !!");
    Serial.println("DURATION IS 60s");

    for (int x = 0; x < 60; x++) {

      Serial.println(y);
      v = digitalRead(but);

      if (v == 0) {

        Serial.println("LAUNCH SCRUBBED !!");
        tone(buzz, 100);
        delay(1000);
        noTone(buzz);
        while (w) {

          v = digitalRead(but);
          if ( v == 0) {

            w = 0;

          }
        }
      }
      if (y <= 60 && y > 45) {
        digitalWrite(led2, HIGH);
        delay(500);
        digitalWrite(led2, LOW);
        delay(500);
      }
      else if (y <= 55 && y > 30) {
        digitalWrite(led1, HIGH);
        delay(500);
        digitalWrite(led1, LOW);
        delay(500);
      }
      else if (y <= 30 && y > 10) {
        digitalWrite(led1, HIGH);
        digitalWrite(led2, HIGH);
        delay(500);
        digitalWrite(led1, LOW);
        digitalWrite(led2, LOW);
        delay(500);
      }
      else if (y <= 10 && y > 1 ) {
        digitalWrite(buzz, HIGH);
        delay(500);
        digitalWrite(buzz, LOW);
        delay(500);
      }
      else if (y = 1) {
        tone(buzz, 600);
        delay(1000);
        noTone(buzz);
        delay(500);
      }
      y = y - 1;
    }
  }
}

void data() {

  File dataFile = SD.open("datalog.txt", FILE_WRITE);
  if (dataFile) {
    dataFile.println(totalX);
    dataFile.close();
  }

  else {

    Serial.println("error opening datalog.txt");

  }
}

and this not my full code but this is where the problem is
and i really don't know why this is happening and if anyone know what is really going on pls pls pls pls say and pls help me to solve this problem, pls pls

Sounds like a lack of RAM and you're getting buffer overflow / corruption. Optimize your code to reduce RAM usage (wrap string literals in F() for a start) to see if that helps.

yes i also tried that but it didn't work

I agree with Majenko.  Your compile report shows 88%/93% Flash/RAM usage - WAY TOO HIGH

thanks for saying


text:
Serial.println Issue with Flame Sensor
I'm really new to coding and Arduino so I would be eternally grateful for the help.
I'm trying to make a really basic flame sensor that beeps, lights up an LED and displays the distance from the sensor to the flame when activated. I keep getting a "'Serial' does not name a type" error message for the line that reads - Serial.println(analogRead(A0));
I’ve tried to figure it out from the information on this forum of similar questions to try to correct the issue but it seems like every time I fix one thing another 2 errors come up. I’ve been stuck on this one for a little while so I’m hoping I might be able to receive some kind of assistance from the Arduino community.
Below is the entire code - any help is appreciated, thanks :)
int Led = 4;
int Buzz = 7;
int Sensor = 11;
int Fire = HIGH;
void setup()
{ Serial.begin(9600);
pinMode(Buzz,OUTPUT);
pinMode(Sensor,INPUT);
pinMode(Led,OUTPUT);
}
void loop()
{
Fire = digitalRead(Sensor);
if(Fire == HIGH);
Serial.print("analog Read = ");
Serial.print(analogRead);
}
Serial.println("HELP! A FIRE!");
digitalWrite(Buzz,HIGH);
digitalWrite(Led,HIGH);
delay(200);
digitalWrite(Led,LOW);
delay(200);
Serial.println(analogRead(A0));
}
else
{
Serial.println("No fire detected");
digitalWrite(Buzz,LOW);
digitalWrite(Led,LOW);
}
delay(500);
}

You should learn to properly indent your code. You'd soon see the problem then.

You should also learn the difference between ( and {. And a tutorial like https://www.youtube.com/watch?v=QO_Jlz1qpDw or equal is recommended.

First things first; please INDENT YOUR CODE. The code you posted is a mess and I took at least double the time to fix that.
First, you have an extra closing curly bracket at line 17 and the if (Fire == High); should be changed to if (Fire == High){
Fixed code:
int Led = 4;
int Buzz = 7;
int Sensor = 11;
int Fire = HIGH;
void setup()
{
  Serial.begin(9600);
  pinMode(Buzz,OUTPUT);
  pinMode(Sensor,INPUT);
  pinMode(Led,OUTPUT);
}
void loop()
{
  Fire = digitalRead(Sensor);
  if(Fire == HIGH){
//Serial.print("analog Read = ");
//Serial.print(analogRead);
    Serial.println("HELP! A FIRE!");
    digitalWrite(Buzz,HIGH);
    digitalWrite(Led,HIGH);
    delay(200);
    digitalWrite(Led,LOW);
    delay(200);
    Serial.println(analogRead(A0));
 }
 else
 {
    Serial.println("No fire detected");
    digitalWrite(Buzz,LOW);
    digitalWrite(Led,LOW);
  }
  delay(500);
}

it looks like the answer helped https://stackoverflow.com/questions/58576149/trying-to-make-a-flame-sensor-code-is-giving-me-the-opposite-to-the-desired-ef

@Jurag can you flag that as a dupe?

no, it is a different question and a different site. it is a follow-up question

Well he took my answer, added a else if, and say that it is his own code. I don't have enough rep over there to comment, can you help me call it out?

you have the thank you in the question :-). the user60250 account is unregistered, so temporary.


text:
Is there something like a Virtual Environment for Arduino?
I'm using Arduino IDE for a variety of projects.
The libraries and boards used in different projects are different and I would like to have a customized environment for each project.
Eg: In a project involving an Arduino, I don't want all the ESP boards or Adafruit libraries that I might use on another project.
Python has something called Virtual Environments, where you can switch between environments and have a different setup of libraries and configurations for each project.
Is there something like this I can configure for Arduino?

Development environment like PlatformIO allow you to have your dependency libraries installed on per-project basis. It can be installed on Atom Editor or VSCode as a plug-in.

in Arduino IDE you can set the sketchbook folder

you can use GIT; all the config is "rest"ful; lives in files.

Has someone ever tried to run the Arduino-cli in a docker container? Just one crazy thought

Sorry, but in Arduino IDE no such functionality as virtual enviroment. To add your own version of libraries to each projects you may only add it (libraries) directly to a project dir.

in Arduino IDE you can select the sketchbook folder. it contains the sketches, libraries, custom hardware specs. that is a much cleaner solution then adding libraries to sketch.


text:
How come `MyClass.MyStaticMethod()` doesn't work, but `Serial.begin()` does?
MyProject.ino:
#include "MyClass.h"

void setup()
{
  Serial.begin(9600);
  // MyClass.MyStaticMethod();
  MyClass::MyStaticMethod();
}

Both uncommented lines work, but the commented (when uncommented, of course) results in this error: expected unqualified-id before '.' token.
Now, I know this is because of the incorrect scope-resolution. Yet, how come Serial manages to call static functions without the need to use :: to correction to scope-resolution.
How come MyClass.MyStaticMethod() doesn't work, but Serial.begin() does?

. is used to call a method on a class instance whereas :: is used to call a static method within a class itself.
There is no Serial class - Serial is merely an instance of the HardwareSerial class.
#if defined(UBRRH) && defined(UBRRL)
  HardwareSerial Serial(&UBRRH, &UBRRL, &UCSRA, &UCSRB, &UCSRC, &UDR);
#else
  HardwareSerial Serial(&UBRR0H, &UBRR0L, &UCSR0A, &UCSR0B, &UCSR0C, &UDR0);
#endif

If you want to use . then you have to instantiate your class and not use a static method:
class MyClass {
    static void myStaticMethod() {
    }
    void myMethod() {
    }
};

MyClass Fred;

// ...

Fred.myMethod();
MyClass::myStaticMethod();

Ah. That was quite the misnomer since instances are usually with a lower case. I thought it was a class. :)

That is the normal way, yes - but since when have Arduino done things normally? ;)

If a newcomer (myself) is just beginning to see abnormalities, I can't imagine how many you've found. :)


text:
Audio sampling and serial communication
tl;dr: The sample rate of my code seems to be lower than what I expect it to be. How can I fix this?
Director's cut:
I am trying to sample audio data and send it via serial. The setup consists of a guitar plugged into an amplifier (about 10x) + low-pass filter (second order, around 1kHz) + voltage divider (centered at 2.5V), that is then connected to and Arduino Uno Rev3. When the Arduino receives a 'cap' command via serial, it enables the interrupt-based function that takes samples and sends them via Serial. With the 10-bit resolution, it gives me a number between 1 and 4 digits. With a baud rate of 115200 and adding 1 byte for the '\n' character, the slowest rate is of 2880 values per second, but most likely around 3.6k values per second (3+1 characters).
From what I understood (not used to working with timer interrupts), I've set up timer1 so that it doesn't have any prescaling, and it should be running pretty close to 2048Hz. The interrupt sequence reads the data at the analog input and sends it via Serial (for now, to the computer; later, a smartphone via Bluetooth).
To check if it is working, I am copying the data received by the computer, putting it into Matlab and running the sound(data, sampleRate) function. If I run it with 2048 as sampleRate, I get a clearly higher pitched sound, which indicates that the sample rate is in fact lower. Testing different values, I found that it sounds close enough around 1900.
From what I've read, the serial and the timer interrupt work in parallel, and the serial is faster than the capture. Why am I getting this apparently lower sample rate? How can I fix this?
Code:
// Variables
const int sampleRate = 2048; // Sampling rate
const int numSamples = 2048; // Number of Samples
//volatile int samples[numSamples]; // Data array
int currentSample = 0;
boolean capturing = false; // flags if it is in capture mode
boolean done = false; // flags if the capture is done
char chrCommand; // holds current character read
String strCommand; // joins the complete command string

// Functions
void captureSample();
void readCommand();
void executeCommand();

void setup() {
  /****************
   * Timer Setup
   ****************/
  cli(); // stop interrupts
  // set timer1 interrupt at 2048Hz
  TCCR1A = 0; // set the entire TCCR1A register to 0
  TCCR1B = 0; // set the entire TCCR1B register to 0
  TCNT1  = 0; // initialize counter value to 0
  // set compare match register for 2048Hz increments
  OCR1A = 7811; // = (16*10^6) / (sampleRate) - 1
  // turn on CTC mode
  TCCR1B |= (1 << WGM12);
  // no prescaling
  TCCR1B |= (1 << CS10);
  // enable timer compare interrupt
  TIMSK1 |= (1 << OCIE1A);
  sei(); // allow interrupts

  /****************
   * Serial Setup
   ****************/
  Serial.begin(115200);

  pinMode(13,OUTPUT);
}

void loop(){
  if(!capturing){
    // Case: waiting for command
    if(!done){
      if(Serial.available() > 0){
        readCommand();
        executeCommand();
      }
    }else{
      done = false;
    }
  }
}

/************************
 * Function Definitions
 ************************/

// Timer function
ISR(TIMER1_COMPA_vect){
  if(capturing){
    captureSample();
  }
}

void captureSample(){
  //samples[currentSample] = analogRead(0);
  Serial.println(analogRead(0));
  ++currentSample %= numSamples;
  if(currentSample == 0)
  {
    done = true;
    capturing = false;
  }
}

void readCommand(){
  strCommand = "";
  while(Serial.available() > 0)
  {
    chrCommand = ((byte)Serial.read());
    if(chrCommand == '\n')
    {
      break;
    } else
    {
      strCommand += chrCommand;
    }
    delay(1);
  }
}

void executeCommand(){
  // Command cap = capture
  if(strCommand == "cap"){
    capturing = true;
    return;
  }
  // Command mov = move
  if(strCommand == "mov"){
    // get the motor movement in the following command
    readCommand();
    moveMotor();
    return;
  }
  if(strCommand == "clr"){
    done = false;
    capturing = false;
    for(int i = 0; i < 2; ++i){
      digitalWrite(13,HIGH);
      delay(50);
      digitalWrite(13,LOW);
      delay(50);
    }
    return;
  }
}

If you run with different (higher) baud rates does the sample frequency change?

I've increased the baud rate and it seems to be working fine. For now, I think this will work, unless something limits my baud rate. Thank you!

You calculation of the data rate is wrong:

Serial.println() adds CRLF (i.e. "\r\n") to terminate the line,
That's 2 bytes, not one.
Each byte is sent by the serial port as one start bit, followed by 8
data bits, followed by one stop bit. That's 10 bits in terms of
timing.

In the worst case scenario (value ≥ 1000), you are sending 6 bytes,
or 60 bits: the fastest possible rate is 1920 samples per
second. In the arguably most common case (100 ≤ value < 1000), you send
50 bits per sample at up to 2304 S/s.
Edit: Here are a few optimization tips, just to make sure your
program is not CPU-bound:

Declare captureSample() as static, this way the compiler can
inline it and save the call overhead.
Make currentSample unsigned, this way the compiler can optimize the
modulo operation into a bitwise AND.
Replace analogRead(0) with a direct read of the ADC register, and
start the next ADC conversion right away. This way you do not have to
wait for 104 µs while the ADC does its work.
You may want to move the Serial.println() out of the ISR, otherwise
you may be blocking interrupts for too long if the serial port cannot
cope with the sampling rate.
Make some kind of binary protocol instead of using plain ASCII.

You may also trigger the ADC directly from a timer instead of going
through the timer ISR (see the datasheet for details). You would then
use ISR(ADC_vect) to retrieve the ADC result. This way you get a very
steady (hardware controlled) sampling rate.
More about the binary protocol: you could send only two bytes per
sample and remain ASCII-compatible (which is often desirable) by using
32 printable characters to represent 5 bits. This is the same idea used
in base64, but simplified to use consecutive characters:
uint8_t high_5_bits = sample >> 5;
uint8_t low_5_bits  = sample & 0x1f;
Serial.write('@' + high_5_bits);
Serial.write('@' + low_5_bits);

This gives a stream of characters in the range @A-Z[\]^_. Then your
maximum sampling rate is 5760 S/s.

Following @Majenko's suggestion, I've increased the baud rate and it seems to work fine. Still, I will try to implement these tips, make it better. Thank you very much for the answer!


text:
ESP 01 - reset settings to default values
I set up communication between Arduino UNO and ESP 01 module. ESP replied to AT commands, but sometimes I got result from ESP uncompleted or with wrong characters, so I tried to set AT+IPR=9600, I didnt receive any output to this command and after reboot I only can see random characters on every baudrate, blue diode on ESP shines all the time. Is there any way how I can reset ESP 01 to default settings? Tried to set RESET pin to GND, but it didnt help.
I use remote power supply 3,3V/1A
Pins connected:
Vcc = external power supply 3,3V
GND = GND (interconnected bot Arduino and power supply GND)
Tx = Arduino Rx(changed pin to 11 by SoftwareSerial)
Rx = Arduino Tx(changed pin to 10 by SoftwareSerial)
CH_PD - 3,3V

reflashing will reset it

Current ESP-01 firmware versions do not have an AT+IPR command. If you're trying to change the ESP's baud rate to use it with SoftwareSerial, the command to do so (in recent versions of the firmware) is: AT+UART=9600,8,1,0,0 for 9600 baud, 1 stop bit, no parity, no flow control.
The full syntax is: AT+UART=<baudrate>, <databits>, <stopbits>, <parity>, <flow control>, where <databits> is the number of data bits per frame, 5,6,7,or 8; <stopbits> is 1, 2, or 3 for 1, 1.5, or 2 stopbits (respectively); <parity> is 0, 1, or 2 for None, Odd, Even (respectively); and <flow control> is 0, 1, 2, or 3 for None, RTS, CTS, RTS and CTS (respectively). Most serial communication and devices that most of us will ever see will be 8 data bits, no parity, and 1 stop bit, abbreviated as "8N1". Flow control is sometimes used, but often it is contained in the data stream itself, such as sending Ctl-S and Ctl-Q from the keyboard to manually stop and resume incoming data transmission.

While this technically is not an answer, I can highly suggest the ESP 8266 Arduino library. This way you can program in the Arduino IDE and upload to the ESP module. It's so much faster and efficient than AT commands and because you can see the code in the IDE, you have a better overview of what is happening in the code.
https://github.com/esp8266/Arduino


text:
Programming Arduino With Python
Im a beginner working with arduino.
Im little familliar with java syn and its not hard for me to do the work with ide ;but i know python better....is there any Lib that let you program Arduino with Python?

This page on playground lists a number of links on the subject. As a matter of fact, the first paragraph hints how you may use python on your pc to interact with an arduino over a serial connection.

This has been asked before.

Here is a page on interfacing Arduino with Python.
Interface Arduino with Python