What is the default setting for a digital output pin

On the AVR-based Arduinos at least, pins start in the INPUT, i.e. high
impedance state. If you then pinMode(pin, OUTPUT);, the pin turns to
OUTPUT LOW. Note, however, that if you first set the pin to
INPUT_PULLUP, and then to OUTPUT, the pin ends up in the
OPUTPUT HIGH state.

Sometimes you want to control the state the pin will have right when
it's turned to OUTPUT. You may for example simulate an open collector
output by switching between INPUT (or INPUT_PULLUP) and OUTPUT
LOW, while avoiding the OUTPUT HIGH state. In this case, a safe
idiom is to set the output level before switching the pin to OUTPUT,
e.g.

// Set pin to OUTPUT LOW without going throught the OUTPUT HIGH state.
digitalWrite(pin, LOW); // do this first
pinMode(pin, OUTPUT);

A side effect of performing a digitalWrite() on a pin that is not set
to OUTPUT is that the pin gets switched to either INPUT (if writing
LOW) or INPUT_PULLUP (if writing HIGH). This is an idiosyncrasy of
the AVR IO ports you should probably not rely on if you want your code
to be readable or portable.

Reference: the source code of pinMode() in the Arduino
core, and the datasheet of the relevant MCU. See for example the section
Ports as General Digital I/O in the ATmega328P’s datasheet.


Using clear command on Octave before executing a=arduino('COM8') will remove this problem.
Use it like this:
clear
a=arduino('COM8')


As others have said, you need to make sure you have pull-up or pull-down resistors on all digital inputs so their value doesn't "float" (fluctuate between high and low.)

Given that water tanks and wells tend to be strongly earth grounded, I would suggest some changes:

Change the common wire to a ground, not +5V

Change all of your other pins to analog inputs. Connect them to high ohm pull-up resistors (say 10kΩ). They will read a full 5V when their ends are not in water. When the water rises and the ends dip into the water, their voltages will drop. Use analog readings to detect those voltage drops.

You could also use something like graphite a pair of graphite rods in the water, and a voltage divider circuit. As the water level rises, the current would travel through less graphite, and the resistance would drop. I don't know if that would give you enough top-to-bottom measuring distance.


Loop code without manually pressing the button

As pointed out by Delta_G, there is no point in resetting your program.
What you should do is think your program in terms of the Arduino logic:

You put in setup() the code you want to run when your program
starts.
You put in loop() the code you want to run over and over again.

In this case loop() is fairly simple, as the stuff you want to run
over and over again is the animation, thus:

void loop() {
  colorWipe(strip.Color(75, 0, 0), 50); // Red
  colorWipe(strip.Color(0, 75, 0), 50); // Green
  colorWipe(strip.Color(0, 0, 75), 50); // Blue
  theaterChase(strip.Color(75, 75, 75), 50); // White
  theaterChase(strip.Color(75, 0, 0), 50); // Red
  theaterChase(strip.Color(0, 0, 75), 50); // Blue
  rainbow(20);
  rainbowCycle(20);
  theaterChaseRainbow(50);
}

Note that I removed the call to resetFunc().

The stuff you want to do at startup is the initialization. Oh, wait. In
a comment you wrote “I want to wait for the button press”. So this also
has to be done before the program starts looping. Hence your setup()
should initialize stuff, then wait for the button press:

void setup() {
  // Initialize the strip to all piwels off.
  strip.begin();
  strip.show();

  // Wait until the button is pressed.
  pinMode(BUTTON_PIN, INPUT_PULLUP);
  while (digitalRead(BUTTON_PIN) == HIGH)
      ; // do nothing
}


How to not wait for USB to become active?

After you post your code this answer may not apply.  But, guessing, you may benefit from changing your code from:

loop()
{
 data = Serial.read();
 // Do other sutff
}

To something like this:

loop()
{
 if(Serial.available() > 1)
 {
  data = Serial.read();
 }
 // Do other stuff
}


Methods to prevent Accelerometer values changing from current spikes

Adding a distinct power supply for the MAX7219, as suggested by @jfpoilpret, solved the issue.


You may want to take a look at LMX by David Anderson A Light-Weight Multi-Tasking Executive.

He has a very good set of videos on the code that he did for Dallas Personal Robotics Group (DPRG).

The specific videos for LMX are:

David Anderson on Robotics Software - part 1
David Anderson on Robotics Software - part 2


How to extract the binary from STM32 MCU

you can download the flash content using a ST-Link probe and STM32CubeProg tool. you can't flash it to just "any" arduino board; it must be the exact same chip or same family MCU, if the IOs and peripherals used are the same.


Measure Water Flow in literes using Arduino Mega 2560 Board and Water Flow Sensor

the pulse rate can be derived without knowledge of the CPU clock speed. To achieve the pulse rate from your sensor input you can do two things:

count the pulses dn within a certain (i.e. fixed) interval T of time) or
measure the time dt between two pulses.

I'll come back later on this concerning accuracy.

To measure time, you can use the function millis(). This function returns you the milliseconds since bootup as an integer upon calling it. Method 2 is rather simple to implement.

Setup three global integers a, b and c.
At the end of setup set a to current millis();
In your ISR set b to current millis();
Also in ISR: set a=b;
calculate c=b-a (i.e. your dt);

c holds your current full wave pulse length in milliseconds, which is updated every pulse. You can derive your flow then from it.

The first method uses a counter as demonstrated in your suggestion. You then need a timer outside your ISR, two variables d and e. Either you poll millis() in your main "loop()" or you install a timer interrupt, both will work here.

At the end of setup set d to current millis();
If your predefined time T is passed (by comparing d with millis(),
save your counted pulses to e=pulseCount
reset: pulseCount=0

e holds your pulse count during interval T, from which you can derive your pulse rate.

Accuracy

Method 1's accuracy increases with higher T and higher flow speeds. Therefore the update rate of your measurement is low. By changing T you can easily increase accuracy on cost of responsiveness. This is perhaps a good idea, if you have pulsating flows in your tubings, or the sensor is a bit rattling.

Method 2's accuracy increases with lower flow speeds. It is best to measure very low flow speeds. Update frequency is minimal (1/dt).

Regarding this sensor you should calibrate it yourself. It is a cheap and rugged device (I'm using it, too), but its output depends on several parameters like mounting position, fluid viscosity and so on. Make sure, there are no bubbles, foam or contaminants in your fluid systems as they garble the results effectively.

n.b.: make sure to take care of an overflow of millis().


Modify Arduino Due's Bootloader to flash when reset

The Arduino Due bootloader is built-in. If you check the Arduino SAM core there are no bootloader files. There is a firmware file for the ATmega16u2 on the Programming Port. You might be able to modify this to do that (given that there is a LED to flash).

The alternative solution to a modified bootloader is modifing the init() of the Arduino SAM core. Please see https://github.com/arduino/Arduino/blob/master/hardware/arduino/sam/cores/arduino/main.cpp#L36 or https://github.com/arduino/Arduino/blob/master/hardware/arduino/sam/variants/arduino_due_x/variant.cpp#L372. Blink code as proposed by Majenko could be added there.

Cheers!


teensyduino with teensy LC: cannot include multiple files in sketch

I get the error "undefined reference to doNothing() in function loop"

The C++ compiler cannot find doNothing(). This is mainly due to the incomplete header file and mix of C and C++.

Two things are needed to avoid this type of problem; 1) protect the file from multiple includes (in the same compile), 2) make the function visible to the C++ compiler as a C function (without name mangling).

tst.h:

#ifndef TST_H
#define TST_H

#ifdef __cplusplus
extern "C"{
#endif

void doNothing();

#ifdef __cplusplus
} // extern "C"
#endif
#endif

Cheers!


Is it possible to configure FRAM memory for use as stack and heap?

No, you can't use SPI or I2C memories to store stack or heap data in AVR microcontrollers, as the AVR MCUs do not allow to map memories connected to the SPI or I2C buses. In other words, there is no way to tell the MCU that you connected a SPI or I2C memory, and how to use it, automatically. Therefore you can only use such memories to manually store/read data, by manually issuing all the correct command sequences, which will be very slow (as you wrote you are already doing by calling some libary functions).

Instead, you can use an external PARALLEL memory, connected to the external memory bus, which is present on SOME AVR microcontrollers (unfortunately, the ATMEGA328 has no external memory bus). Still you'll get a much slower performance with respect to the internal memory.

Finally, Arduino is not a  good platform to process (or store/read) pixel data from a camera, due to severe computing power and memory limits. Even if there are more powerful Arduino (or Arduino-compatible) boards, which feature much more powerful processors (e.g. Cortex M3 or M4), you would probably need to program them using a very optimized C (and not C++!) code, or even ASM. But at this point, there would no reasons to use an Arduino-compatible platform, instead of an another one, possibly much more powerful or even cheaper.


You were able to create a custom data structure from your string, but it seems, that the connections, that are stored in the Map class, are not connected. So the map does not really represent the structure of the "street" net. I would propose a different approach:

Instead of defining connections you can define the nodes of your net (where 2 or more streets meet). For each node you save the position (x, y) (or an instance of your vertex class), a label (like "library") and an array of pointers to other node objects. In code this may look like this (I left the methods out):

class Node {
    Vertex pos;
    char label[25];
    Node *connections[6];
}

Excursion: If you don't know, what pointers are in C/C++, here a short introduction. You should definitely read more about it on the web.

A pointer variable contains the address of another variable in the RAM. You can change this address and let the pointer point to another variable. A variable is marked as pointer with a * at the declaration. You can get the address of a variable (to set the pointer to this variable) through the & operator: pointer = &variable . If you dereference a pointer (by writing a * before the pointer name), you can work with the value, that the pointer points to. Each pointer variable has a type. It is the type of the object, that it points to. The pointer declaration int *var let's var point to int variables. If the type is a class or struct and you want to access members of the target (where it points to), you can use the shortened version pointer->member.

You define each node and add pointers to other nodes to represent connections. To traverse through the map, you need a start node. You save the address of the current node in a pointer. Then you can use it to access the connections of the current node. To actually go to the next node, you would set your pointer to the value saved in one of the connections elements, because that are pointers to the connected nodes.

The robot can then be moved along the straight lines between 2 nodes. When you want to also have non-straight, you can also do that by defining a middle point. You just to define the geometrical form, that the line should take.

The Map class can contain an array of Nodes. You can loop through all nodes in the array, if you need to, or you can traverse through the net by using the pointers.

The actual algorithm to find the path with the smallest travel distance is a big out of scope here. Doing that efficiently can be a complex task. You can research these algorithms on the web. The easiest way is to test all different paths in your program (without actually moving the robot), save the needed distance for each path and then choose the path based on that. You would need to write a termination condition, so that no connected will be taken twice on the same path (which would mean some kind of loop). Also keep in mind, that this will need more and more computation time, as your net grows. If it stays small and you don't need very fast computation, it might stay sufficient. If your implementation is recursive, you also have to consider, that each recursion takes up memory on the stack. You don't want to get out of memory.

