Not only must cnt variable be declared volatile, but accessing it from the main loop must also be protected because:

it can be modified by an ISR
it is longer than 1 byte

In AVR architecture (8-bits), read/write operations on bytes are guaranteed to be atomic, i.e. no function can access a byte while it is read/written by an ISR.

However, operations on types larger than bytes are not atomic!

This means that reading e.g. an int variable from your main loop might be interrupted in the middle of the operation (only 1 byte read) by an ISR that could modify the value (both bytes this time); then when the ISR is finished the main loop would resume reading the second byte -modified by the ISR- of the variable, while keeping the first original byte -not modified by the ISR.

I would advise you to write a pair of functions to read and write cnt in a protected way, i.e. with interrupts disabled:

volatile int cnt;

void set_cnt(int val) {
    uint8_t status = SREG;
    cli();
    cnt = val;
    SREG = status;
}

int get_cnt() {
    uint8_t status = SREG;
    cli();
    int val = cnt;
    SREG = status;
    return val;
}

What those functions do are:

get the current status of exceptions (from SREG register)
disable exceptions with cli()
access cnt without any risk of it being accessed concurrently
restore initial status of exceptions (to SREG register)

Everywhere in your code (except in code called from an ISR where it is not necessary), you must then call these functions to access cnt variable.


How can I get my Arduino to recognize a specific object using some kind of sensor?

You can get an RFID reader for $7 from eBay:

Cards are around 30 cents:

I have example code for an entry control system which uses that reader.

The cards tend to activate at around 3 cm to 5 cm, so that sounds about right. Of course they aren't particularly directional, but if you are driving in a certain direction and it detects a card it is probably in front of you (however possibly off to one side).

You could combine card detection with simple range finding using an ultrasonic detector.


The ATmega32U4 already comes programmed with a bootloader that allows programming via USB; once you've added the basic hardware for a USB connection you should be able to use AVRDUDE, FLIP, etc. to upload firmware to the device.

Having said that, putting an ISP connection as per AVR042 is highly recommended regardless.


How can I stop my Arduino UNO rev 3 from briefly turning on digital output pins on startup or reset?

Digital pin 13 will be turned on briefly as part of the bootloading process (it flashes a few times). Thus this is not a good choice of pin for a device like a motor to be connected to. Also if you are uploading a new sketch the Tx pin (digital pin 1) will be turned on and off.

You can change the processor fuses to not use the bootloader, which would avoid these issues, however then you have to change them back to upload a new sketch - unless you upload using ICSP instead of the bootloader.

As Gerben and Majenko have pointed out, any other issues could be from "floating" pins which some devices might interpret as having a HIGH on them, possibly. Pull-down resistors could help there (or pull-up if that is more appropriate).

The ideal thing could be to structure your system in such a way that the two pins (1 and 13) which come on during the bootloading process are connected to something "harmless" (eg. an LED) rather than "harmful" (eg. a motor).


It should be no problems as long as you can get enough digital inputs into the Arduino.  Search for the library KeyPad, it lets you define the pins that control each row and column and so you could use 2 2*2 keypads quite easily.

I think Keypad is very easy to use, but if you get stuck, just show what code you have so far and describe the problem and people will help you.


Switched from 3ft to 10ft connection wires. My setup doesnt run correctly now. Timing issues?

The pins of logic chips and processors are not line drivers and will not operate properly when used as such. Sometimes you may get lucky but that generally would be intermittent in operation. They make drivers to drive wires off board from the controller and other chips that are receivers on the other end. This needs to be done with each digital line. There are some specialty drivers such as I2C repeater chips, RS485 etc. Remember the wires are antennas and the system is operating at a high enough frequency to be a great radio transmitter. The main thing is to isolate the controller wires from the world.


Trying to pass a char to software serial with a button press

As pointed out by Edgar you should debounce the button. Perhaps increasing the delay() should do the trick.

Try with 100-200 milliseconds.

With this edit you can delete Once unless you are planning on using it somewhere else.


How to connect D1 mini and ATTINY85 over data wire

ATTinyCore seems to come with a Wire library implementation presenting the same interface as you find in other Arduino board packages.  The damellis package doesn't, so if you've been trying to use that one, I'd suggest switching to ATTinyCore.
To get started you should be able to use the ESP8266-Arduino Wire library's Master Writer example with ATTinyCore Wire library's Slave Receiver example.  To be clear, you don't need to get them from github, they should be available in the File/Examples menu.  Because the interface is the same, you may find that it doesn't matter which board from which you take the example.
I don't know that I've ever used this Wire library in ATTinyCore; my only memory of using I2C slave no an ATTiny85 was coding it directly myself, but I expect it works fine.  I may try myself to confirm though.
On the ATTiny85 you'll be using DIP/SOIC pin 7 (PB2) for the SCL signal.  And DIP/SOIC pin 5 (PB0) for the SDA signal.
If I try it myself later I'll update this with more details.
More details
I don't have a D1 mini.  I do have this NodeMCU clone though.  According to the pin maps, the D1 mini's D1 and D2 pins are same as on the NodeMCU, that is GPIO5 an GPIO4 respectively.  I wired it together as shown here:

I've drawn some lines on the lower part of the image where the camera angle is bad.  The smaller inset images are just for showing a better angle there.  The yellow and white leads carrying I2C "Wire" data are doctored simply because they went out of frame.
Don't take the "5V" on the ISP cable breakout too literally, that line is at 3.3V (from the NodeMCU 3.3V pin).
ATTiny85 had the following code loaded onto it.  It is just the ATTinyCore slave receiver example with unnecessary comments removed and code to set the LED based on whether it receives a non-zero byte in the I2C ("Wire") transaction:
#include <Wire.h>

static const int LED_PIN = 4;
static const int SLAVE_ADDRESS = 0x08;

void setup() {
  Wire.begin(SLAVE_ADDRESS);
  Wire.onReceive(wire_receive);
  Serial.begin(9600);
  pinMode(LED_PIN, OUTPUT);
}

void loop() {}

void wire_receive(int howMany) {
  if (Wire.available()) {
    digitalWrite(LED_PIN, Wire.read());
  }
}

The following was loaded onto the NodeMCU board.  Likewise derived from the ESP8266 Arduino Wire master-writer example.  Set the local ESP8266 led when it sends the state over to the ATTiny85.  The result is that the ATTiny85 and ESP8266 change their LEDs every 1 second together.  The NodeMCU module is wired to light the LED on a LOW, the ATTiny85 to light on a HIGH, so when one is lit the other is not.
#include <Wire.h>
#include <PolledTimeout.h>

#define SDA_PIN 4
#define SCL_PIN 5
const int16_t I2C_SLAVE_ADDRESS  = 0x08;

void setup() {
  pinMode(LED_BUILTIN, OUTPUT);
  Wire.begin(SDA_PIN, SCL_PIN);
}

void toggle_led() {
    static bool led_state;

    led_state = !led_state;
    digitalWrite(LED_BUILTIN, led_state);
    Wire.beginTransmission(I2C_SLAVE_ADDRESS);
    Wire.write(led_state);
    Wire.endTransmission();
}

void loop() {
  using periodic = esp8266::polledTimeout::periodicMs;
  static periodic nextPing(1000);

  if (nextPing) {
    toggle_led();
  }
}


Arduino Uno - Multiple modules for HDMI switch device

The relay wiring diagram you are following is just plain bizarre and the strangest one I have ever seen.

Ignore it. It is completely incorrect.

You only need one pin to control a relay, so disconnect it from pin 13.

The switched side can connect to anywhere where you would normally use a switch - such as to switch power to an LED connected between +5V and GND with a suitable current limiting resistor.

You can use any available pin to control the relay, and that includes pins 0 or 1 if you aren't using serial communication.  Note that with the relay connected to one of those pins it will most likely activate and buzz while you upload a sketch - best to disconnect it at that point and reconnect it afterwards.

Devices like relays and LEDs need their own dedicated pin. They can't be shared with other functions or each other.

The only devices that can share pins are devices which connect to a bus, such as SPI or I2C.


Are there any online data analysis websites for arduino IoT projects?

To send data to cloud you will need an internet shield and given that the individual plants are far apart, you will need a wifi shield for each plant that you want to monitor most likely the yun shield.
Now for online services, there are a few like Temboo, Pushingbox, Initial State, Cayenne, Xively.
Each of them works differently and you will need to choose which best suit you.


Wiring for Arduino Mega and multiple MPU 6050/Gy 521?

MPU-6050 uses I2C for comm's, yes?
Connect all the SCLs in parallel to the Mega with a 4.7K, or 3.3K, pullup resistor. Same for the SDAs. I2C is D20, D21 (or D21, D22) on the Mega.

The MPU-6050 has an A0 pin to select from one of two addresses, let's call them Add0 and Add1 for simplicilty.
Connect each MPU-6050 A0 pin to a unique Mega pin.  When none are being addressed, have each Mega output high. When one MPU-6050 is to be accessed, take that device's A0 pin low and communicate with it using Add0. The other's will be looking for communications at Add1 and thus will not respond.

If the MPU6050 is a 3.3V device, then you should also remove the pullup resistor network package on the Mega that pulls SCL/SDA to 5V.  There are 2 pullups in a very little 8-pin package, the other 2 are not used. Connect the 3.3K or 4.7K pullup resistors discussed above to 3.3V.

This is the part, RN1, on the Mega R3 board. It may not be marked as such on the board. Remove it, or cut the traces next to the pad legs, one on the left side (connects to pin 3), one on the top (connects to pin 2).


Working on my second project and I'm confused about proper procedure for turning on the arduino

If you've rewired an Arduino board for a new project, such that outputs from the currently-loaded sketch may cause problems, temporarily jumper from ground to Reset, to hold the MCU (ATmega328, etc.) in reset until you are ready to load the new sketch.  Pull the jumper upon starting a download, of either your new project or an empty sketch as suggested in Majenko's comment.  Typically, Arduinos are reset at the beginning of each download.

Arduino boards (Uno, Nano, Mega, et al) that use an additional chip (FT232, Atmega16U2 or 32U4, CH340G, etc) as a USB interface should be able to register as USB devices even when the MCU is reset.  Arduino boards without a separate USB chip (Leonardo, Micro, et al) should not.


Fast I2C communication between ESP8266 & PCF8591

This line

brzo_i2c_start_transaction(0x48,400);

Sets the SCL frequency to 400kHz.

According to the Datasheet for the PCF8591 the maximum SCL clock frequency is 100kHz.

The other issue may be the "repeated_start" flag on brzo_i2c_write.

If you look at the examples, and "apply" that to your code, your would do something like:

uint8_t ICACHE_RAM_ATTR get_temp(float *t){
  uint8_t bcode=0;
  brzo_i2c_start_transaction(0x48,100); // changed 400 to 100
  buffer[0]=0x04;
  brzo_i2c_write(buffer,1,true); // changed to true because
  brzo_i2c_read(buffer,2,false);
  bcode=brzo_i2c_end_transaction();
  *t=((buffer[0]<<8)|buffer[1]);
  return bcode;
}

