Interaction between Analog Pins when measuring a DC voltage- a common issue?

This is normal and expected behaviour.  There are a number of factors that influence it, and it will help to understand the basic internals of the ADC.

In simple terms the front-end of the ADC looks like this:

simulate this circuit – Schematic created using CircuitLab

The MUX selects which pin (A0-A5) is being sampled. Switch SW1 connects the Sample And Hold capacitor C1 to that selected input, which then charges (or discharges) to the same voltage as the input.

After the acquisition period switch SW1 switches position and the ADC circuit is connected to the capacitor.  Over a period of clock cycles the ADC works out what the voltage across the capacitor is and stores the result in the ADCH and ADCL registers.

Now - on a pin that has nothing connected to it, what voltage will be across that capacitor when SW1 is switched to charge it? Well, this is where your strange results come from:

Any charge already in the capacitor will still be there (which is why it can be good to connect the unused ADC pins to ground through a resistor, to remove that charge).
Signals, either in wires, IC pins, or the silicon circuitry in the chip itself, will be capacitively coupled with what is next to it.

That last one is the most critical for your results.  Capacitive coupling.

Place two wires next to each other and they will, through capacitance, try and get the same charge on them. Under most circumstances that attempt to influence the charge is completely swamped out by what is being send down the wire. But, when there is nothing being sent down the wire that charge becomes noticable. A1 will attempt to "float" to the same level as A0, because they're next to each other. A2 will try and float to the same level as A1, A3 to A2, etc.

If you put a signal in to A0 and plot all 6 inputs you will see each has a progressively lower amplitude copy of the signal. It's hopping, capacitively, between the pins. And all because there's nothing to stop it.

If you think "Ah, but it's DC. DC doesn't go through capacitors", then you're wrong.  Wrong in thinking it's DC.  There's a lot of mistaken assumptions about the labels "AC" and "DC".

DC is not what you have.  Yes, there is a "DC component" to what you have (which is manifest as the average of the voltage over time), but there is a large AC component as well.  That AC component is what you are graphing in the form of your changing battery voltage.

Voltage is far more complex than just DC or AC. What you think of as AC is actually a waveform with a fundamental frequency (e.g., 60Hz) and zero "DC offset". Add a DC offset to the signal and it's still AC, but compared to the "lower" end of whatever adds the DC offset, it's just the waveform is "shifted up".

Pure DC, and what doesn't pass through a capacitor, has no signal components. There is only 0Hz and nothing else. Pure DC is almost impossible to create without highly specialized equipment. All voltages in normal life vary, and that variance is the AC component of the signal.


Arduino UNO and TB67H303HG Ic driver: Wiring question

The Vref potential should not be 24V. As mentionned in the datasheet:

Vref = 0.3V to 1.95V depending on what you want.


Why Are My High and Low Values Not Updating Correctly During Successive Loops

Although you already have two perfectly valid answers, I will share a
trick that completely sidesteps the problem. Instead of choosing a
particular number (here, 10,000) as a “magic” value that has a special
meaning, you can instead initialize the highs and lows in a way that
ensures they will be updated on the very first iteration:

make lTemp higher than any temperature you may ever read
make hTemp lower than any temperature you may ever read

For example:
float lTemp = +INFINITY;
float hTemp = -INFINITY;

and the same of course for the humidities. This way the first iteration
does not need special handling anymore, as it becomes a regular
iteration:
if (CurrTemp < lTemp) lTemp = CurrTemp;
if (CurrTemp > hTemp) hTemp = CurrTemp;

Note that the choice of ±∞ for the min and max of an empty set of
readings is not just a dirty hack. It is actually consistent with the
mathematical notion of infimum and supremum of the empty
set.


Where is the documentation for writing an Arduino core?

There are two major parts to writing an Arduino core: the hardware independent portions and the hardware dependent.
The hardware independent portions are pretty much done for you in the ArduinoCore-API. However I wouldn't just use that verbatim but use it as a starting point and adapt it to your needs. This is because it actually has a couple of unresolved issues and not everything may 100% fit your needs. We don't use it for the chipKIT core because:

It has an unresolved issue around the naming of the String.h file which conflicts with the libc's string.h on case insensitive filesystems
Our USB stack is vastly different to how the Arduino "Pluggable USB" works
We have extra facilities in a number of standard objects to make use of more efficient use of more advanced hardware

Once you have the hardware independent portion sorted you need to write, from scratch, the hardware dependent portion.  The basic list of functions you need to implement are listed in the Arduino reference. How you write them cannot be documented, since that depends on the hardware. And you may well need to (or want to) write considerably more functions that just those. For example on chipKIT as well as the standard analogWrite() function we also have functions to change the PWM frequency and resolution - things that aren't part of the "standard", but are incredibly useful.
A good starting point is to examine the Arduino.h file of an existing core (the AVR core is a good baseline) which will list most of the functions and their parameter/return types. That gives you what the functions expect to receive and what they should emit, but how those functions are written is completely down to you.
And then of course you have to implement the boards variants etc to make the whole things work...
Also, be warned that writing (and maintaining) a core is a long and involved process and will consume the rest of your life.


How to communicate with GPS SIM900a without Serial Monitor

Well, I too had the same problem until now. The simple way to fix is just to delay the void setup() before Serial communication begins. Add delay(15000); //15 Seconds so that GSM module boots up and connects to the network. And there is no need of changing any part of code. Hope this helps someone out there like me. :)


Avoiding false rising and falling edge when using demultiplexer

To do multiplexing with bounce.h you will need one bounce object per button. That's 64 bounce objects for an 8x8 matrix.

Then you only want to update the bounce objects for the group you currently have active.

That is:

Switch to group 1.
Update objects 1-8
Switch to group 2
Update objects 9-16
... etc ...

You need one object per button so that the internal data can track the state of that specific button, and you only update the 8 objects for the currently selected group otherwise the objects that aren't associated with that group will get confused by incorrect data.


The Cortex M does not "have RAM at 0x2000000". The Cortex M is just a CPU. It is down to the chip manufacturer where they choose to place RAM in the memory map.

In the case of the MKL26Z64VFT4 used on the Teensy LC:

  The on-chip SRAM is a single contiguous block split into two ranges: 1/4 is allocated to SRAM_L, and 3/4 is allocated to SRAM_U. Regardless of the block size, the SRAM is implemented such that:

  SRAM_L is anchored to 0x1FFF_FFFF and occupies the space before this ending address.
  SRAM_U is anchored to 0x2000_0000 and occupies the space after this beginning address.

  Valid address ranges for SRAM_L and SRAM_U are then defined as:

  SRAM_L = [0x2000_0000–(SRAM_size/4)] to 0x1FFF_FFFF
  SRAM_U = 0x2000_0000 to [0x2000_0000+(SRAM_size*(3/4))-1]

Since there is 8kB of SRAM, 2kB is below 0x2000000 and 6kB is above 0x20000000. 2kB is 0x800. 0x2000000 - 0x800 = 0x1FFFF800.


Arduino Mega 2560 interrupt pins and port mapping with rotary encoder

Re “pins 2 and 3 are different. I think on the Mega they are PORTH3 and PORTH4 respectively”, it's true that Arduino digital pins 2 and 3 belong to different ports on Uno vs Mega2560 boards.

Mega2560's have six INTx pins, vs two such on Uno's.  On the Mega, INT0...INT3 are PD0...PD3, and INT4,INT5 are PE4,PE5.  On the Uno, INT0,INT1 are PD2,PD3.  Note, in an answer at Can external interrupts be OR'd together on the '328 (Uno)? I show a couple of routines that will display appropriate masks for pins on different Arduinos.  See the sections “Using other pins for PCIs” and “ISR-framework-generating Sketch”.

Here are a few problems with the code shown in the question:

aFlag is initialized to zero, and is never set nonzero in the code shown.  So the first if condition in PinA() is never met.
PinA() is an interrupt handler, connected to interrupts by your attachInterrupt() calls.  Because hardware disables interrupts before it enters an interrupt handler, there is no need for the interrupt handler to turn off interrupts.  That is, delete cli() in PinA().  Similarly, delete the sei() at the end of PinA() because hardware restores interrupt status when a RETI instruction executes.
The Arduino software environment defines constants like B00001100 with binary values that match the name.  That is, in the Arduino software environment, constant B00001100 has the value 0B00001100.  In my opinion, that's a stupid and unnecessary feature; I suggest that in your code you use standard C notation like 0B00001100 when you want to use binary constant values.
I regard writing encoderPos -- instead of encoderPos-- as a perversion and suggest deleting that unnecessary space.
As you haven't shown the PinB() interrupt handler, I don't know how you were going to handle the encoderPos++ case.  Judging from the code shown, you are using a method that won't correctly handle bounce and intermittent errors.  I suggest using pin-change interrupts and a state-machine method, as illustrated in answers to:
• Reading from a KY-040 rotary encoder with Digispark
• How to read RPS for fast rotation with status change method in Arduino?
• Read RC receiver channels using Interrupt instead of PulseIn
• Can external interrupts be OR'd together on the '328 (Uno)?


How to make C++ code compatible with Arduino IDE?

When you run that library on the Arduino and ask it to open a file, where do you imagine it would read the file from? Your Arduino has no hard disk or other file system.

One way to solve this is to include a library that emulates a read-only file system in the Arduino's flash. I dunno whether this exists (such libs do exist for for some other targets, for instance for the Nintendo DS), but it would be a bit of overkill IMO.

Another way is to include the data that is in the file in your program, as a const (expr) array of bytes, and read from that array instead of from the file. But if you have a library that is coded to use file read calls this would require some rewriting.

A third approach would be to do the reading and interpreting of the file on your host PC, output the interpreted content to a const (expr) byte array, and include that in your application. This frees you from having to include the bmp-read code in your image.


Weird formatting behavior with sprintf function

Sometimes the sprintf can be used instead of 20 lines of code. In this case an array with integers and a loop with Serial.print would be better as Majenko already wrote.

When you do use the sprintf, a shift in the data means that one of the parameters has too many or too little bytes. The sprintf does not know the size of the parameter and the parameter will not be converted to a different type. When you use "%d", you have to put two bytes on the stack. Since your 'x' is 4 bytes, all those 4 bytes will be put onto the stack. The first "%d" reads two bytes of 'x' and the second "%d" read the other two bytes of 'x'. That is why it is shifted.

For a data rate of 50Hz, I suggest to raise the baudrate to 115200.

Using millis() for the 50Hz will result into the same timing accuracy as you have now. You don't need the timer and you don't need the interrupt.
See the BlinkWithouDelay example and use 20ms as an interval.


How to have code/sketch that's easily toggleable to work on different nodes