Speaking of memory: In your implementation you use String for the label and you might want to use dynamic memory allocation for your map. That is not a good idea, because it can make swiss cheese out of your heap memory (heap fragmentation). It is better to define a fixed array, that can hold the maximal number of elements (as I have done with the connection of a node). The not needed elements can be set to something meaningless (for the connections you can use the null pointer and for unused nodes simply only null pointer connections).


Interfacing 4 ESCs and an Arduino with a single LiPo battery

Powering all the ESCs from a single LIPO is not an issue.

Using a breadboard to distribute this power is highly unlikely to work, breadboard connectors are usually only good to a few hundred mA, 1A is you want to push your luck.  Most ESCs and BLDC motors are in the 5A to 50A range (each, your power bus has to handle 4 times this current).

Also, ESCs tend to inject a lot of noise into the power bus.  If you connect the arduino to the ESC power bus, you will likely get random resets and really poor noise performance on the ADCs.  Keep in mind that some ESCs actively brake the motors using regenerative braking, which puts the kinetic energy of the motor back into the power bus.  This can increase the voltage on the power bus to more than the nominal battery voltage and can have large voltage spikes on it causing a failure on the Arduino.

If you are prototyping, use a separate power supply/battery for the arduino and connect all the grounds together instead of using a single supply.  If you are building a rover/uav/whatever and don't want a second battery, use a high quality BEC (or the BEC output from a high quality ESC) and remember that the 5V output on a BEC/ESC can be significantly higher than 5V in reality).

ESC = Electronic Speed Controlled
BEC = Battery eliminator circuit (I think, basically a 5V-ish regulator)
BLDC = Brushless DC motor (three phase in this case)


Typically, rational control of an LED sets the amount of current that goes through the LED, rather than setting its voltage.  You could add series resistors so that when the desired current is flowing through the LED, about 1.2 volts is across the LED and the rest (say 3.6–3.8V) is across the resistor.  (See Google images for typical circuits, and see various LED resistor calculator, eg the LED resistor calculator at hacktronics.com.)  It also is possible to use PWM to control LED brightness.

Note that if you have 3.6V across a resistor and 1.2V across an LED, you are wasting 3/4 of the power expended.  When LEDs are low voltage (ie, like 1.2V for your LEDs, vs. 1.6 for typical red or orange LEDs, vs 3+ V for white or blue) you can put several of them in series.  For example, put three of your IR LEDs in series, and calculate R so that 1.2 V drops across a resistor and 3.6 across the series of LEDs.  Also try four LEDs in series, and calculate R to drop 0.1 to 0.3 V.

Edit 1: Ignacio Vazquez-Abrams says, a little  obscurely, “Getting warmer. But this is a IR LED” and also “Pull up the datasheet for a IR LED. Read it carefully. The AVR can't handle one of the numbers”, perhaps in reference to IR LED current requirements.

Typical 5mm IR LEDs can handle several times more current than typical 5mm visible light LEDs.  For example, a typical green LED might be rated 30 mA max sustained current and 20 mA recommended, while a typical IR LED might be rated 100 mA max and 50 mA recommended.  Also note that 50 mA is 10 mA more than the 40 mA that most Arduino pins list as absolute max.  A sustained current of 40 mA or more in or out of an Arduino i/o pin may damage the processor.  If you want to drive a high-current IR LED, use an external driver (eg a transistor).  See eg the answer to How can I efficiently drive an LED? in Electronics SE, which shows dropping resistor calculations, constant current sources, etc. Also see links given in JYelton's answer to  Infra Red LEDs - Voltage Advice.

Treesrule14 points out “IR leds ... don't emit in the visible light range”, which is true; they emit infrared radiation, or heat.  Note, using an IR LED in a remote control usually is incompatible with controlling its average brightness with PWM; the pulses used in PWM would conflict with the pulse train in typical 36, 38, or 40 KHz IR control protocols.


Output frequency from an SPI DAC (MCP4922) is lower than expected

Let's do some maths...

16MHz master clock / 2 = 8MHz SPI clock
2 transactions = 16 bits (not 12!)
8,000,000 / 16 = 500,000
2 transitions per cycle
2 channels
2 + 2 = 4
500,000 / 4 = 125,000Hz

So in a perfect world you could expect 125kHz from the DAC. However the world is far from perfect.

Let's look at what it's actually doing when you use output2():

void DAC_MCP49xx::output2(unsigned short data_A, unsigned short data_B) {
  this->_output(data_A, CHANNEL_A);
  this->_output(data_B, CHANNEL_B);

  // Update the output, if desired.
  // The reason this is only in the dual-output version is simple: it's mostly useless
  // for the single-output version, as it would make more sense to tie the \LDAC pin
  // to ground, or do it manually. However, there should be a single-call method
  // to update *both* channels in sync, which wouldn't be possible with multiple
  // separate DACs (for which there is latch()).
  if (automaticallyLatchDual) {
    this->latch();
  }
}

Assuming automaticallyLatchDual is false we can pretty much ignore that section. So it's calling _output() twice - once for each channel. And what does that do?

void DAC_MCP49xx::_output(unsigned short data, Channel chan) {
  // Truncate the unused bits to fit the 8/10/12 bits the DAC accepts
  if (this->bitwidth == 12)
    data &= 0xfff;
  else if (this->bitwidth == 10)
    data &= 0x3ff;
  else if (this->bitwidth == 8)
    data &= 0xff;

  // Drive chip select low
  if (this->port_write)
    PORTB &= 0xfb; // Clear PORTB pin 2 = arduino pin 10
  else
    digitalWrite(ss_pin, LOW);

  // bit 15: 0 for DAC A, 1 for DAC B. (Always 0 for MCP49x1.)
  // bit 14: buffer VREF?
  // bit 13: gain bit; 0 for 1x gain, 1 for 2x (thus we NOT the variable)
  // bit 12: shutdown bit. 1 for active operation
  // bits 11 through 0: data
  uint16_t out = (chan << 15) | (this->bufferVref << 14) | ((!this->gain2x) << 13) | (1 << 12) | (data << (12 - this->bitwidth));

  // Send the command and data bits
  SPI.transfer((out & 0xff00) >> 8);
  SPI.transfer(out & 0xff);

  // Return chip select to high
  if (this->port_write)
    PORTB |= (1 << 2); // set PORTB pin 2 = arduino pin 10
  else
    digitalWrite(ss_pin, HIGH);
}

That's quite a lot. All those boolean mathematics operations and decision making slows things down a lot. So does hopping from function to function (yes, the compiler will possibly try and inline some things).

Even the SPI.transfer() isn't that efficient with checks and while loops, etc.

To get anywhere near the kind of speed you are looking for you would need to use non-blocking SPI code so you can be transferring a byte out of the SPI port at the same time as getting the next byte ready to send. You don't need to wait for the current SPI transfer to finish (as the SPI library does), you just need to be sure that the previous one has finished before you start the next one.


Compute the size of an array that was passed as a parameter to a function

You can't. You are passing a pointer to the array, and sizeof will give you the size of that pointer (2 on an 8-bit Arduino).

Instead the normal way is to pass the size of the array as a parameter to your function.

myFunction(myArray, sizeof(myArray) / sizeof(myArray[0]));


Problem using ICSC (by majenkotech) in RS485 bus

The documentation for the constructors is out of date (I am re-writing as we speak, and is now here).

The constructors in the header file are like this:

ICSC(Stream *d, uint8_t station);
ICSC(Stream &d, uint8_t station);
ICSC(Stream *d, uint8_t station, int depin);
ICSC(Stream &d, uint8_t station, int depin);

That means you need to provide the serial object as the first entry:

ICSC icsc(Serial1, 'A', 5);

You need to manually start the serial object before ICSC.

void setup() {
    Serial1.begin(9600);
    icsc.begin();
}

This change was made to enable support for software serial and other Stream based devices.

Addendum for your update:

Don't spam the sending like you are. Send periodically, not constantly, or you will never be able to receive.
You cannot use String objects like that.
1 and 2 aren't good choices of station IDs. Yes, they work, but not great, since 1 is the SOH character.


How do I wire a ground rail to a VEROboard?

There's nothing special about ground. It's just a wire like any other.
You could designate a row of holes as ground then link them all together, but you don't need to. Just wire your grounds together as you would any other connection.


6 + 1 motors connected to an arduino uno?

Normally a full H-bridge (for one motor in bi-directional mode) will need 3 ouput pins. You can potentially force the enable pin to a constant level but that means you will always draw current for your motors even when they don't move, which is probably not what you want. ou might also wire all 6 enable pins together to one Arduino pin just to control power of all motos altogether.

In addition, each servo will need one output pin (typically 9 and 10 for both servos).

Hence in the worst case, you would need 20 pins overall. You have them on Arduino UNO but this means you don't have anyhting else left, even Serial communication!

If you can wire all 6 enable pins together, then you will need "only" 15 pins.

Also, note that if you want to control the speed of the DC motors, you will need PWM pins, but then you won't get enough with a UNO.

Regarding drivers ICs (L293 or L298), each of them has 2 full H-bridges, hence can drive 2 DC motors in bi-directional mode, so you will need 3 of them overall.


How to run led and buzzer at the same time?

The following Code is not tested. You can take it as an example. If you find errors, it would be nice to report them, so I can correct my prog.

// here I just guess (10msec), I think you don't want a delay
// of 0 as in your code.
int   blinkDelay        = 10;
long  lastBlinkTime     =  0;
int   patternSequence[] = { 1, 1, 1, 2, 2, 2, 3, 3, 3, 1, 2, 1, 2, 1, 2, 1, 2 };

int   patternSize     = 17;
int   actPattern      =  0;
int   delActive       = -1;

int  frequency     = 635;
int deltaFreq      =   1;
int  toneDelay     =  10;
long lastBuzzTime  =   0;

void setup()
{
  pinMode( 5, OUTPUT ) ;
  pinMode( 6, OUTPUT ) ;
  pinMode( 7, OUTPUT ) ;

  ledsOff();
  buzzer( frequency );
}

void loop()
{
  int actTime = millis();

  if ( ( actTime - lastBlinkTime ) > blinkDelay )
  {
    if ( delActive > 0 )
    {
      ledsOff();
    }
    else
    {
      actPattern++;
      if( actPattern > ( patternSize - 1) ) actPattern = 0;
      pattern( patternSequence[ actPattern ] );
    }
    delActive *= -1;

    lastBlinkTime = actTime;
  }

  if ( ( actTime - lastBuzzTime ) > toneDelay )
  {
    frequency += deltaFreq;

    if ( frequency > 911 ) deltaFreq = -1;
    if ( frequency < 636 ) deltaFreq = 1;

    buzzer( frequency );
    lastBuzzTime = actTime;
  }

}

void buzzer( int freq )
{
  //PIN 9 - Buzzer
  tone(9, freq);
}

