Using a water sensor with a NodeMCU make it less sensitive?

You are using it wrong.

That sensor (crude as it is) is an analog sensor. It's not designed to be used connected to a digital pin.

It outputs an analog voltage proportional to the resistance between the tracks in the sensing portion.

By feeding that voltage into a digital pin you are relying on the logic threshold values, plus any other components (pullup resistors, etc), to give you a "wet" or "try" signal.

Since pins differ (some have pullups, some pulldowns, some nothing, etc) and the logic thresholds are only an approximation in any case, it's doomed to failure.

You need to connect the sensor to an analog input and compare the value read to a threshold value of your choosing.  However the ESP8266 is very very poor when it comes to analog - it only has one analog input, and that is only capable of sensing between 0 and 1 volt.


Arduino PRO Mini - The pads [was "jumpers"] on the back and Low Power Consumption

Both responses are correct but be mindful that this is a SparkFun feature.  An Arduino Pro Mini from China won't necessarily have the SJ1 pad.

1) Like Gerben said, the pads on the underside of the board are for I2C pull-up resistors.

2) Like David said, SJ1 is on the top of the board next to the GND and RST pins.  (It looks like a small solder blob.)

3) To isolate the regulator from VCC, remove the solder blob on the top of the board with a sucker or solder wick.

The Sparkfun schematic shows all of these elements:
https://cdn.sparkfun.com/datasheets/Dev/Arduino/Boards/Arduino-Pro-Mini-v14.pdf


connecting SIM900A GSM/GPRS module Arduino Mega

From your pic, it looks like the upper left corner has a jumper with TTL level TX, RX, GND.


They are the conditional operator. If the expression before the ? is true then the result is the expression before the :, otherwise it is the expression after.


analogWrite is not working - while trying to control DC motor speed

Well, 2M resistor to the base? If the motor is running with that, the transistor must be broken (shorted). Just try to check if the motor is running with disconnected base.

You can also check PWM output by connecting LED with resistor (no, not 2M ohms, just about 330 ohms). For the transistor 1k should be sufficient maybe little less (depends on motor current and h21e amplification coeficient).

Also there are some versions 2N2222 with emitter and collector swapped. And reversed transistor has much lower current amplification coeficient.

And I hope you are using external power supply, USB is not a good idea. Starting power is usually way too much for the overcurrent protections.

Anyways, this works for me:

void setup() {
  pinMode(9, OUTPUT);
}

void loop() {
  analogWrite(9, map(analogRead(A0), 0, 1023, 0, 255));
  delay(100);
}

2N2222A + 1k + PC FAN + 12V Fan Power supply.

Connections: E -> Gnd, C -> FAN-, FAN+ -> 12V, 12V GND -> Arduino GND, Pin 9 -> 1k -> B

On the Arduino side 47k trimmer and the USB


Reading FAN tachometer/RPM on 4 wire fan using arduino

There are no interrupts on pin 9 (unless you are using Pin Change interrupts...?). You have to use pin 2 (interrupt 0), or pin 3 (interrupt 1) (also, on the Mega: 18 (interrupt 5), 19 (interrupt 4), 20 (interrupt 3), and 21 (interrupt 2)).


Project structure to build for PC and Arduino

I haven't done it yet, but you could do the following things to get a somewhat close approximation:

Make three different projects, one for the PC (only), e.g. Visual Studio, and one for Arduino (with the default Arduino IDE or e.g. Visual Micro). The last will be a generic library to be used for both the PC and Arduino.
Use the Arduino specific libraries only for the Arduino project.
Create facade/wrapper classes for each Arduino library.
Use a mock/stub for the Arduino libraries in the PC only project.
Put all non-hardware related code in separate classes, to be used by both projects.
Write unit tests for the PC only project.
The PC project will be tested by unit tests, and can be debugged on a PC
Only the specific Arduino libraries/interfaces have to be tested using the 'hard way', e.g. with Serial.

So the projects (including testing) will look like:

PC Project

References common code
Stubs for Arduino libraries, stubs can possibly be reused by PC Unit tests

PC Unit Tests

Unit tests
References common code

Arduino Project

Containing Arduino libraries
References common code

Common Code

All domain specific classes


I hate to say it, but a multimeter would really come in handy for you.  Harbor Freight has some for under $10.

That said, without knowing anything specific about what you are using, you could try using the same LED you used to test power and put it in parallel with one of the LEDs on the matrix.  I'm guessing you don't have power at the LEDs though because it seems unlikely that all the LEDs would fail.  Check your solder work and make sure you have not shorted anything.  Also, you could have overheated a component when soldering causing it to fail.  Good luck.


3.5" TFT LCD Display is not working with Arduino Mega 2560 R3

http://www.henningkarlsen.com/electronics/library.php?id=51

Download hennings new UTFT library.

in myGLCD define R61581 as this is the driver chip for 3.5 display.

Regards!


Converting an array of uint8_t to a char array

When you cast as char *, println thinks you are passing it a string. It will try to print it as a string and stop on the first 0x00.

You can use Serial.write to send the array as integers (no conversion):

Serial.write(data, sizeof(data));

If you want to send the ASCII representation of these numbers, use a loop. Serial.print will convert:

int count = sizeof(data) / sizeof(data[0]);
for (int i = 0; i < count; i++) {
    Serial.print(data[i]);
}
Serial.println();


Arduino: Sending SD CSV file online at specific time of the day

Well for CSV, you might as well do dataFile.print(",");. It will log a comma and thus separating your values with a comma.

For logging your data at the end of the day, you have multiple ways.

