RF 433 Module with VirtualWire: transmit and receive using the same Arduino board

These lines in the ISR in VirtualWire.cpp

    if (vw_rx_enabled && !vw_tx_enabled)
        vw_rx_sample = vw_digitalRead_rx() ^ vw_rx_inverted;

and

    if (vw_rx_enabled && !vw_tx_enabled)
        vw_pll();

mean that the receive path code is just not executed while the transmitter is enabled.

It kind of seems from the comment as that might not have been true at some point in the past, though I'm not seeing a version history for an "official" version to check.

You could try to modify the code to implement both, but it is worth noting that VirtualWire has been deprecated in favor of the more versatile RadioHead, so you might want to evaluate that and perhaps make modifications there instead.


You can still use both of them although you'll need to buy another piece to make it work.

This is called the Go-Between Shield and it basically lets you re-route a pin to a different one.  You will need to change the pin number in your code to the one you re-assign that signal to but it will still work.

The signals you listed that go on that pin are very incompatible, as in if you try to do it, you'll have problems.  Every time your Wifi shield will try to connect to something, your GSM shield will reset.


cannot get low power with Adafruit Trinket

Please have a look at the schematics:
https://cdn-learn.adafruit.com/assets/assets/000/010/774/original/adafruit_products_trinket5.png?1378223478
The USB connector uses a resistor (1500 Ohms) against the 5V net and a 3.6 Volt Z-Diode on it's (D-)-Pin. In addition to the current that is drawn by the microcontroller, this part of the circuit draws some extra current. (5[V] - 3.6[V])/1500[ohm] = 0.0009333... ~= 0.001 [A].
Even though I'm not completely sure without making some tests, that seams plausible to me.
EDIT
(Answer to the OPs comment below.)
The schematics uses a normal diode symbol but has a 3.6 Volt label next to it. I assume that it should be a Zener diode with a reverse voltage drop of 3.6 Volts. If I'm right, the Diode is used to limit the 5 Volts to 3.6 Volts (for what reason ever). The Zener Diode effectively limits  the Voltage over it to 3.6 Volts. The rest of the voltage of 5 Volts must be dropped over the resistor. i.e. 5V - 3.6V = 1.4V. This voltage drop tells us  by Ohms Law that the current through the  resistor is:
I = U / R
I[A] = 1.4[V] / 1500[Ohm]  = (about) 1 mA.

This value is very reasonable for your observations and the current is drawn from the 5V connect, hence you can measure it, even if you would desolder the microcontroller.


How do I use Microduino (mCookie) on Linux?

First you will need the arduino 1.6.x package from updates, not the 1.0.x package from fedora. Then:

  You will be adding a URL to the new Additional Boards Manager URLs option: https://github.com/wasdpkj/Microduino-IDE-Support/raw/master/package_Microduino_index.json

source

This tutorial tells you where and how to add that URL to the preferences, as well as how to actually install the required support files.

As of this writing, the platform configuration supplied as part of the above won't work out of the box in Linux; you will also have to edit ~/.arduino15/packages/Microduino/hardware/avr/1.6.7/platform.txt to:

replace compiler.path={runtime.tools.avr-gcc.path}/bin/ with just compiler.path=/usr/bin/
on the line starting recipe.ar.pattern=, change {archive_file_path} to {build.path}/{archive_file}

Hopefully this will be fixed in future versions.

You probably also want to prevent ModemManager from probing the serial device with this udev rule, just replace the vendor and product IDs as appropriate:

SUBSYSTEM=="usb-serial", ATTRS{idVendor}=="xxxx", ATTRS{idProduct}=="xxxx", ENV{ID_MM_DEVICE_IGNORE}="1"


How to Run Stepper motor through Serial Communication

Per the documentation of the AccelStepper’s runSpeed()
method:

  You must call this as frequently as possible, but at least once per
  step interval,

It appears the AccelStepper library is not compatible with blocking
code. Not a big deal, blocking code is almost always bad practice
anyway. However, Serial.readStringUntil() is a blocking function: it
will prevent the program from doing any useful work.

You have to read the serial port in a non-blocking fashion,
use the commands to set the motor speed, and always call runSpeed() as
frequently as possible.


There is only one "while loop inside a while loop" and that is hardly complex:

while (Serial.available() == false) {}

All that means is "Wait for something to become available on the serial".  That is ALL it does.