void ledsOff()
{
  digitalWrite( 5, LOW );
  digitalWrite( 6, LOW );
  digitalWrite( 7, LOW );
}

void pattern( int num )
{
   switch ( num )
   {
      case 0:
        ledsOff();
        break;

      case 1:
        digitalWrite( 5, HIGH );
        break;

      case 2:
        digitalWrite( 7, HIGH );
        break;

      case 3:
        digitalWrite( 5, HIGH );
        digitalWrite( 6, HIGH );
        digitalWrite( 7, HIGH );
        break;
   }
}

Update

I've tested the code at home on my esplora. It worked, but not for a long time. I had to change the timing logic, by using the method millis()directly. Now it works. Below is the new code; tested this time. I also introduced some constants on top, because the their names act as documentation ;-). And I experimented with the values. The actual values are my preferences, But I'm by far no Bethoven and can not say if this relly sounds like a police siren. At least, it sounds not like a german police siren which I know better. (No I'm meither a policement nor his/her customer ;-))

Because I tested the code on my Esplora, I had to change the Pin assignments  (now out commented). In this copy I changed back to the original ones.

int   blinkDelay        = 100;
long  lastBlinkTime     =  0;
int   patternSequence[] = { 1, 1, 1, 2, 2, 2, 3, 3, 3, 1, 2, 1, 2, 1, 2, 1, 2 };

int   patternSize     = 17;
int   actPattern      =  0;
int   clearActive       = -1;

int  lowerFreq       = 680;
int  higherFreq      = 840;
int  deltaFreq       =   2;
int  toneDelay       =  20;
int  toneDelayOffset =  -1;
long lastBuzzTime    =   0;

int  actFreqStep   = deltaFreq;
int  actFreq       = lowerFreq;

// orig pins
int col1Pin   =  5;
int col2Pin   =  6;
int col3Pin   =  7;
int buzzerPin =  9;

// esplora pins
// int col1Pin   =  5;
// int col2Pin   = 10;
// int col3Pin   =  9;
// int buzzerPin =  6;

void setup()
{
  pinMode( col1Pin, OUTPUT ) ;
  pinMode( col2Pin, OUTPUT ) ;
  pinMode( col3Pin, OUTPUT ) ;

  // initialize LEDs off
  ledsOff( );

  // and buzzer to the act frequency
  buzzer( actFreq );
}

void loop()
{
  if ( ( millis() - lastBlinkTime ) > blinkDelay )
  {
    if ( clearActive > 0 )
    {
      ledsOff();
    }
    else
    {
      actPattern++;
      if( actPattern > ( patternSize - 1) ) actPattern = 0;
      pattern( patternSequence[ actPattern ] );
    }

    clearActive     *= -1;
    lastBlinkTime  = millis();
  }

  if ( ( millis() - lastBuzzTime ) > ( toneDelay + toneDelayOffset ) )
  {
    actFreq += actFreqStep;

    if ( actFreq >= higherFreq )
    {
      actFreqStep   = -1 * deltaFreq;

      // down sweep is slower
      toneDelayOffset = -1;
    }

    if ( actFreq <= lowerFreq )
    {
      actFreqStep   =  deltaFreq;
      toneDelayOffset =  0;
    }

    buzzer( actFreq );
    lastBuzzTime = millis();
  }

}

void buzzer( int freq )
{
  tone( buzzerPin, freq );
}

void ledsOff()
{
  digitalWrite( col1Pin, LOW );
  digitalWrite( col2Pin, LOW );
  digitalWrite( col3Pin, LOW );
}

void pattern( int num )
{
   switch ( num )
   {
      case 0:
        ledsOff();
        break;

      case 1:
        // red
        digitalWrite( col1Pin, HIGH );
        break;

      case 2:
        // blue
        digitalWrite( col3Pin, HIGH );
        break;

      case 3:
        // white
        digitalWrite( col1Pin, HIGH );
        digitalWrite( col2Pin, HIGH );
        digitalWrite( col3Pin, HIGH );
        break;
   }
}


Why is this variable giving me always the value of 0?

When I formatted your code for readability and then compiled it I got these warnings:

/tmp/arduino_modified_sketch_71221/sketch_may02a.ino: In function 'void loop()':
/tmp/arduino_modified_sketch_71221/sketch_may02a.ino:34:20: warning: suggest parentheses around assignment used as truth value [-Wparentheses]
   if (distance = 15);
                    ^
/tmp/arduino_modified_sketch_71221/sketch_may02a.ino:34:21: warning: suggest braces around empty body in an 'if' statement [-Wempty-body]
   if (distance = 15);
                     ^
/tmp/arduino_modified_sketch_71221/sketch_may02a.ino:41:38: warning: suggest braces around empty body in an 'if' statement [-Wempty-body]
   if ((monroy >= 0) && (monroy <= 5));
                                      ^
/tmp/arduino_modified_sketch_71221/sketch_may02a.ino:47:40: warning: suggest braces around empty body in an 'if' statement [-Wempty-body]
   if ((monroy >= 5.1) && (monroy <= 9));
                                        ^
/tmp/arduino_modified_sketch_71221/sketch_may02a.ino:53:21: warning: suggest braces around empty body in an 'if' statement [-Wempty-body]
   if (monroy >= 9.1);

These are important - you should pay attention to them. For example, here:

  if (distance = 15);  // <-- NO SEMICOLON NEEDED HERE!
  {
    digitalWrite (3, HIGH);
    delay (5000);
    digitalWrite (3, LOW);
  }

Putting a semicolon there means that stuff under the if is always executed - the semicolon terminates the scope of the if.

To see the warnings open the Preferences dialog in the IDE GUI and change "Compiler warnings" to "All".

Also:

  if (distance = 15);

This assigns 15 to distance, so distance will always be 15. You mean:

  if (distance == 15)


Start with the newest Arduino IDE. At this moment that is version 1.8.1.

Try to find the Library Manager. Via the menu: Sketch / Library...

In the Library Manager there is a input field in the upper-right corner where you can search for libraries.

If you can not find the library, then the next step is to download a zip file from Github. There is probably a green button "Clone or Download" on the right side with that project on Github. Use it to download that library and store it. Do not unzip it. In the Arduino IDE in the menu via: Sketch / Library... there is a option to install a .ZIP file. Use that to install the library from Github.

Your projects are probably at: Documents / Arduino

There is also a folder: Documents / Arduino / libraries

That is where the installed libraries will end up. That means you can also add libraries to that folder. Each library in its own sub-folder.


ESP8266 WiFi modules typically have a baud-rate of 115200. This not only won't work with a 9600 baud host but SoftwareSerial can't go that fast. Or, more precisely, it can generally push out characters at that speed but it can't keep up with incoming ones. See this answer for how to change the speed of your module to 9600 baud.

Short answer: You have to reconfigure your ESP module to 9600 baud to use it with SoftwareSerial. You can do it blind (transmit a baud-change command to it at 115200 baud, even though you won't be able to read the reply). Once done, it will remain at 9600 baud and successfully communicate in both directions.


Autosolved thanks to this old forum post.

It is Serial1 not Serial.
In the Arduino code in the Yun Serial is a different object from Serial1. Even if it is not super well document (or at least not in the first dumb google search) here are some links that talks about Serial1:

https://www.arduino.cc/en/Tutorial/YunSerialTerminal
http://andrea-toscano.com/arduino-yun-tcpip-to-serial1-redirect/
http://crossbar.io/iotcookbook/Arduino-Yun-Disable-Bridge/


I want to build a radar alert system with Arduino

I think that's quite possible. As mentioned, not technically radar. I don't know if cats could hear it, but then if it scares them off, job done, right?

I don't know if sending the alert to a PC would help or not - you might just consider an audible alarm using a cheap 8-ohm speaker. Otherwise, USB, bluetooth, wifi, or SMS for notification. A PC or phone (on all the time) to receive the data. Some thought about what you will do with it.

As a deterrent, a water pistol is ideal, you'd need a motor - solenoid? - to fire the water pistol. Harmless, but very distasteful to cats.

https://www.youtube.com/watch?v=lxmRYRlgreo

Update: Inspired by @SDSolar, I checked it out - yes, cats can hear that frequency.

  Cats have excellent hearing and can detect an extremely broad range of frequencies. They can hear higher-pitched sounds than humans or most dogs, detecting frequencies from 55 Hz up to 79 kHz.

(from https://en.wikipedia.org/wiki/Hearing_range#Cats )

This means they will probably learn to associate the sound with the water pistol (yes, cats CAN be trained, if they are motivated). This means if you remove your device, they will probably come back, but if you leave the sensor (active), but remove the water, then it will continue to work!


Control/Interacting with Android OS using Arduino board

What you've seen is most usually a bluetooth module which has a "virtual COM port" service -- you connect to the bluetooth module and you can then send a data stream up and down through this COM port, just like you are able to do with a normal Serial port.

If you want a bluetooth keyboard:

What you want for seamless integration is a bluetooth module which natively exposes a "HID" (Human Interface Device) profile. Keyboard, mice and gamepads are examples of an HID.

There is a multitude of projects which use Arduino + Bluetooth HID module:

http://www.kobakant.at/DIY/?p=3310 uses an Arduino Pro Mini and and BlueSMiRF HID (from Sparkfun)
Evan Kale's video: https://www.youtube.com/watch?v=BBqsVKMYz1I (uses HC05 bluetooth module with altered firmware)
https://mitxela.com/projects/bluetooth_hid_gamepad
Bluefruit EZ-Key: https://www.adafruit.com/product/1535

When you are a beginner you should buy the more expensive modules which don't require you to do any firmware hacking. Adafruit's product might work for you. As the description page says, you can connect a microcontroller's UART TX to the modules RX pin to send arbitrary keystrokes. You can then add a keyboard matrix, or lots of buttons, or whatever you desire to that microcontroller to make it trigger the keypresses you want.

This should get you started on your own research.


Your indenting doesn't match your code.

Right after the very first if (without an else), you have a new open brace ({). This looks wrong:

if ((distance1>7)&&(distance1 <= 20))
 {
  myservo1.write(150);
  delay(1000);
 }
 { // <<<< What is this?

The very very final else matches the very very final if - certainly not the first if!

Also, what is the difference between distance1 and distance2? You only have one ultrasonic sensor - there is only one distance!

EDIT:

I think what you need to do is use loop() more effectively. At the moment, you're pausing in the middle of your code, rather than letting the rest of the code work and using millis(). That function returns the number of milliseconds since the program started - which you can use for your problem (with a little mathematics):

EDIT 2:

I've added a little extra code to play different tunes depending on the current state. It uses the library at http://www.rhydolabz.com/other-widgets-c-205_124/mini-mp3-player-module-p-2159.html

static unsigned lastMilli = 0;
static byte lastLED = 0;
static const byte LEDs[] = { led1, led2, led3 };

distance1 = // Whatever you call to get the distance...
if (distance1>7) && (distance1<=20)) { // Too close?
   if (lastMilli==0) {       // Is this new???
       lastMilli = millis(); // Yes! Record that...
       mysero.write(150);    // ...and set servo.
   } // if
   unsigned delay = millis() - lastMilli; // Get how long it's been
   byte which = delay / 10000 % 3;        // Which LED / tune?
   byte LED = LEDs[which];                // Which LED?
   if (LED != lastLED) {                  // Has LED changed?
       if (lastLED!=0) {
           digitalWrite(lastLED, LOW);    // Yes! Stop that one
       } // if
       mp3_single_loop(true);             // Play forever!
       mp3_single_play(which+1);          // Play "mp3/000#.mp3"
       lastLED = LED;
       digitalWrite(LED, HIGH);           // And start the new one
   } // if
} // if
else if (lastMillis!=0) { // They're gone!
    digitalWrite(lastLED, LOW); // No LED
    myservo.write(0);           // No servo
    lastMilli = 0;              // So start again
    lastLED = 0;
    mp3_stop();
} // else


Yes, it should be.  At least according to the Cortex M3 Technical Reference Manual that I think I downloaded from ARM.  (DDI0337E_cortex_m3_r1p1_trm.pdf)

In section 11.5 of said manual, there is a register called DWT_CYCCNT (Data Watchpoint and Trace Cycle Count Register) which is incremented once per clock cycle when the appropriate flag of the DTW_CTRL (DWT Control) register is set.

This flag is unset on reset of the CPU so it needs to be set manually (unless it is done by the Arduino IDE, but checking the header files of the IDE, it doesn't look like it as unlike many other CPU registers, there is no Arduino REG_ define for these registers).

This untested code should be usable as the basis for your own code.  I suggest you add some serial initialisation in there and dump the value of currentCycles to the serial log to test it.  I am away from my hardware at the moment so can only test that it compiles.

#define REG_DWT_CTRL (*(unsigned int*)0xE0001000U)      /* Data Watchpoint and Trace Control Register */
#define REG_DWT_CYCCNT (*(unsigned int*)0xE0001004U)    /* Data Watchpoint and Trace Cycle Count Register */

#define CYCCNTENA ( 1 << 0 )                            /* DWT CTRL Cycle Count Enable Bit */

void setup()
{
    REG_DWT_CTRL |= CYCCNTENA;
}

void loop()
{
    unsigned int currentCycles = REG_DWT_CYCCNT;
}

Edit:
Note that the counter is a 32 bit register, so at 84 MHz it will reset every 51.13 seconds.  It is a read only register so writing to it will have no effect (you cannot manually reset it that way).


Endurance of Arduino UNO during 24/7 operations and mild power fluctuations

Is the Arduino Uno capable of surviving the extended service expectancy and execute the program correctly?

Yes, it is. Though your program and wiring needs to be stable and correct.

What is the influence of small voltage fluctuations on the endurance of electronics on the board?

Depends on what you call small. As long as you don't enter the brown-out region (where the voltage is so low, that the Arduino goes into reset for safety) or giving a too high voltage to it (See the specifications for that), you should be fine.

Is a heat sink needed for this application? How to determine the power draw to choose heat sink size?

The power draw of the Arduino depends on what you are doing with it. The best way would be to just measure the current of your application. Then you get the power by multiplying current and voltage. Normally you don't need a heatsink with an Arduino. The only part, that can get hot, is the linear voltage regulator. Depending on what you are interfacing with the Arduino, you might need to put a small heat sink on that (12V is a bit on the high side of input voltage for the regulator. It will dissipate the excess 7V as heat, so 7V multiplied by the used current). The microcontroller on the Arduino will not get hot (unless you are doing something terribly wrong).
And you should make sure, that the current for extra peripherals in your project doesn't flow through the Arduino, since that will place an extra burden on the voltage regulator. It should flow past it (means you connect them in parallel to the voltage source).

Is there any fatigue rating for the cyclic running of the program?

No, not really. I think the flash memory (where the program is stored) has a data retention failure rate of less then 1ppm (parts per million) over 20 years. So the program will not be lost, until you plan to run your application a hundret years. Also there is no read limit on the flash memory, only a write limit.


Where can I find the complete list of Arduino Serial Command & Query Strings?

The Arduino has no "standard" serial commands.

It is a programmable device which you have to program yourself. The only serial commands it can respond to are the serial commands you yourself program it to respond to.

There are projects around that provide a serial interface, but they are generally designed for one specific purpose, and the commands or protocol they implement are unique to that project.

The closest to what you are asking for is the Firmata firmware, which comes with the IDE, and can be used to control the Arduino through the serial port using programs on your PC.


How to determine the SPIFFS size on an esp8266-01?

First you need to know the size of the flash memory attached to esp8266 on your module. Common sizes are 512 kB (4Mbit), 1 MB (8Mbit) and 4 MB. Espressif Flash Download Tool (Windows) or esptool can determine it.

You can choose the size of the SPIFFS in your flash 'layout' by selecting the option in IDE Tools menu. Take one according to for you flash size and size of the files you want to put into SPIFFS.

If you have 1 MB flash on your module and you want to use OTA upload, let flash space for twice a space taken by the sketch.


There are more ways to flash a bootloader to new AVR chip. To which you refer? If you replace the chip on Uno to burn a bootloader to it with a programmer, then it is very unclear what you are asking, because the original chip is not involved in this process.

If you ask about ArduinoISP sketch, then simply it is a sketch. You upload it as any other sketch and replace it with any other sketch.


Like Gil said, it sounds like what you are calling a two-way switch is actually a three-way switch. These are typically wired like this (but not always, make sure to double check!):

To replace one of the two switches with a relay, you can simply connect a SPDT relay with the load/hot wire (depending on which side you're adding the relay from) to the common contact, and then the two traveler wires to the normally open and normally closed contacts. This effectively takes your existing wiring and directly swaps in a relay -- after all, the relay is literally a switch, just electrically activated instead of manually.
I can't speak to the reliability or lack thereof of a specific model of relay, but a normal power relay is more than adequate for home automation in almost all cases; you don't need anything too fancy. Yes, there will be a mechanical point of failure, but they are typically rated for 100,000+ actuations minimum on a decent relay (like this one from SparkFun, for example) which will take quite some time to reach. Avoid the super cheap relays both for safety and reliability, and you should be fine.


startFlag variable never goes to zero because there is a bug in this part of code:

 if ( ( buttonstate == HIGH ) && startFlag == 1 ){
          **startFlag = 0;**
          endTime = startTime =0;
          elapsedTime = endTime - startTime;
          countstart = 0;
  }


ArduinoJSON v6 - Passing buffer as function parameter

The StaticJsonDocument is a template class. The template value in <> is here only the size of the internal buffer, but every size used generates a different class. (memory usage!)

To have the parameter of the function take an StaticJsonDocument version instance, it must be the same version or a common base class. In this case the base class is JsonDocument.

If you don't use the reference symbol & the parameter is copied. In this case StaticJsonDocument<200> _doc or JsonDocument _doc would create a copy and that copy would be modified in the function. The object used as parameter value would be unchanged - empty.

So use

void test2(const JsonDocument& _doc) {
  Serial.println("HI");
  serializeJson(_doc, Serial);
}


WiFi thermometers: save different location string as const across many devices

With a set of DIP switches or jumpers on some of the GPIO, you could encode a unique number for each one - 16 of them with 4 I/Os f/ex. The same code could run on all of them, sample the unique ID  report it along with the temperature. Let the PC-side map IDs to locations.


Why does an Arduino UNO need two GND ports?

In electronics circuits, a major point in connecting two circuits and make them "talk" together is to ensure, at the minimum, that they have a common reference of voltage (typically called GND and defined as 0V voltage).

On Arduino, GND pins can be used in 2 situations:

to directly power the Arduino with an external supply which cannot be plugged to USB or power jack. In this case, the positive voltage of that external power source shall also be supplied to Vin pin.
to connect Arduino GND to your circuits.

Having 2 distinct GND pins is, I think, just a matter of convenience when you want to build prototypes but don't necessarily have a breadboard (if you use a breadboard, you will just need to connect its power rail to Arduino GND pin and use this power rail directly).


Arduino SoftwareSerial library basic example doesn't work

If your Arduino is connected via the built-in USB port then you need to use the hardware serial port (pins 0 and 1). To do that, call Serial.begin(..) and Serial.println(..), instead of mySerial....

SoftwareSerial is used when you want to connect via serial on some other pins. It allows your program to emulate serial input/output in software instead of relying on dedicated hardware. In this case, your program is trying to setup software serial on pins 10 and 11. That won't show up on the serial monitor because it's not connected to those pins.


Yes. You need to create a factory partition and upload your bin file to there.

You can read more about ESP32 partitions here

Note that none of the partition schemes in the ESP32 core have factory partitions, so you will need to create a custom one and link it to a menu entry (look at the boards.txt file to see how that is done).

The existing partition files are just .csv files within the ESP32 core. Copy one and modify it, then link that to a menu entry using the new file name.


How to burn the bootloader and upload sketches on ATmega328P U (specifically this model)?

IT WORKED, FINALLY. I followed this tutorial: https://www.electronics-lab.com/project/installing-the-arduino-bootloader-on-the-atmega328p-microcontroller/, followed exactly as it is explained, made the connections (nothing more, nothing less; I even removed the LED on pin 19 and its resistor) and to my surprise... the bootloader was actually loaded and the sketches were uploading just by using the FTDI. Thank you a lot for your help and information and I hope someday I'll pass this knowledge to someone who will be in the spot I was until now. Have a great time and love ya all


I had this issue myself, when I tried to use these stepper motors (which are to be honest really crappy ones, but very cheap). Vibrating mostly means, that the phases of the motor are not activated in the correct order. These motors seem to work with an activation pattern for half steps (I don't know, if the motor is really doing half steps with this, because I didn't counted them for a whole revolution. But at least they worked). The Stepper library (I assume from your code, that you are using this one) isn't meant for this driver, so it will turn on the phases in a wrong order and always two phases at the same time (as for full steps).

I had success, when driving the 4 phases of the driver with the following pattern (for half steps):

1000
1100
0100
0110
0010
0011
0001
1001

I also found hints on the web (on a german site, just for reference, if you can read german), that - despite being meant for half steps - you can drive the motor with full steps with the Stepper library as well. You would have to change the order of pins in the definition of the stepper:

Stepper myStepper(stepsPerRevolution, 8, 10, 9, 11);

This assumes the wiring as: D8->IN1, D9->IN2, D10->IN3, D11->IN4. Note, that using full steps means 2048 steps per revolution.

I also found a library specific for this stepper motor, but I haven't tested it: Stepper_28BYJ_48

Now you can decide yourself, which way you want to go. I personally would go for the full steps with the official Arduino Stepper library.

About the number of steps per revolution: I don't know, why the stepper doesn't work with a vale of 2048. But since the library only uses this to wrap up the correct phases for the revolutions, you can use a lower value, that is dividable by 4. For example 32, which is the number of full steps per revolution of the actual motor (it is attached to gears with a factor of 64). That should work.


In the example, digital pins 10 and 11 (mySerial) on your Arduino board are used as virtual RX and TX serial lines. The virtual RX pin (pin10)is set up to listen for anything coming in on the hardware RX serial line, and to then echo that data out the virtual TX line (pin11). Conversely, anything received on the virtual RX (pin10) is sent out over the hardware TX.


Newbie Using Brown Out detector on Arduino Due for saving variables to eeprom?

Not a good idea - if the power goes down when you writing to EEPROM, your EEPROM data will be corrupted. The brown-out detector goal is to shut off the MCU, before it goes mad due to low power voltage.

The solution of this issue - use some huge capacitors (about 4700 mkF) - like a small UPS device.

When external power goes off, you well get enough time and power to store your bytes safely.

How it works

When +5V is okay, the capacitor is charged on, and the light diode (pins 1-2) inside of PC817 is on, so the transistor part of PC817 (pins 3-4) is open, and POWER_GOOD signal is LOW.

When power goes off, capacitor starts to discharge and give power to the right part of scheme. The Schottky diode acts as a valve, that stops the power to go to the left part. The another diode, which is inside of PC817 now goes off, and the transistor goes to close - POWER_GOOD signal goes to HIGH level and your program may start save data to EEPROM.

Why the optocoupler?

We need to investigate about internal AVR chip circuit. It has couple of diodes on each pin:

So, when we connect PIN directly to power, +5V, and connect AVR's VCC to +5V over the Schottky diode, we've got two diodes in parallel! This situation is very bad, because they may compete, which will conduct the current - and, in some cases, internal (which is weak), chip diode wins. All controller power current start flow thru this weak diode, heats it up and toasts the chip! Not very good.


Adafruit tells to avoid the Arduino Due. One of the reasons is the I2C bus. Can you use an other Arduino board? For example one of the MKR boards with a SAMD21 processor.

The Due has pullup resistors on the board for SDA and SCL which are too low in value. Sometimes the I2C bus with SDA and SCL works, but sometimes it does not work at all. Perhaps you are able to remove the pullup resistors at SDA and SCL from the board.

If possible use Wire1 with SDA1 and SCL1. Those have no pullup resistors at all, so you need to add 4k7 pullup resistors to 3.3V. When you use a library, you might have to change the library to use "Wire1" instead of "Wire".

You need to remove these, they are not doing something:

while (!Wire.available());    <- not doing something

Remove the Wire.endTransmission at the end.

Wire.endTransmission(true);   <- remove this
return data;

That library does not use the Wire library in a proper way.

The pullup resistors are 1k5 or sometimes 1k and are located in the upper-right corner, near pin 20 and 21. A value of 1k5 should be okay, when there are no other pullup resistors. When you board has 1k resistors, then I suggest to remove them.

Removing them is possible with a soldering iron and a big blob of solder. Check if the board is clean afterwards, for example with a magnifier. Avoid overheating your expensive Arduino Due board.

The I2C bus needs pullup resistors to work. A normal value is 4k7. Sometimes there are already 10k pullup resistors on a sensor module.

If the I2C has problems, start by using short seperate wires for SDA and SCL. When a cable is used for the I2C bus, then the cable is probably the problem and not the pullup resistors.


Several issue with this code. First, use public/protected/private for classes. Second, use a const char* instead of String or even better str_P. It is the usage of String that is giving the compile error. Third, the Test::TestCallback function reference is not possible. It is a member function. To correct that either have an instance or define the callback function as static.

You could define an abstract MenuItem class with the string and a virtual member function. A Menu class would hold a collection of MenuItems. All the static data should be put in program memory.

There is a Menu system in Cosa. Please see the example sketch. This implementation follows the MVC design pattern.

Cheers!


Decode rf remote signals with ESP32 or node MCU?

For ESP32, you should provide real GPIO number.
For instance:
mySwitch.enableReceive(13);
And without deep explanation, believe that it properly works
with GPIO 13 and 27.
Details you can find by google...


Uno r3 - Can't get USB Keyboards to work with an USB Host Shield

see last paragraph of this page https://github.com/felis/USB_Host_Shield_2.0

it says this:

  FAQ

  When I plug my device into the USB connector nothing happens?

  Try to connect a external power supply to the Arduino - this solves
  the problem in most cases.

  You can also use a powered hub between the device and the USB Host
  Shield.

  You should then include the USB hub library: #include <usbhub.h>

  and create the instance like so: USBHub Hub1(&Usb);.

your keyboard may be multiple HID devices with a USB hub to connect them


16x2LCD Display serial read extra character

The LCD display acts a bit different to a normal console. For instance, it does not recognize the newline character and uses the corresponding ASCII code (10) like a normal letter. Depending on the letter map of your display (for which there are several variants on the market) this will print a more or less random character. To avoid this, you have to strip the last letter from the input string before sending it to the display.
For the same reason, sending an empty string does nothing, since an empty string sends no letters. To clear individual characters in the display, you have to overwrite them with a space.


Modbus master arduino code is throwing weird errors on upload

Your issue is that you define constants, such as timeout, which are widely used in Arduino library as parameter names. After preprocessing your definitions, correct code in "Arduino.h" such as

unsigned long pulseIn(uint8_t pin, uint8_t state, unsigned long timeout);

becomes

unsigned long pulseIn(uint8_t pin, uint8_t state, unsigned long 1000);

No wonder the latter line fails to compile.

You will need to find unique names for your defines, or use constant variables instead.


Unable to upload sketch using Platformio (but Arduino IDE works)

Please use board = nanoatmega328new in your platformio.ini


Is it wise to use analog input pins to read digital buttons?

The Analog pins are essentially identical in functionality to digital pins when used as digital I/O.

If desired you could "be clever" and use an analog input in analog mode to read multiple keys using one pin. eg using 10k, 22k, 39k, 82k, 150k in series with 5 buttons from V+ to pin and a say 4k7 to ground would result in 5 voltages which were easily distinguished using an analog read. This is a very very old technique indeed and allows far more than 5 keys on one input pin. THere are limitations which can be discussed if required.

R1 ... R5 correspond to buttons 1...5

Vout = V+ x Rb / (Rb + Rbutton)

Example only

Rb = 39k
R1 = 10k
R2 = 22k
R3 = 39k
R4 = 82k
R5 = 150k

Gives

The % of V+ in column 2 when a button is pressed.
The voltage in column 3 with V+ = 5V

Delta-V is the difference between that key and the one below - very ample clearance.


Arduino Yun Python ImportError: No Module named mime.multipart

mime.multipart isnt used in your code at all so you shouldn't be getting that error. The correct import statements for Python 2.7 are:

from email.mime.multipart import MIMEMultipart
from email.mime.base import MIMEBase
from email.mime.text import MIMEText
from email.utils import COMMASPACE, formatdate
from email.encoders import Encoders

Study these examples in the Python 2.7 documentation.


Are these GND connected resistors on the Arduino Due redundant?

Yes, they are redundant. They are elements of resistor arrays (multiple resistors in one package) that aren't used. They have just connected all unused pins of those packages to ground.
If you want to know why they would have unused elements, it's all to do with optimizing the manufacturing process. If you have, say some 100k arrays elsewhere in your design and you want to have maybe one or two other 100k resistors elsewhere, rather than adding another component of a discrete 100k resistor it's cheaper to use a 100k array and not use some of the elements. One of the factors in the cost of pick-and-place operations is the number of different components. By keeping the number of component types to a minimum they keep the manufacture costs to a minimum.


In simpler terms mask <<= 1 is shorthand for mask = mask << 1

In general

variable operator= operand

is the augmented assignment operator which means

variable = variable operator operand


Can I corrupt my Arduino if it's unplugged during an upload?

AVRDUDE does not actually perform the write, it merely directs it. The actual writes are performed either by the bootloader or by the ISP firmware/hardware within the MCU itself.

With the bootloader it depends on how itself is coded, but at worst it would finish off the flash byte or page or EEPROM page zero- or one-filled and then fail to communicate further with AVRDUDE, aborting programming.

With ISP, the page write command would never be received and the programming would be aborted at the last full page. Fuse bytes are done singly and so programming a single fuse can be viewed as an atomic operation.

In either case, a chip erase operation should reset the MCU to a known working state, fuse changes excepted.


Read car high temperature exhaust pressure sensor

Yes, I don't see why it wouldn't be possible.

You would need a sturdy barometer, preferably a digital I2C one because they are typically more accurate. I recently bought this one to measure altitude: BMP180 Barometric Pressure/Temperature/Altitude Sensor- 5V ready.

Be careful about the temperature that the sensor will have to deal with, its maximum temperature is 85°C (185°F).

The motor, I'm assuming, would be fairly large so you would need a beefy motor driver that uses a 5 volt logic level, maybe like this one: L298 Dual H-Bridge Motor Driver.

This is a fairly difficult project, I'd say mostly because of the difficulty you would have mounting the barometer and motor. Never the less, it still is possible.


Programming ATmega328p on external board with FT232R

I suggest use ICSP(In circuit serial programming) feature of the Atmega 328 chip. Grab the .hex file from the arduino IDE and a USB ISP external programmer to write the program to the chip. Here you will have to use a 6 pin header on your custom board to take out the pins which are used to program the atmega.


Signal a LOW level interrupt with an RTC

That page is incorrect, although it reflects what the datasheet says.
The processor can be woken from RISING/FALLING/CHANGE/LOW. I queried this with Atmel and got this response:

Commented by Manoraj Gnanadhas (Atmel)
2015-01-20 06:23:36 GMT
[Recipients: Nick Gammon]
Hello Nick,
Our design team has confirmed that “Note-3 mentioned under Table 10-1” is a datasheet bug. So you can use any type of interrupt (Rising edge/ Falling edge / Low level / Any logical change) to wake up from sleep mode. Sorry for the inconvenience caused.
Best Regards,
Manoraj Gnanadhas

This is mentioned on my page about interrupts.

Why does LOW hang the processor? The LOW interrupt is not an edge interrupt but a continuous one. Thus, while the signal is LOW the interrupt is being continually called, with only one processor instruction being executed after each call to the ISR (which itself takes around 5.125 µs). So, the ISR is not being interrupted, but effectively only one instruction of your code is being executed every 5.125 µs (probably about 1/40th of the usual speed).

and see how much of my problem is due to using an old and buggy IDE

It's nothing to do with the IDE. Change to a FALLING interrupt and your problems should go away. You may also want to clear the interrupt flag (as documented on my page) in case the interrupt event has already happened before you go to sleep. Specifically:
EIFR = bit (INTF0);  // clear flag for interrupt 0


Arduino OBD library and software serial library

That library is hard-coded to use the single Hardware Serial device on the Arduino Uno or the second Hardware Serial1 device on other boards.

#ifndef OBDUART
#if defined(__AVR_ATmega328P__) || defined(__AVR_ATmega168P__)
#define OBDUART Serial
#else
#define OBDUART Serial1
#endif
#endif

You can edit the library's header file OBD.h to define your own serial port though:

#include <SoftwareSerial.h>
extern SoftwareSerial mySerialPort;
#define OBDUART mySerialPort

And then in your sketch create the mySerialPort SoftwareSerial object.


How to drive a stepper motor, by having it go even steps forward and odd steps back?

Ok, I tried to fix a couple of things from your code.

First of all I implemented a small state machine with two states: going forwards and going backwards. Normally you advance by 2 steps, but when you switch state you go directly to 0 or 11. In my opinion this is the most correct way to handle this problem.

Then I modified the way you trigger a movement. I totally dislike interrupts, specifically when not needed like in this case (at least in my opinion). I used the usual approach with millis(). Please note, however, that I had to put 2 milliseconds as period, but I think this was a mistake from your side (I think you wanted 2 seconds). If this is the case, write const uint16_t moveStepMs = 2000; instead of const uint16_t moveStepMs = 2;. If you want to keep the 2ms, please be aware that 2ms * 6 = 12ms, so it will go back and forth in about 25ms. This means it is too fast for you to see anything (and probably also for the motor to move).

Here is the code. I hope it is clear; I tested it online, but there wasn't a stepper in the simulator so I just used some LEDs (I think it works, anyway).

#include <Stepper.h>

const int stepsPerRevolution = 200;

Stepper myStepper(stepsPerRevolution, 2, 3, 4, 5);

const byte State_MovingForw = 1;
const byte State_MovingBack = 2;

byte currentState;
int8_t position; // Note: max 127 for position

const uint16_t moveStepMs = 2;
unsigned long prevMillis;

void setup() {
    Serial.begin(9600);
    prevMillis = millis() - moveStepMs;
    currentState = 0; // Invalid, so it will trigger a change
}

void executeStep(int8_t numOfSteps)
{
    myStepper.step(numOfSteps);
    position += numOfSteps;
}

void loop() {
    if ((millis() - prevMillis) > moveStepMs)
    {
        prevMillis += moveStepMs;
        byte nextState = currentState;

        // Check for a state change
        switch (currentState)
        {
        case State_MovingForw:
            if (position >= 12)
                nextState = State_MovingBack;
            break;
        case State_MovingBack:
            if (position <= 1)
                nextState = State_MovingForw;
            break;
        default:
            nextState = State_MovingForw;
        }

        if (nextState != currentState)
        {
            // Exit condition: what to do when exiting from one state
            switch (currentState)
            {
            case State_MovingForw:
                executeStep(0 - position); // Reset position to 0
                break;
            case State_MovingBack:
                executeStep(11 - position); // Reset position to 11
                break;
            }

            // Advance to next state
            currentState = nextState;
        }
        else
        {
            // no state change (so move to the next value)
            switch (currentState)
            {
            case State_MovingForw:
                executeStep(2); // Move two steps forwards
                break;
            case State_MovingBack:
                executeStep(-2); // Move two steps backwards
                break;
            }
        }
    }
}


Here is a page on interfacing Arduino with Python.

Interface Arduino with Python


MacOS 10.15.1 Catalina CU port always busy, and TTY port not selectable

Nevermind, updating my MacOS version to 10.15.3 magically fixed the problem...


toInt error when converting character of string to interger

The Arduino function toInt requires a String object.
You're passing it a single character, not a String.

int foo = String(bar[1]).toInt();


Arduino as ISP - program is being uploaded on Arduino, not breadboard

Use the "Upload using programmer" in Sketch menu to upload a sketch over ISP

warning, it deletes the bootloader


No. You need an accelerometer.

If you read the article you link to you can see this bit:

  There are many margin of improvement. First, we ought compensate the potential tilt of the device using the accelerometer data from the ADXL345, for example using the info on my previous post!

To do tilt compensation you need three axes of both magnetometer data and accelerometer data to scale and merge those three axes.


Passing user defined callback functions to a library method

A common solution would be to have the user provide a callback which
takes no arguments and returns nothing. This is how attachInterrupt()
works, so it may be the least surprising approach for your users. The
user function can then get data from the rest of the program using
globals.

If you really prefer passing an argument to the user function, the
problem is you do not know the data type. The usual approach in plain C
is to give it a “generic” pointer, and let the user cast it into a
pointer specific for his data type. This is how functions like qsort()
work:

HookNinja hookninja;

void userFunction(void *param) {
    someVariableType foo = * (someVariableType *) param;
    //do something with foo
}

void setup()
{
    hookninja.attachCallback(userFunction);
}

void loop() {
    someVariableType foo = something;
    hookNinja.process((void *) &foo);
}

A cleaner C++ approach could be to make you class a template that is
specialized for the type of the user data:

HookNinja<someVariableType> hookninja;

void userFunction(someVariableType param) {
    //do something with param
}

void setup()
{
    hookninja.attachCallback(userFunction);
}

void loop() {
    someVariableType foo = something;
    hookNinja.process(foo);
}

But keep in mind that many Arduino users may not be familiar with
templates.


Not only can you share the grounds - sharing the grounds is required for there to be any form of meaningful circuit for signals to get around the place.

To copy-and-paste a blog post I wrote some time back:

A lot of the time on the Arduino forums we get questions regarding wiring things together. One common format is:

  I want to connect my 12V powered LED strip to my Arduino but I can’t get it to communicate. I have checked all the connections and they seem fine. I have a 12V power supply for the LEDs and the Arduino is powered from the computer.

And 9 times out of 10 the first question we have to ask in return is:

  Have you connected the grounds together?

And guess what the reply to that usually is? Yep:

  No, do I need to? And isn’t that dangerous, connecting a 12V ground to the 5V Arduino ground?

That in itself shows a fundamental lack of knowledge about what “ground” actually is. So let’s start by clearing that up:

Ground, technically, is just a name given to a point in your circuit. That point is a point chosen by you against which all other voltages in the circuit are measured. Often it is the point of lowest potential, such as the – side of a battery, or the – connection of a power supply. Or it may have been chosen for you, such as the ground signal from the USB connection to your computer.

The 5V pin of the Arduino isn’t actually 5V – it is 5V with respect to the ground pin. Equally you could rename the 5V pin to Ground, and what was the ground pin then becomes -5V with respect to [the new] ground.

So ground has to be a single point in your circuit against which all voltages “make sense”.

Let’s take a look at the typical circuit from the original question. An Arduino connected to some 12V device (such as some 12V LEDs):

Here you can see the Arduino connected to, for example, a 5V USB charger. It could be a battery, or it could be the USB port on your computer. It matters not. Connected to that is a 12V device which then has its own 12V power supply. Now. Where is ground in that circuit?

The 5V pin of the Arduino is 5V with respect to the ground pin of the Arduino. So seen from the Arduino’s point of view ground is, in the image above, the bottom line of the Arduino’s power circuit (charger -). However, the 12V of the external circuit is 12V with respect to the – side of the 12V PSU. So seen from the point of view of the 12V device the ground is the lower side of the 12V circuit – the “PSU -” connection.

That doesn’t sound too bad, does it? Each device’s power is correct with respect to the power supply it is running off. As far as that goes, sure. However take a look at the data signal going from the Arduino to the 12V device. What voltage is that at?

Well, seen from the Arduino’s point of view, with respect to it’s ground, since it is generating the signal, it is a 5V signal. But, what about what the 12V device sees? What voltage is that signal with respect to the 12V circuit ground?

Given that voltages aren’t absolute – they are only relative to a reference point within the same circuit, it is impossible to know what the voltage is there.

There’s something more fundamental at play here though which can help you to understand it even better. In the image above there are two red arrows in loops. That is the flow of the current around the circuit (shown as conventional current flow). The key phrase there is around the circuit. Current has to flow out of a supply, through a circuit, and back to the supply from where it came.

In the circuit above the current can flow out of the 5V, through the Arduino, and back to the 5V again because there is a complete loop there. Likewise there is a loop from the 12V supply, through the 12V device, and back to the 12V supply again. But there is no such loop for the signal from the Arduino to the 12V device.  If we think of the Arduino’s output pin as a small power supply there really should be some way for the current to get out of the Arduino, through whatever it is connected to, and then back to the Arduino again. There is no way for that to happen in this circuit.

So you connect the grounds. As soon as you do that a lot of things start to happen. Let’s do that now and see how the circuit looks:

The grounds are now linked by the green wire at the bottom. Immediately we can now see a loop has appeared where the current from the IO pin can flow through the 12V device, out of the ground connection of the device, along the green wire, and back up through the ground connection of the Arduino.

In actuality the loop is a branch from the 5V power loop. Current goes from 5V into the Arduino where it splits, some to run the Arduino and some out of the IO pin. From there it goes through the 12V device, down to ground, then joins the current flowing out of the ground of the Arduino to go back to the 5V supply. It’s useful to think in terms of discrete loops though so you can get a better idea of how the ground fits into things.

Also, now, since the ground of the 5V section and the ground of the 12V section are one and the same (in a schematic all points along a line are the same point) any signals generated from the 5V side are recognisable by the 12V side as 5V since the reference point (ground) is the same for every point in the circuit.

But isn’t it dangerous?

Absolutely not. Not only is it not dangerous, it’s safer than not connecting grounds together. Since now the whole circuit has a single baseline voltage to reference everything from 12V is 12V and 5V is 5V. Without that link the voltage difference between ground on the 5V side and 12V on the 12V side could potentially be many hundreds of volts (especially when the distances between the two points is great). For fully isolated systems, such as battery powered devices, that is not a problem. For anything using power supplies though it can be quite dangerous. And that leads me on to my next point – a slight variation on the question:

I built a circuit with a 12V device powered from a power supply which is controlled by my Arduino. It all works well. But as soon as I run the Arduino from a battery instead of my computer it stops working.

This is a classic case where the grounds haven’t been connected together by the user, but there exists another path linking the grounds together. This is most often the earth connection of the computer and the earth connection of the power supply being linked together through the house wiring:

As you can see the current loop still exists, it just takes a longer route. As soon as you remove the Arduino from your computer and power it from batteries – or a power supply that has no connection to earth – the lower part of that loop disappears completely and you are back to the original circuit with only 2 loops. And it stops working.

Connect the grounds together manually, though, and you reinstate that portion of the loop, making it all work again.

So there you have it. If you have multiple power supplies in your project, whatever they may be (except in special circumstances) you must connect the grounds together for it to work. If it works without connecting the grounds together then you are inadvertently relying on some pre-existing ground connections to do the job for you, and that is likely to fail if your setup ever changes.


Which is better method to run a stepper motor with maximum possible speed..?

Microstepping

  which can be used to run the motor at almost zero speed ..?

Microstepping

  can we be able to rotate the motor at zero or less than Zero speed with PWM method..?

What is "less than" zero speed? Backwards? Turning through another dimension?  PWM cannot drive a stepper motor. That's like asking if you can download a cake through your suitcase. The concepts just don't match up.  Yes, there are ways of implementing microstepping using closely coupled phase controlled PWM signals, but the end result is microstepping.

A stepper motor requires coils to be activated in the right order and at the right time (and in some cases with the right polarity). PWM just generates a square wave with a set frequency and duty cycle.

To be clear, a single step of a stepper motor involves cycling through all the correct sequence of energising coils (often a sequence of 4 energisings). Microstepping is merely the act of stopping at different points within that single cycle to give a higher resolution that whole steps (usually 4 times the resolution). It is nothing magical or special.


The official arduino uno schematic uses a NPC1117 voltage regulator. This is a linear one. This means that if you put 12V on it, and if your system requises 0.5A, you Will leak 0.5A on the 12V, and, if there is 5V on the output, 12V on the input, there is a 7V drop on the regulator, 7V * 0.5A = 3.5W that turns into heat.

To avoid overheating, the solution isn't to increase the input voltage, but to decrease it. If you have a 6.2V power supply, this will minimize overheating. At least 6.2V are required for the NPC1117 to provide a stable 5V.

An other option is to use a USB 5V power supply with an output current greater than 0.5A. This is often used with smartphones. This allows to bypass the NPC1117, but the power supply shall be exactly 5V (where exactly stands for less than 10% of over or undervoltage).

Also, please note:

  Arduino does not recommend bypass[ing the] Vin supply to directly supply 5V rail on the board as it will damage the NPC1117. See the first two line on page # 3 from the document link below. http://media.digikey.com/pdf/Data%20Sheets/Arduino%20PDFs/ArduinoEthernet.pdf
  You can either do the soldering and remove NPC1117 chip before you apply 5V directly onto the board or find a higher current capability power supply with the output voltage between 7v-12V.


I suspect you are running a 32-bit compiler on a 64-bit operating system. You will need to install the 32-bit support libraries.

$ sudo apt-get install libc6-i386


How do I connect through a HC-05 to PS4 Controller?

The HC-05 uses the Bluetooth Serial Port profile (SPP). The PS4 controller doesn't.

Hence you need something that is capable of using the same profile that the PS4 controller uses (HID?). And to that end you need something a little more configurable than a simple HC-05. One option is, as most people use, a USB Host shield with a Bluetooth dongle that can then be configured to communicate using the right profile.


Arduino Mega prototype analog timer interrupts: newbie question

How would I use interrupts (timer, pin change interrupt?) for an analog pin that triggers when the vibration sensor is triggered, resulting in other components operating?

Thee best and most authoritative answer to that and all your other questions about the chip can be found in thee device data sheet and the compiler manual. Read them thoroughly and then write code to the data sheet to experiment.

Your can fire example have an analog interrupt where the chip constantly does ADC on the pin attached to the sensor and you can test the value of the ADC to see if certain trigger conditions are met and take appropriate actions.

The same with timers, etc. The data sheet is your best friend.


How should I customize UIPEthernet constants?

Creating a copy of the include file in sketch folder will not work. At library compilation the source files of sketch are not included. The "" for include is "search first in the same folder as the including file".
The project in the description of use of uip-conf.h is UIPEthernet. It includes the UIP library by Adam Dunkels and configures it with this file.

A project with UIPEthernet library can configure the library with options in uipopt.h. Most of the options in uipopt.h are defined as
#ifdef UIP_CONF_UDP_CONNS
#define UIP_UDP_CONNS UIP_CONF_UDP_CONNS
#else /* UIP_CONF_UDP_CONNS */
#define UIP_UDP_CONNS    10
#endif /* UIP_CONF_UDP_CONNS */

this allows to define the value on compiler command line as -D. Most IDEs enable to set project defines in project settings. Arduino IDE does not enable this yet, because it doesn't have a project configuration file.
With Arduino IDE you can add defines for platform or for board definitions with build.extra_flags in platform.local.txt or in boards.local.txt. Example for boards.local.txt for Arduino Mega:
mega.build.extra_flags=-DUIP_CONF_UDP_CONNS=20 -DUIP_CONF_MAX_LISTENPORTS=30
platform.local.txt and boards.local.txt must be in boards package folder nect to platform.txt and boards.txt.


Try powering the ESP from an external 3.3V power supply if possible - some people say the Arduino 3.3V regulator may not provide enough power for it (it is quite power hungry at startup).
Another option worth trying is to put a 100uF capacitor between ESP VCC and GND. Put some small delay at the beginning of your setup() function if you do that just in case.
Also, there are several pins you need to pull UP: CH_PD, RESET, GPIO0. If you have GPIO15 broken out (depends on the board), pull it to ground. I have also noticed the ESP won't boot properly if GPIO2 is LOW - either leave it floating or pull it up.
Here is a picture you can use as a guide
Of course, you should make sure the ESP is flashed with the AT commands firmware (they usually are) and your baud rate is correct. If you don't know - try 9600, 57600, 115200.
If you have a USB to TTL converter, it might be better (easier) to test your setup using it, without Arduino. Any serial terminal program (including Arduino IDE Serial Monitor) will be fine. Just make sure you send both CR and LF for new lines. If you send "AT" and receive "OK" your wiring is correct, if you don't - it is not.


The BISS0001 that your unit uses provides an "active high" output. To connect multiple devices together you just need to "OR" the signals.
There's many ways of doing that.
The simplest method is the "wired OR" circuit, which just involves one pulldown resistor plus one diode per device:

simulate this circuit – Schematic created using CircuitLab
You could also use a multiple-input OR gate chip. You can get these in 2- (74HC32), 3- (74HC4075), 4- (74HC4072) input versions.


Arduino bug when "myFile = SD.open" is inside loop()

The solution to your problem is to extend your 2 states machine in a multiple states machine.

Declare the enum eState before setup():

typedef enum e_State {
    STATE_START = 0,    // starting the loop (add some initialisation)
    STATE_READ_FINGER,  // Step1: read the finger print
    STATE_DISP_FINGER,  // Step2: display the finger print
    STATE_OPEN_LOGGER,  // Step3: open the log file
    STATE_WRITE_LINE,   // Step4: append a timestamp finger print
    STATE_CLOSE_LOGGER  // Step5: close the log file
} eState;

And update the loop() function with the state-machine:

void loop()
{
    static eState LoopState = STATE_START; // to store the current state

    eState NextState;  // for the next loop

    switch (LoopState) {
    case STATE_START:
        // add additional settings
        NextState = STATE_READ_FINGER;
        break;
    case STATE_READ_FINGER:
        etat = 0; // keep use your 'etat'
        // or return a boolean from your 'getFingerprintIDez()'
        lcd.clear();
        lcd.setCursor(0,0);
        lcd.print("Put Finger");
        getFingerprintIDez();
        if (etat == 1) {
            NextState = STATE_DISP_FINGER;
        }
        break;
    case STATE_DISP_FINGER:
        lcd.clear();
        lcd.setCursor(0,0);
        lcd.print("ID #");
        lcd.setCursor(4,0);
        lcd.print(finger.fingerID);
        NextState = STATE_OPEN_LOGGER;
        break;
    case STATE_OPEN_LOGGER:
        myFile = SD.open("data.csv", FILE_WRITE);
        if (myFile) {
            // record only if file is opened
            NextState = STATE_WRITE_LINE;
        }
        else {
            lcd.setCursor(0,0);
            lcd.print("Can't open file");
        }
        break;
    case STATE_WRITE_LINE:
        myFile.print(rtc.getDateStr(1));
        myFile.print("\t");
        myFile.print(rtc.getTimeStr(1));
        myFile.print("\t");
        myFile.println(finger.fingerID);
        myFile.flush();
        NextState = STATE_CLOSE_LOGGER;
        break;
    case STATE_CLOSE_LOGGER:
        myFile.close();
        lcd.setCursor(0,2);
        lcd.print("Loged");
        NextState = STATE_READ_FINGER;
        etat = 0;
        break;
    default:
        NextState = STATE_START;
    }
    // next loop()
    LoopState = NextState;
    delay(200);
}


Does not name a type error when using makeTime

You're trying to access the 'properties' (i.e. the members) of the tmet variable in a scope where they aren't accessible (outside of a code block). In this global scope of the program the compiler expects a type name on the left side of a statement (i.e. a variable or type declaration), but tmet's members like tmet.Year aren't types in and of themselves.

There are two solutions. You can move the access to the members of tmet into a code block like the setup function:

#include <Time.h>

tmElements_t tmet;
time_t dateMet;

void setup() {
  // put your setup code here, to run once:
    tmet.Year = 2013-1970;
    tmet.Month = 8;
    tmet.Day = 28;
    tmet.Hour = 18;
    tmet.Minute = 30;
    tmet.Second = 0;

    dateMet = makeTime(tmet);
}

void loop() {
  // put your main code here, to run repeatedly:

}

Or you could declare and define tmet in one statement, which has a different syntax (since you have to provide the content of a tmElements_t in a single line:

#include <Time.h>

tmElements_t tmet2 = { 2013-1970, 8, 28, 18, 30, 0 };

time_t dateMet2 = makeTime(tmet2);

void setup() {
  // put your setup code here, to run once:
}

void loop() {
  // put your main code here, to run repeatedly:

}

Both versions work right away from within the Arduino IDE (i.e. I tested them).


how to find find out capacitance using time constant?

The key concept is this line:

  ... we find the point where the voltage reaches 63.2% ...

The time constant τ is how long it takes for a capacitor to charge up to 63.2% of the supply voltage. That is governed by both the capacitance (C) and the resistance (R). τ=RC. That is one of the basic formulae you should know as an Electronic Engineer.

If you know R (which you do because you chose it at 10KΩ) and you know τ (which you do because you measured it) then you can calculate C (τ/R).

Since τ, C and R are tied together like that it is possible to change the balance of C and R and keep τ the same. For instance, a 10KΩ resistor and a 47nF capacitor would give the same τ as a 1KΩ resistor and a 470nF capacitor. Also the same τ as a 100kΩ resistor and a 4.7nF capacitor.

You can easily change the range without having to change your time measurement system by changing the resistor to give a different scale.


You did not put ESP8266 into programing mode.

the easiest way to do so is to make your own programing board, something like shown here. Go down to middle of the document to title "Writing a program to the ESP8266" where you will see a schematic of simple programing board. You will need two switches and a 10k resistor.

The voltage regulator can be omitted if you are powering it by 3.3v power. Also its a good idea to put a small capacitor (100uf) between vcc and ground to stabilize any drops in voltage which is primary cause of esp8266 rebooting it self.


Plotting a real time graph of sensor data from Arduino on Processing, MatLab or Python

I hope this is helpful to you.

First, you need to read about serial communication between matlab and arduino. You need to establish communication between those two first.

Then take note of the format of the data coming out of your Accelerometer. In my case, I'm working with IMU and my data format is as an example: #YPR = 2.34, 13.23, -2.20

Then, from Matlab, you need to write a script to be able to read this string and identify any floating-point value.

This is what I did in Matlab. YPR = Yaw, Pitch, Roll

data = fscanf(s);              %Read Data from Serial
[Y(count),P(count),R(count)] = strread(data, '#YPR = %f,%f,%f');

Then you have to set up the plot and force matlab to update the plot in real time.

%set() is used to set graphic object properties
       set(plotGraph1,'XData',time,'YData',Y,'color','r');
       set(plotGraph2,'XData',time,'YData',P,'color','g');
       set(plotGraph3,'XData',time,'YData',R,'color','b');
       drawnow;           %force matlab to updata plot instantaneously

The link below is a good place for you to get going. But you need to make some modifications to it though.

https://billwaa.wordpress.com/2013/07/10/matlab-real-time-serial-data-logger/


How can I seriously calibrate ADC voltage readings with Arduino Nano?

Rather than mapping to a range of 0 to 4.4 V, map to the range 0 to 1.1 V and use analogReference(INTERNAL) to select the internal band-gap 1.1 V reference source.  This reference voltage might vary a small amount as Vcc varies, but the variation is likely to be just a few millivolts.

To get your input voltage into the range  0 to 1.1 V, use a voltage divider and a voltage subtractor.  The voltage divider ratio should map the 8-volt range of 22 to 30 V to a 1.1 V range, ie, should have a ratio of 8:1.1, and should map 30 V to 4.125 V and 22 V to 3.025 V.

If you use a Unity Gain Differential Amplifier as described at electronics-tutorials.ws, the divider can use large resistors, ie, need not provide the under-10 KΩ resistance needed for ADC input; instead, the UGDA's low output impedance will meet that requirement when used as ADC input.  For example, you could have 1 MΩ in series with 160 KΩ for the main divider.

Feed that divided voltage into V1 in the diagram below.  Use a pot or another voltage divider to create a 3.025 V reference to feed into V2, perhaps based on the board's 3.3 V regulator output.

Note, use R1 = R2 = R3 = R4, with all of them some value like 10 KΩ or 20 KΩ.


avrdude: ser_open(): can't open device "\\.\COM3"?

I have experienced a similar issue after plugging in another Arduino device. I didn't set up my environment for a long time and thus forgot he iterates the COM-Index. Maybe this is too easy, but you didn't provide much information.

This solved my problem:
Open Arduino application > Tools > Port > Change to the target Port

If you are unsure which port to choose from: (on Windows)
Open Device Manager > Connections (COM & LPT) > Usb Serial Port (COM[x])
where "[x]" is the index you are looking for.


ESP8266 Stops Working if I don't provide Wifi during specifc step

If by "stops working" you mean it doesn't do whatever follows the client->POST method invocation, then your interpretation is correct and you could have found my very same information if you had read the open issues on the library before submitting your own.

If I were the author of the library I would be upset by such behavior.


Maybe your vibrating motor is actually shaking something loose. A dodgy batter clip or something.
Maybe your vibrating motor is drawing too much current and power-cycling the board.
Maybe your vibrating motor is doing weird, bad things like generating back-EMF spikes that it's sending back into the arduino.

It's probably number 3. Generally speaking, you never power motors off an output pin. Run the output into a mosfet or something with a flyback diode across it. Google "circuit to power motor from digital out".


You will probably get only 1 step each button press because your runSpeed() is within the if (button.rose() == true && buttonState == LOW)-statement.

The runSpeed() needs to be called every loop to check if the motor needs to step.

A simple way to change this is to set a boolean to true or false if you check your button and add something like this pseudocode:

if(motorRun == true) stepper.runSpeed();


How to set a not plugged in pin to ground or Low

Seems like you already found the solution. Without a pull-down of pull-up resistor, the voltage at pin 7 will float to some random voltage, when the switch is open.

Either add an (external) pull-down resistor. Or flip things around and use the internal pull-up resistor inside the ATMega328p. Then connect the other side of the switch to GND. Whenever the switch is pressed, your digitalWrite gives you a LOW.

To use the internal pull-up use pinMode(7, INPUT_PULLUP);


MCU to switch single coil latching relay not working (attempting array with common gnd)

You need to use an h-bridge as if you were driving a motor. For this kind of relay you need to be able to both sink and source current, which a Darlington pair cannot do, it can only sink.

I guess you may be being thrown by the symbol of an inverting buffer used in the schematic symbol for the ULN2803 in your schematic capture package. It's incorrect, since it's not an inverting buffer, it's a Darlington pair:

simulate this circuit – Schematic created using CircuitLab

As you can see, setting the input HIGH will allow the transistor pair to conduct, but setting it to LOW will stop it conducting - so the output is either connected to ground, or is floating.


If the code used for Arduino can be embedded into a permanent , callable memory, is there a way to create an OS for Arduino that runs on call?

An AVR-based Arduino is a poor choice for writing an "OS" in the modern sense. It's just too resource constrained. It doesn't have enough RAM, it doesn't have enough flash memory, it's too slow, it doesn't have protected memory or paging, it doesn't have video display, it doesn't have a file system, and on and on.
If you look at an Apple II, something like Apple DOS or ProDos gives you an idea of the sort of thing you can do (minus the video output.)
If you want to develop something like a smart watch an ARM processor is a much better choice. It packs a lot more performance into a small package. You might pick an ARM based Arduino, but you would be fighting against the lack of an OS, the lack of preemptive multi-tasking, etc.
As an alternative, a Raspberry Pi has just about everything you need. It doesn't have as many hardware interfacing options as an Arduino, but a LOT more processing power. Likewise, UNIX is a better choice as the basis for the OS for such a device. It is a protected memory OS that is made to run on relatively modest hardware.


When you put the Serial.begin in the constructor and declare the Command object at file scope, the Serial.begin will occur before setup().  Not recommended, perhaps not allowed.

If you do that, the compiler has to figure out that the Serial instance must be constructed before the Command instance is constructed.  It can't always figure out the correct order.

In general, this is why you see many classes with a begin or init method.  This allows the construction of file-scope instances to take place in any order, before setup.  Then setup does the Command.begin(), which finally calls Serial.begin, long after Serial has been constructed.

Also, using SerialEvent is no better than doing the polling in loop().  If you're busy doing something else, SerialEvent does not get called.  If you need to handle characters in the background, in the RX interrupt, you might want to take a look at a modified version for the Serial object(s) I posted, NeoHWSerial.  You can attach a routine to be called whenever a character is received.


Communication between Genuino Zero and Arduino Uno using UART

Your Arduino Zero transmitter code transmits to the USB Serial ('Serial') only. If you want it to transmit to the serial comm on pin 0 and pin 1, you must have it write to Serial1. (Check variants.cpp file ) you will see that Serial1 is uses SERCOM0 which is on pin 0 and 1.

So, Your code should look like this (noitce "Serial" is replaced with "Serial1"):

void setup() {
  // initialize serial communication at 9600 bits per second:
  Serial1.begin(9600);
  // make the pushbutton's pin an input:
  pinMode(pushButton, INPUT);
}

// the loop routine runs over and over again forever:
void loop() {
  // read the input pin:
  int buttonState = digitalRead(pushButton);
  // print out the state of the button:
  Serial1.println("a");
  delay(1000);
  // delay in between reads for stability
}


How to use voltage divider between ESP8266 (3.3v) and IR proximity sensor (5V)?

My experience with esp8266 tells me that if you power esp8266 with a 3.3V supply and you provide 5V/0V signal to its pins (either Tx/Rx or pin0,1) nothing's gonna happen. It will work fine.

Based on this experience, i would like to suggest you to

power your esp8266 with 3.3V pin of your TTL converter
power your IR sensor using 5V output pin of your TTL converter
connect signal pin of IR sensor to your esp8266 digital pin. (just
in case esp8266 heats up, disconnect circuit and try using voltage
divided only for this particular connection.

If using those external power supplies don't forget to common GND (or -ive terminal) of those power supplies.


I have a problem with my nano arduino and the nrf24l01 as receiver

radio.read() does not return a value.  You can't assign "no value" to a boolean.

If radio.available() is true then radio.read() will succeed. There is no need to test if it worked or not.


This page has the answer to your questions. For reference:

  Setting up SPI/I2C Connection with GMS096A OLED Module

  Being a new entry to the market, only limited resources are available
  on this small piece of miracle (GMS096A). I2C/SPI configuration always
  demands helpful resources as in any case. For the SPI setup, the
  module comes in 4 wire SPI configuration by default and to make it
  work with the arduinos you can use these libraries from Adafruit.

  For the I2C setup it demands a little bit of work on the module.
  Actually it was one of our customers who shared these simple
  configuration steps with us, start with resoldering the resistor from
  position R3 to R1 and then short the R8 resistor with some solder tin
  (0 Ohm resistor). The R6 and R7 pullup resistors are already soldered,
  nothing to do there. Once done, the module is ready for I2C
  communication! The CS Pin is not necessarily needed, so just connect
  it to GND. The DC Pin selects the address. For standard address wire
  it to GND. The RES-pin needs a low pulse at startup and high voltage
  during operation (as in SPI mode), a 100nF capacitor to GND and a 10k
  res to VCC would be ideal!

Your module might differ sightly. But you should be able to figure it out from there. The pulse on the RES-pin needed at startup took me a while to figure out!


How many stepper motors can a motor shield control?

There are motor shields that allow for running two stepper motors, like this one http://www.aliexpress.com/item/L293D-Motor-Drive-Shield-dual-for-arduino-Duemilanove-Motor-drive-expansion-board/32341780904.html?spm=2114.01010208.3.1.PA9IVu&ws_ab_test=searchweb201556_9,searchweb201602_2_10017_10005_10006_10034_10021_507_10022_508_10020_10018_10019,searchweb201603_9&btsid=9d220772-7d0a-437d-8534-651a85644de4

Or there are boards that are smaller than a shield that you could use, like these:  http://www.aliexpress.com/item/28YBJ-48-DC-5V-Five-line-4-phases-Stepping-motor-Deceleration-stepper-motor-Fuses-length-25CM/818857514.html?spm=2114.01010208.3.1.LZ80QW&ws_ab_test=searchweb201556_9,searchweb201602_2_10017_10005_10006_10034_10021_507_10022_508_10020_10018_10019,searchweb201603_9&btsid=201933bf-6385-4a45-a3c2-01236c01cd7a

But you will need to look at the specs to make sure they fit your needs, the best way to do that it to look at the main chip that is driving the motor and look at what that can do.

Hope that helps.


There are slight differences between registers, register names and registers bit names:

WDTCR is named WDTCSR
PCIE doesn't exist in GIMSK as there are two IO ports, so there are two pin change channels: PCIE0 and PCIE1
and PCMSK is similar to PCIE. There'll be two of them too.

Basically you have to look into both datasheets and compare what you are using and check if it's correct.


WebSocketsServer.h: No such file or directory

after you included the zip file to library you must rename directory like this 'WebSocketsServer'. And then you copy all file in 'src' directory and then paste them to its parent directory (WebSocketsServer)