My understanding of the code is that you would set repeated_start to true in the write if you want to then immediately read - which in your case you want to.


Analog inputs showing value even there is nothing connected to it

Your input is floating if nothing is connected.  It is reading whatever random noise it happens to pick up.  That's what it is supposed to do.  For it to read 0 it would need to be connected to ground.  Google "floating input" for more info.


Student Project Inquiry(Building a Self Balancing robot)

The MPU6050 is an I2C device.  By default the Arduino uses the internal pullup resistors in the IO pins for the pullups on the I2C bus.

This is bad - it makes the I2C bus very susceptible to noise, and motors are very noisy devices.

You need to make sure you have appropriate pullup resistors on the I2C bus (3.3KΩ is good) and keep the I2C wires as short as you reasonably can.

Also keeping power sources as separate as possible is essential.  Don't be tempted to use the 5V power from the Arduino to power your motors - you must use an external power source, or the motors will cause havoc with the microcontroller circuitry and communications.


As noted by markshancock, you are using an older version of the Adrafruit Motor Shield library meant for the version 1 of the board (you have the version 2.3), and according to their forum they are not compatible (they use different communication protocols) use the newer version of the library https://forums.adafruit.com/viewtopic.php?f=31&p=276888


Is the arduino nano 33 IOT schematic wrong?

It is correct. You are looking at the wrong datasheet.

This is the correct one:

https://assets.nexperia.com/documents/data-sheet/PRTR5V0U2X.pdf


Is there a real alternative now to using GSM for data sending?

GSM (or more realistically now, LTE) is really the only option.

Simply put: you need some method of accessing the internet, and unless you create your own local infrastructure that means using the mobile phone system. It's the only system that is virtually everywhere and doesn't require you to install your own communication system.

So that means some modem device that can communicate with the mobile phone system. GSM is what it used to be, although some mobile companies are now deprecating the GSM system and only really providing UMTS (3G) and LTE (what will eventually be 4G), but LTE modems are quite expensive still.

So yes, you need a SIM to do it. You can't access a mobile phone network without one.

One option that could be a cheaper possibility would be to get a cheap second hand smartphone off eBay (or dig out your old one from the bottom of the desk drawer) and use that as your own mobile WiFi hotspot. Your Arduino device connects to the phone with WiFi, and the phone connects to the UMTS or LTE network using a cheap PayG SIM.

LoRA is a technology that is gradually becoming more popular and allows long range wireless communications at low power and low cost. There are areas where LoRA is becoming available, such as in Munich. Should LoRA become available in your area, or should you invest in your own infrastructure, that could become a viable alternative to using the mobile phone network.


Failed to initialise SD card on Leonardo

A Leonardo has the SPI pins on the ICSP header, not on pins 11, 12, 13.

And a Pro Micro has the SPI pins on 14, 15, 16.


Arduino Zero - Stepper control (interrupt)?

As Stepper::updateAll(); isn't shown I don't know what it does.  For accurate timing it would make sense to use hardware-operated output-compare output pins like TIOAx and TIOBx, instead of running some code to drive the pins when an interrupt occurs.

If you need to control several wires per motor – such that a pulse on a single output line isn't enough – you might consider using a 74HC595 (or other shift register) to transfer the bits.  Thus, each time an output compare occurs, the  TIOAx and TIOBx line would pulse the ST_CLK (store-clock) line of the SR, to transfer bits from the shift chain flipflops to the output flipflops; then, at its leisure the interrupt routine can shift the next set of bits out to the '595, ready to be transferred at the correct moment, when the next output compare occurs.

During stepper acceleration or deceleration, the timer count-limit would also need to be updated within the ISR.


As noted in the second paragraph on Adafruit's Graphics Library webpage,

  First thing to note is that color is 16-bit, and that includes Red, Green and Blue in a 16-bit variable. The way the color is packed in is the top 5 bits are red, the middle 6 bits are green and the bottom 5 bits are blue.

If you want to specify 8-bit color components, you could write an intermediary routine to translate from that form to the 565 form.  For example:

#define rgbDrawPixel(x,y,r,g,b) drawPixel(x,y,(((r)&0b11111000)<<8)|(((g)&0b11111100)<<3)|(((b)&0b11111000)>>3))

Note, this assumes the TFT library you're using has the same specs as Adafruit's.  That might or might not be; I don't know how to account for a 255 color number showing up as blue rather than white.


You could use ESP8266 and ESP-LINK firmware to update the arduino firmware over the wire. Its also enables you to debug it wirelessly. What it does is provide a serial link but over wifi. Just like connecting it via cable.


Level tracking using optical or capacitance sensors

What about measuring this with two resistive probes - the electricity will go through down one probe to the top of the water, across the water, and up the other probe. You can measure how much of the probe it went down, by measuring the resistance. You would need the probes to be a specific, very consistent distance apart, and be made of resistance wire.

Another option is to use a float of some kind, and measure it this way. This is a lot easier if all you need to know is full/not full.


Simultaneously reading data from multiple serial ports

My question here is how can I simultaneously read out all the data from the different serial ports on the arduino mega sketch.

As you are using several serial ports data can already be received simultaneously. Each serial software class (Serial1, Serial2, Serial3) has an internal buffer where data is stored until it is read.

You only need to read the data before the internal buffers are filled and there is a risk for over-flow. Check that data is available and read as usual per serial port. Avoid any blocking calls to avoid buffer over-flow.

Cheers!


It reports the difference between the head and the tail of the circular buffer the incoming characters are stored in.

The way serial reception on the Arduino works is:

A character is received into the internal hardware RX buffer (UDRx)
An interrupt is triggered
An interrupt service routine (ISR) is executed
The character in UDRx is read and, if there is room, stored in a circular buffer (_rx_buffer).
The head pointer of _rx_buffer is incremented and wrapped if needed.

When you actually read a character with Serial.read() the following happens:

If the head and tail of rx_buffer are equal, return -1
Get the character at tail from _rx_buffer
Increment tail and wrap if needed
Return the character

So when you use Serial.available() it just returns head - tail (taking into account the wrapping, so the sum is slightly more complex than a simple subtraction).

You should examine the files HardwareSerial.h and HardwareSerial.cpp in the Ardino AVR core software.


what is causing my esp8266 setup function to reinitialise?

When a program crashes, you can debug the crash based on the Fatal exception number.

 Exception (9)  Unaligned read/write operation addresses
     1. Unaligned read/write Cache addresses
     2. Wild pointers

This leads than as Juraj points out to a WD reset:

 rst:4     Hardware WDT reset

To get the exact part of the code paste the >>>stack>>> into the window of the espExeption decoder in the ArduinoIDE. Details how to install and use.

My educated guess is that the heavy use of String class in combination with lot of String operations with the getHotspot function leads to heap corruption and crashes the Esp8266. Try defining fixed char arrays and get rid of the String class to get a stable running system. Post the espExeption decoder result as edit to your question if you thing something else might be fishy


Methodology for designing/prototyping LED patterns

For designing patterns for visual evaluation, it would be better to just have the arduino/controller be a pass-through from something like a full computer. There is a project called FadeCandy, which allows one to send various patterns to a WS2812 chain using a protocol called Open Pixel Control.

Some options would be to build or buy a FadeCandy board, or to implement the OPC protocol on your own arduino so that you can play around with test patterns and designs in a rapid development environment like Python or just making the raw patterns in a file and dumping that to your device over the serial port or TPC, etc.

Once you have your patterns or design the way you want it, then you can translate it to C code and FastLED, knowing you have a fixed specification you are trying to implement, rather than reflashing an arduino for every iteration.


How high of a baud rate can I go (without errors)?

There are several factors here:

How high of a baud-rate can the ATmega328P MCU achieve?
How high of a baud-rate can the USB-Serial interface achieve?
What is the oscillator frequency on the ATmega328P?
What is the oscillator frequency on the USB-serial interface (if it has one)?
How tolerant is the USB-serial interface of baud-rate mismatch?

All of these factors are relevant to determining the maximum achieveable baud rate. The ATmega328P uses a hardware divisor from it's clock-rate to generate the base-clock for the serial interface. If there is no integer ratio from the main clock to the bit-time of the desired baud rate, the MCU will not be able to exactly produce the desired rate. This can lead to potential issues, as some devices are much more sensitive to baud-rate mismatch then others.

FTDI-based interfaces are quite tolerant of baud-rate mismatch, up to several percent error. However, I have worked with specialized embedded GPS modules that were unable to handle even a 0.5% baud rate error.

General serial interfaces are tolerant of ~5% baud-rate error. However, since each end can be off, a more common spec is +-2.5%. This way, if one end is 2.5% fast, and the other is 2.5% slow, your overall error is still only 5%.

Anyways. The Uno uses a ATmega328P as the primary MCU, and a ATmega16U2 as the USB-serial interface. We're also fortunate here in that both these MCUs use similar harware USARTs, as well as 16 Mhz clocks.

Since both MCUs have the same harware and clock-rate, they'll both have the same baud-rate error in the same direction, so we can functionally ignore the baud error issue.

Anyways, the "proper" answer to this question would involve digging up the source for the ATmega16U2, and working out the possible baud-rates from there, but since I'm lazy, I figure simple, empirical testing will work.

A quick glance at the ATmega328P datasheet produces the following table:

So given the max stated baud-rate of 2 Mbps, I wrote a quick test program:

void setup(){};

void loop()
{

  delay(1000);
  Serial.begin(57600);
  Serial.println("\r\rBaud-rate = 57600");
  delay(1000);
  Serial.begin(76800);
  Serial.println("\r\rBaud-rate = 76800");
  delay(1000);
  Serial.begin(115200);
  Serial.println("\r\rBaud-rate = 115200");
  delay(1000);
  Serial.begin(230400);
  Serial.println("\r\rBaud-rate = 230400");
  delay(1000);
  Serial.begin(250000);
  Serial.println("\r\rBaud-rate = 250000");
  delay(1000);
  Serial.begin(500000);
  Serial.println("\r\rBaud-rate = 500000");
  delay(1000);
  Serial.begin(1000000);
  Serial.println("\r\rBaud-rate = 1000000");
  delay(1000);
  Serial.begin(2000000);
  Serial.println("\r\rBaud-rate = 2000000");
};

And then looking at the relevant serial port with a serial terminal:

So it appears the hardware can run at 2,000,000 baud without problems.

Note that this baud rate only gives the MCU 64 80 clock-cycles per byte, so it would be very challenging to keep the serial interface busy. While the individual bytes may be transferred very rapidly, there is likely to be lots of time when the interface is simply idle.

Edit: Actual Testing!

The 2 Mbps is real:

each bit-time is 500 ns, which matches exactly with what is expected.

Performance issues! Overall packet length:
500 Kbaud:

1 Mbaud:

2 Mbaud:

Note: The noticeable overshoot is due to poor scope probe grounding practices, and is probably not real. I'm using the ground-clip-lead that's part of my scope probe, and the lead-inductance is likely the cause of the majority of the overshoot.