There is nothing even remotely complex there.  True, it may not be very well written (as is the case with lots of code on t'interwebs).  It's time to start learning how the code works so you can write your own.


You could try to flash the firmware of the USB controller.

General steps for Arduino R3 are:

Put the Arduino in DFU mode (the R3 does not require soldering for that)
Flash the firmware using:

dfu-programmer atmega16u2 erase
dfu-programmer atmega16u2 flash Arduino-usbserial-atmega16u2-Uno-Rev3.hex
dfu-programmer atmega16u2 reset

The package "dfu-programmer" is most likely available for your distribution.

If you have to build it from source, because your DFU programmer does not know the ATmega16U2 yet, you will need to install libusb-dev (on Debian-based systems).

Useful links for that:

Resetting your Uno R3's default firmware
Updating the Atmega8U2 and 16U2 on an Uno or Mega2560 using DFU

A useful search term for that is Arduino R3 DFU-programmer.


Regarding the output voltage and current in arduino

You don't need to "calculate" anything with a MOSFET.  You will be using it in the saturation zone. That means it is fully turned on and will allow through the current you need.

However, the gate of a MOSFET looks, to all intents and purposes, like a small capacitor. That means there will be a certain amount of inrush current to the gate when you turn it on. To limit that inrush current you need a small resistor (say 100-220Ω) on the gate.

When using a BJT, though, you need to ensure that you allow enough current through the base to allow enough current through the collector.  Divide the current you need through the collector by the Hfe (typically 100 for a small signal transistor) and that is the minimum current you need to allow through the base. Subtract a silicon junction voltage (0.6V) from the voltage of the IO pin (5V). Divide it by your base current calculated above, and that is the maximum resistor you can use on the base.

And also your transistor symbol in your schematic is backwards.


You need to send the 5x24 bits out without a pause. If you then keep the line low for over 80us, that is interpreted by all LED drivers as the reset signal. It is not stated explicitly in the datasheet (at least I haven't found it), but I guess the reset signal means, that at that time all drivers will output the received values on the LEDs. That way you can light up all LEDs at the same time with their respective data.
The picture, that you refer to, explains the automatic data cascading. The first row is what you actually send from your microcontroller and also what is seen by the first LED driver in the row. That driver will then consume the first 24 bits, that it sees. After that, it will forward the rest of the data to the next LED driver. That will now consume the first 24 bits that it sees (thus the second 24 bits, that you have send). The third LED driver will do the same. But since in that example you only send data for 3 LEDs, no data is forwarded. Then the reset pulse happens and at some point in time you send a new set of data.
So each row represents, what the corresponding LED driver will see of the data, that you send. D1 sees all the data. Each following LED driver will see 24 bits less. D4 will see nothing, since you send only 3x24 bits in that example.


Motors tend to use more current than the arduino can supply, try hooking up the motor to a different power supply than the arduino 5V. What most likely is happening, is that when the motor turns on, it alters the value of the voltage, which the temperature sensor is using to tell the arduino what the temperature is. You need to have the temperature sensor hooked up to the arduino to have the reference at the right voltage, so the motor should be on a different power supply. That should fix things.


Looking at the schematic of arduino UNO here you can see that Pin 0 and Pin 1 are connected to the same line of RX TX of the ATMEGA8U2. So in theory (and assuming the ATMEGA8U2 behaves like any usb to uart IC) if you remove or disable the ATMEGA328P, your arduino should behave like any cheap usb to serial. The way you can "disable" ATMEGA328P is by setting it in constant reset mode as explained here

By manually reseting and setting the esp into flashing mode, you should be able to upload the new firmware to it from arduino IDE for example by selecting the ESP device.

Two notes on this

1 - The TX line of the ATMEGA8U2 is the marked RX on arduino Uno board and RX line of the ATMEGA8U2 is the marked to TX on arduino Uno board. That means your ESP RX should connect to pin 0 on arduino and TX of ESP should connect to pin 1.

2 - You might need voltage level conversion on pin 0 as ESP is a 3.3V device although in schematic there is 1K resistor in that line


SPI is synchronous. That means that within certain constraints the timing and the width of any part of the signal is irrelevant.

What makes you think that it's bad to have a slight variance in the timing, or that the "pause after CS goes LOW!" is "too low"?

If you think it's from the timing diagrams, those times are minimum times (generally) and all things happen at either the rising or falling edge of the clock (depending on the SPI mode).


Thanks to Mikael Patel for suggesting that link (your Google-Fu must be strong!).

I am pasting the code below so that this answer survives any possible future deletion of the read-only part of the Arduino Forum.

//ONG LIT YIT 2013-07-20
//This following code plays happy birthday melody on Arduino
//Put Piezo Buzzer on GDN and 9 (Positive and negative are reversible)
//this project requires a Piezo Buzzer and

// an Arduino board and
//jumper wires to connect Buzzer's (+) to ~9 and (-) to GND (any GND)

const int speakerPin = 9;
const int LENGTH = 28; // the number of notes
const char notes[LENGTH + 1] = "GGAGcB GGAGdc GGxecBA yyecdc";
const int beats[LENGTH] = { 2, 2, 8, 8, 8, 16, 1, 2, 2, 8, 8, 8, 16, 1, 2, 2, 8, 8, 8, 8, 16, 1, 2, 2, 8, 8, 8, 16 };
const int tempo = 150;

void playTone(int tone, int duration)
  {
  for (long i = 0; i < duration * 1000L; i += tone * 2)
    {
    digitalWrite(speakerPin, HIGH);
    delayMicroseconds(tone);
    digitalWrite(speakerPin, LOW);
    delayMicroseconds(tone);
    }
  } // end of playTone

void playNote(const char note, const int duration)
  {
  char names[] = {'C', 'D', 'E', 'F', 'G', 'A', 'B',
                  'c', 'd', 'e', 'f', 'g', 'a', 'b',
                  'x', 'y'
                 };
  const int tones[] = { 1915, 1700, 1519, 1432, 1275, 1136, 1014,
                  956,  834,  765,  593,  468,  346,  224,
                  655 , 715
                };
  const int SPEE = 5;

  // play the tone corresponding to the note name
  for (int i = 0; i < 17; i++)
    {
    if (names[i] == note) {
      int newduration = duration / SPEE;
      playTone(tones[i], newduration);
    }
  }
} // end of playNote

void setup()
  {
  pinMode(speakerPin, OUTPUT);
  } // end of setup

void loop()
  {
  for (int i = 0; i < LENGTH; i++)
    {
    if (notes[i] == ' ')
      {
      delay(beats[i] * tempo); // rest
      }
    else
    {
      playNote(notes[i], beats[i] * tempo);
    }

    // pause between notes
    delay(tempo);
  }
} // end of loop

I also cleaned up the code a bit.


Using HC-SRO4 sensor and looking for obstacle

There's not much code there, so not much to optimize. I will however show you how to combine your two ifs.

You have:

if(mappedValue>=distance)//checking if the object is in range
    Serial.println("YES");
  else
    Serial.println("NO");
  if(mappedValue>=distance)
    digitalWrite(11,HIGH);
  else
    digitalWrite(11,LOW);

and I guess you tried this:

if(mappedValue>=distance)//checking if the object is in range
    Serial.println("YES");
    digitalWrite(11,HIGH);
  else
    Serial.println("NO");
    digitalWrite(11,LOW);

That would be correct in Python where the indenting matters (oh how that brings back the PTSD of having to work with COBOL...) but not in C.  In C indenting is ignored completely. It's only there for our benefit in reading the flow of code.

Instead to group statements together within an if or an else (or any other conditional or loop structure) you wrap those statements in a block. That is, place { before it and } after it.  Thus:

if(mappedValue>=distance)//checking if the object is in range
{
    Serial.println("YES");
    digitalWrite(11,HIGH);
}
  else
{
    Serial.println("NO");
    digitalWrite(11,LOW);
}

Or with my preferred formatting:

if(mappedValue>=distance) { //checking if the object is in range
    Serial.println("YES");
    digitalWrite(11,HIGH);
} else {
    Serial.println("NO");
    digitalWrite(11,LOW);
}


Setup of Arduino Uno as ArduinoISP for programming attiny45

The capacitor is meant to prevent the programming Arduino from being reset. Normally, when you open the serial connection, the Arduino gets reset and first starts into the bootloader (which would be used to program it). But when using the Arduino as ISP programmer, you don't want to run the bootloader of the programmer. You want to let the programmer sketch work as intended. Thus you want to prevent the programmer from resetting on serial connection. The capacitor between Reset and ground holds the 5V level of the reset pin for the time, that the reset pulse from the USB Serial chip is trying to pull the pin to low. So it prevents the reset from happening.
The value and type of the capacitor is not critical here. I always use a 47uF bipolar electrolyte capacitor, because I have a bunch of them just laying around. The value just shouldn't be unreasonable small or big. The mentioned range of yours is just giving you a hint in which order the value should be. Also you can simply test, if the reset happens with your capacitor. You cannot break things with a wrong value here.

Which clock frequency to use is up to your exact requirements. There is no "this is the best for all occasions"-frequency. Also you are not wrecking the Attiny with any of the clock speeds. Though you should note, that choosing an external clock source means, that you actually need to provide that clock source for the ATTiny to work. The fuses can be reprogrammed, if you have chosen a wrong frequency by accident.
The datasheet states just as you wrote. The interal oscillator is by default set to 8MHz, while the prescaler divides that down to 1MHz as the main CPU clock. So by default the ATTiny runs on 1MHz. You can change that, if you like.
For my Attiny85s I always used internal 8MHz as the setting (the option, that appears in the IDE menu). That is the easiest way (internal means you need no external components for the clock), while being the fastest speed you can get with the internal clock, I think.


Voltage divider arduino 5v and Ethernet board 3.3

From experience with 3.3v ESP8266es with 5v Arduinos, only the signals to the 3.3v device need to be converted (5v high -> 3.3v high). A 3.3v level to the Arduino is high enough for 5v logic to still read it as HIGH. That means you can get away with just a voltage divider on each of the Arduino -> ENC28J60 pins.


Here's a pretty definitive list for you:

// Allocated once in the global area and assigned during
// program startup
int foo = 1;

// May not even be allocated - the compiler will most likely
// optimise it out.
const int foo = 1;

// Allocated once and assigned during program startup. Cannot be
// accessed from outside the file.
static int foo = 1;

// The static here has no real effect.
static const int foo = 1;

void function() {
    // Allocated in the stack each call and initialised each call.
    // Only accessible from inside this function.
    int foo = 1;

    // Allocated in the global area and initialized on the first call
    // of the function. Only accessible from inside this function.
    static int foo = 1;

    // May not be allocated at all. Only accessible from inside
    // this function.
    const int foo = 1;
}

Note that non-simple const values, things like arrays and strings, depending on the architecture (i.e., if it's a Harvard architecture or not) may be copied into a block of global RAM for simpler access. See PROGMEM in the Arduino Reference Manual for more information.


how to count blinking LED flashes using arduino uno boards and LDR?

LDRs only give an analog output, proportional to the amount of light.

To make it give a HIGH and LOW value, you have to tweak the other resistor used in the voltage divider.

Alternatively you could use analogRead and add a threshold value in your code.


This value looks pretty correct to me. It is stored in little endian thou.

0x43000000 is the actual value.

Serial.print(x, HEX) truncates leading zeros. so 00 gets 0
So your output is 0 0 0 43 which corresponds to the little endian representation of the above.

Make yourself familiar with the floating point representation IEEE-754.

Also try the online FoatConverter.

Try the following:

char floatString[9];
sprintf(floatString, "%02X%02X%02x%02x", chpt[3], chpt[2], chpt[1], chpt[0]);
floatString[8] = '\0';
Serial.print(floatString);


parallel communication simulation problem

You problem is that you are only using one phase of your "ES" clock, when in fact you should be using two.
In the first phase, where ES is high, is where you set the IO pins to represent your transmitted byte. Only once that is done can you then progress to the second phase, where ES is low, to indicate to the receiver that "I have set up my outputs, it's now time for you to read them".
So your transmitted code would flow like:

Set ES HIGH
Set output pins to represent the byte
Set ES LOW
Delay
Set ES HIGH

If you look at any timing diagrams for any protocol there will be places where the data is being written to the bus, and places where the data is considered stable and able to be read by the receiver. It's the job of the clock signal to indicate where these points in the protocol - to synchronise the receiver.
For example, here is the Centronics (parallel port) protocol:

The data changes while nStrobe is HIGH, and only when that data is "settled" is nStrobe brought LOW to tell the receiver it can read the data. Once nStrobe is taken HIGH again the data is changed to the next byte to transmit.


So I Finally sort out the problem. Both Battery and Module was completely fine. The problem was with the connecting wires. The connecting wires for some reason was not capable to hold the 2amp current. As a solution what I did was, cut the legs of some  quarter watt resistance and solder them to the wire exiting from the battery and fed them directly to the vcc and ground of the module. This way it works perfectly fine.
Even it seems a weird problem with no proper explanation but this solution works for me.
-----------Editing for a better explanation-------------
So my problem was with the connecting wires. For some reason the wires I primarily used could not deliver the the current from battery terminals to the module. May be those wires had a higher resistance for which the current flowing through those could not stay at 2 ampere magnitude and by the time it traveerses the wires and reached to the module, it was no longer at 2 ampere and might be lesser than a certain value which could not trigger the module and so the module did not work.
what I did was cut some legs of a few quatter watt resistance (the metal leads getting out from the carbon resistance from both sides:pic added) and sholder them to the battery terminals. Since I knew the metal legs of quatter watt resistances had a very less resistance from my course that trick worked and delivered 2amp current through them to the module.
I am trully sorry for not attaching picture as I have already submitted the project and currently have no way to replicate the situation.


#define macro not in scope when i try to use IR library

C++ is case-sensitive. Button_8 is different from BUTTON_8.


If i keep using the CR2032 battery for long run 24/7, how long will battery last? is there a chance of explosion?

Yes. Recharging a non-rechargeable battery is dangerous. It should be avoided at all costs.

  is there any other way than modifying the module it self?

You have to prevent the power getting to the battery. That power is fed through a diode (hence 4.3V, which is 5V minus 0.7v for a silicon diode forward voltage).  Without knowing what the module is, I can't tell you if there is any other way that modifying it - however I would guess that no there isn't. You need to stop that power getting to the battery, and that can only be done at some point between where the power comes in to the module and the battery itself - and the simplest method is to remove the diode.

The purpose of that diode is to prevent power from the battery from trying to power the rest of your circuit when you remove the main power. Removing the diode will have no adverse affect.  You just won't be able to charge a rechargeable battery in future.


how does an 8-bit AVR do 10-bit analog read?

It can do a 10-bit reading quite simply - because the ADC is a 10-bit ADC.  The CPU register size doesn't dictate what it can communicate with, either internally or externally.  The only thing it dictates is how big a number it can cope with at any one time.  Because of this the 10-bit result of the ADC is spread across two registers - 2 bits in the "high" ADC result register, and 8 bits in the "low" ADC result register.


The Arduino IDE does its own non-standard preprocessing before the C++ preprocessor/compiler is invoked. One of the main purposes for this is to detect #include directives which refer to libraries so it can link them properly.

My guess would be that part of this procedure ends up moving all #include lines to the start of the file. In the code you've posted, that means I think it's being moved outside the whole #if/#else structure.

In most cases, you can avoid the Arduino IDE trickery by moving things into a separate header or source file. Unfortunately though, doing that means it may not link the libraries properly. As such, the easiest solution may be to switch to a 3rd party IDE which has Arduino support (e.g. Eclipse).


The millis() function is defined in the Arduino Core for AVR architecture, specifically the wiring.c file.

You can see that timer0 is setup with various parameters for prescaling and interrupt triggering and handling of timer0 overflow such that a variable called timer0_millis contains the number of milliseconds since the sketch started.

The millis() function basically returns that timer0_millis value.

If you wish to make use of the function in AVR Studio, then you would need to include the same kind of timer0 setup and interrupt/overflow handling that the Arduino core does.


A simple switch, frequently called single pole single throw, will have only two pins. A switch works by breaking the circuit. This is shown in a wiring diagram in this manner:

It matters not that the switch in this image is not the same switch as in the image you linked, the operation is identical. You may find momentary switches with similar appearance and identical diagrams. The difference is that one has to hold the button to make (or break) a circuit, which reverts once released.

You mention four pins. Those switches are electrically identical to the SPST switch, except that you may find you can control two independent circuits that both activate when the button is pressed. That would be a double pole single throw. There is also the possibility that the four-pin switch has common connections on each side. That is to say that if you connect your circuit to one pin, it is conductive to the other on on the same side, while the closure of the switch will also equally effect the two pins on the opposite side. I've found some tiny switches that have this arrangement, ostensibly to provide for four points to solder to the circuit board, making for a more sturdy attachment.

One can find some useful switch information on Electronics Hub, which is too exhaustive to cover here.

There are many other types of switches


Don't do delays inside an ISR. Don't do serial prints inside an ISR. Read this.

You need to redesign. The ISR can set a flag, that you then test in loop. Do the delay in loop.


Ensuring specific frequency at specific time?

Generating a linear frequency ramp with accurate timings is not an easy
task. I am providing here only a partial answer, where I first go
through the math of the problem, then give some ideas for the
implementation.

The math

We are dealing with a frequency-modulated signal, with the frequency
ramping linearly from f = 0 at t = 0 up to a
maximum f = fM at
t = tM. Specifically, we have
fM = 48 kHz and
tM = 10 s.
Then, the instantaneous frequency is

f(t) = a t

where a = fM/tM = 4.8
kHz/s is the “acceleration” of the pulsed signal.

Let's define the “integrated frequency” as

n(t) = ∫ f(t) dt = a t²/2

This quantity can be interpreted as the number of cycles completed at
time t, except that it is a continuous variable. The first cycle
starts when n = 0 and ends when n = 1, the next
cycle starts when n = 1 and ends when n = 2, and
so on. The output signal would be high when the fractional part of n
is between 0.25 and 0.75 (or maybe between 0 and 0.5, depending on your
choice of initial phase).

From here, we can calculate at what time each cycle should start:

t(n) = √(2 n/a)

and, by successive differences, the length of each cycle:

n       0     1       2       3      ... 239,998    239,999    240,000
t       0     20,412  28,868  35,355 ... 9,999,958  9,999,979  10,000,000
length   20,412   8,455   6,488      ...        20.833     20.833
diff          -11,957 -1,967  -1,018 ...            -0.000043
approx        +81,650 -1,408  -913   ...            -0.000043

In the table above, all times are in microseconds. The lines are:

t: time
length: length of one cycle
diff: difference between lengths of successive cycles
approx: approximated formula for that difference

The columns are staggered because each cycles spans the duration between
two successive values of t, and duration differences are computed
between successive cycles. The approximated formula is based on the
Taylor expansion:

T(n+1) − T(n) ≈ dT/dn + 1/2 d²T/dn² = −aT³(1 − 3/2 aT²)

where T = 1/f, the instantaneous period, approximates the
length of one cycle. The approximation is not good for the very first
cycles, but it converges pretty fast to the correct value.

Implementation

I did not write an implementation, so I am giving here only some ideas
on how to do it.

I would use Timer 1 of the Arduino Uno, in one of the modes that allows
frequency-modulation, i.e. a PWM mode where the counter TOP is set by a
register (mode 8, 9, 10, 11, 14 or 15). I would set the prescaler to 8
in order to allow for the maximum required period length. The period
resolution would then be:

8 CPU cycles = 0.5 µs in modes 14 or 15 (fast PWM)
16 CPU cyels = 1 µs in the other modes

It could be noted that single-cycle resolution is possible with the
prescaler set to 1, but the first 5 cycles are too long for this
setting. Maybe the prescaler could be changed after the fifth cycle, but
it would be tricky to do so without any glitch.

The timer overflow interrupt would fire at the end of each cycle, and
it's ISR (namely TIMER1_OVF_vect) would be responsible for updating
the timer period in order to make the next cycle shorter than the one
just elapsed. It would do something like

period -= delta(period);

The period should be computed with 32-bit arithmetic, because the
changes get tiny by the end of the ramp. Only the 16 most
significant bits of the computed period would actually be written to the
timer register. The delta() function should be inlined and fast. I may
try the approximation from the previous section implemented in
fixed-point. Or maybe just a table lookup using only the most
significant bits of the period as an index, with the table in PROGMEM.

For details on how to actually program the timer, see
the datasheet of the ATmega328P, section 16.

Update: The following algorithm seems to work well. At least in
simulation, I did not put it inside an ISR. It assumes fast PWM, i.e. a
0.5 µs timer resolution. It remembers the current value of delta
and divides it by 2 each time the period falls below some threshold. The
computed f(t) is almost as smooth as you can expect given the
limited resolution of the timer.

uint32_t period = 40825UL << 16;  // 1st cycle is 20412.5 us
void update_period()  // should be in ISR(TIMER1_OVF_vect)
{
    static const uint16_t thresholds[] = {
            17633, 13309, 10229, 7954, 6230, 4905, 3873, 3063,
            2426, 1923, 1525, 1211, 960, 762, 605, 480, 381,
            302, 240, 190, 151, 120, 95, 76, 60, 48};
    static uint16_t threshold = 29000;
    static uint8_t index = 0;
    static uint32_t delta = 6UL << 27;

    uint16_t period_h = period >> 16;
    if (period_h <= 42) return;  // final frequency achieved
    if (period_h < threshold) {
        threshold = thresholds[index++];
        delta >>= 1;
    }
    period -= delta;
    // set the timer period register to (period >> 16) - 1.
}


Each hardware package has its own version of Print.h in the cores folder. The Arduino IDE installation includes a copy of the Arduino AVR Boards hardware package but that package will not be used if you installed a different version via Boards Manager (Tools > Board > Boards Manager) or if you have a board selected from the Tools > Board menu that is not part of the Arduino AVR Boards package. Operating systems seem to like to hide the folder that Boards Manager installs the hardware packages to by default, which makes things more confusing.

The easiest way to find the location of the active hardware package, and thus the Print.h you want to edit is this:

Select a board of the hardware package you want to locate from the Tools > Board menu.
File > Examples > SPI > BarometricPressureSensor (or any other example sketch of the SPI library)
Sketch > Show sketch folder - this will open the BarometricPressureSensor example sketch folder.
Navigate up 4 folder levels to the architecture folder.
Open the cores subfolder of the architecture folder.
If there are multiple folders inside the cores folder you will need to open boards.txt (which is located in the architecture folder) and find which core library your board is using, which is specified by the build.core property. Most hardware packages only have a single core library so this should not be necessary.
Open the core folder. There you will find Print.h.

The reason I selected the SPI library example is because this is a hardware specific library that is bundled with all hardware packages I've encountered. If you encounter a hardware package that does not bundle an SPI library you would want to open the example for another hardware specific library such as Wire, SoftwareSerial, or EEPROM.


Turn on each of the LEDs in order, by setting the cycle delay to 100 milliseconds

I see in your second diagram that you are controlling the ground side of the LEDs. digitalWrite(PinNumber, HIGH) will turn an LED OFF, digitalWrite(PinNumber, LOW) will turn an LED ON. Using delay() in a sketch should be avoided.

void setup(){
  pinMode(13, OUTPUT);
  pinMode(12, OUTPUT);
  pinMode(9, OUTPUT);
  pinMode(6, OUTPUT);
  digitalWrite(13, HIGH);
  digitalWrite(12, HIGH);
  digitalWrite(9, HIGH);
  digitalWrite(6, HIGH);
}

void loop(){
  digitalWrite(13, LOW);
  delay(100);
  digitalWrite(12, LOW);
  delay(100);
  digitalWrite(9, LOW);
  delay(100);
  digitalWrite(6, LOW);
  delay(100);
  digitalWrite(13, HIGH);
  digitalWrite(12, HIGH);
  digitalWrite(9, HIGH);
  digitalWrite(6, HIGH);
  delay(100);
}


The numbers you are reporting are very familiar to me.  They are telling me that it is not possible to obtain the time from the RTC chip.

You are getting the time from your server, and as long as the string is actually what you think it is, then the values should be fine.  This snippet works perfecty:

#include <RTClib.h>

char siteData[] = "May 19 2015-09:17:24";

void setup() {
    Serial.begin(115200);

    char *tempDate = strtok(siteData, "-");
    char *tempHour =  strtok(NULL, "-");
    DateTime now(tempDate, tempHour);

    Serial.print(now.year(), DEC);
    Serial.print('/');
    Serial.print(now.month(), DEC);
    Serial.print('/');
    Serial.print(now.day(), DEC);
    Serial.print(' ');
    Serial.print(now.hour(), DEC);
    Serial.print(':');
    Serial.print(now.minute(), DEC);
    Serial.print(':');
    Serial.print(now.second(), DEC);
    Serial.println();
    Serial.println();
}

void loop() {
}

So it must be in the passing of the data through the RTC chip that is failing.

Check that the chip is actually wired up properly, is running, and is responding normally before you try adding in the code to set the time from the server.


Measure voltage changes with unknown baseline

An audio signal consists of two main components:

An AC signal
A DC offset

What you are interested in is the AC signal, but not the DC offset.  That DC offset is what is drifting in your current model.

So you need to AC couple the signal. That is, couple the signal to your Arduino in such a way that only the AC portion gets through.

The simplest way is with a capacitor.

But the Arduino can't handle negative voltages, and an AC signal has negative voltages. So you need to get rid of them.

The simplest way is to add a DC offset.

But didn't we just get rid of a DC offset that we didn't want? Yep. But that was an unknown DC offset. If we then add in a DC offset that we do know, and is stable, then we can work with it.

Here's a very simple circuit:

simulate this circuit – Schematic created using CircuitLab

The capacitor C1 removes the existing DC offset.  R1 and R2 then form a voltage divider giving 2.5V (half of 5V), which is then added to the pure AC signal.

That means that the signal now varies around 2.5V.  Silence is 2.5V, and noise is other values above and below that.

Since 2.5V is half of the 5V the Arduino runs on, silence should read at somewhere near half the ADC value. That's about 512.  Sound will be both above and below that value.

So if you subtract 512 from your analog reading you will effectively be subtracting the DC offset you just added, giving you a value that can be either positive or negative.

For simplicity, since you don't care whether it's positive or negative, you can then remove the sign from the number to just give you a magnitude.

int audio = analogRead(A0); // Get a sample
audio = audio - 512; // Remove DC offset
audio = abs(audio); // Remove sign

You can now compare that to a threshold value:

if (audio > 100) {
    // do something
}


Circuit doesn't work when multimeter/current meter is attached

Multimeters have something called a "burden voltage". See this PDF: uCurrent - A professional precision current ... - EEVblog.

Also see Dave Jones' video: µCurrent

Meters measure current by dropping voltage over an internal resistor, and measuring the drop. By definition therefore, there is a voltage drop, which is the "burden voltage".

  the circuit misbehaves, never goes into sleep, and doesn't record any data

If you put a voltmeter on the processor side of the ammeter you will probably find that the voltage going into your processor is somewhat less than you think. That would account for the misbehaving.

One possible approach is to crank up the voltage from your power source, checking the voltmeter to see that it reaches the expected voltage on the processor side of the ammeter, however in a circuit which might turn on and off (ie. sleep) this voltage might jump around (depending on the current) so this should be done with caution (to not exceed the maximum processor voltage).

  Or do I need a different kind/quality of multimeter?

A higher quality meter may well help - watch that video and look at the PDF to see what I am talking about. My meters (which cost more than $15) don't have this problem to the same extent.


How to get current WiFi signal strength?

You use WiFi.RSSI():

RSSI
Return the signal strength of Wi-Fi network, that is formally called Received Signal Strength Indication (RSSI).
WiFi.RSSI()

Signal strength value is provided in dBm. The type of returned value is int32_t.
Example code:
Serial.printf("RSSI: %d dBm\n", WiFi.RSSI());

Example output:
RSSI: -68 dBm


I'm getting watchdog timer resets in NodeMCU. How can I permanently disable or stop that?

here my way to find the bug first
1.comment out the watchdog from the code.
2.debug the code flow and find it get struck. Debugging in the sense put "Serial.print()" in between your code where you feel stuck but here don't disable your watchdog.


Use pointer in calculation results in error

Try this:

long* lRaceStartTime = RaceHandler.lRaceStartTime;
long lRaceElapsedTime = micros() - *lRaceStartTime;

You assigned the pointer to lRaceStartTime on the first line, but on the second line you are subtracting the pointer from micros() which returns an unsigned long.  You need to dereference the pointer before subtracting. Also you might consider making all your longs unsigned to match the return type of micros() http://arduino.cc/en/reference/micros


As I commented on deltaray's answer, a regular expression library is
overkill for finding a fixed string. There is a standard avr-libc
function for that called strstr():

char * strstr(const char *haystack, const char *needle);

where haystack is the Web page and needle is the fixed string you
are searching for.
There is an issue with this function though: in order to use it, you
need to have the whole haystack in RAM. For a non-trivial Web page, this
may not be doable on a small Arduino.
Below is a custom solution based on a finite state machine: the
parser can be in a number of different states:

state 0 = waiting for the 'S' of "Small Craft"
state 1 = waiting for the 'm' of "Small Craft"
etc...

The state is actually an index in a character array representing the
string we are looking for. Each time the parser finds the expected
character, it moves to the next state. Otherwise it moves back to state
0. There is a small kludge though: when in the state waiting for the
'N' of "Nil", if it doesn't get an 'N', it moves to the state waiting
for the 'I' of "In Operation" and tries the match again. This way it
can look for both the possible strings at once. Also, once it got the
full preamble "Small Craft Warning: </b>", if it gets something
invalid, it moves to an extra state called INVALID instead of state 0.
Here is the code:
// Possible return values of parse_forecast().
// The last three are sticky.
enum parse_state {
    NO_PREAMBLE,        // no complete preamble seen yet
    PREAMBLE_COMPLETE,  // preamble just completed
    PARTIAL_NIL,        // received preamble and start of "Nil"
    PARTIAL_IN_OP,      // received preamble and start of "In Operation"
    COMPLETE_NIL,       // result = Nil
    COMPLETE_IN_OP,     // result = In Operation
    INVALID             // valid preamble followed by invalid data
};

parse_state parse_forecast(char c)
{
    // position:      0                        25   29            42
    const char T[] = "Small Craft Warning: </b>Nil\0In Operation\0";
    static size_t i;  // T[i] is the character we expect next

    if (T[i]) {  // non-sticky state
        if (i == 25 && c != T[i])
            i = 29;      // switch to "In Op" branch
        if (c == T[i])   // found expected char
            i++;         // wait for the next one
        else {
            if (i < 25)
                i = 0;   // reset to start of the string
            else
                i = 42;  // invalid state
        }
    }
    return i <  25 ? NO_PREAMBLE :
           i == 25 ? PREAMBLE_COMPLETE :
           i <  28 ? PARTIAL_NIL :
           i == 28 ? COMPLETE_NIL :
           i <  41 ? PARTIAL_IN_OP :
           i == 41 ? COMPLETE_IN_OP :
           INVALID;
}

With this you do not need to store the Web page in RAM. Instead, you
feed the parser one character at a time and, at the end, check the
return value. You expect it to be either COMPLETE_NIL or
COMPLETE_IN_OP.
Implementation detail: there are three NUL characters in the template
string, at positions 28, 41 and 42 (the last one is implicit). They
correspond to the three possible "sticky" states.


Thingspeak Library returns 0 using ESP8266 on Arduino

#include <WiFi.h>

From the WiFi library reference page:

  With the Arduino WiFi Shield, this library allows an Arduino board to connect to the internet.

From the Arduino WiFi Shield product page:

  It is based on the HDG204 Wireless LAN 802.11b/g System in-Package. An AT32UC3 provides a network (IP) stack capable of both TCP and UDP.

But you're not using an Arduino WiFi Shield or anything compatible. You're using an ESP8266 which is completely different. Thus you can't use the WiFi library for your project.

Instead you will need to use the appropriate ESP8266 library. If you are programming the ESP8266 directly that will be the ESP8266WiFi library, which is bundled with the ESP8266 core for Arduino. If you are using the ESP8266 as a WiFi module controlled via AT commands that will be the WiFiEsp library


Arduino Mega 2560 not recognized/overloaded

First off, that is one heck of a rig.  I'm impressed to the point of "I gotta get me one of those."

Bundling your wires shouldn't have the kind of impact you are seeing, unless there are bare wires touching.  You might get induction interference, but not a total shut down.

From what I can see here, it looks like there's so much stuff connected to the Arduino that it's probably starving it for power.  You should look into using power rails for Gnd and +5v.

You will also need to check if you are supplying it with enough amps, too.  Your computer's USB port only supplies 0.5A, unless it happens to be USB3, then it's 0.9A.  Even your 5V1A PSU might not be enough.  Consider finding a 2-5 amp wall wart to do some more testing with.  There are usually spec sheets with components, so you'll need to add all the power draw for all the components, including the Arduino, and make sure you have more than enough to meet that calculated power draw.  Exceeding it by at least 10-20% is usually considered good practice, even for a test rig.

Consider powering your rig's new power rails with the extra PSU even when the Arduino is plugged into your computer.  As long as you make sure you aren't trying to take power from the computer and the PSU at the same time with the same component, you should be fine.  (Don't cross the streams.)

There could be a short or feedback loop somewhere in your sensors that's causing the extra drain.  There are so many wires here that it'd be easy to hook up something backwards.  Along with the number of wires, the bundling doesn't let SE-us help you track that down.

You might want to look at the direction your pins are facing.  It was an odd situation for me, but having two of the metal clips facing each other was enough for a short.  In your "Relay Portion:" pic, they are all facing the same way, which is good.  See if there are places where that's not the case and fix it.  Like I said, it was an odd situation, but it's a phantom problem you can avoid.


Implement two processes at the same time

Think of an Arduino as a circus clown spinning plates. It has to spend very little time on any one plate, and then it can keep a lot of plates spinning, moving quickly from one to the next.
That's how "multi-tasking" works on a realtime device like an Arduino. You write a loop function that buzzes through a bunch of sub-tasks, spending a few microseconds on each one, and then repeats the process. Each plate (sub-task) gets a little bit of time on each pass, but only a little.
The delay() function is the death of that. If you're in a delay(), everything comes to a screeching halt. Your program stops checking for button presses, stops switching output pins to control your motors, etc. It's like the clown taking a coffee break. The plates start crashing to the ground.
You might get away with single-digit delays for things like timing changes in output state (and delayMicroseconds() is rarely a problem since those delays are so short), but a delay(1000) means everything comes to a screeching halt for a full second.
You need to refactor your code to get rid of calls to delay() with delay values of more than a few milliseconds. Do a search on "Arduino blink without delay" to figure out how.
Note that on a single core device with preemptive multi-tasking, the circus clown analogy still holds, but now the OS serves as the clown's manager. The OS schedules the clown's time, and tells it when to switch between plates. If the clown gets distracted by a particularly shiny plate and tries to spend too long on that plate, the OS forces the clown to switch plates. The OS also saves the clown's current state each time it switches away from a task, and restores that state when it returns to that task.
On A multi-core device with preemptive multi-tasking, the manager (OS) has a team of clowns (cores). Each clown (core) gets assigned to different plates (tasks), and all the clowns work at the same time (The cores run concurrently.) The OS has to make sure the clowns (cores) don't bump elbows (have conflicting access to the same memory or other resources.)


Arduino not adding decimals correctly on double variable

The 8 bit Arduinos don't have precision, or anything even close to precision when it comes to working with decimal values.

There is no such thing as double on an 8-bit Arduino - it is only an alias for float. By using double you aren't gaining any more precision than using float.

Even double isn't perfectly precise. It's more precise than float (on systems that support double), but still far from precise.

People that care about specific levels of precision code using variables of that precision. That's called using fixed point mathematics, and it's what DSPs work in. It's fast, efficient, and precise up to the point that you define it to be.

Fixed point mathematics works by operating in multiples of a pre-defined fraction. That fraction is your precision, or granularity and is the smallest value that can be represented. However, working with large numbers and fine granularity results in very large variables to store all that data - which is why for most things people use float: because it compresses the data down into a very small space - and like a highly compressed MP3 it loses a lot of the data.


I don't like using the String class because it can cause memory fragmentation. This would do it by just using C-style strings:

byte fromhex (const char * str)
  {
  char c = str [0] - '0';
  if (c > 9)
    c -= 7;
  int result = c;
  c = str [1] - '0';
  if (c > 9)
    c -= 7;
  return (result << 4) | c;
  }

void setup ()
  {
  Serial.begin (115200);
  Serial.println ();

  const char * test = "#112233AB";

  byte redval   = fromhex (& test [1]);
  byte greenval = fromhex (& test [3]);
  byte blueval  = fromhex (& test [5]);
  byte whiteval = fromhex (& test [7]);

  Serial.println ((int) redval);
  Serial.println ((int) greenval);
  Serial.println ((int) blueval);
  Serial.println ((int) whiteval);

  }  // end of setup

void loop ()
  {
  // whatever
  }  // end of loop

Output:

17
34
51
171

That does not do any validation (that the string is indeed 9 characters long, and contain hex characters) but I'll leave that for you to do. :)


Problem uploading the code into an Arduino Uno

Ubuntu and other Linux operating systems don’t name the serial ports “COM1” or similar.

They use special files like

/dev/tty.[something]

The [something] depends on the USB device driver. The IDE should list available serial ports in the Port selection menu.


Having trouble using RTC if I set an ISR for a 1 second timer

In the Arduino you don't have control how are some essential parts implemented.

For example delay function requires interrupts to be enabled or it'll be deadlocked (for sure).

Serials are little bit better, it'll be working until send buffer gets full. For devices with small RAM it's 16B only! And your traceDebug is little bit longer.

In general ISR should be as short as possible and it's mainly used for setting some flag to be handled in main loop later.

volatile bool flag = false;

ISR(...) {
  flag = true;
}

int main() {
  init();

  while (1) {
    if (flag) {
      do_something();
      flag = false;
    }
  }
}


Yes, if the laptop and tablet are on the same network communication will be possible. One way to implement this would be to have a client/server setup that communicates over TCP/IP.

The laptop can act as a TCP/IP server and also communicate through the serial interface to your arduino. Many languages will be able to do this, Java, C/C++, Python, whatever you're comfortable with.

The android tablet can then connect to the TCP/IP server as a client and send and receive data through your WiFi. Have a look at the android documentation.

This would a simple solution but for a more permanent solution you could also setup a web server on your laptop, look into the apache webserver. Your tablet would be able to communicate with the web server through http requests. The web server can then start further scripts to send data to the arduino or maintain a serial connection depending on your implementation.


What is the best way to define an I/O pin?

#define ledPin 9 is preferred. By doing int ledPin = 9; you will be allocating an int memory whose value is used every time you use ledPin. #define is different in the sense it doesn't allocate memory. there is no memory called ledPin. Before compiling all "ledPin"s in the code(other than strings) are replaced by 9. So basically

digitalWrite(ledPin);

becomes

digitalWrite(9);

Advantages of #define : Saves memory and since all ledPin are replaced by 9 before execution, it saves processor time.
Doesn't really matter in small codes...


How to get response of issued AT command for ES266 on Arduino programatically?

change

AT+CIPMUX=1\r\n

to

AT+CIPMUX=1


Switching LED on and off using microcontroller

A common approach is, to read the input pin, check the read value and then write to the output pin.
As the events on the input pin are generally asynchronous to your code, you have to check it more than once, which means in fact you have to check it regularily.

So in your arduino sketch you could write:

loop()
{
  uint8_t pin1=digitalRead(PA0);
  if (pin1==HIGH)
  {
     digitalWrite(PA4, HIGH);
  }
  uint8_t pin2=digitalRead(PA1);
  if (pin2==HIGH)
  {
     digitalWrite(PA5, HIGH);
  }
  // and so on
}

I assume you have already done the prerequisites in your setup() routine.


Enternal Analog Reference mode not compiling in Arduino + Intel Galileo Gen 2

There is no such thing as an external analog reference on the Galileo.  If you look at the block diagram that is on the Galiley Arduino.cc page you can clearly see that the Aref pin goes nowhere:

So no, it won't support the EXTERNAL analog reference function.


You cannot compare char arrays with ==. A char array, as far as your program is concerned, is just a block of memory. That memory has an address where it starts. It is that address that is stored in your array variable.

C string library functions take that address and read the block of memory starting there. However it doesn't know how big the memory block is, only where it starts. So they operate on the content up until they find the NULL character (which is why it is vitally important to NULL terminate your strings).

Comparing two char array variables with == is just comparing the addresses stored in those variables. Instead you need to compare, byte by byte, the contents of the memory starting at the specified memory addresses up until the NULL characters.

There's various functions for doing that depending on how you want to compare.

strcmp(a, b)
strncmp(a, b, n)
strcasecmp(a, b)
strncasecmp(a, b, n)

All return 0 for a == b, a negative number for a < b and a positive for a > b.

The "n" variants (e.g., strncmp) take the extra parameter giving a maximum number of characters to compare. Useful for looking at just the first few characters of a string (also useful for stopping buffer overruns).

The "case" variants are case insensitive comparisons - that is "foo" matches with "Foo" and "foO".


There are multiple ways to to this. The easiest and most commonly used way is to use a limit switch as home position sensor. At startup the device will first drive the motor in the direction of the limit switch, until the switch get's activated. Now the the absolute position on this axis is known and you can go on from there. (CNC machines and 3D printers mostly work that way. Often they retract again from the limit switch and approach the switch again with less speed, to increase the accuracy). For this you just need a micro switch on the axis and connect it to one input pin. In setup() you are driving the stepper motor in the direction of the limit switch, until it gets activated. Then you are on position zero and can go on with your sketch.

A more difficult way is to introduce a measurement of position into your device. A servo incorporates a potentiometer connected to the axis. By measuring the voltage on this potentiometer (it is basically a voltage divider), the servos electronics can always know, where it currently is. There are also fader potentiometers, where you don't rotate a knob, but you slide a fader over a linear rail. You might find a fader potentiometer, that fits your scale (10cm is not that much, there might be some).

Or you could save the current position to a non-volatile memory (like EEPROM) and retrieve it, when you start up. But since a power-cut during writing of the position may corrupt the data, you would have to go a more complex way. Something like sensing, that the power was cut, providing the Arduino with power through a big capacitor, so that, when it senses power loss, it still has enough time to write the current position to a non-volatile memory. (This is also better for the EEPROM, than continuously writing to it, since EEPROM has limited write cycles).

All in all I would suggest using the first mentioned method (limit switch). It is used in many devices for a reason. Though it depends on your exact project requirements.


Your code looks good. I2C configuration is default which depends on your board manager.
Then your wiring may be wrong.

Using a multimeter to check supply voltage on the BH1750 module. It should be 3.3V
Using a multimeter to check the connection between the BH1750 module with ESP32.
Difference ESP32 vendor may provide a difference I2C pinout. Make sure you connect everything correctly.
Using an oscilloscope or logic analyzer to capture data on an I2C bus.
If everything good, try to use another module.

From your log, I guessed, the power supply is good. I2C connection is your problem.
More, you should use the different color wire for the difference signal. It helps prevent unexpected connections.


How can I define integer inputs to a function and get array as an output?

Defining the array in phi() returns a pointer to unassigned memory - it is no longer reserved once phi() returns. The next function call or interrupt (which you have no control over) will likely clobber the data.

A better choice would be to define z in the caller (loop() in this case) as an uninitialized array and pass it to phi() to fill and return. This is the more usual case, as it:

avoids using globals,
permits multiple calls to the function without clobbering previously returned data (you would pass different arrays in this case), and
it avoids statically defined arrays that may not be needed after the caller returns, in a memory-starved environment (this may not be applicable if loop() is the caller).

In short, it gives the calling function the greatest flexibility, while committing the least amount of memory.


What is the best way to assign pins to an LED Cube?

Well, learning bit manipulations and using three uint16_t (as 9 bits won't fit into uint8_t) to store state for a whole cube is much better. Then you hust have to setup timer ISR and each time it fires just display one "floor". The multiplexing can be done even in loop, but it's usualy flickering as you can't do almost perfect timing as in the ISR.

And for example, I was using two 2x4x4 segments to build up 4x4x4 cube and single MAX7219 to drive it, so I don't have to handle whole multiplexing and so.

My another aproach was using individually addressable LEDs like WS2812B, so I needed only one pin to drive it all. Or by using ARM and DMA transfers, I could drive 8 or 16 lines simultaneously.


Can I power arduino uno R3 with 9v battery through Vin?

About 7.5V to 9V is best. A 9V battery is often not capable to supply enough current for an Arduino. Do you have a multimeter to measure the battery voltage drop when the Arduino is connected ?


attiny85: ISR not triggering for PCINT2?

So, it turns out that it was a really stupid problem and entirely my fault, but I'm going to leave this question here in the hopes that it will prevent someone else from running into the same issue.

The answer is...

DISCONNECT THE PROGRAMMER BEFORE TESTING YOUR SKETCH

That's it.  With the programmer disconnected, it all behaves as expected.


Unusual behaviour when moving data to PROGMEM

Including <avr/pgmspace.h> and using the PROGMEM qualifier macro are only two of the steps required in order to get this to work. Since the data will no longer be available via the data bus you will need to use the various pgm_read_*() macros or *_P*() functions defined in avr/pgmspace.h. These work by using the appropriate assembly code instructions to access data stored in program space, i.e. flash, on the MCU.

Under GCC 4.7 or higher when writing C code, the __flash named address space is available. Variables declared within this namespace do not require any additional steps to access them. Note that the Arduino IDE compiles as C++, and hence does not make this (or any of the others) available.


Is there a way to have the LED switch on after 10 readings or say a minute?

You want to light the LED, when the same chip was read 12 consecutive times. So I would suggest something like this:

Inside your void loop() function you use the millis() coding style (refer to the BlinkWithoutDelay example, that comes with the Arduino IDE) to scan every 10s for a chip. Then you add a counter variable to count, how often the same chip was scanned. If this counter variable is >=12, you turn on the LED. If a different chip was scanned, you set the counter to 1 (since this chip was now scanned 1 time). This leads to a code something like this:

#define READ_INTERVAL 10000
int read_counter = 0;
unsigned long read_timestamp=0;
String last_identifier="";
void loop(){
    if(millis()-read_timestamp>READ_INTERVAL){
        // Read the chip
        if(card_identifier == last_identifier)
            read_counter++;
        else
            read_counter = 1;
        if(read_counter>=12){
            digitalWrite(LED_PIN, HIGH);
        }
    }
}

Be sure to use unsigned long with the millis() function, to prevent it from overflowing to a negative value.


Be careful, you could fry your ESP like that.  You need to get the signal lines down to 3.3V, not the 5V used by the Arduino Uno.  There are many ways to do this, from voltage dividers, to transistors, or you can use a 3.3v Arduino Pro Micro.  I would also recommend starting out with just a 3.3v FTDI board, and interface that directly to the ESP to remove the Arduino and its code from the picture.

I would also make sure that your grounds on the external supply and the Arduino are tied together, or just power the ESP from the 3.3v out of the Arduino.

Other than that, double check your baud rate, some come shipped at 9600, some at 115200, and i'm sure that there are others out there too shipping at different baud rates.


Sending Serial Hex Command from Pin 1 (Tx)

there are 6 bytes just make

byte muteON[] = {0xAA,0x13,0xFE,0x01,0x01,0x13};
byte muteOFF[] = {0XAA,0x13,0xFE,0x01,0x00,0x12};
...
/* To send mute ON comand */
for(byte i =0;i<sizeof(muteON);i++)(Serial.write(muteON[i]));
/* To send mute OFF comand */
for(byte i =0;i<sizeof(muteOFF);i++)(Serial.write(muteOFF[i]));


The code content works fine while compiled as an Arduino program - that is, using the proper setup() and loop() structure:

void setup() {
    DDRB |= (1 << PB4);
    DDRB |= (1 << PB3);
    while (1) {
        PORTB &= ~(1 << PB4);
        PORTB &= ~(1 << PB3);
        delay(1);
        PORTB |= (1 << PB4);
        PORTB |= (1 << PB3);
        delay(1);
    }
}

void loop() {
}

However the same code will not work when using it in main(). This is simply because delay() will never work. Normally main() calls init() which then configures TIMER0 to generate the millis() and micros() count used for the delay() functions.

So either use setup() and loop() instead of main(), or make your program call init() before anything else:

int main() {

    init();

    DDRB |= (1 << PB4);
    DDRB |= (1 << PB3);
    while (1) {
        PORTB &= ~(1 << PB4);
        PORTB &= ~(1 << PB3);
        delay(1);
        PORTB |= (1 << PB4);
        PORTB |= (1 << PB3);
        delay(1);
    }
    return 0;
}


Generating a PWM frequency greater than 125 kHz using Arduino Uno

It's a bit beyond the normal Arduino capabilites so you need to delve into setting some of the registers for your ATMEGA chip directly. See the "Using the ATmega PWM registers directly" http://arduino.cc/en/Tutorial/SecretsOfArduinoPWM


Set the timeout - Ethernet Shield library

In the stream class there is a setTimeout(ms) function. e.g.

String str;
Serial.setTimeout(5000) ;
str = Serial.readStringUntil('\r');

Where this does timeout the initial connection attempt in http.connect(). Whereas I found it also important to timeout each line, as a web page may not disconnect at the end or not send anything.

int httpGetHeaders() {
  String request, response;
  int result = 0;
  long startOfHttpResponseTime;

  client.setTimeout(1000) ;
  response = "";
  inHeaders = true;
  startOfHttpResponseTime = millis();
  while((client.connected()) && inHeaders && ((long)(millis() - startOfHttpResponseTime) < HTTP_RESPONSE_TIMEOUT)) {
    String header = client.readStringUntil('\n');
    header.trim(); // trim off white spaces including CR and LF at end.
    Serial.print(F("head["));
    Serial.print(header.length());
    Serial.print(F("]:\""));
    Serial.print(header);
    Serial.println(F("\""));
    if (!header.length()) { // first blank line indicates end of headers
      inHeaders = false;
      Serial.println(F("No longer in Headers"));
    }
    else {
      if (header.startsWith("HTTP")) {
        Serial.println(F("HTTP Found"));
        int firstspace = header.indexOf(" ");
        result = header.substring(firstspace + 1, header.indexOf(" ", firstspace + 1)).toInt();
        Serial.print(F("result = "));
        Serial.println(result);
      }
    }
  }

  Serial.print(F("Result code = "));
  Serial.println(result);
  return result;
}

You may want to review the whole code at https://github.com/lansing-makers-network/StatusBotArduino/blob/master/StatusBotArduino.ino I have reduced the connection to a sequence of commands that can be used consectutively in the desired order to meet different needs. The above is just to read a headers response.


how to interrupt the loop function and restart it?

"How to interrupt the loop function and restart it?"

You don't. That's not how you write Arduino code. You need to have your loop function call a series of non-blocking functions that check to see if it's time to do something, do a very small bit of work if it is time, or just return if it's not time yet.

What I've done is to create a class ArduinoObject that has a setup function,  a start function, a stop function, a loop function, and a boolean property running. My main program has a global variable that holds an array of ArduinoObjects.

Every time through the loop, I check all the ArduinoObjects in the array, and call their loop functions.

The first thing each object does is check its running flag. If running==false, it exits immediately.

Each object uses unsigned long values to track the next millis() time count when it should do something.

Let's say the object does an animation, so it has an unsigned long nextAnimationStepTime. In the loop() function, if nextAnimationStepTime<millis(), it doesn't do anything. If instead nextAnimationStepTime>=millis(), the object advances the animation to the next step, and sets nextAnimationStepTime = millis() + animationStepDuration. That way, next time the object is called, it will wait until it's time to advance the animation yet another step.

Each object is written to only do a tiny bit of work on each pass through the loop, and return as quickly as possible.

With this design, I can add an arbitrary number of objects/tasks to my loop, and all of them get attention on every pass through the loop. Most objects simply decide they're not running, or it's not time to do anything, and return.

You can then add control logic that starts and stops individual objects based on things like button presses.

With this approach you'd have your button 1 press stop animation 2 if it was running and run animation 1. Conversely, pressing button 2 would stop animation 1 if


There is a library in which you can change the frequency

Here is my example code I did long time ago I had the same problem

Get the library from here

https://github.com/atmelino/Arduino/tree/master/libraries/PWM

Go ahead and try example code there and try to understand too.

Include the library first to code

my code

void setup() {
  pinMode(13, OUTPUT);
  pinMode(8, OUTPUT);
  digitalWrite(8,LOW);
  Serial.begin(115200);
  InitTimersSafe();
}
void loop() {
  //mapping
  long x = map(analogRead(A0),0,1023,1,20);
  bool b = SetPinFrequencySafe(9,x);
  digitalWrite(13,b);
  pwmWrite(9,127);
  Serial.print(x);
  Serial.print(" Hz ");
  Serial.println(b);
  delay(100);
}

Built in led will turn on if the frequency is stetted.

By the way led will turn on in 50% on and 50% off in one cycle in pin 9.

Use only the PWM pins in Arduino 3,9,6 etc.

Now you can change the PWM frequency...

I just put a led in the female socket in for easiness + terminal in 9 and - terminal in 8 to go to ground that's why I did put pin 8 to low.


You set a timestamp = millis() when the button is pushed and then you disable the buzzer only when millis() - timestamp > timeout

if (touchsensorState == HIGH) {
    // buzzer will emit sound:
    digitalWrite(buzzer, HIGH);
    timestamp = millis();
}
if(millis() - timestamp > timeout) {
    // buzzer will not sound:
    digitalWrite(buzzer, LOW);
}


how to make arduino as mind thought reader?

Even if the answer provided by Mike is really doable and can be implemented you should really think about what you want to reach and what is your goal.

The big difference between EEG and mind readers is that the process of thinking, even if you can record all that waves: alpha, gamma,... can be never decoded to get useful informations. I mean: you can record and get a confirm that you have more gamma waves when you are doing meditation. Or that aplha and beta wave are going to be much more present when waking up or in particular hours of the days, but you never get an image of what the person is thinking or what are its emotions... That because you can get some waves coming from the brain but you cannot reconstruct the billion of processes that are happening inside the brain.

A lot of researcher are trying to decoder those informations to move as an example an arm or a leg. But it is the front edge of the reasearch really not doable with an Arduino....

Anyway good luck!


Sublime as external editor, error on Arduino compile dropdown: "avr-g++ is not recognized...", from Stino

Download WinAVR from http://winavr.sourceforge.net/download.html, install it, add(in my case, its: C:\WinAVR-20100110\bin) to PATH variable of your system(If it was left unchecked while installing), And then try to build. I hope your problem will be solved.

Update

I have installed the latest version and found no board selection option. If you want to use it, you can download an older version. from here: https://drive.google.com/file/d/0B4zy7eqONHnuajk2aXlzOTJtaDQ/view it works on older version of arduino(probably 1.5 series)


I've always used flag to indicate a boolean logic value. I would also suggest this is an archaic term.

Was going to come up with my own explanation but found the following at In C language, what does flag mean?:

  A 'flag' is a variable that is supposed to signalize something. Think
  about the word itself - flags are used in sending signals. In our
  world of programming a basic boolean flag can either be "up" or
  "down", either true or false.


It would appear that the wrong A/D reading is due to the reduced +5V output. The A/D reference is powered by the input to the computer chip. The big question is what is causing the voltage drop. Are you powering something else
from the USB supply when the FET is turned on? Bottom line is that you cannot
expect the A/D to read the same voltage when the voltage input to the computer chip is changed.


You need to keep track of multiple WiFiClients - declare an array of them, for example, and each time server.available() gives you a new one, store it in the array.

Then you need to make sure your code doesn't stick waiting for data from each item.  You could service each WifiClient in turn: if it has data waiting (client[i].available() is true), read the data (client[i].read()) and store it. When you get a \r from a client, you know you have a whole line, and you can process it.

Here's a nearly-complete (but untested) example so you can see what I'm talking about.  Naturally it's not the only way to do it.

#include <ESP8266WiFi.h>
const char* ssid = "your-ssid";
const char* password = "your-password";
#define MAX_CLIENTS 10
#define MAX_LINE_LENGTH 50
// Create an instance of the server
// specify the port to listen on as an argument
WiFiServer server(80);
WiFiClient *clients[MAX_CLIENTS] = { NULL };
char inputs[MAX_CLIENTS][MAX_LINE_LENGTH] = { 0 };

void setup() {
  Serial.begin(115200);
  delay(10);

  // prepare GPIO2
  pinMode(2, OUTPUT);
  digitalWrite(2, 0);

  // Connect to WiFi network
  Serial.println();
  Serial.println();
  Serial.print("Connecting to ");
  Serial.println(ssid);
  WiFi.begin(ssid, password);

  while (WiFi.status() != WL_CONNECTED) {
    delay(500);
    Serial.print(".");
  }
  Serial.println("");
  Serial.println("WiFi connected");

  // Start the server
  server.begin();
  Serial.println("Server started");

  // Print the IP address
  Serial.println(WiFi.localIP());
}

void loop() {
  // Check if a new client has connected
  WiFiClient newClient = server.available();
  if (client) {
    Serial.println("new client");
    // Find the first unused space
    for (int i=0 ; i<MAX_CLIENTS ; ++i) {
        if (NULL == clients[i]) {
            clients[i] = new WiFiClient(newClient);
            break;
        }
     }
  }

  // Check whether each client has some data
  for (int i=0 ; i<MAX_CLIENTS ; ++i) {
    // If the client is in use, and has some data...
    if (NULL != clients[i] && clients[i]->available() ) {
      // Read the data
      char newChar = clients[i]->read();

      // If we have the end of a string
      // (Using the test your code uses)
      if ('\r' == newChar) {
        // Blah blah, do whatever you want with inputs[i]

        // Empty the string for next time
        inputs[i][0] = NULL;

        // The flush that you had in your code - I'm not sure
        // why you want this, but here it is
        clients[i]->flush();

        // If you want to disconnect the client here, then do this:
        clients[i]->stop();
        delete clients[i];
        clients[i] = NULL;

      } else {
        // Add it to the string
        strcat(inputs[i], newChar);
        // IMPORTANT: Nothing stops this from overrunning the string and
        //            trashing your memory. You SHOULD guard against this.
        //            But I'm not going to do all your work for you :-)
      }
    }
  }

}


Where to put additional libraries (such as <Wifi.h>) in .h or .cpp, since it works when defined in each one of them?

Any library can reference any other library. So including another library in your library is the same as including in the sketch. They should be on standard locations.

Include the other libraries .h in the file where you need it. If you use something from the other library in your .h, include it there. If you need it only in .cpp include it there.

  What is the purpose of defining variables in the :private section? Since they can be defined inside constructor, and as far as I know/tested, it works as well.

With declaring a class member as private, the author of the class tells: don't use it, it is for internal use and can change in future versions.

  In a .cpp file, does it matter when instances or variables are defined outside a class (at the beginning of code ), since again, it works the same?

If the variable is not a member of the class, then if you create two instances of the class they will share the variable. A variable in constructor is restricted to the constructor's scope.


Trying to understand AccelStepper constant speed

So I ended up doing some source code diving for the AccelStepper library to figure out what the problem was and it turns out there was a missing method call in their example code, specifically a call to setMaxSpeed in the setup function:
void setup()
{
    Serial.begin(9600); // set up Serial library at 9600 bps
    Serial.println("Stepper test!");

    AFMS.begin(); // create with the default frequency 1.6KHz

    // ! Note that you need to set the max speed, otherwise the stepper motor will
    // ! only step once per interval regardless of what `setSpeed` value you give
    Astepper1.setMaxSpeed(1000);

    Astepper1.moveTo(targetDistance);
    Astepper1.setSpeed(targetSpeed);
}

If you look at the setSpeed method in the library you'll notice a constraint of the speed value:

The constrain method takes in a speed value and then a low and high, which the accelstepper library sets to the private _maxSpeed variable. If the speed is outside of that range it will set the value to the low or high value passed in.

This means, if you don't call setMaxSpeed the library will use the default _maxSpeed value assigned during construction which issss 1.0:

So, to correctly use the constant speed methods, you need to be sure to include a call to setMaxSpeed in your code before calling setSpeed, likely in the setup function.
I also shot a video explanation to share with my co-workers. You can see it here: https://vimeo.com/438272826


What are some steps to attach an Arduino to an electric heater?

Would or should begin? Don't fiddle with the internals of the heater.

Set its switch to the always on position and control switching on and off with an external relay. Make a box that has plenty of room (you can reduce size at a later moment), a power cord, a mains adapter for your Arduino and a mains outlet in which you can plug your heater.

Use:

an RTC (real time clock) breakout to keep accurate time
optionally a 7 segment display to display date/time. Just make sure it has a driver chip on it so you don't need your Arduino to multiplex the individual LEDs
couple push buttons to configure the device
a relay rated for the maximum power of the heater to turn it on/off, that can be driven from 5V. Possibly needs a transistor and flyback diode to be controlled from an Arduino GPIO line.

And be very careful when experimenting with mains power, it can be leathal.


How to identify pinout of ATmega 2560 derivative board?

Disconnect everything but the switch.
Run this:
for each pin,
  set the pin to INPUT_PULLUP mode;
  do,
    read and print the pin number and pin state;
  until operator touches a key;
  read and discard the serial input;
end;

You do:

Each time a new pin number prints on the terminal,
toggle the switch a few times to confirm whether you are seeing the result of your actions.
If not, touch the spacebar to try the next pin #
else, you found it.


Is it possible to print a custom object by passing it to Serial.print()?

There is a class called Printable. If you inherit from that, and implement the size_t printTo(Print& p) function, your object can then be passed to the print functions:

class myClass : public Printable {
    private:
        int _val1;
        int _val2;

    public:
        myClass(int v1, v2) : _val1(v1), _val2(v2) {}
        size_t printTo(Print& p) const {
             size_t r = 0;

             r += p.print("One: ");
             r += p.print(_val1);
             r += p.print(" Two: ");
             r += p.print(_val2);
             return r;
       }
};

Then:

myClass ob(4, 5);

Serial.println(ob);
=> One: 4 Two: 5


If a component needs 5V it must be connected to 5V. If it needs 3.3V it must be connected to 3.3V.  Connecting a 3.3V component to a 5V supply is a sure fire way of destroying it.

Furthermore, since the Arduino's main chip is a 5V device, if you want to connect it to a 3.3V device you must use some form of level translation so that the 5V signals from the Arduino don't damage the 3.3V device. Also it may (though not always) be necessary to convert the signals from the 3.3V device to a level that the Arduino can understand (5V).


Arduino wont start up and it wasnt succesfully booted in any time it was downloaded

The Arduino IDE is written in Java. It's 100% platform independent, so the version that you download makes no real difference.

The most likely culprit is the version of Java that is installed in your computer.  I am not sure off hand what versions of Java the Arduino IDE works with, but for certain version 8 will be your best bet.  Make sure that you have the latest version of Java 8 installed.  If you have any older version installed you should uninstall it and replace it with Java 8.  I'm not sure how the IDE works with newer versions than 8, but removing anything newer than 8 and installing Java 8 may be a good idea.


How to use? ATmega328P Development Board for Arduino UNO R3 Bootloader Project DIY

The purpose of this board is to flash (Arduino) bootloader to Atmega 328 chips. It has not a build in programmer, only a ICSP header to connect the programmer.

So wire it with a programmer and then chip in, ZIF close, burn bootloader, ZIF release, chip out, next chip in, ZIF close, ....

video


Power source for Arduino uno, sparkfun usb shield and adafruit motor shield

Its a very bad idea to power everything from the same battery source. Most motors, especially ESP, generate large current spikes, rather than draw a small current throught. AA batteries are not designed for this.

You can get away with using AA batteries for micro-controllers, shields. However, keep motors on a sweater power supply. There are batteries for specific motor types, and these will typically have a high current rating. Of course, without a circuit diagram, I cannot go into details. I'll update my answer when you do.


CH340G and CP2102 devices not recognized with Thinkpad L380

I recently bought a cheap USB 2.o hub.
Turns out that the CH340G devices are recognised if I plug them in the hub rather than in the laptop directly. Maybe this helps somebody else who is searching for a solution, even though I can't explain why the hub is making a difference.


I2C interference SENSOR(SCL+SDA) and MasterSlave comm

The Adafruit BMP280 library uses the Wire library. It calls begin() at default pins (D1, D2). And then you begin() the same Wire object at different pins. From that moment the BMP280 library can't communicate with the sensor.

The I2C (a.k.a. TwoWire or Wire) is a bus. Many devices can be wired to the same pair of pins. They must listen on different addresses. So wire both devices to the D1, D2 and use in slave Arduino an address different then the address of the sensor.

The esp8266 and the sensor are 3.3 V devices. The Uno is a 5 V device. You should use logic level conversion on SDA/SCL to Uno.


GSM incoming bytes from UART not complete

The data arrive over serial very slow compared to MCU speed. In the first snippet you stop reading at first gap between bytes (available is 0). In the second snippet the function readString will wait for the next byte until a second (at default).


Arduino Uno ADC behavior in free running mode

You may want to take a look at Amanda Ghassaei's tutorials on Arduino DSP techniques or the FFT/FHT code at the Open Music Labs. Both use the Arduino ADC in free running mode. Amanda's code uses interrupts, the Open Music Lab code sits in a tight loop waiting for the conversion to complete.

Based on the Open Music Lab code I can say, yes, the conversion is still written to ADCL and ADCH regardless of the interrupt setting in ADIE. I can't tell from your question how concerned you are about cycle counts, but I don't think you'd see a significant change using interrupts (I'd expect it to be zero). But using interrupts you'll take a hit as you enter and return from the ISR.

As I mentioned in the comment, take a look at Amanda Ghassaei's code. She toggles pin 12 which creates a spike in the trace if you have a scope attached to pin 12 (or a logic analyzer). That will give you a very easy way to determine the actual time to handle the conversion.


How can I assign the value of a char array to a uint8_t array?

I don't have a compiler at hand, but you can cast the array  as a char and uint8_t are similar in size:
rf95.send((char*) udp_to_lora, sizeof(udp_to_lora));


Arduino join multiple strings and numbers and then seperate them

To make the string you can:

char outstring[30];
sprintf(outstring, "X:%d,Y:%d,Button:%d", xPosition, yPosition, buttonState);

Be sure to make the outstring big enough to store it all.

That is, of course, if you actually need to have the whole thing in one string all the time.  You haven't said how you are sending it (yes, I know, bluetooth, but there is bluetooth and there is bluetooth, and there are different ways of it working.)

Splitting a string like that can be done with strtok() then looking for the location of the colon in each returned token. Or, depending on how the string data actually arrives, could be parsed on a character-by-character basis, which would be better. Again, because you haven't told us how the data is actually being transferred it's impossible to elaborate on that.


Arduino Due and Vin, 3.3V and 5V power inputs

DC Jack is connected, through a diode, to Vin.

Vin is stepped down to 5V on-board.

5V is stepped down to 3V3 on board.

Thus you can do any one of the following numbered items.

Connect a 7-12V supply to the DC Jack; thus:

use Vin as a supply @ DC - 0.7V for off-board peripherals, and
use 5V as a supply for off-board peripherals, and
use 3V3 as a supply for off-board peripherals.

Connect a 6-12V supply to Vin; thus:

use 5V as a supply for off-board peripherals, and
use 3V3 as a supply for off-board peripherals.

Connect 5V supply to the 5V; thus:

use 3V3 as a supply for off-board peripherals.

The above is only guaranteed for boards that follow the reference schematic, as plenty of clone/compatible boards do. If you buy a cheap Chinarduino and something doesn't work, or the thing breaks, after following anything above then that's your tough luck.


The ESP8266 ESP-12E has only one analog input, that is A0 (which tolerates a range 0-1 volt).

digitalRead() statements are not appropriate for a photocell within a potential divider since you will simply get a boolean result 0 or 1 from the connected pin.

You can read one photocell connected on A0 by analogRead( A0 ) assuming it is so connected within a potential divider that a maximum of 1 volt is presented to pin A0.

The Arduino Uno by contrast has 6 Analog inputs which tolerate up to 5 volts


4-digit 7 Segment LED displaying numbers in the wrong order

Here is a datasheet I found that seems a better macth for your display model (that's the datasheet for a display that I use):

http://www.play-zone.ch/en/fileuploader/download/download/?d=1&file=custom%2Fupload%2FFile-1356269320.pdf

This is the datasheet I directly got from my local supplier.

According to what you say, the problem does not seem to be a wiring problem.

It looks more like a timing issue:

void writeDigit(int digitPin, int number) {
  digitalWrite(digitPin, LOW);

  digitalWrite(LATCH, LOW);
  shiftOut(DATA, CLOCK, LSBFIRST, digits[number]);
  digitalWrite(LATCH, HIGH);

  digitalWrite(digitPin, HIGH);
}

The first issue when you call writeDigit() is that it forces the cathod low BEFORE having set the shift register, so the digit will first show the current register value, i.e. the one from the previous call to writeDigit().

Then it pushes the new value for the segments on the shift register, that will be fast but not as fast as two consecutive calls to loop().

If we try to roll and expand the loop() call in your example that will be:

// First call: writeDigit(DIGIT_TWO, 2)
  digitalWrite(DIGIT_TWO, LOW);
  digitalWrite(LATCH, LOW);
  shiftOut(DATA, CLOCK, LSBFIRST, digits[2]);
  digitalWrite(LATCH, HIGH);
  digitalWrite(DIGIT_TWO, HIGH);

// Second call: writeDigit(DIGIT_THREE, 3)
  digitalWrite(DIGIT_THREE, LOW);
  digitalWrite(LATCH, LOW);
  shiftOut(DATA, CLOCK, LSBFIRST, digits[3]);
  digitalWrite(LATCH, HIGH);
  digitalWrite(DIGIT_THREE, HIGH);

The calls to loop() and writeDigit() are negligible in terms of timing here.

In the sequence above, most of the time is spent in:

  shiftOut(DATA, CLOCK, LSBFIRST, digits[2]);
  shiftOut(DATA, CLOCK, LSBFIRST, digits[3]);

So that means your function will:

show the previous value on the new digit for t1 us
show the new value of the new digit for t2 us

with t1 >> t2, hence your eyes will see the opposite of your intent!

To fix that issue you definitely need to introduce some delay to reverse what your eyes will see:

void writeDigit(int digitPin, int number) {
  digitalWrite(LATCH, LOW);
  shiftOut(DATA, CLOCK, LSBFIRST, digits[number]);
  digitalWrite(LATCH, HIGH);
  digitalWrite(digitPin, LOW);
  delayMicroseconds(100);
  digitalWrite(digitPin, HIGH);
}

In the code above:

no digit shows while the shift register is set
the requested digit shows immediately after the shift registry has been written and lacthed, and for a duration of 100us, which will be much longer than the rest of the time.

That code should also get rid of the "bleeding" you observed.


simulate this circuit – Schematic created using CircuitLab

A piezo element can be connected to an analog input (A0 for example) of your microcontroller, but extra resistors are advisable if you wish to have a digital sample that is linearly proportional to the element's alternating voltage.
Andy's caution about over-voltage is relevant too - these elements can produce voltages far greater than your Arduino's DC supply voltage. Such over-voltage can cause damage. Resistor R3 helps limit potential damage.
Each piezo element will require its own set of three resistors (duplicates of R1, R2, R3). Many microcontrollers have multiple analog inputs - you can have as many piezo circuits as there are analog inputs. You cannot sample them all simultaneously, since most microcontrollers usually have only one analog-to-digital converter, which is switched between its various analog inputs by program control. A piezo element would have to be sampled, then switched to the next element for sampling, then the next....etc.
Sampling can be done fast enough that "audio" (however you define it) is fairly represented by the digital sample stream. However, be aware that processing these audio samples may be beyond the speed capability of simple microcontrollers like Arduino. That part is up to you.
Be aware that piezo elements make poor microphones. Units mounted in plastic shells are designed to output audio tones, and have significant resonant peaks. Frequency response is not flat, as required by a proper microphone.


Arduino ATmega328P works but board (Uno R3) seems broken

The R3 uses an ATmega16u2 in place of the FTDI. It is possible that it is not loaded, busted crystal, or it has no local power to it. It is a small SMT.

You could use your good Arduino setup as ICSP programmer to talk to the ICSP of the 16u2 to see it is alive. And if so then program it.


Does WiFiClient work on a Yún to send data over a certain IP and port to be received by a Python socket?

No, that code is only for the WiFi shield.  For the Yun you need to look at the Bridge library that is bundled with the IDE. It allows you to run commands and perform actions on the Linux based Atheros portion of the Yun which is what has access to the WiFi.


Arduino Analog pins go all to high problem

A high voltage at a pin can damage the microcontroller partially.

The ATtiny microcontrollers can sometimes survive a voltage of 7 V.
The ATmega microcontrollers are damaged by that voltage.
The ATmega2560 is older and even more critical with voltages, it can not work at 16 MHz below 4.5 V and gets easily damaged with voltages above 6 V.

When the microcontroller runs at 5.0 V, a input pin can have -0.5 V to +5.5 V.

When the microcontroller gets damaged, it can be damaged partially. It is impossible to determine which parts of the chip are still okay. Therefor a partially damaged microcontroller should not be used anymore.

Solution:

A simple solution is a protection resistor in the signal path to the analog input.

simulate this circuit – Schematic created using CircuitLab

According to application note AVR182, it is allowed to push 1 mA into a pin or pull 1 mA from a pin for the ATmega microcontrollers. That current flows via the internal ESD diodes to VCC or from GND.

With a protection resistor of 4k7 before an input, the microcontroller is protected up to: 1mA * 4k7 + 5.5V = 10.2 V.

The internal ESD diodes can have more than 1 mA, but the maximum is unspecified. It is also dangerous when for example the ATmega is put into sleep mode. Then the 1 mA can lift the VCC voltage and still damage the ATmega microcontroller.

When a voltage divider is used (two resistors, R1 and R2) and the internal reference is used, then the voltage divider can be designed to be protected against very high voltages. For example with a ATmega2560, internal reference of 2.56V, R1=47k, R2=10k. This can measure up to 14.6 V and be protected up to 78 V.


Smart Chess-board (possibly using RFIDs?)

As I read your post an idea came to me that must be obvious in its simplicity.  Since a chess board has pieces already on it we can simply use hall-effect sensors (dirt cheap) under each square and each piece has a magnet at its base.  Since pieces on a chess board move from one square to another and the initial position of all pieces is known/constant, the detection of a move would be that a piece is lifted from the board (hall effect sensor detects a magnetic field removal) and a piece being placed on a square would be detected by a hall effect senor addition of a magnetic field.  We wouldn't know which piece is placed on a square but we can calculate it by remembering what piece was lifted and it can only be the piece that was placed.


How arduino boards eliminate the need to press buttons to flash?

I'm not familiar with this board, but according to this schematic:
https://wiki.wemos.cc/_media/products:lolin32:sch_lolin32_v1.0.0.pdf

U4 (one of the small 6-leg components) connects to IO0 (pin 25) on the ESP-32. The transistor inside U4 combines the RTS and DTR signals (from U6 USB-Serial converter IC, which will be the large IC marked SIL2104) to put IO0 in the correct state for flashing. The RTS and DTR signals can be set by the host (the computer doing the flashing).

Apologies for the lack of depth, but the short answer is components U4 and U6 on the board work together on the command from the host computer to put IO0 in the correct state for flashing.


Why I cannot connect directly Arduino UNO and Xbee S2?

If you want X-CTU to see the Xbee while it's connected to the Arduino, you have to connect the Arduino's reset pin to ground. This bypasses the Arduino's MCU and allows the Arduino to act as a USB to serial adapter.

Also don't forget to connect the Arduino's Tx to the Xbee's Tx when it's connected like this, and likewise with the 2 Rx's.


Send data string from Arduino UNO to ESP8266-01

Sending data between Arduino and NodeMcu (Serial Communication)
youtube link  (in French):
https://youtu.be/0TXmi9EgaCs


Adafruit ImageReader Library 2.3.5 added several library dependencies

If you don't use the functions of the ImageReader library, which use the additional libraries, your compiled code will not contain code from the additional libraries.

The Adafruit ImageReader library may have functions which use other libraries and the libraries are required for compilation. But at linking the compiled units which are not used by your code and even parts of the compiled units which are not used by your code are not put in the resulting hex or bin file.


You could get your program to output messages to the serial pin on your board, Tx. For example:

Serial.begin(9600) //baud rate of 9600

Serial.print("Debug Message");

You can use this to print out string and integers. Here is the link to further information on the Arduino website - https://www.arduino.cc/en/reference/serial

If you are already using the Serial pins then you could use the SoftwareSerial Library - https://www.arduino.cc/en/Reference/softwareSerial

This library allows you to make two other pins on your board Tx and Rx. For example:

SoftwareSerial mySerial(12,13) //Makes pin 12 Rx and pin 13 Tx

mySerial.begin(9600) //baud rate of 9600

mySerial.println("Debug Message");

To read the output from any of the pins on your arduino - use a USB to TTL serial cable. Plug it into your computer and use a program like PuTTY to connect to the serial cable and read the messages coming from the Arduino.


Use unsigned int IRsignal[] instead.

Also, your array is 48 items long, not 10. So irsend.sendRaw(IRsignal, 48, 38);


'OUTPUT' was not declared in this scope - ATtiny85 with Arduino Uno r3 as ISP

Create an Arduino.h in ...\Arduino\hardware\attiny45_85\cores\attiny45_85 containing

#include <WProgram.h>

From here
https://electronics.stackexchange.com/questions/87328/arduino-as-isp-for-attiny


Minimum current or power for Arduino Mega

The Arduino's voltage regulator is rated for a suggested input range of 7 to 12 volts. Automobile power will range from slightly below 12 volts to over 13 volts, so stepping it down to 7 volts is a good idea.

Looking at the data sheet it doesn't say how much current it draws. Since it uses a linear power supply it will likely draw the same amount of current regardless of the input voltage, and simply waste the power from a higher input voltage as heat.

The power from a car cigarette lighter should have plenty of current, so your proposed setup should work just fine. Is your 7 volt supply regulated?

Note that you could also use a "buck" style switching power supply to feed 5 volts directly into the 5V line. There are several buck style power supplies on the market for less than $10 US that will provide up to 3A of regulated 5 volts.


RF remote control using VirtualWire on ATtiny85 running at 8MHz on internal oscillator

I tried those Tiny cores you are using and had a lot of problems. I switched to http://code.google.com/p/arduino-tiny/ and it seems much better. Create a second Arduino installation folder and add the arduino-tiny cores.  The pin name constants are like PIN_A0, PIN_A1,...,PIN_B1, etc. So, try that out.

I looked briefly at the VirtualWire code and there are ifdefs specifically for the Attiny85, so it should work.  Here is a derivative project with working ATTINY85 examples: http://cosa-arduino.blogspot.de/2013/03/news-virtual-wire-interface.html


Can't communicate with arduino using python (Windows)

More than likely you ran the Arduino program from the Arduino IDE, and left the terminal window open. You must close it before you run the python program, as it will already 'own' the port until it closes. You dont have to quit Arduino IDE, just close the terminal window.


Do I really need Ramps 1.4 for laser engraver

Ramps 1.4 is one of the proof of concept standards for 3D printer systems. It is a motherboard mostly runs Marlin firmware on it. I advice to to take a look at the firmware if you didn't yet. It is also supporting many motherboards, hardware.

When you open the configuration.h file in the firmware and search for this definition #define MOTHERBOARD you will be seeing many options available.

After all, the firmware is the key factor. It contains many engineering solutions in it. So, you shouldn't re-invent the wheel.
All you have to do is to adapt it with some tweaks as per your design specifications.

But, I would worry more about your motherboard (Arduino Uno)
if your design is relatively simple, using less memory and IO pins, it may be just fine. I would consider Mega 2560 instead If I were you.

Good luck with your project.


In your loop function you have:

if(mySerial.available())
{
  String data = "Hello World";

  for(int k = 0; k < data.length(); k++ )
  {
    mySerial.write(0xAA);
    mySerial.write(data[k]);
  }

  mySerial.write(0xA9);
}

The available() function returns the number of bytes available in the receive buffer. You say your module is a transmitter, so there will never be any data to receive (I can see the module doesn't even have a tx pin). Hence you will never transmit any data.

That said it's not a good idea to send data plain over wireless. It might work to some extent, but you'll likely get much more lost data. Look at the virtual wire library or google "manchester coding" if you wan't to roll your own.


Is there any way to group variables like group.variable as you can in Java/Delphi

What you are looking for is a struct:

struct foo {
    uint8_t Ux;
    uint8_t Uy;
    uint8_t Yz;
};

Then:

struct foo A;
struct foo B;

And:

A.Ux = 3;
B.Uz = 48;

int c = A.Ux + B.Uz;

When calling a function you should really use either pass-as-pointer or pass-as-reference to avoid unnecessary copying:

// By Reference
int normal(struct foo &arg) {
    return (arg.Ux + arg.Uy + arg.Uz) / 3;
}

int avg = normal(A);

Or:

// By pointer
int normal(struct foo *arg) {
    return (arg->Ux + arg->Uy + arg->Uz) / 3;
}

int avg = normal(&A);

You can read more about structs here.