1- Use a delay (worst idea EVER! Don't do this!). This will require you putting delay(86400000);. Yes that is indeed a 24h delay!

2- Use the millis() function. This function returns the number of milliseconds since the programmed started running. There is an example code called blinkWithOutDelay(or something like that). This method is somewhat "ok" but after 49 days there is a rollover which makes things complicated. To solve that rollover, see here.

3- Use a RTC. RTC stands for Real Time Clock. It is pretty much a module that keeps actual time even if the power to your project is disconnected. There are many popular models out there such as the DS3231. There are many libraries for it. You can do so that each day, at a specific time, it logs the data to your SD card.

Now to send the data. You have may options for this too.

1- Use an Arduino Ethernet shield. This will connect your Arduino to the Ethernet via an Ethernet cable. From there, you can either log your data to a Google Sheets file or a custom web server. Many tutorials out there for you.

2- Use an ESP8266. With this Wifi module, you can easily host your own web server with it. Note that This makes it somewhat harder for your code then simply using an Ethernet cable but it makes you project wireless. Note that if you do use an ESP8266, you can put the Arduino aside. The ESP has many GPIOs that can be used to do many things, but I'll still suggest keeping the Arduino for sake of simplicity. Again, many tutorials out there.

Note that there are many cloud services out there. A quick Arduino IOT search will bring out many result and interresting projects ideas for you.


Multiple external power sources and one Arduino

Besides connecting all the grounds, a "good idea" whenever working with solenoids or magnetic (as opposed to solid state) relays is to add protection against inductive kickback, which can create really high voltages (hundreds of volts) when the current through an inductor changes suddenly. (The voltage is the product of the inductance and the rate-of-change of the current.)  The protection is simple:  Put a rectifier diode across each coil, with the arrow pointing to positive (reverse-biased).  The rectifier has to handle a big spike of current as well as the high voltage, so use something like 1N4004.
This protection will reduce the likelihood of spikes causing mysterious state changes in your circuits.


How to wire up 4-digit 7-segment display?

The first thing you do is ask Google for a datasheet.  It tells you: http://www.robotshop.com/media/files/pdf/datasheet-com-09483.pdf

Then you can read the datasheet and find the pin diagram:

That tells you that it is a Common Anode LED display - which means that for each digit all the Anodes (positive pins) of the LEDs are wired together.

Further, all the cathode (negative) pins of the LEDs for the same segments across the digits are connected (that is the cathode for segment A on digit 1 is connected to the cathode for segment A on digit 2, digit 3 and digit 4, etc).

From that you can then infer that you need to provide current for each digit in turn through its common anode pin, and sink current from the segments you want to have lit for the digit that is currently having its current sourced.

The diagram also shows you which pin on the display is for what function - the common anodes are pins 9, 10, 12 and 13, with pin 11 the common anode for the extra dots.

The datasheet also tells you which pin is pin 1 - in this case the one in the bottom left when you have the display facing you and the numbers the right way up.  The pins count anti-clockwise from there, so 2 is to its right and 13 is above it.

By the sounds of it though you may not have the same display as in that datasheet.  If your display lacks the extra dots then it may not have the LEDs on pin 11, and pin 12-13 may be moved down one, so you have 4 commons on 9, 10, 11 and 12 with no pin 13.

So the four digit select pins in your program are wired to pins 9, 10, 12 and 13, and the segment select pins connect to pins 1, 2, 3, 4, 5, 6, and 7.  Don't forget the resistors on all the segment pins to limit the LED current or you will damage the Arduino.

You can do some manual testing of the display by using two wires and a resistor (say 1KΩ).  Connect the resistor to +5V, and one wire to the other end of the resistor.  The other wire you connect to ground.

You then take the loose ends of the wires and try probing pins.  Start with the 5V wire touching pin 9 and connect the other one in turn to pins 1-8 to see if the first digit's segments light up.  Repeat with the 5V wire on pins 10-12.

Edit:

If this (http://mklec.com/displays/7-segment-4-digit-12-pin-common-anode-display) is indeed the same display as yours you can ignore the numbers I mention above and work from the pin numbers on that page.  The same principle applies though, just the pin numberings are different.


Arduino IDE doesn't release COM port after programming

To force the Arduino IDE to disconnect from the COM port, simply go into the Tools menu, go to Ports and select another COM port.

Alternatively, you can open and then close the serial port monitor (Ctrl+Shift+M then Alt+F4).


As noted in comments, enable verbose compilation and look at the output to find the temporary-directory location. (Click File, Preferences, verbose compilation.)

Note, after you click File, Preferences and the preferences window appears with its half-dozen items, you should also see a note about directly editing preferences in the preferences.txt file.  Edit that file (using a plain-text editor, not a word processor) when the arduino IDE is not running.  Change the line

preproc.save_build_files=false

to

preproc.save_build_files=true

so the .hex files in the temporary directory have a better chance of sticking around.

(I'm not able to test this suggestion on an MS-Windows system.  On my Linux system most build files stick around anyway in /tmp/)


You do not have a problem with LED blinking (although there seems a resistor missing for your led), but with uploading a sketch.

Hard test: switch off your computer, remove USB cable, switch on computer, check the COM port appearing when connecting the Arduino via USB cable. Then start IDE and try upload again.

Eventually something else was blocking the COM port.


Replace digitalWrite with a selective bitwise operation

Personally I'd expand it out a little:

if (commandbits & (1 << i)) {
    PORTB |= (1<<3);
} else {
    PORTB &= ~(1<<3);
}

It's far more readable, and there are less shifts to mess around with. Plus the AVR has bit set and bit clear operations which that will make use of, especially since it's now using literal values. You could actually replace those values with literals:

if (commandbits & (1 << i)) {
    PORTB |= 0x08;
} else {
    PORTB &= 0xF7;
}


Send stepper to position and back AccelStepper

Gerben's comment:

  You need to call stepper.run() instead of runSpeed, for moveTo to work.

provides the answer. The updated code is:

#include <AccelStepper.h>

AccelStepper stepper(1, 5, 4);

int spd = 1000;    // The current speed in steps/second
int sign = 1;      // Either 1, 0 or -1

int buttonState = 0;

void setup()
{
  Serial.begin(9600);
  stepper.setMaxSpeed(1000);
  stepper.setSpeed(1000);
}

void loop()
{
  char c;
  if (Serial.available()) {
    c = Serial.read();
    if (c == 'f') {  // forward
      sign = 1;
    }
    if (c == 'r') {  // reverse
      sign = -1;
    }
    if (c == 's') {  // stop
      sign = 0;
    }
    if (c == '1') {  // super slow
      spd = 100;
    }
    if (c == '2') {  // medium
      spd = 900;
    }
    if (c == '3') {  // fast
      spd = 1000;
    }
    if (c == '4') {
      //not working, does anyone know how to do this?
      stepper.moveTo(500);
    }
    stepper.setSpeed(sign * spd);
  }
  stepper.run(); //You need to call stepper.run() instead of runSpeed, for moveTo to work. – Gerben
}


The WiFiMulti has nothing to to with the MQTT and TLS side of things at all.  It only has anything to do with the WiFi.  As such it just replaces the code that directly interfaces with the WiFi.

That is, this code:

WiFi.begin(ssid, password);

while (WiFi.status() != WL_CONNECTED) {
  delay(500);
  Serial.print(".");
}

is replaced by this in the global scope:

ESP8266WiFiMulti wifiMulti;

This in setup():

wifiMulti.addAP("primary-network-name", "pass-to-primary-network");
wifiMulti.addAP("secondary-network-name", "pass-to-secondary-network");
wifiMulti.addAP("tertiary-network-name", "pass-to-tertiary-network");

and this in loop():

wifiMulti.run();

All the MQTT side of things remains exactly the same.


I had to install the SiLabs CP2104 drivers and reboot.
Make sure you don't have 2 connection (Arduino IDEs, VS Code with PlatformIO, ...) open. Also, I kept pressing the reset button the first time.

https://learn.adafruit.com/adafruit-feather-huzzah-esp8266/using-arduino-ide


Error opening serial port 'COM1'. (Port busy)

I've got an idea. Your board isn't being recognized. Try unplugging the arduino and see if Com 1 is still there. Sometimes it can recognize mice and other devices as Com 1 or 2 instead of your arduino.

On some of my development machines after everything settled out my devices will show up on Com 4 and 5 when I am working on two at a time.

If this is not the case go into the device manager and see if you can see the board listed.

I would also wonder if you have your sensor hooked to digital pins 0 and 1. These pins are used for your serial line on usb. So if you have anything such as a sensor hooked to them it may be generating data keeping the line busy instead of it being able to negotiate.

I had this happen when setting up hc-05 for the first time. I realized I had to keep the chip off while flashing or I would end up with errors or Com busy.

Please provide your pinout and basic information about the Com ports available on the ide. Also consider that you will need to specify the correct board as it will default to an uno.

Programmer not in sync issues generally occur because the board is recognized but cannot be written to for one reason or another.

the board has something plugged into digital 1 and 0 which are serial i/o pins
the board programmer is busy running your last batch of code
usb error

So

try a different cord
try unplugging potential wiring issues and see if it can be written to without anything on it
try holding down reset on the board until the board when you try to write to it until just after it finishes compiling to clear any potential programing issues

In my experience mega have a tendency to suffer from the last one.


Serial monitor listing unreadable characters

Change Serial.write to Serial.print (or Serial.println).

write writes in binary, which gives you unprintable characters.


Bootloader only works once with usb to serial module

The module I had does not have a DTR signal. I mistook the RTS for DTR. Ordering correct module.


Any time you have the same sequence of code repeated over and over with slight variations, that is a "code smell" (an indication that you may be using the wrong approach.)
You should use arrays of pin numbers as you have in the first couple of commented-out lines, and write code that loops through those arrays, as well as functions that take parameters and can do the same thing using different values that are passed in.
Don't try to tackle a problem like this without learning the skills and concepts you need. You said "...I am new to Arduino and arrays , and now I'm focusing on solving buzzer problem." That is a mistake. Code like you have posted is hard to write, hard to read, and much harder to maintain.


The esp8266 Arduino package has 3 libraries for firmware update.

ArduinoOTA for upload from Arduino IDE
ESP8266HTTPUpdateServer for upload with web browser
ESP8266httpUpdate library to check a web server for new version of the
firmware


A Yun is like a Leonardo with a CPU running GNU/Linux at its side. If your sketch works with a Leonardo, it's likely to work with a Yun.

Uno has a different MCU and thus not every sketch will just work, especially those using the hardware serial. You'll have to convert them.


DHT11 sensor works on Arduino Uno, not on LoLin NodeMcu

The datasheet says 3V-5V. 3V is the minimum so I DOUBT that isn't the problem, BUT try to pump more juice into it to see what happens. Never believe the datasheet if these cheap components at 100%.

It does say this though:

  VDD=5V, T = 25℃ (unless otherwise stated)

So maybe....

Link to datasheet.


Your problem is not with your code. It's with how you're linking your elf file.

You haven't specified the chip to link for.

$ avr-gcc -mmcu=atmega328p boot_loop.o -o boot_loop.elf


Com 20 is not configured with your arduino. Go to the arduino program and I think it is on the tools tab or the one next to it. There should be a port label and it says which com port to use. Then go to device manager, then ports. Then go to properties on the port that has arduino and change that to the port the arduino program said. It should work then. This topic has been solved many times.


Saving Arduino output to a text file in append mode

There are a couple of ways to append to a text file.

You can either read the entire file in a temporary variable, then append the new data to it and then write to file.

you can implement using printWriter instead like mentioned here:
https://processing.org/discourse/beta/num_1267767630.html

Let me know if it works.


Trying your fuse settings on an
AVR fuse calculator shows that you
have selected an “external full-swing crystal” as the clock source.
Now your ATmega won't work unless you connect it to an external crystal.
Or you could try just sending a square wave into the XTAL1 pin. Then
you can try to reprogram it.


Flow meter using Wemos Mini - ISR not in IRAM!

This happens because of conflicts between Serial and external interrupts
Put ICACHE_RAM_ATTR before your interrupt function, like this  ICACHE_RAM_ATTR void ISR()


You receive the character 0 or 1 but compare it to the value 0 or 1. The two things are very different.

You are sending ASCII but comparing it to decimal.

Instead you need to compare like for like.  Either:

if (payload[0] == '0') {

Or:

if (payload[0] == 48) {

You can find an easy reference for the full ASCII table here.


Check the datasheet, probably just search for "internal" or "pullup"  I believe there are little more pins/ports as portB, so they should all have internal pull ups.


Driving multiple LED arrays with shift registers

You haven't provided enough information to allow definitive answers to your questions, but you can apply LED resistor calculators and formulas to determine how much current is available to drive LEDs of various voltages.

Here is an example:  Suppose you hook up a red LED that drops about 1.6 V when it's on and operating at a current of 5 to 25 mA.  Suppose the LED is in series with a 550 Ω resistor, between a 5 V source and ground.  Current will be about (5-1.6)/550 A ≈ 0.0062 A = 6.2 mA.

If you wished to limit current through Arduino Uno pins to safe-area amounts like 25 mA, you could drive at most 4 such LEDs per output pin.  If you decrease the resistor to get more current, the number of LEDs allowed per pin decreases too.

Because pin voltage drops slightly as the pin drives more current, LED brightnesses will also decrease slightly as more LEDs are attached to a pin, so putting different numbers of LEDs on different pins is likely to make light levels uneven.

Limits on output currents from 74HC595 shift register pins are similar to those on Arduino Uno pins; eg 35 mA absolute max ratings for the Qn pins.

Rather than driving LEDs directly from Uno pins or '595 pins, you can use transistor driver stages.  Most transistor drivers will allow higher voltages (ie more LEDs in series, rather than in parallel) and higher currents.  Also consider using LED driver chips; many of them contain PWM circuitry for brightness control and registers for storing drive levels.


Silly me forgot to actually upload the code that fixed my issue. The code shown in the question is correct and works as intended.


ESP8266 - Sending a software Reset Command

1/0 is an exception (divide by zero). esp8266 arduino core has soft reset: ESP.reset(). Calling this function you get a valid reset.

Note to software reset. esp8266 has a bug. If software reset (or exception) is executed in program started right after the flashing, the board goes back to flashing mode because the flashing flag is still active. Perhaps you noticed that after flashing the bootloader doesn't reset the board, but executes the flashed code.


I need a simple, low power, low cost wireless switch to transmit to Arduino

There is no such thing as a transmitter that can attach direct to a sensor, since no two sensors in the world work the same way. You need something intelligent between the sensor (to read the sensor value) and the transmitter (to tell it what to transmit).

There are "all in one" modules, like the ESP8266, which have an MCU and WiFi combined in one chip which are closer to what you want, but it is still down to you to program those modules to work how you need them to work for your sensors.


Why does pulse sensor shows gaps when I move it?

One of the possibilities is when you move your finger, the sensor grip loosened and doesn't count a "beat". So the sensor emits data = 0, and it will cause

Serial.println("");

in your switch-case.


What you are experiencing is due to the fact that your use case does not match with the Arduino foreseen use cases of "importing a library".

Basically you want the use case "include a file" and you get "import a library". The use case "import file" is simply not foreseen in the Arduino IDE.
Because the Arduino IDE add the library to your code it also adds the source doe files to your code. When these source codes contain global variables (which is very common and not a bad practise in embedded world) these will be part of your final code. As such your sketch will increase size even if you do not use these global variables.

To answer questions
1) yes it is normal because the use case "include file" is translated into "include library" in .ino files in the Arduino IDE.
Why this does not happen for the core? The core is first linked into a archive and then linked to the sketch. This leaves the linker more options to remove stuff.

2) I think the easiest is to copy the pins.h file in your sketch work folder (and you probably will need to restart the Arduino IDE).
Another option is to go for a real IDE like the arduino eclipse plugin called sloeber (which I develop)
In sloeber you could link to the pins.h file instead of copying. You could also reference the pins.h with a (partial/full) path avoinding the library include.

3) All global variables, static and similar stuff in the source code of the "imported libraries"


Ethernet Shield 2 data to PHP server doesn't work

I just removed the line server.begin() and it's works !!!
Thanks.


LED does not blink - Arduino UNO+WiFi R3 ATmega328P+ESP8266 board

The Uno+WiFi board is an Uno. With DIP switches 3 and 4 in ON position it is a normal Arduino Uno clone with CH340 chip for USB. All the pin headers at board sides and the ICSP pins are as on an Arduino Uno. Every sketch for Uno will work.
The esp8266 is added for WiFi functionality. The DIP switches allow to program the esp8266 over the CH340 or to connect the esp8226 to Serial of the Uno part (ATmega328p).
To have Serial free for USB, it is usual to wire the esp8266 to a common Uno on some other pair of pins then RX/TX and use SoftwareSerial. There is no such connection on this Uno+WiFi, but the esp8266 header has the Rx/RX pins of the esp8266 so it is possible to wire SoftwareSerial pins with jumper wires (power and ground are connected on board of course).

Don't switch the DIP switches too frequently. They are not made for it and fall apart. Upload some permanent firmware to esp8266 or use OTA upload for esp8266.


I suppose you are using a continuous servo otherwise you won't be able to make it turn 90° more than twice (a normal servo has a varying angle of only 180°).

Now if you are using a continuous servo, you have to be aware that the value you pass to myservo.write() does not represent an angle anymore!

With a continuous servo, the value passed to myservo.write() now means a speed of rotation where, but the rnage of acceptable values is the same as for a normal servo, i.e. [0; 180]:

0 means max speed clockwise
90 means no motion
180 means max speed counter-clockwise

Now if you want to turn the servo exactly 90°, then you must know the max speed of the servo, and from that, compute the time during which you must let it turn:

// Start turning clockwise
myservo.write(0);
// Go on turning for the right duration
delay(TURN_TIME);
// Stop turning
myservo.write(90);

The problem here is to compute TURN_TIME. For this, you must check the datasheet of your servo.

On my own servo, a Feetech Micro 1.3kg Continuous Rotation Servo FS90R, the max speed is:

0.12s/60° when powered with 4.8V
0.10s/60° when powered with 6V

However, with the Arduino UNO, the supplied voltage should be exactly 5V, neither 4.8V, nor 6V.

If we take a linear approximation, then we can apply the following formula to find out the speed T (in s/60°):

T = (0.12 - 0.10) * (V - 4.8) / (4.8 - 6.0) + 0.12

Hence, for 5V, we can take it for granted that the max speed should be:

T = (0.12 - 0.10) * (5.0 - 4.8) / (4.8 - 6.0) + 0.12 = 0.116667

Since we need 90°, this means we must run the servo at its max speed during:

T' = T * 1.5 = 0.175s

Hence we now have the following program:

#include <Servo.h>

#define TURN_TIME 175

Servo myservo;

void setup {
    myservo.attach(10);
    // Initially the servo must be stopped
    myservo.write(90);
}

void loop() {
    // Start turning clockwise
    myservo.write(0);
    // Go on turning for the right duration
    delay(TURN_TIME);
    // Stop turning
    myservo.write(90);

    // Wait for 12h
    delay(12 * 3600 * 1000);
}

Of course, you will need some eperiments to find the exact right values; you may also find out that the servo may be sensitive to noise and even when it should not move (value = 90), it does move (not fast, but still it moves).


Can I use IO10 as digital IO while using SPI interface?

On AVR it must be OUTPUT when using SPI in master mode and INPUT in slave mode.

  If my arduino is the master device in a SPI network, hence not using the slave select SS pin, can I use the same pin as IO10?

The SS pin (D10) has to be OUTPUT when using SPI master mode. It can be used for chip select on the SPI bus (slave select) or some other output function.

So far the Arduino design with AVR (e.g. ATmega328). The Intel Galileo based Arduino has the following block diagram:

IO10-IO14 are multiplexed from SPI1 or GPIO. This implies that the SPI SS (IO10) signal is hardwired to the SPI controller when enabled. Last, according to the product info SPI is master only. More details schematics details here.

Cheers!


Button not working - Arduino Due project (MiniEngine v2)

It was the Arduino Due issue. Arduino digital pin 43 was faulty or something. I managed to change 43 to 53 and now the button works...


Multiple power supply for arduino controlled dc motor

According to the datasheet on the L298 IC the connections you described should be right. First I would recommend to connect 10v to the + and - rails and measure the voltage on the logical inputs if it is 0 or lower than 3v than that should be ok to connect an arduino. Also now you can connect an additional 5v power supply with an the -5v connected to the - rail on the board and try to connect the +5v volts to the inputs and measure the voltages on the output (or connect an motor) if everything is ok you can try to connect your Arduino.


Without seeing the code you are using, it is difficult to know if you are attempting to drive the servo correctly.

Remember, with a servo, the PWM signal is a positioning signal, not a duty cycle signal as used with speed control on regular dc motors.


Is it possible for ESP8266WiFi client to request the number of clients currently connected to Access Point?

Use WiFi.softAPgetStationNum() to return the number of clients connected to an ESP8266 AP.


A nice solution is to use a state variable. In C/C++ (thus Arduino) you can use an enum variable for that.

enum EState
{
  // Button 1 and 2 are not pressed
  NoButtonsPressed,

  // Button 1 is pressed, button 2 is not pressed
  FirstButtonPressed,

  // Both buttons are pressed
  BothButtonsPressed
};

EState _state;

void setup() {
  // put your setup code here, to run once:
  _state = NoButtonsPressed;
}

void loop() {
  // put your main code here, to run repeatedly:
  switch (_state)
  {
  case NoButtonsPressed:
    if (digitalRead(1) == HIGH)
    {
      _state = FirstButtonPressed;
    }
    break;

  case FirstButtonPressed:
    if (digitalRead(1) == HIGH)
    {
      // Button 1 is still pressed, ignore second button.
    }
    else if (digitalRead(2) == HIGH)
    {
      // Button 1 is not pressed, button 2 is pressed.
      _state = BothButtonsPressed;
    }
    break;

 case BothButtonsPressed:
   // Switch on LED
   digitalWrite(2, HIGH);

   // Reset state.
   _state = NoButtonsPressed;
   break;

 default:
   // Other state, illegal.
   break;
  }
}

In every state you can define exactly what needs to be done. Because of the loop function being ran continuously, you just need to handle one state (change) at a time.

Additional notes:

Your requirements are not fully complete (like when to switch off the LED), probably when button 2 is released (which I don't check for), you can add a new state for this.
I did not take debouncing of buttons into account; you might need to do this especially if you check for releasing buttons. On the official Arduino website there is a good article about it.
I haven't tested the sketch.


Arduino Nano Update failure - avrdude: stk500_recv(): programmer is not responding

The Arduino.cc developers changed the bootloader on official Arduino Nanos to communicate at a different speed. Try setting Tools → Processor → ATmega328P (Old Bootloader)


74HC595 to 4 Digit 7 Segment using SevSegShift Library

Finally able to fix it with the help of @PeterPaulKiefer, I was able to find the problem. The problem is in the code itself (schematic is alright. No changes there) and this is the updated code.
#include <SevSegShift.h>

#define SHIFT_PIN_SHCP 6
#define SHIFT_PIN_STCP 5
#define SHIFT_PIN_DS   4

SevSegShift sevseg(SHIFT_PIN_DS, SHIFT_PIN_SHCP, SHIFT_PIN_STCP, 1, true);

void setup() {
  byte numDigits = 4;
  byte digitPins[] = {12, 11, 10, 9}; // These are the PINS of the ** Arduino **
  byte segmentPins[] = {0, 1, 2, 3, 4, 5, 6, 7}; // these are the PINs of the ** Shift register **
  bool resistorsOnSegments = false; // 'false' means resistors are on digit pins
  byte hardwareConfig = COMMON_ANODE; // See README.md for options
  bool updateWithDelays = false; // Default 'false' is Recommended
  bool leadingZeros = false; // Use 'true' if you'd like to keep the leading zeros
  bool disableDecPoint = false; // Use 'true' if your decimal point doesn't exist or isn't connected

  sevseg.begin(hardwareConfig, numDigits, digitPins, segmentPins, resistorsOnSegments, updateWithDelays, leadingZeros, disableDecPoint);
  sevseg.setBrightness(100);
}

void loop() {
  sevseg.setNumber(500);
  sevseg.refreshDisplay(); // Must run repeatedly; don't use blocking code (ex: delay()) in the loop() function or this won't work right
}

What changed:

Turns out my 7-segment is COMMON_ANODE so I changed my hardwareConfig
Set brightness to 100
(At this point, it shows the number in reverse but with a decimal point in each digit)
Set disableDecPoint to false
(At this point, the display is showing but in reverse but no more decimal point)

To fix this, I set the digitPins[] in reverse and it now shows the proper format

Thank you so much Peter for helping me figure out what's wrong!
Also the LED Bar I use is 4-Digit 0.36" LED, 7-segments display, common-anode. (The link is to the shop I got it from)


The ESP trys to connect to port 4160, but the server is listing on port 20.


Store & retrieve parameters after sketch update

There is no need for an SD card.
You can write all relevant parameters into a file in SPIFFS (e.g. json if you like) before starting the OTA update. During initialization you read the file and set the parameters accordingly.
SPIFFS does not get erased when doing an update (at least that's true for the OTA library that I'm using). If it does get erased in your case, there probably is an option in the OTA lib to disable flash erase, just like there is the same option when uploading a sketch via serial.


#pragma once operates on the absolute filename of a file. Include guards work on the content of the file.

If you have multiple copies of the same library (maybe one library has some parts of another included in it - it happens...) #pragma once would have no hope of working right.

Add to that the fact that the Arduino IDE copies some files around the place when building and '#pragma once is pretty much screwed.

Include guards work regardless. So sensible people use include guards and shun #pragma once.


How do I import data from serial monitor to excel document without copying and pasting?

The Arduino IDE's serial monitor is just one of many tools that can open a serial port and collect information from it.

The first step is to make sure the data you are writing to the Serial object in the Arduino is in a format suitable for importing into Excel. Separate multiple values on one line with a comma "," or tab "\t" character.

If you are running windows, you can often just use the built-in type command from a command prompt to write the serial port to a file:

type COM4 >> log.txt

(Assuming the Arduino is on COM4 and you want to write the data to a file called log.txt.)

If you're on a Mac, open the Terminal app and type:

screen -L /dev/tty.usbmodem1441335 9600

(Assuming your Arduino is on serial port named tty.usbmodem1441335 and your port speed is 9600 bps.) The session will be written to a file called screenlog.0.

Then you can open the text/log file in Excel. If you rename it to end in .csv, that may also help Excel recognize it as tabular data.


There are two ways of tackling this.  You can either switch the low-voltage DC power to the EL wire inverter (which is safe and easy) or you can switch the high voltage AC power out of the inverter (which is harder, more dangerous, but does allow you to route the power to different EL wires for animation).

The former can be arranged in just the same way as switching any heavy load from an Arduino - with an N-channel MOSFET as a low-sided switch, or a combination of N- and P-channel MOSFETs as a high-side switch. You could add further isolation with a relay should you wish. BJTs could be used instead of MOSFETs but MOSFETs are better at switching higher currents from low current sources.

For switching the high-voltage side you will need a TRIAC circuit. While it is possible to switch a TRIAC direct from the Arduino it is preferred to opt-isolate the system from the Arduino both for safety and ease of switching at higher voltages.

The most common opto-isolator to use is the MOC3041 Opto-Isolated Triac. This is used to switch the gate of a higher voltage / power TRIAC to switch the load.

In that circuit the "220V" comes from the EL inverter, and the LOAD is the EL wire itself. Each EL wire you want to switch would use a copy of that circuit, but can (power permitting) use the same inverter as the source.


How can I adjust my code so that the value that I print with my BLE device does not get chopped up when I receive it on an app?

how can I adjust my code to make sure it does not send the result chopped up but instead sends it's complete value?

The BLE device uses a package approach and the print member functions only support strings (char vectors and Arduino String). Construct the message as a String:

double lat = gps.location.lat();
double lng = gps.location.lng();
String msg = String(lat, 8) + String(", ") + String(lng, 8);
BTLEserial.print(msg);

Cheers!


Is this a USBasp I can use with Arduino?

That's not a USBasp, that's some other programmer that has co-opted Atmel's vendor ID invalidly. If you want to use it then you will need to find and use some program called "ProgISP" that is only available for Windows.

That particular device does not show the jumper required for reprogramming, so I wouldn't attempt it (and in fact I would find the nearest bin to toss it in and get a couple from Baite and/or LC Tech instead).


Converting live vocals to discrete signals

Confusing question. You list vocals and Digital Instruments, then you ask which audio device provided pre-processing?

There are the auto tunes boxes you mentioned. Since you know about them I don't see how you would be asking about them.

A digital instrument might output midi, and midi is just a simple serial protocol, so there is no device needed.

So what is your question actually?

An auto-tune box does work that would be best suited to a laptop or desktop computer. It first must determine the intended pitch than apply a formant filter to shift the incoming signal to a correct pitch. It requires the use of heavy fast math, Fast Fourier Transforms, FFT.  The smaller boxes you see doing this are actually specialized computers. Do not confuse their size with their power.

Google 'digital tuner software' to get an idea of what goes on.  I do not know of a device that specifically output the 'corrected' midi for an auto-tune, but at that point it would be fairly trivial so it would not surprise me if many did it.  For sure the many guitar to Midi converts do just that, but a good one is several thousand dollars.


Why does getting list of files from SD card FAIL if not printing to Serial? (ESP8266)

Try to use "delay(0);" in the loop (or yield() maybe).


Where are the traces connected to RESET-EN leading?

This is the DTR output of the ATmega16u2 which is connected to RESET pin of the ATmega2560 for reset by avrdude over DTR signal before upload of the sketch. There is a trace by default. Cutting the trace disables the auto-reset. Soldering a bridge on  RESET-EN pads re-enables the auto-reset.

the schematics part you quoted in question misses the long unconnected line for the RESET label. It leads here:


Unable to connect esp8266 12 module with arduino uno

When you are using Arduino board just as USB --> RS232 converter to send AT commands from PC to ESP8266 you have to connect TX to TX and RX to RX. But when you want communication between microcontroler and ESP then you have to connect TX to RX and RX to TX. Here I explained that in details.


Whether your chip is fried or not, we can't say, but they're reasonably tough and will stand a bit of abuse before they fail. Did anything smoke or get hot?

You can buy atmega328p chips pre-programmed with a bootloader from a few vendors, but they don't come from the factory that way so most are not. Preprogrammed chips typically cost a couple of $ US more than blank chips for the time spent by the vendor to buy blank ones, program, and repackage them for sale in small quantities, and are almost always advertised as such. If you don't know whether yours is programmed with a bootloader, it probably isn't. It's worth trying to do it yourself, on a breadboard, using a known-working Uno as a bootloader- programmer. There are lots of how-to articles on the internet.


Comparing a String after reading it from Serial fails

After color = Serial.readString(); color also contains a newline character.
You can remove that by adding the line color.trim();, or even better, avoid the newline altogether by using Serial.readStringUntil('\n'); which discards the terminating newline character.
Also, you could, and maybe should, avoid using the String class and use:
char color[10]; // char array as buffer for reading from Serial

int number = Serial.readBytesUntil('\n', color, 10); //Read input and length
color[number] = '\0'; //Terminate the string by adding '\0' at its end

if (strcmp(color, "red") == 0) //Use strcmp(), not ==

respectively.


To control AC power for inductive load (motor) a Triac is used. The concept is called phase cutting. It works for a resistive load (heater) too.

This module is designed for phase cutting. It contains a zero crossing detector and a Triac. The control is done in MCU. The zero crossing detector is wired to an interrupt pin. The control signal for the Triac is wired to an output pin. In external interrupt function you set a timer interrupt to send a pulse to the Triac after some microseconds. Longer off time results in less power for the motor.

At 50 Hz AC, one pulse is 10 milliseconds. To cut a part of AC wave out, activate the Triac gate for 20 microseconds after 0 to 10 milliseconds. Triac turns self off the AC line at next zero crossing.

Robotdyn has a library for the module.

EDIT:

I bought the Robotdyn AC dimmer module to use it in my AC heater regulation project and I tested it with a incandescent light bulb and a fan. (video on youtube)

The library by Robotdyn works, but it is designed to control many dimmers and uses a timer interrupt every 12 microseconds (yes, micros). The library sets the interrupts over MCU registers.

I wrote an adrduino fade-in/out sketch using TimerOne library to demonstrate phase cutting with this module.

#include <TimerOne.h>

const byte INTERRUPT_PIN = 2;
const byte TRIAC_PIN = 4;
const byte TRIAC_PULSE_MICROS = 30;

const int FADE_MAX = 9800;
const int FADE_MIN = 2000;

volatile bool triacOn;
volatile int period = FADE_MIN; // microseconds cut out from AC pulse

int fadeAmount = 10;

void zeroCrossing() {
  triacOn = false; // triac tuns off self at zero crossing
  Timer1.setPeriod(period); // to call triacPulse() after off period
}

void triacPulse() {
  if (triacOn) { // stop pulse
    digitalWrite(TRIAC_PIN, LOW);
    Timer1.stop();
  } else { // start pulse
    digitalWrite(TRIAC_PIN, HIGH);
    triacOn = true;
    Timer1.setPeriod(TRIAC_PULSE_MICROS);
  }
}

void setup() {
  pinMode(TRIAC_PIN, OUTPUT);
  attachInterrupt(digitalPinToInterrupt(INTERRUPT_PIN), zeroCrossing, RISING);
  Timer1.initialize();
  Timer1.attachInterrupt(triacPulse);
}

void loop() {
  period = period + fadeAmount;
  if (period <= FADE_MIN || period >= FADE_MAX) {
    fadeAmount = -fadeAmount;
  }
  delay(25);
}

EDIT 2 version with triac activated by 'pwm' pin

const byte TRIAC_PIN = 9;
const byte ZC_EI_PIN = 2;

unsigned long topMicroseconds = 9700; // 10000 micros is between zero crossings
int prescaler = 8;
byte prescalerBits = _BV(CS11); // /8

void zeroCrossing() {
  TCNT1 = 0; // reset the timer counter
}

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

  attachInterrupt(digitalPinToInterrupt(ZC_EI_PIN), zeroCrossing, RISING);

  pinMode(TRIAC_PIN, OUTPUT);
  uint32_t topPeriod = ((F_CPU / 1000000)* topMicroseconds) / prescaler ;
  ICR1 = topPeriod;
  OCR1A = topPeriod + 1;
  TCCR1A = _BV(WGM11) | _BV(COM1A0) | _BV(COM1A1);
  TCCR1B = _BV(WGM13) | _BV(WGM12) | prescalerBits;
}

void loop() {
  if (Serial.available()) {
    unsigned long microseconds = Serial.parseInt();
    Serial.find("\n");
    uint32_t period = ((F_CPU / 1000000)* microseconds) / prescaler ;
    OCR1A = period;
  }
}

on SAMD it is possible to setup this to start the timer on external interrupt over event, without an interrupt function. then the CPU of the MCU is not involved in phase cutting after the initial configuration of the peripherals

EDIT 3:

The TriacDimmer library version 1.1.0 for AVR Arduinos available in Library Manager works good with this dimmer. Fun fact: It uses timer1's input capture on pin 8 instead of external interrupt on pin 2 or 3.


It was wrong of you to try and install the driver as this board SHOULD be recognized as Leonardo. I would try to reinstall the Arduino IDE, it will also reinstall the drivers (hopefully)


Will the Arduino's low clock speed limit wireless transmission frequencies that are higher than the clock speed of the Arduino?

The frequency of a (wireless) radio is its carrier frequency. The data stream is carried on it by modulating that carrier wave in some way: by frequency-shifting, for example. A given processor could not provide data at a rate faster than its clock frequency (at least as a steady-state rate), but a packet of data, once supplied to and buffered in the radio, could then be streamed out at a speed unrelated to the physical specs of the supplier (the MCU). If the MCU had to drive the transmitter, bit-by-bit, then that would indeed limit the transmission speed.


Do not try to change millis(). Instead, record the last time the
second code (else statement) ran, and check whether that was more than
five seconds ago:

void loop() {
    static uint32_t lastRun;
    uint32_t now = millis();
    if (now - lastRun < 5000) {
        // Some code
    }
    else {
        // Some code
        lastRun = now;  // record the time
    }
}

This is essentially the same technique used in the Blink without
delay Arduino
tutorial.


How to increase sensitivity of Capacitive Touch Switch?

Sometimes things just ****. In my case, where 0.5 mm more of gap make the TTP223 unable to work, because I designed such a small pad. My solution? Remove the paint in the PCB, put a lot of solder in to make the pad taller. Work like a charm.


Is ATmega 328 on Arduino UNO already bootloaded?

In Arduino board, arduino controller means ATMEGA328P-PU already bootloaded. So, you can use directly. But if you buy only ATMEGA328P-PU chip or any other ATMEGA chip then you have to do bootloading for that.


Using Arduino to create a countdown that unlock a box

This sounds as an escape room puzzle.
From an electronic point of view you need something to lock/unlock the box like a servo motor, a stepper motor or (best option) a normally closed solenoid. You might need some components to drive such locking mechanism, like a mosfet or transistor (possibly a darlington), depending on which device you choose and what voltage it requires to operate. Simplest solution is a servo motor which doesn’t require anything, but has a low torque, meaning the box can easily be forced. Most robust and reliable solution is a NC solenoid, common ones are 12V so you’ll need a p-channel enhance mosfet and a couple of resistors to drive it from an Arduino.
To display the time you’ll probably want to go for an LCD, common ones are 16 col x 2 rows, most have an integrated chip to drive them using only a few wires.
Apart from that, you need a battery pack (voltage and power depending on your locking circuit choice) and may be a push button (for safety unlock).
From a software perspective you want to create a loop which starts by locking the box and then counts down the time: when the time left is less than 5 mins it activates the unlocking mechanism circuit.
int current = 0;
const int max = 2 * 60 * 60; // 2hrs in sec
const int grant = 5 * 60; // 5mins in sec
bool unlocked = false;

void setup() {
    lock();
}

// executed once every second
void loop() {
    // any safety open check should be performed here...
    // if still locked and less than 5 mins to end
    if (!unlocked && current > max - grant) {
        unlock();
    }

    display(current++);
    wait(1000);
}

// does what it is needed to unlock and sets the unlocked variable to true
void unlock() { ... }

// does what it is needed to lock and sets the unlocked variable to false
void lock() { ... }

void display(int secs) {
    int h = secs / (60 * 60);
    int m = (secs / 60) % 60;
    int s = secs % 60;
    // display on LCD the values above with the proper formatting
}

A couple of notes:

if you go for a normally closed solenoid be sure to have a way to get inside the box if something goes wrong with your circuit or if the batteries get drained
you might want to have a hidden button or other way to force the unlock, especially for debugging and testing


The claim “The cause it that your 3rd led (2nd element in the array) is reapeted twice” is wrong.

Apparently that sentence is supposed to mean that the long delay is due to i being one too large, coming out of the first loop and entering the second one.  Indeed, i is too large, but that's because each element of the array is a 2-byte int, so that instead of for (int i = 0; i < sizeof(leds); i ++) being equivalent to for (int i = 0; i < 3; i ++), it is equivalent to for (int i = 0; i < 6; i ++).

Thus, one second goes by with an extra 4 occurrences of delay(250); in the first loop, and another one second with 4 extra occurrences of delay(250); in the other loop.

To correct the problem, write sizeof leds/sizeof leds[0] instead of sizeof(leds), and write for (--i; i > 0; i--) instead of for (i; i > 0; i --).


Where is random defined with no arguments?


Bit mask first 2 bits of 16 bits for accelerometer

Since it won't convert to two's complement if the sign bit is the 14 bit instead of the 16th, it would be easier to just shift the value left by 2. So

int bresult= result<<2;

Since <<2 is the same as *4 the result will be 4 times as high. So you need to divide the result by 4. Since you already have to multiply by 0.025 (or divide by 40), you end up having to multiply by 0.00625 (or divide by 160).


Read ISO/IEC 14443B (NFC Type B) with PN532

I dont have an exact reply but

1) are you certain the other tags are type b?

2) hace you tried connecting the reader using a UART USB cable? You could use libnfc, to check if the reader works.
And going forward at commands FOR the reader are a good way to debbug.


