'MeDCMotor' does not name a type error inside mBlock

I looked at some entries in a google search for error: 'MeDCMotor' does not name a type, such as 1, 2, 3 and 4.  The first three of those latter four links directly address the question you ask, and none of them answer it clearly, except to suggest re-downloading or re-installing the makeblock library.  While the fourth link addresses a “does not name a type” error for another library, rather than for makeblock, it has a relatively clear explanation of the problem for that other library:

  So, as supplied, the ArduinoByteBuffer.zip file had a complex set of sub-directories, and the two files ByteBuffer.ccp and ByteBuffer.h were located one level down in: \ArduinoByteBuffers\ByteBuffer\

  When I 'installed' the library, it went into the directory:

    C:\Documents and Settings\Al\My Documents\Arduino\libraries\ArduinoByteBuffers\ByteBuffer\ByteBuffer.ccp
       C:\Documents and Settings\Al\My Documents\Arduino\libraries\ArduinoByteBuffers\ByteBuffer\ByteBuffer.h

  To solve the problem I moved them up a level to:

    C:\Documents and Settings\Al\My Documents\Arduino\libraries\ArduinoByteBuffers\ByteBuffer.ccp
       C:\Documents and Settings\Al\My Documents\Arduino\libraries\ArduinoByteBuffers\ByteBuffer.h

  That seemed to be the key - moving the two files (*.ccp and *.h) out of the subdirectory.

Instead of following ordinary C or C++ library-finding rules, the Arduino IDE copies sets of files into a temporary directory according to its own rules when compiling a sketch.  You'll need to move your makeblock library files around to match up with Arduino IDE conventions.


Just a small mistake! Not much big of a deal :D

In the move function

void move(int from, int to)
{
  // initiate the move to the new angle
  servoMain.write(to);
  // wait for the movement to actually happen over the actual angle to move through
  delay(1000 * speed * int(from-to));
}

suppose the values passed are 20, 35 then the last line would be 1000*speed*(-15) Which is negative therefore the arduino delay function converts the - signed bit to a very large unsigned number.

All you have to do is to take the magnitude of from - to ie |from - to | by calling the abs() function.

your move function would look like this:

void move(int from, int to)
{
  // initiate the move to the new angle
  servoMain.write(to);
  // wait for the movement to actually happen over the actual angle to move through
  delay(1000 * speed * abs(int(from-to)));
}

Just alter your move function or copy mine and you'll have no problem at all!


Most Arduino projects involve sensing the physical world or controlling the physical world (hopefully with some feed back).  When sensing the physical world, it is best to add extra code to protect the project from locking up.  And then, even more code concerned with what to do when the unlikely happens.  Unfortunately, many projects leave out this extra code.  Reasons vary:

The project is a prototype and the effort is thought necessary.
There is no time in the schedule to create this "extra code".
The unexpected event is thought to be an impossible situation.
There is no room left to add code that is not expected to run.

As an example:

A bicycle is outfitted with an Arduio base digital speedometer.  Speed is calculated based on the period of a wheel mounted magnet passing a frame mounted Hall Effect switch.  It works as long as the bicycle is moving at a reasonable speed.  However, the program does not take into account what happens if the bicycle is not moving.  If the magnet does not pass the Hall Effect switch.  The program's period counter continues to count up.  Eventually the watch dog timer reset the program.  Over and over again.

Approaches to avoid lockup or to avoid using the watch dog timer:

Place all "non-blocking" polling in an infinite loop which also check the elapsed time.  Consider the amount of time allowed to make a successful reading.  If that time expires consider a good course for the program to follow.  For instance a warning to the user or a default value when the measured value is unavailable.
Use interrupts.  That is, use the above method, but relay on external signal changes to generate interrupts to set values and / or flags.  This is a good (however more complex) alternative if the external signal occurs too fast for "non-blocking" polling.


Open Parent Class as Child Class (SD Fat Library)

If RunFat is an instance of SdFile you can just cast it:

SdFile& RunRoot = dynamic_cast<SdFile&>(RunFat);

RunRoot and RunFat are now the exact same file in the exact same state (no need to open it or anything) but seen as an SdFile not a FatFile.


Running ESP8266 at 3.78V to work with ATMEGA328P at 16 MHz

Other possibilities include:

Running the Atmega328p at 8MHz and powering at 3.3v. Both devices would be operating within spec.
Running the whole system at 3.3v but without changing the clock on the '328. The advantage here is you'll get the full throughput from the '328, assuming you need it. The disadvantage (assuming a 16MHz Atmega328p) is that it will be running out of spec (overclocked) but they seem to be conservatively enough speced that most chips do fine. I have built two boards this way for the same reason: to put both a 328p and an ESP8226-01 on one board. I ran some rather rudimentary tests on the Atmega chips I put on those boards to find out if they would work at that voltage. I didn't see any issues and I haven't discovered any since.

Update:

  Would it be possible to run the ATmega at 8 MHz using a 16 MHz
  external oscillator by simply uploading a new sketch?

It may be possible to use its internal resonator and ignore the connected crystal; I haven't tried this. Could you clip off the external crystal if you needed to?

This article talks about setting the fuses that control the clock frequency. One thing to keep in mind is you'll need to replace the bootloader with one appropriate for the new clock frequency. You may find an 8Mz bootloader ready to upload, or recompile it yourself from source. Optiboot is a good choice: open source, has a small footprint, and you can set its upload baud-rate. You can upload a new bootloader using another Arduino as an ISP programmer - there are lots of articles about doing this and the code for the Arduino-as-programmer is one of the Arduino IDE example-programs.


What is wrong with my code? RGB potentiometer

Equality comparison in C and C++ is expressed by == operator. ==, not =. This