As you can see, the overall transmission length is the same for 0.5, 1 and 2 Mbaud. This is because the code that is placing the bytes in the serial buffer is poorly optimized. As such, you will never achieve anything better then an effective 500 Kbaud, unless you write your own serial libraries. The Arduino libraries are very poorly optimized, so it probably wouldn't be too hard to get a proper 2 Mbaud, at least for burst transmissions, if you spent a bit of time on it.


That is a perfectly legitimate use of the RESET pin. Holding the chip in reset perfectly valid. Everything in the chip will be stopped.

Releasing it will start your sketch from the start again perfectly fine.

The only negative point is that your switch will be pulling power through the reset pin's pullup resistor, so will waste a little power.


PIR sensor code logic works on Mega but not on Yún

The Arduino Leonardo uses the ATmega32U4 microcontroller which uses lower logic levels for the digital inputs. Perhaps that is not compatible with the PIR sensor. You can simulate the PIR sensor with a piece of wire and connect it to 5V or GND.

For the Leonardo, sometimes "SerialUSB" is used instead of "Serial". But if see a message on the serial monitor then "Serial" is okay.

If you can't make it work, then try to reduce the number of variables. In this case, remove the Yun shield and try it with the Leonardo board.

The Arduino Mega 2560 and Arduino Leonardo have both a 8-bit microcontroller and 'millis' works on both in exactly the same way. Therefor 'millis' itself or the variables can't be the problem.


Why does the Arduino Uno WiFi network connection drop when requesting a page?

I saw this error when I was running low on RAM. The Arduino Uno WiFi appears to drop the network connection in low memory situations. One fix that made a significant difference for my program was to wrap all of the string literals in the F() macro. This moves the strings from ram to flash storage, and in my case quickly freed 500 bytes of SRAM (25% of the available RAM on this board).
For example, replace:

client.println("HTTP/1.1 200 OK");

with

client.println(F("HTTP/1.1 200 OK"));

Some other memory optimization may also be necessary.
Another possible cause of these symptoms would be low voltage, possibly from trying to draw too much power from the board to power external devices, but in my case there were no external connections, and I confirmed it was a low-memory issue.


Why can't I include a library in another one?

Nested includes lead to these convoluted error messages and are in general, a PITA for the next reader to follow & understand. It is better practice for the dependent library to test, at compile time, for the existence of its required libraries and for each one found missing, issue:

#error DepLibe.h: Missing required include file ReqLibe.h

Most .h files guard against multiple-inclusion by

#ifndef _REQLIBE_H_
#define _REQLIBE_H_
// library definitions here

or some variant of it. DepLibe.h can test for these guard symbols. DepLibe.h should document the dependencies in prominent comments.


The only alternative structure I can think of is, since you have a number of data fields to send, you could create a struct to contain all the fields. Write the gathered GPS data to the file in its raw format, with file.write(&your_struct, sizeof(your_struct)) and read in a similar manner into a struct.

This will reduce the number of bytes written or read for any data point, and
Reduce the overall size of the file, compared to your original method, for the same number of GPS points.

The former improvement means there will be about 3 times as many GPS data points in a single block of data read from or written to the SD card, when compared to your current structure. Another more subtle advantage is that each data point occupies a known number of bytes in the file, making file navigation potentially easier. But you can only use this structure if you don't intend to view the CSV file with some spreadsheet program like MS Excel. You could, of course, very easily write your own PC program to parse the file and write to proper CSV. The Python struct module is very capable.

However, if you wish to continue with your current format, you can keep track of your current position in the file with file.position(); no need to use # as an indicator. You create 2 position variables, one to hold the position of the next line to be uploaded, curr_pos, and the other to hold the position of the end of the file for writing new data, end_pos. Initialize the former to 0.

You gather data as usual, and after 5 mins, you save the current file position to end_pos and seek to curr_pos with file.seek().
You read a line from the file and send it to the server.
If it's sent successfully (use the return code), you update curr_pos with file.position() so that it's now pointing to the next line in the file to be uploaded and go to step 2.
Else if the upload fails perhaps due to service, you stop uploading and don't update curr_pos. You seek to end_pos with file.seek() and go to step 1.

You will, of course, use available() to know when you've hit the end of the file to stop uploading, or you can compare curr_pos with end_pos for equality, whichever's more direct for you.

This involves a lot of operations on the file and I/O operations don't come cheap with SD cards, both in terms of current drawn and latency. Depending on how often you collect data and if you don't need to view it on a PC, you might consider some other means of storage (SPI flash, perhaps) or use a more capable Arduino like the Mega with more RAM and store the data temporarily in an array before upload, granting you faster access by orders of magnitude and much reduced power drain in the long term, since each block of file data will be accessed only once.


Plugged in shield off by one, now all analogues read high

There is not (yet) enough information to be certain, but it seems likely that you have damaged the Arduino.

If damage has occurred it's more likely to have been caused by what happened on the other side of the board, where pins carry power supply voltages. You do not say what your power source is or where it is connected (USB, 5V in, Vin, ...) but I'd guesstimate that the connection of UNO 5V to Shield 3V3 allowed back feed into the UNO by any of a number of possible paths. UNO Vin connects to shield ground and a second UNO ground connects to a second UNO ground - so if the UNO was powered via Vin you'd expect the power supply to have been shorted. This might damage some power supplies but usually not.

Can you please advise what voltage was connected and to what pin. And do shield pins all offset by 1 on the other side, as I've shown?


It may be a dumb question, but are you sure your car CAN bus is 500kbps?
Have a look at this:
pdfLink
Maybe try different speeds? 100kbps maybe?

Also, look at the schematics of your shield? Is the bus termination resistor soldered on the board?


Atmega328 and 4Digit 7 Segment ghost blinking!

You change cathodes (digits) before latching in the new data. So for a spit second the data for the previous digits is shown on the current digit.
Swapping digitalWrite(CAS[count], HIGH); and digitalWrite(latch, HIGH); should fix that.


On a motor after a continuous input of a certain amount of time

You must store the state of the last readings and do something like this:

    //Off-loop:
    bool state_changed = false;
    unsigned long time_in_state = 0;
    unsigned long last_reading = 0;

    //On-loop:
    if (sensorValue > treshold && !state_changed) {
        time_in_state += millis() - last_reading;
        last_reading = millis();
    }
    else {
        state_changed = true;
        time_in_state = 0;
    }

    if (time_in_state > TIME_REQUIRED) {
      digitalWrite (3, HIGH);
    }


Changing the brightness on a Hitachi HD44780 LCD screen

Place a transistor in series with a 33R resistor between the LCD pin 16 (backlight ground) and GND and switch the transistor on and off with a digital pin. That way you'll be able to turn the backlight on and off.

You can have a finer control over brightness if you put a PWM pulse on said pin. Just call analogWrite(D3, value) where value is the desired brightness.

The schematics is below. It's from Freetronics 16x2 LCD SHield.


Temperature and Humidity Sensor TinyShield (No device found on com5)

The below was the issue, i was using the wrong broad and processor.

Thanks for the help!


NRF24L01+ Getting Started Acknowledge Failed

The Arduinos 3V3 does not privide enough current. To eliminate this as a source of your problem you can use a ceramic capacitor of 100µF across VCC and GND pins of the nRF24L01+ module or buy a 5V to 3V3 step down converter specially made for nRF24L01.


How can I declare custom pins when using with ESP8266 in MPU9250 library

You can use Wire.pins(sda, scl); before IMU.begin();.
IMU.begin() then calls Wire.begin() without parameters.


Using a slightly modified version of your sketch, I receive the following output in the serial monitor when I enter the number 2.

  Current Conversion Mode: Enter your mode of Conversion (number 0 - 3):
  Number recieved: 2

  Current Conversion Mode: Enter your mode of Conversion (number 0 - 3):
  Number recieved:

  Conversion mode unsuccessfully set - Please enter a number 0 - 3
  Current Conversion Mode: Enter your mode of Conversion (number 0 - 3):
  Number recieved:

  Conversion mode unsuccessfully set - Please enter a number 0 - 3
  Current Conversion Mode: Enter your mode of Conversion (number 0 - 3):

If you change mode to an int then retest, you'll see the second and third "Number recieved" are 10 and 13. That would be the New Line and Carriage Return characters. When you send data via the serial monitor, do you have "No Line Ending" selected or something else?

Here is a test sketch:

char mode;

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

void loop()
{
  if (true)
  {
    Serial.print("Current Conversion Mode: ");
    //Serial.println(sensor.getConversionMode());
    Serial.println("Enter your mode of Conversion (number 0 - 3): ");
    while (Serial.available() == 0); // Waits for the user input
    mode = Serial.read(); // Reads the input string from serial port
    Serial.print("Number recieved: ");
    Serial.println(mode);
    delay(500);
    if (mode == '0' | mode == '1' | mode == '2' | mode == '3')
    {
      //sensor.setConversionMode(mode);
      Serial.println();
      delay(500);
    }
    else
    {
      Serial.println("Conversion mode unsuccessfully set - Please enter a number 0 - 3");
    }
    delay(1000);
  }
  else // Runs when the device was unable to setup properly
  {
    Serial.println("Device failed to setup");
  }
}


Sharing serial Rx to read a push button on ESP8266-01

I have experimented with my NodeMCU (ESP8266-12F, but the core chip is the same ESP8266EX).

First, the theory: UART is a asynchronous serial protocol. It has a configuration which consits of the baud rate (bits per second), parity bit (enabled or not) and number of stop bits (between 1-2). A common configuration is "9600N1", meaning 9600 bits per second, no parity bit, 1 stop bit.

If you want to trasmit the bitstring 0101 0101 with no parity, 1 stop bit, the RX line voltage will be:

RX line idles in high state (for us: 3.3V). Transmission is started by the start bit, which means that the line is pulled LOW. Then, the bits are transmitted LSB to MSB, followed by parity (if enable) and the stop bits.

I wrote the sketch

#include <Arduino.h>

void setup() {
    //use 300 Baud, lol
    Serial.begin(300);
}

void loop() {
    if(Serial.available()) {
        char readChar = (char) Serial.read();
        Serial.println("Read char: " + String(readChar) + " hex " + String((int)readChar, HEX));
    }
}

When transmitting a normal "A" (binary: 0100 0001) over serial, it looks like this in a logic analyzer:

When I connected a pulled-up button the RX line and press, the signal goes as

As one can see, the analyzer sees the pushing down of the button as a start bit, but the timing is way of. The line is pulled back to high much later. The time slot for the stop bit (which must be 1) was missed, so the logic analyzer displays "FRAMING ERROR". But the UART circuit inside the ESP8266 doesn't seem to care. It reads this as the transmission of a byte of the value "0x00".

Serial output: Read char:  hex 0

So, in response to the question "what would happen the push button was pressed?" we can say: At this speed of 300 baud (lowest possible setting), the UART received a bogus transmission but still reads it as an incomming 0x00 byte. However, depending on the bouncing of the signal due to the button presses, other received byte values might well be possible. You could be able to de-bounce the button to make the signal more stable, timing wise.