How to determine the source of constants in libraries?

The name TC_CTRLA_PRESCALER_DIV1 indicates this is a macro. A trick for quickly finding the exact location of a macro definition is:

File > Preferences > Compiler Warnings > All > OK
In your sketch, add a #define directive for the macro name that definitely changes the definition:

#define TC_CTRLA_PRESCALER_DIV1 foobar

Sketch > Verify/Compile
After the compilation finishes, examine the compiler output in the black console window at the bottom of the Arduino IDE window (you will need to scroll up to see it all) for a "redefined" warning. The warning will state the path of the original definition:

    C:\Users\per\AppData\Local\Temp\arduino_modified_sketch_804921\sketch_aug05a.ino:1:0: warning: "TC_CTRLA_PRESCALER_DIV1" redefined [enabled by default]

   #define TC_CTRLA_PRESCALER_DIV1 foobar

   ^

  In file included from C:\Users\per\AppData\Local\Arduino15\packages\arduino\tools\CMSIS-Atmel\1.1.0/CMSIS/Device/ATMEL/samd21/include/samd21g18a.h:268:0,

                   from C:\Users\per\AppData\Local\Arduino15\packages\arduino\tools\CMSIS-Atmel\1.1.0/CMSIS/Device/ATMEL/samd21/include/samd21.h:69,

                   from C:\Users\per\AppData\Local\Arduino15\packages\arduino\tools\CMSIS-Atmel\1.1.0/CMSIS/Device/ATMEL/samd.h:105,

                   from C:\Users\per\AppData\Local\Arduino15\packages\arduino\tools\CMSIS-Atmel\1.1.0/CMSIS/Device/ATMEL/sam.h:470,

                   from C:\Users\per\AppData\Local\Arduino15\packages\arduino\hardware\samd\1.6.19\cores\arduino/Arduino.h:48,

                   from C:\Users\per\AppData\Local\Temp\arduino_build_309126\sketch\sketch_aug05a.ino.cpp:1:

  C:\Users\per\AppData\Local\Arduino15\packages\arduino\tools\CMSIS-Atmel\1.1.0/CMSIS/Device/ATMEL/samd21/include/component/tc.h:113:0: note: this is the location of the previous definition

   #define TC_CTRLA_PRESCALER_DIV1     (TC_CTRLA_PRESCALER_DIV1_Val   << TC_CTRLA_PRESCALER_Pos)

   ^