if (wavecolor = 0) {

actually assigns zero to your wavecolor variable, thus destroying the value you just read.
The common sense says that you actually need and in your conditions, not or

if (wavecolor > 0 and wavecolor < 333) {

The or conditions that you curently use are simply always true, which makes them nonsensical.
This is valid syntax

wavecolor > 0 or wavecolor < 333
wavecolor > 0 and wavecolor < 333

but you might want to try using more "canonical" forms

wavecolor > 0 || wavecolor < 333
wavecolor > 0 && wavecolor < 333

or and and are "alternative" forms of || and && operators, introduced a long time ago for reasons that are all but obsolete today.
Assuming that you meant and instead of or, in your conditions you managed to "exclude" such values as 333, 667 and 1022 - they wouldn't match any of and conditions. Changing some strict comparisons to non-strict ones might be in order.
As a side note, in a single-file program all file-scope variables should be either const or static. In your case

const int redpin = 6;
const int greenpin = 3;
const int bluepin = 5;
const int potPin = 0;


How to detect the absence of an RFID tag?

I don't think it is particularly practical, unless you make your own RFID scanner. The off-the-shelf ones generally only respond once when a particular card is in range, so you can't even detect if the card is left next the reader, or not.

Also, as the range is usually quite limited (a few cm) I don't see how it could tell the difference between you being out of the house, or taking a bath.

What might work better would be to have an active transmitter (eg. a nrf24l01) in your pocket, which every minute or so sent a "I'm home!" message to a central place. The absence of such a message after 10 minutes could indicate you are out.

The other approach would be to "check out" with your RFID scanner. I did an RFID event management system a little while back. You use a special "admin" card to indicate that a person was leaving an event for a while (a pass-out). You could do that, or have a button by the door, which you press. The "I am leaving" button.


The problem is a combination of several causes.

Assignments are not atomic

An atomic operation is something that is completely done or not. The opposite is some operation that can be disrupted while executing, leaving thing in a inconsistent state.

This is how the count++ works at machine level in Arduino:

void callback()
{
    count++;
  fa:   80 91 0a 02     lds r24, 0x020A
  fe:   90 91 0b 02     lds r25, 0x020B
 102:   a0 91 0c 02     lds r26, 0x020C
 106:   b0 91 0d 02     lds r27, 0x020D
 10a:   01 96           adiw    r24, 0x01   ; 1
 10c:   a1 1d           adc r26, r1
 10e:   b1 1d           adc r27, r1
 110:   80 93 0a 02     sts 0x020A, r24
 114:   90 93 0b 02     sts 0x020B, r25
 118:   a0 93 0c 02     sts 0x020C, r26
 11c:   b0 93 0d 02     sts 0x020D, r27

The first four instruction loads the four count bytes into four separate register, the laboriously increment it by one and then store it back in RAM.

Now, toggle is a variable of interest and you want to use it inside loop, like this:

void loop()
{
    uint32_t x = toggle;
    ...
}

And at machine level you get

    uint32_t x = toggle;
 414:   60 91 04 01     lds r22, 0x0104
 418:   70 91 05 01     lds r23, 0x0105
 41c:   80 91 06 01     lds r24, 0x0106
 420:   90 91 07 01     lds r25, 0x0107

Here we are simply copying the toggle variable into our x variable. As you can see, the copy takes four machine instructions to get completed.

Now, what happens if an interrupt comes while you are copying (or using) toggle?

An interrupt suspend the assignment, go to the ISR (callback in this case and change toggle value. Upon return, copying continues, mixing bytes from the old and new value.

You must use volatile

Any global variable used inside an ISR must be declared volatile. This is an hint to the compiler that the variable could change unexpectedly. Therefore, the volatile variable must be always read afresh, discarding any cached value.

Critical section

The rule for using values changed by ISR is simple:

Always copy the ISR's global variables to your own temporary variable.
Before coping, disable interrupts and reenable it after the copy is done. This prevent the ISR from executing while your are copy the values.

Demo

This little demo shows you all of this in action.

The sketch collect all the values from toggle (not disabling interrupts) during one minute and after that print a table showing what it got.

/*
 * This sketch show how to deal with variables shared between ISR and main thread.
 *
 * By Look Alterno 2018
 */

#include "TimerOne.h"

volatile uint32_t count = 0;
const uint32_t PATTERN_A = 0xFF00FF00;
const uint32_t PATTERN_B = 0x00FF00FF;

volatile uint32_t toggle = PATTERN_A;

#define MAX_CASES 16
struct {
    unsigned long value;
    int count;
} found[MAX_CASES];
int freeFound = 0;

#define PRINT_INTERVAL 60000L

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

    while(!Serial);

    Serial.println("");
    Serial.println("Test assignment under interrupts");
    Serial.println("");

    Serial.print("Value A=");
    Serial.println(PATTERN_A, HEX);
    Serial.print("Value B=");
    Serial.println(PATTERN_B, HEX);

    Timer1.initialize(500);
    Timer1.pwm(9, 512);
    Timer1.attachInterrupt(callback);

    pinMode(A0, INPUT);
    randomSeed(analogRead(A0));
}

void callback()
{
    count++;
    toggle = (count % 2) ? PATTERN_A : PATTERN_B;
}

void loop()
{
  static unsigned long prev = 0;

  //  A random delay to simulate some real, variable work being done.
    delayMicroseconds(random(250));

  // This is the critical section.
//  noInterrupts();
    uint32_t x = toggle;
//  interrupts();

  // Now, let's see what value we got.
    if(x != PATTERN_A && x != PATTERN_B) {
        insert(x);
    }

  // Print values found
  unsigned long now = millis();
  if (now - prev > PRINT_INTERVAL) {
    printFound();
    prev = now;
  }
}

/*
 * Add a value to a table for counting.
 */
void insert(unsigned long x)
{
    int index = 0;

    while(index < freeFound && found[index].value != x) {
        index++;
    }

    if(index < MAX_CASES) {
        if(index == freeFound) {
            found[index].value = x;
            found[index].count = 1;
            freeFound++;
      Serial.print(freeFound);
      Serial.print(". Add=");
      Serial.println(x, HEX);
        } else {
            found[index].count++;
        }
    } else {
        Serial.print("*** Table overflow. value=");
        Serial.print(x, HEX);
        Serial.println(" ***");
    }
}

/*
 * Print the table of found values so far.
 */
void printFound() {
  Serial.println("");
  Serial.println("Values found");
  Serial.println("");
  Serial.println("Value - Count");
  for (int i=0; i < freeFound; i++) {
    Serial.print(found[i].value, HEX); Serial.print(" - "); Serial.println(found[i].count);
  }
}

If you uncomment noInterrupts and interrupts, every thing works just fine.

Other CPU

More powerful CPUs have atomic assignments, but following this practices makes your code portable across platforms, no matter what. Think of defensive programming


Time for a crash course in electronics and power:

The 5V pin only ever provides 5V. That's why it's the "5V" pin. (assuming, of course, that you give the board more than 5V).

In simple linear electronics you have three values:

The voltage
The current
The load

Generally two of the three are either "fixed" or "known" and the third changes depending on the other two. For simple resistive circuits (where the load is a simple resistor) this relationship is Ohm's Law.

If the voltage is fixed, and
If the load changes, then
The current will also change to keep the relationship stable.

A "power supply" (any device which provides power to some other device) generally has two parameters: Voltage and Current.  One of those is always fixed. The other is always variable, and quoted as a maximum that the supply can give.

For the Arduino's 5V pin the parameters are:

Voltage: 5V
Current: 800mA Maximum

That means that the 5V pin has a fixed voltage of 5V, but the current is free to change depending on the load up to a maximum of 800mA (or a lower limit if you are providing the input power from a source with a lower current. There is also heat to consider with the Arduino - see below).

The two values, voltage and current, combine together to give the "power" of the power supply, through simple multiplication. So the Arduino's 5V pin is 5V × 0.8A = 4 watts maximum.

When you provide power to the Arduino through the barrel jack it first goes through a linear voltage regulator.  This is the device which takes the incoming voltage and reduces it to 5V. Since energy can neither be created nor destroyed it does that reduction in energy by converting some of it to heat.

Say you connect something up that needs 100mA and you plug in a 9V power supply to the board. Let's also assume that the Arduino itself needs 50mA (I like nice round numbers).

That's 150mA in total for the "load".
The incoming voltage is 9V
The outgoing voltage is 5V

The power of the input is thus 9V × 0.15A = 1.35W
The power of the output is then 5V × 0.15A = 0.75W

The power difference is 0.6W

That 0.6W is converted from electrical energy to heat energy by the voltage regulator and "thrown away".

So the "heavier" your load (the more current you demand from the 5V pin) the greater the heat that is generated by the voltage regulator.

When the regulator gets too hot one of two things happen:

A good quality regulator will shut down and you will lose power to the board
A cheap Chinese regulator will likely "fail short" and feed your 9V direct into the Arduino causing components to release their Magic Smoke™ and stop working


Error: `nullptr` was not declared in this scope. Arduino IDE

I installed Arduino IDE in two different ways (only god knows why). The first one was via using of manager apt-get and other was manually via downloading, unzipping and installation through the install.sh file.
It seems that on Ubuntu 14.04 the

sudo apt-get install arduino

command provides an installation of an old version of Arduino IDE.
So eventually I was launching Arduino IDE by arduino command in my terminal (actually I was using d-menu in i3). No surprise it ran the old one installed by apt-get. I just removed that version by

sudo apt-get remove arduino

And now I am using executable arduino inside unzipped folder. Actually, I am not using Arduino IDE explicitly at all. I am using a Makefile from here.


Arduino Due uploading error using Eclipse plugin "avrdude: stk500_recv(): programmer is not responding"

avrdude: stk500_recv(): programmer is not responding
  avrdude: stk500_getsync() attempt 1 of 10: not in sync: resp=0x03

There's your clue.
1) programmer is not responding - This usually means the device isn't connected, or powered, or reachable by the IDE, make sure you have eclipse configured correctly for your device, and it's location.

2) not in sync - This is a redundant, or overlapping error, of course it's not going to sync if it can't connect.


How to connect an L293D and an MPU6050 to run together?

There a some mistakes with the wiring of the supply voltage (Vss) according to the datasheet (http://www.ti.com/lit/ds/symlink/l293.pdf) of the L293D a those on pin 8 (Vss2) and 16 (Vss1). I think those are not connected because each Vss is for one motor of the driver. So you have to connect 9V (or 12V) to both pins.
There is also something wrong with the capacitor (polarity). And your connection of the battery to the breadboard is a bit weird because + of the battery is usally the red not the black wire / marked row on the breadboard.


Detecting a 2.8ms pulse using a Arduino Uno

First, better to see whole source and schematics.

"Why is the pin 2 not detecting"

Check:
1. Hall sensor connected to Pin 2

pulses variable declared as volatile.
Check if internal pull up resistor setup consistent with hall sensor connection.
Check that Hall sensor's lowest signal voltage is below 0.3 VCC (you said 5V, so it should drop below 1.5V), BTW 580 - the lowest analog value you showed means 2.83V
Check you are not using nointerrupt();

"Is it possible to gauge anything from Analog read function? Am "

Yes.
Analog read takes about 0.1 ms in default setup, so should make at least 1000 reads per second to catch peak.

So,
Easiest way is to choose some value like 600, when analog read is above mark it as Rising when it drops below mark is Falling.
More complicated ways will include some training and hysteresis to improve detection.

Also I suggest to use voltage limiter instead of voltage divider. This gives better detection.


I want to control a single DC motor with an Arduino. Why would I use an Arduino motor shield as opposed to an H-circuit and a MOSFET?

The major benefit to using a shield vs building the same circuit yourself is convenience. Assuming that your circuit is identical to the circuit on the shield then they should both work in an identical manner (barring any minor variations due to the quality of solder joints or circuit paths). The nice thing about the shield is it is almost plug and play. It has the same footprint as the Arduino and you don't have to design and assemble the circuit on a perf board. Generally, you will end up with fewer wire leads running around making for a cleaner assembly and easier prototyping.


Will this buck converter power my arduino?

Sure the standard 5V barrel adapter prongs could be shrink wrapped to the raw AC wires but that's not very clean.

Also very deadly.  DO NOT DO THIS!!!!  The Arduino will explode (literally. I am NOT joking here!!!) and potentially electrocute you.

Those modules you show are not "buck" regulators. They are SMPS modules - an entirely different thing.

Yes, one of those would be suitable for powering an Arduino from a mains supply, but given your supposition above I rather suspect your skills and knowledge would make wiring it up a dangerous prospect.

Better would be to use a proper off-the-shelf power plug and have someone qualified install a suitable socket inside the enclosure.


Arduino Nano not responding with yellow led blinking fast

I successfully restored both boards using the reset button:

Power off the board (I disconnected the USB cable from computer)
Press and hold the reset button
Connect USB cable (keep holding the reset button)
Click "Upload Sketch"
Wait a second or two until Arduino software says "Uploading..." in the status bar
Release the reset button

Use these steps to upload any small sketch, Blink example is a good choice.


Measuring power consumption on Arduino off of DC supply

What I am wondering is whether there exists an elegant solution for this, with (highly) accurate results (I would most likely quote the power values, so accuracy is a must for me)? Something I can dynamically measure on the Uno itself?

The Uno cannot measure its own power consumption. Indeed, a Uno which has a voltage regulator, power LED, and USB interface chip is not your ideal solution for low-power applications.

See Power saving techniques for microprocessors


SD-Card-Module doesnt work with external power supply

Okay, thank you all for your efforts.

Finally, after changing the PSU and connecting the Arduino to another usb-port without operating system, I found the solution.

The problem was the SD-Card itself:
I swapped the SD-card with a newer (maybe more expensive(?)) one and it just works now. No matter if you connect the Arduino with the PSU or over an usb connection.
My assumption is, that there could be a different clock speed of the sd-card module on different voltages, which causes the problem. The old sd-card can't handle the fast speed and runs into an error (or just rejects it) on a write attempt...

Anyway, thank you again for your efforts!


Can you pass the entries of a strut array to a int array? if so how?

Its not very clear what you are asking, but I think you are saying can you do this

uint8_t anArray[MAX_NOTE];
anArray = Noteseq.pitch;

In general the answer is no.  However in this specific case off the top of my head I think you probably can (maybe).  You have a struct which only contains bytes.  The compiler will probably pack the sequentially so you will effectively have a contiguous sequence of bytes which you would be able to copy to the byte array by doing:

memcpy (anArray, Noteseq, MAX_NOTE);  // THIS IS BAD PRACTICE!

You can only do this in this case because the types are both 8bit numbers.  Its not a good idea to do this copy between an array of structs and a POD type array is just asking for trouble.

Instead use a function to do it.

int* CopyPitch (LearnNote* source, int* destination, int count)
{
    for (int i = 0; i < count; ++i)
    {
        destination[i] = source[i].pitch;
    }
}

(You should really check for null pointers and stuff, but its just an example)


Is there any working analogue to the pair std::function and std::bind in Arduino?

We have written a solution, that we published as a Platformio library: https://github.com/fopeczek/function_objects.
Please note, that each functional object does one allocation, and those are not particularly friendly in an embedded environment. I am not even sure, that the Arduino C++ does heap deallocation, so you may be leaking resources if you create and destroy the functional objects in a loop.


How can I have the user instantiate an object?

You seem like you are almost there. Allocate the objects using new and free with delete.

// Abstract parent
class Playlist {
    public:
    virtual void playNext() = 0;
    // etc.
};
// Derived classes
class Something : public Playlist
    public:
    void playNext() {
        // your code here
    }
};
class SomethingElse : public Playlist
    public:
    void playNext() {
        // your code here
    }
};
// More derived classes......

// A pointer of the current program
Playlist *play_list = nullptr;

// A factory function to create a Playlist while also freeing previous
Playlist * create_playlist(int which_program) {
    // Important - delete old
    delete play_list;
    play_list = nullptr;
    // There are only 16 types, use a switch or if
    switch (which_program) {
        case 1:
            // Create a new one and save in global ptr
            play_list = new Something;
            break;
        case 2:
            play_list = new SomethingElse;
            break;
        // More cases here.....
    }
    return play_list;
}

[edit]--------------------------

Ok. The issue is that C++ does not have a lot of reflection options. So you can't create a class only by its name (as a string). Here's another solution I came up with. It's not completely automatic as it involves registering each class in setup. But I think it's close to what you want:

class Playlist;  //Forward declaration

// Each class will have a function to create itself
typedef Playlist * (*CreateFunc)();

// The parent class. It also holds a list of all child classes
// Could probably refactor into 2 separate classes
class Playlist{
  public:
  // Need virtual dtor
  virtual ~Playlist() {
    delete last_created;
  }

  // Put all the overridable function declarations here
  virtual void playNext() = 0;

  // This has to be called for each child. (See macro below)
  static void register_class(int id, CreateFunc f) {
    all_maps[num_maps].id = id;
    all_maps[num_maps++].f = f;
  }