You can put the per-node parameters in a external EEPROM and load them during setup(). For example the IP address is the first 16 bytes of the eeprom (IPv6), the next bytes would the the topic, etc..

That way every node has exactly the same sketch and the customization is in the eeprom that you could put in a socket and possibly have a separate programmer for them.

EEPROMs with I2C interface are easy enough to get and can store 64kB. Which should be more than enough for most things.


Receiving live astronomical coordinates on Arduino Mega using telnet and ESP8266 wifi module

That telnet interface is an interactive service. Getting an Arduino to interact with it is not an easy task - certainly not a task for a beginner with no experience of network programming.

A much easier task is to scrape the website since that just returns text which you then need to search through a bit at a time looking for the information you need.


Arduino Digital Input. Trigger HIGH by 12V to 36V

Even easier:

input - series 220 ohm resistor, and a 78L05 voltage regulator (check for maximum voltage). This allows you handling like 4..30V and get a solid "1" on digitalRead. (4V input makes like 3V output which is still logic high).


Issue in long ON OFF timer using millis()

You declare interval as an integer, while onTime and offTime are unsigned long.

Change int interval = onTime; to unsigned long interval = onTime;

The maximum value of int is only 32767 (215-1), which is only 33 seconds.

An unsigned long can be as high as 4294967296 (232-1). Which is around 49.7 days worth of milliseconds.


How to calculate illuminance from the output of a TCS34725 color sensor?

In the chip's datasheet on page 8 in the chapter "RGBC Operation" (emphasis by me):

  The RGBC engine contains RGBC gain control (AGAIN) and four
  integrating analog-to-digital converters (ADC)for the RGBC
  photodiodes. The RGBC integration time (ATIME) impacts both the
  resolution and the sensitivityof  the  RGBC  reading.  Integration  of
  all  four  channels  occurs  simultaneously  and  upon  completion  of
  theconversion cycle, the results are transferred to the color data
  registers. This data is also referred to as channelcount.

So, if you read the values from the data registers, you get simple count values, which were determined by the ADCs connected to the channels. To get a value in lux, you need to calculate that yourself.

Adafruit has a library for their breakout board with this chip. In their tutorial it seems, that the library outputs a value in lux. Maybe you can also use this library, or you can check, how they are converting the values from the sensor to lux values.


The most steightforward decision is to use this spike to trigger interrupt in Arduino. The interrupt procedure starts one of the counters and sets 1 at one of the pins. After N milliseconds by counter or by inner timer the Arduino outputs 0 to the same pin, so you will have needed length of the positive pulse. This will work while pulse length will be less then time between successive spikes. Do not forget to make standard spike amplitude enough to start interrupt, but not too big not to damage Arduino. Of course you can work without interrupts, just testing the input in main cycle, but it will be less presise. You will need a decision, how to conveniently control the pulse length by some tool. It can be infrared pult or some other tool and you must see the set time value, so you will need to use some indicator. May be LCD  1602 keypad shield will be enough for this.


You're not comparing strings - you're comparing addresses of strings.  Use strcmp().

