text:
Alternative of relay
I am carrying out a physics experiment using an Arduino. This experiment requires accurate time measurements of upto a millisecond. However I am using a relay to turn on/off an electromagnet and there is a maximum lag of 10ms due to the relay. I am a complete beginner. Please suggest alternative mechanisms to switch the electromagnet and save those precious milliseconds.
P.S. - the magnet is driven by 12V 2.5A DC.

Also, keep in mind that you cannot instantly power an electromagnet. You will have a time constant L/R where L is the magnet's inductance, and R the total circuit resistance (magnet windings, power supply, MOSFET...)

What type of physics experiment?

A relay is just an electromagnet, and the same circuit that can drive a relay can drive an electromagnet. You just need to make sure it can handle the power.
The simplest circuit is to use an N-channel MOSFET:

simulate this circuit – Schematic created using CircuitLab
Just make sure that the MOSFET can handle the required power dissipation and switches on fully at below 5V on the gate (a gate threshold voltage of less than 3V is ideal).

And remember to include a flyback diode https://elinux.org/RPi_GPIO_Interface_Circuits#Driving_a_relay

Good point. I forgot that.


text:
External Interrupt Pins on Nano Clones
Long time lurker, first time poster here.
Do the cheap Arduino Nano clones such as this one have external interrupt pins?
For example, the original Nano has pins 2 and 3 usable for interrupts. Do clones tend to incorporate this feature? If so, can anyone recommend one which does?
I'm planning on using an encoder for my next project and want to make sure I can use interrupts so my code doesn't skip over encoder counts.
Thank you!

I understand your doubt. In a world where Uno WiFi i not Uno it is better to ask. And the Wawgat boards which are named Uno but use a different 8-bit MCU are a trap too.
The Nano in your link has Atmega 328p and interrupts are a feature of the MCU. There is no reason for the clone manufacturer to not use the standard Nano pinout as specified in Open Hardware Nano schematics. Then the board is compatible with Arduino Nano as defined in Arduino AVR boards package.
The clones usually use a cheaper chip for USB. You will maybe need to install a driver for the CH340.
In a few days Nano Every will be available and I expect clones of it in a short time because it is a very simple board. It will use the ATmega 4809 and Arduino advertises exact pin compatibility with old Nano. But I expect in details problems similar to Uno WiFi R2 versus classic Uno problems. One of the problems could be the mapping of interrupt pins.
And later this year Nano 33 will be released. It is a Nano format board with SAMD or nRF52 MCU so 3.3 V (the 33 in name).

source: Stack Exchange

license: Creative Commons - Attribution Share-Alike - https://creativecommons.org/licenses/by-sa/4.0/

sort: votes


text:
Does a GPS need a sim card?
I am trying to use a NEO-6M GPS to datalog my current position on a Micro SD card with the help of an Arduino Pro Mini. It doesn't transmit anything. So do I need a SIM card?

Caution:

The GPS tracker must be worked with a SIM card which may cost data and SMS fee.

No annual authorization fee for the first year. The coming annual fee details, please visit our company website.

There is nothing in this question relating to the Arduino. I suggest posting on the Electronics Stack Exchange.

For use as a GPS device, the NEO-6M doesn't need a SIM card.  For use as part of a tracker that sends SMS / GSM messages, ie, that uses the cell telephone system to send messages, you need a SIM card.  The SIM card is used to authenticate your system to the phone system.
See examples at "arduino gps and sms where are you arduino" (bigdanzblog.wordpress.com) and "vehicle tracking system using arduino gps and gsm" at circuitdigest.com.

license: Creative Commons - Attribution Share-Alike - https://creativecommons.org/licenses/by-sa/3.0/


