Arduino WiFi shield working intermittently, "WiFi Shield not present"

Be sure the shield is not shorting out on the metal USB socket on the Arduino board. I don't know if this is still an issue but I've seen many Arduino boards with black electric tape on the top of the USB socket to insulate it from shorting out the shield.


These are my personal notes I wrote to myself a while back. See if they work for you too. Some of the filenames and versions may be slightly more up-to-date now, but I think this should be what you need. I look forward to hearing back from you to hear if this works for you.
STM32CubeProgrammer Linux install instructions:
Help manual: UM2237, here: https://www.st.com/en/development-tools/stm32cubeprog.html --> download link at bottom; direct link.

Download & install STM32CubeProgrammer: https://www.st.com/en/development-tools/stm32cubeprog.html#get-software --> click "Get Software" download button.

Download STSW-LINK007 (ST-LINK, ST-LINK/V2, ST-LINK/V2-1 firmware upgrade) tool: https://www.st.com/en/development-tools/stsw-link007.html.

Extract the zip file, but do not install it. There is no need to install it, as this tool comes built-in to the STM32CubeProgrammer tool above too, and all we really need from this STSW-LINK007 zip file is the readme and some udev rules.

Reference the readme here: stsw-link007_2.32.22/readme.txt, or even better, the readme here: stsw-link007_2.32.22/AllPlatforms/StlinkRulesFilesForLinux/Readme.txt

Install the udev rules:
cd stsw-link007_2.32.22/AllPlatforms/StlinkRulesFilesForLinux
sudo cp *.* /etc/udev/rules.d

Referencing section 1.2.1 of UM2237 (download link above):
sudo apt-get install libusb-1.0.0-dev