  // Factory method to instantiate an object
  static Playlist * create_playlist(int id) {
      // Delete old pointer
      if (nullptr != last_created) {
          delete last_created;
          last_created = nullptr;
      }
      for (int i = 0; i < num_maps; i++) {
          // Search the list for name match
          if (id == all_maps[i].id) {
              // Call the creation func
              return all_maps[i].f();
          }
      }
      return nullptr;
  }
  protected:
  // A struct to hold the class name and a pointer to the creation function
  struct Map {
    int id;
    CreateFunc f;
  };
  static Map all_maps[32];
  static int num_maps;
  static Playlist* last_created;
};
// Static declarations
Playlist::Map Playlist::all_maps[32] = {{0, nullptr}};
int Playlist::num_maps = 0;
Playlist* Playlist::last_created = nullptr;

// Example child class
class Child1 : public Playlist{
  public:
  void playNext() {Serial.println("Child1");}

  // Must have this function and it must be static
  static Playlist * create() {return new Child1;}
};
// Another example
class Child2 : public Playlist{
  public:
  void playNext() {Serial.println("Child2");}
  static Playlist * create() {return new Child2;}
};

// Helper macro to simplify registering
#define REGISTER_PLAYLIST(id, name) Playlist::register_class(id, &name::create)

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

  // This must be done for all classes
  REGISTER_PLAYLIST(0, Child1);
  REGISTER_PLAYLIST(1, Child2);

  // Example usage
  Playlist*p = Playlist::create_playlist(0);
  p->playNext();
  p = Playlist::create_playlist(1);
  p->playNext();
}

void loop() {

}

I just whipped this up. Probably room for improvement....


If you want a variable to be available within more than one function it has to be global. There is no other possible way of doing it.

If you are only using the variable in the loop() function and nowhere else you can declare it static in loop(), which has the same effect of making it global, but it is only possible to see it within loop().

You can make a pointer global, then create a new object in setup() (using new...) and assign it to the pointer, but that has the potential of making a mess of your heap and should be avoided unless absolutely necessary. Also it's pointless, because you don't gain anything over having the object statically created in the global scope.


arduino creates strange files in SD card

I've had similar issues with large (> 1Gb) SD cards, I've had various different problems with different cards, some things that helped me debugging the problem:

make sure your wires are the same length and try to use short wires
make sure your power supply is sufficient, sd card readers can draw up to 150mA
format the card in either FAT16 or FAT32 and never use "quick erase", try to use official tools (like https://www.sdcard.org/downloads/formatter_4/index.html)
make sure if you're the correct BAUD rate (9600) to talk to your card
filename support is pretty old so keep them short and don't use spaces or special characters
make sure the SD card is not in "write lock" mode, there's a small switch on the side of some SD cards that can prohibit writing (but will allow reading)


There is a function in the standard Arduino library called dtostrf(). I think of it as "Decimal to String Float". You pass in the float, how wide you want the whole number to be (if it will fit), the number of decimals of precision - and the buffer you want it to fill.

Note that! You need to provide the buffer, and you need to be careful to provide more than enough! Don't forget to add 1, too (to store the NUL character at the end):

char result[8]; // Buffer big enough for 7-character float
dtostrf(resistance, 6, 2, result); // Leave room for too large numbers!

This will give result values like "  1.23" and " -1.23" and "123456789" (without the quotes). Note the last example - it won't truncate the number if it's too large, and that 10- character result (don't forget the final NUL) just overflowed your buffer...

Incidentally, if you specify a negative width, it won't right-justify the answer, it'll left-justify it (put any spaces on the end instead of the beginning).


How to implement setSyncProvider and verify it is working with PC

Yes, you'll need something running on the PC which is monitoring the serial port, and which will provide a response in the appropriate format.

The download on this page contains a Processing sketch which will do this for you. After you've unzipped it, look in Time/Examples/Processing/SyncArduinoClock. Open the sketch in Processing, run it, and then start your Arduino.

If you're not familiar with it, Processing is a free programming language / environment based on Java. It's aimed largely at beginners and non-programmers, and is quite commonly used for communicating with Arduino projects via Serial. You can download it here:

http://www.processing.org


Software PWM implementation on ATTiny44 screws up timing functions

What you are doing wrong is:

The problem is your interrupt handling routine lasts too long. Since inside ISR() interrupt flag is automatically cleared, timer0 interrupts are being missed and delay() depends upon timer0 interrupts.

To confirm the problem is ISR, remove the for loop and just toggle one pin instead. I bet the delay will then be as it should.

Try to put sei() at the beginning of your ISR to see what is going to happen with the timming of the delay - but that is not the right way.

Instead of using delay() (based on timer0) you can count the number of timer1 interrupts but ISR routine must not last longer than the time between two interrupts and your ISR spends quite a few T-states inside the for loop. A rule of a thumb is ISR has to be very short (fast) - unless you really know what you are doing. For example, in one of my devices I am using a very long ISR routine (in fact the firmware consists of only the ISR - there is only sleep_mode(); in main) for which I know it sometimes lasts longer than the time window between interrupts and I know some of the interrupts are occasionally being missed. However, these few missed interrupts are not critical to that particular application and I am sure the interrupts are being missed rarely.

You could change OCR1A value to increase the time between interrupts but then you would have lower PWM frequency.


ATTiny85 USB Troubleshooting. Device is not recognized when programmer asks to plug in device

From your AVRDude output:

avrdude: safemode: Fuses OK (E:FF, H:DF, L:62)

It does not appear that you have programmed the AVR configuration fuses.
One for thing, E:FF, is extended fuse value 0xFF, which is missing the SELFPRGEN (self-programming) fuse that would allow Micronucleus to load your code onto the AVR, that is allow the AVR to execute instructions to program itself.  So, assuming it managed to show up on USB, you wouldn't actually be able to use it to put code on your chip.
You can see what they should be where the makefile fuse target defers to your t85_default configuration:
FUSEOPT = -U lfuse:w:0xe1:m -U hfuse:w:0xdd:m -U efuse:w:0xfe:m

The fuses that are actually preventing it from showing up on USB are more likely the clock related fuse bits in the low fuse byte.  In particular CKDIV8 (factory default) is set to divide-by-8 where it is not in the makefile.  The CKSEL bits are set to 0x2 (factory default) for the 8Mhz internal RC oscillator whereas the makefile wants them to be set to 0x1, for internal PLL (phase locked loop) that generates higher clock rates from the RC oscillator.  In short, your chip is running at 1MHz rather than 16Mhz.  The Micronucleus code may also be written such that it needs PLL for bit-banging USB, though I haven't looked into that to be certain.


multiple connection with ISP Pin at Arduino Micro

Each SPI device must have a separate device/slave select pin. The device must disconnect (high impedance state) when not selected. The SD shield will have a level shifter. It may not correctly disconnect from MISO.

Depending on what libraries you are using you might also need to check that they set the SPI hardware attributes correctly (clock, mode, etc).

For more help please post code and references to the shields and libraries.

Cheers!


Problem in Uploading a Bootloader to Atmega8A

Google is your friend!!!
Apparently this is a known regression bug not yet corrected. The possible solution is also suggested there by user rigelinorion and here is the quote:

Hello, I solved it this way...

Open for edit the file C:\Program Files\Arduino\hardware\arduino\avr\platforms.txt
this is standard section uploader/programmers tools

#==============================================================================
tools.avrdude.cmd.path={runtime.ide.path}/hardware/tools/avr/bin/avrdude
tools.avrdude.config.path={runtime.ide.path}/hardware/tools/avr/etc/avrdude.conf
tools.avrdude.cmd.path.linux={runtime.ide.path}/hardware/tools/avrdude
tools.avrdude.config.path.linux={runtime.ide.path}/hardware/tools/avrdude.conf

tools.avrdude.upload.params.verbose=-v -v -v -v
tools.avrdude.upload.params.quiet=-q -q
tools.avrdude.upload.pattern="{cmd.path}" "-C{config.path}" {upload.verbose} -p{build.mcu} -c{upload.protocol} -P{serial.port} -b{upload.speed} -D "-Uflash:w:{build.path}/{build.project_name}.hex:i"

tools.avrdude.program.params.verbose=-v -v -v -v
tools.avrdude.program.params.quiet=-q -q
tools.avrdude.program.pattern="{cmd.path}" "-C{config.path}" {program.verbose} -p{build.mcu} -c{protocol} {program.extra_params} "-Uflash:w:{build.path}/{build.project_name}.hex:i"

tools.avrdude.erase.params.verbose=-v -v -v -v
tools.avrdude.erase.params.quiet=-q -q
tools.avrdude.erase.pattern="{cmd.path}" "-C{config.path}" {erase.verbose} -p{build.mcu} -c{protocol} {program.extra_params} -e -Uefuse:w:{bootloader.extended_fuses}:m -Ulock:w:{bootloader.unlock_bits}:m -Uhfuse:w:{bootloader.high_fuses}:m -Ulfuse:w:{bootloader.low_fuses}:m

tools.avrdude.bootloader.params.verbose=-v -v -v -v
tools.avrdude.bootloader.params.quiet=-q -q
tools.avrdude.bootloader.pattern="{cmd.path}" "-C{config.path}" {bootloader.verbose} -p{build.mcu} -c{protocol} {program.extra_params} "-Uflash:w:{runtime.ide.path}/hardware/arduino/avr/bootloaders/{bootloader.file}:i" -Ulock:w:{bootloader.lock_bits}:m
#==============================================================================

create a new tool called, for example, avrdude1
simply copy section tools.avrdude and name it tools.avrdude1
the trick is that we remove switch "-Uefuse:w:{bootloader.extended_fuses}:m" from "tools.avrdude1.erase.pattern="

#=============================================================================
tools.avrdude1.cmd.path={runtime.ide.path}/hardware/tools/avr/bin/avrdude
tools.avrdude1.config.path={runtime.ide.path}/hardware/tools/avr/etc/avrdude.conf
tools.avrdude1.cmd.path.linux={runtime.ide.path}/hardware/tools/avrdude
tools.avrdude1.config.path.linux={runtime.ide.path}/hardware/tools/avrdude.conf

tools.avrdude1.upload.params.verbose=-v -v -v -v
tools.avrdude1.upload.params.quiet=-q -q
tools.avrdude1.upload.pattern="{cmd.path}" "-C{config.path}" {upload.verbose} -p{build.mcu} -c{upload.protocol} -P{serial.port} -b{upload.speed} -D "-Uflash:w:{build.path}/{build.project_name}.hex:i"

tools.avrdude1.program.params.verbose=-v -v -v -v
tools.avrdude1.program.params.quiet=-q -q
tools.avrdude1.program.pattern="{cmd.path}" "-C{config.path}" {program.verbose} -p{build.mcu} -c{protocol} {program.extra_params} "-Uflash:w:{build.path}/{build.project_name}.hex:i"

tools.avrdude1.erase.params.verbose=-v -v -v -v
tools.avrdude1.erase.params.quiet=-q -q

#this line was edited
tools.avrdude1.erase.pattern="{cmd.path}" "-C{config.path}" {erase.verbose} -p{build.mcu} -c{protocol} {program.extra_params} -e -Ulock:w:{bootloader.unlock_bits}:m -Uhfuse:w:{bootloader.high_fuses}:m -Ulfuse:w:{bootloader.low_fuses}:m

tools.avrdude1.bootloader.params.verbose=-v -v -v -v
tools.avrdude1.bootloader.params.quiet=-q -q
tools.avrdude1.bootloader.pattern="{cmd.path}" "-C{config.path}" {bootloader.verbose} -p{build.mcu} -c{protocol} {program.extra_params} "-Uflash:w:{runtime.ide.path}/hardware/arduino/avr/bootloaders/{bootloader.file}:i" -Ulock:w:{bootloader.lock_bits}:m
#==============================================================================

Here is an example of the use of the tool avrdude1 in boards.txt file

atmega8.name=ATmega8 OPTIBOOT
atmega8.upload.protocol=arduino
atmega8.upload.maximum_size=7168
atmega8.upload.speed=115200
atmega8.upload.tool=avrdude1
atmega8.bootloader.low_fuses=0xbf
atmega8.bootloader.high_fuses=0xCC
atmega8.bootloader.path=atmega8
atmega8.bootloader.file=optiboot/optiboot_atmega8.hex
atmega8.bootloader.unlock_bits=0x3F
atmega8.bootloader.lock_bits=0x0F
atmega8.bootloader.tool=avrdude1
atmega8.build.mcu=atmega8
atmega8.build.f_cpu=16000000L
atmega8.build.core=arduino
atmega8.build.variant=standard


No

As you can see in the schematic, the USBVCC is only connected (via a MOSFET) to the 5V line, when the voltage on VIN (barrel jack) is LOW.

If you connect 9V to the power jack, the mosfet will turn of, and disconnect the USB power from the 5V on the UNO.


Bluetooth data: how to handle these data?

I cannot understand the relation between the air and the lenght: in the second example the response is 13 char but the lenght is 11. Why?

The hex numbers may be one or two digits long.  The way the values are being printed does not enable you to discern between 1 2 3, 12 3 and 1 23. Try this:

for(int i = 0; i < 255; i++)
{
  Serial.print(info.eir[i], HEX);
  Serial.print(" ");
}

(Someone already told you this.)

  How can I parse the eir to obtain all the data? For example the name of the device and the manufacturer data?

This works for the only example of the data you have given.  If I have guessed correctly how further data will follow, it'll work for them too.  (If I haven't, it won't.)  I have assumed that the name always starts in the same place, ends with a space, three bytes of stuff we don't care about, and that the data is groups of 8 bytes.  It's very likely that some of the other bytes give details of the data to follow, but with only one example and no spec, it's basically impossible to tell.

// Let's assume the sensor name always starts at element 5...
char *sensorName = &(info.eir[5]);
// ...and ends on a 0x20 (space) - which is probably a risky assumption
char *end = strchr(sensorName, ' ');
if (end)
{
    *end = '\0';
    // Sensor name is now in sensorName

    // Let's assume the data starts exactly 4 bytes after the end of the name
    uint8_t *dataItemStart = (uint8_t*)(end + 3);
    uint8_t *dataEnd = info.eir + info.eir_len - 1;
    while(dataItemStart < dataEnd)
    {
        // We have a data item here, as 'dataItemStart'.
        // You can get bytes within it using, for example
        //   dataItemStart[5]
        // to get the 6th item (the 00 or 02 in your examples)

        // Each data item is 8 bytes long, so the next one starts 8 bytes later
        dataItemStart += 8;
    }
}


ESP8266: system_adc_read_fast() always give 1024 as output

I created a test circuit using an AC transformer to produce a 50 cycles / second sine wave signal and tried a number of variations on the system_adc_read_fast sample program in the Espressif SDK manual "2C-ESP8266_Non_OS_SDK_API_Reference__EN".

The ESP8266 ADC returned realistic values for adc_clk_div = 8 and 16, but, as you found, the values returned were always 1024 when I tried 32.

I found that the ADC unit was capable of performing ADC conversions in about 6-10 microseconds...

In a test program to collect data for a 40 millisecond period (ie two complete sine waves - I used a diode to chop off the negative halves) I called the system_adc_read_fast function 40 times collecting 116 samples in each call (using "number of samples" = 116).

I collected all the readings in a two-dimensional array before printing any values because the Serial.print function causes long delays between calls to the ADC converter. The "gaps" in the chart represent the changes in the sine wave signal between successive calls to the ADC read function.


Common C-string to byte array functions as shown in https://stackoverflow.com/questions/3408706/hexadecimal-string-to-byte-array-in-c work perfectly fine.

Source hex string: 6D616320747820636E662031352033300D0A
Conversion OK buff 0x289 len 18
output byte array:
  00 6d 61 63 20 74 78 20 63 6e 66 20 31 35 20 33 30  mac tx cnf 15 30
  10 0d 0a                                            ..

#include <Arduino.h>

void hexDump (const char *desc, const void *addr, const int len);

bool convert_hexstr_to_bytearray(const char* source, uint8_t* &output,
        size_t& output_len) {
    size_t len = strlen(source);
    //cannot convert non-even string length
    if ((len % 2) != 0) {
        return false;
    }
    //dynamically allocate output buffer
    output_len = len / 2;
    output = (uint8_t*) malloc(output_len);
    const char* curPos = source;
    for (size_t count = 0; count < len; count++) {
        sscanf(curPos, "%2hhx", output + count);
        curPos += 2;
    }
    return true;
}

String Finalval="6D616320747820636E662031352033300D0A";

void setup() {
    Serial.begin(115200);
    Serial.print("Source hex string: ");
    Serial.println(Finalval);
    Serial.flush();

    uint8_t* buffer = nullptr;
    size_t buffer_len = 0;
    if(convert_hexstr_to_bytearray(Finalval.c_str(), buffer, buffer_len)) {
        Serial.println("Conversion OK buff 0x" + String((long)buffer,HEX) + " len " + String(buffer_len));
        hexDump("output byte array", buffer, buffer_len);
    } else {
        Serial.println("Conversion failed\n");
    }

    //free memory
    if(buffer)
        free(buffer);
}

void loop() {
}

void PrintHex8(const uint8_t *data, uint8_t length) // prints 8-bit data in hex
{
     char tmp[length*2+1];
     byte first;
     byte second;
     for (int i=0; i<length; i++) {
           first = (data[i] >> 4) & 0x0f;
           second = data[i] & 0x0f;
           // base for converting single digit numbers to ASCII is 48
           // base for 10-16 to become lower-case characters a-f is 87
           // note: difference is 39
           tmp[i*2] = first+48;
           tmp[i*2+1] = second+48;
           if (first > 9) tmp[i*2] += 39;
           if (second > 9) tmp[i*2+1] += 39;
     }
     tmp[length*2] = 0;
     Serial.print(tmp);
}

void hexDump (const char *desc, const void *addr, const int len) {
    int i;
    unsigned char buff[17];
    const unsigned char *pc = (const unsigned char*)addr;

    // Output description if given.
    if (desc != NULL) {
        Serial.print (desc);
        Serial.println(":");
    }

    if (len == 0) {
        Serial.print("  ZERO LENGTH\n");
        return;
    }
    if (len < 0) {
        Serial.println("  NEGATIVE LENGTH: " + String(len));
        return;
    }

    // Process every byte in the data.
    for (i = 0; i < len; i++) {
        // Multiple of 16 means new line (with line offset).

        if ((i % 16) == 0) {
            // Just don't print ASCII for the zeroth line.
            if (i != 0) {
                Serial.print ("  ");
                Serial.println((char*)buff);
            }

            // Output the offset.
            Serial.print ("  ");
            PrintHex8((uint8_t*)&i, 1);
        }

        // Now the hex code for the specific character.
        Serial.print(" ");
        PrintHex8(pc + i,1);

        // And store a printable ASCII character for later.
        if ((pc[i] < 0x20) || (pc[i] > 0x7e))
            buff[i % 16] = '.';
        else
            buff[i % 16] = pc[i];
        buff[(i % 16) + 1] = '\0';
    }

    // Pad out last line if not exactly 16 characters.
    while ((i % 16) != 0) {
        Serial.print ("   ");
        i++;
    }

    // And print the final ASCII bit.
    Serial.print ("  ");
    Serial.println((char*)buff);
}


I want to move the mouse pointer with an Arduino and ultrasonic sensor

That's because the Uno can't be a mouse.  For that you need the Leonardo or something else with a similar "U" style microcontroller.

If you are adventurous, and you have a genuine Arduino, you can reprogram the USB controller chip with new firmware so it thinks it's a mouse, but programming the main MCU is then a real chore.


Instructions to installing and binding the Arduino CLI can be found at

https://github.com/arduino/arduino-cli#getting-started

Once you install the binary, copy the executable into a directory which is in your PATH environment variable (such as /usr/local/bin/).

Note: You may have to rename the binary to arduino-cli.


How do I read data from Parallel port DB25 over my Arduino?

I think I can see the problem - although I have no way to test it.

According to Wikipedia:

  When the data was ready, the host pulled the STROBE pin low, to 0 V. The printer responded by pulling the BUSY line high, printing the character, and then returning BUSY to low again.

That's not what you're doing - you are repeatedly reading while the strobe is HIGH.

Here's my attempt at your loop() which I hope will at least get you started:

void loop()
{
    // Wait for strobe to go LOW, indicating a character is ready
    while (digitalRead(nStrobe) == LOW) {
        delay(1)
    };

    // Strobe is now LOW - a character is ready.
    // Pull BUSY to high
    // (NB: I don't know what you're doing with nAct and led)
    digitalWrite(Busy, HIGH);
    digitalWrite(led, LOW);
    digitalWrite(nAck,LOW);

    // Print the character
    ProcessChar();

    // Return BUSY to low again
    // (NB: I don't know what you're doing with nAct and led)
    digitalWrite(Busy, LOW);
    digitalWrite(led, HIGH);
    digitalWrite(nAck,HIGH);

    // Wait for the strobe to go HIGH again
    while (digitalRead(nStrobe) == LOW) {
        delay(1)
    };
}

You should also probably consider setting the initial values of your outputs (BUSY and nAck) rather than relying on them defaulting to some particular state.  I don't know what (n)Ack is for in this case -- Wikipedia doesn't mention it.


You cannot assume anything about serial port names. It's a choice of the operating system, and even if you find the algorithm, there's no guarantee it won't change in the future.

As a reference implementation, the Arduino IDE 1.5.x uses VID (Vendor ID) and PID (Product ID) to identify a board.

Because accessing such information depends on the underlying operating system, the IDE uses three strategies: on windows, it runs a program called ListComPorts.exe, on macosx it uses CLI tool /usr/sbin/system_profiler, on linux CLI tool udevadm


Transfer 10-bit via Arduino-to-Arduino SPI protocol

A byte is only 8 bits, so your code:

  byte x=0000001101;
  byte y=0011111111;

won't do what you think it does.

A 10 bit value will be stored as an int (which is 16 bits) or 2 bytes.

Assuming it is an int then this will convert it to two bytes.

 const int adcData = 0x03FF;  // From ADC
 byte dataToSend[2] = {0, 0}; // Initialise it to zeros
 dataToSend[0] = (adcData & 0xFF00) >> 8;  // didn't really need the bit mask just to make it clearer.
 dataToSend[1] = (adcData & 0x00FF);
 // Now send dataToSend via the SPI bus.

To reassemble the data on the otherside:

 byte dataReadFromSPI[2];  // Filled with the data read from the SPI
 int adcData = 0;
 adcData = (dataReadFromSPI[0] << 8) | (dataReadFromSPI[1]);


Light multiple RGB Led Strips from same 3 RGB PWM outputs

You have few options:

do as you represented in the drawing: it should work, as I expect the transistors to not load too much the input.
add a logic buffer inbetween the arduino and the driver stage
use other pins from the arduino for driving the additional strips and bitbang the PWM, instead of using the HW blocks

Whether the solution you propose (1) will work or not depends entirely on the max current that each PWM pin can output vs the total load from the 3 transistors it will have to drive.


From your description, everything should be wired correctly. It should not have failed.

Unfortunately, testing this sort of thing with a 5 amp-hour lead-acid battery is not a great way to get started, since a battery that large can source a lot of current, and doing anything wrong will likely produce immediate and spectacular failure.

Really, the only think I can think of is that you have the polarity of the output lugs/pins on the battery backwards. Buy a $5 multimeter, and check them.


Running many devices on 5V pin. How to provide external power

There is a maximum current you can use from the 5V pin(s), so it is good to split the current going into the Arduino.

You can use a breakout board for a USB, connect the USB to the breakout board, connect it both to the Arduino, and in parallel to the sensors; meaning the current used for the sensors is not going through the Arduino. You might need 2 break out boards, one for the input USB, one for the output USB.

Note there is a maximum current for USB too.


less expensive alternative arduino board to CMUcam4

I have used OpenCV on Intel Galileo for doing recognition of sub images from a larger image (given the cover of a magazine, identify it in a pile of magazines partially covering it). The frame rate is far from stellar.
I haven't tried with Edison but it should be much faster, as it's an Atom core vs the pentium-like Quark. OpenCV is optimized for x86.

I used a normal webcam to capture the image, so this solution gives more flexibility in the choice of the sensor.

You could have a look at ROS on Edison.


nRF24L01 - leaves out end characters during transmission

This is not a proper solution explaining why the issue occurred in the first place but merely a workaround to anyone encountering the same problem.

There is another function in the RF24 library called startWriting(). The description in the library was not clear about the differences between this and write(). But I noticed that the last character was missing with the use of startWriting(). So I simply changed

radio.read(&text, sizeof(text));

in the master to

 radio.read(&text, sizeof(text+1));

and voila!
The code now does its intended purpose!!


Question about viability of building a Bill Counter machine

There are many more things to consider than just put some parts together if you try to build a counter from scratch. Automated currency handling has come a long way to today's bill counters or any vending machines. You may perfectly handle the computing part of task with an embedded system like the arduino, but paper handling is an art of itself.

If you think of this task as a challenge to acquire and hone engineering skills, go ahead. It may be one of the best training tasks one can think of. But while you may learn a lot from this conundrum, you will propably end up without an usabale device. :)

You have to consider, there are subtasks in

mechanics
electronics
programming

which may include

paper handling (separation, traction, alignment)
pattern recognition
motor control
high speed sensors
signal detection and processing
error and fault processing and handling
motor and gear connection
bearings and mechanical substructure
user interface

and many more.

To modify an existing device solves a lot of mechanical problems in advance. But it may still be difficult to change the firmware of a bill counter to your needs.

You will have to

break into the system (may be impossible)
reverse engineer the firmware
understand the mechanical constraints
find a way to adapt the system to your needs.

A third way, which in my eyes is rather intriguing, is to take an existing bill counter, rip out the controller and try to plug in your own controller, e.g. an arduino. This gives you a real chance to reach your goal while still having the opportunity to learn a lot.


Using Arduino as ISP to burn sketch directly to ATmega328 without first installing a bootloader on the ATmega328

It is possible to skip the Burn Bootloader step. When you do Upload Using Programmer the bootloader is overwritten and thus serves no purpose. However, there is another reason for the Burn Bootloader step, to set the correct fuses for your board selection. The fuse settings configure things on the ATmega328 such as clock speed and clock source. If the ATmega328 you are using doesn't happen to have the correct fuse settings for the board selection you're using in the IDE then things may not work or may not work correctly. For this reason it's best to always do the Burn Bootloader step the first time you use the ATmega328 and any time you change the board selection or other settings related to that board selection(such as custom Tools menu settings). Since you're not using an external clock source for your ATmega328 make sure that you don't select a board that is configured for an external clock as this will cause the chip to no longer work until you have connected an external clock.


Problem : Trigger limit switch to stop DC motor

DISCLAIMER: I haven't tested the code in this answer, but I hope there are no problems.

Your code has a major problem: what happens when one gate is moving and you trigger another movement? (reply: something bad). This design issue can be solved by using a standard way of designing these kind of state machine.

In your case a small state machine is what best fits your problem. Better give your states a meaningful name, no?

Ok, so just to start, let's define the states and how to transition through them.

You have basically an idle state, open gate, close gate, open garage door, close garage door. What should you do in these states, both when entering the state and during the time you are in the state? Here is a table to summarize

State       | Enter         | During time
----------------------------------------------
Idle        | Stop motors   | -
OpenGate    | Start A dir 1 | -
CloseGate   | Start A dir 2 | -
OpenGarage  | Start B dir 1 | -
CloseGarage | Start B dir 2 | -

The transitions are pretty straightforward. Exit from idle when you receive a (valid) command, exit from the others when you reach the endstop.

The implementation is pretty standard:

// Motor for Gate (MotorA)
const byte IN1 = 2;
const byte IN2 = 3;
const byte EnableMotorA = 9;

// Motor for Garage Door (MotorB)
const byte IN3 = 4;
const byte IN4 = 5;
const byte EnableMotorB = 10;

const byte LimitSwitch1 = A1;
const byte LimitSwitch2 = A2;
const byte LimitSwitch3 = A3;
const byte LimitSwitch4 = A4;

const byte State_Idle = 0;
const byte State_OpenGate = 1;
const byte State_CloseGate = 2;
const byte State_OpenGarage = 3;
const byte State_CloseGarage = 4;
byte currentState;

void setup(){
    pinMode(IN1,OUTPUT);
    pinMode(IN2,OUTPUT);
    pinMode(EnableMotorA,OUTPUT);

    pinMode(IN3,OUTPUT);
    pinMode(IN4,OUTPUT);
    pinMode(EnableMotorB,OUTPUT);

    pinMode(LimitSwitch1, INPUT);
    pinMode(LimitSwitch2, INPUT);
    pinMode(LimitSwitch3, INPUT);
    pinMode(LimitSwitch4, INPUT);

    Serial.begin(9600);
    currentState = 0xFF; // Force a change to enter the idle state
}

void loop(){
    // Check if we need to change state
    byte nextState = currentState;
    switch (currentState)
    {
    case State_Idle:
        { // If we received a valid command, start the operation
            if(Serial.available() > 0)
            {
                switch (Serial.read())
                {
                case 'A':
                    nextState = State_OpenGate;
                    break;
                case 'B':
                    nextState = State_CloseGate;
                    break;
                case 'C':
                    nextState = State_OpenGarage;
                    break;
                case 'D':
                    nextState = State_CloseGarage;
                    break;
                default:
                    // Here you can notify that there was a bad command
                    break;
                }
            }
        }
        break;
    case State_OpenGate:
        if(digitalRead(LimitSwitch2)) // == HIGH is not necessary
            nextState = State_Idle;
        break;
    case State_CloseGate:
        if(digitalRead(LimitSwitch1)) // == HIGH is not necessary
            nextState = State_Idle;
        break;
    case State_OpenGarage:
        if(digitalRead(LimitSwitch4)) // == HIGH is not necessary
            nextState = State_Idle;
        break;
    case State_CloseGarage:
        if(digitalRead(LimitSwitch3)) // == HIGH is not necessary
            nextState = State_Idle;
        break;
    default:
        nextState = State_Idle;
        break;
    }

    // If there was a change, switch state and trigger enter condition
    if (nextState != currentState)
    {
        currentState = nextState; // Move in the new state
        switch (currentState)
        { // Entering the new state
        case State_Idle:
            // Stop motor A
            digitalWrite(IN1, LOW);
            digitalWrite(IN2, LOW);
            analogWrite(EnableMotorA, 0);
            // Stop motor B
            digitalWrite(IN3, LOW);
            digitalWrite(IN4, LOW);
            analogWrite(EnableMotorB, 0);
            break;
        case State_OpenGate:
            // Start motor A
            digitalWrite(IN1, LOW);
            digitalWrite(IN2, HIGH);
            analogWrite(EnableMotorA, 250);
            break;
        case State_CloseGate:
            // Start motor A
            digitalWrite(IN1, HIGH);
            digitalWrite(IN2, LOW);
            analogWrite(EnableMotorA, 250);
            break;
        case State_OpenGarage:
            // Start motor B
            digitalWrite(IN3, LOW);
            digitalWrite(IN4, HIGH);
            analogWrite(EnableMotorB, 250);
            break;
        case State_CloseGarage:
            // Start motor B
            digitalWrite(IN3, HIGH);
            digitalWrite(IN4, LOW);
            analogWrite(EnableMotorB, 250);
            break;
        }
    }
}

(Note: I changed some types because your poor 8-bit uC asked me to avoid complicating its calculations unnecessarily)

One modification to your algorithm is to detach the two loops, since they seem, well, detached.

// Motor for Gate (MotorA)
const byte IN1 = 2;
const byte IN2 = 3;
const byte EnableMotorA = 9;

// Motor for Garage Door (MotorB)
const byte IN3 = 4;
const byte IN4 = 5;
const byte EnableMotorB = 10;

const byte LimitSwitch1 = A1;
const byte LimitSwitch2 = A2;
const byte LimitSwitch3 = A3;
const byte LimitSwitch4 = A4;

const byte StateA_Idle = 0;
const byte StateA_Open = 1;
const byte StateA_Close = 2;
byte currentStateA;

const byte StateB_Idle = 0;
const byte StateB_Open = 1;
const byte StateB_Close = 2;
byte currentStateB;

void setup(){
    pinMode(IN1,OUTPUT);
    pinMode(IN2,OUTPUT);
    pinMode(EnableMotorA,OUTPUT);

    pinMode(IN3,OUTPUT);
    pinMode(IN4,OUTPUT);
    pinMode(EnableMotorB,OUTPUT);

    pinMode(LimitSwitch1, INPUT);
    pinMode(LimitSwitch2, INPUT);
    pinMode(LimitSwitch3, INPUT);
    pinMode(LimitSwitch4, INPUT);

    Serial.begin(9600);
    currentStateA = 0xFF; // Force a change to enter the idle state
    currentStateB = 0xFF; // Force a change to enter the idle state
}

void loop()
{
    byte readChar = 0;
    if(Serial.available() > 0)
        readChar = Serial.read();

    stateMachineA(readChar);
    stateMachineB(readChar);
}

void stateMachineA(byte readChar)
{
    // Check if we need to change state
    byte nextState = currentStateA;
    switch (currentStateA)
    {
    case StateA_Idle:
        { // If we received a valid command, start the operation
            if(readChar > 0)
            {
                switch (readChar)
                {
                case 'A':
                    nextState = StateA_Open;
                    break;
                case 'B':
                    nextState = StateA_Close;
                    break;
                default:
                    // Here you can notify that there was a bad command
                    break;
                }
            }
        }
        break;
    case StateA_Open:
        if(digitalRead(LimitSwitch2)) // == HIGH is not necessary
            nextState = StateA_Idle;
        break;
    case StateA_Close:
        if(digitalRead(LimitSwitch1)) // == HIGH is not necessary
            nextState = StateA_Idle;
        break;
    default:
        nextState = StateA_Idle;
        break;
    }

    // If there was a change, switch state and trigger enter condition
    if (nextState != currentStateA)
    {
        currentStateA = nextState; // Move in the new state
        switch (currentStateA)
        { // Entering the new state
        case StateA_Idle:
            // Stop motor A
            digitalWrite(IN1, LOW);
            digitalWrite(IN2, LOW);
            analogWrite(EnableMotorA, 0);
            break;
        case StateA_Open:
            // Start motor A
            digitalWrite(IN1, LOW);
            digitalWrite(IN2, HIGH);
            analogWrite(EnableMotorA, 250);
            break;
        case StateA_Close:
            // Start motor A
            digitalWrite(IN1, HIGH);
            digitalWrite(IN2, LOW);
            analogWrite(EnableMotorA, 250);
            break;
        }
    }
}

void stateMachineB(byte readChar)
{
    // Check if we need to change state
    byte nextState = currentStateB;
    switch (currentStateB)
    {
    case StateB_Idle:
        { // If we received a valid command, start the operation
            if(readChar > 0)
            {
                switch (readChar)
                {
                case 'C':
                    nextState = StateB_Open;
                    break;
                case 'D':
                    nextState = StateB_Close;
                    break;
                default:
                    // Here you can notify that there was a bad command
                    break;
                }
            }
        }
        break;
    case StateB_Open:
        if(digitalRead(LimitSwitch4)) // == HIGH is not necessary
            nextState = StateB_Idle;
        break;
    case StateB_Close:
        if(digitalRead(LimitSwitch3)) // == HIGH is not necessary
            nextState = StateB_Idle;
        break;
    default:
        nextState = StateB_Idle;
        break;
    }

    // If there was a change, switch state and trigger enter condition
    if (nextState != currentStateB)
    {
        currentStateB = nextState; // Move in the new state
        switch (currentStateB)
        { // Entering the new state
        case StateB_Idle:
            // Stop motor B
            digitalWrite(IN3, LOW);
            digitalWrite(IN4, LOW);
            analogWrite(EnableMotorB, 0);
            break;
        case StateB_Open:
            // Start motor B
            digitalWrite(IN3, LOW);
            digitalWrite(IN4, HIGH);
            analogWrite(EnableMotorB, 250);
            break;
        case StateB_Close:
            // Start motor B
            digitalWrite(IN3, HIGH);
            digitalWrite(IN4, LOW);
            analogWrite(EnableMotorB, 250);
            break;
        }
    }
}

This second implementation has two parallel state machines (sharing only the serial input). This will allow you to control both gates at the same time (for instance when the gate is closin you can open the garage)


Finally I found ATTinyCore library. I have tested it with a blink sketch. Just download the zip file. Unzip and copy  Attinycore-master directory into "program files/Arduino/hardware/arduino/avr" directory. Restart the IDEA. Select ATTiny x8 Series from the boards menu, and select the specific chip (48 or 88), clock speed, and BOD level from the appropriate menus that will appear in the tools menu after selecting ATTiny x8 series as the board.

https://github.com/SpenceKonde/ATTinyCore


Only if you need crystal accuracy. If the internal RC oscillator is accurate enough then feel free to use it instead.


How to detect an read buttons pressure on touchscreen

The fillRoundRect function format is (initial_Xpoint,initial_Ypoint,length,width,corner_radius,color)

Therefore, you already have the information about the location of the button itself. Next, check if the x and y value is within the button area.

void setup() {

  tft.begin();
  tft.fillScreen(BLACK);

  tft.fillRoundRect (12,15,30,80,5,RED);  //button1
  tft.fillRoundRect (50,15,30,80,5,RED);  //button2
  tft.fillRoundRect (88,15,30,80,5,RED);  //button3

  delay(500);
}

void loop()
{
  int x, y, pressedbutton=0;

  if(ts.dataAvailable())
  {
    ts.read();                //-----------> this is the whole thing
    x = ts.getX();
    y = ts.getY();

    if ((x>=12) && (x<=12+30) && (y>=15) && (y<=15+80)) pressedbutton = 1; else
    if ((x>=50) && (x<=50+30) && (y>=15) && (y<=15+80)) pressedbutton = 2; else
    if ((x>=88) && (x<=88+30) && (y>=15) && (y<=15+80)) pressedbutton = 3;
  }

  ...
  ...
  ...
 }


Error in sending AT commands in esp8266 connecting to arduino IDE

Looks like your connection is somewhere missing.

Connect CH_PD and reset pin to high--i.e. 3.3v.


16*2 1602A LCD not displaying any character or contrast, although correct wiring

Ok so the problem were the wires.
Although I tested every single wire for continuity I went to the store and bought a brand new (expensive/not-from-aliexpress) pack of jumper wires. I rewired the entire project with the schematic and code that was posted in my question-post and it worked like a charm..

So I'm not sure what exactly caused the problem, but it was in the wire. I thought having continuity in a wire is like a 100% proof that the wire works properly. Maybe someone has an idea what could cause this?

So again, I only replaced the wires, not the schematic nor the code, with brand new ones and it worked perfectly.


Can I use an ESP8266 as a replacement for an original Arduino?

Yes, No and Maybe is the best answer :)

