Whats the difference between RF options (wifi, xbee, NRF24L01)

There are many different type of RF networks with various advantages and disadvantages. The main things I consider when choosing a wireless communication method are network topology, data rate and power consumption.

WiFi:

High data rate (54Mbit/s +) but also high power consumption. Used when you need to connect directly to the internet, such as an internet-of-things device, and have an external power source.

XBee:

Low data rate (250kbit/s) and low power consumption. Used to make mesh-type sensor networks; each XBee device can communication with each other, and through each other via the mesh to devices that are out of range. Used for networks of devices, particular home automation and sensors. link.

Bluetooth:

Medium data rate and medium power consumption. IEEE standard has different device profiles to enable interoperability between devices. 'Pairing' type network however, so not useful for sensor networks, but good for controlling devices using a laptop or phone which usually have Bluetooth on board. Communicates with Arduino via serial RX and TX pins. link.

Bluetooth Low Energy, ANT, etc:

Very low data rate and very low power. These RF chips can run for years on an AA battery and so are used for things like heart rate sensors. The data rate is quite low so only good for transferring a small amount of data such as sensor readings. Most devices are setup as peripherals and can only connect to one 'central' device, so no good for sensor networks. Bluetooth low energy is supported by the latest mobile phones and laptops however. Useful to enable control of a device using a phone or laptop, for example a LED lamp. (See redbearlab for some Arduino options)

GSM

Phone connection. TODO

nRF24L01 / RFM12B / RFM22B(SI4432)

Popular proprietary transceivers. They can connect via SPI and have a lot of fancy features like low power modes, multiple channels, channel hopping, frequency calibration, CRC, retransmit and so on. The nRF24L01 from Nordic Semiconductor link operates in the 2.4GHz band, others use the ISM band 433/470/868/915Mhz.
These are todays state of the art highly integrated and low cost hardware for  reliable telemetry and consumer applications. The range is between 10m and 150m. The SI4432/RFM22B has the range of about 1.5Km.

Other RF modules

Simple and cheap serial devices. Single transmitter/receiver or transceiver that operate in the ISM band link. Often used as garage door opener. Useful for sensor network where interoperability with other devices is not required and you can implement your own protocol. link


Is setup and loop provided for convenience?

Those pieces of code are pretty much the same.

If you look at the Arduino source code you'll see:

setup();

for (;;) {
  loop();
  if (serialEventRun) serialEventRun();
}