text:
"Exit(0);" caused uninterruptible uninterruptible loop on 32u4 board
I bought this 32u4 board on Amazon (https://www.amazon.it/gp/product/B019SXN84E/ref=oh_aui_detailpage_o00_s00?ie=UTF8&psc=1) that should be recognised as an Arduino Leonardo by the Arduino IDE.
At first it totally worked as I was only trying to emulate keyboard and mouse USB input. I was searching for a code line that could stop the void loop(), so I tried using "exit(0);", as it was suggested in an other topic here. Now since that moment the board is stuck in a loop.
It continuously repeat the loop, while the red led is always on. I tried to upload a different code, but the IDE gives me alternatively two error messages:

"processing.app.debug.RunnerException
at cc.arduino.packages.uploaders.SerialUploader.uploadUsingPreferences(SerialUploader.java:159)
at cc.arduino.UploaderUtils.upload(UploaderUtils.java:78)
at processing.app.SketchController.upload(SketchController.java:707)
at processing.app.SketchController.exportApplet(SketchController.java:680)
at processing.app.Editor$DefaultExportHandler.run(Editor.java:2176)
at java.lang.Thread.run(Thread.java:745)
Caused by: processing.app.SerialException: Error touching serial port 'COM3'.
at processing.app.Serial.touchForCDCReset(Serial.java:87)
at cc.arduino.packages.uploaders.SerialUploader.uploadUsingPreferences(SerialUploader.java:143)
... 5 more
Caused by: jssc.SerialPortException: Port name - COM3; Method name - openPort(); Exception type - Port busy.
at jssc.SerialPort.openPort(SerialPort.java:164)
at processing.app.Serial.touchForCDCReset(Serial.java:81)
... 6 more";
"Forcing reset using 1200bps open/close on port COM3". (Even waiting for hours didn't solve the "forcing")

I already tried uninstalling drivers, uninstalling the IDE and changing COM port. Nothing worked. Unfortunately the reset button is missing on this board.
Is possible to restore the board or is totally lost?
Thanks in advance!

My question is different from the one there (What happens when I call exit() from my program?) because I used that code and I need to solve a loop problem, it's not just a theorical question. I'm also using a different type of board.

You could try manually resetting the board before an upload, by pressing the reset button.

SparkFun bootloader can be activated by pressing reset twice. So it's not waiting 8s in bootloader after every reset.

Possible duplicate of What happens when I call exit() from my program?

And if you have another Arduino, you can use it as an Arduino ISP programmer for burning Bootloader (this also cleans up sketch).

This isn't really a duplicate of what happens when calling exit() from an Uno, as the consequences are different.  On an Uno, entry into the bootloader is a hardware operation, but on a 32u4 based board it is typically a software one.  Apparently calling exit() breaks the latter.  It cannot break the former.

Majenko's answer is probably the solution. Thanks to everyone for the help ^^

exit(0) basically shuts the board down. That includes the USB connection, which is managed by software. All functions stop - interrupts are disabled, etc.
You need to do a manual reset of the board when it's time to program. For that you need a reset button. If there isn't one on the board then just connect one between the RESET and GND pins.  Press it just before programming (LED should glow for something like 8 seconds) and upload your new sketch.
exit(0) is only safe to use on boards with a UART interface (such as the Uno). Other boards you should use while(1); or for(;;);

Thanks for the answer. I didn't know about that.
I will try to reset the board manually in that way.

all_licenses: Creative Commons - Attribution Share-Alike - https://creativecommons.org/licenses/by-sa/3.0/


text:
Arduino int problem
I made a counter to count pulses:
int count  = 0 ;
.
.
.
setup()
{
}

while (count <= 35000)
{
  digitalWrite(9, HIGH);
  delayMicroseconds(500);
  digitalWrite(9, LOW);

  count = count + 1;
}

But when I try while(count <= 40000), it does not stop counting.

int in AVR GCC is 16 bits. All possible int values are less than 32767.

To be precise, the maximum value of int on this platform is 32767. If you add 1 to 32767 you get -32768 which then counts back up to 0, then up to 32767 and so on.

If you made it unsigned int then the maximum value is 65535 which would work for counting up to 40000.

You have reached the maximum number that an int can represent. That is 32767.
int is a variable type that is made up of 16 bits. It is signed, meaning that it can represent positive and negative numbers.
Out of the 65536 (ie. 2^16) possible numbers from the 16 bits, half of them represent negative numbers and the remaining half represents positive numbers (including zero). Or in other words, -32768 to 32767.
If you don't need negative numbers, then you can change your variable type to unsigned int which  will use numbers up to a maximum of 65535. So it becomes:
unsigned int count = 0;

But when I try while(count <= 40000), it does not stop counting.

"int" has a range from -32k to +32k-1. so "count <= 40000" will always be true as count is "int".


text:
Can I change Vcc to some other pin?
I was working on an Arduino Uno and while carrying it to my teacher the wire's pin got stuck into the Vcc of 5 V. Can I set Vcc to other inputs? If so, then how?

if you are an english speaking person, then your grammar needs some serious work. looks like you wrote three sentences, but there is no proper punctuation. as a result it is absolutely unclear what you are asking. .... what is a wire's pin ?

No, you can't program it to any other pin, but you can pull out the wire by simply sticking another wire in, putting a tiny amount of solder on that new wire and then the solder would stick to that stuck wire too. Afterwards, you can pull the new wire out, and both wires will come out as one. Happened to me once and this way I got it out.

No, you can't. Well, you can if all you want is a few mA (just set a pin to OUTPUT and HIGH), but chances are you need more than that. So no.

The VCC pin is not programmable.
However, both ICSP buses have a pin that connects to the 5V VCC line. See the diagram here: https://i.sstatic.net/wKz2l.png
 These are both male headers while the pin marked 5V is a female header so you will need to use a different connector than what you used previously.
If you choose to go this route, you should use the bottom ICSP header (opposite side of the board from the USB) as it is wired directly to the ATEMEGA328 chip. For this same reason, you should be very careful if you are trying to apply or draw power from any of the 5V pins as they are not protected by a fuse.


text:
Arduino-based mains frequency monitor
I'm looking to put together a simple mains frequency monitor based on the Arduino platform. The mains here are 250 V @ 50 Hz, but obviously these fluctuate slightly, which is the whole point of the exercise. (I am not interested in capturing voltage fluctuations, only frequency fluctuations).
I have never used any Arduino products before, but I am familiar with PIC-based MCUs. I understand Arduino should be somewhat simpler. Also, I am not an electronics engineer.
Presumably, the Arduino will sample the mains frequency for a second or two, and then report the result somehow. I guess the easiest way is for a computer connected to the Arduino by USB to receive the result and act accordingly. Otherwise, other options include adding an Ethernet module to the Arduino and having it HTTP POST the result to a web server.
(I assume doing this naive method is preferable to recording a time series and then performing a Fourier transform?)
Size isn't a huge concern, but a compact device is preferable over a larger one as I'll be 3D-printing a custom enclosure for it. Therefore I would like to use the Arduino Nano if it's suitable.
Here is what I have so far:

The 250V mains will be half-rectified with an IN4004 (?) transistor (together with a 1K resistor and 0.22 uF cap), and that will go into a 4N35 optocoupler.
A digital (?) GPIO pin from the Arduino goes into the base of the 4N35 and emitter goes to GND.
The Arduino samples for a short time the number of pulses on that pin, does a simple calculation, and reports the result.

Here are my uncertainties so far:

Based on my research, I believe the Arduino can reliably be powered by USB. If this is correct, this would be ideal as it would avoid me having to build a low voltage DC power supply for it.
How stable is the clock on the Arduino? How many decimal places on the frequency can I realistically achieve?
I presume I'll need to debounce the result from the optocoupler? Will there be some noise as the transistor transitions between states? Are there built-in debouncing functions or will I need to write my own? How is this likely to affect available clock cycles and therefore the accuracy of the measurement?
I've seen PIC projects where it interacts with the computer by emulating a keyboard. While simple, this wouldn't be ideal as the computer it's connected to must also remain usable. The software processing the result should run in the background while a user can continue using the computer. How simple is it to write some software (in C#) that will recognise the Arduino connected via USB, and communicate with that device in particular?

I also welcome any other comments and suggestions. Thank you.
Edit: Following these helpful comments and suggestions, I've made some revisions and asked a follow-up question.

The stability of the mains will exceed the accuracy of the Arduino clock by several orders of magnitude. Arduino usually uses a ceramic resonator and you would be lucky if this is accurate to 1%.  If you wanted to monitor the short term mains frequency deviations you first need to use a stable reference (atomic clock or GPS).

@Milliways: [citation needed] ;-) The inaccuracy of the Arduino clock is not an issue if you calibrate it away. And the mains may not be as stable as you seem to believe. Here is a mains stability measurement showing an Allan deviation higher than 1e-4 for 40 s ≤ τ ≤ 1 h. In the same τ range, an Arduino with a ceramic resonator has been measured to be better than 1e-6, whereas a quartz-based one is better than 1e-8, more than four orders of magnitude better than mains.

@EdgarBonet I do not deny there are short term variations in mains frequency. Most networks (at least in advanced countries) adjust mains frequency so the total number of cycles is constant over longer periods (typically 24 hours). My experience as a telecommunications engineer has confirmed this (at least in Australia). Ceramic resonators can be stable (if not accurate) PROVIDED the temperature is kept constant. Your second reference (one measurement) claiming MOST use a crystal is just plain wrong. I am sure there are more Unos than all others combined.

@Milliways: The second reference is old: nowadays most Arduinos use ceramic resonators, as I stated in my answer. But that does not invalidate the measurements which, by the way, were not done with a controlled temperature.

Either way, I want the highest resolution and best tolerance possible. Given mains in Australia is required to be 50Hz +/- 0.5Hz, I probably want 4 decimal places if possible. I'm trying to find a way to determine which Arduino boards use crystals for the MCU clock and which use ceramic resonators. From what I can see, they all have a crystal, but presumably that's for the USB interface? How can I get a list of Arduinos that use crystals? Otherwise I'll just scrap the Arduino idea and do it all myself with a PIC.

Too many questions to answer in a comment. See my amended answer.

I understand Arduino should be somewhat simpler [than PIC].

The whole Arduino platform (boards, core library and IDE) makes it super
easy to get started and do simple things. However, if you want to
“push the limits” and use the full potential of the MCU, you may have to
dig into low-level programming, and this has a steep learning curve.

The 250V mains will be half-rectified with an IN4004 (?) transistor
(together with a 1K resistor and 0.22uF cap), and that will go into a
4N35 optocoupler.

1 kΩ seems way too low to me: your resistor will dissipate on
average 31 W, and it will burn unless it is a heavy-duty power
resistor. You should choose a resistor that limits the current to a
value low enough to avoid overheating, but still high enough to reliably
turn on the optocoupler. If these two constraints end up being
incompatible, you will need a step-down transformer in addition to (not
instead of) the optocoupler.

A digital (?) GPIO pin from the Arudino goes into the base of the 4N35
and emitter goes to GND.

The base of the optocoupler is typically left floating. You connect the
Arduino input to the collector, using either the internal or an external
pullup resistor, and you ground the emitter.

I believe the Arduino can reliably be powered by USB.

Yes, powering through USB is fine. The Arduino itself draws very little
power. Only when it is powering something else you may worry about
power limits. Here it would seem your Arduino will only be sourcing a
very small amount of current into the output transistor of your
optocoupler, so you will be fine.

How stable is the clock on the Arduino?

Terrible. Most Arduinos are clocked off a ceramic resonator. These
are typically specified with 0.5% frequency tolerance, but their
frequency is constantly fluctuating, and is also strongly dependent on
ambient temperature. This makes those Arduinos grossly unsuited for any
job requiring precise timings. I would recommend you get an Arduino
sporting a real quartz crystal, like the Leonardo or the Micro. A quartz
crystal can be quite inaccurate, but at least its frequency is stable.
It's orders of magnitude more stable than a ceramic resonator. C.f.
for example this article about the Arduino clock frequency
accuracy.

I presume I'll need to debounce the result from the optocoupler?

If the capacitor after your half-wave rectifier is well dimensioned,
your signal should be clean and not need debouncing. The Arduino digital
inputs all have Schmitt triggers which clean up the input noise as
long as it is not excessive. If you really need debouncing (check with a
scope if you can), well... there are no provisions for doing so in the
Arduino core library, but there is a Debounce tutorial among the
examples shipped with the Arduino IDE, and there are a few third party
debounce libraries floating around the Web.

How simple is it to write some software (in C#) that will recognise
the Arduino connected via USB, and communicate with that device in
particular?

As stated in other answers, your Arduino will be seen by your computer
as a virtual serial port. I don't know C#, but any decent programming
language should allow you to easily read data from a serial port.
Measuring method:
You will time one or several periods of the input signal. There are
several ways of doing so. In roughly increasing order of complexity and
accuracy:

You continuously monitor the digital input, in a loop, and whenever
you see a transition from LOW to HIGH you record the current time
using micros().

You use an interrupt pin as the input and you have the interrupt
handler record the time with micros().

You use the input capture facility of your 16-bit timer running at
the full CPU speed.

The methods using micros() have a resolution of 4 µs. Both will
give you some software-induced jitter because they depend on the timing
of your program execution. The advice given by GuitarPicker: “Keep your
code predictable, using as few conditional branches as possible that
might alter how long your code takes to run each cycle” is relevant only
to the first method. The interrupt method is immune to your main loop
timing, but it is still affected by the CPU processing other interrupts.
The input capture method will give you single-cycle resolution and
accuracy, with zero software-induced jitter. That would be my first
choice, but it requires digging into the MCU datasheet and doing some
low-level programming.

Addendum: Here are some tentative answers to a comment posted by
Ozzah to his own question:

I probably want 4 decimal places if possible.

If you want 10−4 absolute accuracy, you may need to
calibrate your clock, even if it is a crystal. If you only require
10−4 stability (variations of the frequency), then even a
ceramic resonator may be (barely) up to the task, if you don't mind
recalibrating it every few weeks, and assuming your indoor temperature
doesn't vary by more than ≈ 10°C.

I want the highest resolution and best tolerance possible.

Then a quartz crystal is definitely a plus. It's roughly 100 times
more stable than the ceramic resonator.
But if you really want the “best”, you may as well follow Milliways'
advice and get a GPS reference. Some options, in increasing order of
price and accuracy:

A simple GPS module for the Arduino. Make sure you get one with a
1PPS output (a “one pulse per second” reference signal). You may want
an external antenna for better reception.
A GPSDO (GPS disciplined oscillator). This is typically a lab-grade
frequency standard consisting of an OCXO (oven-controlled crystal
oscillator) disciplined by a feedback loop into tracking GPS time. It
gives the same long-term stability as the simple GPS module but has
far better short-term stability.
A rubidium-based GPSDO. This is similar to the above but has also a
rubidium atomic frequency reference. Still better short-term
stability. Now we are talking about stabilities in the
10−11 to 10−12 range. Provably overkill for
your use case.

From the software point of view, I would recommend you start with the
interrupt method, just to get a prototype working easily, and then go to
the input capture method, as it will give you the best accuracy. It
should be possible to be cycle-accurate with the interrupt method, but
that would require some non-trivial tweaks.
Note also that the Arduinos based on the ATmega32U4 (Leonardo and Micro
at least) have two 16-bit timers with input capture capability. You
can then time both the mains signal and a 1PPS reference in parallel. If
your Arduino has only one 16-bit timer (like the Nano), you would have
to time one of the signals with the interrupt method.

I'm trying to find a way to determine which Arduino boards use
crystals for the MCU clock and which use ceramic resonators. From what
I can see, they all have a crystal, but presumably that's for the USB
interface?

Yes, the USB/serial interface is clocked off a crystal more often than
the main MCU. The Arduinos that do not have a separate USB/serial
bridge (like those based on the ATmega32U4) seem to have the main MCU
clocked off a crystal.

How can I get a list of Arduinos that use crystals?

It's often stated in the product page. E.g., the page of the Arduino
Micro states
(emphasis mine): “It has 20 digital input/output pins (of which 7 can be
used as PWM outputs and 12 as analog inputs), a 16 MHz crystal
oscillator, a micro USB connection, an ICSP header, and a reset
button.”
Arguably, the info is not very prominent, and a compiled list would be
useful. I think this could be a very good question to ask in this site.

Thanks so much for your insightful answer. I had later revised it to 6K resistor and then finally decided it would be best just to transform down to a lower voltage, probably 5V. I will look into the models with quartz crystals. Is it simple to replace the ceramic resonator with a quartz? Is it just a matter of swapping out some components?

@Ozzah: Replacing the ceramic resonator with a quartz doesn't look like an easy task. It's a tiny SMD component, you will need to find a quartz small enough to fit in there, and most quartz crystals require a pair of capacitors that you would also have to fit, together with the crystal, into the footprint of the resonator.

I would use a step-down transformer with that 1N4004 rectifier diode to limit the peak rectified voltages to less than the Arduino's safe input voltage. I would also be inclined to add a zener diode to ground at the Arduino's input to "clamp" or limit that input voltage to whatever your Arduino's safe upper limit is.
At some point you might also find it beneficial to double the 50hz using a full-wave rectifier to give you more pulses to count for finer resolution.
A low current fuse in there somewhere wouldn't be a bad idea either.

So I'm not an electronic engineer, but I don't understand why I need to bring the voltage down to the Arduino's range? Isn't that the whole point of the optocoupler? The input end runs at 250V and the output end runs at whatever voltage the Arduino is running at?

It sounds like you're well on your way to creating a solid project.  I will attempt to answer some questions and offer some suggestions on approaching this.
Rather than counting the number of AC pulses per time period, you might get better results seeing how many Arduino clock ticks you get between a sampling of say, 50 (debounced) pulses.  This will give you bigger numbers to work with.  Doing the opposite (seeing how many pulses per time period) will not give the same precision.  If you only got 49 pulses in a second, did you just barely miss the 50th, or was it a whole 2% off?  Since the Arduino clock can count much faster, it would be better to count those ticks instead.

Arduinos can be reliably powered by USB, as long as you don't draw too much current.  Your application sounds like it shouldn't draw much at all.
The clock on the Arduino isn't going to compare with using a separate real-time clock circuit, but it should be good enough to measure trends and differences.  Keep your code predictable, using as few conditional branches as possible that might alter how long your code takes to run each cycle.
Debouncing is probably a very good idea in this situation.  There are several debouncing libraries available for the Arduino, or you can roll your own.  Once again, the library should written as to not introduce inconsistent delays into the code.  For this reason, it might be better to write your own specifically suited for this application.  You might need to borrow an oscilloscope and see how long the pulses are from your optocoupler circuit.  The closer you can get them to being a 0V/5V square wave, the better.
Arduinos come in many flavors.  Some can emulate keyboards, but most act natively as serial ports.  If you can read data from a serial port, then you can read the output from the Arduino.  This should be trivial in C#, or just use a terminal emulator or the Arduino IDE's serial console to view the results.  Once again, if you are outputting data while still measuring, then you should use use fixed width output so that the program takes the same amount of time to run each cycle.  It would be far more accurate instead to take your measurements silently, and output the results afterward later so that you don't have to account for serial port buffer delays.  Take another "flush" delay before starting measurement cycle again.

It's a safety issue at the very least. A catastrophic failure of the opto & everything is gone. At least with a "wall bug" style transformer, you've given yourself & your device a large safety margin.
I assume your opto will be triggered at line voltage & frequency to subsequently switch a 3.3 or 5v bus to an Arduino input pin at the 50hz line rate.
The opto you've chosen turns ON at ~1 volt & it needs a current limit of ~10ma thru it. You'll need to calculate a dropping resistor value to bring the rectified peak voltage down so that the opto isn't overloaded in either category. You'll need to also compensate for the eventual surge/peak voltages well above the typical line voltages.
There could conceivably be enough constant "noise" riding in on the line that prevents the opto from regularly seeing the "zero crossing" moment that your pulse counter relies on.
Transforming that line voltage to a much lower level decreases ambient line noise by the same transformer ratio, increases safety & makes it easier for the opto to detect the zero crossing in the presence of line noise etc.
bc

Thanks. I think I'll drop down to ~5V with a transformer as you suggest.

It wouldn't hurt to do both the transformer and the opto.  I've seen wall transformers fail with higher voltages than their usual output.  I'm thinking back to a cheap powered USB hub I encountered that kept zapping flash drives (back when they were new and expensive).

Based on my research, I believe the Arduino can reliably be powered by USB.

it can also be powered by the mains directly. ST wrote such an application note for its STM8 but the basic principle is the same. The beauty of this approach is that your zero cross detection can be done without the use of an optocoupler, directly through a gpio pin.

How stable is the clock on the Arduino? How many decimal places on the frequency can I realistically achieve?

depending on your board. crystals are usually specified to 20ppm but typically within 10ppm at room temperature. resonators, which some arduino uses, are 0.1 - 1%.
if you are n't too picky, even the internal oscillators will do -> you can average the measurement over a long period of time to minimize jitter.

I presume I'll need to debounce the result from the optocoupler?

generally no.
when you measure frequencies, you typically count the input signal. for low frequencies like the mains, you do the other way around: count the internal clock and use the input signal to gate its counting.
This allows frequency calculation down to quite a few decimal points: you should average approximately 8M counts per half cycle.
that's a lot of effective digits.


text:
"undefined reference to" - C++
Hi fellow programmers,
I started to program Arduino a little deeply and popped out the following error when I was writing a class to read the pulses of a Hall effect flow rate sensor:
SensorDeVazao.cpp.o: In function `SensorDeVazao::Resetar()':
SensorDeVazao.cpp:141: undefined reference to `SensorDeVazao::SensorHandle'
SensorDeVazao.cpp:141: undefined reference to `SensorDeVazao::SensorHandle'
SensorDeVazao.cpp:141: undefined reference to `SensorDeVazao::SensorHandle'
SensorDeVazao.cpp:141: undefined reference to `SensorDeVazao::SensorHandle'
SensorDeVazao.cpp:141: undefined reference to `SensorDeVazao::SensorHandle'
SensorDeVazao.cpp.o:SensorDeVazao.cpp:141: more undefined references to `SensorDeVazao::SensorHandle' follow
collect2: error: ld returned 1 exit status

The code is divided in two files, a *.h and a *.cpp, so it is uncircumstantial to paste the code here (pos-edited: the codes are the following: *.h: codepad.org/UyLfik6W *.cpp: codepad.org/5KJmraCC). But I will explain the context:
SensorHandle is a static object of the own class SensorDeVazao (Brazilian Portuguese to FlowRateSensor) and it is used in an glue function used by the attachinterrupt to read the pulses I've mentioned previously. The function claimed in the error log ("Resetar", Brazilian Portuguese for reset) don't use the variable "SensorHandle". Last but not least, the message shown in the second line appears subsequently multiple times in the error window.
I hope, I provided all the informations to help you solve this issue.
Thank you for the attention.
PS.: Sorry if this is a duplicated post. If yes, please forward it in the comments below.

Sorry Bruno but we need to see the code to know whats going on.  Can you post the code around line 141 (130 - 150) if nothing else?  I think it is very stange that it is looking for SensorDeVazao::SensorHandle within the class (unless that is a quirk of the compiler).

I've posted below at @frarugi's comment.

@BrunoHenriquePeixoto Usually it is better to add them directly to the question (just edit the post and put at the bottom the two links) so people coming here will know that they are here

Thank you for the advice. I was not sure about the privilege to add links to the question.

Without seeing the actual code (BTW why can't you add it? Is it top-secret?) I can't be sure, but usually this happens when you don't define a variable but just declare it. Example:
// File myclass.h
class A {
public:
  static int i;
};

// File myclass.cpp
void myfunc() {
    A::i = 0;
}

If you actually declare it the error should go away:
// File myclass.h
class A {
public:
  static int i;
};

// File myclass.cpp
int A::i = 0;

void myfunc() {
    A::i = 0;
}

Remember that the class definition (so the class {}) can go in a header file, but the variables definition MUST go in a source file (so the .cpp one) AND if you have multiple source files you have to put this in ONLY ONE file (usually the file where you implement the functions).
This only applies to static variables.
EDIT: Further explanation.
You should understand the difference between declaration and definition of a variable.
Definition is just stating "there exist a variable called i, which is an integer"; for instance the statement extern int i; defines a variable. All the variables listed in a class are only defined there.
Declaring a variable is one more step: it tells the compiler to reserve the space in memory (this operation is called allocation) and so to physically create the variable. Always keep this in mind.
Little example. Let's say you have a library, using files lib.h and lib.cpp, and files A.cpp and B.cpp both referencing the library (they have a statement saying #include "lib.h"). When writing a library without a class you usually write global variables in this way:
// header file: lib.h
extern int i;

// source file: lib.cpp
int i;

(note: it is better to always define an initialization value, so for instance int i = 0;). The two files (A and B) both have the line extern int i; in they, which means "there exist a variable called i, and someone else is allocating the space for it. Result: the compiler will link all those definitions to the same memory location, thus actually sharing the variable. If you wrote int i; in the header file each cpp file would have its i variable allocated, so each would point to a different block of memory.
Now, for the classes. If you write
class A {
public:
    int a;
    static int b;
}

you have two variables. A gets instantiated when you instantiate an object, so does not have any problems. But b... well, b is just defined, never declared. So there is no place in memory where b actually resides (the reference is undefined).
To deal with this, you have to manually declare it in a cpp file, with the syntax int A::b;. This way you are reserving some space for that variable

Oh, damn, I've been discovered. Haha. Sure, I'll post it, but I'm a little bit skeptical in regard to this definition in *.cpp thing.
*.h:
http://codepad.org/UyLfik6W
*.cpp:
http://codepad.org/5KJmraCC

The header file looks fine at a first glance, so I'm pretty confident that adding SensorDeVazao* SensorDeVazao::SensorHandle = NULL; (or whatever value you should initialize it) before the functions in your SensorDeVazao.cpp file will solve your problem

It worked like a charm. Thank you, Sir! :D But now an explanation is required.

@BrunoHenriquePeixoto I added a small explanation. Keep in mind that I'm not an expert, though, so these info come from what they explained me when I faced the same problem ;) anyway if the answer successfully answers your question, please mark it as accepted so other people looking for this can find a quick answer

@BrunoHenriquePeixoto - I can't see codepad (bloody firewall :() but Majenko's answer's are normally right so I'd go with what he says.

Where do I accept it?

There should be a tick sign or something similar under the votes (on the left of the answer). You can click it to mark it as accepted

Much appreciated. You've excelled in the explanation. :D

@BrunoHenriquePeixoto Well, it was a pleasure to see someone asking for further explanation. Sometimes people come here to just solve their problems, but, IMHO, this is a wrong approach. Understanding why it was wrong is a more correct approach, and, according to your comments, you are the kind of person who wants to understand.. so, my compliments, good attitude :)

Where is my cookie? I demand my cookie! ;P I think asking for how things work is a better way to continuosly learn something new and trick the time about aging. :)

An explanation of what is happening:
When you define a class you indicate what variables will be in it.
When you then instantiate the class (MyClass c;) the variables within the newly instantiated object get allocated.
Static variables never get instantiated. After all - which instance of the class should instantiate them when you create one? And if you never create one? So it's simple: static variables never get created by the class definition or anything else. It is up to you to provide the storage space for that variable, which means statically allocating it in your C++ code as has been demonstrated.

Thank you once more for the clear explanation. This code will work with sensors in the University of São Paulo in Brazil. The students and I are very much appreciated. :)


text:
Headers linking - PlatformIO
For those who use the IDE Platform IO, I have an issue for you. I use to program a home application of sensor reading and use the library "JC_Button.h" to manage buttons. There are other third-party libraries, but this in especial is cumbersome. The project tree is shown below.
.
The compile log of the build is here. I have few notion of what is happening. In my opinion, the project does not find the necessary lib.
Thank you in advance.

your log file says the compiler can’t find the header file. check that the include dir exists and that the compiler knows how to find it

It looks like you are not telling PlatformIO that you need the JC_Button library. Try adding this to your platformio.ini file:
lib_deps = https://github.com/JChristensen/JC_Button

all_licenses: Creative Commons - Attribution Share-Alike - https://creativecommons.org/licenses/by-sa/4.0/


text:
What are the tools that I need to program the Arduino in C?
The Arduino IDE by default is oriented towards C++. The linker for example requires .cpp files and not .c files, otherwise it leads to errors during the linking process. See name mangling if you want to know more.
So, what are the tools that I need to setup a C environment? Can this be done from the Arduino IDE itself?
I work on a Linux system (Ubuntu 12.04).

Why would you want to prgram Arduino in "pure C"? C++ is often seen as superset of C (although purists may say that is not 100% true). Is your problem related to how you can link to libraries developed in C? Or is it more related to performance?

@jfpoilpret Its a matter of personal preference. I prefer using C to C++, most of the time.

OK. But, if you setup a pure C environment for development, that means you won't be able to use 3rd-paarty libraries based on C++, wouldn't that be a problem?

@jfpoilpret Hmm. I didn't give that aspect much thought. Yes, that will be a problem.

In general, it is feasible (and easy) to link a C++ program with pure C libraries, but the opposite is not true. Otherwise, you can still restrict yourself to code "like in C" on Arduino IDE, the C++ compiler would spot any problems the same as a C compiler.

Also, I see AtmelStudio 6 has support for AVR-C projects so you should be able to work in a pure C development environment, but then you will lose all Arduino stuff and would work directly (and only) with AVR libraries.

There are features supported in C that are not supported in C++, such as __flash introduced recently in avr-gcc.

Well, if you want to do more advanced stuff with your AVRs, you should definitely leave the Arduino environment, and integrate your AVR development in your "usual" favorite development environment, whatever it is.
Then you've got two choices, either do 100% pure C with AVR libraries, for which you only need a simple makefile that calls avr-gcc with avr-libc libraries as include path. You can also use Atmel Studio that helps you a lot on that stuff. But if you do so, you're loosing the advantages of the libraries built for/by the arduino community – which, sadly, is not a huge loss for a strong majority of those.
Or you can work your code out as a 100% C external library, used from within the sketch, and included at linking time. Then you'll have all the advantages of working with any C++ library you'd like to have, but still doing the important code in pure C. Having only the .ino used to generate the main .cpp and any .cpp library you'd need. Though, for many basic features like writing on the serial port, you'll have to do it [the good old way][2] or by doing some weird encapsulation of Serial.println() call sent as a functor to the pure C parts.
In the makefile I've written (debian offers another one with the non-gui install of arduino), every .c file from declared libraries are detected and compiled with avr-gcc, every .cpp file is compiled with avr-g++ and both gets linked when doing the .elf/.hex file.

Why do you say that Atmel Studio will prevent you from using the Arduino libraries? They work just fine. But I agree fully with your recommendation to exit the Arduino IDE. With Atmel Studio you can add an AVR Dragon for $US50 or so that will support debugwire (for the UNO and friends) and JTAG for the Mega 2560.

The linker for example requires .cpp files and not .c files, otherwise it leads to errors during the linking process

No, it doesn't.

So, what are the tools that I need to setup a C environment?

Why do you want to?

The answer
Make a new tab in the IDE (top RH corner). Call it, for example, foo.c. That's your C file.
Put whatever C code you want into it. For example:
#include <Arduino.h>
void foo ()
{
PORTD = bit (1);
}

Now in your "main" sketch call that function, eg.
extern "C"
 {
 void foo ();
 }

void setup ()
  {
  foo ();
  }  // end of setup

void loop ()
  {
  }  // end of loop

Repeat as required for any C functions you care to write.
Of course, you can't use Serial (that's a C++ class) or Wire (that's a C++ class) or SPI (that's a C++ class), but if you want to work with C, you can certainly do that.

You're already there with the Arduino IDE; C++ compilers understand plain C just fine, but may interpret C syntax slightly differently in some cases. I write most sketches in C, invoking C++ objects from libraries as necessary.
If you're to the point where you want finer grained control over which compiler, C or C++, gets used for a given module, then it's time to graduate to another environment. Eclipse is a very popular and flexible IDE for a large range of languages, compilers & cross-compilers, and provides a very flexible Arduino environment. Or your favorite shell, programming editor, Make, and the avr-gcc cross-compilation tool-set will give you the ultimate access to and control of every detail - perhaps more than you wanted - of the edit/compile/link/download/debug process.

Take a look at ino on linux and PCs and Mac.  It's available in the fedora repos, not sure about other distros; though, I'm sure everyone can install it from the github project site, regardless of the distribution.  According to the website, you can also install it with python setup tools:
pip install ino

or
    easy_install ino

BTW: sorry for not including this "answer" in a comment due to reputation restrictions.
Here's the description from the fedora repos; I think it's taken directly from the ino tool website:

Summary     : Command line toolkit for working with Arduino hardware
URL         : http://inotool.org/
License     : MIT
Description : Ino is a command line toolkit for working with Arduino hardware.
            :
            : It allows you to:
            : Quickly create new projects
            : Build a firmware from multiple source files and libraries
            : Upload the firmware to a device
            : Perform serial communication with a device (aka serial monitor)
            :
            : Ino may replace Arduino IDE UI if you prefer to work with command line and
            : an editor of your choice or if you want to integrate Arduino build process
            : to third party IDE.
            :
            : Ino is based on make to perform builds. However Makefiles are generated
            : automatically and you'll never see them if you don't want to.


text:
How do I communicate with the Uno using R through RStudio?
I am working on a real time application which is recording sensor data continuously. I need to process the data in realtime using R. Is there a way to connect and communicate with the uno board through RStudio via serial port?

This question appears to be off-topic because it is about a serial interface for R; Best bet would be for this to be migrated to SO.

@MatthewG. Side Note: Migration paths don't exist for private betas.

Ahh, good point.

If RStudio has serial support. Yes, it can talk to a Uno. If it does not. No.
This is really a question about RStudio (and actually just pure R), not arduinos.
Furthermore, RStudio is just an IDE. Therefore, no, RStudio can not communicate with an arduino, compile a program, or do much of all aside from edit source-code files. RStudio does not run your code at all. It uses an external interpreter to run your source files.
R, on the other hand probably can talk to serial interfaces. The fact that you're using RStudio is entirely irrelevant.
I'm not familliar with R, but a little googling leads me to think that R can talk to serial interfaces without too much trouble, though I have not been able to find any information about doing so on windows. What platform are you using?

I can't seem to figure out directly how to read from a serial port using R; While there does seem to have been at least one attempt to provide this, it's not clear that it ever graduated to something supported or easily installable.
Having said that, R does have read.socket and write.socket, which I believe would make it easy enough to use through ser2net, which exposes a serial-port as a socket.


text:
How to change Void with button press
I have 2 buttons and 2 voids (blink_slow) (blink_fast).
i need to be able to press button 1 and blink-slow void will run, then press button 2  and blink fast will run. none of my code works, any idea how i can do this?
const int btn1 1;
const int btn2 2;
const int led  13;

void setup(){
pinMode(btn1,INPUT_PULLUP);
pinMode(btn2,INPUT_PULLUP);
pinMode(led,OUTPUT);
digitalWrite(led,HIGH);
}
void loop(){
if(digitalRead(btn2 =LOW)){
blink_slow();
}
if(digitalRead(btn3 =LOW)){
blink_fast();
}

void blink_slow(){
digitalWrite(led,LOW);
delay(1000)
digitalWrite(led,HIGH);
delay(1000)
}

void blink_fast(){
digitalWrite(led,LOW);
delay(500)
digitalWrite(led,HIGH);
delay(500)
}

Start by correcting the obvious:
const int btn1 = 2;
const int btn2 = 3;
const int led = 13;

void setup()
{
  pinMode(btn1, INPUT_PULLUP);
  pinMode(btn2, INPUT_PULLUP);
  pinMode(led, OUTPUT);
  digitalWrite(led, HIGH);
}

void loop()
{
  if (digitalRead(btn2) == LOW) {
    blink_slow();
  }
  else if (digitalRead(btn3) == LOW) {
    blink_fast();
  }

void blink_slow()
{
  digitalWrite(led, LOW);
  delay(1000)
  digitalWrite(led, HIGH);
  delay(1000)
}

void blink_fast()
{
  digitalWrite(led, LOW);
  delay(500)
  digitalWrite(led, HIGH);
  delay(500)
}

The mistakes where 1) const variable assignment, 2) using pin 1 (TX) is a potential risk if you later what to use Serial for debugging, etc, 3) condition expression, and a lot of formatting. Open your C/C++ book and check the syntax.
Now your turn to improve this!

He's not using Serial, so it's possible to use the TX pin?
I'm not sure if it has internal pull-ups aswell (or other specifics), but in theory it's not wrong?
But yes, I would advise to use Serial for debugging, since that almost everything you've got.

Yes, using pin 1 (TX) is possible when not using Serial but may give issues later on when doing do. A good practice is to avoid pin 0 and pin 1 until the sketch is debugged. Not a mistake, more a potential risk. Good catch, Paul!


text:
help compiling code for flora project
I'm working on the Adafruit Firewalker shoes.
I can't make my code compile to test my flora project.
This is my error message:
Arduino: 1.6.7 (Windows 10), Board: "Adafruit Flora"

C:\Users\Devi\Documents\Arduino\test_2\test_2.ino\test_2.ino.ino:1:29: fatal error: Adafruit_NeoPixel: No such file or directory

 #include <Adafruit_NeoPixel>

                             ^

compilation terminated.

exit status 1
Error compiling.

  This report would have more information with
  "Show verbose output during compilation"
  enabled in File > Preferences.

https://learn.adafruit.com/firewalker-led-sneakers/test-circuit
    #include <Adafruit_NeoPixel.h>

const int analogInPin = A9;  // Analog input pin that the potentiometer is attached to
Adafruit_NeoPixel strip = Adafruit_NeoPixel(10, 6, NEO_GRB + NEO_KHZ800);
int sensorValue = 0;        // value read from the pot

void setup() {
  // initialize serial communications at 9600 bps:
  Serial.begin(9600);
 pinMode(9, INPUT_PULLUP);
   strip.begin();
  strip.show(); // Initialize all pixels to 'off'

}

void loop() {
  // read the analog in value:
  sensorValue = analogRead(analogInPin);
  // print the results to the serial monitor:
  Serial.print("sensor = " );
  Serial.println(sensorValue);

if (sensorValue < 100){
  Serial.println("leds triggered");
colorWipe(strip.Color(255, 0, 0), 25);
colorWipe(strip.Color(0, 0, 0), 25);
}

}

void colorWipe(uint32_t c, uint8_t wait) {
  for(uint16_t i=0; i<strip.numPixels(); i++) {
      strip.setPixelColor(i, c);
      strip.show();
      delay(wait);
  }
}

Can you please copy and paste the code, and the error message, into your question as text? Not a screen-shot? I can hardly read what the error is. Edit your post and format the code using the code formatting markdown (four leading spaces). For help see Markdown help. You should be able to do this by selecting the code and pressing Ctrl+K to have your browser do this for you.

@NickGammon thank you sorry I'm a mess ive never coded with Arduino before

Your error message says #include <Adafruit_NeoPixel> but your code says #include <Adafruit_NeoPixel.h> - which do you actually have?

@NickGammon I have #include <adafruit_neopixel.h>  all I did was copy and paste the source code

I had the same problem, you just have to download the Adafruit Neo Pixel library:

i think issue is in your this path
C:\Users\Devi\Documents\Arduino\test_2\test_2.ino\test_2.ino.ino:1:29: fatal error: Adafruit_NeoPixel:
make new arduino file and copy the same code and save it on other folder on desktop or other drive then compile it
Compilation
I compiled you same code and my stored path of .ino file is
C:\Users\Muhammad Hassaan\Documents\Arduino\sketch_mar04a

this did work it still says no directory found for neopixels did I install something wrong all I did was copy and paste source code

i think issue is with your library that you have downloaded, please reinstall the Arduino IDE and download the library again with the help of ide then recompile your code


text:
NodeMCU sensor values to web page
I post NodeMCU sensor values to a web page. But how can I pass those values to a database using PHP?
Here is the code to post sensor values to a web page:
#include <ESP8266WiFi.h>

const char* ssid = "CDS_ARDUINO";
const char* password = "arduinotest@wifi";

WiFiServer server(80);

void setup() {
  Serial.begin(115200);
  Serial.print("Connecting to ");
  Serial.println(ssid);
  WiFi.begin(ssid, password);
  while (WiFi.status() != WL_CONNECTED) {
    delay(500);
    Serial.print(".");
  }
  Serial.println("WiFi connected");
  // Start the server
  server.begin();
  Serial.println("Server started");
  // Print the IP address
  Serial.print("Use this URL : ");
  Serial.print("http://");
  Serial.print(WiFi.localIP());
  Serial.println("/");
}

void loop() {
  WiFiClient client = server.available();
  if (!client) {
    return;
  }
  // Wait until the client sends some data
  Serial.println("new client");
  while(!client.available()){
    delay(1);
  }
  String request = client.readStringUntil('\r');
  Serial.println(request);
  client.flush();
  client.println("HTTP/1.1 200 OK");
  client.println("Content-Type: text/html");
  client.println("Connnection: close");
  client.println();
  client.println("<!DOCTYPE HTML>");
  client.println("");
  client.println("<meta http-equiv=\"refresh\" content=\"3\">");
  client.println("
Getting NodeMCU Analog values
");
  int sensorReading = Serial.read();
  client.println("");
  client.println("");
  client.println("
");
  client.println("");
  client.println("");
  client.print("
");
  client.println("");
  client.print("&nbsp &nbsp &nbsp &nbsp &nbsp");
  client.print(" Analog input value is ");
  client.println("");
  client.print(sensorReading);
  client.print("
");
  client.println("");
  delay(100);
  Serial.println("Client disconnected");
}

Before your question gets closed, since it's only merely related to Arduino, I'd like to post this answer to give you more of an clue on how to set up the system.

Connect PHP and the database of your choice.
Connect the Arduino to PHP (probably with TCP/IP or HTTP), to send the values to the database.
Use PHP (+ webserver) to generate and serve webpages.

Only point 2 is somewhat related to Arduino.SE, so I'll try to give you some "handles" to get started.
https://www.arduino.cc/en/Tutorial/WebClient
https://www.arduino.cc/en/Tutorial/HttpClient
You can issue a GET request with variables to a webpage using Arduino.
In PHP you can read out these variables.
And using PHP you can connect and send variables to your database.
You shouldn't connect the Arduino directly to the database, because exposing your database to the world wide web is a security risk.
After this, it will be relatively easy to generate a page with the contents from your database.


text:
Rotary Encoder problem with LCD Display
Program reads rotary encoder correctly without bouncing in this code:
int val = 0;
byte clkPin = 3;
byte dtPin = 2;
bool lastClk;
bool lastDt;
void setup() {
  pinMode(clkPin,INPUT);
  pinMode(dtPin,INPUT);
  lastClk = digitalRead(3);
  lastDt = digitalRead(2);
  val = 0;
  attachInterrupt(digitalPinToInterrupt(clkPin), clkRise, RISING);
  Serial.begin(9600);
}

void loop() {
}

void clkRise(){
      lastClk = HIGH;
      lastDt = digitalRead(dtPin);
      if(lastDt == LOW){
        val--;
        Serial.println(val);
        }  else{val++; Serial.println(val);}
        }

but when i use lcd to show the result, i get massive bounces (i think) in this code:
#include <LiquidCrystal_I2C.h>

#include <Wire.h>

LiquidCrystal_I2C lcd(0x27,20,4);
int val = 0;
byte clkPin = 3;
byte dtPin = 2;
bool lastClk;
bool lastDt;
void setup() {
  lcd.begin();
  pinMode(clkPin,INPUT);
  pinMode(dtPin,INPUT);
  lastClk = digitalRead(3);
  lastDt = digitalRead(2);
  val = 0;
  attachInterrupt(digitalPinToInterrupt(clkPin), clkRise, RISING);
  Serial.begin(9600);
  lcd.home();
}

void loop() {
  lcd.print(val);
}

void clkRise(){
      lastClk = HIGH;
      lastDt = digitalRead(dtPin);
      if(lastDt == LOW){
        val--;
        Serial.println(val);
        }  else{val++;}
        }

it increases and decreases by random numbers between 0-5.I use KY-040 R.E. it has built-in 10k pull up resistors.
This is what i use to debounce:
A or B pin of R.E--10k R----------------------------------Arduino INPUT PIN
                         |
                         |
                         =0.1uF C
                         |
                         ---------------------GND

Try adding a slight delay after lcd.print(val);. Something like delay(50);. Also, if the R.E. has in internal pull-up of 10k, the series resistor between the A/B pin should be lower than 10k. Otherwise the maximum voltage is only 2.5V (Vcc/2).

@Gerben i tried delaying, it works better but there are still big jumps like 3-4+

Either increase the delay, or only do the lcd.print if the value of val has changed.

@Gerben it work way better now, but there are still rare jumps. would a schmitt trigger fix this? I took off the 10k resistor that i placed.

I don't know. That's not my area of expertise.

I suspect the problem is that your hardware-debounce capacitive circuit isn't working well enough to accurately debounce the contacts, and that invalid transitions are occurring on the quadrature lines as read by the program.
Note that use of Serial.println() within your clkRise() interrupt handler is problematic, because Serial.println() uses interrupts itself. As far as I know, println() is not reentrant, ie cannot be used correctly from the multiple interrupts that may start before previous println() calls finish their background processing.  The bits of extra delay introduced by LCD code may merely be exposing a problem.
There is no need for either hardware or software debouncing on quadrature inputs.  A correctly-implemented state machine will reject invalid conditions that arise during bounce, or will immediately follow any extra up-tick by a corresponding down-tick, or vice versa.
For some state machine code, see for example answer 16420/3917 and also see answer 18221/3917.  Also see answer 19109/3917.

Çay Öncesi should definitely not be doing Serial.println inside an ISR.

@NickGammon alright. I finished my project. just curious, what is the outcome of placing Serial.println inside an ISR?

Serial.print puts whatever-it-is you want to print into a buffer. It then waits for interrupts to empty the buffer. If the buffer is full already, it waits before putting data into the buffer. Since the buffer won't be emptied inside an ISR, if the serial buffer is full, the program will then block indefinitely.

What I've been doing in my decoder interrupt routines is to set a "valueChanged" flag. Then in the app's main loop, if value changed is true, I use Serial.println() to print it and set valueChanged=false. That way I'm not trying to do serial.print inside an ISR. When I needed more info than that. I created a large (char logBuffer[100]) C string to contain my logged data, and used strcat() to append to that. Then in the app's loop() I print the logBuffer and set it back to empty.

@DuncanC, the general idea of using a buffer like that is ok, but there are several races that can occur -- eg if the ISR adds to the buffer between loop()'s "print the logBuffer" and its "set it back to empty" operations, the added data gets lost.  One can fix the problems using semaphores, or switching between two buffers atomically, etc


text:
Using a MIDI connector both as MIDI In and Out (not simultaneously)
I asked this question also in Electrical Engineering (stack exchange), however on question is more appropriate on this board (question 5). For completeness, I kept all questions intact, but made question 5 bold.
Electrical Engineering StackExchange Question Link: Using a MIDI connector both as MIDI In and Out (not simultaneously),
In my current (Arduino) project I have (currently) 3 MIDI INs and 2 MIDI OUTs. However, it would be nice if I can configure each of the MIDI connectors as IN or OUT by software (Arduino).
The circuits I am using are:

And

What I would like is to use the connector shown in the above picture as MIDI In OR MIDI out. I have not tried it yet, since I have too many doubts and I do not want to break a component. However, I thought about it (with my limited electronic knowledge), and I think:

Pin 2 afaik for MIDI In, normally has +5V. In the MIDI Input circuit it is not connected, but in the MIDI Output circuit, it is connected to GND. I don't think this is good when being used as MIDI out, resulting in a short circuit (?). So I guess I have to make it +5V when used as MIDI Input and GND when used as MIDI Output (so putting HIGH or LOW 'digital' for Arduino).
Pins 1 and 3 remain in both circuits untouched (so I assume I can do the same).
Pin 4 and 5 is a bit tricky, since they are connected. I think I have to use one or two transistors to create two alternative paths for pins 4 and 5 for MIDI Input and Output. Or can I just set a specific voltage on pins 4 and 5 when used as MIDI In or Out? (and what would those values be?).
For the MIDI input, an optocoupler is used, while for MIDI output, directly the Arduino is used. I wonder if I have to use for both an optocoupler (since people might connect it accidentally to a MIDI output from a MIDI device.

5. I'm not sure how to handle the RX and TX pins ... for 5 MIDI devices, I would need to use 5 RX and TX pins, but the Arduino (Mega) only has 4 of each. But this is probably a question for the Arduino board.

Could you check over your question for typos in the pin numbers, please? I got confused at the first part about lin 3 - do you mean pin 2?

@MarkSmith Thanks ... I indeed made a mistake (and also in item 1, where I meant pin 2). In item 3 I only wanted to mention pins 4 and 5.

See the [tag:softwareserial] tag.

@CL: I think I should really do some testing for MIDI with software serial.

I suggest you have a look at the 4051 or 4052 chip (datasheet). The 4051 is a 1:8 analog multiplexer while the 4052 contains two 4:1 multiplexers. So basically it allows you to switch one pin on your Arduino to any out of 4 or 8 MIDI circuits.
In the case of TX, it's really simple. You just need a pullup resistor on each output so that the pins don't float when not switched to.
In the case of RX, you have to make sure that you don't miss any transmissions. If your MIDI sources are not sending simultanously, that's easy as well... but probably they are. In that case you cannot use an existing RX UART. Since MIDI is very slow, you could still switch back and forth between the inputs and catch all the bits (you would be writing a software UART then). But if you're not short of pins, it would be much easier to just use SoftwareSerial for one input.

Thanks for the answer, for output this would work great. I tried before using a software serial, but didn't work out well. However, good to know that at least for output there is a good way.

I'm pretty sure this would also be a good way for RX. It's just more work to implement, but MIDI is really so slow that you could mux between several ports and still catch all the bits. I'm doing serial reading by bit banging at 160 KHz on an ATtiny running at 8MHz, so a 16MHz Arduino should be able to handle roughly 10 MIDI inputs through one multiplexed digital input pin.

Hmm I tried long time ago (this is an old post) and I got regularly missed MIDI messages.

As MIDI is not clocked, it's crucial to get the timing right. You've got 32 microseconds per clock cycle which is not too bad, so once you detect the start bit, the data bits should be sampled at t+32us, t+64us etc. I'm getting curious what your application is :)

My app is initially to build a device that can receive different MIDI channels and 'process'/change these and send it back to other MIDI channels (or different messages). The message processing should be very configurable (so software is more complicated, but I am a programmer).

I decided some time ago to use STM32 since these have more serial ports and are faster (CPU). These have depending on the type 5 or 6 UARTs.


text:
Non-blocking SoftwareSerial.Write
How to use SoftwareSerial.Write without blocking if buffer is full? Serial.write blocks if the buffer is full. So I need to check Serial.availableforwrite before calling write to prevent blocking. But there is no SoftwareSerial.availableforwrite. How can I use SoftwareSerial.Write without blocking?

AltSoftSerial has availableForWrite()

What's your use case for Software Serial?

In short, you don't.
The SoftwareSerial implementation for AVR doesn't have an outbound buffer at all.
It just turns the interrupts off during each character outbound and it sends them all immediately.
This means a call to SoftwareSerial's write simply will block until all of the data you've tried to send has in fact been sent.  If you can't afford to wait for your data to go out on the TX line now, then it's up to you to send it later when you can afford to wait.
SoftwareSerial has no flow control.  When you write(), the data is sent out on the TX pin regardless of whether anything is present on the other side of the connection.  And when present, the data is still transmitted regardless of whether other side considers itself "ready" to receive.  There's simply no feedback from the receiver to tell the sender to stop.  So SoftwareSerial itself will never block owing to these things.

This means I can call Write whenever I want without a risk of blocking my main program?

I've updated the answer in attempt to address that.

My problem is I can't make sure someone is listening or not. For the program it is not important if someone is listening, but ending in a deadlock is inacceptable.

Updated again in attempt to address that.

Thank you. That helped a lot.

Is the last part (no flowcontrol) identical to the normal Serial.write? So I don't have to check Serial.availableforwrite for Serial.write too?

For Serial (HardwareSerial) on UNO (you have tagged), there's also no flow control between the ATMega328P chip and the serial transceiver (ATMega#U2 or FTDI, CH340, etc).  So it will not block owing to flow control.  You can fill the transmit ring buffer and have to wait for the USART transmit interrupt to drain that ring buffer.  But it will not deadlock.

Thanks again 3moreWords


text:
Bootstrap not working: Arduino MKR WiFi 1010 AP mode
I'm trying out the AP mode of the device, where it can serve as its own server. Most of the tutorials have been loading the html from the SD card. I can do the same, but the bootstrap of the website is not working. It just loads the basic version of the website. How can I fix this?
APMode.ino
#include <SPI.h>
#include <SD.h>
#include <WiFiNINA.h>
#define WEBHTM "SERVER/index.htm"

///////please enter your sensitive data in the Secret tab/arduino_secrets.h
char ssid[] = "MKRTEST";        // your network SSID (name)
char pass[] = "PASS";    // your network password (use for WPA, or use as key for WEP)
int keyIndex = 0;                // your network key Index number (needed only for WEP)

int status = WL_IDLE_STATUS;
WiFiServer server(80);

File webFile;

void setup()
{

    //Initialize serial and wait for port to open:
    Serial.begin(9600);
    while (!Serial);

    Serial.println("Access Point Web Server");

    // check for the WiFi module:
    if (WiFi.status() == WL_NO_MODULE) {
    Serial.println("Communication with WiFi module failed!");
    // don't continue
    while (true);
    }

    if(!SD.begin(4))
    {
        Serial.println("SD card not found!");
        while(1);
    }

    if (!SD.exists(WEBHTM))
    {
        Serial.println("missing index.htm!");
        while(1);
    }

    String fv = WiFi.firmwareVersion();
    if (fv < WIFI_FIRMWARE_LATEST_VERSION) {
    Serial.println("Please upgrade the firmware");
    }

    // by default the local IP address of will be 192.168.4.1
    // you can override it with the following:
    // WiFi.config(IPAddress(10, 0, 0, 1));

    // print the network name (SSID);
    Serial.print("Creating access point named: ");
    Serial.println(ssid);

    // Create open network. Change this line if you want to create an WEP network:
    status = WiFi.beginAP(ssid);
    if (status != WL_AP_LISTENING) {
    Serial.println("Creating access point failed");
    // don't continue
    while (true);
    }

    // wait 10 seconds for connection:
    delay(10000);

    // start the web server on port 80
    server.begin();

    // you're connected now, so print out the status
    printWiFiStatus();
}

void loop() {
  // compare the previous status to the current status
  if (status != WiFi.status()) {
    // it has changed update the variable
    status = WiFi.status();

    if (status == WL_AP_CONNECTED) {
      // a device has connected to the AP
      Serial.println("Device connected to AP");
    } else {
      // a device has disconnected from the AP, and we are back in listening mode
      Serial.println("Device disconnected from AP");
    }
  }

  WiFiClient client = server.available();   // listen for incoming clients

  if (client) {                             // if you get a client,
    Serial.println("new client");           // print a message out the serial port
    String currentLine = "";                // make a String to hold incoming data from the client
    while (client.connected()) {            // loop while the client's connected
      if (client.available()) {             // if there's bytes to read from the client,
        char c = client.read();             // read a byte, then
        Serial.write(c);                    // print it out the serial monitor
        if (c == '\n') {                    // if the byte is a newline character

          // if the current line is blank, you got two newline characters in a row.
          // that's the end of the client HTTP request, so send a response:
          if (currentLine.length() == 0) {
            // HTTP headers always start with a response code (e.g. HTTP/1.1 200 OK)
            // and a content-type so the client knows what's coming, then a blank line:
            client.println("HTTP/1.1 200 OK");
            client.println("Content-type:text/html");
            client.println();
            webFile = SD.open(WEBHTM);
            if (webFile)
            {
              while (webFile.available())
              {
                client.write(webFile.read());
              }
              webFile.close();
            }

            // The HTTP response ends with another blank line:
            client.println();
            // break out of the while loop:
            break;
          }
          else {      // if you got a newline, then clear currentLine:
            currentLine = "";
          }
        }
        else if (c != '\r') {    // if you got anything else but a carriage return character,
          currentLine += c;      // add it to the end of the currentLine
        }
        if (currentLine.endsWith("POST /enterCredentials")) {
        //   digitalWrite(led, HIGH);               // GET /H turns the LED on
        Serial.println("Hello there!");
        }
      }
    }
    // close the connection:
    client.stop();
    Serial.println("client disconnected");
  }
}

void printWiFiStatus() {
  // print the SSID of the network you're attached to:
  Serial.print("SSID: ");
  Serial.println(WiFi.SSID());

  // print your WiFi shield's IP address:
  IPAddress ip = WiFi.localIP();
  Serial.print("IP Address: ");
  Serial.println(ip);

  // print where to go in a browser:
  Serial.print("To see this page in action, open a browser to http://");
  Serial.println(ip);

}

index.htm
<!DOCTYPE html>

  <title>LPS Server</title>
  <meta charset="utf-8">
  <meta name="viewport" content="width=device-width, initial-scale=1">
  <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/4.4.1/css/bootstrap.min.css">

Low Power Sensor (LPS) Server

Please enter needed Credentials

  <form action="/enterCredentials.htm" method="post">SSID:<input type="text" class="form-control" name="SSID">PASS:<input type="password" class="form-control" name="PASS">Broker/Host:<input type="text" class="form-control" name="BROKER">Device ID:
    <input type="text" class="form-control" name="DEVID"><input type="hidden" name="eof" value="#EOF">
<button type="submit" class="btn btn-primary btn-block" value="Submit">SUBMIT</button></form>

All Rights Reserved 2020

so, what does this have to do with the arduino?

I'm using the Arduino MKR WiFi 1010. The library used is the "WiFiNINA" library which has an "AP mode" where the device can act as its own mini server.

how are you getting this file? ... https://maxcdn.bootstrapcdn.com/bootstrap/4.4.1/css/bootstrap.min.css

Now I understand. I need to load the stylesheet from the file in the SD card. This won't work without internet connection. The only problem is how I can do that.

Any ideas or suggestions would be greatly appreciated. Thank you.

take the css file, copy it to SD card and modify the path in html file

there is no reason for sending headers in a command line ... client.println("HTTP/1.1 200 OK"); .... just put the header lines at the top of index.htm

@jsotola, then it would not be a valid html file to debug it on PC


text:
Getting a fixed sampling rate
Ultimately I will move to a generic smart phone for this project.
I'm trying to read 4 analog inputs from my arduino with a fixed 1kHz sampling frequency. I managed to set it to read at 1kHz as you can see from this link. The issue is that after running several times, I kept testing the frequency by logging the time vector (produced by arduino to the serial terminal) into Excel and calculating the frequency using the equation:
f=1/(t2-t1)
I did this to the entire column and I noticed that I got a changing frequency. The difference is very big as it ranges from 780 to 1kHz. I need a fixed sampling rate because we will be applying some digital signal processing on the obtained results which obviously requires a sampling frequency. My code to send the data is the following:
#define INTERVAL_LENGTH_US 1000UL

unsigned long previousMicros;
#define FASTADC 1
int recValue;
// defines for setting and clearing register bits
#ifndef cbi
#define cbi(sfr, bit) (_SFR_BYTE(sfr) &= ~_BV(bit))
#endif
#ifndef sbi
#define sbi(sfr, bit) (_SFR_BYTE(sfr) |= _BV(bit))
#endif
double t = 0;

void setup() {
  int start ;
  int i ;

#if FASTADC
  // set prescale to 16
  sbi(ADCSRA, ADPS2) ;
  cbi(ADCSRA, ADPS1) ;
  cbi(ADCSRA, ADPS0) ;
#endif

  Serial.begin(115200) ;
}

void loop()
{
  unsigned long currentMicros = micros();

  if ((currentMicros - previousMicros) >= INTERVAL_LENGTH_US)
  {
    previousMicros += INTERVAL_LENGTH_US;

    int val_a0 = analogRead(A0);
    int val_a1 = analogRead(A1);
    int val_a2 = analogRead(A2);
    int val_a3 = analogRead(A3);

    Serial.print(((double)currentMicros) / 1000000UL, 5 ); // 1 is the number of decimals to print
    Serial.print('\t');

    Serial.print(val_a0);
    Serial.print(',');

    Serial.print(val_a1);
    Serial.print(',');

    Serial.print(val_a2);
    Serial.print(',');

    Serial.println(val_a3);

  }
}

Ps. I'm using Arduino Leonardo,
What's the right way to achieve this?
EDIT: Thank you all for responding, As you wanted to see my data, here is a screenshot of the results after I applied Jwpat7's suggestion:

The yello shaded column is the frequency calculated, the first and 2nd columns represent T1 and T1 (T2 is just T1 shifted upward for easier calculation). You may notice the Matlab section, this is because I'm trying to plot the data in Matlab and use it to do the digital signal processing after transmission. The plotting will be real time (I'll the data in txt files for later processing). the bottom potion of the figure shows the frequency after a while....as you can see it's decreasing!
Thanks

Comments are not for extended discussion; this conversation has been moved to chat. Comments are also not for answering the question, or for discussing various possible solutions. Comments on questions are for clarifying the question. That's it!

You can speed your code up slightly by sending a raw microseconds reading, rather than divided by 1000000.  Floating arithmetic on typical Arduino devices can be quite slow.  Also, the time to complete a divide is data dependent, so may occasionally but not always delay the next reading; that is, the division may contribute to jitter as well as overall slowness.
Another source of jitter is polling via loop() rather than within loop [see below].  However, this probably adds only a few microseconds of jitter.
To test if too-slow serial transmission is the problem, you could comment out all the serial printing and substitute Serial.println(currentMicros).  (Or print the low two bytes of currentMicros.)

Polling within loop(): You could replace
currentMicros = micros();
if ((currentMicros - previousMicros) >= INTERVAL_LENGTH_US)
  {  ...  }

with
while (micros() - previousMicros < INTERVAL_LENGTH_US) ;
currentMicros = micros();
...

This would tighten up the busy-wait loop and reduce jitter slightly.
If small changes as suggested above don't resolve the problem, you might need to use timer-based interrupts interrupt flags to schedule trigger ADC reads (as suggested in comments) and/or create a circular data buffer to make data collection timing less dependent upon data transmisssion timing.
The ADC Auto Trigger Source Selections table in the ATmega32U4 datasheet shows the ADTS bit settings to select various ADC trigger sources, which include Free Running, Analog Comparator, External Interrupt Request 0, and various Compare/Overflow/Capture events on Timer/Counter0, 1, and 4.  Your ADC conversion-complete interrupt handler would need to read the ADC, store the reading, set a volatile flag to tell loop() which reading is ready, and set the ADC input selection to the next channel.

Edit 2: Where the code spends its time: In the version that busy-waits until the next time-mark arrives, and then takes four ADC readings, the process sits and waits for the ADC to complete.  With a standard prescale factor of 128 and 104 μs per conversion, about 416 microseconds are spent waiting on ADC completion.  If FASTADC is set and prescale is 16, giving 13 μs per conversion, then only 52 μs is spent in that waiting.  In brief: use of a standard prescale factor will probably use up too much time if the polling method is used.  But if readings are timer-interrupt triggered and ADC-ready-interrupt stored, a standard prescale factor is ok.
Serial transmission rate estimates:
As noted in Edgar Bonet's  answer, 115200 bps isn't fast enough to support 1000 Ascii-data serial transmissions per second.  If working at 100% throughput, that data rate allows only 115 bits per transmission, or 11.5 characters, which typically is not enough for the data you are sending.  Additionally, sending the time in Ascii adds another digit to the transmission length at the 10 second and 100 second marks, which may account for the observed slowdown in the "Test ARDUINO" scenario.  (The slowdown in the Matlab case may be due to rapidly-growing memory use by Matlab; possibly try less-accurate plotting, or narrower plots, or a specialized graphing program.)
Edgar Bonet's code sidesteps this problem by transmitting data from a fixed-length (8 byte) buffer in binary, hence the 80000 bps figure he mentions (8 bytes times 10 bits per serially-transmitted byte times 1000 readings per second).  Since ADC readings are timer-triggered, there probably is no real need to transmit a clock time with each reading, but resynchronization (in case of lost bytes) might need to be added somehow.  Possibly one could send a 9-byte packet at each transmission; the extra byte would allow use of a protocol to support error-detection, resynchronization, periodic clock readings, and packet counts.

I am not suggesting timer-based interrupts, I suggest using the “auto-trigger” feature of the ADC to trigger the conversion on a timer event. This is based on the timer interrupt flag (i.e. event detection) and works irrespective of whether the corresponding interrupt is enabled or not.

@EdgarBonet, I've edited accordingly

@jwpat7 That's what I was doing, I did the time and voltage conversions in Matlab since I will be plotting my data there. I added the division to Arduino's sketch just when I was trying to find out if the jitter was from Arduino's side or from Matlab. I edited the question to explain what I mean on the screenshot. As you can see the freuqency starts high then it gets lower. Even worse, the readings from Matlab (when I read via Matlab the second time) have lower frequency with the same decreasing frequency after a while.

I know Matlab is not the best option, I'm open to use a faster multi channel plotting tool if it's going to help but I need to make sure that the results are solid from Arduino's side first.

@Isra, I edited answer.  Note, if you don't have a convenient way to read binary data, to have enough serial throughput for Ascii data, slow things down to 800 or 750 Hz instead of 1000, or try some of the higher bps settings like 250000 or 1000000.  However, general purpose PCs may have trouble keeping up at those rates.

I tried to go for 250000 baudrate and 500us sampling period (to get 500 Hz frequency) but the results were in the range of 900 Hz and also alternating between different values in this range. I've used Leonardo and Pro Micro to test several times, each trial gave me different results. It's strange that the frequency is in the 900HZ range when I set it for a lower range, what am I missing?

@Isra, 500 μs = 2000 Hz :)

That was a horrible mistake! I changed to 2000us and I managed to get a consistent 500 Hz! I guess it's not meant to handle that high frequencies. We'll have to see if 500Hz will give us similar results after the data is processed, if yes, then we can work with the 500 Hz. Now I need to plot it but when I send it to Matlab, data is mixed and I get so many different frequencies. Any suggestions to a fast and good tool to realtime plot and log the 4 channels in an excel or txt file?

Expanding on my previous comments...
The only reliable way to get jitter-free ADC readings is to trigger the
ADC from a timer event. I wrote the following program to demonstrate the
approach on an Arduino Uno, as I don't have a Leonardo. The program
configures the Timer 1 to set it's overflow flag every 250 µs, and
the ADC to start a conversion on every rising edge of that flag. When
the conversion is done (104 µs after it started), the ADC ISR
fires. It's job is to retrieve the conversion result and set the analog
multiplexer for the next channel, switching round-robin through channels
0 – 3.
volatile int adc_readings[4];
volatile bool fresh_readings;

// Used only to clear the interrupt flag.
EMPTY_INTERRUPT(TIMER1_OVF_vect);

ISR(ADC_vect)
{
    static int buffered_readings[3];
    static uint8_t channel;

    if (channel == 3) {

        // "Export" the 4 readings at once.
        adc_readings[0] = buffered_readings[0];
        adc_readings[1] = buffered_readings[1];
        adc_readings[2] = buffered_readings[2];
        adc_readings[3] = ADC;
        fresh_readings = true;
    } else {

        // Buffer the current reading.
        buffered_readings[channel] = ADC;
    }

    // Move to next channel.
    channel = (channel + 1) % 4;
    ADMUX = _BV(REFS0)  // reference = Vcc
          | channel;
}

void setup()
{
    Serial.begin(115200);
    Serial.write("================");

    // Configure the ADC.
    ADMUX  = _BV(REFS0)   // reference = Vcc
           | 0;           // channel = ADC0
    ADCSRA = _BV(ADEN)    // enable
           | _BV(ADSC)    // start first conversion
           | _BV(ADPS0)   // prescaler = 128
           | _BV(ADPS1)   // ...ditto
           | _BV(ADPS2);  // ...ditto
    ADCSRB = _BV(ADTS1)   // trigger source = Timer 1 overflow
           | _BV(ADTS2);  // ...ditto

    // Wait for and discard the first conversion.
    loop_until_bit_is_set(ADCSRA, ADIF);

    // Configure Timer 1 to overflow every 250 us.
    TCCR1A = _BV(WGM11);  // fast PWM mode, TOP = ICR1
    TCCR1B = _BV(WGM12)   // ...ditto
           | _BV(WGM13)   // ...ditto
           | _BV(CS11);   // clock at F_CPU/8
    TIMSK1 = _BV(TOIE1);  // enable overflow interrupt
    ICR1   = 500 - 1;     // period = 500 * 8 CPU cycles

    // Set the ADC to auto-trigger mode.
    ADCSRA |= _BV(ADATE)  // enable auto-trigger
            | _BV(ADIF)   // clear interrupt flag
            | _BV(ADIE);  // enable interrupt
}

void loop()
{
    if (fresh_readings) {
        Serial.write((uint8_t *) adc_readings, sizeof adc_readings);
        fresh_readings = false;
    }
}

A few comments:

The Timer 1 overflow interrupt is used only to clear the timer
interrupt flag. The flag has to be cleared because the ADC is
triggered only on it's rising edges. Alternatively, that flag could be
cleared inside the ADC ISR.
I choose to deliver the readings by batches of 4 (one reading per
channel), thus the buffering inside the ADC ISR. The choice is
arbitrary: you can, if you wish, transmit the readings as they come,
as suggested in jwpat's answer.
The very first ADC reading is manually started and discarded. The only
reason for this is that it takes longer (200 µs instead of 104).
The readings are transmitted in binary form at 115.2 kb/s. The
effective data rate is 80 kb/s. ASCII would not be possible at
this sampling rate.
The loop() function must never take more than 1 ms to execute,
otherwise there is a risk of it reading the adc_readings array while
the ADC ISR is updating it, which would lead to corrupt data.
Protecting the access to adc_readings inside a cli()/sei() pair
would not significantly ease the timing constraint, as a long loop()
execution would still carry the risk of loosing data points.

From a cursory look at the ATmega32u4
datasheet
it would seem it's Timer 1 is identical to the one of the ATmega328P
powering the Uno, save for an extra PWM channel. The ADC, however, is
slightly different, but similar enough to make porting fairly
straightforward. At least the setting of ADMUX would be different.

I have an Uno so I can try this and see how it works. I have little eperience in programming Atmega in the low level but I understood what you meant. One poit which wasn't clear to me though is 4th comment. I know that the ADC's readings re 10 bits each, so I will need to transmit 2 bytes for every reading and then reconstruct them in the recieving end (in my case Matlab). wouldn't that be slower than sending ASCII?

What you have here is a classic case of the measurement of something changing what is measured.
I guessed when I saw your question that the time taken to transmit all that serial data would be longer than 1 ms. If you really were transmitting at 115200 baud then it would take 2.6 ms to send the 30-odd bytes you are sending (30 * 1/11520). Since you are using a Leonardo you get USB speeds which is faster but not infinitely fast.
I could reproduce your figures when I tested.
However if I comment out the two lines that send the time:
//    Serial.print(((double)currentMicros) / 1000000UL, 5 ); // 1 is the number of decimals to print
//    Serial.print('\t');

And also measure separately by toggling pin 13:
  if ((currentMicros - previousMicros) >= INTERVAL_LENGTH_US)
  {
    previousMicros += INTERVAL_LENGTH_US;
    digitalWrite (13, !digitalRead (13));

Then I found that pin 13 toggled at exactly once per millisecond.
(edit) Close enough. See screenshot of logic analyser (0.996 ms):

That is only 4 µs out - within error range for the processor clock.
Uncommenting the timing code I found that for a short time I still got 1 ms per iteration, but it then dropped down to around 1.04 ms (ie. 960 Hz). I am guessing that some USB buffer, somewhere, is filling up and not being emptied as fast as you would like.
Here is the screenshot of the code which sends the time (1.0366 ms):

Notice how simply sending the number of microseconds has increased the time between toggling the pin?

It is helpful to have extra hardware to hand to measure things like this. Using the processor that you are trying to time, to send its own timing information is fraught with problems.

Can you explain to me how you found the frequency by toggling a digital pin? is there a counter that does that?.....I tried to go for 250000 baudrate and 500us sampling period (to get 500 Hz frequency) but the results were in the range of 900 Hz and also alternating between different values in this range. I've used Leonardo and Pro Micro to test several times, each trial gave me different results.

See amended answer.

I tried to go for 250000 baudrate - on the Leonardo and Micro the baud rate does not affect the results. I set the baudrate to 1 (lol) and still got the same results. The Serial output goes to the USB interface, bypassing the concept of baud rates.


text:
MIDI connectors / Diodes
Does anybody know if the following MIDI DIN connectors will fit in a breadboard?
(or in general with 'generic' electrical components?)
MIDI DIN
And the same for:
Diodes to be used for MIDI in.

What does the footprint diagram in the datasheet tell you?

There are dimensions (no real datasheet), but since the pins of the Arduino breadboard are like 2 mm apart I guess it would work.

2.54mm to be precise. It's a 0.1" grid.

Breadboards use a 2.54 mm (0.1") grid. The PCB footprint on that link uses a nominal 2.5 mm grid, which is essentially the same:

However, those pins are rather large; it's possible that you need to rotate some pins by 90° (with pliers and brute force) to make them fit into your breaboard's holes, or that they do not fit at all. And even if they fit, they can ruin your breadboard.
You might need to file them off.
Consider using a panel-mount MIDI jack instead (which would require soldering, or leads with test clips):

(search for "5 pin DIN female jack")

The MIDI specification recommends a 1N914 diode, but that is only because it was written over thirty years ago. The 1N4148 is much more common now, and has the same characteristics. But this diode is used only as reverse voltage protection for the optocoupler's LED, so you can use any random fast switching diode.

As for the optocopler (which you didn't mention, but I'll throw in my two cents worth anyway): the PC900 was discontinued, and the 6N138 is slow. Use either the H11L1 (of which the PC900 was a clone) or the 6N137; both work best with a 1 kΩ pull-up resistor.

Thank you for all this useful information. I need to check for soldering, no experience with that either (and I'm not so handy). And thanks for the other  info too... I almost wanted to buy that specific 1N914 diode and 6N138. Sorry, I don't have much electrical knowledge (yet).

All those PCB-mount DIN jacks have the same footprint.

It's almost impossible to destroy anything if you try to solder thinner wires to the pins … :)

That's true maybe... however, the problem with thinner wires is that it the MIDI connectors will be not really placed directly in the board probably (meaning like resistor wires they will moving) and to regularly replace MIDI cables) which are heavy I hoped for a MIDI connector (or more) that can be inserted without any issue.
This one looks really much like the one I posted in my question and is prototype friendly: https://www.sparkfun.com/products/9536
Also I have to check into test clips.

authors: Валерий Ряпосов


text:
Slave SPI does not work
I am trying to use both an SRAM (23LC1024) and SD card reader on an SPI bus.
My connections (for SPI):

Arduino pin 11 (MOSI) -> SRAM pin 5 (SI/SIO0)
Arduino pin 12 (MISO) -> SRAM pin 2 (SO/SIO1)
Arduino pin 13 (SCK ) -> SRAM pin 6 (SCK)
Arduino pin 10        -> SRAM pin 1 (CS )

In this way, I can read data from the SRAM.
To connect the SD I connected:

SRAM pin 2 (SO/SIO1) -> SD MISO
SRAM pin 5 (SI/SIO0) -> SD MOSI
SRAM pin 6 (SCK    ) -> SD SCK
Arduino pin 9        -> SD CS

Currently the SD card works, but read-byte commands to the SRAM always gives the same (wrong) value.
If I remove the wire between SRAM pin 2 and SD MISO the SRAM gives correct values, but the SD card does not have a MISO connection and seems to always return the same data (but still functions).
I also tried to first make the connections from the Arduino to the SD and than to the SRAM (but same result, not working).
What am I doing wrong?
Update: The problem is solved, however I do not understand why. I reconnected all pins, removed the shield to access the SRAM directly which worked. Than I put the shield back on (and moving the pins back) ... maybe it was something stupid that one pin did not have good contact. I'm sorry for the inconvenience.
New question (related):
Now it works with the Data logger shield, but not with the (cheap) SD reader breakout cards.
However, my eventual solution needs more proto space than is available on the Data logger shield.... do I really need to use a complete shield (and later the Arduino Mega), and a Mega proto shield ... that will be a big box.
While for the data logger, I don't need the RTC neither.

It doesn't sound like you are doing anything wrong as such, it all sounds fine.
However SD cards, certainly some cheap ones, don't like to play nicely with other devices on a shared bus. Also some SD card adapters with level shifting don't play nicely.
By not playing nicely I mean tri-stating the MISO line in a timely fashion (or at all in some cases) which stops any data getting out of other devices, and can even cause damage in some cases.
You should check out the level shifting on the SD card adapter to see if it has tri-stating control of MISO (if it is shifting that line, not all do), try other brands of SD cards, and maybe add your own tri-state buffer to the SD card signals.

It is for this reason I always use an SD card on a dedicated SPI bus rather than sharing it.

Mine is very cheap so maybe that is the reason.
I'm new to electronics, but how should I check the level shifting of the adapter if it has tri-stating? I don't have an oscilloscope ... I have one other SD card. Also I have an SD protoshield, but that one is so huge, I definitely do not want to use it in a prototype.

You say it may not play nicely on a shared SPI bus, but afaik the Arduino has only one SPI bus ... so how I can prevent it sharing while having two SPI devices?

Without a scope you can guess and try.  It is the harder way to do this.  For example, in your case we can disconnect the MOSI pin from the SRAM and see if we then can talk to the SDCard.  To verify we can replace the SRAM's MOSI pin and disconnect the MOSI from the SDCard and verify we can talk to the SRAM.

Arduino's now are made with many different processors.  Some have more hardware (more SPI buses) than others.  Also, there are now many Arduino libraries some which might emulate a SPI bus.  However, such libraries usually run slower than hardware and such libraries usually place a heavy burden on the processor not leaving much time to do other things.

I work almost exclusively with PIC32. Some have 4 or more SPI buses. You need the schematic of your SD adapter.

I tried a shield (datalogging sheet) and have approximately the same problem there ... SD card works, but SRAM gives always a value (different than with the breakout SD card reader).

@st2000: I tried this, the SD works OR the SRAM works, but not both at the same time

@Majenko I just got in the world of Arduino, so I don't know if I already want to step over at such a short period (I don't like quitting so easily). But I will check if the Mega has more SPI busses ... I have one in order and need to use it anyway to have more UARTs.

I tried to use 2 resistors to the MISO line (for the tristate behavior), but it does not work, so I use the SD data shield which works ok.