Assuming that you want to replace a Arduino Uno board with an ESP8266 based board.  Your best choice at the moment would be a Wemos D1.  It has the same form factor as the UNO, but it has less pins, 9 digital and 1 analog.

If you are not bothered about the form factor, you could also try a Node-LUA, or a Wemos D1 Mini.  If you have steady hands you could try just using the heart of these three boards directly, which is usually called an ESP8266-12E, but it has 1mm pitch and no voltage regulation.

There are a lot of sites around that have tutorials on using ESPs.  They are mostly interchangeable with Arduino boards from a software perspective, they have more memory and a faster clock speed.

The biggest difference between an Arduino based board and an ESP board is most Arduino use 5v and most ESP based boards use 3.3v.  Make sure you read the datasheet before you hook up you sensors.

There is an ESP-32 as well.  This is not interchangeable with an Arduino Uno at the moment.


First off you never want to use String - especially on a chip with a mere 512 bytes of SRAM.

You should really be learning about struct for sending of data in the most efficient way.  A struct is a complex data type that combines multiple bits of data into one single variable - a bit like a record in a database.

You should avoid sending text as it is generally wasteful. The odd character, yes, but not whole strings of text.

For instance, you might want to send temperature, humidity and pressure:

struct data {
    int8_t temperature;
    uint8_t humidity;
    uint16_t pressure;
};