8cm is 233µs of sound travel time.  There and back again would be 466µs.  466µs, at 16MHz, is around 7400 instructions.

When an interrupt is triggered you don't get an instant response.  First the built in interrupt function is called. That then looks to see if you have registered an interrupt function.  It then calls that interrupt function.

All that takes time, and when you're working with microseconds it makes a big difference.

And then you have to go and get the current micros() value, which again takes time to do.

So it all adds up to a delay.  Not ideal.

For greater accuracy you should investigate using input capture which will start a timer running when you send the trigger and the timer will automatically stop the nanosecond the echo is received.  From that you can calculate a much more precise distance.

As for why you are getting strange results with the servos on?  Most likely because you are moving the receiving head while the pulse is being received.  I made a similar system while playing once and found that the best results were achieved by moving the head to the desired position, waiting a moment for any vibration to settle, do the ping and get the result, then move the head to the next position.

Oh, and by the way, the HC-SR04 is (from memory) only really rated for up to 2m - I have never achieved anything more than around 1.8m with any accuracy.


ESP8266 UDP multicast doesn't receive packets

I recently had the same problem.

The unequivocal answer is that there is a power optimization (internal by Espressif) to save power, I guess, and it really creates havoc in the UDP Multicast receiving. Why? I have no idea. Same problem with the ESP32 and ESP8266.