Anyway, you should not make a push button act as a crude UART transmitter if it isn't the absolute last possible solution. Depending on your application, you might be able to use the solution from this question and switch the function of the TXD0 and RXD0 to GPIO (more info). If you know exactly when to expect a button push, switch the pins to GPIO mode before and poll the status of the button (or install an interrupt).

However, as a bottom line: If you have no idea when the button will be pushed, then you will be fundamentally unable to distinguish the cause of the RX line falling low at the time the transition happens. It could be the transmission of some actual data (maybe also the zero-byte), but it could have also been the button.

A I²C GPIO port expander like the MCP23017 (link) would make much more sense, especially if you already have an I2C bus. There are also SPI devices available for this.


Stepper motor doesn't start immediately when i pressed the button

You tell it to move whole 200-step revolutions, so once it begins a revolution, it must continue.  At 60 RPM, that should be up to 1 full second after you open pin 2.   Depending on the analogRead(A0)/100, a full revolution could take much longer than 1 second -- maybe 5.86s to 6000s

If you want it to stop immediately, disregarding full revolutions, you could:

      stepsPerButtonpress = 1;

      ...

      if (dir) {
        //Serial.println("clockwise");
        myStepper.step(stepsPerButtonpress);
        //delay(500);
      }
      // step one revolution in the other direction:
      else if (!dir) {
        //Serial.println("counterclockwise");
        myStepper.step(-stepsPerButtonpress);
        //delay(500);
      }

Or you could reduce stepsPerRevolution to the fraction of steps you want to treat as a unit, and increase rpm proportionally.


Once per second? I don't see any problem, I will try to calculate:

3 ports: send + receive 255 bytes, let's say 270 bytes (with start/stop bits, probably way too much) per message:

3 * 2 (send + receive) * 270 = 1620 bytes
4th port: 50 * 6 bytes = 300 bytes

Total: 1920 bps

The serials can easily keep up with this, so that is not a problem.

90 MHz is 90 million instructions per second. As you can see, handling 1620 bytes is nothing ... it could do many more, a factor of multiple thousands more.

Unless of course you want to do heavily calculations for the received/sent data.


nRF24L01 with antenna transmitter and receiver