void sendData() {
    struct data myPacket;

    myPacket.temperature = 23;
    myPacket.humidity = 72;
    myPacket.pressure = 1016;

    driver.send((uint8_t *)&myPacket, sizeof(myPacket));
    driver.waitPacketSent();
}

With a struct, if you want to send text, you need to allocate enough space in the struct for your text. For instance, enough room for 9 characters plus NULL:

struct data {
    int8_t temperature;
    uint8_t humidity;
    uint16_t pressure;
    char weather[10];
};

Then, to get data into it, you (for example):

strcpy_P(myData.weather, (PGM_P)F("fog"));


ESP32-CAM interfacing with CCS811+HDC1080+BMP280

No. Those three devices are I2C devices, not SPI devices.

Using that is no different to using three individual sensors all wired to the same I2C bus.


Why isn't there bus contention on the MISO line during SPI-based programming?

Yes, you can get SPI bus contention when using multiple SPI slave devices. It is up to you, the designer, to ensure that each SPI slave device has its chip select (CS or SS) asserted only when no other devices are driving MISO. Normally that is achieved by:

initialize all of the CS pins high (inactive) during setup
in the code that accesses SPI device #1,

assert SPI device #1 CS1 low (active)
perform SPI transfers on SPI device #1
release SPI device #1 CS1 high (inactive)

in the code that accesses SPI device #2,

assert SPI device #2 CS2 low (active)
perform SPI transfers on SPI device #1
release SPI device #2 CS2 high (inactive)

SPI bus contention can also occur during device programming (loading the bootloader or firmware image), if there is an attached SPI slave device, and its chip select (SS) is not pulled inactive by a pullup resistor.

I had a problem with this on one of my designs a few weeks ago. I was trying to burn the bootloader into some blank ATmega328-AU chips post-assembly, and my device programmer wasn't able to successfully program the chips because my one slave device had its chip select connected only to an ATmega328 pin.

I had previously breadboarded this design using an Arduino Pro Mini board, and it was working fine; but when I moved to first prototype PCB there was bus contention on MISO -- the blank ATmega328 wasn't driving the slave device's chip select high or low, but it floated low (active), causing MISO contention.

My solution (workaround) was temporarily contacting the chip-select to VDD 3.3V through a 10kohm resistor. This made my SPI slave device inactive, allowing the device programmer to successfully load the bootloader.