(I'm not sure what serialEventRun() does.)

I don't think you can 'overload' the main function declaration. Also note that the main function calls init, which e.g. configures the timers, so millis() etc. will work.


The function println usually appends a carriage-return and linefeed to what it prints. It wouldn't surprise me if those two extra characters are its attempt to "render" that.

Try replacing println with print and see what happens.


Is it possible to reprogram an atMega328 chip inside of a pcb?

I'm assuming you're trying to program using an AVR programmer.

Yes, it's very likely you'll be able to do that. You need to connect the AVR programmer to the correct MCU pins (Sck, Si, So and Rst), including ground and vcc... as you would do with the chip by itself.

If you have any othe SPI device connected to the same pins, make sure it's not enabled - that might be as simple as having the device's CS pulled high.

The way you'll make the connection is up to you, you might need to use some clips, pogo pins or simply solder some wires to the MCU pins.

If you have other things connected to any of the MCU programming pins, you might need to disconnect, but that will vary case by case.

Cheers


I could not figure out what was wrong, but I changed to this library for NRF24: http://tmrh20.github.io/RF24/

and I started using the GY-85 with the FreeIMU Library : http://www.varesano.net/projects/hardware/FreeIMU

Following this advice:
http://forum.arduino.cc/index.php?topic=164222.msg1539961#msg1539961

It works now, so if it was SRAM as @Avamander suggested, it was not on my side.


Wirelessly (but fast) transfer STEP and DIR output from Arduino to stepper driver

(Moved to "answer" for space; it's definitely not an answer. Sorry all!)
Minor points:

It's a motor controller shield; the GRBL is on the Arduino.
You'll need a motor controller at each motor; not clear if that's understood.
I'd also consider optical comms, although it has a different set of problems.

Ultimately I might approach this in a different way: instead of a single GCode box attempting to synchronize and control itself and an (essentially) independent system, I'd consider having a single GCode box (GBOX) controlling two independent systems (M1, M2).
GBOX would be a laptop/RPi/whatever that processes the "real" GCode. Based on the GCode commands, which in the end just tell motors what to do, I'd send each GCode command to its associated M1/M2 system.
How well this works depends a lot on the GCode, however; diagonals, arcs, etc. require motor cooperation, so a command like G02 X2Y0 R2 might cause problems, even though we can pull out the X and Y data. How the GCode is generated matters, but note that GBOX could also interpolate "tricky" commands to break them into something a dual-target system might be able to understand.
The "meaning" of the moves also matters: there's "getting from one place to another" and "getting from one place to another while drawing a line": the former may (or may not) have requirements around what that actually means, while the latter requires coordinated motion, and even if you're splitting the commands up correctly, even a fraction of a second difference in receive/action time will matter. Of course, you could also transmit both motors' commands to both motors and rely on timing or cross-Mn synch for starting their respective commands.
In the end it may be the only real way to make this work would be to have the "independent" systems be able to synchronize with each other, so that they know they're (a) ready to start, and (b) starting at the same time. GBOX could also potentially handle that synchronization as a "Go!!!" command is about as deterministic as it gets, especially if M1/M2 can receive a broadcast signal at the same time.
https://www.zikodrive.com/motor-control-case-studies-and-applications-2/a-remote-controlled-and-synchronised-stepper-motor-controller/ (very) briefly discusses the issues around synchronizing remote motors where their relative positions matter.


Which is RX and TX pin of the HM-10 module?

That's not an HM-10 but an EY-08. It's the same chip, but it's been provided in a different footprint (and maybe with different firmware installed).

Pin P03 is TX and pin P02 is RX.

The AT command set, pinouts, and examples for wiring it are detailed here (Thanks to Mikael Patel for finding that link).


Arduino as USB HID is slowed down when PC doesn't read events

For those that hit the same issue, here is how I solved it:

Expose the USB_SendSpace() information in the HID interface by editing

/usr/local/arduino-1.8.12/hardware/arduino/avr/libraries/HID/src/HID.cpp

u8 HID_::SendSpace(void)
{
        return USB_SendSpace(pluggedEndpoint);
}

And adding the interface to class HID_ in:

/usr/local/arduino-1.8.12/hardware/arduino/avr/libraries/HID/src/HID.h

That way, before calling HID().SendReport() you can check for send buffer space available by calling the HID().SendSpace() method.

If there is no space, just skip the SendReport() calls, and the Arduino loop() will no longer be slowed down by time outs.


While @alexan_e’s suggestion fixed your practical problem, I would argue that it did not address your root cause, which is that whatever board setting you’re working from in boards.txt assumes a clock rate of 8MHz, while in reality your fuses are set to boot the microcontroller at 1MHz. This caused your delay(100) to take 800ms, and was the entire reason for the slowdown.

Instead of fixing this at runtime, as aleman_e suggested, it seems more natural to me to bring your fuse settings into alignment with your compiler settings, using the “burn boot loader” Arduino command (which on Attinys generally does NOT burn a boot loader, but only sets the fuses to be in sync with the compiler settings).

If your application is not going to become much more complex, running at 1MHz might be a more efficient choice than running at 8MHz.


How to avoid report of unsuitable sketch names?

That message is actually a hang-over from when the IDE was Processing.  The name of a file had to match the name of the Java class within that file, and there are strict rules about what can be in a Java class name.

They just basically haven't got around to deleting that piece of ancient code yet.

So you have 3 options:

Rename all the folders and files.
Edit the IDE's source code to delete that old code
Use a different IDE.

The first option can be long winded if you don't know how to do good scripting, as you have found out.

The second option requires knowledge of Java coding.

So that leaves the third option.  Now, I'm going to be shamelessly advertising my own work here ;)  Why not try a better IDE?  Such as the popular and powerful UECIDE (yes, written by me). It's based on the Arduino IDE, so it will mostly be familiar to you, but the whole of the insides have been ripped out and re-written.  If you're feeling brave you might want to give the beta version a go - it has some really really cool features not found in any other IDE in the history of mankind.


Arduino write to memory and self shut down (over MOSFET) - An idea help

You should be using a P-channel MOSFET (which is set to be normally OFF with a pull-up resistor) and the Arduino is responsible for keeping it on:

simulate this circuit – Schematic created using CircuitLab

In this schematic M1 is normally off.  You press and hold SW1 and the Arduino gets power. The first thing it then does is turn on the GPIO. That turns M2 on, which in turn pulls the gate of M1 LOW turning it on. You can now release M1 and the Arduino will stay on.  When you want to turn off, just switch off the GPIO, turning off M2, which then allows R1 to pull the gate of M1 up again turning off the power.

This arrangement means:

You can control an incoming voltage higher than 5V (thanks to M2 doing the actual switching of the power MOSFET)
You get a soft-power switch to turn the power on
Current draw of the control circuit is basically the incoming voltage divided by the resistance of R1 (you can safely increase this if you want to reduce current draw - 1MΩ is fine).
You can have all the rest of the circuitry on the Arduino side of M1 so it has power removed when switched off (to prevent over-discharge of your batteries)
You are switching VCC, not GND (switching GND can cause all sorts of problems).


Send data to a pc localhost with ESP-01 wifi module

"localhost" is a name associated with the loopback interface of your computer. That is, 127.0.0.1.

It is not the address of your computer on the network. The only computer that can talk to "localhost" is the computer itself.

Instead of "localhost" you must use the IP address of your computer (or a FQDN that resolves to the IP address of your computer).

And you cannot open a TCP connection to a URL.  You open a TCP connection to an IP or FQDN.

You really should learn the basics of IP networks before trying to write software for them.

Since your PC can communicate with the ESP8266 on 192.168.4.1 I assume that you are running the ESP8266 in SOFTAP mode and you have a WiFi interface connected to that access point. If so that WiFi interface will have a 192.168.4.x address assigned to it.  That is the address you must open with a TCP connection on port 80 to connect to your apache server.

For example:

sendData("AT+CIPSTART=0,'TCP','192.168.4.3',80\r\n",1000,DEBUG);

Then you can craft a suitable HTTP request to send the data.


Is the a low memory alternative to SoftwareSerial?

Simplest thing would probably be to edit your copy of SoftwareSerial.h
and replace #define _SS_MAX_RX_BUFF 64 on line
42
by something smaller. If your loop() runs fast enough (no delays, no
blocking code) you could probably get away with buffering only a very
few bytes.

Or you could rewrite the library so that, instead of buffering the
incoming bytes, it handles them to you for processing. See for example
this receive-only UART code based on the USI
port for an illustration of the
approach.


How to design and debug a custom I2C master-slave system?

This tutorial I gave at the Embedded Linux Conference tries to answer the questions, providing links to more detailed description of the topics addressed and using the practical example of driving a 4WD drone, where an Arduino Mini Pro acts as slave and controls the 4 independent wheels.
The original document can be found here.

Note: This answer is currently work in progress, as I adapt the highlights from the link.

Typical Applications of the I2C bus

Interfacing with relatively slow peripherals. Ex: sensors, mechanical actuators.
Controlling “fast” peripherals, that use other channels for exchanging data. Ex: codecs.

In a PC, the Operating System usually interacts over I2C with:

temperature and battery voltage meters;
fan speed controllers;
audio codecs.

In case multiple bus controllers are available, peripherals are grouped by speed, so that fast ones are not penalized by slower ones.

A quick introduction to the I2C bus - key features

Serial bus.
Only 2 lines: Serial CLock and Serial DAta (plus ground).
4 speeds: 100kHz, 400kHz, 1MHz, 3.2MHz.
Typically, 1 master device and 1 or more slaves.
Communications are always initiated by a master device.
Multiple masters can co-exist on the same bus (multi-master).
Open-Drain: both SDA and SCL need pull-up resistors.
“Clock Stretching”

The master controls SCL, but a slave can hold it down (because open drain), if it needs to adjust the speed.
The master must check for this scenario.
A slave can get stuck and jam the bus: need for reset lines from the master to the slave.

Typically 7-bit addressing, but also 10 bit is supported.
Logical protocol: actual voltage levels are not specified and depend on individual implementations. Ex: 1.8V / 3.3V / 5.0V

Reference URLs:

http://www.i2c-bus.org
http://www.robot-electronics.co.uk/i2c-tutorial

Example of Bus Configuration

Characteristics of the Protocol (simplified)

2 message types: read and write
Start / Stop bit - represented as “[“ and “]” in the rest of the answer
Address: 7 or 10 bits
R/W bit: R = 1 / W = 0 Used to discriminate the type of message sent.
Data on the bus: (Address << 1 | R/W)
Registers as information handlers, within the selected device.

Example of Bus traffic

Custom Slaves

Why create a custom I2C slave?

Desired sensor/actuator unavailable with I2C interface.
Less unique addresses available than slaves needed.
Desired custom functionality on the slave:

Semi-autonomous reactions to stimuli.
Filtering/preprocessing input data.

Power optimization: custom “sensor hub” does the housekeeping while the main processor is idle.
Realtime response to inputs.
[your imagination here]

How to design a custom I2C slave?

Define requirements (see previous slide).
Choose microcontroller or microprocessor.
Choose Scheduler or Operating System (if any).
Define communication sub-protocol:

Define parameters and commands to be exchanged.
Organize them into “registers” and choose a free address.

Design of the I2C Master

Key design criteria:

Weight/Dimensions.
Required computational power and average latency.
PC-like device

Embedded device, typically headless.
Preferred programming language: interpreted vs compiled.

Availability of busses/gpios for driving the slave(s):

GPIOs only: bitbang the protocol
I2C: user-space application vs kernel driver.
No GPIOs/I2C interfaces available: USB to I2C adapter.

Debugging: Divide and Conquer

Take direct control of the bus with an ad-hoc device.
Examples:

Bus Pirate (useful also for other busses)
USB to I2C Master adapter, also based on the FTDI FT232R chip.
Custom device (could be a separate project).
Snoop the bus with a logic analyzer or a scope/advanced meter.
Examples:

sigrok/pulseview with compatible logic analyzer
2-channels standalone scope/meter
Use slave-specific In Circuit Debugger/In Circuit Emulator.

Example:
AVR Dragon for AVR chips (Arduino UNO, Nano, Mini, MiniPro)

BUS Pirate

Primarily for development purposes.
Can both sniff the bus and drive it.
Console interface over serial (ttyACM) port, including macros, or programmatic access for several programming languages.
Built-in pullup resistors and voltage sources (5V / 3.3V)
Supports many other protocols.
References: Wikipedia, main page

USB to I2C Adapter

Small footprint.
Suitable for permanent installations.
No need for special connections on the host: it can be used to interface with a typical PC.
Variant available that is also SPI-capable.
No console interface, only serial binary protocol.
Requires protocol wrapper.
Reference: protocol

sigrok and pulseview

sigrok(bakend component) logo

pulseview (visualizer) example

Example of low end logic Analyzer

De-facto standard for PC-driven measurements on linux (but available on other OSes too).
Support for vast range of logic analyzers, scopes and meters.
Various protocol decoders, including I2C.
Useful for visualizing the logical signals and debugging protocol errors.
Even very low end, inexpensive HW can provide a whole new dimension to debugging.
References: sigrok, pulseview, supported hardware

Example: steering a 4WD drone

Prototype built using 2 Arduino Mini Pro.

What does the slave do in the example?

The I2C slave:

Controls the amount of torque applied to each wheel.
Controls the direction each wheel spins.
Measures  the rotation speed of each wheel through an optical encoder (Odometer).
Exposes the parameters above to the I2C Master.

High level block diagram of the I2C Slave.

Selecting the Slave: Arduino Mini Pro

Enough pins/functions to provide for each wheel:

1 PWM output with independent configuration of the duty-cycle.
1 GPIO for registering odometer input as IRQ.
2 GPIOs for selecting:

Forward
Reverse
Idle
Lock

I2C HW block for interrupt-driven i2c exchanges.
Dedicated pins for SPI-based programming.
Small footprint.
Low Cost.
The board layout of the clone represented in the picture is optimized for mounting on a DIL socket.

Slave-specific ICD: AVR Dragon

Supports various programming modes, included SPI programming, through AVRDude.
Doesn’t interfere with normal AVR operations, so it can be left plugged into the system.
After enabling debugWire interface, it allows configuring HW/SW breakpoints, by a dedicated backend for gdb/ddd.

Selecting the OS: ChibiOS

RTOS: preemption, tasks, semaphores, dynamic system tic, etc.
Small footprint: link only used code/data.
Distinction between RTOS and BSP through HAL.
GPLv3 for non-commercial use.
Actively developed, but already mature.
Supports 8bit AVR.

However it had limited BSP support for AVR, lack of:
 - interrupts driver for AVR GPIOs (added).
 - I2C support for AVR slave mode (custom).
Which had to be developed separately as part of the Drone SW for the AVR.

Defining the Communication Parameters

For each wheel:

Duty Cycle of the PWM signal used to drive it - 1 byte.
0xFF = max torque / 0x00 = no torque.
Direction of rotation - 1 byte.

0x00 = idle
0x01 = reverse
0x02 = forward
0x03 = locked

Average period in between slots of the optical encoder - 2 bytes.

Writing anything resets the measurement.

Parameter Index - 1 nibble:

0 = Duty Cycle
1 = Direction
2 = Average Period

Wheel indexes - 1 nibble:

0 = Left Rear
1 = Right Rear
2 = Right Front
3 = Left Front
4 = All

Sub Protocol: Defining the Registers

Register format:   0xαβ
 - α = Parameter Index
 - β = Wheel Index

Address (chosen arbitrarily): 0x10

Bus Pirate format:
 - [ = start bit
 - ] = end bit
 - r = read byte
 - address times 2 (left shift 1), for R/W bit

Example - in Bus Pirate Format

[   i2c_addr   reg_addr=(parm,wheel)   reg_value  ]

[0x20 0x20 0x02]  Left Rear Forward
[0x20 0x21 0x01]  Right Rear Backward
[0x20 0x22 0x01]  Right Front Backward
[0x20 0x23 0x02]  Left Front Forward
[0x20 0x14 0xFF]  Wheels set to max torque

The car spins clockwise.


This is functional. I would do more by making a function to be called with the time and state information. It would reduce the number of if statements. But this is simple to understand. I started with Blink without delay.

I did two relays. For the others, copy and paste, then change the relay numbers and times.

/*
  Blink without Delay
  http://www.arduino.cc/en/Tutorial/BlinkWithoutDelay
*/

const int On =  1;
const int Off =  0;

// constants won't change. Used here to set a pin number:
const int ledPin =  LED_BUILTIN;// the number of the LED pin
const int relay1 =  5;
const int relay2 =  6;

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

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

int    secondCount = 0;

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

#define onTime  2           //relay on time

#define relay1_on1 0
#define relay1_on2 (relay1_on1+onTime+1250)

#define relay2_on1 62
#define relay2_on2 (relay2_on1+onTime+630)

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

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

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

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

    //------------------------------
    // Relay 1
    if (secondCount == relay1_on1) {
      digitalWrite(relay1, On);
    }
    if (secondCount == (relay1_on1 + 2)) {
      digitalWrite(relay1, Off);
    }

    if (secondCount == relay1_on2) {
      digitalWrite(relay1, On);
    }
    if (secondCount == (relay1_on2 + 2)) {
      digitalWrite(relay1, Off);
    }

    //------------------------------
    // Relay 2
    if (secondCount == relay2_on1) {
      digitalWrite(relay2, On);
    }
    if (secondCount == (relay2_on1 + 2)) {
      digitalWrite(relay2, Off);
    }

    if (secondCount == relay2_on2) {
      digitalWrite(relay2, On);
    }
    if (secondCount == (relay2_on2 + 2)) {
      digitalWrite(relay2, Off);
    }

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

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

    secondCount++;
    if (secondCount == 180) {
      secondCount = 0;
    }
  }

}


Unable to turn off SRAM 23LC1024 connected to Arduino

As an experiment I would make sure ALL the pins are at 0V for reset. Power on ANY pin with a return path may provide enough parasitic power to prevent a proper shutdown.

As has been pointed out you can use a I/O pin to power the device. This SRAM has 10mA operating current; enough to be supplied by an I/O pin. Then, with code only, you can make sure all pins go to 0V for the reset. This will also give you an extra power saving mode for free.


How to get a feedback that something connected to an Arduino is working?

To expand on Juraj's answers, tackle this question from the user's point of view. What does all things are working mean for them? Does the temperature you read from a sensor have to be within .2C of a reference value? The stepper has to move a thing from defined positions A to B?

Based on the answers to questions like this, which is sort of a black-box testing approach, think about how to obtain reference values, then write tests in your Arduino to check if they are met. You might have to move your system into a defined testing stage first, like move the steppers to a defined starting point, then go test.


The VIN pin on the NodeMCU board can take the 5V directly. Had no problem with that way until now.

What is strange to me is that the current from your 5V to 3V regulator  is degrading. The regulator on the board it's self is basically the same (maybe another manufacturer). What may be the cause is that the regulator is overheating and somehow that the effects the output current and/or voltage.