Solution:

#include "user_interface.h"

and after:

WiFi.mode(WIFI_STA);
// the below instructions and now u will receive.
wifi_set_sleep_type(NONE_SLEEP_T); //LIGHT_SLEEP_T and MODE_SLEEP_T


How to automatically reset the NRF24L01 module

This is a known problem with those chips (especially Chinese clones). It is caused when a chip gets stuck in TX mode waiting for an ACK that never arrives back.

The chips don't have a "reset", but switching them into low power mode and then back on again, which doesn't affect any register settings, aborts the current TX operation.

RF24Network is merely a protocol layer on top of the RF24 library. That RF24 library has powerDown() and powerUp() methods. Simply call powerDown followed by powerUp on your RF24 driver object.


On a classic Arduino pins 0 and 1 are used for serial communication with the host PC, so you cannot use them to talk to a peripheral without conflicting with that.  The library may well be coded to trap and reject such an attempt.

On various alternate (ARM, Atmega32u4, etc) boards these pins may be usable, though the library may not be aware of that.  Also on such boards you would generally want to use an available hardware UART rather than a software simulation of one, which may be fairly ATmega-specific anyway - the end result of which is that library code may well need modification to work on a non-traditional device.


ESP8266 12e Arduino IDE outputs garbage values on serial monitor

The baud rate you specify in your program and the baud rate in the serial monitor must match. The ESP8266 outputs a boot message at its own baud rate (varies from model to model - try 57600) before it executes your sketch.

For example:

You can choose any (within reason) baud rate in your program as long as you also choose the same baud rate in whatever is communicating with it (such as the serial monitor in the IDE). If you want to see the boot messages then the serial monitor will have to be set to the right baud rate.


Can I connect an SD card shield to Digispark ATtiny85 board?

In short I am going to say NO.

The flash is too small to adequately run the SD library as well as the rest of your Arduino code.

The RAM is also underpowered for what is needed to properly access files on an SD card.

Having said this, I am sure there are some clever software engineers that could write a cut down SD card library to do limited commands. Overall this is too hard for the beginner - Just buy an Arduino Uno/Mega/Due and avoid the unnecessary hassle.


There is a few possible scenarios to create a H-bridge:

with NPN transistors only or PNP
mix of PNP and NPN

You have to be careful to not mix the types and inputs. See pictures below:


Serial communication mac to Digispark ATtiny85

SoftSerial and a real serial port on the mac will work. Or if you are careful use the DigiKeyboard and print the debug to the HID keyboard REMEMBERING to switch to a notepad equivalent window on the mac to receive and display the debugging text and not have it overwriting the arduino sketch by mistake.
DigiCDC is a kludge that does not work properly on modern operating systems sorry!


Should L, TX, RX led light on while connected with laptop

On Arduino Uno (and most basic Arduinos), the 'L' LED is operated by whatever code is on the Arduino. RX and TX flicker whenever the Arduino is sending data to the PC (TX) or is receiving data from the PC (RX).

If you have never re-programmed your Arduino, it is running whatever code was in it when it was shipped to you. It sounds like your Arduino has a bootloader but no code yet. The bootloader listens for the PC to try upload a new program. While it is listening, it blinks the L LED.

If the PC tries to upload, you will see the RX and TX lights flicker as the two communicate, until the upload is finished. Then whatever program was uploaded will run, and it will control the LEDs.

If the PC doesn't try to upload a new program within a few seconds (how long depends on which bootloader version is in the Arduino), the bootloader will start whatever program is already in the Arduino. Again, that program will then control the LEDs.


Uni-directional communication between NodeMCU and Arduino spits out garbage

https://www.pjrc.com/teensy/td_libs_AltSoftSerial.html
Do you GND them via your PC USB? Try connecting their GND as well.
External power could be an issue as well, I am not aware of power consumption of ESP when they do stuff with their WiFi.


Testing Conditions on Port Bytes - ignoring certain bits?

You need to use boolean arithmetic.  Use the AND operator (&) to combine the incoming value AND the "mask" value (the value of the bits you do care about) and see if it equals the mask bit:

byte wanted = 0b11001110; // 207
byte incoming = 223; // for example 11011111

if ((wanted & incoming) == wanted) {
    // whatever
}

The AND operator compares each bit of the bytes in turn.  If they are BOTH 1 then the result is 1. Otherwise the result is 0.  So the above gives:

wanted:    11001110
incoming:  11011111
AND:       11001110

And the result matches "wanted". If you had some other value for incoming it could look like this:

wanted:    11001110
incoming:  01011011
AND:       01001010

And you can see that the result doesn't match.


Your problem is that you use delay() in your loop. This stops the code execution for the given time, so no wonder your code starts to frickle after some time.

To achieve what you want try this:

void loop() {
  if(millis() - prev >= gap){
    Serial.print("Prev: ");Serial.println(millis()-prev);
    prev = millis();
  }
  if(millis() - prev2 >= mils){
  Serial.print("Prev2: ");Serial.println(millis()-prev2);
  prev2 = millis();
 }
}

EDIT If you try to create a frequency generator, it won't work that way - read this thread and look at the program in the last third which uses bitbanging technique to achieve that. Here an example of a wave generator (with extra hardware)


You cannot pass an array of characters as an argument (implicit or not)
to a function. When you write

String rtcTimeString(char ts[] = "MM/DD/YY hh:mm:ss");

The array notation is implicitly converted to a pointer. The line above
is then equivalent to:

String rtcTimeString(char *ts = "MM/DD/YY hh:mm:ss");

And this is incorrect: you are initializing a pointer to modifiable
characters using the address of an array of constant characters. The
compiler should have warned you about this... if you enabled compiler
warnings. The correct prototype should be

string rtcTimeString(const char* ts = "MM/DD/YY hh:mm:ss");

But then you cannot pass this pointer to DateTime::toString(), as this
method expects the template string to live in a buffer it can overwrite:
that's where it will write the formatted string.