I think there would be no harm in leaving the pullup resistor on chip select (since it's an active-low signal), but it was only really necessary when using the device programmer. After I had the prototype boards initialized with the bootloader image, I was subsequently able to load firmware images as usual.

(One minor unrelated issue was that my assembler purchased ATmega328-AU when I had specified ATmega328P-AU -- they are almost the same, and it doesn't make a difference for my application, but it was annoying that I had to use a slightly different command line argument than then one I used with the Arduino Pro Mini board.)


Try measuring with a voltmeter to compare the good board to the bad one. If it is the diode as mentioned in the comments under the question, you should get a different reading on the bad board. It should be fairly easy to replace if you have a soldering iron and a steady hand.


exit status 1 error compiling for board arduino/Genuino Uno when tone code is used

If you have a look at the complete error message you will see that there is a collision between the libraries NewPing and Tone.

Arduino: 1.8.9 (Windows Store 1.8.21.0) (Windows 10), Board: "Arduino/Genuino Uno"

Tone.cpp.o (symbol from plugin): In function `timer0_pin_port':

(.text+0x0): multiple definition of `__vector_7'

libraries\NewPing\NewPing.cpp.o (symbol from plugin):(.text+0x0): first defined here

collect2.exe: error: ld returned 1 exit status

exit status 1
Error compiling for board Arduino/Genuino Uno.


There is a difference between Wifi and Wireless. Wifi requires an already established network and uses the standard internet protocols. If this is what you mean, then the communication speed would only be influenced by the bandwidth of your network and the speed of the arduinos. I have not been able to find what the speeds of the modules are, but if they are 150 mB/s and your network is only 100, then you'll only get a speed of 100mB/s (which is a pretty decent speed).

If you want wireless (they create their own network using the unlicensed 2.4ghz spectrum, then buy these: nRF24L01+ 2.4GHz. They seem pretty reliable at short distances, and have a low power and high power variant. These have a speed of (at tops) 2 mB/s, but you won't have to worry about having a Wifi connection.

I personally do not know much about Bluetooth modules, so I cannot comment there.

Hope this helped.


As you have noticed yourself, this can be somewhat platform-dependent.
Since you are working on a Nano, my answer will be for the AVR
architecture, when compiled with gcc, the avr-libc, and the Arduino core
library.

First, let me reassure you: this weird behavior you saw of the Wixel
doesn't happen on this platform. Local variables get allocated mostly in
CPU registers, then on the stack.

Now, the first general rule may sound obvious: think twice about what
your program really needs to remember. Also, use each time the
smallest possible data type. The C99 types int8_t, uint16_t and co.
are useful for this.

Another rule you will often hear on this platform: avoid dynamic
allocation, i.e. malloc() and new, as quite often you cannot afford
heap fragmentation. Avoid also the String class, as it relies on
dynamic allocation. Prefer when possible static allocation, or stack
allocation for small things.

Don't forget to use const for constants: with this qualifier the
compiler can often optimize the constants out as immediate operands. For
arrays of constants, use PROGMEM. Yes, it's not comfortable
to use, but it can save you lots of RAM. The F() macro for printing
constant messages is a special case of PROGMEM.

Lastly, be very careful with recursion.


One possible option would be these 8x8 pixel displays.

I got that from eBay for $8.50 (for the 4 modules).

They come pre-assembled, this is the back:

Notice the data direction. You can connect them together like this:

That one (3 lots of 4 modules) is 25.4 cm long (10 inches) and 3.2 cm high (about 1.25 inches).

That's 96 pixels (8 x 4 x 3) in 10 inches, which is a lot less than 40 DPI, but really, if you want to read them from 15 feet away, that is probably OK.

Note: These were single-colour only.

If you want 40 DPI x 6 inches that means you must want 240 pixels horizontally and 120 pixels vertically. That would be 240 / 8 modules horizontally (30 modules) and 120 / 8 vertically (15 modules). That's a total of 450 modules. Since they come in lots of four that would be 116 in total (rounded up). 116 x $8.50 = $US 986.

I don't know if that is what you have in mind by "cost cutting" but that is one option.

You would need to assemble them yourself, connect them together, supply power, and have a suitable driver. I have some code that drives those boards, although I certainly have not tested it with 450 of them at once.

As you can see those boards come with mounting holes on the back, and are designed to be physically adjacent to each other. Mounting 450 of them could be quite tedious. The LED modules on the front pull off to give access to the mounting holes, but it would be a long job.

You can get larger modules, as mentioned in another reply, I expect they would be more expensive, but you would of course get more pixels.

Example: 64x32 RGB LED Matrix - 4mm pitch. That one is 64x32 pixels for around $US 80.

You would probably need 4 of those horizontally (256 pixels) and 4 vertically (128 pixels). Thus, a total of 16 which would cost you around $US 1280. However for that at least you get RGB. Note that the Adafruit page mentions you cannot drive that many pixels with a Uno.


Can I use two sensors with different baud rate without problems on arduino?

You can only have one sensor on one serial port, and the baud rate is set on the serial port.

So as long as you have two serial ports, or SoftwareSerial ports (I wouldn't, it causes more problems that it solves - get a board with multiple UART interfaces) then yes you can have two baud rates.


How to write data in RAM memory using Arduino Uno or Arduino Due?

DRAM of any kind requires a memory controller which is not present in any AVR device. Larger AVR devices such as the ATmega64A and ATmega128A do have an external memory bus that can be used for SRAM and MMIO.


char reqst[] = " ";

Here you created an array two chars in length. But one of those characters must be used for the null terminator so actually it can only hold a string that's a single character long. If you write past the end of the array that will cause undefined behavior. This is likely to be the cause of the strange results you encountered. You need to size reqst[] large enough to contain any string you may receive, including the null terminator. You should add code to ensure that you never write off the end of the array and that it will always end in a null terminator.

I realize it may only be a simplified minimal example, but in the code you posted there is no need to store the incoming characters. Instead you could just print them as they are received.


Controlling stepper motor direction with push buttons

Try using digitalRead() for button presses. Chances are your buttons, especially when on a breadboard, don't return exactly 0 for analogRead().

IMHO, simple On-Off switches should always connect your pin to either Vcc or GND, with either the internal pullup turned on (if connected to GND), or an external pulldown resistor in place.

To debug this, you might want to Serial.println() the values of your button states to your Arduino IDE and observe if their values are like you'd expect.


Maximum frequency that can be converted with Arduino Uno?

First of all, the ADC on the Uno is 10 bits, not 12.

The naive approach of having analogRead() in a tight loop can give you
up to 8.9 kS/s (112 µs per sample), but you won't be able to
do much else, as the CPU spends most of it's time just waiting for the
ADC to do its job. If you configure the ADC manually, then you can set
it into the so called “free running mode”. You then get about
9.6 kS/s (104 µs/S), but then the CPU is free to process one
sample while the next one is being converted.

If you need to go faster, you can tweak the frequency of the internal
ADC's clock. Then it's a compromise between speed and accuracy: the
faster you go the less accurate. You may get rough but kind of usable
samples at up to 77 kS/s (13 µs/S).

For a detailed comparison of the different clocking options, with speed
and accuracy estimation, see the article ADC conversion on the Arduino
(analogRead), by Nick Gammon.


You can get sprinkler valves, that use solenoids, for under $20 that fit on plastic PVC pipe and are designed for water, such as these at SprinklerWarehouse.  They typically use pipe sizes of about 1 inch.


Why won't the slide switches control the motor in this 123d simulation?

This should be written like this:

if ( digitalRead(guard)==HIGH && digitalRead(switchPin)==HIGH ) {

// Rest of the code..

}


I assume that, if this is a cost sensitive item, you need a reliable supply of multiples (so looking for small SD cards on e-bay isn't a viable solution).

Does it need to be non-volatile storage? If it does't you may be able to find small 8-bit wide RAM chips at a pretty good price. If it needs to be non-volatile, you might look at individual flash chips. I found this one, an 8-bit by 512 KB Serial-SPI flash chip for £0.19 (about $0.28 US) in single units and £0.176 if you can by 100 at a time. I would expect DRAM chips and chips with a simpler interface to be less expensive (but you might end up spending more on interfacing the chips so it might end up as a wash).

If you're able to consider a variety of processor chips it might be worth looking for something that has adequate storage on chip. That might be the most cost effective way to get the space.


Your first decision is to figure out the heat load on the space. How many BTU/hr you need to remove to keep the temperature you want. Then figure out how large / how many Peltier you need to remove that much heat. Do you need some reserve capacity for unusual circumstances or is a higher inside temperature Ok sometimes? Then you need a power budget - how much power will it take to remove that much heat with Peltier panels. How much PV area will you need to provide that power? If you need cooling when the sun isn't out, your power budget has to include the 24-hour demand, and the intermittent supply, perhaps again with some headroom. Power storage - batteries or the power grid - will be a requirement to match the two. The same storage can power your Arduino. The Arduino's power budget will be minuscule compared to the rest of the installation and you can totally ignore it. Do you have to power your internal network that connects the Arduino to the Internet, too? Figure that in. By this point, you'll have the answers to most of your questions. Just a heads-up: A Peltier beer-cooler is quite doable. A whole house A/C might be doable but no practical - you probably won't like the numbers! I'm guessing your project lies somewhere between the two.


Additional boards manager option is missing from Arduino IDE

You need to download and install a recent version of the Arduino IDE from:

http://www.arduino.cc/en/Main/Software

When you install the Arduino IDE using apt-get you get a very outdated and non-standard version, which does not have the Boards Manager feature. The reason for this is that the license documentation of the Arduino IDE does not currently meet the required standards for the package manager:

https://github.com/arduino/Arduino/pull/2703


Reducing noise and finding sampling rate

Just to as a complement to Majenko's answer (which I second), there are
a couple of flaws in your program that may be related to your problem:

lowest is always zero, as it is initialized to 0 and cannot increase
your computation of the mean is incorrect: the mean is the sum of the
readings divided by their number
you fail to reset lowest and highest between consecutive runs of
8000 samples
there is no point in putting all of loop() inside an infinite loop.

Assuming you really intend to print summary statistics on runs of
8000 samples, as your code suggests, I would write it like this:

const int SENSOR_PIN = A0;
const int SAMPLE_COUNT = 8000;
const uint32_t SAMPLE_PERIOD = 125;  // 125 us

void loop()
{
    long sum = 0;
    int lowest = INT_MAX, highest = 0;

    uint32_t lastTime = micros();
    for (int i = 0; i < SAMPLE_COUNT; i++) {

        // Wait until it's time.
        while (micros() - lastTime < SAMPLE_PERIOD) ;
        lastTime += SAMPLE_PERIOD;

        // Take and process the sample.
        int sensorValue = analogRead(SENSOR_PIN);
        sum += sensorValue;
        highest = max(highest, sensorValue);
        lowest = min(lowest, sensorValue);
    }
    float mean = (float) sum / SAMPLE_COUNT;
    Serial.print("mean: "); Serial.print(mean);
    Serial.print(", minimum: "); Serial.print(lowest);
    Serial.print(", maximum: "); Serial.println(highest);
    Serial.flush();
}

Edit: I changed the code in order to keep a roughly constant
sampling rate of 8000 samp/s. The main change is that, before
taking a reading, we wait until it's time to do so (until
micros() - lastTime >= SAMPLE_PERIOD).

Note that lastTime could be updated with lastTime = micros(), in
which case it would have hold the time we last took a sample. By
updating it with lastTime += SAMPLE_PERIOD it instead holds the time
we shoud have taken the last sample. This is the right choice for
enforcing a given average sampling rate.

Running on an Uno: I have no experience with the Due, but here are
some remarks that would apply to an Uno, or any other AVR-based Arduino:

analogRead() takes about 110 µs, which means we cannot sample
more than one channel, and we only have about 15 µs to process
the sample. Here the processing is simple enough that the Arduino can
do it in this limited time.
There is some jitter in the sampling, because micros() has a limited
resolution of 4 µs, because of the timer interrupt kicking in
from time to time, and because the while loop takes a finite amount
of time.

If I were to do something similar on an Uno, I would forgo
analogRead(), configure the ADC to be triggered by a timer, and set
the timer to trigger the DC every 125 µs. Not only would this get
rid of the jitter, it would also allow the CPU to do its job in parallel
with the ADC, instead of just sitting idle and waiting until the ADC is
done. This would allow for more complex per-sample processing.

About the Due: As I said, I have no experience with this board. It
has a more capable processor, but this tells you nothing about the speed
of its ADC. I would expect to face the same issues as with the Uno,
though maybe to a lesser degree. I guess it should be possible to
trigger the ADC from a timer, but I have no idea how to do so.


Can I detect with software when a PIR sensor is physically connected to Arduino?

The PIR sensor I have will overpower the internal pull-up resistor of the ATmega328P used on the Arduino Nano. This means if you turn on the pull-up and then get a read of LOW you know something is connected to that pin because the unconnected pin will always read HIGH with the pull-up on. With this approach you can get false negatives because the pin will also read HIGH if the PIR is triggered but you won't ever get false positives for PIR sensor detection. This means you can't rely on just doing a single test in setup() because the PIR might be triggered then so you will need to repeatedly run the test until the PIR sensor is detected. Example sketch:

int PIRpin = 2;    //the input pin for the PIR sensor
boolean PIRconnected = false;

void setup() {
  Serial.begin(9600);
  pinMode(PIRpin, INPUT);
}

void loop() {
  if (PIRconnected == false) {
    pinMode(PIRpin, INPUT_PULLUP);
    if (digitalRead(PIRpin) == LOW) {
      Serial.println(F("PIR sensor detected"));
      PIRconnected = true;
    }
    pinMode(PIRpin, INPUT);  //turn off the internal pull-up to reduce power consumption
  }
  Serial.println(digitalRead(PIRpin));
  delay(500);
}


Im trying to map a joystick to a servo but need the servo to be at 0 when the joystick is in nerural. And up to 180 when joy is forward or back

You can use the map function, see Arduino Map Function.
So in your case, assuming a value of 0..1023 coming from an analog pin, where 0 needs to be mapped to -180 and 1023 to +180, you get
int mappedValue = map(value, 0, 1023, -180, 180);

(note I assume you mean -180 when backwards, +180 when forwards).
UPDATE
It seems value 0 (backward) needs to be mapped to 180, 512 (neutral) to 0, and 1023 (forward) to 180 (again).
For this you need two maps depending on the value:
int mappedValue = 0;
if (value < 512) // Backwards
{
    mappedValue = map(value, 0, 511, 180, 0);
}
else // Forward
{
    mappedValue = map(value, 512, 1023, 0, 180);
}


WiFiClient.connect() does fail all the time (ESP8266 Core for Arduino)

If the server has a default IP address of 192.168.0.1 and the client has an IP address of 192.168.4.1 my guess is they won't be able to talk because you are using a 24 bit mask.

The subnet mask defines the number of bits that makes up the subnet, so if you were using the two addresses above and had a mask of 255.255.255.0 or 24 bits then the subnets you were using would be 192.168.0 and 192.168.4.  To cross subnets you need some form of routing process (usually a router, switch that can route, etc).

So you need to either change the mask or, stick both devices on the same subnet.
(Don't rely on defaults, when they change your code breaks)


The 'old' ATmega 8 bit microcontrollers don't have an event system peripheral. The new "megaAVR 0 series" has an event system. Atmega 4809 on Arduino Uno WiFi Rev2 and on Nano Every is "megaAVR 0-series". The event system of the new ATmegas is similar to SAMD event system I know.

ARM MCUs for example SAMD by Atmel/Microchip used in Arduino Zero and MKR have an event system. Event system is a MCU peripheral. It enables direct communication between peripherals without the involvement of the CPU of the MCU.

The MCU peripherals are what makes the MCU a MCU. Examples of peripherals are GPIO pins, external interrupts, timers, SERCOM, watchdog...

To give you an example of use of the event system. To perform AC phase cutting with a Triac the Triac must be pulsed at right time after zero crossing. (It turns off self at next zero crossing.) To achieve this with MCU, the MCU must sense the input from the zero crossing detection circuit, then start timing the requested off time, then start a pulse to triac's gate and then stop the pulse.

It can be implemented with an external interrupt function for zero crossing, which starts a timer to generate a pulse on a wave output pin.

On ARM MCU it is possible to setup the event system to start the timer on external interrupt over an event, without an interrupt function. Then the CPU of the MCU is not involved in phase cutting after the initial configuration of the peripherals.

After setting up the zero crossing detector input pin for external interrupt without interrupt function and setting up the timer to execute one-shot pulse, the event system will re-trigger the timer on external interrupt.

a simple Arduino SAMD lib for a Triac/ZC module (in development):

#ifndef _TRIAC_LIB_
#define _TRIAC_LIB_

namespace Triac {

const unsigned long AC_WAVE_MICROS = 10000; // at 50 Hz
const int TIMER_PRESCALER = 8;
const unsigned long PULSE_PERIOD = ((F_CPU / 1000000) * 200) / TIMER_PRESCALER;

Tcc* TCC;

void syncTCC() {
  while (TCC->SYNCBUSY.reg & TCC_SYNCBUSY_MASK);
}

void zeroCrossing() {
}

void setup(byte zcPin, byte triacPin) {

  // setup the external interrupt
  attachInterrupt(zcPin, zeroCrossing, RISING);
  uint8_t ulExtInt = g_APinDescription[zcPin].ulExtInt;
  EIC->EVCTRL.reg |= (1 << ulExtInt);// enable event
  EIC->INTENCLR.reg = EIC_INTENCLR_EXTINT(1 << ulExtInt); // turn-off interrupt

  const PinDescription& pinDesc = g_APinDescription[triacPin]; // Arduino pin description
  TCC = (Tcc*) GetTC(pinDesc.ulPWMChannel);
  uint8_t tcChannel = GetTCChannelNumber(pinDesc.ulPWMChannel);

  // setup the pin as TCC wave out pin
  PORT->Group[pinDesc.ulPort].PINCFG[pinDesc.ulPin].bit.PMUXEN = 1;
  PORT->Group[pinDesc.ulPort].PMUX[pinDesc.ulPin >> 1].reg |= PORT_PMUX_PMUXE_F;

  // setup the timer

  REG_GCLK_CLKCTRL = (uint16_t) (GCLK_CLKCTRL_CLKEN | GCLK_CLKCTRL_GEN_GCLK0 | GCLK_CLKCTRL_ID(GCM_TCC0_TCC1)); // assign clock
  while ( GCLK->STATUS.bit.SYNCBUSY == 1 );

  TCC->CTRLA.bit.SWRST = 1; // reset timer
  syncTCC();
  TCC->WAVE.reg |= TCC_WAVE_WAVEGEN_NPWM; // normal PWM as wave output mode
  syncTCC();
  TCC->CTRLBSET.reg = TCC_CTRLBSET_ONESHOT | TCC_CTRLBSET_DIR; //one shot and count down
  syncTCC();

  TCC->PER.reg = ((F_CPU / 1000000) * AC_WAVE_MICROS) / TIMER_PRESCALER; // initial value of period (triac off)
  syncTCC();
  TCC->CC[tcChannel].reg = PULSE_PERIOD; // pin on at compare match and off at 0 (timer counts down)
  syncTCC();

  TCC->EVCTRL.reg |= TCC_EVCTRL_TCEI0 | TCC_EVCTRL_EVACT0_RETRIGGER; // retrigger on event
  syncTCC();
  TCC->CTRLA.reg |= TCC_CTRLA_PRESCALER_DIV8 | TCC_CTRLA_ENABLE; // set prescaler and enable
  syncTCC();

  // event system
  PM->APBCMASK.reg |= PM_APBCMASK_EVSYS; // power it on
  GCLK->CLKCTRL.reg = GCLK_CLKCTRL_ID(EVSYS_GCLK_ID_0) | GCLK_CLKCTRL_CLKEN | GCLK_CLKCTRL_GEN(0); // assign a clock
  while (GCLK->STATUS.bit.SYNCBUSY);

  EVSYS->CTRL.bit.SWRST = 1; // reset
  while(EVSYS->CTRL.bit.SWRST);

  EVSYS->USER.reg = EVSYS_ID_USER_TCC0_EV_0 | EVSYS_USER_CHANNEL(1); // set user TCC0 event 0 on channel 0
  EVSYS->CHANNEL.reg = EVSYS_CHANNEL_CHANNEL(0) | EVSYS_CHANNEL_PATH_ASYNCHRONOUS | // channel 0 is async
      EVSYS_CHANNEL_EDGSEL_FALLING_EDGE | EVSYS_CHANNEL_EVGEN(EVSYS_ID_GEN_EIC_EXTINT_0 + ulExtInt); // source is ext.interrupt
  while (!EVSYS->CHSTATUS.bit.USRRDY0);
}

/*
 * r is from interval <0.0, 1.0>
 */
void setPeriod(float r) {
  unsigned long period = ((F_CPU / 1000000) * ((1.0 - r) * AC_WAVE_MICROS)) / TIMER_PRESCALER;
  TCC->PER.reg = period + PULSE_PERIOD;
  syncTCC();
}

}
#endif

other SAMD example


You can try SO002 or DS-TR250.

  Is it possible to increase the threshold of sensitivity of the sensor?

I don't think its possible. Perhaps you can tweak the reading sensitivity, but since the sensor are mostly analog, it's not possible. And maybe that also the reason the 2 sensors I've mentioned above have several series based on their measuring threshold.


Function not successfully reading sensor registers

Wire.requestFrom(register_address, numBytes);
  byte c;
  Serial.println(Wire.read());
  while (Wire.available()) {
    c = Wire.read();
  }

This has a number of problems. For one thing your (I presume) debugging print consumes the data from Wire.read, so when you go to get it into c, you have already printed it. In other words, you are reading byte #1 and printing it, but using byte #2. This seems an odd thing to do.

Next, what is this doing?

  while (Wire.available()) {
    c = Wire.read();
  }

You are reading an indefinite number of bytes, and retaining the last one. Why?

Possible rework:

byte fp::readRegister(byte register_address, int numBytes) {
  Wire.requestFrom(register_address, numBytes);
  byte c = Wire.read()
  Serial.println(c);
  Serial.print("0x");
  Serial.print(register_address, HEX);
  Serial.print("\t");
  Serial.print(c);
  Serial.print("\t");
  Serial.println(millis());
  return c;
}

  Here is the Git repo with the rest of the code: https://github.com/fpdotmonkey/fp_accel

From your linked code:

  byte xlm = readRegister(fp::OUT_X_L_M, 1);
  byte xhm = readRegister(fp::OUT_X_H_M, 1);
  byte ylm = readRegister(fp::OUT_Y_L_M, 1);
  byte yhm = readRegister(fp::OUT_Y_H_M, 1);
  byte zlm = readRegister(fp::OUT_Z_L_M, 1);
  byte zhm = readRegister(fp::OUT_Z_H_M, 1);

You have the wrong end of the stick here.

  Wire.requestFrom(register_address, numBytes);

You request from the I2C address - that is the device address. The register is something else.

Judging by the datasheet you first have to send the register address, and then request the data. Something along the lines of:

byte fp::readRegister(byte register_address, int numBytes) {
  Wire.beginTransmission (DEVICE_ADDRESS);
  Wire.write (register_address);
  Wire.endTransmission (false);  // repeated start
  Wire.requestFrom(DEVICE_ADDRESS, 1);
  byte c = Wire.read()
  Serial.println(c);
  Serial.print("0x");
  Serial.print(register_address, HEX);
  Serial.print("\t");
  Serial.print(c);
  Serial.print("\t");
  Serial.println(millis());
  return c;
}

Similarly for writing to a register:

void fp::writeRegister(byte register_address, byte val) {
  Wire.beginTransmission(DEVICE_ADDRESS);
  Wire.write (register_address);
  Wire.write(val);
  Wire.endTransmission();
}

This is untested because I don't have the device here, but I know that what you had won't work. To check the actual device address run the I2C scanner I mentioned before.


analogRead function not working in MATLAB

That function is part of legacy code.

  NOTE: This solution (formerly known as "Arduino IO Package") is no
  longer supported. It is recommended that you use Arduino support
  packages that are developed and supported by MathWorks:

  MATLAB Support Package for Arduino Hardware: Read, write, and analyze data from Arduino sensors
  http://www.mathworks.com/hardware-support/arduino-matlab.html
  Simulink Support Package for Arduino Hardware: Develop algorithms that run standalone on your Arduino
  http://www.mathworks.com/hardware-support/arduino-simulink.html

  Use this legacy support only if one of the following is true:

  - You are using MATLAB R2013b or earlier (but not earlier than R2011a).

You are using 2014a, so its probably the reason analogRead isn't working. Get the more recent package and use this function instead:


how can i conect a lipo charger to a teensy 4.0?

The output voltage of the charger board is marked with BAT. You should connect it to the Vin pin of the Teensy, which then will convert the batteries 3.7-4.2V down to 3.3V.

Of course you need to connect the grounds of the charger board and the Teensy (on the charger board ground is marked with G).

The 5V pin on the charger board is no output. The board does not give you 5V. This is actually the pin for the charging voltage, which is 5V. Here it depends on how you want to charge the battery. If you use an external source, you can simply connect it's 5V to the board. If you want to use the USB jack of the Teensy, you can connect the boards 5V to the Teensys 5V. But: Be sure to cut the little trace between Vin and VUSB/5V at the back of the Teensy. You don't want to connect the battery voltage with an USB power source.