What you can also try is a LM2596 step down regulator.
Those are pretty cheap as well and have a good output capacitance. They can deliver up to 3A at down to ~1.3V. Input voltage is somewhere between 40V and your output voltage plus 1 or 2 volts to let it properly regulate.
You can use that module to transform your 5V down to 3.3V easily - i've done it so often with it, i lost count.


EthernetClient not initializing properly

An EthernetClient expects to connect to a remote socket. At no point do you instruct it to connect to a socket, so it never succeeds.

At some point before checking for a connection you need to initiate that connection:

// arduino.cc is 100.24.172.113
IPAddress server(100, 24, 172, 113);
client.connect(server, 80);

The if (client) operation relies on sockindex having been assigned a valid value, and that is only ever done either by EthernetClient::connect() or by being explicitly set by EthernetServer::available().


Can Serial be safely used in an SPI interrupt routine

Serial should be avoided in ISRs because interrupts are disabled inside ISRs, and Serial transmission uses interrupts to operate. Better to have the ISR set a flag that is read in the next iteration of loop() to print the desired info.


I feel like an idiot, why can't I make a servo move with the boilerplate code?

The only thing I see that could be the problem is with your servo wiring. It seems that most servos use this kind of wiring  Which is the way that you seem to wire it, but depending on how Radioshack servos are made the signal wire could correspond with a different wire. I imagine this could possibly be on the packaging so I would start by looking there to confirm your wiring.


So that you can terminate the output prematurely, e.g. during an interrupt.


Is my idea sensible and achievable (technically)?

Yep, sure is. It's not really much different to a DIY Reflow Toaster Oven.

  I know that I will need a 240V relay to control the heater. Is this safe and reliable? ** This is my biggest concern. What can you recommend for this - there are so many available on the market.

I would suggest an SSR instead of a mechanical relay. Easier to drive, and less electrical noise.

  I think I will also need 3 more additional relays for the 2no fans and LED strip light. Is this the best way to control the 12V fans and LED light?

No. Use MOSFETs for those. You can drive those with PWM to change the speed / brightness.

  Can I control the speed of the proposed 12V fans? And how is this achieved?

Yes - see above.

As far as control goes you may want to investigate PID as your calculation method.


I looked up the datasheet and product specs for the GPS device. It says that the output is RS-232.
Note that RS-232 is NOT compatible with the Arduino levels. Arduino "talks and listens" at 5V or 3.3V depending on which board you're using.
So what you need is a RS-232-to-TTL converter. Now, TTL speaks Arduino. So Arduino will be able to understand that. So try using a MAX232 IC or a shield, whichever you're comfortable with.


Majenko's answer is the right answer for your question. But to answer the title of the question, if you ever need to use different Arduino outputs and inputs as variable, most of them have common type Stream or Print. So it would be:
Stream& SensorSerial = Serial;

or
Stream* SensorSerial;
SensorSerial = &Serial;

The Arduino Stream classes hierachy:


Vin is a power INPUT. It is connected to the input of the voltage regulator, which enables you to power the Arduino with voltages between 6V and 12V, while the Arduino itself is running on 5V.

The 5V pin can be both an power INPUT and OUTPUT. It is connected to the general 5V power rail inside the Arduino and thus to the power inputs of the microcontroller. This rail/pin needs to be provided with 5V power to let the Arduino work. Where this power comes from (from the voltage regulator, from USB or from your own external 5V power supply connected to the 5V pin) is irrelevant for the Arduino. The 5V pin can even be used to provide power to other components in your circuit (though with certain limitations, see below).

The 3V3 (meaning 3.3V) pin is a power OUTPUT. It is connected to the output of another voltage regulator, which brings the 5V from the 5V rail down to 3.3V. It can be used to power external parts, that need 3.3V to work.

Up to this point I only wrote about voltage. But depending on your circuit you also need to consider the current. The different electrical parts on the Arduino can only handle a specific power (measured in Watts). Thus with a given voltage you can only draw up to a specific amount of current through them, before you destroy them.

As an example, let's assume you provide the Arduino with 9V through Vin and you want to drive a middle sized motor. Motors in general can draw a lot of current. When you now drive the motor from the 5V pin of the Arduino, the motors current will flow through the Arduinos voltage regulator. Thus the regulator will go into emergency shutdown and cut the power (applies for a genuine Arduino) or it will get destroyed (applies for most cheap Arduino clones). To prevent that, you need to connect the motor directly with the power supply (or through an extra voltage regulator, suitable for the needed current), so that the current for it is no longer flowing through the Arduino.

This explanation is only to prevent you from destroying your board. That is always very annoying, when it happens.


Repeatedly checking multiple "if" statements

I am going to assume you don't want to include cm == 6 which is why you have both cases. I would consider using a while loop instead of a singular 'if' statement in order to continuously check if those buttons are being pressed or not (while (cm<6){do this stuff}). Otherwise, it will check once and never check again.

Instead it will jump down to the next 'if' statement, it will fail and then jump to the top of the loop where it will check for the code 0xFF807F. Let me know how it goes!


Reset Button not working + Can't Upload code , What is wrong?

Try manually resetting the board:

Before uploading, run Verify.
Hold the reset button and click Upload.
Release the reset button.

If that worked, your board's reset isn't fried, it just isn't receiving a reset via the serial cable. If it failed, either part of the board or MCU may be damaged; something attached to the board may be inhibiting the reset signal; or the software may have disabled the board's reset pin. In the latter case, see the Arduino StackExchange article, How do I repurpose Arduino's reset button, for how this can happen and how to undo it if it has.

  Is here anything wrong with using pins 12 and 13?

I'm not familiar with stepper driver, but at a quick glance at its data sheet, and it's logic being 3.3v & 5 v compatible, I don't see any problem with connecting any of its logic to any of Arduino's logic pins (almost all of them). Since the driver also has a motor drive-voltage input for driving your motors, accidentally connecting an Arduino pin to a driver pin (or anything else) carrying the drive-voltage could - probably would - damage at least the connected pin driver in the MCU, and possibly other parts of it as well.

If your Arduino has a socketed Atmega chip, and since you already know another Arduino works as you expect it to, replacing the Atmega chip will be the quickest, cheapest & easiest fix. Just go over your wiring and make sure no motor drive voltages are connected to the Arduino board.


Microphone Data on Arduino to Wav File on RaspPi

Why use the arduino, when you can use the Pi directly? I would get a high quality ADC, connect the mic to it, and then make the Pi write the value from the ADC directly to file. The arduino simply isn't fast enough for good quality audio recording - the ADC is 10-bit, 9.6 khz. At best you could get a stereo 8-bit 8khz wav file. With a good ADC on the Pi, you would be able to go up to stereo, 16-bit(maybe even 24-bit), 44.1 khz. Also, the Arduino would be massively slowed down by sending the data, so the actual sample rate would be much lower.


So, according to the comments the main problem should be a thermal protection in LM7809C regulator.

The voltage drop between regulator's input and output is about 15 Volts and even with current consumption about 150mA it means 2.25W of power dissipation on it.

For such a big difference between input and output voltage switching regulator is recommended. (Or 9V power supply instead of 24V)

And it is not possible to have 2mA current consumption. I've just measured power consumption of bare Arduino Mega 2560 and it is 81mA through barrel jack input (9V) without anything on it. Not even blinking Led. So if you've measured for example 0.2A it's not 2mA but 200mA


Atmega 328p at 3.3v : Internal vs external oscillator

If the 8 MHz oscillator is off by a handful of percentage points, it will affect timing measurements you make using millis() and micros(). It could affect the baud-rates of Serial or SoftwareSerial. If these are not of any concern, the only remaining difference would be how fast your code can be executed. It's unlikely that the code pushes the chip runs so close to its maximum capability that it would matter, even at ~8 MHz.
Update:

... I just want to know if clock frequency effects the code and if I need
to change code a bit like for example blink sketch runs at different
time intervals on 8mhz and 16mhz(I tested it).

If you do nothing else, then yes, millis() will appear to run at half speed. You need to add a board definition to the IDE for an Arduino Uno running at 8 MHz. Then millis() and micros will be adjusted for the slower processor clock. How you do this depends on whether you choose the internal and less accurate 8 Mhz oscillator, or an external 16 MHz crystal.
For the internal oscillator, there is a board-definition on Github with instructions to load it into your IDE.
For an external oscillator, this article describes how to select the board type as "Arduino Pro or Pro Mini" and then be able to select the board frequency, using the Tools menu twice.


One approach would be use of a DS3231 (Precision Real Time Clock) module.  Such modules sell on Ebay for under $1.  Search for ds3231 arduino.

Typically, these modules have a six-pin connector, with pins labeled 32K, SQW, SCL, SDA, VCC, and GND.  As noted in DS3231 specs, the INT/SQW pin is used either for square-wave output or for interrupt output.  On page 13 of specs, in the Control Register section, it says:

  Bit 2: Interrupt Control (INTCN). This bit controls the INT/SQW signal. When the INTCN bit is set to logic 0, a square wave is output on the INT/SQW pin. When the INTCN bit is set to logic 1, then a match between the time-keeping registers and either of the alarm registers activates the INT/SQW output (if the alarm is also enabled).

Initially, you would run a sketch to set up the DS3231: turn on a daily alarm, enable an interrupt rather than square wave, set the current time, etc.  Then, load an operational program that reads car-battery voltage each time it runs, and acts appropriately.

The DS3231 INT/SQW pin would be wired to the gate of a P-channel mosfet that switches 12V power to the Arduino.  The P-fet would turn on when the alarm's open-drain output pin INT/SQW turns on.  The operational program does its business and then clears the DS3231 interrupt flag, to shut down power until the next alarm occurs.  (For debugging, set briefer intervals than a day; for example, once a minute, as described in Table 2, Alarm Mask Bits, on page 12 of specs.)

Typically, the DS3231 draws 0.84 μA when running from a 3.3V battery, or 1 μA from 5V.  See Electrical Characteristics, page 3 of specs.


difference between output pin high and 5v pin

That's probably caused by the motor's current consumption. The 5V pin can deliver much more current than the output pin in high state. If you want to switch the motor on/off by software, you need a "hardware driver" for the motor, in the simplest case a power transistor.


Why do I get “ stray '#' in program ” error?

Use the escape backslash to get a double quote in a text. See: https://en.cppreference.com/w/cpp/language/escape

Is the *123$ between double quotes?

Serial.println("Hello");
Serial.println("I said: Hello to you");
Serial.println("I said: \"Hello\" to you");
Serial.println("AT+CUSD=1,\"*123#\"\r");
Serial.println("AT+CUSD=1,\"*123#\"");

I think the carriage return \r at the end is not needed when the println is used. The println adds a linefeed \n by the way.


Can't use Arduino nano as ISP because it can't read the Device signature

It seems that you are using too high programming speed. SCK period al of 0.1 us renders 10 MHz, which is to fast if crystal is working at 8 MHz. Not sure where to change it in Arduino environment, but you should add this key to avrdude.exe run string:

avrdude.exe -B 8

This will set programming speed to 125 kHz. Also I suggest you to buy a cheap USBasp programmer from eBay or AliExpress. It is well documented and have plenty GUI programs, running on top of the avrdude. In newest Arduino IDE you can generate hex files in the sketch directory, and burn it with programmer.


Wouldn't this be simpler?

Note: amended answer increases R1 to 10 k.

The 10 k resistor limits current to 0.17 mA. The 3.3 V zener diode clamps the input voltage to 3.3 V (I measured 2.3 V on mine so that is well within spec). The other end of the zener diode goes to the Arduino ground pin.

I originally had R1 as 1 k however if you had a high voltage input (like 20 V) it didn't quite clamp the pin to 3.3 V (more like 3.8 V). This is a bit high for an input pin, so I tried 10 k instead.

This gives:

For an input voltage of 5 V -> 2.3 V on the Arduino input
For an input voltage of 10 V -> 2.6 V on the Arduino input
For an input voltage of 20 V -> 2.9 V on the Arduino input
For an input voltage of 30 V -> 3.1 V on the Arduino input

This is all within spec for the Arduino.

Now the question is, will 2.3 V on the input pin register as HIGH? The answer is "yes" because high is considered to be 0.6 * VCC.

3.3 * 0.6 = 1.98

Thus any voltage of 1.98 or above is considered HIGH, and it will successfully read 2.3 V as high.


Getting more current through an LED array

The current a bipolar transistor configured as a common emitter amplifier will allow from its collector to its emitter is equal to its beta time the base to emitter current.

A beta of 100 is common for many transistors. Assuming this information is close enough to your transistor, we can choose a base series resistance suitable for the collector to emitter current desired.

For example if you were using a 5 volt microprocessor and the voltage drop across the base to emitter was the usual 0.7 volts for silicon semiconductors and you had a base series resistor of 10Kohms:

V = I * R
V = 5 - 0.7 = 4.3 volts
R = 10000 ohms
I = 4.3/10000 = 0.43mA
I(ce) = Beta * 0.43mA
I(ce) = 100 * 0.43mA = 43mA

You could pass up to 43mA from the collector to the emitter.  If that is not enough,you can lowered the base resistor to 1Kohms:

R = 1000 ohms
I = 4.3/1000 = 4.3mA
I(ce) = Beta * 4.3mA
I(ce) = 100 * 4.3mA = 430mA

And increase the current to 430mA.  You still need to verify that the processor can supply the current to control the transistor (4.3mA as calculated above) as well as pick a transistor of sufficient capacity to handle the load.

If a beta of about 100 is not enough, consider using a Darlington transistor arrangement. This type of "2 transistor" device has a gain of the product of each individual transistor's beta.  So, it is common for such a device to have a beta of 10000!  Using this device, you can use a much larger base resistor and still be able to switch more current.


I am assuming millis() is a Timer ISR function.

It is a function that retrieves a value that is updated by and ISR.

What would happen if the ISR asynchronously changes the value being
read in a function.

Cannot happen: the value is read with interrupts disabled.
See for example, in the AVR core:
// disable interrupts while we read timer0_millis or we might get an
// inconsistent value (e.g. in the middle of a write to timer0_millis)
cli();
m = timer0_millis;
SREG = oldSREG;

I mean if I have read one byte into currentMillis, but millis had
changed the value before the remaining 7 bytes are read.

An unsigned long is only 4 bytes. That is, until someone comes with a
64-bit Arduino platform.


Controlling 16x2 LCD backlight (I2C module)

It's hard to tell from the limited information, but chances are the "backlight jumper" mentioned in passing in the datasheet can be simply removed.  This will then give you two pins.  One will connect to pin 3 of the IO expander, and the other will connect to the back light anode itself.

Which is which you will have to discover for yourself.  One of them will have the 100Ω resistor in line with it as well.

If you can't see the tracks (some black boards are hard to make them out) then you should get a digital multimeter and set it to continuity mode and probe the pins to see where they lead.

Once you have identified which pin is which you can connect the one that goes to the back light to your Arduino and drive it with PWM.


Did you follow the setup exactly? In particular, did you modify main.cpp to have this:

#if defined(BLEND_MICRO_8MHZ)
    // As the F_CPU = 8000000UL, the USB core make the PLLCSR = 0x02
    // But the external xtal is 16000000Hz, so correct it here.
    PLLCSR |= 0x10;             // Need 16 MHz xtal
    while (!(PLLCSR & (1<<PLOCK)));     // wait for lock pll
#elif defined(BLEND_MICRO_16MHZ)
    // The CPU clock in bootloader is 8MHz, change to 16MHz for sketches to run (i.e. overclock running at 3.3v).
    CLKPR = 0x80;
    CLKPR = 0;
#endif

If not, what happens is once the sketch starts the USB stops working and you can't see the serial port due to the clock speed being incorrect. This is why you can only see /dev/tty.Bluetooth-Serial-1 in the port list.

Modify main.cpp according to http://redbearlab.com/getting-started-blendmicro
Press the reset button on the Blend Micro, then quickly select Tools -> Serial Port in the Arduino IDE. The Blend Micro serial port should be there because the boot loader is still running. It will be named like /dev/tty.usb????????
Select that serial port. Compile your code. Now press reset at the same time as pressing upload. Your sketch will upload and the serial port should now be present when the sketch is running.

Update: The Timing Tricks

Note: Blend Micro is basically the same as Arduino Leonardo.

This is the timing:

The reset button is pressed.
The ATMega32u4 restarts. It jumps to the bootstrap loader code.
The bootstrap loader starts up the USB as a CDC device (serial port) and waits for firmware upload instructions. (Pulsing L LED)
If no upload instructions are received within a certain time (8 seconds?), it jumps to the application code.
The application code starts up the USB as a CDC device again.However, since the oscillator (clock) on the Blend Micro is different to the Leonardo, it requires the modifications above, otherwise the USB clock will wrong, and the USB won't work.

If the modifications above were not done, Step 3 is the only time when the USB is working and the serial port can be selected in the Arduino software.


How many LED Strips can we connect to an Arduino Uno? Is there a way to connect 1-3 meters worth without needing extra parts (relays)?

Yes, the current draw is the main factor here.  That's not really an Arduino issue though, as I will enlighten you about later on when I talk power supplies.

I assume, since you don't mention what the LEDs are, that you are talking about strips of WS2812 "NeoPixel" LEDs (the ones where you can control the colour of each and every individual LED).

I would recommend keeping all the LEDs as one single strip.  That doesn't mean you can cut the strip into segments, just join the ends to each other using wire in one chain.  That way you just have one chain to deal with in the Arduino.  Running multiple chains can be somewhat more resource hungry and I'm not even sure it's possible on an Arduino.  So keep it all as one long chain split into chunks and re-joined with wire.