while (
    (strcmp(userid, "A00034732") == 0) &&
    (strcmp(password, "123456789") == 0)
) {


Error:expected declaration before { token. (Havent i already declared it?)

Probably the error is in line

dht.begin();

You did not declare the variable dht, probably of type DHT11 ? You can find the correct class name in the dht.h header file.

After checking this (random) website compute heat index arduino about DHT11 I see the line:

DHT dht(DHTPIN, DHTTYPE);

Which you also have to add, probably as:

DHT dht(DHT11_PIN, DHTTYPE);


Trying to switch a 5v fan with a LiPo and can't figure our what's wrong at full duty cycle

According to specs I found online, the NodeMCU wants 7-12V on Vin. Most LiPo cells put out around 4 volts, which isn't enough. The battery voltage may drop and the MCU's voltage regulator probably fails to keep putting out 3.3V when the fan's average power draw exceeds some threshold.

It might also be that the fan itself is slowing when the duty cycle approaches 100% and the battery voltage drops.

Doesn't the NodeMCU run on 3.3V, not 5V? If you feed 5V into the 3V pin and that's supposed to have 3.3V, it will likely damage or destroy the board.


How to connect IR Transmitter and Receiver Module?

The device in the question is commonly sold on aliexpress.com and the likes of ebay.com.  As you might guess there is little in the way of documentation.  Without documentation we can only speculate.  As such, I expect that the module handles all the modulation and demodulation.  It is likely all you need to do is use the Arduino serial library and connect the TX and RX to the Arduino's RX and TX pins.  However, if you would like to preserve the function of these pins for use with the Arduino Uno's USB port, you can use the Arduino software serial library which will "emulate" a serial port an an unused (alternate) set of pins.

(This is an example of a similar well documented device with access to the schematic and source code.  Armed with this type of knowledge you can turn this device into what ever you want.  In other words, you probably don't even need an Arduino.  You can just program this device and be done with your project.)


Since you seem to need some orientation, I will explain a few things, to get you started.

The MPU6050 is a device, that communicates through the I2C interface. It uses 2 communication lines (SCL for the clock and SDA for the data). To use is with the Lilypad, you have to connect those two lines, Vcc (5V) and Ground. If you look at a pinout diagram, you can identify, which of the pads are SDA and SCL on the Lilypad.

It is up to you, if you connect the mentioned lines via soldering or by other means. Normally you would solder connecting wires between the MPU6050 and the Lilypad. If you want the MPU to be removable, you can solder a cable with a pin header (for example female) to the Lilypad and the according pins to the MPU (for example a male pin header). That way, you could also stick the MPU to the board and remove it again if necessary. How you are doing it is not important, as long as the electrical contact is good.

There are also a lot of tutorials and ready to use libraries for the MPU6050 on the net. newbie already posted a link to a tutorial. Also Adafruit has a library on github with examples, that explain how to use it. That way you should be able to get started with your project.

Good luck!


https://youtu.be/EoHD0m3uUhA. Ig this should do it. There are many more tutorials on YouTube to achieve this.


I think what @IgnacioVazquez-Abrams is getting at is:

void setup() {
  FastLED.addLeds<WS2812B, LEDCOUNT>(leds, LEDCOUNT);
}

Has LEDCOUNT showing up for both the number of LEDs and the data pin identifier.

Try:

void setup() {
  FastLED.addLeds<WS2812B, DATAPIN, GRB>(leds, LEDCOUNT);
}

This puts DATAPIN in the right place, and also adds the color order typical for WS2812B, GRB


If you're working with the standard Arduino environment and libraries then printf() won't display anything anywhere. The reason is that microcontrollers could be connected to any number of different output/communication devices in any way. stdio would have no idea how or where to send the data.

The most common approach to outputting text from an Arduino (particularly during development) is to send it to the primary UART port using Serial.begin() and Serial.print(). If the Arduino is connected to your computer via USB then the Arduino IDE's serial monitor should display the result.

If you really want to use printf() though then it is possible to make it work (or implement similar functionality). A full explanation is on this page:

http://playground.arduino.cc/Main/Printf


Why is my esp8266 still visible under "available connections" when connecting to WiFi?

It's because you don't actively program the WiFi - you just give instructions to configure it, and those instructions are stored elsewhere in flash, separate to a sketch.  The WiFi code is always included and always running regardless of what you include or don't include in your sketch.

Uploading a sketch doesn't replace those settings, and so they remain.

To change the settings you will need to write a sketch that specifically changes them - maybe set it to STA mode, for example.

If you want to completely blank the ESP8266, including the WiFi settings, there is an option in the Tools  menu in the IDE to Erase Flash.


Wemos D1 mini not being shown when connected to macbook

All of the cables I tried don't have a data line


Is there an equivalent to Grbl for Excellon PCB drilling?

No, there is no existing Arduino library to parse Excellon format drill files in order to control a drilling machine. Looking at the specification it looks to be very similar to G Code, and some brief googling shows that there are various utilities for converting it to G Code that could be run from something like grbl.


So, apparently the motors I am using have a optimal work range that doesn't start at 0 but 200PPS. Though, even generating properly the velocity ramps, when using a low acceleration, my motors would be running for some steps outside this optimal range, causing strange movements at the beginning of the movement.
In order to solve it, these non-optimal low velocities are avoided while accelerating so that motors enter directly to the optimal work area.


How to get weight data from glass electronic bathroom scale sensors?

Your four half bridge load cell sensors can connect into a full wheatstone bridge as in https://electronics.stackexchange.com/a/199470/30711

If your sensors are like this 50kg load cell from SparkFun's https://www.sparkfun.com/products/10245  or Ebay's http://www.ebay.com/itm/4pcs-Body-Load-Scale-Weighing-Sensor-Resistance-Strain-Half-bridge-Sensors-50kg-/251873576571 they might have a compression and tension gage both on the top surface. The Ebay site has a diagram like:

... which indicates a positive strain gauge on the red-white, and a negative strain on the red-black. (note that the coloring order in this diagram does not match the coloring order in this picture.  I have a similar gauge with blue-red-black colors, and the positive strain gauge is the right pair, negative on the left.) The gauged surface on the center bar between the face-to-face coupled 'E's in the sensor should act like a parallel bar and has portions under compression and under tension, rather than purely under tension.  In cross-section, the gauged bar in the center is sort of the cross-piece in a Z-shaped spring. In this case, the strains oppose each other, and, if manufactured well, the reduction of resistance in the negative strain portion will offset the increase in resistance in the positive strain portion and the total white-black resistance should be constant.  One still needs to set up the bridge so that the voltage dividers move in opposite directions with added load, and 4 devices wired in a white-to-white and black-to-black loop should work as above.

If you wire four of these up carefully by flipping them around so the stress sensitive portions unbalance the bridge constructively, you can use all four sensors without any extra resistors.

Basically, two diagonally-opposite sides of a wheatstone bridge are each formed by the compression elements of two gauges wired in series, while the remaining two sides of the bridge are each formed from two tension elements from two cells.  With load on all the sensors, the compression resistances are reduced, while the tension resistances are increased and it pulls the bridge out of balance.

To get this, wire all four sensors in a big ring with maximum resistance, matching colors and initially ignoring the red center tap wires.  (This is the function of the soldered-together blues and blacks are in your scale.)  Choose two opposite (red) center taps as E+ and E-, and the remaining two (red) center taps as S+,S-.  Put the excitation voltage on the E+/E- from the diagram above and read a force-sensitive voltage difference across S+/S-, and this is what you feed into your HX711 as A+ and A-  (Ignore B+/B- as a second, unused channel.)

Here's a schematic with gauges 1-4 as G1 G2, G3, G4 per the above specs, applying an excitation on the G1 and G3 reds, and reading the signals off the G2 and G4 reds.  The G4 gauge is loaded a bit with some positive strain increasing the G4+ resistance, and some negative strain reducing the G4- resistance.  Ideally, loading G4 with 25kg would produce 0.5mV/V times its 2.5V excitation voltage, producing 1.250mV across Sig+/Sig-, and stretching R8 to be 1001 ohms and compressing R7 to 999 ohms as shown.   (The schematic/simulator thing on electronics.stackexchange.com is pretty cool.)

simulate this circuit – Schematic created using CircuitLab

Instead of the "White" wires in the diagram and like on my gauges, consider it the "blue" wires from your scale's sensors.

With only two of these half-bridge sensors, one should not match the end colors and hook white-to-black (blue-to-black) and black-to white, (black-to-blue) imposing an excitation voltage from between these two junctions, and read the differences across the reds, as increased load pulls one side high and the other side low.  This will look like the plain 4-resistor wheatstone bridges in the common datasheets, rather than the 4-half-bridge/eight-resistor scheme above.


connection of led with dht and code combination

Only thing that gives people problems when combining two simple sketches are "delay" commands. There is just one "delay" so it's perfect.

Create new sketch
Paste everything that's not in a method from the two sketches.
Combine setup methods together by pasting first one and second one below.
Remove duplicated commands like Serial.begin(115200); from the method
Combine loop methods together by pasting first one and second one below.
Move code in loop to make the code visually pleasing (it's called the "smell" of code)

This should not be a big problem with those two particular sketches.
Please ask more precise questions as soon as you will have problems.


Leonardo Serial1 enable internal pull-up for removable Bluetooth module

Yes, what you have done is good.

It is important to tie all unused inputs to a stable state (normally low) to reduce current consumption from floating inputs.  When those inputs are actively used but not connected it is even more important to stop things happening that shouldn't.

As I mentioned, normally you'd use a pull-down, not a pull-up, but the UART is actually a special case where you would want to use a pull-up (as you have) not a pull-down.

UART is "Idle High", which means that when there is no data being transmitted on a line it is held high by the transmitter.  By adding a pull-up you are making it appear as if there is something connected but that something isn't actively transmitting at the moment.

The internal pullups aren't very strong, so in a noisy environment you may still get some spurious data on the UART.  If that happens then you want to add an external stronger (lower resistance) pull up.

Another thing to think about with your disconnected pins is to protect them from ESD.  You should have some TVS diodes on those pins to absorb spikes, and some small inline resistors to limit any overcurrent conditions.


There is this board called Bluno
Its an Arduino UNO Based board with built in Bluetooth 4.0

Bluno - An Arduino Bluetooth 4.0 (BLE) Board


You will need an Ampere meter and a Voltmeter. Watts is Volt * Ampere.

There are logic level compatible units out there for ampere meters ranging from a few mA to at least dozens of Amperes.

Also for voltmeters there are several logic level compatible units available, to plug in your project.

The rest is math. (Watts = A * V )


Arduino Uno - combined LCD and keypad interfacing problem

You could use a shift register to read the switches as outlined by the excellent tutorial Parallel to Serial Shifting-In with a CD4021BE. Quoting the summary:

  Sometimes you'll end up needing more digital input than the 13 pins on
  your Arduino board can readily handle. Using a parallel to serial
  shift register allows you collect information from 8 or more switches
  while only using 3 of the pins on your Arduino.

So you would only use 3 pins to read the seven switches, which would leave you with 9 pins to play with, for the LCD.

In addition, you could use a similar method for the LCD, using a shift-out register, and use just 3 pins for the 6 inputs of the LCD. A tutorial for that is Alphanumeric LCD with Shift Register on Arduino – part 1, using the AlphaLCD library or 3-Wire Serial LCD using a Shift Register, which has no library, but provides code.

This would leave you with 6 pins free (out of the total 12 pins, if you exclude pins 0 and 1 for serial), after both the switches and LCD are wired up.

Of course, this solution requires you to purchase one or two shift (in and/or out) registers.

The Arduino IDE may come with a built-in library that use shift registers, but I am not sure about that. Maybe someone can confirm, or refute, this?

I hope that this helps.


How to transmit more than 1 byte continually?

I want to point out here that async serial communications relies on both ends providing a clock (there is no transmitted clock signal). Thus the sender clocks out bits at the "baud rate" (eg. 9600 bits per second) and the receiver clocks them in at the same rate.

With a start bit and 8 data bits therefore you can tolerate some difference in the clocks between sender and receiver (and there will be some difference). Effectively you could probably tolerate around a 10% difference in clock frequencies, as even if they are out by 10% the sample at the receiver will still land inside the data bit of the sender.

Now if you want to transmit 64 bits you have reduced this error margin by a factor of 8. So let's say (ball park) that you can now only tolerate a difference of 1% between sender and receiver.

You now need to be pretty sure that the clocks on the respective boards are pretty accurate. The Uno, for example, has a resonator CSTCE16M0V53-R0 which appears to have a tolerance of 0.5% and a frequency stability of 0.2%.

So, if the sender is running 0.5% slow, and the receiver 0.5% fast, you will almost certainly get errors.

  However, when it becomes unsyncde, some new 0 bit should be treated as the startbit, in which case it should not be printed. But i don't see any misisng zero. It's as if the actual data just got shifted.

How will it get unsynced?  I don't think you are following how serial comms works. If you don't have any delay between bytes (or batches of bytes in your case) then it is impossible to resync, because if you miss a start bit, all the following bits will appear valid, they'll just be shifted. This is exactly what you are describing.

Really, to ensure syncing you need to have a gap between bytes (or batches-of-bytes in your case) longer than a byte might be, otherwise you can get this mis-sync happening. So if you make your batches longer, the gap has to be longer, effectively removing the slight advantage of larger batches.

Imagine you have an incoming stream of bits on the receiver:

011110101101100011110101101101101100110101100101100110101111001010101110111001010101111
1101001010100101101001010100111011111001000010111100100011011001001001001011001001010

And imagine that you missed that first start bit. Without a gap between bytes (which would appear as: 111111111) you have no way of knowing which is a start bit and which is a data bit. Valid data would have a start bit, so you don't mistake valid data for the inter-byte gap.

In other words, with 8-bit bytes, data will always be 0xxxxxxxx1 and thus a gap of 1111111111 must be the gap and not data because there is no zero there. But with any shorter gap, and if the receiver samples in the middle of byte, it certainly might think that the next 0 in the stream is a start bit (wrongly).


Fastest way to send serial commands and do something

Simple answer: don't.

Don't even consider strings in any form. Instead you want a state machine.

In pseudocode:

Start with an invalid count number (-1)
Read a character.
If that character is x then set your counter to 0.
Otherwise, if counter is 0 or more, convert the character to a number and place it into the right byte depending on the value of your counter
Increment counter
If counter is 6 then set your LED colours and set the counter to "invalid".
Return to start.

Or, in untested C:

static int8_t counter = -1;
static uint8_t r = 0;
static uint8_t g = 0;
static uint8_t b = 0;

if (Serial.available()) {
    char c = Serial.read();
    if (c == 'x') {
        counter = 0;
    } else {
        if (c > 0x39) c -= 7;
        uint8_t v = c & 0x0f;
        switch (counter) {
            case 0: r = v << 4; break;
            case 1: r |= v;
            case 2: g = v << 4; break;
            case 3: g |= v;
            case 4: b = v << 4; break;
            case 5: b |= v;
        }
        counter++;
        if (counter == 6) {
            counter = -1;
            analogWrite(3, r);
            analogWrite(5, g);
            analogWrite(6, b);
        }
    }
}

The "clever" bit that may confuse you is:

if (c > 0x39) c -= 7;
uint8_t v = c & 0x0f;

That is, if the character is greater than a "9" (character 0x39) then it should be a-f. Subtracting 7 from it converts ASCII HEX from 0123456789ABCDEF to 0123456789:;<=>?.  If you then mask it with 0x0F you end up with a number between 0 and 15, or 0-F in hex.

The rest just takes each nibble and places it into the right half of the right colour variable.


The problem is not a SoftPWM limitation but a physical one. SoftPWM have a PWM cycle at 60Hz, that makes impossible to update output faster than 34mS and that explain why I see low frequency trying to change the state with every 10 ms.

Hardcoding the IRS I can reach a much faster PWM cycle, keeping the same PWM frequency I have roughly 60% less of CPU used. With a full CPU load and latest version of the code I can reach ~600Hz PWM cycle. I decided to use a ~300PWM cycle to have enough CPU to perform other tasks (mainly handle RF24 to receive packets @ 60Hz and, if needed, forward them too other bases)

Even at higher frequencies average intensity is not stable, but higher the frequency more stable the result. That can be explained because the eye "average" incoming light and that average is not very stable

Since leds are used to produce visual effects I don't need a very accurate output, and 300Hz are enough. (I also don't have big mosfets and I don't want to stress them with higher frequencies)


How to access serial terminal through USBASP?

From the USBASP documentation:

  Planned: serial interface to target (e.g. for debugging).

..and further on..

  Firmware:
  The firmware dosn't support USB Suspend Mode. A bidirectional serial
  interface to slave exists in hardware but the firmware doesn't support it yet.

Keep in mind, that's from 2011, so it's possible someone has built an updated version of the firmware with that functionality. You'd have to do some searching (I'm not familiar with any such firmware).

For now, your best bet is just getting a TTL serial-USB converter (they're cheap) and connecting it directly to the Pro Mini.


I think the problem is more going to be that you don't have a serial connection to the arduino. ie, if you look in the Arduino IDE, you assign a serial port to the application. When you upload your sketch, a connection is made, the arduino resets (by design) and your sketch is uploaded.

What it appears you are doing here is opening a new connection and sending the character (which is ASCII) which in turn sends the arduino into reboot to look out for a sketch being uploaded.

I'm not familiar with popen and maybe you can use it and keep the connection open and even monitor the data stream, but I would say instead of writing directly to the device as you've done, use an application that will initialise the port properly (ie open it and leave it open) so that you can continue to use/monitor it.

A quick google search has brought up Mike's PBX Cookbook which has some good info about it. I've personally used minicom (a guide for installing minicom) and CoolTerm, I have used Screen but it was so long ago I don't remember why I moved on.

edit: I just followed the link submitted by the first commenter (sorry name not available in the edit screen), and although you've responded with "that's not it", it actually is, you just haven't realised it since your popen command is actually opening the port and triggering the RTS mentioned in that post


I found I could accomplish this using the arduino-builder tool. I created this simple bash script to do the compilation:

#!/bin/bash
CURRENT_DIR=`pwd`
mkdir -p $CURRENT_DIR/.build
arduino-builder -compile -hardware /usr/share/arduino/hardware -tools /usr/share/arduino/hardware/tools -tools /usr/share/arduino/tools-builder -libraries $CURRENT_DIR/lib -fqbn arduino:avr:uno -build-path $CURRENT_DIR/.build $CURRENT_DIR/src/main.ino


What is the difference between the two sensors?

Apart from the obvious construction and component differences the two sensors seem totally equivalent from their look.
They seems to both be FC-51 modules: those are “line followers” meaning one diode (the clear one) emits infrared light and the other (the dark one) measure the amount of IR light reflected by the surface in front of them.
The potentiometer is there to determine the triggering level so that when powered you can have a LOW signal on the OUT pin when the threshold is reached.


Is there any way to separate this short code into its own function? (webserver, trying to use client.print outside of main loop)

You can pass client to the function by reference, like this:

void displayBullet(EthernetClient & client, int toggle)
  {
  if (toggle == 0)     //switch is off, so display red bullet
    client.print(F("&#8226;"));
  else    //switch is on, so display green bullet
    client.print(F("&#8226;"));
  }

Now it knows about client. Make sure you pass client when you call it:

displayBullet(client, 1);


Each wire in the Dupont ribbon cable is is independent, and does not hold onto its neighbors with any real force. You can split them or join multiple wires together using larger connectors as desired.


Arduino Uno with SD, Cardinfo sketch how to list only visible files

Simple Answer: Don't think you can

Long Answer: Dont think you can, because, unlike an OS like windows, mac, linux, etc. The arduino just tales all the files. You could save those two files and format it as FAT16 though, then add the 2 files back on the sd and there you go.


You can use full wave rectifier, but there is a significant voltage drop on it.

Another way is using Voltage divider to provide 1/2 Vcc to one of the motor terminals. But then you can measure just 1/2 Vcc in both directions (without another Voltage divider)

Something like:


Unable to understand the acquisition of data from Magnetometer HMC5883L and Accelerometer ADXL345

If you read the datasheet for the mentioned magnetometer, it is clearly mentioned that the data is to be read at once. Below is the implementation of pseudo code mentioned in the datasheet.

void setup()
{
  // put your setup code here, to run once:
  Serial.begin(9600);
  //send 0x3C 0x00 0x70 (8-average, 15 Hz default, normal measurement)
  Wire.begin();
  Wire.beginTransmission(0x1E);
  Wire.write(0x00);
  Wire.write(0x70);
  Wire.endTransmission();
  delay(10);
  //send 0x3C 0x01 0xA0 (Gain=5, or any other desired gain)
  Wire.beginTransmission(0x1E);
  Wire.write(0x01);
  Wire.write(0xA0);
  Wire.endTransmission();
  delay(10);
  //send 0x3C 0x02 0x00 (Continuous-measurement mode)
  Wire.beginTransmission(0x1E);
  Wire.write(0x02);
  Wire.write(0x00);
  Wire.endTransmission();
  delay(10);

}
void loop()
{

  Wire.requestFrom(0x1E,6);
  if (Wire.available() > 5)
  {
    x = readValue();
    y = readValue();
    z = readValue();
  }
  else
  {
    Serial.println("No data found");
  }
  data = String(x) + "   ,   " + String(y) + "   ,   " + String(z);
  //Send 0x3C 0x03 (point to first data register 03)
  Serial.println(data);
  Wire.beginTransmission(0x1E);
  Wire.write(0x03);
  Wire.endTransmission();
  delay(100);
}

Similarly, it is mentioned in the datasheet for ADXL345 as well that the data should be read separately from each axis register separately.


Addressable RGB strip works fine individually but cannot set all LEDs to full white

I would suspect that it is a voltage drop in the power rails caused by the current draw. Probably cheap construction with copper tracks that are just too thin and so have too high a resistance.

To combat it you will need to inject power into the strip at various points along it.  Initially to prove the theory you can try connecting the power to both ends of the strip and see if the "dull" spot is half way along the strip.  If it is, then it's certainly a voltage drop.  (incidentally, a voltage drop will cause the blue LEDs to fade out first making it go yellow-red. Then the green ones would probably be next, making it go red).

Then, once proved, you will need to add extra power connections into the strip at the middle of any dim sections and feed the voltage directly in at those points.


Arduino ,How I can see the value (0 or 5) on my screen, where I connected my sensors output to analog input A0,A1.. pins

You can use DigitaRead command instead of analogread. It will give result in only 1 or 0. Hopefully this will help you.


You are looking at the wrong place. Tx and Rx are at the bottom of you picture (new picture at the bottom to help you). What you need to do is to get a jumper, heat up the Rx pin and put the jumper in the molten solder. That is not the ideal choice but because you don't have enough solder, thats the way to go. To the same to the Tx pin, GND, and VCC.

A more permanent and clean way of doing this will require extra solder (which you dont have at the moment) and some "shield headers" (aka stackable headers). This will let you connect the shield to your Arduino while still leaving you with all of your female headers.


An SD card has two interfaces: The SPI interface is what is used by the Arduino (it is rather slow). The second one is a parallel interface, which is capable of way bigger transmission speed. It is most likely, that the camera uses that interface, since it has to transmit rather big data packets in a short time. But as I remember some pins are used for both interfaces.
We cannot know, what happens inside the camera. But providing voltage to a digital pin of a microcontroller, while it is not powered, (as it would happen, when you drive the SD card while the camera is off) can be harmful. We must assume, that this would also happen with your camera, or you risk damaging it.
Using multiplexers (or - if you find no fitting one - some simple transistors) to disconnect the camera, when you want to connect with the Arduino, seems a good idea to me. Disconnect all lines, including the supply voltage. The ground line has to stay together, though you should check with a multimeter, if the SD slot ground is the same as the shutter connector ground (if they are not, you don't want to connect these grounds). Is most likely is, but you should check it to be sure.


Is there any way to control current precisely with Arduino without using a DC-DC converter?

The Arduino (like other microcontrollers) is a digital device. It doesn't "control current" on its own. It has outputs which can either be off or on. Off is 0V and on is 5V (assuming you are powering it from a 5V supply). The continuous current you can drawn from output pins is 20 mA.

You can use PWM to effectively reduce the power output (for example, a 50% duty cycle would be half on and half off, thus you would have 50% power).

If you drive your torquer from some sort of transistor (eg. a MOSFET) then PWM could conceivably achieve what you are wanting to do. A link to this device would be helpful. Plus, the other circuitry you have in mind.


Determining which raw IR code to use for AC

It appears from the data you've posted, the remote is holding the presets for what the A/C unit needs to be doing when after every button is pressed.  This will keep the remote with LCD disply? in Sync with the A/C master.

Ie.  The remote is sending an entire setup string EVERY time ANY button is pressed.

Can you post a capture of an ON and OFF Raw's only?  Do not press any other buttons after pressing ON, or before pressing OFF.


How to send and receive unsigned int from one arduino to another arduino

There are 2 ways to transmit data over serial: As byte data or in ASCII codes

Byte data: Everything, that is digitally stored or processed, is a series of 0s and 1s (bits) (electrically HIGH and LOW level), which are grouped into bytes (8 bits). So all data is just numbers at low level. The different datatypes (like numbers, Strings, executable code) are only reached by different interpretation of the byte data. You can take the number value of a byte directly. A byte like 0b00000101 for example is equivalent to the decimal value 5. So every byte can hold numbers between 0 and 255. (Google the binary system for more information). To hold bigger numbers, more bytes are put together. For example an integer consists of 2 bytes (16 bits) and can hold numbers between 0 and 65535. Note: These are the unsigned types. There are also signed types, that also can hold negative values. To understand this, google binary two's complement. To transmit such a bigger type over serial (which is byte based), you need to seperate the bytes of the type, send them consecutively and put them back together at the receiving side. You can do this with the following code:

unsigned int number = 54321;
Serial.write(number & 0xFF); //getting the lower byte of the number by using bitwise AND
Serial.write(number >> 8); // getting the high byte of the number by shifting the bits of the value 8 bits to the right

There are macros defined for Arduino, that can do this for you:

Serial.write(lowByte(number));
Serial.write(highByte(number));

In long term, you should learn, how the bitwise operators work. They are often needed. To put the data back together, you can look at CrossRoads answer.

Note: Serial.write() will send the byte data unchanged, while Serial.print() will convert the data to ASCII before sending. They are not equal.
ASCII Data: One interpretation of byte data is the ASCII standard (which is really old). Every byte value between 0 and 127 get's a corresponding ASCII value, meaning characters of the alphabet, digits, some special characters and some control characters. Numbers, that are transmitted as ASCII data, consist of multiple bytes, one for each digit. Thats, what you tried. Since the receiver has to seperate the different numbers to process them correctly, you have to mark the end of each number. This is commonly done with the newline character \n (optionally preceeded by the carriage return character \r, windows style). You add this at the end of every number. Serial has an extra function for that: Serial.println() will print the parameter as ASCII and will add a carriage return and newline character. On the receiving side you read the bytes into a buffer, until you see this delimiter sequence. After that, you process the whole buffer. If you want to know, how this Serial communication is done in code, look at the SerialEvent example, that comes with the Arduino IDE.

What way you use for transmitting data, is up to you and depends on your needs. If you only want to transmit number data, nothing else, you can use byte data. For complex or diverse data types, you can use the ASCII representation.

EDIT: I have described above, that - when using ASCII data - you can use one or more special characters to delimit one message/number. The receiver can then distinguish between the numbers in that row of digits. This is just some kind of protocol, that you impose on the data. You state, that every message is ended with this special character, much like very sentence in the english language is ended with a dot.

An important requirement is, that the special character does not occure inside of a message/number. So cannot use the character '1' as delimiter, since it will also occur inside of your numbers and you would chop the numbers in the wrong way.

The same principle can be imposed as protocol onto a byte stream. For example: You define, that every message/number will be ended with a special byte sequence, so that the receiver always can say: "This is the whole data of a number and not just a part of it." As above, the special byte sequence must not occur inside of the valid data. You wrote, that your numbers are always in the range of 0 to 62000. This means, that the value 65535 will never occur as valid data, thus you can use it as delimiter. In hex 65535 is written als 0xFFFF, which means, that you send two bytes with every bit set to 1 (each byte having a decimal value of 255). In your code everytime, that you are receiving something, you can check, if you have got 2 consecutive bytes with the value 255 (or written as 0xFF). If not, write the data into a buffer. If yes, that means, that you can process the data inside the buffer to a number.

For sending that would look like this:

Serial.write(lowByte(number));
Serial.write(highByte(number));
Serial.write(0xFF);
Serial.write(0xFF);

Note: This protocol will make sure, that sender and receiver cannot get out of sync. But still the first reading after a transmission problem (for example that a byte got send before the receiver was ready) will be garbage. That will happen very very rarely, so for most people it's not a problem. There are more principles, that you can use in your protocol to mitigate those problems, if you want to. For example you can define another special byte sequence as the start of a message/number. Or you can calculate a checksum of the number and only use messages/numbers, that fit to that checksum.


Measure LiPo / Li-Ion SOC or the ever standing question of how much juice is remaining in my battery?

Use a low-leakage op amp to divide the battery voltage by 8 (AV of 1/8). Connect the output to an analog input. Set your reference to the internal 1.1V reference (INTERNAL). Perform analog reads. Full battery will be about 975 ((8.4V/8)/1.1V⋅1024 ~= 977.45455). Empty will be about 700 ((6.0V/8)/1.1V⋅1024 ~= 698.18182). Note that the voltage scaling for Li-ion cells is non-linear; see the datasheet for the cells for the appropriate scaling (and if you want more precise full and empty values).


PB3 etc don't refer to Arduino pins. Instead they refer to the bits in the internal registers.

To use digitalWrite() etc you must use Arduino pins not internal register bit numbers.

The pin to port/bit mapping is defined by what board you have selected, and if you want to look it up you should examine the pins_arduino.h file for your selected board.


Olimexino 32u4: Wire.endTransmission() hangs

I've did not got it working with Wire. Hence I've implemented a I2C protocol myself using bit-banging and then it works.

Update from 2017-September-16

The problem was not Wire.h but a specialty of the Olimexino 32u4 board. I've only found out by using a Real Time Clock connected to the UEXT port's I2C bus, that I have to switch on the power for the UEXT port by setting D8 to LOW. Otherwise SDA or SCL seem to be pulled down preventing any I2C communication.


ACS712 Not working correctly with Arduino

You are seeing that because that is what the current is doing. It's called AC - Alternating Current. It's what the mains current is.

To work with AC you have to rapidly sample over a short period to get the maximum and minimum values. Subtract one from the other and that gives you the peak-to-peak current. You can then use that to calculate the RMS current which is what you are (most likely) interested in.

http://whatis.techtarget.com/definition/root-mean-square-RMS


Arduino time keeping using millis() is not accurate or correct?

millis() is interrupt driven so delay() won't impact it, at least not on an ATmega based board.

That isn't to say that millis() is totally accurate either. Each tick of the timer is not exactly 1ms, but is 1.024ms. This error gradually accumulates until a correction is made. This can be seen in the implementation of the TIMER0_OVF (timer 0 overflow) interrupt handler.

Another source of inaccuracy is the oscillator/crystal itself, which is not exactly 16MHz. It is pretty close though, and as long as temperature doesn't change too much, is relatively stable.

The above means that you might be about 1ms out when using millis(). This doesn't sound like your problem.

Another potential issue would be what getECG() is doing - it might be very slow.

float eHealthClass::getECG(void)
    {
        float analog0;
        // Read from analogic in.
        analog0=analogRead(0);
        // binary to voltage conversion
        return analog0 = (float)analog0 * 5 / 1023.0;
    }

analogRead() is slow, but not so slow as to impact a loop like this.

Another problem I have seen people have is when they change the clock speed but don't correctly change boards.txt. This means that the constants used in the millis() implementation are wrong and the times are wrong.

If you actually want to read values every 50ms, a much better way of implementing this is to do the following

static long lastUpdate;

if (millis() - lastUpdate > 50)
{
    lastUpdate = millis();
    //Do stuff
}

We'd really need to see the timestamps you are getting. If you actually seeing 30s showing as 10s, then there is something else at work.


Ultrasonic Range Sensor won't print distance in Serial Monitor

You have to manually switch from OUTPUT (for sending the trigger pulse) and INPUT (for reading the distance) mode on the shared IO pin.

//Work out the distance
pinMode(trigPin, OUTPUT);    // << ADD THIS
digitalWrite(trigPin, LOW);
delayMicroseconds(100);
digitalWrite(trigPin, HIGH);
delayMicroseconds(100);
digitalWrite(trigPin, LOW);
pinMode(echoPin, INPUT);     // << ADD THIS
pulsetime = pulseIn(echoPin, HIGH);
distance = pulsetime / 58;
delay(10);

To save some confusion you might like to change your code to just use sigPin instead of a pair of pins that are both the same pin.  That way you would avoid confusing bits like:

pinMode (echoPin, INPUT);
pinMode (trigPin, OUTPUT);

Which of course is the equivalent to:

pinMode (4, INPUT);
pinMode (4, OUTPUT);


How do I join two RGB ledPanel 32x64 in order to get one 64x64?

First off, connecting the 2nd panel to the same output pins as the first one, you are simply sending same data to the 2nd panel, which is why you get the duplicate visuals. I'm guessing you are sending power that same way, which is why you are seeing the brightness dim.

Secondly, it's hard to read on the pics in the AliExpress listing, but the Sparkfun site had a better image, which shows an "Output" connection on the back of the panels.  You need to daisy chain the 2nd panel to the first panel through this "Output" connection. This should prevent you from having to create a 2nd matrix2 and use a 2nd set of pins.

Third, having a 2nd set of pins and controlling the 2nd LED matrix can make updating the image faster. It depends on your library as well as how the LED matrix is made, so it really depends on those factors, but some LED systems are designed so there is a maximum amount of pixels that can be displayed before there's a noticeable delay in LED updated. With this amount of LED pixels, you're probably fine, but if you want fast updates and expect to expand your matrix in the future, you might want to consider driving the panels separately. I'm not saying you have to now, but if you're seeing lag, this might be a good option.


analogRead() doesn't read more than 500Hz

You have 4 calls to analogRead() in your loop. At about 112 µs per
call, that's already taking 448 µs. Add to that the time taken by the
floating point calculations, and you are likely to end up with something
in the order of 500 µs per loop iteration. This should give you a
sampling rate close to 2 kHz, which should allow you to detect the highs
and lows of an input signal up to 1 kHz, provided the duty cycle is
close to 50%.
There are a couple of easy optimizations that could be done here. Two of
the calls to analogRead() serve no purpose, as the results are never
used. And the floating point calculations are also pointless. The whole
loop can be simplified to this:
void loop() {
    if (abs(analogRead(A0) - analogRead(A1)) >= 512) {
        digitalWrite(6, LOW);
    } else {
        digitalWrite(6, HIGH);
    }
}

This should take about 224 µs per iteration. If you need to go faster,
you will have to increase the working frequency of the ADC. This can
cost some accuracy, but if accuracy is not critical to your application,
it can be a good trade-off. See Nick Gammon's page on the Arduino
ADC for details. If that's not enough, you will have to use
external components, e.g. an analog subtractor made from an op-amp, and
a couple of comparators.


Multiple Wire.write() not working for Arduino Nano I2C

Important information: Wire.write() does NOT send anything over the I2C lines. It just puts the data into the libraries internal buffer. The actual transmission is then done by Wire.endTransmission().
I2C is packaged transmission protocol. That means, that the transmission is done in confined data packages. In your master code you are calling Wire.write() two times before Wire.endTransmission(). That means you are sending 1 package with 2 data bytes in it.
Now for your slave code: You are using a callback function for the onReceive event. This callback function is called once per transmission. In there you can read all the data of that transmission. After that the data is thrown away (I think actually it gets deleted, when a new transmission is received). You are only reading once with Wire.read(). So you only ever read the first byte of every transmission, which is always the letter 'c'.
What to do know? This depends on how you want the code to behave. Since you are setting 2 LEDs based on the received byte it would be better to only send 1 byte transmissions. For that, you can change your master code. For example like this:
#include <Wire.h>

void setup()
{
  Wire.begin();

  Serial.begin(9600);
}

void loop()
{
    // Send the command c
    Wire.beginTransmission(9);
    Wire.write('c');
    Wire.endTransmission();

    // Wait 1s, so that we can see the LEDs state accordingly
    delay(1000);

    // Send command a
    Wire.beginTransmission(9);
    Wire.write('a');
    Wire.endTransmission();

    // Wait 1s, so that we can see the LEDs state accordingly
    delay(1000);
}

This code will change between 'c' and 'a' every second. You need a delay there to actually see the LEDs light up. Otherwise they would change too fast for you to see it.
Note: Actually you need to declare the variable x as volatile, because the onReceive callback is called from an ISR. With that keyword you are telling the compiler, that x can change at any time (by the ISR of the corresponding I2C interrupt). It might be, that your current code works, because the compiler was smart enough to see that, but in general you should always use volatile with every variable, that can change in an ISR. Declaration then looks like this:
volatile int x = 0;

And to handle the ISR data really correct, you would need to make the usage atomic, because the ISR can happen in the middle of the comparison for the if statements. An int is two bytes, so the first byte might be updated and the second byte not. That would corrupt your data. There are two ways to handle that in your case:

Make the reading of x atomic: Normally one would turn of the interrupts, read the volatile variables into local variables (as a copy) and then turn the interrupts on again. That way the interrupt cannot corrupt the data in the variable during reading. The further calculation/comparison would then be done with the local variable.

Use a single byte as volatile data: The described problem does not apply to variables, which only use 1 byte (since on the 8bit Arduinos like the Nano the reading of a single byte cannot be interrupted). So just make x of type char (or uint8_t or byte).

You should use the second option.


How do you use an Arduino to control a 4 - 20 mA transmitter?

I can recommend the Click boards from MikroElektronica (I am the chief engineer porting support for them, and the PIC32-based Clicker development board series, to the chipKIT™ system).

The 4-20mA-T Click board is controlled by the Microchip MCP4921 DAC. This is a common DAC family used in many Arduino projects and there are plenty of libraries around for them (mine is here though it's aimed at the 4822 not the 4921).

Basically you set the DAC output voltage which sets the current output from an XTR116 current loop transmitter.

The XTR116 takes an input of 0 - 4.095v, and provides a convenient 4.095v reference voltage to the MCP4921.

Datasheet for the XTR116
Datasheet for the MCP4921
Manual for the 4-20mA T Click

The whole thing is isolated from your main board through an ADu M1411 to keep everything safe from industrial process noise.


Physical safety: Prevent linear actuator from crushing my fingers

The easiest way to prevent things becoming trapped is to take reasonable steps to prevent things getting near the "danger zone", so a barrier 2 metres around the barrel would be a good start.  Probably it would be an impractical idea, but...

A physical barrier of some sort would be the best idea, because that is less likely to suffer a failure than an electronic system (well assuming it has been designed right).  If you are using an electronic system then it needs to "fail-safe", when it suffers a failure it must adopt its safe state (barrel open).

You could surround the lid with IR lights and receivers in the lip.  They would need to be spaced at a distance where an arm/finger couldn't get between the lid and lip without breaking a beam.  This solution would only work over the last few inches, because of the angle of the beams.  If all receivers had a signal the it would be safe to close.  The problem is the receivers would need to be close together to prevent transgression.

Monitoring the current drawn by the actuator and the position of the actuator might be another.  I am assuming that there is an increase in current draw when the lid actually closes, and a similar increase in draw when something is trapped.  If the lid isn't fully closed when the current increases then something is trapped.

The final way I can think of is probably the most effective.  As the barrel closes don't close it the last few inches, allow it to 'fall' as the actuator descends.  This means if there is an object in there the actuator isn't pulling the lid down and the object will hold the lid against gravity.  This would be done by having a channel in the mounting block for the actuator 'pin'/ connection point to slide up and down.

OK Its not an electrical solution.


Doubt with the library esp8266wifi and Station Mode

This is the function prototype:

Per C++ rules, in order to supply an argument for bssid, you have to pass an argument for channel as well, but connect is optional since it's positioned after your target argument. This should not be a problem though since you can just pass the default value of channel (i.e. 0) into the function; the channel argument is only relevant if you enter a value between 1 and 13 inclusive.

So your call should basically look like:

char ssid[] = "ssid";
char pwd[] = "pwd";
uint8_t bssid[] = {0x00, 0x1b, 0x44, 0x11, 0x3a, 0xb7};
WiFi.begin(ssid, pwd, 0, bssid);


Maintain constant PWM voltage with changing Vcc


Long freezes at the beginning of sd card transfer

As a temporary workaround I have come to the following procedure:

I inserted a function that writes a certain amount of bytes into a dummy file, closes it and finally deletes it, all during setup().

This does indeed seem to cure the freezes if (in my scenario) I write at least 6 blocks (512 bytes each, i.e. total 3072 Bytes). Remarkably there were always exactly 6 freezes visible in my oscilloscope plots. I don't even remotely know what the meaning of this magic number 6 could be...

Just to have some additional safety in case I choose a different type of sd card (and this workaround becomes permanently temporary...), I have decided to write 16 kB into the dummy file. This is ~5 times as much as the empirical minimum value (3 kB) and is still pretty fast so that I don't notice any significant startup delay after power-up.

This empiric approach is still unsatisfactory though, and certainly a piece of mediocre engineering. So I won't mark my answer as accepted, to leave the chance for someone else to give a more well-founded answer.

void writeAndEraseDummyFileToEliminateFreeze()
{
  if (SD.exists("dummy")) SD.remove("dummy");
  File dummyFile = SD.open("dummy", FILE_WRITE);
  int n = 16384/recordSize+1; // write 16kB in chunks of recordSize (just because we have that buffer already
  for (int i=0; i<n; i++)
  {
    // buffer values are uninitialized, but who cares, we'll dispose of them anyway
    dummyFile.write(buffer,recordSize);
  }
  dummyFile.close();
  SD.remove("dummy");
}

void setup()
{
  // ...other things I have been already doing...

  writeAndEraseDummyFileToEliminateFreeze();
}


Why does this array have stored values in it even though I have not put any values in it?

The values haven't been "put" in the array. The array has been located in memory where those values (left over from some earlier operation, possibly as part of a function's stack frame) happen to be.

The simple fact that you haven't put anything in there means that what was there before hasn't been changed.


using esp8266 feather to burn bootloader on redboard

The RedBoard has an FT232 chip for the USB interface.  Flashing the bootloader on the main MCU will have no effect at all on your problem.

While, yes, it is technically possible to use the ESP8266, it's not easy and, since it won't cure your problem of a greyed out port option, isn't worth the effort to try and do it.

Instead, you should be looking at things like your USB ports, USB cables, FT232 drivers, etc on your computer.


Yun did not connect to WiFi after configuration and restart

My wireless config is in the /etc/config/wireless, not in the /etc/config/arduino

How do you configure your Wifi ?
There is at least 4 methods  :
you can do this through OSJS, through LUCI, through ARDUINO IDE, or with UCI.


Do I Have to Change Internal Interrupt Setups when I Change Clock Speed?

The equation for timer period is given by the following formula, where N is the value of the prescaler, TOP is the value given by either MAX (i.e. 0xFF, 0xFFFF) or the value in register OCRnx, and f is the frequency of the I/O clock.

If you're using phase-correct or phase- and frequency-correct mode, the factor (TOP+1) in the formula above should be replaced by 2 × TOP.


The best replacement (but keep in mind that Tinkercad is prob the best for code AND hardware sim) would be Yenka. They offer a "block style" language but you can go in depth with the hardware more than most programs.

Here is a ref image:


What could I use to vary the temperature of a Heating Pad?

In principle, I don't see any problems. Your heating pad uses 12V and 10W, which means it would be consuming slightly less than one amp of current. The MOSFET you linked can go up to 5A (needing a heat sink with over 1A).

You could use PWM (there are 6 pins on a Uno that can do that) to provide pulse-width modulation to control the amount of output you give to the heater.

You would, of course, need to measure the heat of the device to work out when to adjust the PWM output. You might look up using a PID algorithm to adjust the PWM output depending on the sensed heat input.

References:

pid
pwm
mosfet
sensors


That method only works on AVR based systems.  It exploits a "feature" whereby the IO pin, when in OUTPUT mode, is also in INPUT mode at the same time, and reading the pin reads the value that the pin is being driven to by the digitalWrite function.

The same is not true of the Due, which is an ARM based system.  The IO pins function completely differently and the same "feature" cannot be used.

You will have to remember the state of the pin yourself.


After looking at the product spec again I think it might be possible to get this working. The protocol is MSB with a start bit S followed by two bit op-code, and parameters. SPI on AVR is 8-bit transfer but transfer can be byte aligned with the start bit.

READ is op-code(10) followed by 7-bit address, a dummy bit and the read value. That is in total 11+8-bits. Mapping that to 8-bit transfer would be:

spi.transfer(0b110);
spi.transfer(addr << 1);
data = spi.transfer(0);

That will give 5-bit zero, start-bit, op-code in the first transfer, and followed by 7-bit address and dummy bit (LSB) in second transfer. The third transfer is the read data.

EWEN would map to:

spi.transfer(0b1001);
spi.transfer(0b10000000);

EWEN has op-code(00), followed by 9-bits, 0b11XXXXXXX.

The WRITE operation becomes:

spi.transfer(0b10);
spi.transfer(0x80 | addr);
spi.transfer(data);

Cheers!


Multiple shift registers, 16 bit numbers

Your problem is entirely that you declare val to be uint8_t, instead of uint16_t. You are truncating your data to 8 bits before displaying it. One other note, the 74HC595 has a maximum total drive current of 50mA. Your circuit will draw around 90mA for each of the 74HC595's if all of the LEDs are on. You may want to change the resistors to something bigger (510 Ohm, for example) to avoid this problem. Of course that will make the LEDs dimmer, so it's a tradeoff. Here's your project in 123D Circuits. You can simulate it in the browser and look at the code running in the Arduino there.


How to send RPM data as analog input from arduino to Xbee

I would suggest you to send bytes instead of "analog value". When you calculate your value, not sure why you use float and then convert it to int, but here is how i would do. Communicate to xbee via serial communication, send bytes to xbee(its even easier than "analog value"). Added if statment to print RPM every second.

Here is my code:

#include <SoftwareSerial.h>
/* Serial communication with Xbee.
On Arduino pin 9 is Rx connect to Xbee Tx,
pin 8 is Txconnect to Xbee Rx*/
SoftwareSerial xbeeSerial(9, 8); // RX, TX

int pin = 7;  //7
float rpm;
float duration;
float y;

unsigned long val,time;
float rps;
float read_rpm;
int pin_out=10;

void setup()
{
  // Open serial communications and wait for port to open:
  Serial.begin(9600);
  pinMode(pin, INPUT);
  pinMode(pin_out,OUTPUT);
  Serial.println("I am ready to send some RPM!");

  // set the data rate for the SoftwareSerial port
  xbeeSerial.begin(9600);
  time = millis();
}

void loop()// run over and over
{
 val =  pulseIn(pin, LOW,70000000);

 duration=(float)val/1000000.00;
 rps= 1.00/duration;
rpm=60.00*rps;

/* Sending float to Xbee
Float is 4 byte size*/
serialFloatPrint(rpm);

int floatToInt = (int)rpm;

/* To send INT to XBEE
Int is 2 byte size*/
xbeeSerial.write(highByte(floatToInt));
xbeeSerial.write(lowByte(floatToInt));

/*Print RPM every second*/
If(millis()-time>1000){
  Serial.print("RPM=\t");
  Serial.print(rpm);
  Serial.print("\t rps= \t");
  Serial.print(rps);
  Serial.print("\t dt=\t");
  Serial.println(val);
  time = millis();
 }
}

void serialFloatPrint(float f) {
  byte * b = (byte *) &f;
  //xbeeSerial.print("f:");
  xbeeSerial.print(b[0]);
  xbeeSerial.print(b[1]);
  xbeeSerial.print(b[2]);
  xbeeSerial.print(b[3]);
  /* DEBUG */
  Serial.println();
  Serial.print(b[0],BIN);
  Serial.print(b[1], BIN);
  Serial.print(b[2], BIN);
  Serial.println(b[3], BIN);
  //*/
}


How to modify this code to simulate a binary encoder?

You may try to bit-bang the protocol using direct port access. This
is less convenient, but way faster than digitalWrite(). Below is an
example, untested program. I am assuming the pinout is

data = PB0 = digital 8
clock = PB1 = digital 9
pins PB2 – PB5 (10 – 13) are unused

Edit: This updated program uses the clock as an input, and the data
as an output. The previous version used both lines as outputs, which was
due to a misunderstanding of mine.

#include <avr/io.h>

int main(void)
{
    uint16_t data = 0x155;

    DDRB  |= _BV(PB0);
    PORTB |= _BV(PB0);
    TCCR1B = _BV(CS10);  // start timer 1 @ F_CPU
    loop_until_bit_is_clear(PINB, PB1);

    for (;;) {
        loop_until_bit_is_set(PINB, PB1);
        PORTB = data & 1;
        data >>= 1;
        TCNT1 = -304;        // 20 us * 16 MHz - 16 cycles
        TIFR1 |= _BV(TOV1);  // clear overflow flag
        while (bit_is_set(PINB, PB1)) {
            if (bit_is_set(TIFR1, TOV1)) {  // timer overflowed
                PORTB = 1;  // data high
                data = 0x155;
                loop_until_bit_is_clear(PINB, PB1);
                break;
            }
        }
    }
}

This should be able to operate at frequencies up to about
200 – 250 kHz. There is a delay of about 0.5 µs
between the rising edges of the clock and the data been sent out, with a
jitter of 3 clock cycles.

The data word is sent least significant bit first, contrary to what the
protocol diagram shows. However, if you send arbitrary data, this should
not be an issue.

Note that this is a pure avr-libc program, which does not use the
Arduino core. It uses polling to check the inputs and the timer. The
interrupts are never enabled.


Edit: Forget the post above if you just want to know how your board is working. Your board is a retired Spurkfun product - clone.

Here you can see the schematics and all info about your board:

https://learn.sparkfun.com/tutorials/retired---using-the-logic-level-converter

Original post:

The module you got, use the BSS138 MOSFET.
The circuit is easy, and how @Majenko said, it has just 2 pullups:
See https://electronics.stackexchange.com/questions/367052/replace-bss138-with-ao3400a-in-level-shifter-circuit

But this board is really strange: what means TX0, TX1, RX0, RX1 on the same MOSFET? It is better if you can measure it to be sure how to connect the sensor to the TX.

But there is a better way to solve it: Since you just have 1 input to your ESP, why not use 2 resistors?
5V--- 1k --- 2k --- GND
And connect the ESP input between the 2 resistors? It is even faster, because the MOSFET need up to 20ns to change state.


ESP8266 NODEMCU V3, HOW TO USE AND CONTROL V3 OUTPUT POWER

You cannot control the "V3" output. It's a 3.3V power supply output. Think of it like a battery. It's always on and always giving power.

Instead, you need to add a "switch" to control that power that the ESP8266 can itself control, such as a MOSFET or a motor driver (H-Bridge).


PIR sensor and sleep (interrupt) on Mega2560

This is a problem with the Arduino Mega board. On the Mega, D2 is not INT0 as it is on the Uno. It's INT4. There's a footnote in the spec sheet that says only level interrupt is supported. That means you can't use RISING, FALLING or CHANGE. Your only choice is to use LOW. So the Arduino will be woken up when the motion turns OFF, not on. That's why it's backward. If you use an Uno instead of a Mega, you can use RISING and it will work as you think it should.


Arduino TCP Server establishes connection with client but does not receive data

You have created a TCP server. You need to connect other clients to it to start data send and receive process between them. If you just simply run this and wait, then you probably won't get anything because nobody is attempting to connect to it.


How will I solve my problem : expected primary-expression before '>' token

You need curly brackets around your if block.

if (distance > 10) { // this solves the problem
  car.set_speed(127);
  car.forward();
  delay(3000);
}

etc
Edit: Thanks to the commenter.


Why is it i need transistors and resistors to turn a dc motor with an Arduino but i can connect it directly to a battery

If you want the motor to rotate continuously, without using PWM, and without switching the motor on and off from the Arduino, you can connect the motor straight to 5V and ground. If you then add a large resistor like you tried, not enough current will pass through the motor to rotate it; in the image the resistor is there to limit the current into the transistor, not to limit the current into the motor.
You can't connect a motor directly to an IO pin because an IO pin can only deliver about 20mA, which isn't enough for a motor. So, if you want to control a motor from an IO pin, you need a transistor as a switch and you operate that transistor from the IO pin. The transistor does the heavy lifting and switches the larger current the motor needs. The resistor is there to limit the current into the transistor.
Note that it is generally better to wire a motor directly to a 5V power source and not to the 5V pin on the Arduino, as the current you can get from that pin is limited; it will do for small motors, though, if they don't pull more than, let's be safe, about 300mA. In other words, it is preferred not to use the Arduino 5V pin as a power source, but use a 5V power source directly.
Also note that you always need the diode across the motor, however you wire it. It keeps inductive spikes away from the rest of your circuit.


Check your wiring! My guess is the twisted pair (A-B swap).

I've checked your code, it seems right. Please note that /RE and DE were designed that way so you can simply connect them and control with only one pin.

I don't have the exact same hardware, I had MAX485 and Arduino Nano at hand. Nano only has one hardware serial, so I've used the SoftwareSerial library instead.
I've connected them, adjusted your code to my setup, and it worked. Here it is in case it helps to troubleshoot your issue. I've also optimized your version a little bit (but it worked before so the bug is somewhere else).

#include <SoftwareSerial.h>
SoftwareSerial mySerial(2, 4); // RX, TX

const int dir_pin=9;
const int dir_transmit=1;
const int dir_receive=0;
long rate=38400;

void setup() {
    Serial.begin(rate); while (!Serial);
    mySerial.begin(rate); while (!mySerial);
    pinMode(dir_pin,OUTPUT);
}
char s;
void loop() {
    if (Serial.available()) {
        digitalWrite(dir_pin,dir_transmit);
        while(Serial.available())
        {
          s=Serial.read();
          mySerial.write(s);
        }
        mySerial.flush();
        digitalWrite(dir_pin,dir_receive);
    }
    while (mySerial.available()){
        s=mySerial.read();
        Serial.write(s);
    }
}


I2C communication between Arduino Due and Nano

Dead easy !!
(Well only because I had a -fpermissive yesterday :) )

You are trying to implicitly cast, and you can't do that with modern GCC versions (quite rightly).

So you need to explicitly cast the first parameter to void*.

Because this is in a "core" library for the Due I would get the latest version of the board package and see if it goes away.  You can turn the check off, but you will need to google on how to do that.


Basic safety precautions:

Always fully unplug the lamp before working on any wiring, even when working with the low-voltage side of things.
Invest in a proper enclosure and follow the rules of insulation and earthing: if the enclosure is metal or has exposed metal they have to be earthed. If it is plastic it is insulated and there is nothing to earth (plastic is best).
Use nylon bolts etc when situated near mains voltages.
A proper relay module with good screw terminals is recommended.
Do not tin your mains wires when screwing them into a terminal block
Do your mains wiring with your left hand in your pocket (an old electrician's trick: if you should get a shock the path to earth is down the side of your body and through your foot. If you have your left hand touching something the path to earth could well be straight across your chest, through your heart, and down your other arm, killing you. It has saved my life a few times...)
Keep mains voltages and low-voltage areas separate. Cable ties and self-adhesive nylon cable tie pads are great for keeping cables where they should be.
Shield any exposed mains connections from touch. Things like the underside of the relay module where the terminal blocks are soldered, that sort of thing.
Don't let the relay module wave around loosely. Keep it well secured in the enclosure.

I'm sure I could find more tips if I tried :)

The main thing to remember is that mains electricity is deadly and should be treated with the utmost respect.

For the ultimate in safety though you could get an isolating transformer. This separates your work from the main supply and means that the only way of getting a shock is by actively touching both outputs of the transformer at once - something you're not really likely to do - and even then it's usually a very localised path for the electricity (through a finger or two).

Adding an ELCB to the lamp's plug (if it is earthed) can be a good precaution while you are working too - and making sure the socket is connected to a ring main that is protected by an RCD is pretty much essential (in the UK it is the law that all ring mains are protected by an RCD - I would hope the same is the case where you live).


You seem to already understand that it's not null-terminated and that's why it's not working the way you expect.  So, I'll take a different tact for "how to fix it".
You can simply not treat the payload as a string, and instead use memcmp, as in:
if (length == 9 && memcmp(payload, "ravenclaw", 9) == 0) {

memcmp behaves similarly to strcmp, except that it isn't looking for a null terminator. It just compares however many bytes (chars) you specify.  In practice you may want to use a variable to hold "ravenclaw" and to strlen() on it rather than specifying the length separately as I've done above, e.g.:
static const char ravenclaw[] = "ravenclaw";
static const size_t ravenclaw_len = sizeof ravenclaw - 1;
if (length == ravenclaw_len && memcmp(payload, ravenclaw, ravenclaw_len) == 0) {

or any number of variations on that which might use strlen(), or a pointer rather than array (if not using sizeof) or PROGMEM with strlen_P() and memcmp_P() or... etc, etc, possibly putting this into a function so you can reuse it.

As a side note, if you know payload contains non-null-terminated text that you want to print, you can use the overload of write() that allows you to specify the length.
Serial.write(payload, length);


Arduino Nano use SPI pins as I/O pins? and still be able to do ISP?

Yes, you can use SPI in your sketch just as you like. The programming over ISP is triggered by resetting the microcontroller. That means, that when trying to program over ISP your sketch (which configures the SPI hardware for use) doesn't run. The programming is starting at a stage, before the sketch runs, thus the sketch cannot interfere.

By the way: The same is correct for programming over Serial, though for a different reason. Programming over Serial is done by the bootloader, which runs before your sketch.


I think I am using a setup like you wish at my home:

PoE Switch (for example Cisco SG300-28P)
Arduino Ethernet's with PoE Module (https://www.arduino.cc/en/Main/ArduinoBoardEthernet) I bought one for every room ;-)
Use DHCP-Server on raspberry PI
Put your sensors on your Arduino ethernet board
I am also using MQTT as protokoll for example http://pubsubclient.knolleary.net/
Use MQTT broker Mosquitto on raspberry pi

For the case that you want to use your switch also for internet connectivity, define a vlan (search wikipedia) for your arduino sensor network.

Hope that helps.


Neither the Uno nor the Mega have the hardware required for Bluetooth. I have no idea what “The Arduino 101 extension” is (you don’t provide a link - and you should.)

If that’s only software, it can’t possibly provide a feature that requires hardware support. You’ll need to add a Bluetooth module to your Arduino.

After doing some searching, I found this link: https://randomnerdtutorials.com/getting-started-with-mit-app-inventor-2-and-arduino/

It discusses using the MIT app inventor 2 and a hardware Bluetooth module to communicate between an Arudino and an Android device. I don’t know if they support other desktop or mobile device platforms or not.


How should I decide the cut-off frequency for my low-pass filter?

That looks like the spectrum of an 8-bit sound that is playing low bass notes only.  Most everything above that looks like noise floor.  (You can only get about 6 dB range per bit of resolution, so 8 bits gives about 48 dB max.)  If this is the case, you definitely don't want to reproduce the upper frequencies.  If you want to stick to your original PWM scheme, use pins 5 or 6 because they use 980 Hz PWM instead of 490.  I suggest you determine the filter by trial and error, since it comes down to how much PWM carrier you can tolerate.  You can make a simple RC filter using the formula F = 1 / (2 * pi * R * C) where F is the cutoff frequency in Hz, R is ohms, and C is farads (that's 10^6 microfarads per farad).  This type of simple filter will have a very soft cutoff frequency, about 6 dB per octave, so if you set it for 123 Hz (3 octaves below 980 Hz) the 980 Hz PWM will be reduced by 18 dB.  The R connects to the PWM pin, and the C goes from the other end of R to ground, as does the signal output.  The formula assumes that there is no output load, so you should connect an amplifier there.  If you are like most folks, you probably have fewer capacitor values on hand than resistor values, so pick the C value first.  Let's say it's 1 uFd.  Then if you use R=1K the cutoff will be 159 Hz.  Change R while listening to the output


You are still not giving the full picture, pun intended.

I'll give you an example of what sort of info is missing.

For example, what's the frame rate? What's the color depth of the sensor?
If you look at the SAM3x TRM, it says that the SPI is clocked at max 65MHz.

So, the (simplified) math would say:

24bit/pixel * 5Mpixel / 65MHz =  1.846 seconds

And that doesn't even account for acquisition time, so if you do not have fully working DMA on both sides, it's probably even worse.
And it will be worse, because you cannot stuff in RAM in one go the entire image.

But maybe that's good enough for you, however it's not possible to say because of the missing info.


Simulate motor encoder quadrature signals using an Arduino UNO

Wow, that turned out to be way harder than I expected. It is very hard to do cleanly on the AVR timer. But I was able to come up with this working function, which I think is what you are looking for...
// freq_hz is frequency in hertz from 122 to 4,000,000
// shift_deg is phase shift between output A and output B in degrees (values outside -180 to +180 are normalized)

// Note that at frequencies above 44KHz you will loose precision on phase shift. At 4Mhz, everything is rounded to just 0 or +/-90 degrees.
// Note that all timing happens in 1/16Mhz increments, so frequencies that do not land on integer multipules of that will be aproximiate.
// Use startWaveforms() directly for more precise control.

void startQuadrature( unsigned long freq_hz , int shift_deg  );

It can glitch at start-up, shutdown, and changes in speed and direction... but so can a motor encoder so I guess that is ok. It would be possible to create a glitch-free version but more work.
Github repo here...
https://github.com/bigjosh/Quadrature
So, to simulate a motor going forward with 50KHz pulse rate, you would use something like...
startQuadrature( 50000 , +90);
...and the same pulse rate going backwards would be...
startQuadrature( 50000 , -90);
Do note that if you connect an Arduino UNO output pin to a Raspberry Pi input pin that it will likely damage the Pi. This is because the UNO outputs 5 volts for a "1" signal, but the Pi can only tolerate a maximum 3.3V on any pin. You can google "5V 3.3V level shifting" for solutions to this problem.


Common ground serial communication trouble SIM800L

I finally fixed my issue.
I disable the auto baud rate of SIM800L trough FTDI232, with these at commands:

AT + IPR = 9600
AT & W

AT + IPR: Fix the baud rate at 9600
AT & W: Save in SIM800L

Then when i use with SoftwareSerial i have no issue anymore. When i reset the module with short connect RST with GND i have a good reply from SIM800L :

RDY

+CFUN: 1

+CPIN: READY

Call Ready

SMS Ready

Thanks for your help.

Note : And be sure you are a good power supply and good wire.


Why do people complain when I call my functions voids?

This is an easy mistake for a beginner to C++ to make. Let's look at other languages, like PHP:

function add ($a, $b)
  {
  return $a + $b;
  }

Or Lua:

function add (a, b)
  return a + b
end

Or JavaScript:

function add (a, b)
  {
  return a + b;
  }

Or VBscript:

Function add (a, b)
  add = a + b
End Function

All those languages have the word "function" there to indicate that you are declaring a function.

So what does C++ look like:

int add (int a, int b)
  {
  return a + b;
  }

So this must be an "int" right? Or what if it doesn't return a value?

void loop ()
  {
  }

Now it's a "void"? Kind of a weird name for a function!

Actually int and void in these examples are not weird names for functions. They are the return types of those functions. int add (int a, int b) is a function that returns an int. And void loop () is a function that returns nothing.

The C++ compiler can deduce when it is seeing a function declaration from some clues:

A return type (eg. int, float, long)
A name (the function name)
Some parentheses (for the function arguments)

Think of the word function as being there in spirit:

int [function] add (int a, int b)
    ^^^^^^^^^^   <-- don't actually type this!
    {
    return a + b;
    }


Communication between two Arduinos over RF module

You have 4 channels of raw HIGH/LOW communication.  How you use them is up to you.

The simplest method is to use an asynchronous serial protocol:

Use Serial: Connect the TX of one Arduino to channel 1 at the TX, and RX channel 1 to RX on the other Arduino
Use SoftwareSerial: The same as above but you choose the pins
Use VirtualWire: very similar to SoftwareSerial

For higher speeds, since you have 4 channels, you could use a synchronous serial communication protocol. It should be perfectly possible to connect three of the channels to SPI and communicate as if it were talking directly to an SPI device - one channel to SCK, one to MOSI and one to SS. The other end has SCK, MOSI and SS but running in slave mode.

No need to "invent" a 4-bit protocol, it's too much work.


Sending 5 Led pixel values to arduino , is this a good way?

I would recommend a similar solution as DaveX with a small modofication.

If you bitmask your LEDS, and leave room for a possible additional 3, you can mask any combination of them in the space of 00-FF. then you could send to the arduino a single string of 0xFFFFFFFF  FF(LED bitmask),FF(Red value), FF(Green Value), FF(Blue Value).

so
LED 1 {00000001 =01} all red {FF0000} would be 0x01FF0000

LED 2 and  4 {00001010 =0A} all green {00FF00} would be 0x0A00FF00

LED 5 and 1 {00010001 =11} all blue {0000FF} would be 0x110000FF

ALL LEDS off would be 0xFF000000

All LEDS onn full white would be 0xFFFFFFFF


I am planning to do a periodic table with Arduino's help but I have a few questions

Expanding an answer from my comment on your question:

First thing is to define a struct that holds all the data you want to
store and display for one element:

struct Element {
    char symbol[3];
    char name[16];
    float mass;
    char electronic_state[9];
    // etc...
};

Do not store the atomic number, as it will be deduced from the index on
the array you will build. Each string in this struct (symbol, name...)
should be big enough to store the longest possible string, including the
final NULL terminator. The compiler will help you here: if you do not
allocate enough room, it will later say something like “error:
initializer-string for array of chars is too long”.

It is obviously somewhat inefficient to allocate each string the maximum
possible length. I suggest you do this for the sake of simplicity, and
because I do not think you should be short on flash, even on an Uno. If
you really end up being short on flash, then I suggest you seriously
consider jwpat7's answer. It is somewhat complicated, but likely to be
significantly more efficient than mine in terms of flash usage.

Second step is to write down the periodic table as a PROGMEM array:

const Element periodic_table[] PROGMEM = {
    // symbol  name    mass      electronic state
    {"H",  "Hydrogen", 1.008,    "1s1"     },
    {"He", "Helium",   4.002602, "1s2"     },
    {"Li", "Lithium",  6.94,     "[He] 2s1"},
    // etc...
};
const size_t table_length = sizeof periodic_table / sizeof *periodic_table;

Then your program will only have to browse through this table in order
to get the needed information. The only tricky part here is that you
will have to copy the data to RAM before using it, for example with
something like:

Element elt;  // element in RAM
memcpy_P(&elt, &periodic_table[i], sizeof elt);

I do not have an LCD, so I wrote a test program that simply dumps the
table through the serial port:

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

void loop()
{
    Serial.println(F("Z  Symbol  Name  Atomic mass  El. state"));
    Serial.println(F("---------------------------------------"));
    for (size_t i = 0; i < table_length; i++) {
        Element elt;  // element in RAM
        memcpy_P(&elt, &periodic_table[i], sizeof elt);
        Serial.print(i+1);  // Z = i+1
        Serial.print(F("    "));
        Serial.print(elt.symbol);
        Serial.print(F("     "));
        Serial.print(elt.name);
        Serial.print(F("  "));
        Serial.print(elt.mass);
        Serial.print(F("  "));
        Serial.println(elt.electronic_state);
    }
    Serial.println();
    delay(1000);
}

This program only takes 4480 bytes of flash. This means I could expand
the table to 118 elements and over 200 bytes of data per element before
running out of flash on an Uno.


This schematic contains also the OpAmp stage for a microphone.
You could take it as reference against the design you are using.
The LM386 is basically a more integrated version, iirc.


How would I hook up the arduino to the 12v system? As in, what should I do to protect the io of the arduino?

First you're going to need to do some investigative work. You're going to need to beg, steel, borrow (or use your own if you have one) an oscilloscope. You can then use that to examine the 12V power coming from the cigarette lighter.  Armed with that you can then tell:

If there is any power fluctuation from the engine, and
What form that fluctuation takes.

If there is any fluctuation it will appear as an AC component imposed on top of the 12V DC voltage. Removing the 12V DC offset is simple enough. All you need to do is pass the power through a high pass filter. That's simply a capacitor and a resistor. You need to ensure that the cut-off frequency of the filter is below the lowest frequency you want to measure (idle frequency) yet high enough to cut out the DC component effectively.

Once you have done that you can then clip the waveform using a diode to protect against negative voltage, and a resistor and zenner diode to limit the positive voltage.

For instance, something similar to the following (it's not exact - the source isn't creating spikes, but an offset low duty cycle PWM, which is kind of similar for demonstration purposes):

The first point measured is the 12V signal with big high voltage spikes. Next the power has been high-pass filtered by the RC network and the lower portion of the waveform clipped by the reverse biased diode. Following that the zenner diode clips the upper portion of the waveform to within safe limits for the Arduino. The 100Ω resistor with the zenner is there to limit the current through the zenner.

Don't take any of those values as gospel, since the signal I am filtering there is not your signal. You need to know your signal first before you can work out exactly how it should be filtered, but that gives you the basic idea of how it can be done.

  How would I gather the test data to see if this is possible? Is there a way to hook the arduino up to the truck via the 12v and my computer via usb and send data back that I can record or monitor?

Connect the filtered and clipped signal to an interrupt input on the Arduino. Count the pulses within a given time period (1 second, 5 seconds, whatever you choose) and multiply up for number of pulses in a minute. Don't forget to then divide by 4 for a 4-cylinder engine, since I would expect you would see 4 sparks per revolution. How you then gather the data is up to you. It might be simplest to add an SD card shield to your Arduino and record the data onto an SD card. You can then place that card into your computer to process the data at your leisure.

The best way to power your Arduino is, of course, direct from the truck's power. The safest way, because of all those nasty spikes in the power, is to use car USB phone charger adapter. Plug that into the USB of the Arduino and all should be nice and happy.