I suggest this solution:

string rtcTimeString(const char* ts = "MM/DD/YY hh:mm:ss") {
    DateTime now = rtc.now();
    char buf[strlen(ts)+1];  // allocate a fresh buffer
    strcpy(buf, ts);         // copy the template there
    return now.toString(buf);
}


How to flash an ATMEGA2560 using a WIZnet 5500?

The latest Ariadne bootloader from 'codebender' is in his 'personal' GitHub repository. It has W5500 support. Per created his fork with better documentation and a hardware package earlier. The loathingKernel's repo still lacks good documentation.

I installed Per's Ariadne package over Board Manager and then I replaced the files in Per's package with files from loathingKernel's repo. The I flashed the bootloader to Mega without problems and the Ariadne bootloader worked for me over W5500.

I configured the upload from IDE too.


Arduino raise the error: `does not name a type` when an Object is used outside of the main two blocks setup and loop

As you have already noticed, you cannot call methods of a class, nor access its properties, outside a "block" (as you call it).  More specifically, you can only perform "programatical" operations from within a function.  Anything outside a function (known as the global scope) is purely for declaration and initialization of variables and types, etc.

Any class variables declared in the global scope have their constructor executed before the rest of the program (even before setup) gets run.  However, setup is not the first function to be called at startup.

Anything you put into a constructor has to take into account the fact that anything might be happening between the constructor being called and the object instance actually being used.  Things like pinMode and digitalWrite are unsafe to use in a constructor, since there is a chance they may be negated during the startup.  That is why the majority of Arduino classes have a .begin() method which is called from setup().

The proper method for using classes with pin control and similar operations is:

The constructor takes the pins to use
The constructor saves those pins in variables
The begin() method is called in setup()
The pins are configured appropriately.

For example:

class myClass {
    private:
        int _myPin;
    public:
        myClass(int pin) : _myPin(pin) {}

       void begin() {
            pinMode(_myPin, OUTPUT);
            digitalWrite(_myPin, HIGH);
        }
};

myClass p(4);

void setup() {
    p.begin();
}

void loop() {
}

The object instance p is in the global scope and can be referenced from any function. The pin is configured only when setup() is run.

The startup sequence, more specifically, is typically this:

The memory used by global and static variables is "zeroed".
Any pre-defined variable values (BSS) are copied from flash into RAM.
Any object constructors are called.
The main() function is called (main startup function).
The init() function is called which configures the Arduino platform.
The initVariant() function is called which performs any board specific setup routines.
USB is configured on the boards that have it
Your setup() function is called.
Your loop() function is called.
The serialEvent() system runs if defined.
Go to 10.

As you can see quite a lot happens between the constructor being called and setup() being called, and you cannot reliably predict what that might be.  Some boards may do nothing more than configure interrupts and enable timers (for things like delay and millis), but other boards may configure IO pins to default settings (especially more complex boards with multiple functions per IO pin), so really the only safe operations you can perform in a constructor are operations which act directly on the internals of the class itself.  Anything outside the scope of the class could be changed before you come to use it.


Background processes - Arduino Mega and SeeedStudio CAN shield

I see several options:

Change your code to achieve lower delays on the other functions
Use interrupts at a set frequency to trigger the sending (and maybe the automatic transmission trigger pins, see MCP2515 datasheet, depending on pin use & schematic of your specific shield)
Use a basic scheduler/rtos

It is hard to tell what is going on without the rest of your code, if it is a good idea to try to achieve faster functions.

I am not 100% sure the CAN-lib would will work well in the context of an interrupt.


Draw a truth table and look at it from there.  From your words, it is confusing.  From your code it looks like this:

mainPin    reedPin   relayPin
HIGH        LOW      LOW
HIGH        HIGH     LOW
LOW         LOW      HIGH
LOW         HIGH     HIGH

So:

void loop() {
      digitalWrite(relayPin, !digitalRead(mainPin));
}

If you want:

mainPin    reedPin   relayPin
HIGH        LOW      LOW
HIGH        HIGH     LOW
LOW         LOW      HIGH
LOW         HIGH     LOW

then:

void loop() {
      digitalWrite(relayPin, !(digitalRead(mainPin) || digitalRead(reedPin)));
}


Can you activate the whole pixel on LCD?

The LCD is made up from 32 characters each is 5x7 pixels in size, with a 1 pixel gap between each character.

You can never put anything in the gap between the characters, as there is just nothing there.

But what you can do is define your own characters to fit within the 5x7 pixel rectangles.

Some variants of the HD44780 have character 255 as a solid block, but not all (it depends on what language the ROM is).  If you have one that has that character you can just print it with lcd.print("\xff") or lcd.write(255).  If it doesn't it will print ÿ instead. In that case you will have to define your own character.

One benefit of defining your own characters is that you could then do partial blocks to give you a higher resolution.  Here's an example:

You can find that example and the code that goes with it here.


No. The INT pin of the MPU-9250 is not presented on the IO header of the GY-91.

The only way of knowing what is going on inside the MPU-9250 at any time is to go and look. I.e., periodic polling of the sensor.

If you want to use the interrupt pin you will have to shop around for a different module that gives you access to that pin.


How can I sense very high temperatures with Arduino?

You probably want to use a thermocouple. It'll give you the ability to measure much higher temps than regular temperature sensor. You'll also need a IC like the MAX6675 to interface with it.

  The MAX6675 performs cold-junction compensation and digitizes the
  signal from a type-K thermocouple. The data is output in a 12-bit
  resolution, SPI™-compatible, read-only format.

  This converter resolves temperatures to 0.25°C, allows readings as
  high as +1024°C, and exhibits thermocouple accuracy of 8 LSBs for
  temperatures ranging from 0°C to +700°C.

Page 6 of the datasheet has the serial interface protocol information and. You can really just set the Chip Select line and it'll give you 16 bits of information, 12 of which will be the temperature.


Does Arduino.cc sell the Ethernet Shield?

ebay is overflowing with ethernet shields/modules.

Alternatively, if you trust Wikipedia, you can form your own opinion about from which of the parent stores to buy.


Arduino has created binary numbers: B1, B101, B00111, and so on.

It is documented in the reference page "Integer Constants".
The "B1" is defined in "binary.h".

They should not have done that. Not a single C++ software engineer thinks that it was a good addition. The C++ language is perfectly fine for creating binary values: 0b1, 0b101, 0b00111, and so on.

It is not your fault, you can blame Arduino. Because of this, you should never create variables with the name: B1, B101, B00111, and so on.


adding a dead band to my motor and gearbox

The simple way is to just subtract one from the other, take the absolute value and see if it exceeds your hysteresis range.

eg.