Reload udev rules (source: https://unix.stackexchange.com/a/39371/114401):
sudo udevadm control --reload-rules && udevadm trigger

Unplug and plug in the STLink programmer.

Open and Run STM32CubeProgrammer GUI to verify things.

Make a symbolic link to the programmer CLI executable so we can run it as STM32_Programmer_CLI:
mkdir -p ~/bin
sudo ln -s ~/STMicroelectronics/STM32Cube/STM32CubeProgrammer/bin/STM32_Programmer_CLI \
~/bin/STM32_Programmer_CLI

If this is the first time ever creating and using your ~/bin directory, where we just placed the executable symbolic link above, log out and log back in to have Ubuntu automatically place this folder into your PATH.

Now flash your chip with the programmer. Example flash command:
(Refer to UM2237--link above--for more info on commands.)
# connect, erase all, write, and verify; Note: the `-e all` option
# to "erase all" is NOT necessary, as erasing the sectors to be
# flashed is automatic when you do the write (`-w`) command!
# The `0x8000000` part specifies the starting address in the chip to
# start programming. Leave this off to use the chip's default
# programming start address, or, adjust this address to your specific
# needs for your chip.
STM32_Programmer_CLI -c port=SWD -w my_hex_file.hex 0x8000000 -v


Sound localization using two mics, Arduino Uno on MATLAB

Let's assume a microphone distance of 0.5m (which may be just small enough for you). Sound travels with about 300m/s in normal conditions. Let's also say, that you want at least a precision in the angle measurement of 15°.

As stated in the project Mikael linked, it is important that the distance to the sound source is big enough (so that the waves can be seen as planar). Then you have the following situation:

We are interested in the difference in distance, that the waves have to travel to the two microphones. It can be calculated by delta s = d * sin(alpha). With 15° we get delta s = 0.13m. The time difference is calculated by delta t = delta s/v, where v is the speed of sound. We get delta t = 0.43ms which equates to 2.32kHz sampling frequency. Since we use two microphones that must be sampled sequentially, the sampling frequency must be doubled. In the end we have a sampling frequency of 4.64kHz. So your sampling time of 0.01s wouldn't be enough for that.

The largest time difference in this setup (with the sound source in line with the microphones) would be 1.6ms, so your sampling time would be too big even for this.

Regarding the transmission with a baudrate of say 115200 baud this shouldn't be a problem.

But the actual speed of your setup highly depends on your code, which you haven't shown. Maybe this forum post can help you going further.


"Processing" is a simplified programming language/environment based on Java. It's designed to be very easy for non-programmers to use, and is quite a popular choice for using alongside Arduino projects.

You can download it for free (and get lots of tutorials/documentation) from here:

https://processing.org

As a side note, the Arduino IDE was based on Processing, so it will probably look familiar!


Controlling Protoneer CNC shield without PC

An Arduino can talk directly to a shield, independent of a PC.

This will, however, need a way to tell your Arduino to do it's thing. Depending on what you want it to do, this may require nothing ("send this pre-defined g-code as soon as you are turned on"), a memory card of some sort, one or more pushbuttons, or even a small screen. I have seen several 3d printers with memory cards, buttons (usually up/down/select/back), and a small screen that, once set up, can print anything you can load onto a memory card.

There are other forms of communication, too - ethernet, wifi, etc., which you can use, with appropriate shields.

In the end, of course, you still have to design your object - 3d graphics are well beyond the ability of an Arduino, so there will still be some form of computer involved.


Is it OK to Serial.print(message), when the USB cable is not connected to a host PC?

It is OK to write out serial data with nothing connected.
In case (2) "Arduino + USB interface chip", the arduino has no idea if anything is connected or listening to the serial port. The code will transmit the bytes and act exactly the same whether plugged in to anything or not.
In case (1) "arduino with built in USB" it has some idea, but just drops bytes that are going to be transmitted when the USB port is not connected.
Hardware serial (case 2) has an output buffer, but that just makes the program a little faster. When the buffer is empty, a call to serial.{print, write} will place bytes in the buffer and move on. When it's full, Serial.{print,write} will wait until there is enough room to put the rest of the message in the buffer and move on. The hardware UART and interrupts it generates will keep taking bytes out of the buffer and transmitting them at a constant rate whether something is plugged in or not. In any case, the buffer is a fixed size and will never overflow.
As far as I can tell USB-Serial (case 1) only buffers incoming data. Since the calls to Serial.{print, write} do nothing when not connected, they may take less time than they would otherwise. If your code is really unsafe about timing, that could cause a problem, but I doubt it will.
Many examples that come with the Arduino IDE have the following bit of code that pauses native USB Arduino-compatibles until the USB connection is initialized:
  while (!Serial) {
    ; // wait for serial port to connect. Needed for native USB port only
  }

This code stops the Arduino from doing anything until the USB cable is connected.
Comment out or delete those 3 lines if you want the Arduino to run "stand-alone" without a USB cable connection (Arduino Cookbook p. 117) --
after you delete those lines, if you later plug in a USB cable, the USB will initialize correctly, and then you will see on your serial monitor everything printed by any later Serial.print() commands that run. (Tested on a Teensy LC).


How does Arduino WiFi Shield connect to Blynk and How can I use ESP Module to connect to blynk?

how does Arduino WiFi Shield allow Arduino Uno to connect to blynk

Blynk is just a web service. The WiFi shield connects your board to the internet and sends data to that web service. The Blynk app is just an interface to that web service.

  how can I use the ESP boards to connect to blynk using Windows10?

That makes no sense. You can connect an MCU to Blynk through something like an ESP8266 board (or program the ESP8266 board directly to communicate with Blynk). It is merely a network interface.

Windows 10 is not an MCU, and you already have an internet connection on it. If you want to communicate with Blynk from Windows 10 I suggest you look at the documents to see if there is an API you can use from your own programs, or a web interface you can view in your browser of choice.

Windows 10 and ESP8266 are two completely alien concepts.


sizeof() on custom library constructor returns wrong result

It is working perfectly correctly.

sizeof doesn't return the number of elements in an array, it returns the number of bytes the array takes up. Since each entry in your array is an instance of your DigitalOutput class, the size is the number of elements multiplied by the size of the class - in this case 10 bytes.

To get the number of elements you must divide the number of bytes by the size of one element:

int numEles = sizeof(LED_array) / sizeof(DigitalOutput);

or

int numEles = sizeof(LED_array) / sizeof(LED_array[0]);


Arduino LED backlight - should PWM be used with transistor or capacitor?

You don't need the MOSFET, you don't need the capacitor, you do need the resistor.

The pins on your Arduino can deliver up to 20mA comfortably, so in this case there is no need for the MOSFET. However, if you were to replace your backlight with a high power LED, your current setup will work just fine.

Without a capacitor, your PWM is a nice square wave. The cap will, depending on its capacity and the resistor in your circuit, turn that into a more rounded waveform, or very ripply DC. Whichever is the case, it will not benefit the (dimming of) your LED. With some bad luck it will even introduce flickering instead of preventing it!

The reason why you should still use the resistor is to prevent the LED from drawing too much current. Without it, it's simply a game between the LED and the Arduino pin to see who will burn first. Whoever wins, you'll end up with a destroyed backlight or fried Arduino. Adding a component costing a few cents can prevent that.


DVD drive stepper motors with polulu a4988 on Arduino

According to Pololu's website, the VMOT pin needs at least 8V to function. Try a 12V switching (important!) wall wart supply that can supply at least 1A instead of your USB supply. Avoid supplies that can deliver currents >3A, as they are overkill for a small stepper motor and can be dangerous if shorted. Be sure to put a large (100uF is good) capacitor across that supply to prevent voltage spikes. To prevent damaging the motor from the higher voltage, follow the information Pololu provides on setting the current limit and set it to about 350mA. If you notice the motor is too hot to touch, try 200mA.


You wouldn't be able process (acquire, store, resize, output) any sensible video signal with the Uno (or any other Atmega-based board). The amount of memory and clock speed is way too low. Peripherals and instruction set are also lacking - no DMA, FPU, DSP instructions. Arduinos barely cope with audio - any kind of video is out of question, except if you want something like a 5fps 32x32 raw feed. Uncompressed, of course.

If you want another hobby-friendly open source solution, I'd look at something with at least an ARM M4 core, with DMA of course. For communication, regular IEEE 802.11 Wifi is your best bet (high throughput) - those 433Mhz RF modules only transmit 4800bps or so.

There may be better solutions, but I've only used stm32f429 for video: they have DMA(2D), display interface (RGB, 8080 memory interface, ...), DCMI (digital camera interface). Wifi could be handled by something like WifiMCU.

You could use the STM32F429DISCOVERY board with LCD for you remote controller, another STM32F4 board with a camera (ex http://hackaday.com/2014/12/04/serial-camera-courtesy-of-the-stm32f4/) and pair them with two WifiMCUs, if You want to do it with off-the-shelf boards.


Measuring voltage

Use the following interfacing circuit for measuring voltage:

Resistors R1, R2, R3 (1% tolerance or better recommended) will map the voltage input range (-12 to +12V DC) to an output range that can be read will the Arduino ADC  (+0.5 to +4.5V DC, in order to have some slack from the top and bottom end of the ADC range). The actual theoretical input range would be -15 to 15V DC.

The optional (but recommended) Schottky diodes D1 and D2 will protect the Arduino analog IN pin that you connect to Vout from any input under/overvoltage outside the -15 to +15V DC range.

This is the resulting input to output voltage translation curve:

Measuring current

For measuring current, use a current shunt (i.e., a very low resistance resistor, in the milliohm range) and measure the voltage drop on it via a high input impedance differential amplifier, then sample the output of the amp with the Arduino ADC.

simulate this circuit – Schematic created using CircuitLab

Follow this link to an article in EE Times to learn more about the main options available for current measurements using a shunt.


Is it possible to use Arduino UNO programmer for other AVR microcontrollers?

The AVR microcontrollers that support ISP are all tinyAVRs other than the 4/5/9/10/20/40, and all megaAVRs.

The ATtiny4/5/9/10/20/40 requires TPI (Tiny Programming Interface). AVR XMEGA devices require the use of PDI (Program and Debug Interface). Neither can be programmed using ArduinoISP.


Can I make multiple void loops with Arduino Uno?

As the others have stated, no you can't have multiple loop functions. What you need to do is modify your approach so that each thing you are trying to do can be done sequentially without blocking (ie: remove the delay function usage). Expanding on some suggestions by JRobert, Here is how I would make these functions "run at the same time":

void loop() {

    lights1();
    lights2();
    motor();

}

void lights1() {

  static unsigned long lastTime = 0;
  const long interval = 3000;
  static bool state = 0;

  unsigned long now = millis();

  if ( now - lastTime > interval && state == 0) {
    state = 1;
    lastTime = now;
    digitalWrite(enablePWMPin, HIGH);
    digitalWrite(controlPinA, HIGH);
    digitalWrite(controlPinB, LOW);
  }

  if ( now - lastTime > interval && state == 1) {
    state = 0;
    lastTime = now;
    digitalWrite(controlPinA, LOW);
    digitalWrite(controlPinB, HIGH);
  }
}

void lights2() {

  static unsigned long lastTime = 0;
  const long interval = 250;
  static bool state = 0;

  unsigned long now = millis();

  if ( now - lastTime > interval && state == 0) {
    state = 1;
    lastTime = now;
    digitalWrite(red1, HIGH);
    digitalWrite(red2, HIGH);
    digitalWrite(blue1, LOW);
    digitalWrite(blue2, LOW);
  }

  if ( now - lastTime > interval && state == 1) {
    state = 0;
    lastTime = now;
    digitalWrite(red1, LOW);
    digitalWrite(red2, LOW);
    digitalWrite(blue1, HIGH);
    digitalWrite(blue2, HIGH);
  }

}

void motor() {
  int directionA = digitalRead(controlPinA);
  int directionB = digitalRead(controlPinB);
  if (directionA == HIGH && directionB == LOW) {
    digitalWrite(front1, HIGH);
    digitalWrite(front2, HIGH);
    digitalWrite(back1, LOW);
    digitalWrite(back2, LOW);
  } else if (directionA == LOW && directionB == HIGH) {
    digitalWrite(back1, HIGH);
    digitalWrite(back2, HIGH);
    digitalWrite(front1, LOW);
    digitalWrite(front2, LOW);
  } else {
    digitalWrite(front1, LOW);
    digitalWrite(front2, LOW);
    digitalWrite(back1, LOW);
    digitalWrite(back2, LOW);
  }
}

This approach will simulate running all three functions at the same time. Each function runs one at a time. But, since the delay has been removed from the light1/2 functions, they will end quickly during the 'waiting' period instead of pausing execution. This will allow the motor(s) to run and lights to blink all at the same time.


double to char* conversion. Weird results from dtostrf

If len is the text array size, you need space there for the terminating '\0'.
So the second paramater to dtostrf has to be smaller than len.


Your board will only present a serial port if the sketch that is running on it is programmed to present a serial port. The board does not have an actual serial port for communication with the PC - only what the sketch provides.

If the sketch doesn't provide one, or if the sketch isn't running (for example if it was compiled for the wrong board by accident) then you will never see a serial port.

Since the "normal" way of resetting the board to enter the bootloader (which does present its own serial port) is to open the serial port at 1200 baud, since you don't have one to open it's kind of hard to get to the bootloader. However, depending on what bootloader you have installed there are a number of options that can help you:

Briefly connecting RST to GND just before uploading may activate the bootloader for a few seconds.
Doing the above twice in rapid succession may activate the bootloader for longer (depending on the bootloader version)

Erasing the chip and reinstalling the bootloader is the only real way that is guaranteed to work, though. But that said, I have seen boards come out of China without any bootloader at all - so reinstalling the bootloader is always a good first option with cheap boards.  You can use your Arduino UNO as an ISP programmer (using the ArduinoISP sketch and treating it like you're making a breadboard Arduino).


How to detect lipo battery % charge left?

LiPo batteries do not work well for percentage of charge remaining when using voltage as a reference. Lithium chemistry batteries hold a voltage quite close to level up to the point of near-exhaustion. That is to say, you can deplete such a battery by 80%, leaving only 20% capacity and have a few tenths of a volt reduction, depending on the configuration of your battery pack.

Unfortunately, should you continue to deplete the battery, damage may result. Some will say that damage WILL result.

The only certain way to determine a battery capacity is to use a smart charger and/or a smart discharger (often combined into one) to profile a battery.

For example, I have a 2000 mAh battery. After a few conditioning runs, either in use or on the smart dis/charger, the battery shows as having 1600 mAh capacity to 80% discharge.

Using a device to monitor the discharge rate, one can determine that if one uses 1550 mAh of the capacity, one is quite close to the risky cut-off point.
To continue discharging, there is risk involved in the lifespan of the battery.

LiPo batteries will have greater than 4 volts reading immediately off the charger and will "flatten" to optimum voltage in a short time and hold very close to that level, depending on the current load, until it virtually vanishes at the cut-off point.

One can approximate a safe voltage for the cut-off point, but one risks the chance of an inaccurate volt meter. Collecting ampere-hours as a reference for cut-off is the most accurate method and also allows more capacity with less chance of damage.


Whatever components we connect to the Arduino, their grounds and 5v pin connection must be the same?

All the grounds must be connected. They don't have to be the same physical pin - the Arduino has multiple GND pins, but they are all connected internally.
The 5V doesn't matter where you get that from, as long as it's regulated and the associated ground is connected to all the others.


Advisability of Using Bit Fields in Structs

What you are facing is the classic time-memory tradeoff.  The bit fields will be smaller in memory,  but will take more time to operate on.  You can count that no matter what processor, the bit fields will be slower.

You use the word efficient, but that word has no certain meaning without a metric for what is good or bad.  When you only have 8 k of RAM, using memory is bad, time may be cheap.  If you have real time constraints, then using time is bad and memory may be cheap.  In general, you can only buy your way out of this tradeoff.  In other words, when you find both time and memory bad, spend cash and use a bigger chip.  There is no single answer for what is good or bad.  This is part of why there are so many choices for microcontrollers, people fit the chip to the application and application to the chip.

Populating the bits of a bit field will be slower than filling of complete bytes.  Take for example

x = 5;
...
asimplestruct.len = x;
// vs
abitfield.len = x;

The first simple case will just:

load value of x to a register
store it to the byte for len

The second does something like:

loads the current value of abitfield
loads a mask
clears the bits for len
loads current value of x
loads a mask
clears off unused bits of x
shifts the bits of x
or's x with the abitfield
stores the current value back to memory

If all your operations are packing data into the bit field, or unpacking out of the bitfield, you should expect slower execution.  Bit fields are a type of compression - they cost ticks.

But moving around bit fields will be faster because there are less bytes to load and store.  If you where sorting this array, the smaller byte count could be an advantage.  If you where transferring them over a serial port, the compressed size of the bitfield might be a winner.

So with respect to your question:

  Is there a good way to test this?

The only good way to test this is to write test cases for both approaches using a pattern that closely matches your application.  It really matters what mix of operations you perform to decide whether the difference is negligible or significant.

When doing this sort of optimization experiment, definitely use source control on your project.  You can create a local GIT or Mercurial repository with just a few clicks.  Keeping a chain of checkpoints allows you to tear up your code exploring the effects of different implementations.  If you take a wrong turn, the repository allows you to simply go back to the last good point and try another path.

(Side note:  This time memory tradeoff exists in the opposite direction also.  If you look through the compiler options for desktop class processors, you will find something called structure packing.  This option allow you to add blank bytes between single byte fields such that they stay aligned at word or double word boundaries.  This may seem crazy to throw away RAM on purpose, but on processors with 16 or 32 bit wide registers and buses, so called word or dword aligned memory operations can be faster than byte wise operations.)


You can use arrays to hold sets of row pin numbers or column pin numbers, which then allows use of for loops for pinMode() settings and for testing LEDs one after another, as shown in code below.

Note, using enum { ... }; for integer-constant declarations is slightly more compact than a series of const int statements.  When a constant name in an enum does not have an = and value after it, it is given a value one larger than the previous constant.  So, for example, the first enum in the following code sets x2 to 3, x3 to 4, etc.

enum { x1=2, x2, x3, x4, x5, x6};
enum { y1=8, y2, y3, y4, y5, y6};
const byte rowPins[] = { x1, x2, x3, x4, x5, x6};
const byte colPins[] = { y1, y2, y3, y4, y5, y6};
enum { nRow = sizeof rowPins / sizeof rowPins[0] };
enum { nCol = sizeof colPins / sizeof colPins[0] };

void setup() {
  for (byte i=0; i<nRow; ++i) pinMode(rowPins[i], OUTPUT);
  for (byte i=0; i<nCol; ++i) pinMode(colPins[i], OUTPUT);
  for (byte i=14; i<18; ++i)  pinMode(i, INPUT);
}

void loop() {
  byte test = digitalRead(17);
  if (test) {
    for (byte x=0; x<nRow; ++x) {
      digitalWrite(rowPins[x], HIGH);
      for (byte y=0; y<nCol; ++y) {
        digitalWrite(colPins[y], HIGH);
        delay(15);
        digitalWrite(colPins[y], LOW);
      }
      digitalWrite(rowPins[x], LOW);
    }
  }
}

Note, subroutines and functions can be used to modularize code and (typically) reduce its volume.  See code sample below.  In the code as is, the subroutine doesn't particularly reduce volume, but definitely adds modularity.  You may find it useful to look up refactoring.

enum { x1=2, x2, x3, x4, x5, x6};
enum { y1=8, y2, y3, y4, y5, y6};
const byte rowPins[] = { x1, x2, x3, x4, x5, x6};
const byte colPins[] = { y1, y2, y3, y4, y5, y6};
enum { nRow = sizeof rowPins / sizeof rowPins[0] };
enum { nCol = sizeof colPins / sizeof colPins[0] };

void setup() {
  for (byte i=0; i<nRow; ++i) pinMode(rowPins[i], OUTPUT);
  for (byte i=0; i<nCol; ++i) pinMode(colPins[i], OUTPUT);
  for (byte i=14; i<18; ++i)  pinMode(i, INPUT);
}

void lightup(byte x, byte y, unsigned int howLong) {
  digitalWrite(rowPins[x], HIGH);
  digitalWrite(colPins[y], HIGH);
  delay(howLong);
  digitalWrite(colPins[y], LOW);
  digitalWrite(rowPins[x], LOW);
}

void loop() {
  byte test = digitalRead(17);
  if (test) {
    for (byte x=0; x<nRow; ++x)
      for (byte y=0; y<nCol; ++y)
        lightup(x, y, 15);
  }
}


Powering Arduino Pro Mini with different voltage, fuse setting

Read the datasheet once more. A certain voltage is needed for a certain clock frequency. There is a graph somewhere.

Since the Atmega328p is able to run up to 5.5V for VCC, that 5.5V is for every clock frequency.

Using 2V for VCC is not enough to run it at 16MHz. According to the datasheet even 3.3V is not enough. But 3.3V and 16MHz will work (it is outside the specifications though).

The RAW pin is the voltage before the voltage regulator, right ? Depending on the voltage regulator you can apply a large range of voltage.
See the pinout.

When you remove the voltage regulator, the RAW pin is open. Sometimes I remove the voltage regulator and use 3 AA batteries and feed the 4.5V into the VCC (or 5V pin) of a 8MHz ATmega328p board.

Yes. The bootloader and sketch have to know the clock frequency. A sketch compiled for 8MHz is for a 8MHz Arduino board and a sketch compiled for 16MHz is for a 16MHz Arduino board.
2V is too low. 3.3V should work.
2V is too low. 3.3V depends on the voltage regulator.
No problem. The voltage regulator gets a reverse voltage.
No problem.
No. See the schematic.
To VCC.
Not a "must", but it is highly preferred to remove the voltage regulator, so no current is leaking towards the voltage regulator which gets a reverse voltage.
Yes. The fuses are to lower/disable the BOD, so a higher voltage is no problem.

This is the best tutorial about the power of the Atmega328p : Nick Gammon about Power

ADDED

I forgot to mention to remove the led as well.
This is a Pro Mini with a coin cell.

Lowering the clock speed will make it run at lower voltages, but that will not always reduce the used energy. Doing a calculation at a slow speed takes more time than the same calculation at high speed (and going into sleep mode after that).

ADDED 2

When a low voltage is supplied (for example 2V to a 5V 16MHz Arduino board), the voltage regulator will not work. How much current/voltage is still passed on depends on the voltage regulator. With the BOD disabled, and the microcontroller runs below its required voltage, anything weird can happen. Parts of the chip will work and parts will not. That is why the BOD was invented in the first place (to reset the chip and avoid weird things to happen). I think it is very unlikely that the microcontroller will get damaged with a (too) low voltage.


Suggestions for latest ESP8266 WiFi module

No, I'm afraid we can't, since we're not ESP8266 salesmen.

However, I would seriously recommend not using an Arduino to communicate with the ESP8266 but instead to program the ESP8266 directly so you don't have any communication worries.  If you want to add an Arduino into the mix at a later date for its enhanced IO capabilities, then feel free to do so - where you can then implement your own serial protocol at whatever baud rate you like (or other protocol even - SPI? I2C?).

All you need is:

The Arduino core for the ESP8266: https://github.com/esp8266/Arduino
Some form of USB serial adapter (eg FT232 breakout board).

The controller chip on the ESP8266 is considerably more powerful than the Arduino's chip, and the fact that many people insist on using the ESP8266 as a slave device to the lower powered Arduino always seems completely backward to me.

If you want an easier board to program that messing with breakout boards you can do a lot worse than investing in a NodeMCU board. Make sure you go for the version 1 not the version 0.9 since the version 1 has a slightly more enhanced chip on it with more IO facilities than the version 0.9.


Trying to connect a 1.3" IIC OLED display to an Arduino M0 board (not Uno)

That header part should look like this (notice the comment starts and ends):

    /*=========================================================================
    SSD1306 Displays
    -----------------------------------------------------------------------
    The driver is used in multiple displays (128x64, 128x32, etc.).
    Select the appropriate display below to create an appropriately
    sized framebuffer, etc.
    SSD1306_128_64  128x64 pixel display
    SSD1306_128_32  128x32 pixel display
    SSD1306_96_16
    -----------------------------------------------------------------------*/
#define SSD1306_128_64
//   #define SSD1306_128_32
//   #define SSD1306_96_16
/*=========================================================================*/

If it compiles but doesn't work try to replace the I2C address of Adafruits 128x64 module (0x3D) by the address often used in Chinese modules (0x3C):

display.begin(SSD1306_SWITCHCAPVCC, 0x3D);

to

display.begin(SSD1306_SWITCHCAPVCC, 0x3C);

If that doesn't work, use an I2C scanner to find the address of the connected module.


Option 1

Seems you say you can make the balls out of whatever you want, I would suggest the spheres be made of a metal and then you can either suspend them by wire spot welded or soldered onto the balls. Then what you do is you connect all the balls to inputs of an Arduino ( this is if you are doing this with one). Then connect all inputs to pull-up resistors.

Then to read if a ball is touching a neighbour you start with ball n and set it as an output and use digitalWrite(n,LOW);  and then poll all the other balls as inputs to see which one reads LOW/0V and then record that in an array, you the move onto ball n+1 and scan the rest of the balls. There is also no need to read the previous ball to n+1 as if it did not register a touch, then it won't register with the next ball.

Then at the end you reset everything and start at the beginning again. Using the data how you wish at the end.

Below code is just to show, not tested.

for(int n =0; n < total_N; n++){
      pinMode(n, OUTPUT);

  for(int i = 0; i < total_inputs; i++){
          if(!(digitalRead(n)))// ball is touching
   {

         myArray[i] = 1;// store a point in the list, replace with a way you want
    }
    else myArray[i] = 0;
}
     pinMode(n, INPUT);
}

Option 2 (probably to much to go wrong)

You could use material that will allow IR rays to pass through and make you balls with that. Then in each ball is have a IR transmitter and a IR receiver, making a transceiver basically and then have each ball echo a specific ID and let the other balls pick it up.

To solve the issue that IR travels a good distance you will need to limit the power/voltage/current to the IR transmitter(LED) so that they only work within a certain range.

Option 3

You could place reed switches or hall effect sensors in each ball, with a magnet. Place a niece of metal behind the sensor so that the magnet is drawn to it. The only issue with this is that either the magnet in each ball will not only affect its neighbour but also itself. So they will need to be spaced and also the right strength of magnet.

Option 4

A combination of option 2 and 3 would be to surround a IR receiver setup with a piece of metal disk(like a washer) and also a reed switch or hall effect sensor, and then have a ball with a magnet and a IR transmitter by a magnet, so that when the two are pulled together the transmitter and receiver match up in the same view and are able to tell them that they are connected, you would thus have each ball with a set, one to receive placed on one side and another on the opposite side to transmit.


However, despite ESP8266 running at 160MHz, 10 times faster than nano, it's taking 3.5 ms to complete the loop, compare to 2.5 ms than that of nano.

There's a number of reasons for that. Chiefly:

The ESP8266 has no I2C hardware, so has to use software "bit-banging" to emulate I2C. That is slower to execute.
The ESP8266 also has to manage the WiFi hardware which takes a portion of the processing power away from the user

The result is slower execution for I2C operations and "jitter" added to timings of loops and such.

  will the same thing (wire) happen to esp32?

No (or not as much). The ESP32 has hardware I2C so it doesn't need to use bit-banging to emulate it, so it will be faster. Also it is dual core and one core is used for "system management" including managing the WiFi and Bluetooth, while the second core is used to execute your sketch, so there is no (or little1) interruption by the WiFi slowing down your sketch.

1: Two cores accessing the same area of RAM causes some contention as only one core can access the same block of RAM at a time, so it's not perfect. You may still get slight delays, but they will be minuscule compared to the processing needed for the ESP8266's WiFi code.


How to merge two arduino sketches, one for relay's and one for Servo motor?

A couple of things stand out in your code.

Whenever you perform a digital write you assign a value to ledpin:

digitalWrite(ledpin = 3, LOW);

This is not necessary as you do not do anything with the ledpin variable. Instead, just have the digital I/O pin number:

digitalWrite(3, LOW);

Or simply have 2 variables, one for pin 2 and another for pin 3. Eg.

redledpin = 2;
greenledpin = 3;

This also applies to the pinMode function calls in the setup function.
Each one of your  if( Serial.read() == xx) statements will read a serial character off of the serial buffer. Instead store the read character in a local variable:

readChar = Serial.read()
if( readchar == 'a')
...
if( readchar == 'A')
...
if( readchar == 'b')
...
if( readchar == 'B')
...

I would encase all of the code inside loop() with:

if ( Serial.available() )
{
    ...
}

The delay function is blocking and this will cause issues. I suggest deleting the delay altogether.
Due to the fact that you are sending commands to turn digital outputs on and off as well as sending an integer for motor and another for pos, I suggest that you define a packet structure and make your code follow that (with the necessary error handling). As the code currently stands you will miss information, depending on what character it sees first on the serial buffer.

I suggest something like:

A, B, 142, 090

Starting the packet off with a know character is a good idea. So is having a timeout period - in case only a portion of your packet is received.


Arduino code not working properly (Please Help)

The problem is that, if you enter 'O', you go thorugh the set alarm case only once. If no alarm was triggered, it just falls through the if statements and is then back in the main loop. In that main loop, you only check for your sensors, if something was entered to the serial console. That means if you do not enter anything during a loop, nothing happens.
The solution to this would be to implement a finite state machine.
That means you use a state variable for the switch case. You then update your state based on the state and the external conditions. In your case you can just update the state using user input.
I changed your code a bit for a possible (but bad) implementation. I did not verify or check for errors. I recommend using a more solid implementation, if you plan to build upon this code for more complex behavior.
char state = 'A'; //initialize state in Off state
char b;          // make user input variable global
void setup()
{
  Serial.begin(115200);
  pinMode(12, OUTPUT); //RED
  pinMode(13, OUTPUT); //GREEN
  pinMode(14, OUTPUT); //YELLOW
  pinMode(16, OUTPUT); //SPEAKER
  pinMode(4, INPUT); //Echo
  pinMode(2, OUTPUT); //Trig
}

void loop()
{
  if (Serial.available() > 0)
  {
    b = Serial.read();
  }
  // close user input section

  switch (state) // run switch case every loop
  {
    //Turn Alarm off
    case 'A' :
      {
        digitalWrite(12, LOW); //red off
        digitalWrite(13, LOW); // green off
        digitalWrite(14, LOW); //yellow off
        noTone(16);

        delay(500);
      }
      break;

    // Set alarm
    case 'O' :
      {
        int light;
        light = analogRead(0);
        unsigned long distance;
        digitalWrite(2, LOW);
        delayMicroseconds(2);
        digitalWrite(2, HIGH);
        delayMicroseconds(10);
        digitalWrite(2, LOW);
        distance = pulseIn(4, HIGH);
        distance = distance / 58; //centimeters
        delay(500);

        digitalWrite(12, LOW); //red off
        digitalWrite(14, LOW); //yellow off
        digitalWrite(13, HIGH); //green on

        if (light < 400)
        {
          digitalWrite(12, HIGH); //red on
          digitalWrite(13, LOW); // green off
          digitalWrite(14, LOW); //yellow off
          tone(16, 832);
          delay(500);
        }

        if (distance < 50)
        {
          digitalWrite(12, HIGH); //red on
          digitalWrite(13, LOW); // green off
          digitalWrite(14, LOW); //yellow off
          tone(16, 832);
          delay(500);
        }

      }
      break;

    // snooze option
    case 'Z' :
      {
        digitalWrite(14, HIGH); //yellow on
        digitalWrite(12, LOW); //red off
        digitalWrite(13, LOW); // green off
        noTone(16);
        delay(300000UL);
        digitalWrite(12, HIGH); //red on
        digitalWrite(13, LOW); // green off
        digitalWrite(14, LOW); //yellow off
        tone(16, 832);
        delay(500);
      }
      break;
  }

  state = b; // update state based on input

}


Assigning float to 10 decimal place for longitude,latitude

But when after setting the Longitude and Latitude to float.When I use
  this code, I don't get a valid gps data.

Some statements in C/C++ are not what they might seem. The value of the statements:

Longitude = (sim808.GPSdata.lon, 10 );
Latitude = (sim808.GPSdata.lat, 10 );

Are actually the same as:

sim808.GPSdata.lon;
Longitude = 10;
sim808.GPSdata.lat;
Latitude = 10;

Which is then optimized to:

Longitude = 10.0;
Latitude = 10.0;

That is, when using list notation, the value of the expression is the same as the value of last expression in the list.

The other answers have covered the fact that float and double on Arduino (AVR-GCC) are only 32-bit, and that gives 6 to 9 significant decimal digits precision.

Cheers!


It looks like you're using pin 10 to indicate whether sweep your servo through 180-degrees or through 90-degrees. Is that correct? Then you only need the if/else statements to select one of the two 'map()' calls. I see several problems:

Your indentation suggests you tried to select 3 statements with your 'if', but an 'if' only refers to one following statement or block of statements. If you want it to control a block of statements, you need to surround those statements with braces: '{' and '}'.
In this case, you need everything but the 'map' calls to be outside the 'if' statements.
Statements (except 'if' and 'else' by themselves) need to end with a semi-colon.

I think you meant to write:

val=analog.read (potpin);     // read the pot

if(pin10==HIGH)               // pin 10 selects servo range
  val=map(val,0,1023,0,180);  // map the pot value ...
else                          //   into one of
  val=map(0,1023,0,90);       //   the servo ranges

servowrite(val);              // drive the servo

Update:

  I had try every thing , but there is some shaking and vibration when
  if condition is satisfied.

Was the shaking near rotation limits? Most servos, especially the inexpensive hobby ones, get unstable near each end of their travel. Some will move smoothly to the limit, others get shaky within a few degrees of the limit. Each one is a little bit different.

Update 2:

Here is a complete, working example based on the Arduino Servo-example and your specifications. There were two bugs above:

I left out the 'val' argument in one of the map commands. This cause a compile error and should have prevented you from testing it. It could not have run, properly or improperly.
In your code example, if(pin10==HIGH) doesn't read any input pin! It just reads some (unseen!) variable named 'pin10' - unless you did read the pin in some code you didn't show us? Which is why we ask for a minimum, complete, & verifiable example.

This code runs and rotates my sg90 servo through 90 degrees, if pin 10 is low, or 180 degrees, if pin 10 is high.


send configuration commands with arduino

Here you find a standard library from arduino.
https://www.arduino.cc/reference/en/libraries/sparkfun-ublox-arduino-library/
You can find the documentation here:
https://github.com/sparkfun/SparkFun_Ublox_Arduino_Library


An Arduino Uno has 512 bytes of non-volitile memory called EEPROM or Electrically Erasable Programmable Read Only Memory. Other Arduino platforms might have more. Accessing it is complex.  Fortunately there is an Arduino EEPROM library already written for you.  Your value is stored in a type int so I would use the read() and update() methods in the EEPROM library.  The read is self explanatory.  But the update, unlike the write, only runs if what is in the EEPROM location is different from what you want to write.  In this way we save the EEPROM a little bit of ware and tare.  As EEPROMs usually have a finite number of write cycles until they start failing.  Which usually is in the tens of thousands.


Getting the contacts/ storing contacts to SIM card

What have you researched so far? Following the link you have given for the shield, about the third line of the description is a reference to the AT Command Set used by the chip.
I just did a couple of quick searches through it and found:

2.2.4  ATD><n> Originate phone call to number in memory
3.2.26 AT+CPBF Find phone book entries
3.2.27 AT+CPBR Read current phone book entries
3.2.28 AT+CPBS Select phone book memory storage

probably a good place to start.


esp8266 esp-01 crashing, restarting over and over

Turns out I was pulling up on the GPIO0 pin, instead of down.  Ensure you have the correct pin-out when flashing.

ESP-01 VCC - 3.3v Serial Adapter
ESP-01 GND - Ground or Minus Serial Adapter
ESP-01 RX - Connect to TX on Serial Adapter
ESP-01 TX - Connect to RX on Serial Adapter
ESP-01 CH_PD - 3.3v Serial Adapter
ESP-01 GPIO0 - Pull low by connecting to ground / minus

There also seems to be a problem with NodeMCU not clearing variables in the Ram, so Ram fills up as you run, and this causes the module to crash upon restarting, over and over.  That is also what was happening.  There is some problem with wifi.sta.getap() that exacerbates this.


You'll most likely need a USB host shield (like this) for the Arduino to be able to communicate with the dongle, so that doesn't help. You may (this is a long shot) be able to crack open the dongle, look up some datasheets, and possibly find a serial interface inside that you could connect to Arduino... but like I said, it's a long shot.


Make action happen after time is passed using interrupts

Since I don't have enough reputations to comment on your question I am going to drop my two cents here.

Since your question is a little bit vague, I am going to suppose that you don't want any external interrupts thus, you don't need to use the attachInterrupt function. I am going to suppose that there is no need to use timers' interrupts as well.

Have a look at the following code:

#include <Time.h>
#include <TimeLib.h>
#include <Adafruit_RGBLCDShield.h>
#include <utility/Adafruit_MCP23017.h>
Adafruit_RGBLCDShield lcd = Adafruit_RGBLCDShield();

void setup() {
  lcd.begin(16, 2);
  setTime(02, 10,00, 14, 03, 2016);
}

void loop() {
  char time_out[16];
  lcd.setCursor(0, 1);
  sprintf(time_out, "%02u:%02u:%02u",hour(),minute(),second());//use %x to get hex
  lcd.print(time_out);

  int totalSeconds = (hour() * 3600) + (minute() * 60) + second();
  lcd.print(totalSeconds);
  if(totalSeconds > 7806) {
    blink();
  }
}

void blink() {
  lcd.print("time passed");
}

You should know the following:

Commands inside void loop() is going to be executed for ever again and again. Especially lcd.print(time_out);. You had better refresh the LCD every 1 second.

After 6 seconds blink() is going to be executed many times (maybe forever) since it is inside the loop and if(totalSeconds > 7806) is going to be always true.

If you have any question let me know in the comment section.


Equivalent for PORTB in Arduino Mega 2560

This code sends a pulse on pin PB0, which on the Uno is equivalent to
digital 8. On the Mega, digital 8 is PH5, thus you would write

PORTH |= _BV(PH5);
PORTH &= ~_BV(PH5);

The equivalence between the Arduino pins and the AVR pins is provided in
the official
documentation, but
there are nicer versions at pighixxx.com:

Uno pinout
Mega pinout


Controlling a capacitive touch screen that doesn't have I2C/SPI

Do I need some sort of driver board?

There are quite a few solutions around to interface with parallel devices like that. Some can be purchased off-the-shelf. I described a home-made solution on my page Connecting a graphical LCD via a I2C/SPI using a 16-bit port expander.

This isn't a touch screen, but from what I can make out of your (rather hard to read) image, it looks similar in concept.

I used a MCP23017 16-bit port expander (that is an I2C part, but you can get the MCP23S17 chips which has an SPI interface).

As you can see from the photo, there are only four wires from the Arduino to the LCD board: +5V, Gnd, SDA, SCL.

When I wrote that article it looks like the MCP23017 was $AUD 2.30. A quick Google search indicates it is still selling for around $US 2.50. On eBay they seem to be selling for around one dollar (eg. $5 for 5 chips).

Depending on the complexity of the driver (on the touch-screen board) writing suitable code may be moderately easy to slightly harder. It depends on how much you are used to coding for these port expanders, and how fiddly the interface requirements are.

Since Adafruit offer a driver shield, it can presumably be done.


Here is what you have asked for:

  I am making home coming/leaving light for car. First i want that
  whenver i press car key lock a timer will start for 10 second.And if i
  press button twice within 10 second pin 13 will high remain for 10
  second and if i cant press the button it return to the void loop aor
  condition may get false. I am working on it but dont getting the
  correct approach . But i am not able to use millis twicely in this
  program.

So, I have refactored, and done my best to interpret your words, and the code that you wrote.

You will see that I broke down quite a bit the deep nesting of your code into separate methods.  I hope that you see that it makes it more readable and understandable.

I have replaced the "magic numbers" like 10000 with more readable code like tenSeconds.  And I hope the code does what you want now, but I'm not sure.  Hopefully the readability has improved enough that you can massage and reshape the code into what you want it to do, as well as shown you what direction to head when you don't understand your own code because it has grown (deeper, longer, more complicated, etc.) as most code does.

In the professional coding world, allowing code to remain like that is called "not paying down your design debt" and you (or your organization) will pay the consequences, with interest, just like a credit card.

Finally, note that my comments don't restate the code, but tries to add something (mine often tries to finish sentences involving readable code).  My comments also tend to be on the ends of lines to try to stay out of the way.

This code compiles, but has not been tested on an actual Arduino.  Please let me know if this meets your need, and please choose this as the answer if it does answer your question, and at least please vote up the answer if it doesn't quite answer you...   ...and give me a second chance, if possible.  Thanks.

// pins defined and named
int pin_button = 8;         // button Pin
int pin_LED = 13;           // LED Pin

int currentButtonState = 0;         // current state of the button
int lastButtonState = 0;

int buttonPushCounter = 0;   // counter for the number of button presses
unsigned long currentMillis = 0;
unsigned long previousMillis = 0;
const unsigned int tenSeconds = 10000; // 10,000 milliseconds

void setup()
{
    pinMode(pin_button, INPUT_PULLUP);
    pinMode(pin_LED, OUTPUT);
}

void loop()
{
    currentMillis = GetCurrentMillis();
    if (ButtonIsToggled() == 1)
    {
        CountButtonPushes();
    }
}

int ButtonIsToggled()
{
    int isToggled = 0;
    currentButtonState = digitalRead(pin_button);
    if (currentButtonState != lastButtonState)
    {
        lastButtonState = currentButtonState;
        isToggled = 1;
    }
    return isToggled;
}

void CountButtonPushes()
{
    int valueToWrite = LOW; // LED-OFF is default value unless overridden

    if (currentButtonState == LOW) // we just toggled from HIGH to LOW...
    {
        buttonPushCounter++; // We've successfully completed another button-press
        if (buttonPushCounter % 3 == 0) // if (buttonPushCounter==3) should be faster
        {                               // because compare is faster than division
            buttonPushCounter = 0;  // Reset
            valueToWrite = HIGH; // LED-ON
        }
    }

    if (valueToWrite == HIGH) // LED is ON
    {
        digitalWrite(pin_LED, HIGH); // valueToWrite
        while (currentMillis - previousMillis < tenSeconds)
        {
            // do nothing -- wait while LED is on
            // busy wait. Consider sleeping instead.
            currentMillis = GetCurrentMillis();
        }
        previousMillis = currentMillis;
        digitalWrite(pin_LED, LOW);
    }
}

unsigned long GetCurrentMillis()
{
    return millis();
}


I think it is the de facto standard for VS (of course the default Arduino IDE is used most).

However, I think some advanced features (like breakpoint if I recall right) is only temporarily for free and you have to pay later for a subscription.

Note however, that debugging/breakpoints are not used often anyway since mostly it's more realtime controlled than PC applications.

If you need breakpoints etc. probably the easiest is to make stubs for some libraries and first develop the application not using Arduino and later use the Visual Micro plugin. [Update: it seems breakpoints are possible with vMirco, I never got them to work though].


Unable to use analog pins as digital inputs

A6 and A7 are special on the nano. They are the only pins that can't be used for digital.  They are only analog inputs.


How to disable the write protection of the USART mode register?

Under Windows, Arduino puts the source code for hardware specific stuff in User\AppData\Local\Arduino, and not in the installation folder.

/* -------- US_WPMR : (USART Offset: 0xE4) Write Protect Mode Register -------- */
#define US_WPMR_WPEN (0x1u << 0) /**< \brief (US_WPMR) Write Protect Enable */
#define US_WPMR_WPKEY_Pos 8
#define US_WPMR_WPKEY_Msk (0xffffffu << US_WPMR_WPKEY_Pos) /**< \brief (US_WPMR) Write Protect KEY */
#define US_WPMR_WPKEY(value) ((US_WPMR_WPKEY_Msk & ((value) << US_WPMR_WPKEY_Pos)))

I would guess unlocking / locking would take the format:

????->US_WPMR = (US_WPMR_WPEN | US_WPMR_WPKEY(0x555341));
????->US_WPMR = (~US_WPMR_WPEN & US_WPMR_WPKEY(0x555341));


The ST7735 uses SPI to communicate. It will always be slow compared to parallel connected screens.

The fact that you appear to be using bitbanged SPI (manually toggling IO pins) makes it even slower.

The fastest you will be able to get with that screen will be to use hardware SPI instead (which most likely limits which pins you can use - I am not familiar with the ESP32 though) but that will still be somewhat slow.

If you want really high speed screen updates then you will need a parallel interface screen, ideally a 16-bit parallel interface screen. However, for that you need around 20 IO pins to drive it.


Is it ok to share the same power rail for the arduino and a shield?

the Vin pin on the Arduino is the source to the internal voltage regulator. It needs about 7 volts in order to work. If you try to feed 5V into the Vin then the Arduino won't get a full 5V.

Motors draw a lot of current, and cause transients on the power line as they switch on and off. (They will cause transients even in a regulated supply, because it takes the regulator time to respond to the rapidly changing load of the motor.) If you're going to feed both your motor shield and the Arduino's 5V from the same power supply, you will need a reservoir capacitor between 5V and ground as close to the Arduino 5V input as possible. The reservoir capacitor will even out drops and spikes in power to the Arduino.

You'd be much better off feeding 7-9V into the Arduino's Vin. That way it's power is regulated separately.


What components do I need to build Arduino based water pump controller?

If you are controlling an AC pump, you might look into a PowerTail switch, which allows you to control AC power easily and relatively safely, but of course, if you are working with anything around water, be careful!  http://www.powerswitchtail.com/


This very much looks like the Serial-over-USB-Driver has chosen another port than COM5 on reconnecting the board. Assuming you are using the Arduino IDE, check whether COM5 still shows up in the Board -> Port menu -- or, in other words, go there and select the port that is listed there while the board is plugged in.

Usually, I'd expect this port to be COM3 on Windows, but that may change when you...

physically disconnect and reconnect the board too fast (i.e. the driver has not yet shut down the old COM port when a "new device on USB!" event comes in)
still have the Serial Monitor open when disconnecting and reconnecting (because the driver cannot remove the virtual COM port device while the Serial Monitor has it opened, in which case the driver creates another virtual COM port device on a different number)
disconnect and reconnect while the esptool process is still working (same reason as above).

It also might help to enable verbose output for compiling and uploading (see preferences dialog in Arduino IDE).


How to share a library on Arduino Playground?

The Arduino Playground library list is a wiki page (like everything on the playground). That means anyone can log in to edit it and add links to their own libraries. The "Log In" and "Sign Up" links are at the top right of the Arduino site. When you first go to edit a Playground page you'll be taken to a "Password required" page but don't worry, this is only to prevent spam and the password is pre-filled. You only need to click the "I'm not a robot" checkbox, wait for the green checkmark to appear, then click "Submit".

There are a couple of important things to note though. Firstly, the Playground library list isn't there for getting your work reviewed. It's a place to post things that are functional and ready to be used by other people. If you need someone to help with your project then you can maybe post on the Arduino forums. Alternatively, if you have specific questions, you can post here on Arduino SE.

If you're ready to post your library online, you also have to be aware that the Playground itself won't host your code. You can put a link there and maybe some documentation. However, you'll need to host your code somewhere else, such as Github.


Arduino due temperature reading shows random temperatures

Did you read about this smt160 sensor ? It relies on the calculation of duty cycle of the square wave output from the sensor, to calculate the temparature.

  temperature = (dutyCycle) -0.32)/0.0047

The square wave output has to be sampled at 8KHz or at 125us for no loss of information. This block samples that data.

  if (now - lastSample > 50) {

  sampleSize++;

  highCount1 = highCount1 + digitalRead(sensorPin1);

  highCount2 = highCount2 + digitalRead(sensorPin2);

  highCount3 = highCount3 + digitalRead(sensorPin3);

  lastSample = now;
      }

  else {
          delayMicroseconds(10);
      }

when you increased the number of code lines , information loss also increased, cz more number of instructions have to be executed now , till reaching the corresponding digital reads.


Piezo buzzer with PWM on arduino uno with atmega328p in C on registers + analogRead on registers

In fact all the mentioned function calls are using the Special Function Registers (SFR) and thus the hardware peripherals of the Arduino in the background to work. But I guess this is an exercise to learn how to configure and use these peripherals yourself. Doing this for the whole code is a rather big task for a single question on this site. So I will give you hints and will point you to the corresponding registers. Then the datasheet of the Atmega328P (the microcontroller on the Arduino Uno) is a must read for you. It contains detailed descriptions for almost every function and SFR of the microcontroller.

PWM: I think you want to use PWM for creating a tone from your buzzer. This is not the classical PWM use case (as you don't need to change the duty cycle but the frequency to get different tones). Nonetheless you reach it with the same hardware. For hardware PWM you need to configure a Timer. The Uno has 3 Timers, where Timer0 is already configured by the Arduino IDE for functions like delay(), millis() and such. So I suggest you use Timer1. It has 3 control registers called TCCR1A to TCCR1C. You want the timer to be in CTC Mode (Clear Timer on Compare Match)(Waveform Generation Mode Bits set to 4, CTC mode for OCR1A). The timer will count up with the set frequency (will describe this later) until it gets to the value, that you wrote into the OCR1A register (Compare Match). Then it will reset. If you have set the COM1Ax bits in the TCCR1A register to the correct values, you can set it up to toggle the OC1A pin on a Compare Match).

So in this mode, the timer will reset at a counter value that you set and will toggle the OC1A output pin for you. Thus it generates a square wave with variable frequency, that you can control by writing different values to the OCR1A register.

But we also need to configure the frequency with which the timer will count up. This is done by the clock selection bits CS10 to CS12 in the TCCR1B register. A value of 0 for all bits means the timer is stopped. Look at the corresponding table in the Timer1 register descriptions in the datasheet. You want to connect the timer to the internal system clock. With these bits you can set the prescaler. This determines how many clock pulses it needs to let the timer count 1 up. With no prescaler the timer will count at every clock pulse. With the bit values 0 1 1 you will get a prescaler of 64, so the timer will count up 1 every 64 clock pulses. This sets the frequency range, that you have with the counter. The internal system clock runs at 16MHz on the Uno (you can do the math with the prescaler to calculate for the wanted frequency).
analogRead aka ADC: For reading an analog voltage the ADC (Analog Digital Converter) is used. It has the SFRs ADMUX, ADCSRA, the convertion result registers ADCL and ADCH, and ADCSRB. First we want to set the reference voltage for our conversion. When we set the REFS1 and REFS0 bits in the ADMUX register to 01 we use Vcc as voltage reference, which is sufficient most of the time. The bits MUX3 to MUX0 in the same register select one of the ADC pins for AD Conversion (We have only 1 ADC in the Atmega328P, but we can connect it to multiple ADC pins one after another). Now on the ADCSRA register: The ADEN bit will enable the ADC, with ADSC we can start a conversion. With the bits ADPS2 to ADPS0 we can select a clock prescaler for the ADC. This determines how fast the ADC runs. For maximum resolution you should keep the frequency between 50 and 200kHz.

You can start a conversion by writing 1 to the ADSC. Then you can poll the ADIF bit in the same register. It will be set to 1, when the ADC has completed the conversion. Then you can read the conversion result from the ADCL and ADCH registers (for the Low byte and the High byte of the 10bit result). You should reset the ADIF bit after that by writing a 1 to it.
LCD: I don't know, if you also need to replace the LiquidCrystal library by your own code, since it does not use special peripherals (just digital pins). Digital pins are controlled via the DDRx, PORTx and PINx registers. Google "arduino port manipulation" for more information. And then you can resemble the functions from the library with it.


Background "static" on side of TFT screen?

It will be a problem with the library you are using. Not all screens that use the same CoG are wired in quite the same way. Often a CoG that supports a larger number of columns is used with a screen that doesn't have that many columns (132 in this case), and the actual screen is placed at an offset within the available columns, and it's up to the manufacturer of the screen where that offset is.

So the library has to initialize the CoG with where the screen actually is within its physical column range, and your screen is different to what the library is expecting.  Looking at the TFT library bundled with the IDE most screen configurations appear to impose a couple of pixels offset in the columns, which you don't want.

I would suggest investigating other TFT libraries, such as UTFT, which may give better control over screen parameters.


Library to set internal analog gain of the Arduino?

I would recommend you to check Nick Gammon's example on using the analog comparator by means of configuring the relevant flag bits of registers in the ATmega328. Sample code from the link, by Nick:

volatile boolean triggered;

ISR (ANALOG_COMP_vect)
  {
  triggered = true;
  }

void setup ()
  {
  Serial.begin (115200);
  Serial.println ("Started.");
  ADCSRB = 0;           // (Disable) ACME: Analog Comparator Multiplexer Enable
  ACSR =  bit (ACI)     // (Clear) Analog Comparator Interrupt Flag
        | bit (ACIE)    // Analog Comparator Interrupt Enable
        | bit (ACIS1);  // ACIS1, ACIS0: Analog Comparator Interrupt Mode Select (trigger on falling edge)
   }  // end of setup

void loop ()
  {
  if (triggered)
    {
    Serial.println ("Triggered!");
    triggered = false;
    }

  }  // end of loop


Optical Incremental Encoder Reading using Arduino UNO

You are attaching your interrupt incorrectly. You should not pass in the pin number, but the interrupt number. There is also a handy function that converts a pin to the right interrupt number:

attachInterrupt(digitalPinToInterrupt(pin), ISR, mode);

So, your code should be:

attachInterrupt(digitalPinToInterrupt(encoderPinA), isr,CHANGE);

Also, you should declare your counter variable to be volatile, since it is modified within an ISR, and thus the compiler should not assume that it doesn't change even though the loop() never changes it:

volatile int counter = 0;


Error while uploading the sketch for Arduino Mini

On Uno and other boards with USB on board, for flashing the IDE resets the Atmega to bootloader, sending signal over USB. Mini has not an build in USB and you connected it with an USB to TTL cable. Has this cable a Reset signal line? If yes, did you connect this line to Reset pin?

If not, then you need to do a manual reset in the right moment when avrdude sends the hex file. I count to 9 after the first attempt and then I push the reset button.


I formated the SD card, and then work correctly

Thanks!


How to switch on and off an HD44780 LCD Display?

Assuming that display is initialized in 8-bit mode: to send command such as "Turn display on/off",

set RS to LOW first (meaning it is command, not data)
set command bits on DB7-DB0 (in your case it could be 0x08 - DB2/DB1/DB0 all LOW to turn off following: display, cursor and blinking)
make a pulse on EN pin LOW-HIGH-LOW (take a 40uS delay before further communication)


Using an Android bluetooth terminal to change preset states on 8x8 LED matrixes

Your problem is, that you read from the EEBlue serial interface, but you are just echoing it over Serial and don't do anything with it. The display code is only executed, when the commands come through Serial.

The simplest way is to copy the code in the if(Serial.available()) statement into the if(EEBlue.available()) statement and changing the read to use EEBlue. Of course you should delete the existing EEBlue.read() from this statement.

But that way would mean to have double the code to maintain. It is cleaner to first read data from either serial interface and then process it. Something like this:

if(Serial.available()){
    cmd = Serial.read();
} else if(EEBlue.available()){
    cmd = EEBlue.read();
}

// insert the code to check the cmd variable for the expected values and act accordingly

cmd = 0; // Resetting the cmd to prevent multiple executions of one command


always detects same pin as HIGH even when its not connected

You're not showing your schematic but I'm sure that you are simply leaving the Ax pins OPEN when you are not connecting them to your +V line.  In that case they are "floating" and as such they can float HIGH or LOW or just about anywhere.  What's happening is that when you hook up +V to any of them, that has the side-effect of pulling at least A0 HIGH along with it since you have allowed it to float.
Two things to do here:

Don't allow lines to float and expect deterministic behavior.  Tie them to +V or to GROUND when you are not using them.
Pull the Ax lines to +V or GND via a resistor like 10K Ohms.  This will prevent them from floating and will give you predictable results.


Because you're using delay() within your while loop you have to ensure that you are pressing the key at the precise moment it is read.

You should not use delay().

Instead take a look at the BlinkWithoutDelay example in the IDE. And also consider implementing a Finite State Machine to know both if you're blinking and what state you're blinking currently is in.


Modular Coding - What types of code portions to convert into library files? Rationale and methods?

It's very subjective what should and shouldn't be put in a library.

I use the simple rules:

If it's an atomic piece of code like a hardware driver, it's a library.
If it's something that could be used in multiple sketches, it's a library.

Maybe things like configuration options could be put in a header file (not a library - a header file in the sketch folder).

You could maybe split portions of your sketch into C++ files or INO files within the sketch (not a library - files in the sketch folder, and using INO files is easier since you don't need header files, the IDE does it all for you) to group things logically together and make it easier to manage (all the LCD code in one file, all the temperature sensor code in another file, that kind of thing).


Arduino fried? Onboard blink ok; offboard blink not ok

Here's a guide posted by Nick Gammon for checking if your Arduino is bricked Is My Arduino Bricked ?


Are there sensors that can detect the color of an LED?

You can use an LED as a light sensor - http://www.instructables.com/id/LEDs-as-light-sensors/

In theory, LEDs should be most sensitive to the frequency it emits - if this is true, the same type of red/green/yellow LED would be best.

I don't know how sensitive this will be.

If you control the "external device", then you could get much better accuracy by blinking the LED at very high rates (not visible to the human eye). Or, if you can get at the legs of the LED, you can tap into the signal directly (you should use an opto-isolator - even if powered at a few volts, the ground of your project may be different from the ground of the external device, causing 100s of volts to run through your Arduino - not good!).


Why do NRF24L01 modules only communicate in 1 direction

In receiving code....try only defining variable.
char text[32];
You change the datarate , palevel and channel in nrf24l01.
See datasheet for more info.
Or visit https://howtomechatronics.com/tutorials/arduino/arduino-wireless-communication-nrf24l01-tutorial/
You may have power issue because pro mini might not deliver sufficient....to neglect use a 10uf Cap in nrf.


You can either set the router to allocate a static IP based on your esp8266's MAC address, or go the DHCP-way first, read the gateway IP address you got, and then do a WiFi.config(), something roughly like this (untested):
WiFi.begin(ssid, password);
IPAddress ip = WiFi.gatewayIP();
IP[3] = 15;
IPAddress dns(8, 8, 8, 8);
WiFi.config(ip, WiFi.gatewayIP(), dns, WiFi.subnetMask());

It is a bit of a trick, and not pretty, and you don't get to set the DNS as provided by the DHCP, because there is no getDNS(), for some silly reason, hence the use of Google DNS.
Note that when doing this, you run the risk of setting the esp8266's IP address to an address already taken by another device on the same router.


Pin 10 is special. It's the hardware chip select pin for SPI.  It is integral to the SPI peripheral in the chip.

That pin must be an OUTPUT for SPI to operate as master, or INPUT for it to operate as a slave.

It's a stupid design decision by Atmel if you ask me, but there you go.  So basically trying to use SPI at the same time as PWM on pin 10 is "undefined" and to be avoided.

Use a different pin for PWM or if you need more than there are PWM pins available then consider an external PWM control chip.

Just probing around to get more detail on exactly how it all works, this is what I have found:

digitalWrite() explicitly disables PWM on a pin.
The direction of pin 10 defines the SPI operation as master or slave.
analogWrite() sets pinMode(OUTPUT).
The SD library calls pinMode(OUTPUT) and digitalWrite(HIGH) on pin 10.

This means that:

SD.begin() will terminate any existing PWM on pin 10.
Using PWM on pin 10 will force the pin to output rendering SPI slave mode impossible

You should be able to use PWM on pin 10 if, and only if:

You use analogWrite() after using SD.begin(), and
You never want to use SPI slave mode.


To any 2 free IO pins.

To quote sparkfuns datasheet:

  (1) Using IO trigger for at least 10us high level s ignal,
  (2) The Module automatically sends eight 40 kHz and  detect whether there is a pulse signal back.
  (3) IF the signal back, through high level , time of high output IO duration is  the time from sending ultrasonic to returning.
  Test distance = (high level time×velocity of sound (340M/S) / 2,

In other words you send a short pulse to trigger pin and then wait for the echo pulse and measure how long it was high. Divide the number of microseconds it was high by 58 and you have the distance in centimetres ( use 148 for inches)


Trying to read the current position of a flex sensor and store it as a variable? NANO ATmega328p

You will need to add this at the start of your code.

int LoggedPosition=100;

Change this line

if (flexSensorReading < 100) {

To this

if (flexSensorReading < LoggedPosition) {

and add this at just before the delay, at the end of the loop() function

if(digitalRead(inPin)){
    LoggedPosition=flexSensorReading;
}


Are there any alternatives to Tinkercad Circuits that is PC application based instead of web app based?

I work with the wokwi Arduino simulator

It is faster
It uses the latest Arduino IDE for compilation
It almost runs in real-time. For example, your job of 15 seconds might get executed at about the 17th or 20th second.

Please give it a try. here are some references

Links: https://wokwi.com and https://wokwi.com/arduino/libraries


Arduino webserver: faster alternative to "indexof" for parsing GET requests?

Well, for fast parsing I wouldn't use String for a start. I've written an example (below) which does away with the String class, and also demonstrates parsing the line once.

#include <SPI.h>
#include <Ethernet.h>

// Enter a MAC address and IP address for your controller below.
byte mac[] = {  0xB3, 0x8D, 0x72, 0x1D, 0xCE, 0x91 };

// Our IP address
IPAddress ip(10,0,0,241);

// Initialize the Ethernet server library
// with the IP address and port you want to use
// (port 80 is default for HTTP):
EthernetServer server(80);

void setup()
  {
  // Open serial communications and wait for port to open:
  Serial.begin(115200);
  while (!Serial) { } // wait for serial port to connect.

  // start the Ethernet connection and the server:
  Ethernet.begin(mac, ip);
  server.begin();
  Serial.print(F("Server is at "));
  Serial.println(Ethernet.localIP());
  }  // end of setup

// how much serial data we expect before a newline
const unsigned int MAX_INPUT = 100;
// the maximum length of paramters we accept
const int MAX_PARAM = 10;

// Example GET line: GET /?foo=bar HTTP/1.1
void processGet (const char * data)
  {
  // find where the parameters start
  const char * paramsPos = strchr (data, '?');
  if (paramsPos == NULL)
    return;  // no parameters
  // find the trailing space
  const char * spacePos = strchr (paramsPos, ' ');
  if (spacePos == NULL)
    return;  // no space found
  // work out how long the parameters are
  int paramLength = spacePos - paramsPos - 1;
  // see if too long
  if (paramLength >= MAX_PARAM)
    return;  // too long for us
  // copy parameters into a buffer
  char param [MAX_PARAM];
  memcpy (param, paramsPos + 1, paramLength);  // skip the "?"
  param [paramLength] = 0;  // null terminator

  // do things depending on argument (GET parameters)

  if (strcmp (param, "foo") == 0)
    Serial.println (F("Activating foo"));
  else if (strcmp (param, "bar") == 0)
    Serial.println (F("Activating bar"));

  }  // end of processGet

// here to process incoming serial data after a terminator received
void processData (const char * data)
  {
  Serial.println (data);
  if (strlen (data) < 4)
    return;

  if (memcmp (data, "GET ", 4) == 0)
    processGet (&data [4]);
  }  // end of processData

bool processIncomingByte (const byte inByte)
  {
  static char input_line [MAX_INPUT];
  static unsigned int input_pos = 0;
  switch (inByte)
    {
    case '\n':   // end of text
      input_line [input_pos] = 0;  // terminating null byte
      if (input_pos == 0)
        return true;   // got blank line
      // terminator reached! process input_line here ...
      processData (input_line);
      // reset buffer for next time
      input_pos = 0;
      break;

    case '\r':   // discard carriage return
      break;

    default:
      // keep adding if not full ... allow for terminating null byte
      if (input_pos < (MAX_INPUT - 1))
        input_line [input_pos++] = inByte;
      break;
    }  // end of switch
  return false;    // don't have a blank line yet
  } // end of processIncomingByte

void loop()
  {
  // listen for incoming clients
  EthernetClient client = server.available();
  if (client)
    {
    Serial.println(F("Client connected"));
    // an http request ends with a blank line
    boolean done = false;
    while (client.connected() && !done)
      {
      while (client.available () > 0 && !done)
        done = processIncomingByte (client.read ());
      }  // end of while client connected

    // send a standard http response header
    client.println(F("HTTP/1.1 200 OK"));
    client.println(F("Content-Type: text/html"));
    client.println(F("Connection: close"));  // close after completion of the response
    client.println();   // end of HTTP header
    client.println(F("<!DOCTYPE HTML>"));
    client.println(F(""));
    client.println(F(""));
    client.println(F("<title>Test page</title>"));
    client.println(F(""));
    client.println(F(""));
    client.println(F("
My web page
"));
    client.println(F("
Requested actions performed"));
    client.println(F(""));
    client.println(F(""));

    // give the web browser time to receive the data
    delay(10);
    // close the connection:
    client.stop();
    Serial.println(F("Client disconnected"));
  }  // end of got a new client
}  // end of loop

The incoming lines from the client are captured in a static buffer. This eliminates issues with memory fragmentation (caused by using String).

processIncomingByte is called for each byte from the client. Once an entire line is assembled it calls processData. If that finds a "GET " line it calls processGet. That looks for the parameters on the GET line. The GET line looks like this:

GET /?bar HTTP/1.1

So we need to get between the "?" and the next space, to get the parameter ("bar" in this case). This can be accomplished by finding their positions with strchr.

Finally (as a simple example) I tested with strcmp for a direct match on various words. You could probably make that more efficient but I doubt it would matter much.


How can I connect the MP503 to an Arduino Uno (Smoke, Alcohol Sensor)?

Ok, first of all I doubt you will be able to get a lot of measurements with that. Because... I know that kind of sensors and you will quickly get tired of it.

Anyway, you have to connect

pin 1 to +5V
pin 2 to ground
pin 3 to +5V
pin 4 to a resistor towards ground. Value has to be determined.

To chose the value, you have to try. Change resistor values until, in fresh air, the voltage you can sense across the resistor is approx 1V. I think it is arount 10k, but you'll have to try

Chosen the resistor, you have to simply attach the node between pin 4 and the resistor to an analog input and then read the voltage.

Now you have to calibrate the sensor. Put it in a fixed-concentration gas and measure the voltage: nCalib = analogRead(sensorPin);.

Then, when you need to measure the concentration, you just have to read the voltage again with nMeas = analogRead(sensorPin);. The factor Rs/Ro can be calculated with the formula

Rs_over_Ro = nCalib / (1024 - nCalib) * (1024 - nMeas) / nMeas;

Once you have the factor, look at the graph in figure 3 to get the concentration:

As I told you, I think you will quickly get tired of it, but this is how to use it.


Why delay of more than 64 millisecond stops the servo motor from rotating? I am not using "Servo.h" instead i am just managing the length of pulse

A servo motor doesn't just require a single pulse to send it to a specific angle. It requires a constant stream of pulses at the right frequency for it to track what the angle should be.
By sending one pulse you're just hinting where it might like to go to, then stopping. It's never going to get there, unless you keep sending those pulses fast enough.
Also if you don't send pulses then the servo will go into a "low power sleep mode" where it's not actively driving the output and it will go "floppy" where you can move the servo by hand.
Typically you need to send pulses at about 50Hz, which is one pulse every 20ms. Many servos will be more forgiving, but if you send too slowly they just won't know what to do.
If you want to be handling the pulses yourself then you need to do it in the right way.  That is:

Send a pulse of your desired length
Delay for 20ms minus your desired length
Go to 1 until your desired elapsed time has been reached.

For example:
for (angle = 0; angle<180; angle++){
  uint32_t ts = millis();
  while ((millis() - ts) < 100) { // 100ms delay
    digitalWrite(servo, HIGH);
    delayMicroseconds((angle * 11) + 650);
    digitalWrite(servo,LOW);
    delayMicroseconds(20000 - ((angle * 11) + 650));
  }
}

That won't be exact, owing to the latency of the loop instructions, but it will be close enough.


What would cause a delay when using serial between the Arduino IDE & external clients?

If your data input rate is higher than, or even close to, your serial output rate (baudRate/10 char/s), your system will be unable to keep up.

With an interrupt driven system, make sure your interrupt function executes and returns as quickly as possible, i.e., does as little as needed to not lose data. Let the background process (the main sketch code) deal with the incoming data as it appears. Make sure the both processes are short enough to deal with the worst-case input-data bursts without losing any. For the background process, use as high a baud rate as it is capable of - and as it's downstream neighbor (Storage device? Another MCU or PC?) is capable of - keeping up with.


millis() returns the ACTUAL time milliseconds since the start of the program. Wheter you put a delay, you do multiple tasks, millis() will still return the right time.

The other method that you mentionned will not work if, for example, you add a delay in the program. Then, for more complex tasks that might take more time, your "custom" counter will be very unacurate.

I short, just use millis(). It is easy to use and works great.

P.S. Use an unsigned long instead of a long.


Flickering LCD backlight with fingerprint scanner

The backlights on these LCDs are just an LED array with a series resistor so the intensity will be directly proportional to the input voltage; flickering voltage = flickering backlight.

Check these things:

Measure the output of the 5V regulator with an AC volt meter to see if the regulator is oscillating when the backlight flickers, i.e. AC voltage >> 0V.  If it is, then you probably need to increase the size of the output and possibly the input capacitors.
Measure the Input-to-Output voltage differential of the regulator and multiply it by the output current.  If you dissipate more power than the thermal design allows this will heat the regulator making (1) more likely as well as driving the regulator into thermal shutdown.

If the regulator is linear, i.e. 7805 etc, you can solve both (1) and (2) by changing the regulator to a drop in switching type.  These will dissipate heat as a percentage of the output power instead of as a function of the input voltage and can be made self contained with regard to input/output capacitors which would be on-board instead of off-board.  A switcher can also do something a linear can't do:  Supply more current than the source.  A 12V 0.5A power supply into a 5V regulator can supply 5V at 0.5A with 3.5 watts of waste heat.  That same 12V supply into a decent switcher can deliver 1.14A at 5V with only 300mW of waste heat!

This PDF is an example circuit that runs about 95% efficient and fits on a 7805 footprint.

This PDF is the circuit of the 1516 switcher linked above configured to replace the NCP1117 linear regulator use on the Uno Rev3.

This PDF is a full thermal analysis of the Arduino Uno NCP1117 regulator running under the conditions stated in your question.  As you can see, you were right on the edge of what the NCP1117 could handle at 200mA (LCD plus scanner).  I have included a thermograph showing the same unit supplying 1.85A at 5V using a drop in switching regulator with no issues.


Why can't I declare a class in another tab in Arduino IDE?

It is not possible to declare and use classes declared in one .pde file in another .pde file from within the Arduino IDE.

One workaround is to make the second file into a C++ source file (.cpp) and then add a #include "<filename>" directive in the beginning of the first file.

This code compiles correctly:

Tab 1:

#include "test.cpp"

TestClass obj;

void setup()
{
    obj.init();
}

void loop()
{
    //...
}

test.cpp :

class TestClass
{
public:
    void init()
    {
        //...
    }
};


Reproducing a Fiber Optic Shape Sensor with Arduino?

I think nobody here can really give you an answer, if this is possible with an Arduino, since we don't know enough about the technology and the nitty gritty things, that make this a difficult task. So making a hobbyist version won't be easy and maybe really expensive.

In the fiber each bragg grating reflects a bit of the light back. The wave length of this reflected light is dependend on the angle between light and grating. So you get a specific wave length back from each grating, that corresponds to the bending at that particular part of the cable. The task is to measure the many wave lengths, that are being reflected in the fiber, and match them to a particular part of the cable. Since they don't say, how they are solving this, I will mention some ideas here:

Spectral Measurement (Wave length):

From the video I guess, that they use white light to shine into the cable. The gratings will only reflect the wave lengths from this spectrum, that satisfy Bragg's law due to bending angle. You have to measure the wave length directly with a spectrometer. Mostly this is another grating, that will seperate the wave lengths spatially, so that you can measure the spectral structure by using a spatial sensor, for example a camera or a line sensor. You would have to correct for different wave length sensitivities of the camera.
Maybe they are only using a laser with 1 wave length. Then the bending would result in a change in intensity reflected from that grating. If you can seperate the signals from the different gratings good enough, you would be able to measure just the change in intensity, which would be easier, since you basically need just a photo transistor or similar for that wave length. (In this case you would need to calibrate the sensor each time as a straight cable and ensure, that the measurement is fast enough for the expected movement).

Matching of signals to each part of the cable: Here I guess, that they use a time-of-flight sensor, because I cannot think of anything else without further information. This is a really difficult problem, because most available sensors are not sensible enough for measuring quarter inches without being cheap in the first place. You will likely spend a lot of money for a sensor like this. And you building an own time-of-flight sensor with the wanted sensitivity may be as difficult as building the whole device in the first place.
Needed Parts: Also you will need the fiber itself, which is - as stated - not a normal glas fiber, which you can by everywhere. It is most likely a custom build and you will pay a lot of money, to get one of these. The light source is dependend on the spectral measurement above. For a white light it is important, that all wavelength should have as equal intensity as possible. You would also have to account for the spectral absorption and the overall absorption in the fiber, which restricts the sensitivity and possible lengths.

  Is there anywhere to buy this sensor directly?

Most likely not. In the videos it seems like a device, that was developed by the NASA for a specific application. The video is a proposal for other companies to learn from the NASAs development, so the device is not consumer ready. But you might be able to get a paper about this device by searching the internet for it or by asking the NASA directly. This paper would contain way more information about the device as the videos.

All in all this would be an extremely difficult task. Since you came here (a simple Q&A site) with this difficult question, I think, that you are not really ready for this big of a task. Most likely even the developers at the NASA needed long and much money for this.

  Are they any alternatives for 3D shape/position sensing besides 3D magnetic sensing?

I would propose to build a string of bending strips, which change their resistance according to the bending angle. You can use multiple strips for getting multiple readings for different parts of the human arm. With each strip you build a voltage divider and do an analog measurement. With a bit of calibration you should be able to measure the curls.


Entering integers as bytes in serial monitor

Using the Arduino IDE Serial Monitor, there's not much you can do. But you can use a different serial-port terminal such as RealTerm (for Windows, if that's your thing) which allows for a wide array of serial port nitty-gritty details.


The answer is yes and no.

Only the Arduino and its IDE, no.

The way I found is to use Processing to wait until it detects a hotkey, then send a serial message to your Arduino. If you tune in the right COM port, this should work.


The Arduino core does things at startup. One of those things is to configure the timers ready for PWM operation.

Here's the relevant bits from init() in wiring.c:

    // set timer 1 prescale factor to 64
    sbi(TCCR1B, CS11);
#if F_CPU >= 8000000L
    sbi(TCCR1B, CS10);
#endif

#if defined(TCCR1A) && defined(WGM10)
    sbi(TCCR1A, WGM10);
#endif


max7219 chained display showing mirrored text

Since version 3.0 MD_MAX72xx.h no longer supports that definition. Now the hardware type is defined as a parameter on creation (in the "Example" file you are using - not in MD_MAX72xx.h)

#define HARDWARE_TYPE MD_MAX72XX::FC16_HW
...
MD_Parola P = MD_Parola(HARDWARE_TYPE, CS_PIN, MAX_DEVICES);

Note that I've changed the hardware type from PAROLA_HW to FC_16.


Using 18650 batteries with a 3.7v to 5v boost converter

is it safe to wire the boost converter directly to the output terminals of the battery/batteries and take the 5V off the +5v pin using a common ground?

Yes. That is the normal way of using them.

  Also, I'm not 100% sure how to go about charging this setup. One option would be to put the batteries in cases and use an external charger with replaceable cells.

That is the simplest option, yes. You shouldn't charge Li-Poly / Li-Ion batteries whilst using them - the load messes with the charge termination detection and can cause your batteries to over-charge and explode.

  Would it make more sense to get one of these? This should be able to handle both charging AND stepping up the voltage, am I right?

That gets around the problem of charging while running, yes. A proper charger like that should bypass the battery when charging so the load is running from the incoming charge power rather than the battery.

One option you haven't considered though is to not use step-up.  Step-up is harder to manage with heavy loads. As you can see that first step-up module you link to has an upper limit of only 1.2A.  If you have 60 LEDs per meter, and 1 meter of LED strip, that's a maximum of 3.6A (60 * 0.02 * 3) which is 3x what that module can provide.

A better solution would be to use two batteries in series, not parallel, to give you about 7.2V. Then you can use a step-down switching regulator to give you your 5V and have far higher current limits.  Looking for a "UBEC" or "SBEC" in a model RC supplier shop is usually a good bet. For example:

Turnigy 5A (8-26v) SBEC for Lipo

HobbyKing™ HKU5 5V/5A UBEC

These are all designed for use with two or more LiPoly batteries in series.


The processor is somewhat faster than serial input. If you really want to wait for nothing more to arrive you should probably add a short delay (although jsotola's suggestion of looking for a newline is sensible). Something like:

void serial_flush(void) {
 while (true)
   {
   delay (20);  // give data a chance to arrive
   if (Serial.available ())
     {
     // we received something, get all of it and discard it
     while (Serial.available ())
       Serial.read ();
     continue;  // stay in the main loop
     }
  else
    break;  // nothing arrived for 20 ms
   }
}


DigiSpark attiny85 computer not detecting

Unless, during the short time it shows in device manager, you see that it is missing a driver, it would seem you don't need to do anything further with drivers.  You didn't mention it saying it was missing a driver or as an "unrecognized" device, so I'm guessing you mean it doesn't stay recognised or that it isn't recognized as a serial device.  If I'm incorrect in that, do say. The fact that it is showing in device manager for any length of time suggests that your cables are fine.
I'm not a Digispark user, but as far I can understand what you're saying, the connecting and disconnecting (once at least) is expected behaviour:

In addition remember the Digispark only shows up as a programmable
device for 5 seconds, after that it will start running its code (when
it is new and un-programmed this means it will blink) and disappear or
act like the USB device you programmed it to act like.

If anything in the sketch (or lack thereof) causes the board to reset or jump to the bootloader, it would continually reconnect for 5 second intervals.  They documentation suggests should blink, as in run a blink sketch that was put on the board before you received it.  But then you got this from ebay, so who knows what they did or did not put on it.  I haven't studied the micronucleous bootloader enough to know, but it wouldn't surprise me if it jumps to the sketch area irrespective of whether or not it's unprogrammed.  If it is unprogrammed then it is probably nop-sliding, for lack of a more appropriate term, right back into the bootloader.
You're not going to see it recognized as a serial port device like a typical Arduino.  The bootloader uses a vendor specific protocol that will not list as a COM# (or /dev/ttyXYZ#) device.
Indications are that if you compile the blink sketch and "upload", the IDE will run the micronucleus programming tool which gives you a 60 second window for you to plug the board in, at which point it will load the board with the blink sketch.  After which it should blink the LED.  If unplugged and replugged, you can expect it to show up for 5 seconds on USB and if left alone should disconnect (electrically) from USB and begin blinking.


Newbie question: Set servo at certain degrees when something happens

From your statement pinMode(D6, OUTPUT);, It looks you're using pin6 for the servo - ? If so, you need instead: myservo.attach(6); to prepare a servo object to use that pin to drive a servo. Not having done this is the reason why your servo wasn't moving. There is an example program to drive a servo using the servo library on the Arduino site.

Your code will run very fast, but since soil moisture can't change rapidly, the value being read from the soil sensor shouldn't either - unless there is electrical noise (and there will always be some; it's a question of how much). Your print statements should show you how consistent the readings are.

There are a couple of things you can do about it:

Delay for a second or so at the bottom of the loop() function so the servo updates will come less frequently and the servo will have time to track them. This really doesn't help with a noisy signal though, and you probably don't want it to track noise. Also, I don't usually suggest using delays but in so uncomplicated a program as this one, it is really the most straightforward approach.
Calculate the servo position from an average of a few sensor readings rather than using just one. This will help with noise so the servo should only have to track real data rather than data+noise.
Do both. Update less frequently and average a few readings taken a few 10s of milliseconds apart. This will both reduce noise and keep the servo updates to within its tracking ability.


Adjust time calculation after Timer0 frequency change

Fixing the timekeeping functions with your PWM settings is not so
simple. You should at least try to rewrite ISR(TIMER0_OVF_vect),
micros(), and probably delay(). Here is why:

First, there is a rounding problem. Time is kept using two global
variables:

volatile unsigned long timer0_millis;
static unsigned char timer0_fract;

The first one is what millis() returns. The second one keeps track of
how much time has passed since the last full millisecond, and it does so
in units of 8 µs. The two variables are incremented by
ISR(TIMER0_OVF_vect) like this:

m += MILLIS_INC;  // temporary copy of timer0_millis
f += FRACT_INC;   // temporary copy of timer0_fract

On a normal Uno configuration, the ISR is called every 1024 µs.
Then MILLIS_INC is 1 and FRACT_INC is 3. With your timer
configuration, the ISR is called every 31.875 µs (510 cycles), then
MILLIS_INC should be 0 and FRACT_INC should be 3.984375. But since
we are dealing with integers, it will be rounded down to 3, and your
millis() will tick about 25% too slow.

A simple fix would be to

#define MICROSECONDS_PER_TIMER0_OVERFLOW (clockCyclesToMicroseconds(1 * 512))

in order for FRACT_INC to be 4 and millis() to be 0.4% too fast. Or
you could make timer0_fract a 16-bit variable and have it count clock
cycles, just to avoid this error. Either option should fix millis(),
but you still have a problem with micros().

micros() works by reading both timer0_overflow_count (incremented by
1 in the ISR) and the actual counter value. Since your counter is now
going alternatively up and down, it will be harder to compute a
microsecond count from these readings. Maybe you could take two
consecutive readings of the counter, just to know whether it is going up
or down...

And then there is delay(), which relies on micros(). If you fix
micros(), delay() should work fine. If not, You could rewrite
delay() to use millis() instead, which should be easy but you will
loose some accuracy.


Powering SD breakout board with 3.7V battery

You haven't connected the grounds together in your circuit. You need to connect all the grounds together so every connection has a return path back to where it came from.  That means connect together:

An Ardino GND pin
The GND pin of the SD card breakout board
The negative (or ground) pin of the battery


That depends on if you're using a NodeMCU or a "naked" ESP8266.

The NodeMCU has a fixed voltage divider with 220K/100K resistors to ground, contributing about 10 µA to quiescent current (plus the much smaller current caused by the ADC input impedance).

If you're using a NodeMCU you also have to worry about the USB-to-Serial chip and the on-board voltage stabilizer.

The input impedance of the ADC input of a "naked" ESP8266 is (probably) a lot higher, 1 or more MΩ, although it is almost impossible to find definitive numbers.


You can't have a single ESP8266 be both an access point and a client, at least not using the exposed API (recall that the Arduino libaries do not implement much functionality themselves, all they do is call the underlying RTOS API).

Also, a signal repeater is not a radio-only device. It would have to understand the low-level 802.11* protocols and packet types so you don't end up with forwarding loops. You can't do it just by connecting a pair of 8266s back-to-back over SPI and blindly forward packets; there is a lot of networking code that would have to be written.