Now for power.  Your computer has a big powerful power supply in it.  That gives a very good regulated 5V supply with many many amps available.  More than enough to run hundreds of LEDs.  By all means run the Arduino from USB (makes for easy programming - inspect your motherboard, it may well have an internal USB connector that would be ideal (I know mine has).  And then run the LEDs themselves off the +5V direct from the computer's power supply.  A spare hard drive power connector could be good for that.


Can I use this replacement motor without modifying the circuit?

Regarding voltage, I think there should be no problem as the datasheet for your replacement motor specifies a "suggested voltage 4.5V DC".

However, be careful that there is another important value in motor datasheets: the stall current.

Simply stated, this is the current consumed by the motor when it tries to rotate but is unable to, due to its too low torque in comparison with the effort needed for rotation, e.g. if it tries to rotate the wheel of a robot that is too heavy.

The original motor has a stall current of 0.8A according to its datasheet (you can get it from the link you provided).

Your replacement motor has 1A according to the link you provided.

These 200mA can make a big difference for the transistor used in your circuit, a P2N2222A.

Indeed, that transistor is specified to switch a maximum of 600mA current at the collector.

So in the best case, the motor will run correctly without load, but if you provide some load that makes it stall, then the transistor will raise temperature (you could sense that by approaching your finger) and ultimately would get toasted.

Please also note that some poorly designed motors may consume a current near the stall current, due to internal friction (I have already almost grilled a transistor this way...)

So my answer is:

you can do it for a simple experiment with no load on the motor
if you really want to do something with the motor, take another transistor with a higher Ic current


I2c device disappear from bus after writing

By default the FAST register is set to 0 at power up.
When the FAST mode is 0 and you set LOW to 0 you are entering Power Down mode.

Looking at your code it looks like you are not altering the FAST register which means I can simplify your question to "Why does my device disappear from the I2C bus every time I turn it off".

Just looking at page 34 of the English User Manual I would say you have to set FAST to 1 before setting LOW to 0.

Also - Do you have pull-up resistors on the I2C bus?  You might encounter problems without them.  They are normally around 4.7K for 5V, but I don't know what they should be for 3.3v systems.


Is it unable to operate two operations simultaneously?

The only way you can do two operations simultaneously is to have two Arduinos. An Arduino can only do one thing at a time. In order to make it seem like it's doing things at once you have to create your sketch accordingly. The use of delay() is right out. As are long loops using things like while(). In short: anything that blocks is bad.

  Can we use these two sentences in one code?

Not reliably, no.  They are both resource hungry and, to a large extent, blocking. A general rule is, if you need at least two more UARTs than the board provides then you need a different board. You can only reliably work with one software UART at a time.

I would suggest upgrading to a more capable board with more hardware UARTs. Either that or use a bluetooth system that doesn't use UART, such as an SPI based BLE module.


Can I use this cheap GPS module with arduino

Yes.  You can tell that from two entries in the specification:

  TTL Level 9600 Baud Rate

That tells you it uses standard TTL (5V) serial to communicate, so on an Uno that would be pins 0 and 1 and the Serial object, or any pins of your choice and the SoftwareSerial library.

  Output SiRF binary system OR nmea0183 V3.0(GGA, GSA, GSV, RMC, VTG)

It outputs NMEA encoded data (bold added by me) which is what most of the Arduino GPS libraries are written to use.


MD_Parola display issue when constructing test

The library documentation states:

The library does not allocate any memory for the text message

That suggests, that the buffer has to be valid beyond the execution of the displayText() function. But as you declare it inside of your updateTime() function, it the buffer gets out of scope, when exiting that function. The memory space can then be reused by the rest of the program. At that point the library will still have the pointer to the old location, though that pointer can now be considered invalid. Thus you are just reading, what the compiler decided to place in that memory location.
To solve that, you need to keep the buffer variable in scope. You can do this by moving the declaration to the global scope.


Interface a mobile phone's finger print scanner with arduino

In general: It depends. We can only talk about the general situation, not about details, because we don't know the exact sensor type. You are facing some serious problems when doing this.

Without a part number or something like this, we cannot say, how the sensor communicates with the phones mainboard. It might or might not be a communication interface, that the Arduino has or can be made capable of.
The sensor and it's interface might be proprietary, which would mean, that there is no public documentation about the interface and how it works. Reverse Engineering something like this need mostly a big amount of time and experience with various electronical systems.
As Shyam Singla already pointed out in his/her answer, most (if not all) Arduino compatible fingerprint sensors don't send the actual fingerprint image, but do the difficult image handling and recognition by themselves. The Arduino only get's status information (for example if a previously saved fingerprint was detected). On a phone, this is most likely not the case. The main processor of the phone has way enough power to do the calculation by itself. It doesn't need to offload them to an external chip like the Arduino needs to. (Also this gives the vendor the opportunity to update the recognition software later on with a simple OS update.) That means, that the sensor will most likely only send images and you would need to do the image handling and recognition on the Arduino. AVR based Arduinos (like the Uno or Nano) are totally undersized for this.
The connection pins of the sensor will be very small and difficult to connect, especially if you are a beginner.
You would have to use level shifters and voltage regulators to interface between the 5V devices Uno/Nano and the sensor, which will most likely work with a significantly lower voltage (at max 3.3V, most likely less).

Using FPGAs to tackle some of these problems is possible, but also very challening. If you need to ask this question, this is most likely out of scope. (A friend of mine did program a FPGA for his physics master on university. It can be very difficult.)

All in all I would say, it is not worth the effort to even try this. Instead buy an Arduino compatible fingerprint sensor.


Volatile variable not updating from timer ISR

You want CTC mode for that to work. As in:

#include <avr/io.h>
#include <avr/interrupt.h>

volatile uint8_t count;

void init_100us_tick(void) {
    TCCR0A = _BV(WGM01);       // CTC mode 2 with OCRA as top
    TCCR0B = _BV(CS01);        // CLK / 8 prescaler
    TIMSK0 = _BV(OCIE0B) | _BV(TOIE0);      // Interrupt enabled on OCR0B
    OCR0A = 200;                            // 16 MHz / 8 / 200 = 100 us
    sei();                                  // Enable interrupts
}

ISR(TIMER0_COMPB_vect) {
    count++;
}

int main(void) {
    DDRB |= _BV(DDB5);                      // PB5 output
    init_100us_tick();                      // Initialise 100 us tick
    count = 0;                              // In case of micro reset

    for (;;) {
        if (count >= 100) {                 // Every 10 ms
            count = 0;
            PORTB ^= _BV(PORTB5);             // Toggle PB5
        }
   }
   return 0;
}

That toggles every 10 ms.

(Edited to add)

The PWM mode you chose will work providing you enable the correct interrupt. This also outputs 10 ms pulses:

#include <avr/io.h>
#include <avr/interrupt.h>

volatile uint8_t count;

void init_100us_tick(void) {
    TCCR0A = _BV(WGM01) | _BV(WGM00);       // Fast PWM mode 7 with OCRA as top
    TCCR0B = _BV(WGM02) | _BV(CS01);        // CLK / 8 prescaler
    TIMSK0 = _BV(OCIE0A);                   // Interrupt enabled on OCR0A  ***
    OCR0A = 200;                            // 16 MHz / 8 / 200 = 100 us
    sei();                                  // Enable interrupts
}

ISR(TIMER0_COMPA_vect) {                    // Compare A vector ***
    count++;
}

int main(void) {
    DDRB |= _BV(DDB5);                      // PB5 output
    init_100us_tick();                      // Initialise 100 us tick
    count = 0;                              // In case of micro reset

    for (;;) {
        if (count >= 100) {                 // Every 10 ms
            count = 0;
            PORTB ^= _BV(PORTB5);           // Toggle PB5  ***
        }
   }
   return 0;
}

Changed lines indicated by ***

Note that you should not have enabled _BV(TOIE0) because you have no interrupt handler for Timer 0 overflow. Without an interrupt handler the compiler probably generated code to jump to the reset vector.

The interrupt occurs when the timer matches the Compare A amount (not Compare B) so you need an interrupt on the A side.


can i use L298N H bridge with 12v 7AH battery?

Yes, though at 2A you're at the top end of the L298N current limit. Expect excessive heating. You will have to manage your thermal environment appropriately.
You should consider a more capable driver with more current headroom and less heat problems. (Note: the L298N is a very old chip and uses old technology. It's not a good choice for modern drive systems and a more appropriate device should be investigated, for example the MC33931 as the first hit on google).


It sounds like your 12 volt adaptor is not powerful enough to operate the lock solenoid. If you power up the solenoid only and directly using the adaptor it should work. If it doesn't, you'll need a more powerful adaptor. If it does work, then the problem is somewhere in your driver circuit or Arduino sketch.


How to compile a sketch using arduino-builder?

You need to specify the path to the tools-builder folder, which is where ctags is. Try this:

arduino-builder \
  -compile \
  -hardware /usr/share/arduino/hardware \
  -tools /usr/share/arduino/hardware/tools \
  -tools /usr/share/arduino/tools-builder \
  -libraries lib \
  -fqbn arduino:avr:uno \
  -build-path .build \
  src/main.ino


Custom board with ATMega32u4 having USB issues

As Chris Stratton pointed out, I neglected to include the 1uF capacitor on UCap. This is absolutely necessary on a 3.3v board for the board to communicate with USB properly.

Thanks!


ESP-01 not responding to serial data while programming with esptool.py

I found my problem.
esptool.py uploads the firmware at 115200 baud rate, which my logic level converter couldn't handle.  I found this out after writing this question. I thought of connecting RX and RX directly to the ESP module's RX and TX and it uploaded the program. Maybe I am wrong.  Please, if any one know why this happened I am curios to know.  Thanks in advance. ;)


4x4 matrix keypad - Multiple inputs cause extra readings

I have a post about keypad matrices which discusses this issue. The issue with keypads is, that if you don't install diodes, if three keys are pressed the current finds its way around those three keys and it looks like a fourth is pressed.

If you install diodes, like this, the issue goes away:

It can be a little tedious to do, but I managed it the other day with surface mounted diodes.

The above board is different from yours, mine is one with soft switches which I could lift off to get at the board.

Yours looks like it might be almost impossible to cut the tracks and install the diodes. Without them you can press two keys at once without issues. Perhaps that is enough. :)


What is the Maximum Current an Arduino can Supply?

40.0mA.

The Arduino UNO Digital IO pins are connected directly to the IO pins on the ATMEGA328P processor.

From page 299 of the data sheet for that processor...

Note that there is also a total current limit for all output pins combined, and that the voltage starts to drop as the current goes up.


It is done by using Source Routing

The 16-bit addresses of the hopped devices are added to the RF payload space, thus it will reduce the number of bytes that can be sent in one RF packet.


What you want might be way more complex, than you think, depending on your exact requirements.

The vibration sensor activates with any small vibration. It is not capable of distinguish different sources of the vibrations. The only pattern, that you might be able to look for with it, is a special pattern of multiple activations, as the coin jumps over the surface (depending on the max activation frequency of the sensor). Obviously this error prone.

Using a microphone to record the direct sound can give you more information about what happens. But that can get very complex very fast:

You need to measure the voltage from the microphone (which needs a suitable amplifier) with a sufficient samplerate (at least 2 times as fast as the highest frequency, that you want to measure). A high quality microphone might also need a better ADC (Analog Digital Converter), than the Arduino has build in.
The pattern recognition is another problem. Basically you have 2 ways:

You can look at the target sound signal and look for a few special properties of that signal, for which you can test the signal (for example a specific pattern of peaks above a threshold. Then you can test with some if statements for these properties, which is relatively easy. Though this is still very error prone.
You can train an AI to recognize the coin sound pattern. Though this is not a job for an Arduino, especially not for the Uno. You should use a special AI board for that. Though this is off topic here.

Which way you want to use depends on your exact requirements. When the recognition with the vibration sensor is sufficient, just use it. But we cannot say, if that is the case, because we don't know the actual pattern, that you want to recognize, nor do we know your exact requirements. You will need to test that yourself.


Why is my real time clock getting the wrong time from my PC?

The __DATE__ and __TIME__ are set when the code is compiling so they will naturally be behind since the code still needs to finish compiling and then be flashed to the chip.

See the Arduino Playground for an example of how to sync it to your computer over serial.

  TimeSerial.pde shows Arduino as a clock without external hardware.

  It is synchronized by time messages sent over the serial port.   A
  companion Processing sketch will automatically provide these messages
  if it is running and connected to the Arduino serial port.


The DO pin gives a Digital Output that is HIGH when the light falling on the LDR is above a threshold, and LOW when it's below a threshold. Just connect it to a digital input pin and read that pin with digitalRead().

You can change the threshold by adjusting the small blue trimpot.


Using esp-wroom-32 without a development board

There are programming boards available to which you can plug one of these SOCs into them. There are different boards for different types of ESP SOCs.
You can find them at popular Chinese vendors, and probably elsewhere too.
They look like this:


Library for working with a 4-digit 7-segment indicator SH5461AS

This one  tm1637 sounds good. I was thinking to use it next time.
Edit 1:
Lately posted image suggests that it is without a separate display controller chip, then this library should work.
Edit 2:
This library specific to the SH5461AS display: Library
Include these three libraries:
#include "Segment.h"
#include "Digit.h"
#include "Display.h"

Print needs to be in the loop:
void loop() {
  d.print("1.234"); // Must be looped!
}

For disabling decimal points:
#define DISABLE_DP

The library's Github has very good documentation too


Cisco Switch not receiving serial communication from Arduino

Assuming this is a flow control problem:

  Is there such a thing as inb vs oob for a serial console connection?
  This isn't on the internal network of the switch in any way but the
  console port

It assumed this is a managed switch and the traffic on the console port has nothing to do with the traffic going through the switch. Rather this is likely a port to the computer inside the switch.  Such a port might be able to use RTS/CTS/DSR or X-on / and X-off.

If this is a flow control problem, consider first looking for thumb switches on the back of the switch to see if the method used for flow control over the console port can be selected. If that is not possible, consider simply hardwiring the out of band flow control pins to always allow for data to flow.  At 9600 baud, a dedicated Aruidno should be able to keep up.

Refer to the 9 pin connector in this chart to find the out of band flow control pins.


When a pushbutton and sensor are in a certain state, do something for a certain period of time (15 seconds)

Here below is modified code based on your requirement. There are some changes in your code and I also comment it out. I hope it will help you.

/*
 6 Flashing LED Lights With A Pushbutton and FSR Sensor
*/

const int buttonPin = 8;

const int LedPin1 = 7;
const int LedPin2 = 6;
const int LedPin3 = 5;
const int LedPin4 = 4;
const int LedPin5 = 3;
const int LedPin6 = 2;

const int kDelay = 1000; // Take one varible "kDelay" and value = 1000

int buttonState = 0;
int SensorPin = A0;
int SensorPinReading;

void setup()
{
  Serial.begin(9600);
  pinMode(LedPin1, OUTPUT);
  pinMode(LedPin2, OUTPUT);
  pinMode(LedPin3, OUTPUT);
  pinMode(LedPin4, OUTPUT);
  pinMode(LedPin5, OUTPUT);
  pinMode(LedPin6, OUTPUT);

  pinMode(buttonPin,INPUT_PULLUP); // Provide PULLUP
  pinMode(SensorPin, INPUT);
}

void loop()
{
  SensorPinReading = analogRead(SensorPin);
  Serial.print("Analog reading = ");
  Serial.print(SensorPinReading);

  if(SensorPinReading < 10)
  {
    Serial.println(" - No Pressure");
  }
  else if (SensorPinReading < 200)
  {
    Serial.println(" - Light Touch");
  }
  else if (SensorPinReading < 500)
  {
    Serial.println(" - Light Squeeze");
  }
  else if (SensorPinReading < 800)
  {
    Serial.println(" - Medium Squeeze");
  }
  else
  {
    Serial.println(" - Big Squeeze");
  }

  buttonState = digitalRead(buttonPin);

  if(buttonState == HIGH && SensorPinReading > 10)
  {
    digitalWrite(LedPin1, HIGH);
    digitalWrite(LedPin2, HIGH);
    digitalWrite(LedPin3, HIGH);
    digitalWrite(LedPin4, HIGH);
    digitalWrite(LedPin5, HIGH);
    digitalWrite(LedPin6, HIGH);
    delay(15 * kDelay);            // You need 15 Sec, multiply kDelay with 15
    digitalWrite(LedPin1, LOW);
    digitalWrite(LedPin2, LOW);
    digitalWrite(LedPin3, LOW);
    digitalWrite(LedPin4, LOW);
    digitalWrite(LedPin5, LOW);
    digitalWrite(LedPin6, LOW);
  }
  else
  {
    digitalWrite(LedPin1, LOW);
    digitalWrite(LedPin2, LOW);
    digitalWrite(LedPin3, LOW);
    digitalWrite(LedPin4, LOW);
    digitalWrite(LedPin5, LOW);
    digitalWrite(LedPin6, LOW);
  }
}


You can't use that TFT screen with SPI. The SPI interface (SD_DI, SD_DO, SC_SCK and SD_SS) is for the SD card slot only.

All the pins starting LCD_ are the 8-bit parallel ("8080" style) interface for controlling the TFT screen.


I think the problem is that you only trigger the interrupt when the button is pressed (interrupt FALLING)

Therefore, there is no opportunity to call debounce when the button is released.

Therefore, there is no way to change the button state variable back to HIGH (I.e. when the button is released).

To verify the hypothesis or gain some other insights, I suggest trying to put a debug statement in your loop similar to the following

  If (millis () >= debugTime) {
       DebugTime = millis() + 1000:   // output every second...
       Serial.print("value of button state is: ");
        Serial.println(button_state);
      // and a few other variables.
  }

I will leave it to you to properly declare debugTime (unsigned long) and choose a few other key variables (maybe interrupt flag) to print in the debug message block.

And i think you already have done so,  but also delete the print statements in your ISR.


Replacing Atmega8a pu 1440 arduino Ic with 1337

If you have a bootloader installed on the 8A then yes, you can.  The two chips are pin and electrically compatible.


Counter using Ultrasonic Sensor (self.arduino)

Count is a local variable - it gets re-created afresh every time the loop() runs.

Either make it global, or make it static.

These two options look like this:

Global

long count = 0;

void loop()
{
  // establish variables for duration of the ping,
  // and the distance result in inches and centimeters:
  long duration, inches, cm;

Static

void loop()
{
  // establish variables for duration of the ping,
  // and the distance result in inches and centimeters:
  long duration, inches, cm;
  static long count = 0;

Both will do the same job, but the static form is preferred since it is always better to keep a variable's scope as narrow as possible.  It is also important to provide a start value for the counter to begin from (0 in this case) otherwise the starting value will be unknown.


How to Send Live Sensor Data to iOS Custom Apps with BLE

I would expect this to be pretty straight forward. Off hand, I can't think of anything that would be a major roadblock to creating your iOS apps. It seems like there are two problems you'll need to solve:

Finding a BLE chip that is relatively easy to integrate with an Arduino, and
Selecting the tools that you'll use on the iOS side to develop your app.

Since I haven't done this my self, I started off looking on the Arduino side – mostly because it seemed like the problems there would be larger. I searched on Google using the terms:

aruduino ble

I found quite a few candidates that look promising, here are some of the better ones:

Bluefruit LE - Bluetooth Low Energy (BLE 4.0) - nRF8001 Breakout - v1.0 – I put this one on the top of my list because the price is pretty reasonable (< $20 US) and Adafruit tends to do a good job of supporting their products with tutorials and at least a basic library that demonstrates the functionality of the device.
Redbear Labs - I don't know anything about Redbear, but they do well in Google searches and appear to have several products, including a BLE shield, that might do what you want.
BLEduino - this is a Kickstarter, and while it looks interesting, a very quick investigation didn't reveal a source where you can buy one.

The choice of devices will partly depend on what your ultimate goal is. Something like the BLEduino will give you an all-in-one package to build your project around. The downside of this is that you may be spending money on functionality that you don't need/want to duplicate. A breakout board like the Bluefruit LE gives you a smaller device and possibly more flexibility at the expense a bit more work to get up and running.

Next you'll need to select development tools. I started by searching with the terms:

ble swift ios

I got a number of promising results, including:

Arduino Tutorial: Integrating Bluetooth LE and iOS with Swift
Apple: Bluetooth for Developers
Adafruit - Introduction to Bluetooth Low Energy

These first three look like good starting points for "getting your bearings," the following two are specific to actual boards.

Getting Started with the nRF8001 Bluefruit LE Breakout
RedBearLab/iOS


3pin (GND, 12V, tach) 12v FAN control using PWM

Yes, and yes.
You have to modulate the +12V rather than GND because the output is referenced to ground. That means you need to use the classic N+P channel FET arrangement:

simulate this circuit – Schematic created using CircuitLab


Understanding the variation of Arduino's current consumption with respect to the voltage supply

There is a basic error in your methodology which leads to incorrect conclusions.

You cannot determine what is going on from just two data points. Instead you need far more.

Here is a voltage sweep from 5V to 12V with a 0.05V resolution (overkill, but the default setting for the script I use) connected to a Mega:

As you can see the current steadily climes in a pretty linear fashion up to a certain point, then it flattens out.

Everything up to the point where it flattens is below the minimum input voltage for the board. During this time the voltage regulator isn't getting enough voltage, so can't regulate its output voltage to 5V. So the board is running under voltage at this point.  Once it reaches that "knee" point the voltage regulator can regulate the voltage properly - so most of the components on the board start seeing a steady 5V and their current consumption flattens out.

There are a handful of components on the high-voltage side of the regulator - most notably the voltage divider for detecting the input voltage and feeding it to the comparator that drives the P-channel FET to turn the USB power on and off - which will consume slightly more current when the voltage increases, but that is only very small amounts.

So, in short, by comparing a voltage that is below the minimum input voltage for the board with one that is above the minimum input voltage, you are comparing an invalid result with a valid result and inferring that everything in between is valid.


I have a page about connecting Arduinos using RS485. You can connect multiple devices up like this:

That has a reasonable range, 20 metres or more.

On that page I describe a Rolling-master system where each device takes turns to be the master and transmit information to the other devices. It also manages some devices not responding.

This screenshot shows the various devices "talking" during their timeslot:

In that particular case there were 3 devices active out of 4 configured.

  I have a master ardunio polling a number of sensors.

I'm assuming in my answer that you have an Arduino at each sensor point (you could use a cheap ATtiny85 or something). That would be needed to run the rolling master code.


Connecting two arduinos with wifi over the Internet

The ESPs are easy to work with and more than capable, BUT (there's always a "but"): with a public network in the middle, latency, routing, and traffic issues will be beyond your control. Look, for instance, at the variability in page load times when loading over the internet.

If you use an IoT server in the middle, there will be server delays outside your control as well, though connecting to a common server from both ends can make it much easier to get everything talking for the first time. (There may, however, be data-rate limits imposed on you if the server in the middle is a free service.)

  So can I send and receive real time data over the internet, and
  receive it fast?

Define "real fast". Do you mean "really quickly" (short delay from start of transmission to start of reception at the other end)? Or "really high throughput" (moving lots of data in a short time, or continuously without falling behind? Or something else?

Since you're working with an Uno, if you need to use a SoftwareSerial port to talk to the ESP, the SS will be limited to 9600 baud (equivalent to 960 Bytes/sec) and your ability to push data through it to somewhat under that. If you can use the built-in hardware UART your data-rate to/from an ESP can be much higher, at least 115200 baud or 11,520 B/sec (again, gross rate; rate of pushing data will be somewhat lower).

tl;dr: The network will be a much greater limitation than the ESP devices.

Update:

  the problem i see is the delay with communication over the internet
  between the two uno if i use a server.can i communicate between the
  two with out the use of a server

Of course. Using an intermediate server might be a useful step on the way to getting your devices to talk directly. It would allow you to focus on the clients themselves at first and leave (most of) the networking issues to work out later. But you'll still have the issues of any network and especially a public network. If you have no other choice, you build it and you get whatever you get for performance. How serious are the consequence of a delay or a lost packet? Inconvenience? Delayed system functions? Will it cost someone money? Could someone get hurt? Could someone die? How dire the consequences could be will determine how stringent (and expensive) your solution has to be and what backups might have to be in place.


Can I prevent the Stepper library from holding the motor?

use disable output class in  accelstepper library.
http://www.airspayce.com/mikem/arduino/AccelStepper/


How to recover an I2C bus when SDA is stuck low? Edit: SDA line stuck high

I solved the problem by replacing the pull-up resistors with 2k Ohm resistors. I thought I connected 2k Ohm resistors when in fact their value was 1k. So sometimes the SDA line couldn't be driven low due to the too strong pull-up resistors and that caused the hanging.


Can the nRF24L01+ CE and CSN pins be attached to Arduino pins A0 and A1?

Yes, you can. The mirf library is using the regular arduino functions pinMode and digitalWrite to manipulate the pins. So A0 and A1 should work as expected.

Please note that when you use SPI (which the NRF does), you have to use pin 10 (SS) as an OUTPUT (as to not put the AVR into SPI slave mode).


Is it possible to use SPI on Redbot Mainboard?

From the silkscreen on the board you appear to be either mistaken or already re-purposing signals - pins 10 and 11 are labeled as used for Servo position command PWM, not for sensor input.

Therefore, as long as you don't use those signals for servos (or ignore the labeling and use them for something else) there should be no issue using pins 11, 12, and 13 in the ordinary manner for SPI, by finding them in any available place on the board, including the 6-pin ISP connector your identify.

If you did need to use pins 11 and 12 for another purpose you could still "bit-bang" "software SPI" on any other available set of four pins.

It is also vaguely possible that you could share functions by connecting bumper switches through resistors - when the software is driving those signals as SPI outputs, it will dominate the resistors, but at other times it can re-purpose the pins as inputs to read the bumper switch state. However this may require modification of Arduino library code to accomplish repeated mode switching.


How to approach an complex Arduino Uno project (Serial, SPI, Ethernet) in pure C, without libraries?

As Hans Neve wrote, you should really refer to the docs.

This is how it works in real life, when you want to write a driver for a new piece of HW.

You have to at least understand the block diagram, programming models and register sets of the device you want to control.

Then read whatever existing code you might find. In the practical case you have the driver for the version N-1 of the HW. Or maybe for something close enough.

As generic programming advice goes:

avoid any dynamic memory allocation, you will thank yourself later on, when you do not have to debug unexplained memory issues
if you want to write a driver, consider making it reentrant, should the same code be shared across multiple IP blocks
if you want to use OOP, avoid anything that requires runtime lookup. The compiler should have enough information to resolve everything statically.

WRT debugging: both device drivers might suffer from interference if you try to use the serial port. Consider using some ICD tools, like the AVR Dragon. Alternatively, you might find that debugging over I2C is less penalizing. But you have to define your debugging messages.


Updating Array Values Incrementally Overwrites The Existing Values, Why?

You are using a char pointer (char*) instead of a char.

When you say;

response[idxUpd]  = assign;

you are assigning not the value but a pointer to that value. That points to assign for every element in response[]. Every response[] get the same pointer value, every response[] get the same value.

Use this:

#define RespLength 10
int response[] = {0,0,0,0,0,0,0,0,0,0};
int idxUpd  = 0;

void setup() {
    // put your setup code here, to run once:
    Serial.begin(115200);
    Serial.println("Start");
}

void loop() {
  // put your main code here, to run repeatedly:
    int wkt = random(10, 99);
    response[idxUpd]  = wkt;

    Serial.print("Iteration "); Serial.print(idxUpd); Serial.print(" : ");
    for (int i=0;i<RespLength;i++){
        Serial.print(response[i] );Serial.print(",");
    }
    Serial.println();
    delay(500);

    idxUpd++;
    idxUpd = idxUpd >= 10 ? 0 : idxUpd;
}

I don't understand why you are converting a int to a float. That value doesn't change, so I omitted the dtostr() call.


Your problem most likely stems from this bit:

client.println("Content-Length: ");
Serial.println("After content length");

client.println(postdata.length());

You have an extraneous "ln" in there causing the post data length to be on a separate line from the Content-Length:

Content-Length:
23

You should change the first println to a print. Also the order could do with changing to keep things logically grouped:

client.print("Content-Length: ");
client.println(postdata.length());

Serial.println("After content length");

Which would result in:

Content-Length: 23


I used an HC-05 module to do over-the-air programming for an Arduino MCU some time back, and documented the procedure in this post.  Maybe that will help?


digitalwrite with function parameter as parameter

You are sending the parameter Relay_Nb as a character, and then using it as an integer.
You need to turn the character into an integer - and the simplest way is to subtract the ASCII value of 0 from it:
Relay_Nb = payload[0] - '0';

But with that said, a note on how you have written your callback:

You aren't checking the data is valid.

You should really be doing, at the very least, the following:

Check that the length parameter is at least 2,
Check that the two data values are within the correct range for your function


you can do it in a single line:

bool isSet = (var & (1 << bitNumber)) != 0;

1 << bitNumber is a bit shift in this case it means that the 1 will be multiplied with the power of 2

& is the bitwise AND operator. The each bit of the result is 1 if and only if both the corresponding bits in the inputs is 1.


I take your code as a test sketch and will not comment on the terrible way you read Serial input.

The AT firmware requires \r\n as command ending characters. You can set them in Serial Monitor as option LN & CR, but then use print to send the command to esp8266.

Or set in Serial Monitor "No line ending" and let in sketch the println to send the command. println adds \r\n to printed string.

If you had only "New line" set in Serial Monitor and used println the resulting command was for AT firmware disturbing "AT\n\r\n".


Short answer: No.
Arduino Unos and Megas have PWM (Pulse Width Modulation) output, which rapidly turn the output on and off with a varying "duty cycle" (The ratio of on time to off time.) That is not the same thing as an analog output voltage.
If you have a constant load you can build a low pass filter that will smooth the output to a slightly dirty DC output based on the PWM output.
You're better off using an external DAC (Digital to Analog Converter.) You send that a digital value and it converts it to a clean, filtered analog output. Most modern DACs are fast enough to output complex waveforms like music.
Edit:
The Arduino zero apparently has a built-in DAC with up to 10-bit resolution. you could use that to output a low current DC voltage. However the zero is a 3.3V device.


FFT (or similar) library for the Arduino

I havent used any of the libraries to make the FFT for my personal project, due to complexity. Instead I bought a spectrum chip, which returns 7 frequencies: MSGEQ7  ( 63Hz, 160Hz, 400Hz, 1kHz, 2.5kHz, 6.25kHz and
16kHz ).

Otherwise if you are very keen on using a library, this one is very famous and fast for Arduino processors.

But again, if you dont need to have a precise band and the MSGEQ7 is good enough to detect what you want, go for it.


My two arduino nanos did flash and run the program correctly. I suspect a problem with the uno's serial communication but unwilling to troubleshoot further (i only have one uno). I decided to switch to the nano for further prototyping.


Temperature sensors TMP36 and LM35 have temperature diff. (offset) in the same circuit

The sensors have different accuracy, according to their datasheets.
The TMP36 has ±2°C typical accuracy, while the the LM35 has 0.5°C typical accuracy (over 25°C).
Read the datasheet carefully and pay attention to the characteristics, more specifically to the accuracy error graphs for each sensor. At your measured temperature (~17°C), you should expect the following error (the red line is not super accurate, but should give a general clue):

LM35:

TMP36:

In addition, as Michal stated, you might have noise in your circuit, and you are not connecting the TMP36 as per the datasheet suggests (note the capacitor between +V and Ground):


fatal error: avr\wdt.h: No such file or directory in arduino due

The Due is a very different board than the Uno. It uses a completely different architecture (ARM vs AVR). You can't use AVR-specific  code on an ARM chip, and the Watchdog code is AVR-specific.

You will have to find (or write) the equivalent ARM code using the Due's register set instead.


Digital pin input stays high after receiving a high signal

I ran across this post and thought that a more in depth explanation should be given on why when using digital inputs that more times than not you will need to use the pull-up resistors.

When you define one of the pins to be a input the chip measures the voltage on the pins, if the voltage measures more than half of the VCC voltage the input is off. What happens if you don't use a Pull-up Resistor the chip will measure a seemingly random voltage. This is because of interference from other electronics, radio waves etc.

So what happens when you use a high resistance Resistor (10 - 100 ohms) it forces the voltage to remain high if the pin is not grounded since there is voltage being applied. But when you ground the pin using a Button or whatever the pin is kept under the halfway mark around 0V.

As you mentioned using the code:

pinMode(PIN, INPUT_PULLUP);

enables the internal Pull-Up Resistors in the chip by setting the Pin to a High state like you would defining it as a output. The code above is a newer way of writing:

pinMode(PIN, INPUT);
digitalWrite(PIN, HIGH);

Now there is another reason for seemingly random input signals, which is called "Button Bounce". What happens here is when a User presses the Button there might be a very small time that the Button actually connects then disconnects then finally reconnects. This is because of when the contacts of the Switch come together sometimes they don't connect perfectly, one side of the Switch might connect then be disconnected as the connecting plate levels out before finally connecting as it should.

Below is a Snapshot I found from http://www.gammon.com.au, it shows a bounce from a Osillicope showing the actual Button Bounce:

To make sure that the user is actually pressing the button use a delay and recheck the Button again to see if it is still pressed. I find that a 500 - 700 microsecond delay works great. I provided a quick example on how to catch a Button Bounce (https://www.arduino.cc):

// constants won't change. They're used here to
// set pin numbers:
const int buttonPin = 2;    // the number of the pushbutton pin
const int ledPin = 13;      // the number of the LED pin

// Variables will change:
int ledState = HIGH;         // the current state of the output pin
int buttonState;             // the current reading from the input pin
int lastButtonState = LOW;   // the previous reading from the input pin

// the following variables are long's because the time, measured in miliseconds,
// will quickly become a bigger number than can be stored in an int.
long lastDebounceTime = 0;  // the last time the output pin was toggled
long debounceDelay = 50;    // the debounce time; increase if the output flickers

void setup() {
  pinMode(buttonPin, INPUT);
  pinMode(ledPin, OUTPUT);

  // set initial LED state
  digitalWrite(ledPin, ledState);
}

void loop() {
  // read the state of the switch into a local variable:
  int reading = digitalRead(buttonPin);

  // check to see if you just pressed the button
  // (i.e. the input went from LOW to HIGH),  and you've waited
  // long enough since the last press to ignore any noise:

  // If the switch changed, due to noise or pressing:
  if (reading != lastButtonState) {
    // reset the debouncing timer
    lastDebounceTime = millis();
  }

  if ((millis() - lastDebounceTime) > debounceDelay) {
    // whatever the reading is at, it's been there for longer
    // than the debounce delay, so take it as the actual current state:

    // if the button state has changed:
    if (reading != buttonState) {
      buttonState = reading;

      // only toggle the LED if the new button state is HIGH
      if (buttonState == HIGH) {
        ledState = !ledState;
      }
    }
  }

  // set the LED:
  digitalWrite(ledPin, ledState);

  // save the reading.  Next time through the loop,
  // it'll be the lastButtonState:
  lastButtonState = reading;
}

I hope that this explanation will help others out saving them from banging their heads against the wall trying to figure out where these phantom signals are coming from.


You can write a helper function to do it, like this:

void printRepeat (Stream & device, const char * str, unsigned int count)
  {
  while (count-- > 0)
    device.print (str);
  }   // end of printRepeat

void setup()
  {
  Serial.begin (115200);
  printRepeat (Serial, "-", 20);
  Serial.println ();
  } // end of setup

void loop()
{
  printRepeat (Serial, "Hello, World! ", 5);
  Serial.println ();
  delay (500);
} // end of loop

The function printRepeat is passed a Stream argument, which can be something like Serial, Serial1, a SoftwareSerial instance, and so on.


Sending "Blink" to pin 12 is causing on-board led to blink?

See Have I bricked my Arduino Uno? Problems with uploading to board

As I state on that page, if pin 13 is set to input the LED may turn on due to being driven by an op-amp. A nearby pin turning on may be enough to cause that effect. Try adding:

 pinMode(13, OUTPUT);
 digitalWrite (13, LOW);

See if that changes the behaviour.


Can a PC connect to an Arduino for serial communication without installing the entire dev kit?

On Windows in C:\Program Files\Arduino there is a folder called drivers, which contains all the drivers for the Arduino boards. I think that's what you are looking for.


Looking for a Mega 2650 drawing or picture that shows the components labeled

Yes, it exists, but not (commonly) as an "image" in the traditional sense.

You need to install Eagle PCB design software and open the PCB file downloadable from the Arduino site from where you can see exactly which component is where.


How to decrease delay for String concatenation + Arduino Due

I don't have Arduino Due but I have an Arduino Uno so I had to adjust the code to run with much smaller RAM and use the standard Serial.

This is the original code as you can see i can use only Max_pack_size of 5

#include <CStringBuilder.h>

int Max_pack_size = 5;

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

void loop() {

  String inputsig[Max_pack_size][9];
  char buff[((8 + 1)*Max_pack_size + 1) * 9];
  CStringBuilder sb(buff, ((8 + 1)*Max_pack_size + 1) * 9);

  for (int i = 0; i < Max_pack_size; i++)
  {
    for (int j = 0; j < 9; j++)
    {
      inputsig[i][j] = 16777215;
    }
  }

  int t0 = micros();

  for (int i = 0; i < Max_pack_size; i++)
  {
    for (int j = 0; j < 9; j++)
    {
      sb.print(inputsig[i][j]);
      sb.print(',');
    }
  }

  int t1 = micros();

  Serial.println(float(t1 - t0) / 1000.0);
  delay(1000);

  Serial.println(buff);
}

The timer displays values around 2.08 milliseconds for the code above.

First optimization attempts is to stop using StringBuilder. Everything that's written to be universal and easy to use is usually slow.

Note that when we generate String from long the implicit cast allocates char buf[2 + 3 * sizeof(long)]; so the max length of such string is 14 characters. String is of course terminated by null character '\0'

#include <CStringBuilder.h>

int Max_pack_size = 5;

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

void loop() {

  String inputsig[Max_pack_size][9];
  char buff[((8 + 1)*Max_pack_size + 1) * 9];

  for (int i = 0; i < Max_pack_size; i++)
  {
    for (int j = 0; j < 9; j++)
    {
      inputsig[i][j] = 16777215;
    }
  }

  int t0 = micros();

  int p = 0;
  for (int i = 0; i < Max_pack_size; i++)
  {
    for (int j = 0; j < 9; j++)
    {
      for (int k = 0 ; k < 14; k++)
      {
        char c = inputsig[i][j][k];

        if (c == 0)
          break;
        else
          buff[p++] = c;
      }

      buff[p++] = ',';
    }
  }

  int t1 = micros();

  Serial.println(float(t1 - t0) / 1000.0);
  delay(1000);

  Serial.println(buff);
}
}

Now the timer displays 0.86 milliseconds. Much better, but we can improve even more!

Let's drop the String. It's just an over complicated wrapper for a char array anyway.

#include <CStringBuilder.h>

int Max_pack_size = 5;

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

void loop() {

  char inputsig[Max_pack_size][9][14];
  char buff[((8 + 1)*Max_pack_size + 1) * 9];

  for (int i = 0; i < Max_pack_size; i++)
  {
    for (int j = 0; j < 9; j++)
    {
      ltoa(16777215, inputsig[i][j], 10);
    }
  }

  int t0 = micros();

  int p = 0;
  for (int i = 0; i < Max_pack_size; i++)
  {
    for (int j = 0; j < 9; j++)
    {
      for (int k = 0 ; k < 14; k++)
      {
        char c = inputsig[i][j][k];

        if (c == 0)
          break;
        else
          buff[p++] = c;
      }

      buff[p++] = ',';
    }
  }

  int t1 = micros();

  Serial.println(float(t1 - t0) / 1000.0);
  delay(1000);

  Serial.println(buff);
}

Now the timer shows 0.50 milliseconds. So we optimized the code to the point it runs 4 times as fast.


It can't be done (also, why would you think that would ever be a good idea?!)

The 8 pin chip on the ESP-01 is a 512kB SPI flash that runs at (at least) 40MHz.  So to emulate that you would need:

More than 512kB of flash,
A slave SPI interface that can operate at a minimum of 40MHz, and
The knowledge, time and energy to write the firmware to emulate an SPI flash chip

The first two are certainly beyond an ATMega328P with 32kB flash and an 8MHz maximum speed SPI interface. The third is probably beyond you since you have to ask the question in the first place (which shows a certain lack of knowledge on what it is you are proposing).

There are plenty of examples for creating a web server using an ESP8266 using either the standard AT firmware or by directly programming the ESP8266's flash chip through the ESP8266's built-in UART bootloader.  Personally I find the use of AT firmware clumsy at best and prefer to always program my ESP8266's directly.  If you feel the need to also add an ATMega328P into the mix for some reason then the communication protocol that you use between them is entirely up to you.


Is it possible to obtain %0.05 duty cycle at 1hz in arduino?(a 500us square pulse at 1 sec period)

Expanding from my comment. This is an attempt to generate that signal with Timer 1. No time to test it now... Edit: tested, works as advertised.

/*
 * Configure Timer 1 to generate a slow, low duty cycle PWM signal.
 * Output pin = digital 9 = PB1 = OC1A.
 */

const float PWM_PERIOD  = 1.0;     // 1 s
const float PULSE_WIDTH = 500e-6;  // 500 us

/*
 * With a 16 MHz clock and this prescaler, the resolution is 16 us and
 * the maximum period is 1.048576 s.
 */
const uint16_t TIMER_PRESCALER = 256;
const float F_TIMER = F_CPU / TIMER_PRESCALER;

void setup()
{
    // Configure Timer 1.
    DDRB  |= _BV(PB1);    // set PB1 = OC1A as output
    ICR1   = round(PWM_PERIOD * F_TIMER) - 1;
    OCR1A  = round(PULSE_WIDTH * F_TIMER) - 1;
    TCCR1A = _BV(COM1A1)  // non-inverting PWM on OC1A
           | _BV(WGM11);  // fast PWM mode, TOP = ICR1
    TCCR1B = _BV(WGM12)   // ditto
           | _BV(WGM13)   // ditto
           | _BV(CS12);   // clock at F_CPU/256 = 62.5 kHz
}

void loop() {}


How to update the character table of MAX7456

To solve this problem one would need to get the builtin character updating sketch work (Max456WriteTable.cpp in examples folder). After the sketch has been compiled one would have to connect either FTDI cable or a USBASP programmer to the board and upload the sketch to it.

The character set (array) itself used in the code can be updated with the appropriate program available at this site.

UPDATE: In the end I solved it this way.

Many thanks to Charlie Hanson & Nick Gammon.


First things, try to use multiple function and call it from the loop()

You can use some code magic for dealing with multitasking on Arduino.
It's a bit tricky to understand but it's working.

Here is an example :

const int BROCHE_LED_1 = 13;
const int BROCHE_LED_2 = 12;
const int BROCHE_LED_3 = 11;

const unsigned long BLINK_INTERVAL_1 = 1000;
const unsigned long BLINK_INTERVAL_2 = 500;
const unsigned long BLINK_INTERVAL_3 = 2000;

void setup() {

  pinMode(BROCHE_LED_1, OUTPUT);
  pinMode(BROCHE_LED_2, OUTPUT);
  pinMode(BROCHE_LED_3, OUTPUT);

  digitalWrite(BROCHE_LED_1, LOW);
  digitalWrite(BROCHE_LED_2, LOW);
  digitalWrite(BROCHE_LED_3, LOW);
}

void loop() {

  task_led1();
  task_led2();
  task_led3();
}

void task_led1() {
  static unsigned long previousMillisLed1 = 0;
  static byte etatBrocheLed1 = LOW;

  unsigned long currentMillis = millis();

  if(currentMillis - previousMillisLed1 >= BLINK_INTERVAL_1) {

    previousMillisLed1 = currentMillis;

    etatBrocheLed1 = !etatBrocheLed1;
    digitalWrite(BROCHE_LED_1, etatBrocheLed1);
  }
}

void task_led2() {
  static unsigned long previousMillisLed2 = 0;
  static byte etatBrocheLed2 = LOW;

  unsigned long currentMillis = millis();

  if(currentMillis - previousMillisLed2 >= BLINK_INTERVAL_2) {

    previousMillisLed2 = currentMillis;

    etatBrocheLed2 = !etatBrocheLed2;
    digitalWrite(BROCHE_LED_2, etatBrocheLed2);
  }
}

void task_led3() {
  static unsigned long previousMillisLed3 = 0;
  static byte etatBrocheLed3 = LOW;

  unsigned long currentMillis = millis();

  if(currentMillis - previousMillisLed3 >= BLINK_INTERVAL_3) {

    previousMillisLed3 = currentMillis;

    etatBrocheLed3 = !etatBrocheLed3;
    digitalWrite(BROCHE_LED_3, etatBrocheLed3);
  }
}

Second things, Try to use Real time operating system

You can try to use FreeRTOS, it's work with most arduino and you got lot of infos on the web.

It make multi tasking way more easy than the previous example.

Here is the Docs i've found


Stepper motor is not working according to code

Does the relay actually connect the pin to ground when it is off?  Or does it leave the input floating?  If it leaves it floating then you should use a pull-down resistor to make sure the pin actually sees ground and not stray interference.

If you can rewire the relays you can use an active low configuration and save the resistor since the Arduino has built-in pullup resistors.


Measure current across shunt resistor (Power Analysis)

In the graphs they've got 2.5mA tops, so you've got about 2mV on that 1.2R shunt resistor.

And Uno's default ADC reference is 5V divided into 1024 steps each of them roughly 5mV. That's more than peak value of measured voltage.

And with such small sampling frequency you won't be even able to spot fast changes as you'll be measuring much slower that it needs to be.

ADC step precision can be better by using internal 1V1 reference, but it's still way too big step. And there is no other option on UNO. The Mega on the other side has also possibility to configure diferential ADC inputs and with 1x, 20x or 200x gain. But it's not supported by Arduino core, so you'll have to do it directly. However it won't help much if it's sampling too slow.


First, ESP32 ADC is 12-bit, not 10-bit. therefore the formula should be:
float voltage = sensorValue * (3.3 / 4096.0);

Secondly, ESP32 ADC is not really linear, and tend to have lower reading than the actual value. You will need to do some calibration if you want to get a more accurate reading. You can take a look at my github on esp32-adc-calibrate.