if (abs (sensorValue - where) >= 0.5) {
  {
  // do something

  if (sensorValue > where)
    {
    // one way
    }
  else
    {
    // other way
    }
  } // end of large enough to worry about

In response to this (since deleted):

  would this not have the same problem as mine as instead of hunting round its target it will just do it 0.5 away from the target?

By subtracting and taking the absolute value, we create a band of +0.5 and -0.5 where, if the sensor is in that range, we do nothing. It hasn't moved the problem because it can't move in two directions at once (both up and down).


Measuring the capacitance of 2 capacitors at a time

Before we get started, there are a few problems with your code.

First, I wouldn't check for ==648 or ==0: what if you miss it by a moment and it jumps to 649, or it doesn't quite discharge to 0v?  I'd use >=648 and <=2 (or some other similarly low number - experimentation required).

How is your circuit connected?  I can't quite get my head around the charge and discharge pins, but I'll stick with what you have, assuming it works.

You say you want measurements every 30s, but don't say how long they take. (I have no idea of the capacitance of your bottle.)  My code assumes it takes much less than 30s to measure one bottle.  If it takes near to 30s to do one, this won't work.

I'll also assume your code works.  This is a bad assumption, since it won't even compile (capital I in if) but regardless, that's what I'll assume.

All that being said, here's the code:

// Pins connections
int analogPinA = 0;
int analogPinB = 1;
int chargePinA = 13;
int chargePinB = 12;
int dischargePinA = 11;
int dischargePinB = 10;

// Resistor being used
int resistorValue = 10000;

void setup()
{
  pinMode(chargePinA, OUTPUT);
  pinMode(chargePinB, OUTPUT);
  digitalWrite(chargePinA, LOW);
  digitalWrite(chargePinB, LOW);
  pinMode(dischargePinA, OUTPUT);
  pinMode(dischargePinB, OUTPUT);
  digitalWrite(dischargePinA, LOW);
  digitalWrite(dischargePinB, LOW);
  Serial.begin(9600);
}

// Measure the capacitance of specified capacitor
float measureCapacitance(int analogPin, int chargePin, int dischargePin)
{
    // Ensure the capacitor is discharged
    digitalWrite(dischargePin, LOW);
    while (analogRead(analogPin)>2) { /* Do nothing */ }
    pinMode(dischargePin, INPUT);

    // Start charging
    unsigned long startTime = millis();
    digitalWrite(chargePin, HIGH);

    // Wait for the capacitor to charge
    while (analogRead(analogPin)<=648) { /* Do nothing */ }
    unsigned long endTime = millis();

    // Start it discharging again, ready for next time
    pinMode(dischargePin, OUTPUT);
    digitalWrite(dischargePin, LOW);

    // Calculate measured capacitance
    unsigned long elapsedTime = endTime - startTime;
    float microFarads = ((float)elapsedTime / resistorValue) * 1000;
    return microFarads;
}

void loop()
{
    // Measure capacitance of first bottle
    float microFarads = measureCapacitance(analogPinA, chargePinA, dischargePinA);
    if (microFarads <= X) // X is an arbitrary capacitance when the bottle is empty
    {
      Serial.println("Bottle A is empty");
    }

    // Measure capacitance of second bottle
    float microFarads = measureCapacitance(analogPinB, chargePinB, dischargePinB);
    if (microFarads <= X) // X is an arbitrary capacitance when the bottle is empty
    {
      Serial.println("Bottle B is empty");
    }
}


How to read a specific amount of data via serial?

From what you have posted, assuming this is the ESP code in the question, it is clear that for every character the Arduino sends the ESP the ESP will send 3 back. So at some speed this will likly stop working


Why can I power an SD card reader from a digital pin?

I just tested a SD card in an adapter (with level shifters). Without any activity the SD card is only drawing around 0.5 mA. So that is in the capability of an output pin.

Doing a directory list appears to use a maximum of 7 mA, so that is OK.

Writing a file used a maximum of 54.3 mA, which is exceeding the absolute maximum ratings for an output pin (40 mA - recommended only 20 mA for continuous current).

Now you may say that "it works" but the question is: for how long? Exceeding absolute maximum ratings is a path to damaging your processor.

If you want to turn the SD card on and off from time to time, to reduce power, I suggest you arrange to switch the 5V line (and not use a digital output). For example from this page about a low-power temperature sensor I have this schematic:

The MOSFET there switches a 5V line on and off under program control.

That particular design includes a SD card, and that particular gadget has been working for a couple of years now.

Photo of hardware:


OTA update - sodaq board (arduino M0 compatible)

SOLVED!
I have compiled my own SDUBoot.ino with fixed SDU_START 0x2000 and for SODAQ Sara (boot/sodaq_sara.h). My sketch with #include "SDU.h" compiles successfully. The board package is also installed in Arduino (http://downloads.sodaq.net/package_sodaq_samd_index.json). Here my code with changes (base is SodaqCore-samd-1.8.6-sodaq from Github):
File libraries/SDU/extras/SDUBoot/SDUBoot.ino:
#include <SD.h>
#include <FlashStorage.h>

#define SDU_START    0x2000
#define SDU_SIZE     0x4000

#define SKETCH_START (uint32_t*)(SDU_START + SDU_SIZE)

#ifndef SDCARD_SS_PIN
#define SDCARD_SS_PIN 10
#endif

#define UPDATE_FILE "UPDATE.BIN"

FlashClass flash;

// Initialize C library
extern "C" void __libc_init_array(void);

int main() {
  init();

  __libc_init_array();

  delay(1);

  if (SD.begin(SDCARD_SS_PIN) && SD.exists(UPDATE_FILE)) {
    File updateFile = SD.open(UPDATE_FILE);
    uint32_t updateSize = updateFile.size();
    bool updateFlashed = false;

    if (updateSize > SDU_SIZE) {
      // skip the SDU section
      updateFile.seek(SDU_SIZE);
      updateSize -= SDU_SIZE;

      uint32_t flashAddress = (uint32_t)SKETCH_START;

      // erase the pages
      flash.erase((void*)flashAddress, updateSize);

      uint8_t buffer[512];

      // write the pages
      for (uint32_t i = 0; i < updateSize; i += sizeof(buffer)) {
        updateFile.read(buffer, sizeof(buffer));

        flash.write((void*)flashAddress, buffer, sizeof(buffer));

        flashAddress += sizeof(buffer);
      }

      updateFlashed = true;
    }

    updateFile.close();

    if (updateFlashed) {
      SD.remove(UPDATE_FILE);
    }
  }

  // jump to the sketch
  __set_MSP(*SKETCH_START);

  //Reset vector table address
  SCB->VTOR = ((uint32_t)(SKETCH_START) & SCB_VTOR_TBLOFF_Msk);

  // address of Reset_Handler is written by the linker at the beginning of the .text section (see linker script)
  uint32_t resetHandlerAddress = (uint32_t) * (SKETCH_START + 1);
  // jump to reset handler
  asm("bx %0"::"r"(resetHandlerAddress));
}

File libraries/SDU/extras/SDUBoot/build.sh:
#!/bin/sh -x

ARDUINO=arduino
SKETCH_NAME="SDUBoot.ino"
SKETCH="$PWD/$SKETCH_NAME"
BUILD_PATH="$PWD/build"
OUTPUT_PATH="../../src/boot"

if [[ "$OSTYPE" == "darwin"* ]]; then
    ARDUINO="/Applications/Arduino.app/Contents/MacOS/Arduino"
fi

buildSDUBootSketch() {
    BOARD=$1
    DESTINATION=$2

    $ARDUINO --verify --board $BOARD --preserve-temp-files --pref build.path="$BUILD_PATH" $SKETCH
    cat "$BUILD_PATH/$SKETCH_NAME.bin" | xxd -i > $DESTINATION
    rm -rf "$BUILD_PATH"
}

mkdir -p "$OUTPUT_PATH"

buildSDUBootSketch "SODAQ:samd:sodaq_sara" "$OUTPUT_PATH/sodaq_sara.h"

File libraries/SDU/src/SDU.cpp:
#include <Arduino.h>

#include "SDU.h"

__attribute__ ((section(".sketch_boot")))
unsigned char sduBoot[0x4000] = {
  #include "boot/sodaq_sara.h"
};

Sketch file sdu_test.ino:
#include <Arduino.h>
#include "SDU.h"

#if defined(ARDUINO_SODAQ_SARA)
#define DEBUG_STREAM SerialUSB
#else
#error "Please select the SODAQ SARA as your board"
#endif

#define DEBUG_STREAM_BAUD 115200

String message;

void setup() {
  // Start communication.
  DEBUG_STREAM.begin(DEBUG_STREAM_BAUD);

  while (!DEBUG_STREAM) {
    // Wait for Serial Monitor to be opened.
  }

  message += "Sketch compile date and time: ";
  message += __DATE__;
  message += " ";
  message += __TIME__;

  // print out the sketch compile date and time on the serial port
  DEBUG_STREAM.println(message);
}

void loop() {
  // add you own code here
}

File arduino/50/.arduino15/packages/SODAQ/hardware/samd/1.8.6/variants/sodaq_sara/linker_scripts/gcc/flash_with_bootloader.ld add these lines:
KEEP(*(.sketch_boot))

. = ALIGN(0x2000);

here:
...
SECTIONS
{
    PROVIDE(__sodaq_firmware_state = ORIGIN(FLASH) - 0x100);

    .text :
    {
        __text_start__ = .;

        KEEP(*(.sketch_boot))

        . = ALIGN(0x2000);
        KEEP(*(.isr_vector))
        ...

On SD card (formatted as FAT32) I have stored the renamed file UPDATE.bin without bootloader of the compiled sketch file. Pin D10 is connected and used as chip select CS.
Build boot hex files:
$ cd libraries/SDU/extras/SDUBoot
$ ./build.sh

Version 1.8.6-sodaq has these missing lines on arduino_zero variant but not on sodaq_sara variant.


Fastest Communication from NodeMCU to Arduino Nano

If it comes to speed and reliability you have to choose an interface that is handled in hardware on both sides. For the arduino nano you have the following options (nodeMCU supports all of them):

UART:

not very fast (order of 10kbit/s), but it's full-duplex (asynchronous communication in both directions)
implementation is trivial due to Serial.h
long distance (order of meters)

I2C:

not very fast either (order of 100kbit/s), but not full-duplex
implementation is straight forward because both slave and master are implemented in arduino library
only over short distance (order of cm)

SPI:

quite fast (>1Mbit/s), full-duplex
implementation might require some experience (as far as I know, slave mode is not supported by SPI.h)
long distance (order of meters)

Which of those is the best option still depends on your specific requirements, but personally I like SPI very much because it is very fast and stable.


Arduino Due and BNO055 address in i2c mode

I've built MotioSuit, a mocap suit based on the BNO055 which currently has 9 sensors but could go up to 18.

https://hackaday.io/project/9266-motiosuit

The sensor board and library are open-source and documented in the link, I hope it helps!


How to display information from a web API on an LCD (2x16) in real time?

Your API presents the information in a format called JSON, JavaScript Object Notation. It is a human readable way of passing around data structures. Web APIs often make use of it.

Benoît Baluchon has a library, Arduino JSON for manipulating JSON in embedded systems. You can download it from GitHub. The documentation is here. Assuming that the problem you need to solve is getting the information out of JSON and into a form that you can display, this looks like a good place to start.

Using Arduino JSON, the code to get the first time would look something like this:

char* getSchedule();

StaticJsonBuffer<200> jsonBuffer;

JsonObject& root = jsonBuffer.parseObject(getSchedule());

char* next = root["response"]["schedules"][0]["message"];

Note: this is from a quick search on "arduino json" followed by quickly reading the code. I doubt if it is exactly right, but hopefully it is enough to get started.


There is nothing special about it, it just works.

I strongly suggest to remove everything that is Arduino related from the repositories and have a minimal Java environment installed.

It is no problem to have a gcc build environment together with Arduino though. Even a gcc-avr build environment from the repositories is no problem. But don't install any Arduino or Java-rxtx from the repositories.

You can download the linux version and unpack it in a folder.
Go to that folder where you unpacked the Arduino files and right-click on the 'arduino' file to create a shortcut. Move that shortcut to your Desktop.
Depending on the flavor of Ubuntu that you have, you can also create a starter and fill in the whole path of the 'arduino' file.

Then you can start the Arduino IDE, and just click/activate that shortcut or starter again for another instance of the Arduino IDE. They will work independent of each other. You have to set the right board for each instance of course. A third one or more is also possible.

If you have trouble with shortcuts or starters, then you can even open a terminal and go to the unpacked files, type "./arduino" to start it. Open an other terminal (or new 'tab' in the terminal) and do the same.

You don't have to makes copies of the Arduino files, you don't have to make multiple shortcuts or starters. Just start a new instance by activating the shortcut or starter once more.

I recommend to use only the newest version (at the moment 1.8.3). But if you need to run an older version then you can download and unpack older versions in seperate folders. Be careful that you can not run different versions of the IDE at the same time. The Arduino IDE before 1.6.x differs too much from 1.8.x. All of them share the same ~/.arduino15 folder with settings and downloaded files, which can cause trouble when running a new version, then an older version and then a newer version again.


How to connect 70 analog sensor to a single Arduino (Mega or Uno) device?

There are fairly inexpensive chips called "analog multiplexers" which let you choose one input out of a range (8 or 16 is typical). You could take the reading, then switch to a different input, and take another reading.

I have a page about analog multiplexers.

Example of it in operation:

In this example you have 8 inputs, and by setting the A/B/C pins appropriately, one of the 8 is selected and appears at the O/I pin (output/input).

There is a 16-channel model as well. I see the 16-pin chip (74HC4067) available on eBay for $US 1.26 right now. You can get four of them (which would give you 80 inputs) for $4.88.

Also see the Wikipedia article on multiplexers.

  For this, I need to collect soil moisture value from 70 sections of the farm on a single Arduino.

Yes, well how will these sections get their data into one place? That is probably the bigger problem.

You may need to use a lengthy cable using RS485 (balanced signals) or maybe cheap radio transceivers.

Trying to use a "single Arduino" on what might be quite a large farm is the issue. It's not the Arduino's fault. You have to have some way of sending the data from the further points to where it is to be collected.


Sample code for using adafruit servo shield?

Adafruit's guide for the shield is here:
https://learn.adafruit.com/adafruit-16-channel-pwm-slash-servo-shield/using-the-adafruit-library

I'm not sure how much the library you linked and the official one differ. They seem to be used the same way, but you should probably stick with the official one.

You are going to have to use setPWM(pin, on, off) since the arduino is not generating the signals like it would with servo.write(), the arduino is sending commands to a chip on the shield that generates the signals for you.

Adafruit recommends calibrating SERVOMIN and SERVOMAX yourself with whatever brand of servo you plan on using, but those default values should be pretty close.


MQTT not working on ESP8266 (Nodemcu 0.9)

The Soft WDT reset means that the software watchdog timer reset. Depending on the version of Arduino core to the ESP8266 using delay() can cause this to happen, though current versions handle this better, and using delay() does not cause problems. Make sure you are up-to-date with the Board Manager definitions for ESP8266-based projects.

This page has lots of information on the watchdog timers and especially notes how to use a tool called ESP8266/ESP32 Exception Stack Trace Decoder to determine exactly what line in your code caused the reset to happen.

This page notes that the PubSubClient library can cause problems with the watchdog feeding and gives examples of some alternative yield() and delay() functions you can include and call instead of the built-in versions, which help alleviate resets when using PubSub on ESP8266.

The software watchdog timeout is on the order of 3 seconds, so you can also try reducing your delay(5000) to something shorter, like delay(1000) while debugging, to rule out the 3-second WDT reset due to the delay() call.

Your output also indicates status -2 to the state() function. The documentation for PubSubClient notes that this means "the network connection failed". So one other thing to check is that your device actually connects to the WiFi network and that the MQTT server is listening on the IP address and port you specify.


It's doing basically this:
clockSource = TCCR2B & (_BV(CS22) | _BV(CS21) | _BV(CS20)); // store prescaler
TCCR2B &= ~(_BV(CS22) | _BV(CS21) | _BV(CS20));             // select "no source" - disable clock source
power_timer2_disable(); // disable whole timer2 in Power Reduction Register

Definition of power_timer2_disable macro is:
#define power_timer2_disable()  (PRR |= (uint8_t)(1 << PRTIM2))

In short, you have to turn off the clock source before the power gets cut off by PRR register (to avoid unexpected behaviour).

Power Reduction Register
The Power Reduction Register (PRR), provides a method to stop the
clock to individual peripherals to reduce power consumption. The
current state of the peripheral is frozen and the I/O registers can
not be read or written. Resources used by the peripheral when stopping
the clock will remain occupied, hence the peripheral should in most
cases be disabled before stopping the clock. Waking up a module, which
is done by clearing the bit in PRR, puts the module in the same state
as before shutdown. Module shutdown can be used in Idle mode and
Active mode to significantly reduce the overall power consumption. In
all other sleep modes, the clock is already stopped.


How to calculate phase shift between two square waveforms with Arduino DUE

With 0° you have two inputs triggering interrupts at the same time.  That can't happen.  You can't run two interrupts at the same time, so the second one gets queued up until the first has finished.

With all that serial printing in there there's going to be quite a delay between one interrupt triggering and the next one being allowed to trigger - giving you skewed results.

I would suggest passing your signal through an XOR gate so that you end up with a single small pulse that represents the phase shift between the two signals.


ESP8266 only executes Sketch after switching on/off CH_PD pin

Well, after literally spending hours trying to figure out what the heck is going on, I decided to test the setup with a ESP8266-12 NodeMcu, which is essentially the same but more resembling to an Arduino in that it has more in/out pins and it's better for testing.

On this platform I got a different behavior. I was able to send an Email by the push of the button but... only once. So apparently, contrary to what I believed, something was wrong with the code.

In the code there is this method, which essentially initiates the WiFi connection:

void initializeWifi(){

  WiFi.begin(WIFI, PASSWORD);

  // allow time to make connection
 while (WiFi.status() != WL_CONNECTED)  delay(5000);

  }

Somehow the delay(5000); didn't seem right as delay usually freezes the whole thing. When I commented out the line, everything worked as expected. With the NodeMcu as well as with the ESP8266-01.

However, I still have to figure out how to give time to the WiFi to connect without freezing out all together. Probably it's the time for millis();

I hope this becomes useful to somebody else in the future.


Power Arduino Over 9V automatically after being disconnected from USB 5V

there is one way you can make it.
you can use a temporary capacitor(with a voltage output near to 9v)(or a lipo battery) connected to arduino's voltage input pin and 9v battery connected to arduino with a transistor.
whatever program you are uploading to arduino, you can add a code that reads the serial port, and if serial port is not available then it opens the transistor's gate so as the capacitor gets discharged very quickly the 9v battery takes the job.when it gets the serial port again it closes the transistor's gate and arduino stops feeding upon battery and takes power from USB port.


I managed to do this using solution from Ken Sheriff's Blog. Ken provides a simple example and documents it perfectly. Due to the nature of my IR Receiver (rejecting continuous beam) I used the sample code provided by Stephane Deniaud in the comments section. Thanks to both...

#include <IRremote.h>

#define PIN_DETECT 2
IRsend irsend;

void setup()
{
    pinMode(PIN_DETECT, INPUT);

    Serial.begin(115200);
    Serial.println("READY");

    attachInterrupt(digitalPinToInterrupt(PIN_DETECT), checkIRBeamBreak, RISING);

    // Note : the IR emitter is on PIN #3
    irsend.enableIROut(38);
    IREmitterOn();
}

// Use this function instead of delay() as delay() does not work in interrupt callbacks
void pause(int ms) {
    // We need a loop as the largest value for delayMicroseconds that will produce an accurate delay is 16383
    for (int i = 0; i < ms; i++) {
        delayMicroseconds(1000);
    }
}

void IREmitterOff() {
    irsend.space(0);
    pause(60); // 60 ms is OK for my TSOP but should be tuned
}

void IREmitterOn() {
    irsend.mark(0);
    pause(10);
}

void switchOffOnIREmitter() {
    IREmitterOff();
    IREmitterOn();
}

void checkIRBeamBreak() {
    int val = digitalRead(PIN_DETECT);
    // LOW : no beam break
    // HIGH : beam break
    if (val == LOW)
        return;

    detachInterrupt(digitalPinToInterrupt(PIN_DETECT));
    switchOffOnIREmitter();
    if (digitalRead(PIN_DETECT) == HIGH) {
        Serial.println("IR BEAM BREAK !!!!");
    }
    attachInterrupt(digitalPinToInterrupt(PIN_DETECT), checkIRBeamBreak, RISING);
}

void loop() {

}


Connecting ACS 712 30A to my Solar Panel with Arduino

I am not sure if an Allegro ACS712 30Amp chip could handle the voltage/current of my system which is usually over 60v dc and 4-5 amps.

Easily. It's designed for mains voltages up to 30A. You're using a fraction of that. You could even use the 20A version to get more accuracy and resolution.

  The confusing part here for me is that the solar panel is connected via an MPPT charge controller to my 1.5 KVA inverter which in turn powers my house equipment, and I am not sure if the two connecting ends of the ACS712 can handle this load (which sometime exceeds to over 450 Wh) if connected in between the wire connecting the panel and charge controller.

Why is that confusing? If you're monitoring the feed between the solar panel and the charge controller what comes out of that system at the other end is of no concern. Just because you are drawing a larger current from the output doesn't mean that the solar panels are providing that current - that comes from the batteries. Now if you were monitoring the current to/from the batteries that would be a different matter. You'd need to calculate the peak current that your house would draw at mains voltage then convert that to the current at the battery voltage (converting to watts in between is a good step. Note that Wh is meaningless when you want a peak value - Wh is a total power over a period of time ["area under a curve"], but you don't care about time, only peak ["maximum value of curve"]).


What's the problem with program , continously beeping buzzer

noTone()

Description

Stops the generation of a square wave triggered by tone(). Has no effect if no tone is being generated.

NOTE: if you want to play different pitches on multiple pins, you need to call noTone() on one pin before calling tone() on the next pin.


OCR2A doesn't do anything because the timer is in 'normal' mode. In normal mode the timer will just count to 256, not 125. Which would mean the you get a serial.print every 2.05s.

You need to use CTC mode. Do this by setting the WGM21 bit to 1.

TCCR2A = _BV(WGM21);


How to vary the frequency of a PWM sinewave with arduino uno?

First thing, you must find a way to output the samples at a steady rate.
Your best bet is to use a timer. Ideally, you want to use the same timer
used for the PWM output, in order to have them synchronized. See for
example how it is done in the Mozzi sound synthesis
library.

Then you can lower the frequency by repeatedly outputting the same
value: if you output every value once, you get the “base” frequency
(sample frequency ÷ 1024). If you output each value n times you get
the base frequency divided by n. Conversely, you can get higher
frequencies by skipping samples. For example, if you output only every
other sample, you get twice the base frequency.

These two approaches can be conveniently combined in a very simple code:
you keep a phase variable and, on every sample, you increment it by an
amount proportional to the desired frequency. You then use the higher
bits of the phase as an index into your array. The lower bits then serve
only to increase the frequency resolution and allow frequencies lower
than the base one. Here is a simple implementation:

const uint8_t pin = ...;
uint8_t frequency;

// Call periodically.
static inline void output_a_sample()
{
    static uint16_t phase;
    analogWrite(pin, SIN1024_DATA[phase>>6]);
    phase += frequency;
}

This lets you set the frequency in units of the sampling frequency ÷
216, i.e. the base frequency ÷ 26.

Note that the phase here is 16-bits: 10 bits for the array index and 6
bits for the fractional part. Since all the bits are used, you do not
need to handle the rollover: a uint16_t automatically rolls over
modulo 216, which is just what you want here. You can use a
32-bit variable if you need more frequency resolution.


Your suspicions are correct. Calling analogReference() with a value of DEFAULT sets the ADC reference to the voltage at AVCC which at least on the Uno R3 is tied directly to VCC and hence has the same voltage as whatever you're supplying there.


Why does the standard Arduino IDE not include the CH341G USB Drivers?

This is simply because the CH340G is not supported officially. The Arduino IDE is meant primarily for genuine Arduinos.

What you could do is repackage the Arduino zip file with the required library and create a basic script file to install the drivers with just a couple of clicks.

Or you could shift to another board that uses the ATMEGA32u4 as this might not require anything special. Have a look here. I don't have tested this board so you will need to check the quality and whether it works with your projects.


Serial read multiple digits and always reading 10 at the end?

for some reason it read integers as 48 more than they are (5 read as 53)

That's because you're not entering numbers, you're entering ASCII characters that represent numbers.

Everything you see on a computer or similar device is not really what is there. It is all translated into a form that we mere humans can see.  Every number is translated into readable characters, and readable characters have to be converted into numbers.

For example, the number 165 is the characters 1 (49), 6 (54) and 5(53).  When you enter that number you are sending those three individual characters.

You see the entire ASCII table here.

Another effect of sending individual characters is that you also send a marker to say "This is the end of the line". That can either be character 13 (Carriage Return), character 10 (Line Feed), or a combination of the two.  You can select which is sent in the Serial Monitor.

You should really use that line ending character or combination of characters to work out how many characters there are in your number so you can convert them into a proper integer value.

Some further reading:

Reading Serial on the Arduino (my blog)
The atoi() function


Individually addressing LEDs in a multiplexed matrix

Thanks to KIIV in the comments I figured it out. Apparently the trick is to rapidly switch between columns or rows without ever having two on at the same time.

With the below code running in the main loop it appears that (0,0) and (1,1) are lit at the same time even though they are actually switching rapidly.

void loop()
{
  digitalWrite(latchPin, LOW);
  shiftOut(dataPin, clockPin, MSBFIRST, B00011110 );
  digitalWrite(latchPin, HIGH);
  digitalWrite(latchPin, LOW);
  shiftOut(dataPin, clockPin, MSBFIRST, B00101101 );
  digitalWrite(latchPin, HIGH);
}


Help connecting an Arduino and an electronic speed controller

HobbyKing, which sells Arduinos and is a great source for motors and controllers, has an instructable on this at http://www.instructables.com/id/ESC-Programming-on-Arduino-Hobbyking-ESC/

I found another on the OpenROV site, at http://community.openrov.com/forum/topics/how-do-i-activate-electric-speed-controller-with-arduino

Did you actually try googling "arduino electronic speed control" before coming here?


"SparkFun SAMD21 Mini Breakout" 'Serial1' was not declared in this scope

Ahhhh, I figured it out.  I had to add #include "Arduino.h" to the .cpp file.