Search in the code for the line Serial.begin(###) where ### is a number representing the serial speed, also known as baud rate.
This number must match with the baud rate of your serial monitor, otherwise all you get is garbage.

BTW, this has nothing to do with nRF24, this is plain Arduino serial connection.


How do I create a constant loop with an event that only occurs once?

What you want is not to check the distance but to check that the distance condition changed.

static boolean present = false;

Inside loop:

if (present == false && distance <= 150){
    personPresent();
    present = true;
} else if(present == true && distance > 150) {
    personAbsent();
    present = false;
}


can teensy 3.0 or above run fingerprint scanner fps gt-511c1r?

The GT-511C1R is a 5V device. The Teensy 3.0 is a 3.3V device. You will require some level shifting as you would with any 3.3V Arduino connecting to a 5V device.

Besides that, yes, the Teensy 3.0 is more than capable of working with the fingerprint scanner. Will the software work? Most likely, but only trying it will confirm that.


How to control 12v water pump by arduino?

It's not possible to control it directly. You need relay module (better one is with opto coupler).

Or you can use some N-Mosfet like IRF540 with antiparallel fast diode to supress induced high voltage from coil. However arduino output might be weak for fast charge/discharge mosfets gate and it gets hot.


Port Manipulation - fastest implementation

The standard Arduino way of doing this is to use pinMode(). It's not
fast, but it's easy to understand, especially for beginners. And it's
portable across architectures.

If you want to go fast, then you should skip the Arduino functions and
use port manipulation, and avr-libc. The standard avr-libc way of doing
what you want is:

DDRF = _BV(PF2)   // set PF2 as output
     | _BV(PF1)   // also PF1
     | _BV(PF0);  // and PF0

This compiles to two assembly instructions: one for loading a CPU
register with the constant, and the other to copy the register to the
DDRF IO port. Notice that you set the bits for the pins you want to set
as outputs, and you clear the bits for the inputs. By default, all the
pins start as inputs.

The _BV() here is not a function call: it's a macro that expands to
(1 << (x)). The way you write the expression to the right of the =
sign is irrelevant as long as it is recognised to be a compile-time
constant. If you want to see for yourself, you can disassemble the
generated binary with the command

avr-objdump -S -C my_prog.elf > my_prog.lst

You get an assembly listing interspersed with your source. Doing this on
the example above yields:

    DDRF = _BV(PF2)   // set PF2 as output
         | _BV(PF1)   // also PF1
         | _BV(PF0);  // and PF0
100:    87 e0           ldi r24, 0x07   ; 7
102:    80 bb           out 0x10, r24   ; 16

Here, the ldi instruction means “load immediate”, i.e. load a register
(r24) with a constant value (0x07). The “out” instruction copies that
register into port 0x10 (namely DDRF). Both are single cycle
instructions, so the whole sequence takes two CPU cycles.


How to declare and use "Variabled arrays" inside arrays

Something is wrong with your type description:

byte arrayX[4] = {1,2,3,4}; byte arrayY[4] = {5,6,7,8};

byte arrayZ[2][4] = { arrayX[4], arrayY[4] };

Serial.println(arrayX[2]); is equals to '3'.

This is normal ... arrayX[0] = 1, arrayX[1] = 2, arrayX[2] = 3

However, the next one is not good:

byte arrayZ[2][4] = { arrayX[4], arrayY[4] };

You are declaring a byte array, but you add arrayX[4] and arrayY[4] which, where arrayX[4] is the 5th elements of arrayX but it has only 4 elements, so it points to memory outside the array (probably into the next array.

byte arrayX[4] = { 1, 2, 3, 4 };
byte arrayY[4] = { 5, 6, 7, 8 };

byte* arrayZ[2] = { arrayX, arrayY };

Serial.print(arrayZ[0][2]);

This should print 3 (not tested).


How do I change PGA gain in this Arduino program?

The symbol PGA appears in exapmle.ino (sic) twice, once each in lines 28 and 30:

 #define PGA 1                     // Programmable Gain = 1
 ...
 #define VFSR VREF/PGA

It is not used elsewhere in the example or the library code.  The only effect of changing its value from 1 to 32 is to change the value of VFSR, and asVFSR appears only in line 30, that effect is nil.

Looking at the ads1262.cpp file from github, it appears that ads1262::ads1262_Init() initializes register MODE2 to 0x6, via:

ads1262_Reg_Write(MODE2, 0x06);

which per the ADS1262 spec sheet, page 93, table 44, enables the PGA and sets its gain to 1 and sets the sample rate to 60 SPS.

Apparently, if you wish to use some other gain setting, you should define PGA appropriately and put a corresponding setting into MODE2.  For example, if you want to set up a gain of 16 and sample rate of 400 SPS, in setup() you could say

PC_ADS1262.ads1262_Reg_Write(MODE2, 4<<4 | 8); // 4=gain 16, 8=400 SPS

More generally, you could set up some constants for gain codes and SPS rates, and reference those constants when writing to MODE2.  For example, after

enum { GainCode1, GainCode2, GainCode4, GainCode8, GainCode16, GainCode32 };
enum { SPSCode2p5, SPSCode5, SPSCode10, SPSCode16p6, SPSCode20, SPSCode50,
       SPSCode60, SPSCode100, SPSCode400, SPSCode1200, SPSCode2400,
       SPSCode4800, SPSCode7200, SPSCode14400, SPSCode19200, SPSCode38400};

you would say

PC_ADS1262.ads1262_Reg_Write(MODE2, GainCode32<<4 | SPSCode2400);

to set the gain at 32 and the sample rate at 2400 SPS.

(Note, enum is a C language element used to define integer constants.  In an enum, each symbol mentioned without an explicit value has a value one more than the previous symbol, or zero if there's no preceding symbol.  So GainCode1 is 0, GainCode2 is 1, GainCode4 is 2, etc.)

Note, to get better ultimate resolution, you may need to combine multiple readings, or may need to set the ADS1262's filtering parameters.


I had this problem with communication with Arduino Uno (I think that the Arduino Uno, and other boards, with this type of scheme, suffer this problem).

The DTR line on Arduino Uno is connected with RESET, including when you use the Arduino IDE Serial Monitor port, such that the parameter of DTR is false. Yeah, you can fix this with capacitor or catch place RESET EN on board. But when you set setting you can just write:

comport3.setParams(9600, 8, 1, SerialPort.PARITY_NONE, false, false);

The last parameter is DTR and its default is true, the second to last parameter is RTS (it defaults to true too). I set both of these parameters to false and my board reads commands from the computer without resetting.

I write this for other people who had this problem.


Cannot send any UDP packets from ESP8266 Wemos D1

Per the esp8266 subreddit, you need to add a sufficient delay() of 50-100 milliseconds (not microseconds) before going to sleep as none of the udp functions are blocking.


How to keep amperage in serial and parallel?

You haven't said what the voltage rating of your Power Supply is, but if we assume it is a "constant voltage" regulated supply, then it will attempt to maintain a constant voltage up to the rated current capacity (2000 mA).

If you put your LEDs in series, then the voltage from your power supply is distributed across the LEDs, and is therefore lower on each LED. This would cause your LEDs to be less bright.

If you put your LEDs in parallel, then the voltage remains constant.


Bluetooth: sync time from an NTP server via Internet connection shared with Android phone

No, not really. It is possible, but not easily like you want it to be. The HC-06 is a Bluetooth-Serial bridge. In the Bluetooth protocol there are many types of interfaces, that a client device might expose to the master. A Bluetooth mouse exposes a HID interface, a headset exposes a corresponding audio interface and the HC-06 exposes a pure Serial interface. Thus the HC-06 does not support what ever interface is used for tethering.

Ways, that may make it possible:

Change the firmware of the HC-06 for exposing the correct interface and interact with it. For this you need to know how to reprogram the HC-06 and how exactly bluetooth works. I guess this is over your current level.
Write an app for your Andriod smartphone, which plays the Serial-Internet bridge on the phone. The app would translate between Serial and Internet, involving your own protocol on the Serial interface. Easiest, when you just make a specialized app for syncing time, so that it does not have to do any other communication.

And at that point it is just too much work to go either way. It is unlikely, that you find libraries or any code for this, since it just doesn't make much sense. Instead you could move from an Arduino to an ESP, which can directly connect to the WiFi network in question and thus get directly the time from the internet, without tethering. That is way easier and you can use the many libraries, that already exist for that problem.


An Exploring the I/O Performance of the Arduino 101 webpage by Dan Watson has a number of relevant comments:

  The board uses three Texas Instruments LSF0108 level translators to accommodate all of the I/O lines (including the analog inputs). This is an interesting part. It's not really a level "shifter", and it's not a buffer. The Curie is still sourcing and sinking current to the pins, but the voltage levels are clamped at 3.3V on the Curie's side of the chip. In this regard it's kind of like a fancy analog switch. The on resistance of each signal path is in the neighborhood of 10 ohms.

Somewhat later in the article:

  Analog Input Linearity:  Next I tested the analog inputs. I was curious if the level translators affect the accuracy of the readings. I applied a DC voltage on pin A5, starting at 0V and increasing to 3.3V in 100 mV steps. At each step, I recorded the 10-bit analog-to-digital (ADC) readings reported by the Arduino 101. I then created a graph of the data, which is shown [on the webpage]. As you can see, the results are pretty linear across the entire input range. Spot-checking a few values, I found that there might have been a +20mV bias on the readings at the top end of the scale.

To summarize:  As a consequence of being like an analog switch, the LSF0108 allows the Curie's analog input pins to accept analog inputs, and apparently it works ok.

Regarding the second question, whether 3.3 V levels are ok at the I/O ports, I think they are.  See the article mentioned above for more comments.  Here is one that may be relevant:

  Digital Input Logic Transitions:
  I applied a DC voltage to pin D7 and varied it up and down while the Arduino 101 reported the logic state in the serial monitor. This was done in order to discover the logic transition levels. Going from high to low, it returned a low state after crossing 1.26V. Going from low to high, however, the transition occurred at 1.55V.

Edit 1:  Regarding two questions in a comment...

  What is the function of the level translators.. do they actually map the 0 to 5V levels to 0 to 3.3V on the curie side. ?

See the LSF0108 datasheet.  The LSF0108 has eight A, B pairs: (A1,B1);  (A2,B2); ... (A8,B8).  If you drive Ai low, Bi goes low too; and vice versa, if you drive Bi low, Ai goes low too.  That translates low to low. If neither side is driven low, connected inputs can pull up to an individual-pullup level but not higher than a reference level (VREFA or VREFB).  This translates high to high.

  If I give a 0 to 5V analog voltage at the headers will the 3.3V to 5V level part of the signal be lost, I mean does the board only take care of the 0 to 3.3V part of the signal and the adc will give max counts at 3.3V?

It should be 'lost', because as noted in the Curie datasheet's Table 2-5. ADC - DC I/O specifications, the AIN Full-scale input range is ≤ ADC_3P3_VCC and ≤ AON_IO_VCC.  (The latter voltage is 1.8 or 3.3 V.)  I'm not clear on why the LSF0108 doesn't interfere with ADC measurements.  Maybe the switches operate in a linear mode when pullups are turned off?


So my question: is 20 ms enough to read like 50 pages of 512 bytes from an SD card which are located on different (but known) file offsets within a 2+ MB file?

Let us do the numbers: 50 * 512 = 25 Kbyte in 20 ms is 1.25 Mbyte/s. As the max speed for SPI is 1 Mbyte/s (on Arduino AVR, 16 MHz) we do not have to go any further. The answer is: No.

Cheers!


Motor running slowly when connected to digital pins, but fine with 5V pins

No Load Current: 190mA (250mA MAX)

You're not getting that out of a ATmega328P GPIO. Use a driver instead.


You don't need to revert to sending single bytes. Line oriented
protocols work well with both Arduino and Node.js. The only difficulty
is that you have to decide what line terminators you want to use, and
then consistently use them.

I tend to use CR for the PC → Arduino stream and CRLF for Arduino
→ PC. Using different line terminators is kind of odd, but this
convention plays well with terminal emulators: the emulator usually
sends CR when you hit <Enter>, and expects CRLF in return. Also,
Arduino's Print::println() sends CRLF.

Here is a simple test demonstrating this convention. Node.js side:

var SerialPort = require('serialport'),
    port = new SerialPort('/dev/ttyACM0', {
        baudRate: 9600,
        parser: SerialPort.parsers.readline('\r\n')
    });

port.on('open', () => setInterval(() => port.write('Test\r'), 1000));
port.on('data', console.log);

Notice the different line terminators in readline() and write().

The Arduino side:

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

void loop() {
    static char buffer[128];
    static size_t pos;

    if (Serial.available()) {
        char c = Serial.read();
        if (c == '\r') {                       // line terminator
            buffer[pos] = '\0';                // terminate the string
            Serial.print(F("Arduino received: "));
            Serial.println(buffer);            // echo received message
            pos = 0;                           // reset buffer position
        } else if (pos < sizeof buffer - 1) {  // regular character
            buffer[pos++] = c;                 // buffer it
        }
    }
}

Here you may notice that Arduino has no equivalent of
parsers.readline(), so I had to implement it (comparing the incoming
character to '\r'). Note that explicit buffering of the incoming
message is a standard way of handling line-oriented protocols on
Arduino. Stream::readString() does not work well for this purpose, as
it waits for incoming bytes until it times out.
Stream::readStringUntil() may work better, but I prefer to avoid it
just because it returns a String, which relies on heap allocation.


Currently you are just setting the LEDs manually one after another in your code. That is not actually a binary counter (as it is most likely wanted by the exercise), but only looks like one.
First you need to understand, what a counter really is: Basically it is just a variable, that holds a number. Where exactly this variable is saved, is not important. For your case you would use a variable in your code. The Counter/Timer hardware in the Arduino uses a fixed SFR (Special Function Register) for it.
That the counter is 4bit, means, that its value is hold by only 4 bits. That gives you a value range from 0 to 15 (2^4 values). So a 4bit counter variable would count from 0 to 15. You could just have a counter variable, that you could increment or decrement (depending on the direction, that you want to count).
// Declare counter variable and initialize with zero
int counter_variable = 0;
// Increment
counter_variable++;
// or Decrement
counter_variable--;

For the "binary" part: Here it is important to understand, that the decimal number from 0 to 15 is already saved in the variable as binary (since microcontrollers/computers only know binary, nothing else). So you can write out the state of the 4 least significant bytes of the counter variable:
digitalWrite(pin8  ,counter_variable & 0b0001);
digitalWrite(pin9  ,counter_variable & 0b0010);
digitalWrite(pin10 ,counter_variable & 0b0100);
digitalWrite(pin11 ,counter_variable & 0b1000);

The & is a bitwise AND. The result of the operation will only leave bits set, when they are set on both sides. So here we are isolating the corresponding bits. digitalWrite() will interpret anything but zero as HIGH. Thus the pin is set HIGH, if the corresponding bit is set in counter_variable. But you see, that we are repeating us here. We could use a for loop and define our pins in an array:
// at global scope
int led_pins[4] = {8, 9, 10, 11};

// in the button if statement
for(int i=0; i<4; i++){
    digitalWrite(led_pins[i], counter_variable & (1 << i));
}

We have organized the pins of the LEDs in an array, so they can be easily indexed. Then we are looping through the pins array and setting the pins similar to the last version. But now we are using (1 << i). The << operator shifts the bits of the number before it by the number of digits, that comes after it. Decimal 1 is binary 0b0001. So, when i is 2 (for example), this would shift the bits 2 digits to the left, giving you 0b0100. We are just generating the same bit patterns as in the last version.
But we can even optimize further via direct port manipulation. Inside the microcontroller the output pins are controlled via simple Special Function Registers. They work somewhat like a variable. All output pins are organized into socalled "Ports" (groups of up to 8 pins). Each port has one PORTx registers (where x stands for the character associated with that port), which sets the state of the pins, if they are in output mode. Setting the corresponding bit in the correct PORTx register will set the pin to HIGH. Clearing the bit (setting to zero) will set the pin to LOW.
You are using the Arduino pins 8 to 11. If you look at a pinout diagram of the Arduino Uno, you will see, that these pins are also marked as PB0 to PB3, which stands for "Port B, pins 0 to 3 (inside that port)". The corresponding PORTx register is PORTB. So we can set all pins of the port at once by assigning a new value to that register. The following code would set an alternating on/off pattern for all 8 pins of PORTB:
PORTB = 0b10101010;

Now we only want to use the lowest 4 bits and set them to the values, that our counter variable has. So we are masking away the 4 higher bits with the bitwise AND operator and then assign that value to the register:
PORTB = counter_variable & 0b00001111;

So now the if statement in void loop() might look like this (using a for loop):
if(buttonState == HIGH){
    // count up counter variable
    for(int counter_variable=0; counter_variable < 16; counter_variable++){
        // write out to the pins
        PORTB = counter_variable & 0b00001111;
        // delay a bit to show the value
        delay(timer);
    }
}

And now we want that each consecutive button to count in the other direction than before. So we can declare another variable as direction and then use another if statement, to switch between two for loops:
// On global scope
int direction = 1;

// in void loop()

if(buttonState == HIGH){
    if(direction == 1){
        // count up counter variable
        for(int counter_variable=0; counter_variable < 16; counter_variable++){
            // write out to the pins
            PORTB = counter_variable & 0b00001111;
            // delay a bit to show the value
            delay(timer);
        }
        // change direction
        direction = -1;
    } else {
        // count up counter variable
        for(int counter_variable=15; counter_variable >= 0; counter_variable--){
            // write out to the pins
            PORTB = counter_variable & 0b00001111;
            // delay a bit to show the value
            delay(timer);
        }
        // change direction
        direction = 1;
    }
}

Note:

This is probably not the most efficient way, but I think it is quite understandable (which is also important).
This still uses much delay() calls, just as your code. That will make your button unresponsive. The counter must first finish, before the button will react again. That might be ok for you. If not, you need to restructure the program for using a non-blocking coding style like in the BlinkWithoutDelay example from the Arduino IDE (using millis()). There are lots of tutorials about that on the web.
When using a non-blocking coding style, you also need to check the button for the transition to HIGH, instead for the state high. Otherwise the code would run only, while the button is pressed.
Buttons bounce, when being pressed. So there are many transitions between HIGH and LOW for a few ms, when the button is pressed. In the code above this is not important, because the started counter needs so long, that every bounce is finished after the counter finished. With code, that needs less than a few ms, you might get into problems there. I would suggest the Bounce2 library for that. It handles the bounce detection for you.


detecting presence inside - PIR or ultrasound?

PIR sensors work fine and are probably easier to program for than ultrasonic sensors. For example, this tutorial on a PIR sensor sold by Adafruit has a datasheet at the bottom that says:

Operating Conditions Operating Temperature -20 ˚C to +70 ˚C
Storage Temperature -30 ˚C to +80 ˚C
Operating Voltage 3 to 10 V at Rs = 47 kΩ

You can try to find and check the datasheet for the sensor you intend to purchase to determine if it will work.


which is the number of bits in a float variable

No, it is not integer, so you cannot calculate it that way. It have floating point (not in fixed place).

It is stored as

1.significand x 2 ^ exponent.

It takes one bit for sign (+/-), 23 for significand (0 is not stored it is implicit) and 8 more for exponent.

Because of this, you have fixed precision (number of significant digits) for very large numbers and also for numbers which are close to zero.

You have it all explained here:
https://en.wikipedia.org/wiki/Single-precision_floating-point_format


This answer assumes Arduino Uno. For other types, refer to the documentation.

Ardino pins are not positive per se: you can change the voltage with digitalWrite() to either 0V (LOW, equal to the GND pin) or 5V (HIGH, equal to VCC).

The difference between a common cathode or common anode will be the flow of the current. With a common cathode (negative), the pins will need to provide current ("source" current), with a common anode, the pins will need to receive current ("sink" current).

There is a description for the limits of sourcing and sinking:

  Pin SOURCE Current Limitations:

  20 mA at VCC = 5 V

  Pin SINK Current Limitations:

  20 mA at VCC = 5 V

Please also read about the maximum total of 150 mA sourcing and 100 mA sinking.

You'll need to compare those current limits with the current requirements of your 7 segment display. My guess is that your a 7 segment display has 1 VCC pin and 7 output pins that you connect to the Arduino. The limiting factor is the total maximum here. The Arduino can handle 100 mA/7 = 14mA in the worst case. If that's enough for your 7 segment, it should work.

For example, this one works with 10 mA, so it would be compatible with Arduino. Make sure you have resistors in place.


Typedef not accepted as a data type in a function?

I do not get this error in Arduino IDE 1.8.5 with snippet you provided, but I get it in Sloeber Eclipse plugin. The later attached sketch fails to compile in Arduino IDE 1.8.5 too.

The error is in Arduino build chain ino to cpp conversion for the C++ compilation. Put the typedef declaration into .h file and include it in ino.


How can I measure maximum range of my ohm meter?


How to load page from SD card and still show live data from sensors?

Based upon this W3C example you can have w3-include-HTML.js file with the following contents:

function w3IncludeHTML() {
  var z, i, a, file, xhttp;
  z = document.getElementsByTagName("*");
  for (i = 0; i < z.length; i++) {
    if (z[i].getAttribute("w3-include-html")) {
      a = z[i].cloneNode(false);
      file = z[i].getAttribute("w3-include-html");
      xhttp = new XMLHttpRequest();
      xhttp.onreadystatechange = function() {
        if (this.readyState == 4 && this.status == 200) {
          a.removeAttribute("w3-include-html");
          a.innerHTML = this.responseText;
          z[i].parentNode.replaceChild(a, z[i]);
          w3IncludeHTML();
        }
      }
      xhttp.open("GET", file, true);
      xhttp.send();
      return;
    }
  }

Now you can put this in your .html file:

and then you can use something as:

server.on("/generated_data.html", live_data);

If you want to be able to use server.on() you must include <ESP8266WebServer.h> but you can serve the content the way you like. You can examine the ESP8266WebServer::on() method source code and adapt it according to your needs or you can just use that method as is.

Everything until now will result with calling the live_data() function and inserting it's response into the div which has the attribute w3-include-html="generated_data.html".

Now you only need to generate the live data inside the live_data() and to send the response:

void live_data() {
  String data_from_sensor;

  // read here the data from some sensor and store it in data_from_sensor
  String response = "
Live data

The data is: " + data_from_sensor + "some unit
";
  server.send(200, "text/html", response);
}

And that's it. The live data generated inside live_data() will show where was the empty div with w3-include-html attribute.

Of course, you can have more divs with different w3-include-html attributes and belonging server.on() statements.

There are many ways, this is just an example so you can get an idea from where to start. This code will not update the live data on and on but now that you know the mechanism, you can modify the code to do whatever you like.


Arduino with HC-05 Bluetooth Module | No data will be transmitted

The TX signal coming from either the Arduino or HC-05 should be
connected to the RX of the other as I understand it, because both are
labeled from the perspective of their respective chips

Like @timemage already said, I connected TX with TX and RX with RX but this is wrong. The solution was to plug TX (Arduino) with RX (HC-05) and RX (Arduino) with TX (HC-05).
Thank you for your help. :)


verification error, first mismatch at byte 0x3895 0xdf != 0x44?

If your sketch contains !!! in it, that can cause some versions of the bootloader to drop into interactive mode, eg.

Serial.println ("Rocket firing!!!");

Also there can be problems with 0xFF bytes in your code causing the bootloader to incorrectly assume that that page of memory was erased, when it was not.

I have a bootloader-uploader sketch at: Atmega bootloader programmer

You need a second board to use it (eg. a Uno) - the bootloader for the Mega2560 is a reasonably up-to-date one. I haven't actually tested it with the Sainsmart version of the Mega, but I presume that internally that part is the same.


Possibly not "genuine" Arduinos, but eBay has many sellers in China and Hong Kong who sell boards that are just like Arduinos, if you're willing to wait several weeks for delivery.

I was able, just now, to find an Arduino UNO compatible board for US$3.59, plus less than $2 shipping to the US. Note that they do not come with tech support, and none of the profit goes to support the official Arduino developers.


Getting gibberish serial port until button is pressed, plus the button is turning the leds off instead of on

When pin 2 is connected to ground as you have done it puts the chip into an invalid boot mode. It will be spewing out messages at 74880 baud complaining about the boot mode being invalid.

You must not connect pin 2 to ground. It must, at boot time, be connected to 3.3V through a resistor (which is should be provided by the board for you if you use a development board not a bare module).

By connecting the button between 3.3V and GND you are causing a short circuit that removes the power from the module and risks damaging the power supply on your board.

The proper way of wiring a button is to use:

pinMode(2, INPUT_PULLUP);

and then connect the GPIO pin to ground through the button.

The INPUT_PULLUP acts like the required pullup resistor keeping the input HIGH while "idle", and the button connects the input to GND when you want to "activate" it, making it LOW.

Those are the only connections you should make.  If you want to use an external resistor instead of the internal one with INPUT_PULLUP, then that goes between the input pin and 3.3V.

Never ever cause 3.3V to be directly connected to GND.


Calling a localhost php script from arduino

You can program the ESP-01 module using the arduino IDE. There are instructions in the README here: https://github.com/esp8266/Arduino
You can program the ESP-01 to connect to WiFi and communicate with your arduino sketch using the serial port. Don't forget the ESP-01 runs at 3.3V while the arduino runs at 5V. You'll need to shift the voltages somehow, otherwise you'll burn the arduino uno.
Here's an example of code you can run on the ESP-01 to connect to WiFi and start a TCP connection: https://github.com/esp8266/Arduino/blob/master/libraries/ESP8266WiFi/examples/WiFiClient/WiFiClient.ino
All that's missing is making an HTTP request instead of a "raw" TCP connection. You can probably find that in the examples. Then, add code for serial communication back to your arduino uno.
Good luck!


How to emulate an RFID tag with the RC522

No. Looking at the datasheet, card emulation is not a feature provided by the RC522.

Another popular chip, the PN532, does seem to indicate support for that feature, however, looking at the most popular library for this chip from Adafruit, it does not implement this feature. Another library from Seeed, does seem to implement it, but it looks rather limited as to which cards can be emulated, and the library itself hasn't been updated in a while.


It's no different to working with Make and any other form of GCC.  Just set your CC variable and CFLAGS variable accordingly and work as per normal.

For instance, I just knocked this one up:

CC=avr-gcc
OBJCOPY=avr-objcopy

CFLAGS=-Os -DF_CPU=16000000UL -mmcu=atmega328p
PORT=/dev/ttyACM0

led.hex: led.elf
    ${OBJCOPY} -O ihex -R .eeprom led.elf led.hex

led.elf: led.o
    ${CC} -o led.elf led.o

install: led.hex
    avrdude -F -V -c arduino -p ATMEGA328P -P ${PORT} -b 115200 -U flash:w:led.hex

That's saying that any automatic C compilation will be done with avr-gcc and the flags specified in CFLAGS.  It will by default make the hex file using OBJCOPY, which is set to the avr one, which relies on the file led.elf - so to get that file it runs the led.elf target, which links the object file led.o with the default libraries using whatever was set in CC. To do that it needs led.o, and it makes that automatically using the program specified in CC and the flags in CFLAGS.  You can then optionally to make install which will run avrdude to install the hex file into the chip.

You can make it even more generic so you can copy it in to other projects and make the minimum changes necessary:

BIN=led
OBJS=led.o test.o

CC=avr-gcc
OBJCOPY=avr-objcopy
CFLAGS=-Os -DF_CPU=16000000UL -mmcu=atmega328p
PORT=/dev/ttyACM0

${BIN}.hex: ${BIN}.elf
    ${OBJCOPY} -O ihex -R .eeprom $< $@

${BIN}.elf: ${OBJS}
    ${CC} -o $@ $^

install: ${BIN}.hex
    avrdude -F -V -c arduino -p ATMEGA328P -P ${PORT} -b 115200 -U flash:w:$<

clean:
    rm -f ${BIN}.elf ${BIN}.hex ${OBJS}

That uses "automatic variables" and simple name replacement.  BIN contains the "base" of your binary files, OBJS contains the list of object files.  $@ is the name of the current target, $< is the name of the first prerequisite, and $^ is the list of all the prerequisites.  Just change BIN and OBJS to suit.  As a bonus I have thrown in make clean to remove the compiled files and just leave you with the source.


You don't have a UUID.

You only get a UUID in the USB-enabled chips, like the ATMega32U4.

You would have to create your own UUID and store it in EEPROM, or embed it within your sketch.


Can I use a ThunderBorg is a dual motor controller on an Arduino UNO R3

Hello,
You have many possibility for drive one or more motor.

Transistor(1 motor)
L293D(2 motor backward and forward or 4 motor just forward)
L298D (like L293D but he support more Amp and Vol
L293D Adafruit shield(4 motor)
...

Here is an example for L293D:
enable PWM(0-255), inputs digital(0-1).
Motor1 : Input1, Input2, Enable1,2
Motor2 : Input3, Input4, Enable3,4

void motor1RotationDirection(int input1arg, int input2arg){
    digitaleWrite(input1, input1arg);//  LOW  |  HIGH
    digitaleWrite(input2, input2arg);//  HIGH |  LOW
                                     //Forward|Backward
}

void motor1speedRotation(int speed){
    analogWrite(enableMotor1, speed);
}    //for motor2 is the same.


PushButton as LED Switch (does not work)

Based on your response to my comment, it sounds like you have a floating input.  When the button is NOT pressed, the pin isn't connected to ground or 5V so it is floating and picking up whatever stray electrical signals happen to be bouncing around the room.

The easiest way to handle buttons on an Arduino is to wire them between the pin and ground.  Then in the code you use INPUT_PULLUP instead of INPUT for the pinMode call.  Once you've done that then the pin will reliably read HIGH when the button is NOT pushed and will read LOW when the button IS pushed.  Note that this is backwards of how newbies tend to think, but is really the more common way to handle a button.


The colors of the LEDs in your sketch are set in this loop:

for(int i = 0; i < NUM_LEDS; i++ )
{
    leds[i].setRGB(0,255,250);  // Set Color HERE!!!
    leds[i].fadeLightBy(brightness);
}

You loop over all LEDs and set them to a specific color and brightness. The changes will be send to the LEDs, when you call FastLED.show() afterwards. There is nobody, that prevents you from setting a different color for each LED or to only chnage the value for some of the LEDs.

For example, to light the first 5 LEDs in red, the next 10 in green and leaving the rest as they were before, you can use this code (Just exchange it with your for loop):

for(int i=0;i<5;i++){
    leds[i].setRGB(255,0,0);
    leds[i].fadeLightBy(brightness);
}
for(int i=5;i<15;i++){
    leds[i].setRGB(0,255,0);
    leds[i].fadeLightBy(brightness);
}
FastLED.show();

The principle is, that you have an array with color values. Each value consists of 3 smaller values for red, green and blue (RGB)(The color results from the distribution between red, green and blue; the brightness results from the overall level of red, green and blue). And each value of the array is bound to an LED (First value to first LED, second value to second LED,...). You can change the color values in the array as you like. And when you want the LEDs to show the current values in the array, you send them out by using FastLED.show(). This means you have to call this function everytime, that you want LEDs to change. You don't have to change every value in the array for this to work.

If you would like to build an asynchronous change of colors, you can ditch the delay(80) and use non-blocking code like in the BlinkWithoutDelay example of the Arduino IDE. There you use the millis() function as a clock (it returns the milliseconds since the Arduinos startup). You take a timestamp at the beginning and compare the difference between it and the current time:

unsigned long timestamp=0;
unsigned long interval=80; //interval of 80 milliseconds

void loop(){
    unsigned long current_time=millis();
    if(current_time - timestamp > interval){
        // do something here, like setting LED colors
        timestamp = current_time;
        // don't forget FastLED.show(), to output the colors
    }
}

You can use multiple of these timestamps with if-statements, one for each segment you want to change in a different frequency.


How do I program the Arduino Primo Core using the Arduino Primo?

instructions were on arduino.org. it is turned off now, but you can find them in Web Archive (without downloads)
Arduino.org pages in web archive


LED on same Pin as Toggle Switch, not illuminating

LEDs have a (fairly) fixed voltage drop across them.  The red LED is about 2V.

You can use that to work out the voltage at the input.  You basically have a voltage divider, with your 200Ω resistor as R1, and your 1kΩ resistor as R2.  The voltage drop of the diode is subtracted from Vin.

So:

Vout = (Vin - Vled) * (R2 / (R1 + R2))

     = (5 - 2) * (1000 / (200 + 1000))

     = 3 * (1000 / 1200)

     = 3 * 0.833

     = 2.5V

The ATMega328P datasheet states that a HIGH input voltage must be over 0.6*Vcc, and a LOW input voltage must be below 0.3*Vcc.  That means to register a HIGH you need more than 3V.  To register a LOW you need less than 1.5V.

You're between those two voltages - in the "dead zone".

The simplest way to achieve what you want is to use a douple-pole switch and keep the LED completely separate from the Arduino.


Receiving and sending on the Arduino Duemilanove with an MAX3232 chip

With your final comment, the behavior is understandable.  The schematic will help

You have wired two devices to the single UART on the processor.

The TX pin (output) on the ATMEGA8 is connected to the input pins of both your MAX2323 and the FT232 chip on the Ardiuno.  That works okay because 1 output pin can easily drive 2 inputs.

The RX pin (input) on the ATMEGA8 is connected to the output pins of both your MAX and FT.  The two transceivers are both attempting to drive the single input -- this is a bad thing.  When one output pin tries to drive logic 1 and the other is driving logic 0, one of the devices will win and one will lose.  Whether any of the devices is physically damaged depends on whether one device can source enough current to damage the other.

But you haven't broken anything because of the wise series resistors, R8, you see on the schematic.  The series resistor limits the current to 5 mA even if you short the RX pin to ground.  The series resistor is what creates the unequal behavior:

The ability of the FT chip to source current and drive a logic 1 is limited. So when the FT chip tries to drive logic 1 and the MAX is output 0, a 5 V drop will be seen across R8.  The RX pin is on the MAX side, so the Arduino sees 0.
The MAX chip is not limited.  When it drives 1 and the FT is at 0 there is still 5 V across the resistor.  But the RX pin is on the MAX side and sees the 1's (data).

If you want the Arduino to receive from two devices you need to "add" the data correctly with a circuit.  There are several ways, here are two:

Use an OR gate to combine the data.  The serial bus is idle at zero.  When data comes across it is a sequence of 1 bits.  Remove R8 and connect the M8RXD side to the OR input.  Connect the MAX to the other OR input.  Connect the OR output to the RX input.
Cheap and small is "wire or'd".  Remove R8 and replace with small diode, pointing at RX.  Connect small pull down resistor (10k) from RX to ground.  Connect external MAX with diode pointing at RX.  In this arrangement, either chip will source current towards the RX ping to drive a logic 1, but neither chip can sink current to drive the logic 0.  Only the pull down resistor creates the 0.


Arduino's power connector jack's tip is positive while the sleeve is negative but the more important thing to know is what will you be using in powering Arduino? Please provide more information about your setup and possibly a schematic. This will help us understand more what you're trying to accomplish.


Why does analog sensor "hum" when plugged into common ground?

@Milliways remarked:

You have a ground loop. Without seeing the actual physical layout it is impossible to determine the cause. This is a common problem in audio circuits. Fixing this is as much an art as a science. The usual solutions involve a single earthing point, earthing at one end only or in extreme cases common mode rejection techniques.
Yours is an idealised diagram. These kind of problems are often related to the physical layout e.g. parallel wire runs. I agree that there appears to be nothing amiss. As I stated this is a black art. I would suggest separating the low level analog circuit from the rest of the wiring - i.e. DO NOT share any earth cabling with any other circuit. This appears to be what you have done when it worked. You should also minimise any other source of interference by using twisted wires to the sensor.


How to capture the compilaton output to a text file in Windows?

The post Capturing avrdude command in IDE gave me the clue. Under Windows the file
C:\Program Files (x86)\Arduino\arduino_debug.exe
can have its output redirected to files same as a shell command.
In the CMD.exe DOS box, I executed:
C:\Program Files (x86)\Arduino>arduino_debug.exe >\temp\logfile.txt 2>\temp\errfile.txt
and the regular log stuff went to logfile and the errors and warnings went to errfile.
There's enough material in those two files to hurt yourself.


Choosing a proper power source for for basic RC car with 4 motors

2S LiPo with 5V UBEC is what you want.  Hit your favourite RC model seller for those.  I use HobbyKing (as the links show).

The capacity choice of the LiPo depends on

How much power your motors etc need, and
How long you want it to run for

You could also go for 3S or 4S to get more power if your chosen UBEC supports the voltage.


Why the global variables info is not shown for Arduino Due in IDE?

There is a difference in how the build system calculates the memory size for AVR and SAM. The platform.txt file contains the rule for calculating the size. There is a difference how this is done for SAM (Arduino Due).

The AVR size rules (https://github.com/arduino/ArduinoCore-avr/blob/master/platform.txt#L79) are:

## Compute size
recipe.size.pattern="{compiler.path}{compiler.size.cmd}" -A "{build.path}/{build.project_name}.elf"
recipe.size.regex=^(?:\.text|\.data|\.bootloader)\s+([0-9]+).*
recipe.size.regex.data=^(?:\.data|\.bss|\.noinit)\s+([0-9]+).*
recipe.size.regex.eeprom=^(?:\.eeprom)\s+([0-9]+).*

And the rules for SAM (https://github.com/arduino/ArduinoCore-sam/blob/master/platform.txt#L91) are:

recipe.size.pattern="{compiler.path}{compiler.size.cmd}" -A "{build.path}/{build.project_name}.elf"
recipe.size.regex=\.text\s+([0-9]+).*

They may be updated to give more information about the memory size. A good reference on the subject is http://www.support.code-red-tech.com/CodeRedWiki/FlashRamSize which shows that the output from size command for SAM contains much more information.

I assume that from the above information you see how this could be updated.

Cheers!


Is Sparkfun's MicroView OLED Arduino module a shield?

No, MicroView is not an Arduino shield, so you can't plug that into any Arduino. Arduino Uno and MicroView are developed based on Atmega328 controller. So it is 100% code compatible with Arduino Uno, means the code that runs on an Arduino Uno will also be able to run on the MicroView.


How to power an Arduino using automated mains/rechargeable battery switching?

Yes, charging a battery and supplying an Arduino at the same time is possible as long as we manage the caveats (see below) of in-circuit charging.

This is what I use:

a 3.3V Arduino (a Pro Mini in my case),
a regular Li-Ion battery,
a charging controller that supports constant voltage (CV) and constant current (CC) charging,
optionally, a 6V solar panel.

This is how it works:

charger is fed via solar panel and/or USB supply,
battery is continuously supervised and charged on demand
Arduino is connected to the output side of the charger

This works because the load that the Arduino presents is relatively small compared to what the charger can feed (and what the battery can take).
During recharging the charge current will predominantly flow through the battery.
And since the current through the battery drops once it gets full, the charger can still recognise this drop and finish the charge cycle – even though the Arduino is connected all the time.

Example setup:

I took some quick snapshots, please excuse the image quality. Charger is in the center, Arduino to the upper left, battery in a holder to the lower left, solar panel to the upper right.

The Arduino has a voltage regulator, but I don't use it in this setup. An explanation why and when to use the regulator is beyond the scope of this question and a matter for another answer.

In the first photo the charger input is only connected to the solar panel, but the panel voltage is low. So the charger is actually off and the Arduino is running off the battery.

In the second photo the charger is now connected to a USB power supply. The charger is on and in CC/CV charge mode (as indicated by the red LED of this charger model).

In the third photo the charge cycle is completed, the battery is full (as indicated by the blue LED of this charger model). Note that the charger could determine the charge completion even though the Arduino is connected and running (no power saving tricks involved here).

Background info:

The charger switches between CC and CV mode, depending on the level of discharge the battery is in. Particularly, my charger uses CC mode in case the voltage on the battery side is below 4V and CV mode in case the voltage on the battery side is above 4V. The current limit can be configured and the voltage limit is hard coded to around 4.2V, which makes the circuit save for a device like Arduino.

Image source: Nanjing Top Power

Other chargers may have other thresholds, but that doesn't matter as long as it fits your battery type and uses constant current/voltage only.
I have no particular recommendation for a charger, but so far have a good impression of the one I used in this answer.

Caveats:

There are a couple of cases to consider, though:

Deep discharge

Should the battery voltage ever go below around 2.9V (e.g. deeply discharged battery), the charger will switch into trickle charge mode where only very small amounts of current are passed to the battery – too little current (i.e. too low a voltage) for the Arduino to run. Arduino will go into brown-out and try to restart until the battery has recovered. So this can become a state in which your Arduino won't respond for an unknown amount of time.

High load

If the load connected to the battery draws a current that isn't small anymore – compared to the battery charge current – then the charger cannot recognise a full battery anymore, since the current as seen by the charger will never fall off at the end of any charge cycle. So watch out how many gadgets you connect to this kind of in-circuit charger.

Wrong charger type

There are a multitude of ways to charge a battery. Things like trickle charge, pulse charge, timer based charging, and so on.
None of these would likely work, as the voltage those charger types generate could upset the Arduino and the load the Arduino presents could upset the charger.

Please also note that some chargers don't supervise the battery. With Li-Ion or Li-Poly (and other) batteries this would be a very bad idea. Always choose a charger appropriate for your battery.

Alternatives

The charger I use employs a linear regulator. That's not very efficient, other topologies are possible. But they might require supply filtering for the Arduino.

Shameless plug

I wrote a library for the purpose of supervising an Arduino's supply voltage (and chip temperature). This technique allows to check the battery level without any additional components. That library is called CoreSensors.

Further links:

New TP4056 Lithium Cell Charger Module with Battery Protection
Solar Pannel and LiOn or Lipo
How to autoregulate a TP4056 for maximum solar power extraction


I think want you to look at this function SetWindowsHookEx on Windows.  It lets you grab any mouse of keyboard input and don something,  The input still follows the normal route, you just get notified about it.

I used this function to hook the 4th and 5th buttons on my mouse to start and stop media player, so when people pestered me at work I could pause my tunes.

MSDN - SetWindowsHookEx function

StackOverflow - Example that might work


Arduino measuring high-voltage electric fence

You are talking about measuring 2kV to 10kV pulses, with about 1J to 5J of energy per pulse.
The maximum current may be very low, but the voltages you want to measure are very high, and will very probably damage your Arduino without proper measures.
You will at least need a voltage divider to reduce the voltage the Arduino sees to 5V (or 3.3V for some Arduinos) to be able to make a measurement with the Arduino's ADC.
The voltages are high enough to bridge a fair distance with a spark; they could well bridge a physically small resistor or the distance between two connections on your breadboard or PCB.
To be honest, I think you shouldn't go anywhere near such voltages with an Arduino, unless you know exactly what you are doing when preparing the signal for an Arduino's ADC pin.


Instead of using the high level digitalRead() function access the low level port registers. See this documentation.

A port register is one byte and each bit represents one of the digital inputs on the arduino.

Do something like this:

pin_status = PIND; //Input port D (pins 0-7)
button_1 = bitRead(pin_status, 2); // digital pin 2
button_2 = bitRead(pin_status, 3); // digital pin 3

The values are read simultaneously so it is possible to have a tie.


How to code multiple conditions inside if statement?

I'm not sure how quickly you soil could get dry, but I suspect what you want to do is to periodically check the dryness throughout the day. Say like every two hours:

// Check every 2 hrs (when hr is even)
if ( t.hour % 2 == 0 && moistureOneSensorValue >= 700 ) {...}

You could also bound it to only during the day time:

if ( t.hour >= 7 // after 7a
  && t.hour <= 19 // before 7p
  && t.hour % 2 == 1 // every 2 hrs (when hr is odd)
  && moistureOneSensorValue >= 700 // soil is dry
) {...}


How to read temperature from multiple DS18B20 faster?

With 12 bits precision, DS18B20 may take up to 750 ms converting a temp.

Try using async reading, so you don't have to wait for the end of the process.

First you ask for a reading, later your read it

    DallasTemperature sensors(&oneWire);
    ...
    sensors.setWaitForConversion(false);  // makes it async
    sensors.requestTemperatures();
    sensors.setWaitForConversion(true);
    ...
    // Do something else while temp is been reading by the sensor
   ...
   float temp = sensors.getTempCByIndex(0);


The main problem is you have to reset brightness to 0 when the switch is LOW. Btw, I did not test the sketch, only compiled it.

int led = 9;
int brightness = 5;
int fadeAmount = 5;

void setup() {
   Serial.begin(9600);
    pinMode(led, OUTPUT);
}
void loop() {
  int val = digitalRead(2);
  Serial.println(val);
if (val==HIGH){
  analogWrite(led, brightness);
  brightness = brightness + fadeAmount;
  if (brightness <= 0 || brightness >= 255) {
    fadeAmount = -fadeAmount; }
  delay(100);
}
else{

  digitalWrite(9, LOW);
  brightness = 0;    // Restart with brightness 0
}
}

Some other improvements result in:

#define LED_PIN      9
#define DELAY_TIME 100
int brightness = 5;
int fadeAmount = 5;

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

void loop() {
  int switchButton = digitalRead(2);
  Serial.println(switchButton);

  if (switchButton == HIGH) {
    analogWrite(LED_PIN, brightness);
    brightness += fadeAmount;
    if ((brightness <= 0) || (brightness >= 255)) {
      fadeAmount = -fadeAmount;
    }
    delay(DELAY_TIME );
  }
  else {
    digitalWrite(LED_PIN, LOW);
    brightness = 0;    // Restart with brightness 0
  }
}

Explanation

Always indent your code (so that { and } are clear, notice each new { increases the indentation by two spaces, each } decreases the indentation by two spaces.
For values that do not change use a #define. This prevents (in this case) a few bytes not be stored in valuable memory space. Especially if you would use arrays this is important.
You used 9 in digitalWrite(9, LOW); which was probably a mistake, always use defines wherever possible. I also would use #define DELAY_TIME 100 instead of the hardcoded 100 value.
I addes some spaces before/after values (like switchButton == HIGH). It doesn't matter if you do or not, but be consequent.
Use good variable names (switchButton is more clear than val.
Use brightness += fadeAmount; instead of brightness = brightness + fadeAmount;; this is the normal way of increasing (or decreasing/multiplying/whatever) the value of a variable.
Use ( and ) in non trivial if statements like if ((brightness <= 0) || (brightness >= 255)), this could save you hours of searching in case you ever make a mistake (in this case there is no functional change).

Good luck with your project.


How to slow ADC clock speed to 1MHz on Arduino Due?

You can change the prescaler (ADCSR register). Lowest scaler is 2, so it can never run at 20mHz. Also Atmel recommends a max ADC clock of 1MHz.

Arduino sets the ADC clock to 125 KHz (prescaler of 128)

So to match Arduino, you should select a prescaler of 8 ( set bits ADPS1 and ADPS0)


Need function to convert bool array to int- why doesnt this work?

Assuming little-endian bools (least significant bool first), you should use simple bit-shifting, not floating point power calculations:

for(int id=start_index;id<=stop_index;id++){
    result |= b_array[id] ? (1 << run) : 0;
    run++;
}

The ternary operation (b_array[id] ? (1 << run) : 0) means:

If b_array[id] is true,  then

Or result with 1 left-shifted run times and store in result

otherwise

Or result with 0 and store the result (no-operation).


NRF24L01 Transmission Problems between Arduino UNO and Arduino Nano

I had the same problem and when I tried the isChipConnected () function, it told me that one of the nrf24l01 was not connected to the SPI and I assumed that one was bad. I bought 2 nrf24l01 with antenas and they work well (mostly). ( Here is the link to the library reference. Also, make sure you are using the TMRh20 version of the library, This one. This is more updated and better as far as I'm aware.
Like everyone would suggest, try to solder a 10uF capacitor between GND and VCC (that module requires more power sometimes). And the last thing I tried was to use one of this socket adaptors for the 2 modules here to use the 5v output from the arduino since it can deliver more mA and thus the module can work better.
This guide help me a little bit, I'll drop it here
I don't see anything wrong in the code, but I'm a newbie like you so (It seems we are using the same adress in our codes)


Rewrite part of the example code from Adafruit FONA

I had to enter the numbers as a string. Also I found out that I had set the variables in a wrong way.

The library for the FONA Shield needs the number to call as a string. They are creating it by assigning the input from serial to a char.
The problem was that I tried to input numbers. Also, I found out that when I tried to work with variables instead of hard coded numbers I messed around in data types.

Final conclusion:
When calling the fona.callPhone function, you have to put in a string containing the numbers instead of actual numbers.


Is there any better choice other than using delay() for a 6 hours delay?

Several options here, and a couple folks have pointed out some challenges.
"Best" answer -- probably to use a real-time clock (RTC) board to assist your timing, and effectively set a target time (next motor run is at 23:14...) each time the cycle restarts.  By saving this target off (to the EEPROM or an SD card for instance), you'd protect against a potential shutdown and reset of the arduino in the middle.
Secondary answer; set your loop() to include a relatively short delay() statement, then check the elapsed time since the last motor engagement.  This would allow you to have other items processing, as someone else noted in this thread.  This I've pseudocoded below.
unsigned long lastMotorRunTime;

void loop()
{
    /*
     * do whatever
     */
    if(millis()-lastMotorRunTime > 21600000)  // 6 hours have passed
    {
         runTheMotor(); // placeholder for the motor movements you need
         lastMotorRunTime = millis();
    }
   /*
    * do other stuff
    */
   delay(100); // loop about every 1/10 second, or whatever works
}

Given you don't seem to need detailed precision -- a few seconds either way wouldn't matter -- this should work reasonably.  Note it WILL fail if the Ardiuno is reset -- then it will only (in my pseudocode) rotate the motor 6 hours after the last Arduino reset.  Probably better to assume that an arduino reset means move the motor 'now', if the point is to ensure periodic motion rather than precise timing.
For precise timing, as noted, the RTC would be required.
(Updated: Changed lastMotorRunTime to unsigned long)


(not enough point to comment, so here's a potential answer)
I had enormous troubles getting these things to work reliably.  I tried all kinds of caps over the power supply. In the end I went for a 1$ piggy back board that takes 5v input and regulates to 3.3V. It also has the right pin female header to fit the nfr nicely. Since then I've had no issues. I also did a bit of experimentation and found that the RX side was the side giving problems.


Adafruit's rectangular 9DOF device, unlike their round 9DOF, brings several more signals out to pads.  When using I²C with the rectangular 9DOF board, as I understand it signal pin SA0_G can be set low or high to modify the device address:

  The SDO/SA0 pins (SDO_XM/SA0_XM or SDO_G/SA0_G) can be used to modify the least significant bit of the device address. If the SA0 pin is connected to the voltage supply, LSb is 1 (ex. address 0011101b) else if SA0 pad is connected to ground, the LSb value is 0 (ex. address 0011110b).

Controlling that signal should let you put multiple 9DOF's on one system.  (See my answer to  question 13830 for some additional comments on setting an I²C address.) Also see tables 15 and 16 on page 33 in the spec sheet (DM00087365.pdf) regarding addresses.

If you insist on using round 9DOFs for this application, you would need to find the trace from pin 22¤ of the LSM9DS0 to Vcc on one of your 9DOF boards; working under a microscope with miniature tools, cut the trace and rewire the pin end of the trace to Ground.  This will change that board from using addresses 0x1D and 0x6B to 0x1E and 0x6C, if I correctly understand the spec sheet.

It probably would be a good idea to get one of the rectangular 9DOF's so that you could experiment with changing its addresses, before modifying one of the round ones.

¤ Looking at the top of the chip, pin 24 is just clockwise from the depressed round dot marking pin 1; pin 22 is 1.75 mm from the corner.  See Figure 21, LGA 4x4x1 mm 24-lead outline, in the spec sheet.  That figure shows the underside of the chip.