Binary reader with arduino blinking 8 leds

You just prepend the number in binary with B e.g. B01100100 which is 100 in decimal

byte sequence[] = {
    B10000000,
    B01000000,
    B00100000,
    B00010000,
    B00001000,
    B00000100,
    B00000010,
    B00000001
}

And to check the n-th bit from the right in a number you do

boolean bit_set = number & (1 << (n - 1)) != 0;


How to convert Unicode char to “Unicode HEX Position” in Arduino

Unlike JavaScript, C++ makes no difference between a character and its
code point. Thus, 'A', 0x41 and 65 are just different ways of
writing the same number.
Note, however, that the char type is intended to hold ASCII only. For
everything else, you may try using wide characters. For example, the
program
void setup() {
    Serial.begin(9600);
    wchar_t c = L'س';
    Serial.println(c, 16);
}

void loop() {}

outputs 633 on the serial port. Note the second argument to
Serial.println() which specifies base 16. Default is to print
numbers in decimal.
Beware that the representation of wide characters is implementation
defined, and the avr-libc doesn't provide support for manipulating them
or strings made with them. If you want to transmit them, you will also
have to decide for yourself how to break them down into a sequence of
bytes, as that's the only thing a serial port (or I2C, or SPI for that
matter) can transmit. UTF-8 is the most popular choice. I doubt wide
characters are popular in embedded systems at all.


If you're okay with grayscale, you don't need 1 MB buffer space. With the YUV422 colour space, you can extract only the Y component and need only 640*480 = 307kB buffer for a VGA grayscale image.

However, according to this, you can set the hardware serial baud rate to 1M-baud and transmit the image bytes as you receive them without buffering. main() shows how to set up the serial port and you can also see how they received each VGA pixel byte in Bayer-RGB and transmitted immediately; notice that all interrupts are disabled first, given the high-speed nature of the transfer. But instead of Bayer, I'd recommend you use YUV422 instead, meaning the camera sends 2 bytes per pixel. Because you're only interested in the Y byte, you can place that in the UART buffer and use the time spent in receiving (and discarding) the second U/V byte to give the UART peripheral some additional breathing room to send the Y byte, before you send the next one.

Regarding the high baud rate, the crystal frequency of the Arduino doesn't matter so much because you'll only be transmitting to your PC, which should be able to handle the speed even given the rate error. Note that in main(), double speed async is enabled, and UBRR is set to 500 kBaud to obtain 1-Mbaud. Also notice that an 8MHz PWM signal was used to clock the camera (XCLK signal) with no PLLs activated in the camera register settings. This is another tutorial related to the same code; may clear up a few things.

If you really want to use a chip solution, you can look up parallel SRAM like the HM628128; it's only 128kB though, you'll need to find a bigger one to hold an entire frame of 307kB. Parallel SRAM are great because you can attain really high write speeds because of the simple interface. You'll need some sort of counter connected to the SRAM address lines clocked by the PCLK line (divided by 2, since you only want every other byte) so that every pulse increments the address. This same clock will feed the nW signal to actually clock the data into the SRAM (after satisfying address setup times somehow). The camera data lines will be connected directly to the SRAM and you activate the SRAM's chip select signal based on your monitoring of the camera's VSYNC signal (to know when a new frame's about to start). When the frame's done, you read from the RAM and forward the bytes to your destination.

All this assumes you aren't trying for video, merely taking frames "once in a while". Though the first solution will work for video, albeit poor video.


Yes, you can use an external ADC chip. You can get SPI and I2C ΣΔ ADC chips at 16-bit and higher quite easily.

I often use the MCP3553 which allows 60sps at 22-bit.


An Arduino running at 5V needs at least 3.0V on the pin to read it as rising high.  You probably want to go a little more than that.  So that means your lowest voltage has to be like 3.3V or so.

Note that the analog pins don't have an external interrupt, you'll have to use pin change interrupts and then read with analogRead in the ISR.  So you can't use "RISING".  The pin change interrupts act on any edge.  So they'll trigger when falling as well.

That's a pretty poor way to handle these buttons.  Normally one would just poll buttons like this.  If your loop takes so long that you might miss a human pressing a button then perhaps you should look at that instead.


For an extern the whole definition has to match the "master" definition.
So if you have:
StaticJsonDocument<JSON_SIZE_IOT> paramJSON;

then you extern has to be:
extern StaticJsonDocument<JSON_SIZE_IOT> paramJSON;

Of course you have to make sure your JSON_SIZE_IOT is the same for both - so it's best if that comes from a common source.
This is known as explicit instantiation declaration and you can read more about it in the Class template C++ reference.


Why do DigiKeyboard.print and println change my string?

The problem is your keyboard layout.

The USB HID protocol was originally intended to include keyboard layout information in it (country code selection in the descriptor) however no one ever used it.  All keyboards have the same layout, but manufacturers just print different letters on the keys for different countries.  It's down to the operating system to map those key codes to actual characters using the keyboard layout selected in the operating system. (The original intended method of operation would have allowed keyboards to select their own language instead of having a single global one in the OS, but people do like to choose the cheapest option...).

The Arduino is effectively a US keyboard. The letters and numbers you "print" are first converted to their keyboard codes as they would appear on a US keyboard. Those keyboard codes are then converted back to letters and numbers using your Italian keyboard layout selected in the operating system.

You would get the same effect if you got a US keyboard and plugged it in. Pressing the keys for the symbols as printed on the keys themselves you give you the same wrong characters. Pressing the keys that you are used to pressing and ignoring what is printed on the keys would give you the right symbols.

So you have a number of options:

Use a US keyboard globally on your computer, which would break your existing keyboard layout, or
Modify the Arduino core to map the characters using an Italian keymap, or
Work out which characters you should be sending to get the right ones for your keymap, and change your code to send those characters instead.

Of the three I'd go for option 3.  Option 1 would be too annoying, option 2 would be undone with the next Arduino core update and you'd never remember what you did.  So spend some time and work out which characters, when you print them, result in which characters being typed.


MQ4 gas sensor is not working with Arduino UNO

That is what I would expect to see with one of these sensors.

I'm not sure on the wiring, I think you may be wrong.  Have a read of http://playground.arduino.cc/Main/MQGasSensors#readdatasheet and see if you agree.

Did you leave the sensor to warm up?  It takes a few minutes (from memory) and until its warm it won't give you a proper reading.

An MQ4 should be able to detect Methane, butane and propane, so was your lighter using on of these gasses?  When it does detect the target gas, the number will go up, and stay up for a while.

Another thing you can try is blowing on the sensor, the results will vary depending on what you have been eating, but it should shift one way or another.

If it still doesn't work then buzz out your connections, just to triple check, and re-read the manual.


ATtiny85. How do I burn a bootloader? What is the process?

Yes, there are USB interfaces for ATtiny85. Just look at one of the open hardware designs out there, e.g. Digispark.
An USB interface is going to require two pins, so using one to save one pin doesn’t strike me as cost effective.
I agree with @FAD, that you don’t really need an USB stack, and simply could do a time-delay-at-boot thing with the UART pins.
HVSP (the high voltage programming) is not hard to do. If you’re already comfortable with ArduinoISP, you can try ScratchMonkey, which uses the same approach (with a 12V power supply and one transistor) to do HVSP programming.


Lego / Meccano style blocks for 'serious' projects

Here is what comes to mind (by no means exhaustive):

billed as "the Industrial erector set", 8020 is legitimately used in industry for that kind of purpose, and if I remember correctly, pretty expensive. It is the most "professional" thing I can think of.

OpenBeam styles itself as the the cheaper, "open sourced" 8020. I've frequently heard of it being used in 3d printers.

These are not as serious or professional, but might be worth mentioning:

MINDSi is pretty close to the mindstorms, but tries to be more rigid/durable. It's aimed at robotics.

Servo City's actobotics is an aluminum modular building system. It is also sold on sparkfun.

I have not used these enough to give good comparisons, but I hope one of these will be what you are looking for.


As I said in my comment, all float operations are implemented in
software. As a simple test, I compiled the following program:

volatile float x, y, z;

int main(void)
{
    z = x + y;
    return 0;
}

The compiler translated the sum operation into a call to __addsf3.
This function extends its arguments to flt40_t format (non-standard 40
bits float), calls __addsf3x to do the 40-bit addition, then calls
__fp_round to convert the result into the standard float format.
__addsf3x also makes a few library calls of its own. In the end, the
addition pulled the following functions into the compiled program:
__subsf3, __addsf3, __addsf3x, __fp_inf, __fp_nan,
__fp_pscA, __fp_pscB, __fp_round, __fp_split3, __fp_splitA,
__fp_zero and __fp_szero.

All these functions are provided by the avr-libc. You can find them in
the libm/fplib directory. See for example the files:

addsf3.S
addsf3x.S
fp_round.S


does not allow reentrant interrupts.

a few suggestions:

1) understand what "reentrant interrupts" means;

2) see if you need it;

3) see what needs to be done to get it to run on your hardware;

4) see if your code does what needs to be done.

hope it helps.


In C++, a class that holds reference members (in your sample, LiquidCrystal& _Clcd1; and LiquidCrystal& _Clcd2;) must ensure these references are initialized at construction time, not later.

This means your void init(LiquidCrystal& Clcd1, LiquidCrystal& Clcd2); method is not the right way to initialize _Clcd1 and _Clcd2 because it will be called after construction time.

You have 2 ways to solve this issue,t hat I will detail further below.

HOWEVER, before we discuss the solutions, you must be aware that your sample code has a huge defect in setup() method code!

void setup()
{
    //LiquidCrystal lcd(RS,RW,Enable1,Enable2, data3,data2,data1,data0);
    LiquidCrystal lcd(12, 11, 7, 6, 5, 4);  //declare two LCD's
    LiquidCrystal lcd2(12, 10, 7, 6, 5, 4); // Ths is the second

    LCDController.init(lcd, lcd2);
}

Here, you create lcd and lcd2 in your setup method, but their life ends at the end of setup(), because they have been allocated on the stack. Using these outside setup() will most likely cause your program to crash as soon as your loop() tries to access lcd or lcd2, indirectly through LCDController method calls.

To remove this defect, you must declare these variables outside setup:

//LiquidCrystal lcd(RS,RW,Enable1,Enable2, data3,data2,data1,data0);
LiquidCrystal lcd(12, 11, 7, 6, 5, 4);  //declare two LCD's
LiquidCrystal lcd2(12, 10, 7, 6, 5, 4); // Ths is the second

void setup()
{
    LCDController.init(lcd, lcd2);
}

Now you can use them anywhere in your program, you are sure they are present and "alive".

Now we can go to the solutions of the original compilation problem.

1. Initialize references at construction by adding a constructor

class LCDControllerClass
{
    public:
    LCDControllerClass(LiquidCrystal& Clcd1, LiquidCrystal& Clcd2)
    : _Clcd1(Clcd1), _Clcd2(Clcd2) {}
    ...
};

You can still keep an void init() method to complete the initialization if you don't want it to occur right at construction time, or you can fully integrate the current init() content into the constructor and re,voe init() altogether:

class LCDControllerClass
{
    public:
    LCDControllerClass(LiquidCrystal& Clcd1, LiquidCrystal& Clcd2)
    : _Clcd1(Clcd1), _Clcd2(Clcd2)
    {
        _Clcd1.begin(40, 2);
        _Clcd1.clear();

        _Clcd2.begin(40, 2);
        _Clcd2.clear();
    }
    ...
};

In anycase, you will have to change the way you instantiate your LCDControllerClass LCDController which you did not show in your sample code, that would be something like this:

LiquidCrystal lcd(...);
LiquidCrystal lcd2(...);
LCDControllerClass LCDController(lcd, lcd2);

That obviously requires that you can instantitate lcd and lcd2 before creating LCDController. If that is not possible for you, then  you'll have to use the second way.

2. Replace references with pointers

As mentioned before, in a class reference members MUST be initialized at construction time (moreover, they cannot be changed afterwards, to point somewhere else). This is not the case for pointers however:

class LCDControllerClass
{
    public:
    void init(LiquidCrystal* Clcd1, LiquidCrystal* Clcd2);

    private:
    void _UpdateLCD(int iLine, int iPosition, String cText);
    LiquidCrystal* _Clcd1;
    LiquidCrystal* _Clcd2;
};

void LCDControllerClass::init(LiquidCrystal* Clcd1, LiquidCrystal* Clcd2)
{
   _Clcd1 = Clcd1;
   _Clcd1->begin(40, 2);
   _Clcd1->clear();

   _Clcd2 = Clcd2;
   _Clcd2->begin(40, 2);
   _Clcd2->clear();
}

Note that now, you need to use the arrow notation -> to access _Clcd1 and _Clcd2 members (dot notation cannot work for pointers).

The rest of the code should be slightly modified to reflect this change:

//LiquidCrystal lcd(RS,RW,Enable1,Enable2, data3,data2,data1,data0);
LiquidCrystal lcd(12, 11, 7, 6, 5, 4);  //declare two LCD's
LiquidCrystal lcd2(12, 10, 7, 6, 5, 4); // Ths is the second

void setup()
{
    LCDController.init(&lcd, &lcd2);
}

Note that we now have to pass the address of lcd and lcd2 to init(), by using & before their names.


I'd check 3 things:

If it's a specific USB port/cable problem, not related to the NodeMCU itself (your said it interacted with your USB keyboard, what makes sense if it's a computer-usb issue). Try to connect the NodeMCU to a different USB port/hub in your computer using another USB cable.

Of course it could be a USB-Serial driver issue. Please make sure what chip is used on your NodeMCU (CH340 or CP1202) and make sure the correct driver is installed.

Most important - you must make sure your Serial pins on the NodeMCU (TX, RX) are not connected to anything during program upload. They are bridged to the Serial connection that is coming from the computer (through the USB-to-Serial chip) and interact and interfere with them.

Good luck!


How to solve this "xpected primary-expression before ',' token"

This:

#define speaker

defines "speaker" as nothing, an empty string. Then:

tone(speaker,131);

is translated into

tone(,131);

which makes no sense. The compiler expected to find an expression before the comma.


Should be easy enough.  Do you already know how to connect and communicate with one I2C device?  If so, connecting multiple should be simply a case of connecting them in parallel.

If you don't know how to communicate with a single I2C device, then...

For the Arduino software you can use Wire to talk to devices over I2C.

For the hardware, connect the I2C clock and data lines from the Arduino to the I2C devices.  More on that here.


You need to include DEC as the second argument to the Serial.println() call to get the correct numbers out.  Read up on this here: Arduino Serial Print.

In other words, make change below:

Serial.println(number, DEC); // DEC is needed to get the correct values


Arduino Micro just blinks, won't connect to PC

I have something similar happen a couple of times with some atmega328s (on arduino unos). I believe it was the bootloader that some how became corrupted and so no longer responded to the computer. The only way to fix this is to reflash the bootloader using an ISP programmer. Luckily the arduino can act as an ISP programmer so all you need is another working arduino.

See https://www.arduino.cc/en/Tutorial/ArduinoISP for how to do this on an uno. The same can be done with the micro/nano as they all use the same atmega328p chip its just a matter of wiring it up correctly.

If you cannot reflash the bootloader with this method then one of the chips is probably damaged and would need to be replaced. At this point it might be easier to replace the whole board.


How can Arduino source code be tested automatically (continuous integration)?

Newest version of Arduino ide has a command line interface to build and upload code. But you can obviously do it by makefile and avrdude.
Now, you have compiled your code BUT you need testing.
As simulator are complex,incomplete, expansive and.. Just a simulation, and because the chip are relatively cheap, building a board witch will make HW interaction AND check the results its the fastest and easiest way.
On that "special" board you may upload something like an interpreter witch take a test from the PC and execute it, something similar to firmata for arduino.
At least that is how I would build it.
And as far as I know there are no know implementation of this, even if I'm quite sure many industries should and probably do that.


Reset arduino nano after disabling tx/rx

After some more tries something actually worked reinitialising the TX/RX pins, but i don't know why really. I wired RX pin to the reset and i loaded an empty code into the arduino, after that i was able to load any program into my arduino again. Problem solved, but why it solved the problem is the question now.


DS1307 RTC not working with CC3000 WiFi shield (I2C bus hangs)

It could be that the CC3000 interrupts are affecting the Wire library's behaviour since the latter is interrupt-driven itself.
Try disabling the CC3000 IRQ before calling rtc.isrunning() or any other RTC functions. First #include "ccspi.h" in your sketch. Then place WlanInterruptDisable() before any RTClib function call, and then WlanInterruptEnable() after the RTC function returns.

Even if this works, it may affect the functionality of the CC3000, since it increases the chances of missed interrupts. You can search for DS1307 libraries that employ SoftwareI2C instead such as this one. They should be better able to recover from the CC3000 interrupts.


To make it generic, you simply divide the sizeof the array by the sizeof the type:
for(int i=0; i<sizeof(controls)/sizeof(SwitchControl); i++){
}

Then you can later change the items if the array, or the structure and the code will be the same.


'Servo_Pointer' was not declared in this scope

You should make Servo Servo_Pointer; global, i.e. place it outside the setupfunction, e.g. after the line int average = 0;.
In your code, it is a local variable within the setup function. When this function ends, the local variables within this function (such as Servo_Pointer ) do not exist anymore.
By making the variable global, you can use it anywhere. However, it's not a good coding practice to use global variables when not needed.
A benefit of making the variable global is that you can see the memory consumption of the instance of Servo_Pointer when compiling.
Also see the comment of timemage below: Don't put #include statements in the middle of your code, put them in the beginning of your code.


Unable to compare char from radio (RF24)

That is not a good way to solve it.  That is a hack.  The String class does bad things on microcontrollers and it is something you should try to stay away from.  What you need to compare two char arrays is the strcmp function.

if(strcmp(someCharArray, anotherCharArray) == 0){
    // the strings are the same
}

Use google to find out more about strcmp.


A compiler translates c/cpp to target assembly language.

To keep it short, some c/cpp language statements or keywords can be used to shorten the code (in c/cpp)... but the mechanics behind all that to translate to assembly can generate more instructions than you thought.

It would maybe be easier to explain if you put some example...


analogWrite(_pin, duty_cycle) will work properly only on pins that support PWM. Older Arduino boards with an ATmega8 only support analogWrite() on pins 9, 10, and 11. The Arduino Due supports analogWrite() on pins 2 through 13, plus pins DAC0 and DAC1. Unlike the PWM pins, DAC0 and DAC1 are Digital to Analog converters, and act as true analog outputs. Check the following link to find yours:
https://www.arduino.cc/reference/en/language/functions/analog-io/analogwrite/


Can I cut the pin holes off of my Arduino board?

I guess that one could cut (or hone down) parts of the PCB. Obviosly this process devoids the warranty and there is the risk of damaging either the board or some components on it (i.e. by holding or clamping it during the process).

I would not expect any other wiring besides those connecting the pins to run in this part of the PCB. The reference layout (see board layout and using Eagle (free version)) - if the clones follow that layout - confirms that there are no other traces there. So it is mostly important to not cut any other traces and remove any chippings after the cutting to avoid short circuits.

If in doubt buy two or three boards ;) to try and repeat the process.


How do I connect this SPI serial display to an Arduino?

That kind of connector is most commonly directly soldered on to a PCB.  You can buy adaptor boards with the various different pitch pads on them for soldering it to.

Also there is no mention of what chip the screen uses (I am unfamiliar with "XS057" as a chip, so that is probably the model of the screen not the chip).  At that resolution it's probably an ILI9163, but without being sure all you can do is stab wildly in the dark and try different drivers.


Why Ethernet webclient fails to initiate?

What you write is not a function but a variable. And the variable will not change its value (unless you have some interrupt and it is a global variable).

so you need to change 'client' to some function you want to call, probably 'client.xxx()' where xxx is the name of the function you want to call (possibly with parameters).


Variable i & j are not declared. They should be declared as 3. Try this:

const int x = 3;
const int y = 3;

int pinMatrix[x][y] = {{2, 3, 4}, {5, 6, 7}, {7, 8, 9}};

void setup() {
  for (int i = 0; i < 3; i++) {
    for (int j = 0; j < 3; j++) {
      pinMode(pinMatrix[i][j], OUTPUT);
    }
  }
}

void loop() {
  for (int i = 0; i < 3; i++) {
    for (int j = 0; j < 3; j++) {
      digitalWrite(pinMatrix[i][j], HIGH);
      delay(1000);
      digitalWrite(pinMatrix[i][j], LOW);
    }
  }
}


I don't think you need a file system: that is usually needed when you want to manage many files. Your weather data log sounds like a single file.

What you seem to need is to access EEPROM as a stream, exactly like you would for an open file. There are stream wrappers around some EEPROM libraries, e.g. this one for ESP. I suggest you check it out and see if you can adapt it to the EEPROM library you use.


There are multiple options for this project as you just want to send/ upload data on the cloud server rather than using Arduino MKR 1400 you can use any of the following.

Arduino UNO with GSM module: As per your requirement you can use Arduino UNO to read the data from the sensor and the GSM module will be used to upload the same on the cloud server. There are various GSM modules available in the market which are cheap also and good. You can also use SIM800 one of the GSM module.

Other GSM modules which you could use can be,
SIM900, Quectel EC-20, Quectel M95. You can also visit SIMCONN website where you can find multiple GSM module options.

You can also use ESP8266 or ESP32 which are Wi-Fi modules but in this case you will require a internet/ Wi-Fi connection near the controller. ESP8266/ ESP32 will read data from the sensors and can also upload the same to the cloud servers. But as you said you are using them to monitor agriculture field it won't be possible to have a Wi-Fi which will cover such long range.

One of the possible solutions to the problem is to use RF-link to transmit data and collect it at a base-station and from the base station you can upload/ send them to the server.

You can also make use of the LoRa Network to communicate along the fields and then receive data from the whole field at a base station and then upload them to the server. But this could be a more expensive solution.


Serial communication between python and arduino

If the python Serial write function sends byte, then you should read it in Arduino with Serial.read().

void loop() {
  if (Serial.available()){
    byte data = Serial.read();
    myservo.write(data);
  }
}

If python sends the number as text, then you can read it with parseInt().

void loop() {
  if (Serial.available()){
    int data = Serial.parseInt();
    myservo.write(data);
  }
}

The parseInt is one of the blocking functions and will by default wait one second for next char after the last sent digit was received. But the number is sent at once from python so the delays between digits are small. Set in setup() Serial.setTimeout(10);


Double clap sensor not working as intended

If your first clap rings for more than 50ms, the program counts it as a second clap.  After detecting a clap, you need to wait for the sound to die down before you start listening for a second clap.


Cannot ping ESP8266's IP address from a computer on the same network

First, you need to confirm that your PC's wireless connection is on the same IP subnet as the ESP8266. At the CMD prompt, type:

ipconfig /a

and look for the wireless adapter. Hopefully the IP address will start with 192.168.1.... It should but there's no harm in checking!

Second, check that your WiFi router hasn't disabled pinging between its clients - some do (mine did, until I threw it out...). Do you have a smartphone or other WiFi device? If so, find out its IP address (hopefully also 192.168.1....) and confirm that you can ping it.

Pinging your own address isn't very useful. Normally it detects the fact that it's its own address, and replies with no attempt at sending over the air.


How is stack memory used for fuctions and local variables?

Local variables and function parameters are stored on the stack. However, that is not a reason not to use them. Computers are designed to work that way.

Stack memory is only in use while a function is active. As soon as the function returns, the memory is freed. Stack memory is a GOOD Thing.

You don't want to use recursive functions with lots of levels of recursion, or allocate lots of large structures on the stack. Normal use is fine however.

The 6502 stack is only 256 bytes, but the Apple II works just fine.


Can stack size be determined by free heap?

I read heap and stack memory are facing each other and if heap or stack gets full and reachs another strange things happen.

Indeed they do. And such things can be a pain to track down.

  So i am wondering if can we use ESP.getFreeHeap() to get free heap and conclude usage of stack.

No, you can't.  The "free" amount of heap does not equate to the top address of heap. Heap can (and generally does) have holes in it. The "free" space is the sum of all those holes plus any extra "heap reserved" space above the highest heap entry.

To get the current stack usage you need to know two things:

The staring address of the stack, and
The current extent of the stack

Item 1 will be a fixed value, though what that value is I have no clue, but some reading will surely give you that value.

Item 2 can be obtained by allocating a local variable in a function and getting the address of that variable.

If all you care about is the change in stack imposed by your code you can record the "starting" stack point and use that in point 1.  For example:

char *stack_start;

void setup() {
    char stack;
    stack_start = &stack;
}

Then you can use that to get the current stack size compared to the start of your program:

uint32_t stack_size() {
    char stack;
    return (uint32_t)stack_start - (uint32_t)&stack;
}

  one tiny question here: can Serial.println("asd asd") cause memory fragmentation?

No.  Use of String and other dynamic allocation is what causes memory fragmentation.


MKR ZERO is not detected in IDE / MKR ZERO not showing up in windows 8.1/

A few possibilities come to mind:

Your USB cable is bad.  Try a known good one.
Your USB port has failed.  Try a different port or try plugging something else into this one to verify that it's still OK.
Your MKR ZERO has become damaged somehow.


How do voltage and resistance work for two 5v servos when using an external 12v power supply?

Because the supplies of both servos are connected in parallel, they both see the same voltage. Hence there is no "pool", both are being supplied the same 5V.

There is a regulator on the Arduino which reduces the 12V input down to 5V. It does so by burning off the other [7V times however much current is being used] as heat. Since you are supplying it with 1.5A, the most it can supply is in turn 1.5A.


The sampling frequency you are referring to (twice the highest frequency) is for capturing waves, but is not really a concern for the sensors you are using and the types of data they are used to measure.

If you wanted to analyse the magnitude of a 40kHz vibration in a structure, you should worry about sampling rates on your accelerometer; however, if you want to measure the accelerometers current angle to the ground (assuming its not accelerating), you only need to take one sample.

With the ECG, there will be a signal among all the analog voltages you read of a heartbeat (I'm assuming its hooked up to a person). This signal will never get much over 200 beats per minute, or 3.3 Hz. To capture a 3.3Hz signal you need a minimum sampling rate of 6.6Hz, which as still incredibly slow. The same goes for capturing a gait with your accelerometer.

If you capture the analog voltage of your sensors output with analogRead 100 times a second, you should have a very clear and well defined view of the very low frequency signals you are trying to track, and should not have any issues with transferring that much information over serial.

5, 16 bit values can theoretically be sent at 120Hz over 9600 baud, and its very easy to use faster speeds then that if you want more information.


I suggest using a different logic in your program. I would first divide up the different parts of the project:

A code part, which reads the 3 buttons and sets/increments/decrements a variable based on the button clicks, and
a code part, which takes a variable as set point and ramps the PWM (analogWrite()) output up or down, until the set point is reached. (So the setpoint is the target speed/PWM value)

This division between "input code" and "output code" is rather common, since it often makes your code better structured and makes it possible to easily add new inputs for one single output.

Let us first look at the second part (ramping the PWM signal up and down). We need a variable, that holds the current PWM value, and one, that holds the current set point (for both we are starting with zero, thus the motor stands still here:
int current_speed = 0;
int speed_setpoint = 0;

We also need a timestamp variable for using millis() to regularly setting the PWM output according to the set point and the corresponding interval (here as a define). Additionally we also define the increment, with which the PWM value should be incremented on each sample:
unsigned long motor_timestamp;
#define MOTOR_SAMPLE_INTERVAL  100
#define MOTOR_SAMPLE_INCREMENT 3

We are doing all this in the global scope. Now in the loop function we first check for millis() and the timestamp (which gives us a regular sample interval for the motor speed) and then check, if the current speed is higher or lower than the setpoint and change the current_speed accordingly. At the end we write the value of current_speed to the output:
if(millis() - motor_timestamp > MOTOR_SAMPLE_INTERVAL){
    if(current_speed < speed_setpoint){
        current_speed += MOTOR_SAMPLE_INCREMENT;
    } else if(current_speed > speed_setpoint){
        current_speed -= MOTOR_SAMPLE_INCREMENT;
    }
    analogWrite(motor, current_speed);
    motor_timestamp += MOTOR_SAMPLE_INTERVAL;
 }

So now we current_speed of the motor will follow the speed_setpoint, but will only increment or decrement with the speed you set with the MOTOR_SAMPLE_INTERVAL and the MOTOR_SAMPLE_INCREMENT. The new target speed is simply set by giving the variable speed_setpoint a new value. The above code will take care of reaching it.

Now lets look at the first part (reading the buttons for changing a variable). At your current code, you need to hold the button down for the value to change. From your text is guess, that you want a click behavior (1 step in speed for 1 button click, meaning button press and release). For that I suggest using the Bounce2 library, which will handle the buttons - especially the debouncing - for you:
#include <Bounce2.h>
Bounce bounce = Bounce();

void setup(){
    bounce.attach( BOUNCE_PIN, INPUT_PULLUP );
    // DEBOUNCE INTERVAL IN MILLISECONDS
    bounce.interval(5); // interval in ms
}

void loop(){
    bounce.update();
    if(bounce.fell()){
        // Handle the button click here
    }
}

Inside the if(bounce.fell()) statement, you would handle the action for the button click, in this case: updating the speed_setpoint variable. Define an increment value for the buttons and do the increment/decrement in the if statements. In global scope:
#define BUTTON_SPEED_INCREMENT 4

In the loop() function:
if(slower_bounce.fell()){
    speed_setpoint -= BUTTON_SPEED_INCREMENT;
}
if(faster_bounce.fell()){
    speed_setpoint += BUTTON_SPEED_INCREMENT;
}
if(tillend_bounce.fell()){
    speed_setpoint = maxspeed;
}

Now you need to put all this together. I will leave that to you. You can then tune the behavior to your liking by changing the defines.

Note the following points:

The motor will accelerate linear. That should be fitting for you.

The code will restart the PWM wave at every MOTOR_SAMPLE_INTERVAL. That is ok for a motor when the interval is significantly higher than the PWM interval. When you choose the interval too low (like single digit milliseconds), you need to put the analogWrite() call into the if statements with the increment of speed_setpoint. That will take 1 more statement, but will solve the problem.

If you choose the MOTOR_SAMPLE_INTERVAL too low, the speed change will get stuttery


Controlling 2 DC Motors with L293D and 6 V battery pack?

The L293D can handle two motors at a time and as per the data sheet the maximum voltage that you can give to the motor as a supply (on pin 8) is 36 volts.


Are you just looking for a way to get an arbitrary number expressed as a string? If so, you'll likely want to use some existing functions to help you along.

I recommend using sprintf

sprintf(char * str, char * format, args)

Where str is the string you're storing results in, format is the string you're inserting your values into for, you guessed it, formatting, and args are all the args, separated by commas, that you'll be passing into the format string to be inserted into the str string. An example might be:

char[x] result;    //x is the number of elements in your array, atleast one for every letter and one for the end character, ex: "hello" needs 6.
int number = 24;
sprintf(result, "My number is %d", number);
sendSomewhere(result);   //sends "My number is 24"


How to measure free RAM on an Arduino Due in Runtime?

As mentioned by Mikael Patel in a comment, the library from Arduino-MemoryFree
 should do it. A minimal sketch that seems to work on the Due:

extern "C" char* sbrk(int incr);

int freeMemory() {
  char top;
  return &top - reinterpret_cast<char*>(sbrk(0));
}

void setup ()
{
  Serial.begin (115200);
  Serial.println ();
  Serial.print ("Free memory is: ");
  Serial.println (freeMemory ());
}  // end of setup

void loop () { }

I'm not totally convinced that this gives the correct figure. The figure returned by the library above for my Uno was too high (2297 bytes).


There's a discussion on the Arduino Forum about this:

Mystery component on Yun board?

From what I read it's only for testing purposes.

  the connector is a MM8430-2610 (see this). You can plug in a
  MXGS83RK3000/MM126036: once plugged in, the switch connector will turn
  the internal antenna off and use the probe as an external antenna


delete the memory or re-upload a program

How do I know, how much storage capacity is available on the Arduino board before and after I uploaded something?

In yellow is how much bytes does your program take.

In purple is how much bytes are available on your board.

In green is how many bytes does your global variables take.

In orange is how many bytes are left for local variables.

In blue is how many bytes are available for all of your variables.

In red is the general specs of your board and to which COM port it is connected to.

  How can I delete a program from the Arduino board?

Once  a new program is uploaded, the old one is deleted (somewhat). Still, you get all your bytes back and it is like if you start from scratch

  When I upload a program, will the program that is already on the Arduino been overwritten?

Yes.

  Is an Arduino generally used to execute one specific program and not to hold a set of totally different programs?

An Arduino can only execute 1 program at the time. It doesn't usualy hold on to any other programs, but can store 1024 bytes in it's EEPROM. This lets your write in the EEPROM with a program and access that data with an other.


Hooking up LCD screens reclaimed from old camcorders to Arduino

This is likely a type of TTL LCD interface.  But it is nearly impossible to describe more as there are so many variations both in hardware and in timing.
Likely a steady stream of Red Green & Blue binary data way faster than an Arduino Uno could possibly manage is required to create an image.  For the necessary processing power, you would have to utilize one of the top end Arduino boards.  Even then, software to create the steady stream of binary data for this particular LCD is still required. Also, there are hardly no standards beyond saying the LCD is a TTL or LVDS.  Which means hours spent on developing software for this LCD will likely only work for this LCD.

It would be far easier to just buy an LCD and interface board known to work together.  If you are using an Arduino Uno, there is not much processing power beyond saying "I want a circle here" or "I want a line there".  Fortunately, there are such COTS parts available.  Here is a tutorial describing such a device connected to an Arduino Uno.


You have to write an application for your PC that

reads a number from the clipboard
adds some constant
puts the result back in the clipboard
quits

Then you have to configure you desktop environment in order to have this
application launched from a keyboard shortcut.
Once you have done that, you can do the whole operation from a regular
keyboard: Ctrl-C + Launcher shortcut + Ctrl-V.
If you can do it from a regular keyboard, you can do it from the Arduino
emulating a regular keyboard.
Edit: The way you do the first two steps is very dependent on the OS
running on your PC. On Linux, for example, the mentioned “application”
can be a minimal shell script:
#!/bin/bash

x=$(xclip -o -selection clipboard)
xclip -i -selection clipboard <<< $(bc <<< "$x + 0.25")

These steps are, however, outside the scope of this site.


Writing Libraries that use libraries that are being used in the sketch

The proper way to handle this is to have an #include guard in the header file to prevent the content from being included more than once.

In your header file filename.h you would add something like this:

#ifndef _FILENAME_H_
#define _FILENAME_H_

// Your header code here

#endif /* _FILENAME_H_ */

The #ifndef block will prevent the code from being included more than once. Best practice is to always put include guards in header files.


Arduino UNO does not get recognized by PC(no USB connecting sound), also TX and RX not blinking, neither are lit

You should definitely avoid connecting anything else than 5v to these 5v(!) PINs. The Uno has regulators, but these only work when powered through the power-dc-connector (or USB). You can easily buy a 9v-block to dc-jack cable to connect power to the right point easily.


How do you write to a specific register using I2C communcation?

The Arduino uses the Wire.h library to communicate on an I2C bus.

Writing to a register in I2C is usually done by sending two bytes to the correct I2C address.  The first byte is usually the register address, and the second is the value to place into the register:

#define CHIP_ADDRESS     0x6B
#define REGISTER_ADDRESS 0x12

Wire.beginTransmission(CHIP_ADDRESS);
Wire.write(REGISTER_ADDRESS);
Wire.write(0x18);
Wire.endTransmission();

Reading from a register is slightly more tricky, in that first you need to write to the chip to set the register address, then as a separate operation you need to read from that address:

Wire.beginTransmission(CHIP_ADDRESS);
Wire.write(REGISTER_ADDRESS);
Wire.endTransmission();
Wire.requestFrom(CHIP_ADDRESS, 1); // We want one byte
uint8_t val = Wire.read();


Can I have Arduino to read and write data using SDcard?

Yes, you can. You need to find an Arduino shield (or other board) that lets you attach SD cards to your board, and use that. (A quick Google search on "arduino SD card shield" reveals this SD card reader shield, for example. There are also "breakout boards" that are not shields. You'd have to attach wires to those rather than plugging a shield into your Arduino's headers.) This one, also from Adafruit, apparently has a built-in 5V-3V regulator, as well as voltage level shifters, so it should work well.
The specifics of how you read/write to the SD card will depend on the shield you buy.
Note that Arduinos include a certain amount of flash memory that is available for your program to read and write. If your storage requirements are modest, and you aren't writing data very frequently, that flash memory might work also. (Note that the built-in flash memory has a pretty low lifespan. If you write to it to many times, it will eventually fail. I forget the number of times, but you could look it up on Arduino's site.


I think the main problem here is that you want to measure in the presence of high voltage from the TENS. Not having experience with TENS circuits, I would suppose that their contact pins are connected to the high voltage source through resistors to limit the current. (Or some equivalent current-limiting scheme.)  If so, the voltage between the contacts should drop when there is a person connected. You should be able to detect that drop with the Arduino.  The "obvious" approach would be to use voltage dividers to reduce the no-load voltage to less than 5V so the Arduino ADCs can handle it. You'd need high-value resistors in the dividers so they don't load the TENS... maybe 1 Megohm or more for each divider.  One problem with this simplistic approach is that the TENS is putting out its stimulus using brief pulses, which may be too quick to catch with the ADCs.  To get around that, you'd feed the output of each divider through a diode to an R-C filter.  (Note that you need the diode anyway, since the TENS output is probably AC and the Arduino ADCS only want DC.)  This may take a fair amount of experimentation to get the values right, which you should do without the Arduino... just a DVM or scope that you can start at a high-voltage range until you sure you have everything worked out to 0-5V.


If you wire up your circuit as shown below, the bulb and the LED should flash together.


Arduino Servo.h library returns error in compilation

Servo is a class not an object. You have to instantiate it, and then call the functions on the instance. For example:

#include <Servo.h>

Servo sv;

void setup() {
  sv.attach(9, 554, 2400);
}

void loop() {
  sv.write(2000);
}

(Unlike some other libraries, it's done this way so that you can use more than one servo at the same time. You'd make one instance for each servo you want to control.)


Integrating 2 push buttons to toggle the LED ON and OFF

You are better off, in this case, remembering the state of the LED not the state of the buttons:

If the LED is OFF and BUTTON1 is PRESSED then turn the LED on.
If the LED is ON and BUTTON2 is PRESSED then turn the LED off.

For example:

void loop() {
    static bool ledState = false; // LED is off by default
    if ((digitalRead(pushbutton1) == LOW) && !ledState) { // 1 pressed & led is off
        digitalWrite(ledpin, HIGH);
        ledState = true;
    }
    if ((digitalRead(pushbutton2) == LOW) && ledState) { // 2 pressed & led is on
        digitalWrite(ledpin, LOW);
        ledState = false;
    }
}


Sure. Take a multimeter and measure the resistance between the left-most pin and each of the other pins with all the different combinations of button pairs pressed. Write down the results.
Then build a voltage divider for each output (Connect a resistor to ground on each output, and then connect that pin to an analog input on the Arduino. The resistor value to use will depend on the readings you get, but a 1K ohm resistor would be a good starting point.)
Then set up the 2 input pins on your Arduino as analog inputs and measure the voltage with no buttons, top button, bottom button, and both buttons pressed for each pair. Write those values down. Then write code that checks for voltages roughly equal to your measurements for each button press combo (You will need check for ranges of values, since the values will vary some.)


Are you willing / able to work with Xcode? There is a package called embedXcode that enables Arduino development on Macs – I'm just getting up to speed with it, but it does appear to allow you to work either in Xcode or with the Arduino IDE (the .ino file is present and is what you edit in Xcode). In my testing so far it appears that the easiest thing to do is to create a project using Xcode and then you can point the Arduino IDE at the project pretty easily, getting Xcode to pick up a sketch started in the Arduino IDE is currently beyond me.

From the point of view of your students I would think that you'd want to keep the .ino file rather than make them learn about the conventions of C or C++. It would also save you the hassle of somehow managing file names – although you could probably get make to do this for you.

I haven't looked into it at all, but I think you could do something similar with Atom (a quick Google found a blog post called Arduino Development in Atom Editor and an Atom package called nino that is described as a "Toolbelt for Arduino") or Emacs, or for that matter Vim is also like to have some Arduino support.


The web page on the Arduino site for the board tells you in plain words what they mean:

  On board indicators The shield contains a number of informational LEDs:

  L9 (yellow) : this is tied to digital pin 9
  LINK (green) : indicates a connection to a network
  ERROR (red) : indicates when there is a communication error
  DATA (blue) : indicates data being transmitted/received


Is Roboteq motor driver compatible with Arduino?

It is not directly supported. But the device description lists RS232 port that can be interfaced with an Arduino using a TTL to RS232 converter. The description also mentions "several Analog, Pulse and Digital I/Os which can be remapped as command or feedback inputs, limit switches, or many other functions" so it is totally possible to control the controller with an Arduino, but depending on the method you choose it may require some effort.


The first thing to try is replacing lcd.begin(16, 2) with lcd.begin(20, 4). The image of your LCD looks like a 20 char by 4 line display. Based on your comments, it seems that the SMS part of your code is working because it's outputting the correct characters to the serial monitor. I would focus on the LCD code and connections to your Arduino.


Introduction to SPI

The Serial Peripheral Interface Bus (SPI) interface is used for communication between multiple devices over short distances, and at high speed.
Typically there is a single "master" device, which initiates communications and supplies the clock which controls the data transfer rate. There can be one or more slaves. For more than one slave, each one has its own "slave select" signal, described later.

SPI signals
In a full-blown SPI system you will have four signal lines:

Master Out, Slave In (MOSI) - which is the data going from the master to the slave
Master In, Slave Out (MISO) - which is the data going from the slave to the master
Serial Clock (SCK) - when this toggles both the master and the slave sample the next bit
Slave Select (SS) - this tells a particular slave to go "active"

When multiple slaves are connected to the MISO signal they are expected to tri-state (keep at high impedance) that MISO line until they are selected by Slave Select being asserted. Normally Slave Select (SS) goes low to assert it. That is, it is active low. Once a particular slave is selected it should configure the MISO line as an output so it can send data to the master.
This image shows the way that data is exchanged as one byte is sent:

Note that three signals are outputs from the master (MOSI, SCK, SS) and one is an input (MISO).

Timing
The sequence of events is:

SS goes low to assert it and activate the slave
The SCK line toggles to indicate when the data lines should be sampled
The data is sampled by both master and slave on the leading edge of SCK (using the default clock phase)
Both master and slave prepare for the next bit on the trailing edge of SCK (using the default clock phase), by changing MISO / MOSI if necessary
Once the transmission is over (possibly after multiple bytes have been sent) then SS goes high to de-assert it

Note that:

The most significant bit is sent first (by default)
Data is sent and received at the same instant (full duplex)

Because data is sent and received on the same clock pulse it is not possible for the slave to respond to the master immediately. SPI protocols usually expect the master to request data on one transmission, and get a response on a subsequent one.
Using the SPI library on the Arduino, doing a single transfer looks like this in code:
 byte outgoing = 0xAB;
 byte incoming = SPI.transfer (outgoing);

Sample code
Example of sending only (ignoring any incoming data):
#include <SPI.h>

void setup (void)
  {
  digitalWrite(SS, HIGH);  // ensure SS stays high
  SPI.begin ();
  } // end of setup

void loop (void)
  {
  byte c;

  // enable Slave Select
  digitalWrite(SS, LOW);    // SS is pin 10

  // send test string
  for (const char * p = "Fab" ; c = *p; p++)
    SPI.transfer (c);

  // disable Slave Select
  digitalWrite(SS, HIGH);

  delay (100);
  } // end of loop

Wiring for output-only SPI
The above code (which sends only) might be used to drive an output serial shift register. These are output-only devices, so we don't need to worry about any incoming data. In their case the SS pin might be called the "store" or "latch" pin.

Examples of this are the 74HC595 serial shift register, and various LED strips, just to mention a couple. For example, this 64 pixel LED display driven by a MAX7219 chip:

In this case you can see that the board maker has used slightly different signal names:

DIN (Data In) is MOSI (Master Out, Slave In)
CS (Chip Select) is SS (Slave Select)
CLK (Clock) is SCK (Serial Clock)

Most boards will follow a similar pattern. Sometimes DIN is just DI (Data In).
Here is another example, this time a 7-segment LED display board (also based on the MAX7219 chip):

This uses exactly the same signal names as the other board. In both of these cases you can see that the board only needs 5 wires to it, the three for SPI, plus power and ground.

Clock phase and polarity
There are four way you can sample the SPI clock.
The SPI protocol allows for variations on the polarity of the clock pulses. CPOL is clock polarity, and CPHA is clock phase.

Mode 0 (the default) - clock is normally low (CPOL = 0), and the data is sampled on the transition from low to high (leading edge) (CPHA = 0)
Mode 1 - clock is normally low (CPOL = 0), and the data is sampled on the transition from high to low (trailing edge) (CPHA = 1)
Mode 2 - clock is normally high (CPOL = 1), and the data is sampled on the transition from high to low (leading edge) (CPHA = 0)
Mode 3 - clock is normally high (CPOL = 1), and the data is sampled on the transition from low to high (trailing edge) (CPHA = 1)

These are illustrated in this graphic:

You should refer to the datasheet for your device to get the phase and polarity correct. There will usually be a diagram which shows how to sample the clock. For example, from the datasheet for the 74HC595 chip:

As you can see the clock is normally low (CPOL = 0) and it is sampled on the leading edge (CPHA = 0) so this therefore is SPI mode 0.
You can change the clock polarity and phase in code like this (choose one only, of course):
SPI.setDataMode (SPI_MODE0);
SPI.setDataMode (SPI_MODE1);
SPI.setDataMode (SPI_MODE2);
SPI.setDataMode (SPI_MODE3);

This method is deprecated in versions 1.6.0 onwards of the Arduino IDE. For recent versions you change the clock mode in the SPI.beginTransaction call, like this:
SPI.beginTransaction (SPISettings (2000000, MSBFIRST, SPI_MODE0));  // 2 MHz clock, MSB first, mode 0

Data order
The default is most-significant bit first, however you can tell the hardware to process the least significant bit first like this:
SPI.setBitOrder (LSBFIRST);   // least significant bit first
SPI.setBitOrder (MSBFIRST);   // most significant bit first

Again, this is deprecated in versions 1.6.0 onwards of the Arduino IDE. For recent versions you change the bit order in the SPI.beginTransaction call, like this:
SPI.beginTransaction (SPISettings (1000000, LSBFIRST, SPI_MODE2));  // 1 MHz clock, LSB first, mode 2

Speed
The default setting for SPI is to use the system clock speed divided by four, that is, one SPI clock pulse every 250 ns, assuming a 16 MHz CPU clock. You can change the clock divider by using setClockDivider like this:
SPI.setClockDivider (divider);

Where "divider" is one of:

SPI_CLOCK_DIV2
SPI_CLOCK_DIV4
SPI_CLOCK_DIV8
SPI_CLOCK_DIV16
SPI_CLOCK_DIV32
SPI_CLOCK_DIV64
SPI_CLOCK_DIV128

The fastest rate is "divide by 2" or one SPI clock pulse every 125 ns, assuming a 16 MHz CPU clock. This would therefore take 8 * 125 ns or 1 µs to transmit one byte.
This method is deprecated in versions 1.6.0 onwards of the Arduino IDE. For recent versions you change the transfer speed in the SPI.beginTransaction call, like this:
SPI.beginTransaction (SPISettings (4000000, MSBFIRST, SPI_MODE0));  // 4 MHz clock, MSB first, mode 0

However empirical testing shows that it is necessary to have two clock pulses between bytes, so the maximum rate at which bytes can be clocked out is 1.125 µs each (with a clock divider of 2).
To summarize, each byte can be sent at a maximum rate of one per 1.125 µs (with a 16 MHz clock) giving a theoretical maximum transfer rate of 1/1.125 µs, or 888,888 bytes per second (excluding overhead like setting SS low and so on).

Connecting to Arduino
Arduino Uno
Connecting via digital pins 10 to 13:

Connecting via the ICSP header:

Arduino Atmega2560
Connecting via digital pins 50 to 52:

You can also use the ICSP header, similar to the Uno above.
Arduino Leonardo
The Leonardo and Micro do not expose the SPI pins on the digital pins, unlike the Uno and Mega. Your only option is to use the ICSP header pins, as illustrated above for the Uno. However the Leonardo and ProMicro don't expose the SS pin and thus cannot be used as an SPI slave.

Multiple slaves
A master can communicate with multiple slaves (however only one at a time). It does this by asserting SS for one slave and de-asserting it for all the others. The slave which has SS asserted (usually this means LOW) configures its MISO pin as an output so that slave, and that slave alone, can respond to the master. The other slaves ignore any incoming clock pulses if SS is not asserted. Thus you need one additional signal for each slave, like this:

In this graphic you can see that MISO, MOSI, SCK are shared between both slaves, however each slave has its own SS (slave select) signal.

Protocols
The SPI spec does not specify protocols as such, so it is up to individual master/slave pairings to agree on what the data means. Whilst you can send and receive bytes simultaneously, the received byte cannot be a direct response to the sent byte (as they are being assembled simultaneously).
So it would be more logical for one end to send a request (eg. 4 might mean "list the disk directory") and then do transfers (perhaps just sending zeros outwards) until it receives a complete response. The response might terminate with a newline, or 0x00 character.
Read the datasheet for your slave device to see what protocol sequences it expects.

How to make an SPI slave
The earlier example shows the Arduino as the master, sending data to a slave device. This example shows how the Arduino can be a slave.
Hardware setup
Connect two Arduino Unos together with the following pins connected to each other:

10 (SS)

11 (MOSI)

12 (MISO)

13 (SCK)

+5v (if required)

GND (for signal return)

On the Arduino Mega, the pins are 50 (MISO), 51 (MOSI), 52 (SCK), and 53 (SS).
In any case, MOSI at one end is connected to MOSI at the other, you don't swap them around (that is you do not have MOSI <-> MISO). The software configures one end of MOSI (master end) as an output, and the other end (slave end) as an input.
On some boards (like Leonardo, ProMicro — see above) the SS pin isn't exposed (rather it is connected to RX_LED). It is not possible to remap SS to another pin to be able to use those boards as an SPI slave as the AVR uses fixed SPI pins according to the datasheets (PB0-PB3 on 32U4).
Master example
#include <SPI.h>

void setup (void)
{

  digitalWrite(SS, HIGH);  // ensure SS stays high for now

  // Put SCK, MOSI, SS pins into output mode
  // also put SCK, MOSI into LOW state, and SS into HIGH state.
  // Then put SPI hardware into Master mode and turn SPI on
  SPI.begin ();

  // Slow down the master a bit
  SPI.setClockDivider(SPI_CLOCK_DIV8);

}  // end of setup

void loop (void)
{

  char c;

  // enable Slave Select
  digitalWrite(SS, LOW);    // SS is pin 10

  // send test string
  for (const char * p = "Hello, world!\n" ; c = *p; p++)
    SPI.transfer (c);

  // disable Slave Select
  digitalWrite(SS, HIGH);

  delay (1000);  // 1 seconds delay
}  // end of loop

Slave example
#include <SPI.h>

char buf [100];
volatile byte pos;
volatile bool process_it;

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

  // turn on SPI in slave mode
  SPCR |= bit (SPE);

  // have to send on master in, *slave out*
  pinMode (MISO, OUTPUT);

  // get ready for an interrupt
  pos = 0;   // buffer empty
  process_it = false;

  // now turn on interrupts
  SPI.attachInterrupt();

}  // end of setup

// SPI interrupt routine
ISR (SPI_STC_vect)
{
byte c = SPDR;  // grab byte from SPI Data Register

  // add to buffer if room
  if (pos < sizeof buf)
    {
    buf [pos++] = c;

    // example: newline means time to process buffer
    if (c == '\n')
      process_it = true;

    }  // end of room available
}  // end of interrupt routine SPI_STC_vect

// main loop - wait for flag set in interrupt routine
void loop (void)
{
  if (process_it)
    {
    buf [pos] = 0;
    Serial.println (buf);
    pos = 0;
    process_it = false;
    }  // end of flag set

}  // end of loop

The slave is entirely interrupt-driven, thus it can doing other stuff. The incoming SPI data is collected in a buffer, and a flag set when a "significant byte" (in this case a newline) arrives. This tells the slave to get on and start processing the data.
Example of connecting master to slave using SPI

How to get a response from a slave
Following on from the code above which sends data from an SPI master to a slave, the example below shows sending data to a slave, having it do something with it, and return a response.
The master is similar to the example above. However an important point is that we need to add a slight delay (something like 20 microseconds). Otherwise the slave doesn't have a chance to react to the incoming data and do something with it.
The example shows sending a "command". In this case "a" (add something) or "s" (subtract something). This is to show that the slave is actually doing something with the data.
After asserting slave-select (SS) to initiate the transaction, the master sends the command, followed by any number of bytes, and then raises SS to terminate the transaction.
A very important point is that the slave cannot respond to an incoming byte at the same moment. The response has to be in the next byte. This is because the bits which are being sent, and the bits which are being received, are being sent simultaneously. Thus to add something to four numbers we need five transfers, like this:
transferAndWait ('a');  // add command
transferAndWait (10);
a = transferAndWait (17);
b = transferAndWait (33);
c = transferAndWait (42);
d = transferAndWait (0);

First we request action on number 10. But we don't get a response until the next transfer (the one for 17). However "a" will be set to the reply to 10. Finally we end up sending a "dummy" number 0, to get the reply for 42.
Master (example)
  #include <SPI.h>

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

    digitalWrite(SS, HIGH);  // ensure SS stays high for now
    SPI.begin ();

    // Slow down the master a bit
    SPI.setClockDivider(SPI_CLOCK_DIV8);
    }  // end of setup

  byte transferAndWait (const byte what)
    {
    byte a = SPI.transfer (what);
    delayMicroseconds (20);
    return a;
    } // end of transferAndWait

  void loop (void)
    {

    byte a, b, c, d;

    // enable Slave Select
    digitalWrite(SS, LOW);

    transferAndWait ('a');  // add command
    transferAndWait (10);
    a = transferAndWait (17);
    b = transferAndWait (33);
    c = transferAndWait (42);
    d = transferAndWait (0);

    // disable Slave Select
    digitalWrite(SS, HIGH);

    Serial.println ("Adding results:");
    Serial.println (a, DEC);
    Serial.println (b, DEC);
    Serial.println (c, DEC);
    Serial.println (d, DEC);

    // enable Slave Select
    digitalWrite(SS, LOW);

    transferAndWait ('s');  // subtract command
    transferAndWait (10);
    a = transferAndWait (17);
    b = transferAndWait (33);
    c = transferAndWait (42);
    d = transferAndWait (0);

    // disable Slave Select
    digitalWrite(SS, HIGH);

    Serial.println ("Subtracting results:");
    Serial.println (a, DEC);
    Serial.println (b, DEC);
    Serial.println (c, DEC);
    Serial.println (d, DEC);

    delay (1000);  // 1 second delay
    }  // end of loop

The code for the slave basically does almost everything in the interrupt routine (called when incoming SPI data arrives). It takes the incoming byte, and adds or subtracts as per the remembered "command byte". Note that the response will be "collected" next time through the loop. This is why the master has to send one final "dummy" transfer to get the final reply.
In my example I am using the main loop to simply detect when SS goes high, and clear the saved command. That way, when SS is pulled low again for the next transaction, the first byte is considered the command byte.
More reliably, this would be done with an interrupt. That is, you would physically connect SS to one of the interrupt inputs (eg, on the Uno, connect pin 10 (SS) to pin 2 (an interrupt input), or use a pin-change interrupt on pin 10.
Then the interrupt could be used to notice when SS is being pulled low or high.
Slave (example)
// what to do with incoming data
volatile byte command = 0;

void setup (void)
  {

  // have to send on master in, *slave out*
  pinMode(MISO, OUTPUT);

  // turn on SPI in slave mode
  SPCR |= _BV(SPE);

  // turn on interrupts
  SPCR |= _BV(SPIE);

  }  // end of setup

// SPI interrupt routine
ISR (SPI_STC_vect)
  {
  byte c = SPDR;

  switch (command)
    {
    // no command? then this is the command
    case 0:
      command = c;
      SPDR = 0;
      break;

    // add to incoming byte, return result
    case 'a':
      SPDR = c + 15;  // add 15
      break;

    // subtract from incoming byte, return result
    case 's':
      SPDR = c - 8;  // subtract 8
      break;

    } // end of switch

  }  // end of interrupt service routine (ISR) SPI_STC_vect

void loop (void)
  {

  // if SPI not active, clear current command
  if (digitalRead (SS) == HIGH)
    command = 0;
  }  // end of loop

Example output

Adding results:
25
32
48
57
Subtracting results:
2
9
25
34
Adding results:
25
32
48
57
Subtracting results:
2
9
25
34

Logic analyzer output
This shows the timing between sending and receiving in the above code:

New functionality in IDE 1.6.0 onwards
Version 1.6.0 of the IDE has changed the way SPI works, to an extent. You still need to do SPI.begin() before using SPI. That sets up the SPI hardware. However now, when you are about to start communicating with a slave you also do SPI.beginTransaction() to set up SPI (for this slave) with the correct:

Clock speed
Bit order
Clock phase and polarity

When you are done communicating with the slave, you call SPI.endTransaction(). For example:

SPI.beginTransaction (SPISettings (2000000, MSBFIRST, SPI_MODE0));
digitalWrite (SS, LOW);        // assert Slave Select
byte foo = SPI.transfer (42);  // do a transfer
digitalWrite (SS, HIGH);       // de-assert Slave Select
SPI.endTransaction ();         // transaction over

Why use SPI?

I would add one preliminary question: when/why would you use SPI? A need for multi-master configuration or a very large number of slaves would tilt the scale toward I2C.

This is an excellent question. My answers are:

Some devices (quite a few) only support the SPI transfer method. For example the 74HC595 output shift register, the 74HC165 input shift register, the MAX7219 LED driver, and quite a few LED strips that I have seen. So, you might use it because the target device only supports it.
SPI is really the fastest method available on the Atmega328 (and similar) chips. The fastest rate quoted above is 888,888 bytes per second. Using I2C you can only get around 40,000 bytes per second. The overhead of the I2C is quite substantial, and if you are trying to interface really quickly, SPI is the preferred choice. Quite a few chip families (eg. MCP23017 and MCP23S17) actually support both I2C and SPI so you often can choose between speed, and the ability to have multiple devices on a single bus.
The SPI and I2C devices are both supported in hardware on the Atmega328 so you could conceivably be doing a transfer via SPI simultaneously with I2C which would give you a speed boost.

Both methods have their place. I2C lets you connect many devices to a single bus (two wires, plus ground) so it would be the preferred choice if you needed to interrogate a substantial number of devices, perhaps fairly infrequently. However the speed of SPI could be more relevant for situations where you need to output rapidly (eg. a LED strip) or input rapidly (eg. an ADC converter).

References

My page about SPI - also has details about bit-banged SPI, and using the USART to gain a second hardware SPI on the Atmega328 chip.

Serial Peripheral Interface Bus - Wikipedia

Arduino SPI library reference pages

SPI documentation at PJRC

SPI protocol - Sparkfun


How to program an Arduino Uno to collect data using a timer interrupt and analyze that data in matlab?

I've configured the timer differently making use of its UserData property. The timer will update the data every fixed period for a specified number of samples.
close all;
clear all;

% Some useful constants.
NUM_SAMPLES = 20;
PERIOD = 0.05;

global a;
a = arduino('com4', 'uno');

% Initialise data. It will be updated by the timer.
data.i = 0;
data.v1 = zeros(NUM_SAMPLES, 1);
data.v2 = zeros(NUM_SAMPLES, 1);
data.x = (1:NUM_SAMPLES) * PERIOD;

% Initialise timer for a fixed period for a specific number of samples.
t = timer;
t.ExecutionMode = 'fixedRate';
t.Period = PERIOD;
t.TasksToExecute = NUM_SAMPLES;
t.TimerFcn = @TimerCallback;
t.UserData = data;

% Run the timer and wait for it to complete.
start(t);
wait(t);
stop(t);
data = t.UserData;  % Retrieve the updated data.
delete(t);

% Plot voltage versus time.
figure(1);
plot(data.x, data.v1, '-', data.x, data.v2, '-');
xlabel('Elapsed time (s)');
ylabel('Voltage (V)');
title('Voltage Data');
st = sprintf("%0.3f seconds", NUM_SAMPLES * PERIOD);
subtitle(st);
legend('v1', 'v2');

function TimerCallback(obj, event)
    global a;
    obj.UserData.i = obj.UserData.i + 1;
    obj.UserData.v1(obj.UserData.i) = readVoltage(a, 'A0');
    obj.UserData.v2(obj.UserData.i) = readVoltage(a, 'A1');
end


Arduino does not make any sound when connected to laptop?

The Arduino will not make a sound, but probably you refer to the sound Windows makes when a USB device is connected?

Try (except for the tips already given by JRobert)

different USB port
reinstall Arduino IDE
disable/enable or reinstall driver in Control panel/hardware/system/USB devices


The easiest is to clear the entire screen (I'm sure there is a function for that).

What you also can do:

Create lines which are 16 characters wide and print them, so the old text is overwritten
More complicated: store the text that is written in two strings (one per line) and check where are not spaces, to overwrite it with spaces to clear.

You would have to do a performance/time check to see what works best.

If performance is not an issue (which I doubt), keep it simple and just overwrite the two lines (without a clear, assuming you call the clear function yourself).

Another solution is to keep the word Celcius always on the same location... this means you might have to change formatting:

_28.6 Celcius
__3.8 Celcius
_-12.3 Celcius

Where _ are spaces (so the word Celcius is always on the same location)


Non intrusive current sensor with unreliable (strange) readings

Every time you use a real clamp meter, you should zero it out before measuring.

The hall effect sensors you describe are the same way. There's magnetic pull from the earth and other sources that need to be corrected for. When you draw 5 or 10 amps, that noise is masked out. They are likely still apart roughly the same # of ma as the baseline reading.

Once you subtract the no-load load from each, maybe on startup, you should get a lot better readings in terms of accuracy and precision.


I presume you have boot loader on your Nano, so you can use your USB to serial, just wire (D0)TX->RX(USB), (D1)RX->TX(USB), GND-GND and supply power to the target Nano. You will need to reboot Nano just before the uploading the code. Uploading is same as usual.

Using other Arduino as ISP needs more wires as well as 2nd Arduino, so i would use above method.


What happens if I connect an external power supply, plus to GND and minus to VIN?

Some systems have protection against people connecting things in reverse.
Some don't.

On unprotected systems you MAY destroy the powered system and/or you MAY destroy the power supply - both these depend on happenstance, system design and luck.

Possibly worse - you may damage the target system in an inobvious way so that it subsequently behaves incorrectly or damages other equipment.

Systems which are designed to be protected may not be protected in all cases. eg if you have a "shield" connected that accesses the Vin pin outside the protection diode the reverse polarity voltage may damage the shield AND current may travel via the shield circuitry back into the Arduino via other connections.

Advice on You tube may just sometimes very very occasionally be wrong. Or more often.

If this "Reference Schematic"  is correct (as you'd hope it was) then Vin is connected to the "inside" of protection diode D1 - so D1 does not protect against reversed polarity. See lines and boxes in red.
Larger version of diagram here

D1 does protect against reversed polarity on "PWRIN".
How PWRIN relates to shield feeding I know not.


1 - Can i use Hardware serial pins with RS485 for 40ft distance, i tested code and it does work but i couldn't test that for 40ft. So not sure if it works or not.

Yes.

  2 - Is it good idea to use hardware serial pins for my project i explained, as i see plus and minus over internet and making me confuse. I see majority people recommend Hardware pins though.

Yes. SoftwareSerial is awful.

  3 - Is there limitation connecting multiple arduino nano with this approach, i only did this with 2 so far.

Yes. The MAX485 and similar chips can only handle up to about 30 devices on one bus. The exact number is in the datasheet for the chip.


Cannot receive data from GPS SD Shield V2-B

You need to set the jumps as per the instructions that came with the shield ...
PAGE4 : short jumpers TX and MRX .... and RX and MTX


The second trace looks like a pulse to me. With that kind of sensor you don't get the PQRST traces of an ECG - just a slight bump when you get a pulse.


Why cannot I input arrays as digitalWrite arguments?

You've written the for loop incorrectly.

for (byte i = 0; i >= 6; i++)   <-- ERROR HERE
  {
    digitalWrite(pins[i], one[i]);
  }

That first line should be for (byte i = 0; i <= 6; i++). i begins at zero, which is less than six, and the loop only runs while i is greater than 6.


How to control 2 servos at same time in sync?

If you have two RC servos that are always required to move together you can simply connect both control inputs to a single output.


What does the following code in Morse Code Arduino mean?

Step by step:

  struct node *root, *currentNode;

Pointer variables root and currentNode. Pointers to struct node.

  root = (struct node*)malloc(sizeof(struct node));

Allocate memory for a struct node and assign root pointer.

  root->value = '\0';
  root->next = 0;

Assign struct node members using the root pointer. Assign value member to character 0. Assign next to zero, NULL, i.e. often marks end of list.

  currentNode = root;

Last assign currentNode to point to the save value as root, i.e. the allocated struct node.

Next question?


Based on the link to the specifications, this is a "high speed, high torque" servo. Unfortunately, none of the information includes the maximum or typical current draw, though there are warnings to higher gauge wire than usual and to avoid long leads and Y-splitters.

These are indications that your power supply should be "beefy", and by the class of servos this is in, I would guess you need a supply capable of supplying 5V at up to 3 amps.

The "harder" the servo has to work to move, the more current it will draw. This servo wants around 5V, but 4.8V is acceptable from a 2S (2 series) LiPo battery pack.

4.8V, however, is not quite enough for a 5V Arduino at 16MHz (the standard speed). As long as all the Ground wires are connected together, you could have one battery pack for the Arduino and a 4.8V pack for the servo.

All that said, there are only 2 primary specification points of a power source -- Output Voltage and Max current. You should try to MATCH voltage ratings of a power source to the device being powered, and ensure the device being powered DOES NOT EXCEED the current rating of the power source.


How to utilize SPI Serial bus on a ATSAMD21G18?

Use the SPI API provided by Arduino (https://www.arduino.cc/en/Tutorial/SPITransaction) and the command format that the chip wants you to use based on the datasheet. Here's a bit of example code for SPI transaction. Though untested, it's what I understood from reading the datasheet. Written for an Adafruit Feather M0 express (uses SAMD21G18 MCU). For pinout see https://learn.adafruit.com/adafruit-feather-m0-express-designed-for-circuit-python-circuitpython/adafruit2-pinouts#logic-pins-2-8.

Also note that Analog Devices does provide Arduino-Code for similiar devices like LTC6803-2 but not for the -4. Still, you can look how they implemented a driver. See here

#include <Arduino.h>
#include <SPI.h>

/* pin setup */
int chip_select_pin = PIN_A2;
/* SPI pins labeled "SCK" "MO" "MI" on the Adafruit Feather M0 express board
 * are used implicitly.
 * PIN_SPI_MISO (22),  PIN_SPI_MOSI(23), PIN_SPI_SCK(24),
 * */

#define LTC6803_4_MAX_SCLK_FREQ 1000000
#define LTC6803_4_USED_SCLK_FREQ (LTC6803_4_MAX_SCLK_FREQ/2)

SPISettings settings(LTC6803_4_USED_SCLK_FREQ, BitOrder::MSBFIRST, SPI_MODE3);

void start_voltage_adc_conversion(){
    SPI.beginTransaction(settings);
    digitalWrite(chip_select_pin, LOW);
    //STCVAD
    //Start Cell Voltage ADC Conversions and Poll Status, with Discharge Permitted
    uint8_t tranfer_buf[2] = {
            0x10, //CODE
            0xB0 //PEC
    };
    SPI.transfer(tranfer_buf, 2);
    //wait for conversion, just a static time. at least 12 milliseconds.
    delay(20);
    digitalWrite(chip_select_pin, HIGH);
    SPI.endTransaction();
}

void read_voltages_1_to_4(){
    //trigger voltage conversion
    start_voltage_adc_conversion();

    SPI.beginTransaction(settings);
    digitalWrite(chip_select_pin, LOW);
    //transfer buffer must have 2 bytes for command
    //and 6 bytes for response (four 12-bit ADC values encoded in 6 registers CVR00..CVR05)
    //plus 1 byte for PEC from chip
    //Read Cell Voltages 1-4, "RDCVA", page 22
    uint8_t tranfer_buf[2 + 6 + 1] = {
            0x06, //CODE
            0xD2 //PEC
    };
    SPI.transfer(tranfer_buf, 9);
    digitalWrite(chip_select_pin, HIGH);
    SPI.endTransaction();

    //recover 12-bit ADC value from C1V[0]..C1V[11] from register values CVR00 and CVR01
    //see datasheet page 24
    uint16_t adc_cell_1 = tranfer_buf[2] | ((tranfer_buf[3] & 0B1111) << 8);
    //adc value to voltage conversion according to page 15
    float voltage_cell_1_millivolt = ((int)adc_cell_1 - 512) * 1.5f ;
    Serial.print("Cell voltage 1: ");
    //print with 5 digits accuracy
    Serial.print(voltage_cell_1_millivolt, 5);
    Serial.println(" mV");
}

void setup() {
    Serial.begin(115200);
    pinMode(chip_select_pin, OUTPUT);
    SPI.begin();
}

void loop() {
    read_voltages_1_to_4();
    delay(2000);
}


It seems like the math of arduino is off

If your program is basically working but gives you rounding errors, it can be that you are facing some problems related to conversion from floating-point to binary or reverse. It is a very common problem in computer science. For example, the decimal number 0.1 has no exact binary  representation, it is infinite. For more information, you can read these pages:

http://www.exploringbinary.com/why-0-point-1-does-not-exist-in-floating-point/
https://www3.ntu.edu.sg/home/ehchua/programming/java/datarepresentation.html

In order to solve your problem, you can try to apply appropriate rounding to your results and if possible avoid mixing different data types and use double only if absolutely needed (which I guess is the case in your application).


Passing reference to hardware between methods in custom class

I don't think you are creating instances of these classes correctly. Instead of:

CDSensors*     LSensors      = &CDSensors     (0);
CDSerialPrint* LSerialPrint  = &CDSerialPrint (0);
MPU9250_DMP   Limu = MPU9250_DMP ();

How about:

CDSensors LSensors (0);
CDSerialPrint LSerialPrint (0);
MPU9250_DMP Limu;

I can't get your code to compile, but what I suggest looks a lot simpler.

Is your intention here:

if (imu.begin() != INV_SUCCESS)
  imu.setSensors(INV_XYZ_ACCEL | INV_XYZ_GYRO | INV_XYZ_COMPASS);
  imu.setGyroFSR(2000);
  imu.setAccelFSR(2);
  imu.setLPF(188);
  imu.setSampleRate(100);
  imu.setCompassSampleRate(100);

.. to really be:

if (imu.begin() != INV_SUCCESS)
  {
  imu.setSensors(INV_XYZ_ACCEL | INV_XYZ_GYRO | INV_XYZ_COMPASS);
  imu.setGyroFSR(2000);
  imu.setAccelFSR(2);
  imu.setLPF(188);
  imu.setSampleRate(100);
  imu.setCompassSampleRate(100);
  }

The indentation suggests so.

  if I understood correctly the class is created on startup with

       CDSensors* LSensors = &CDSensors (0);

  and is then persistent.

LSensors is a persistent pointer but CDSensors (0) is a temporary object created for the purpose of doing an assignment. For example:

int foo = 2 + 3;

Now the compiler calculates 2 + 3 (giving 5), assigns that to foo, and then discards the temporarily-calculated 5 used to do the assignment.

In your case CDSensors (0) calls the constructor for CDSensors, creating a temporary object. Then the "&" operator takes its address (somewhere on the stack I would guess). This address is copied into LSensors. Then the object is destroyed because its lifetime is over. The compiler even warns you this is happening:

 CDSensors*     LSensors      = &CDSensors     (0);
                                                 ^
sketch_may07a:5: error: taking address of temporary [-fpermissive]

That means the pointer is now invalid because the underlying object (that it is pointing to) has now been discarded.

I've even seen people do something like this quite a bit:

     CDSensors LSensors = CDSensors (0);

This isn't so bad because pointers aren't involved, but it still involves making a temporary instance of the class, then copying that into LSensors, and discarding the original one.

This is how to make a new instance of a class:

 CDSensors LSensors (0);   // the actual class, not a pointer

Or if you want a pointer:

 CDSensors * pLSensors;  // a pointer to the class (initially NULL)

Then in setup you create the instance:

pLSensors = new CDSensors (0);


This is a C question, not an arduino question, but anyway:

From the man page:

DESCRIPTION
   The  strtok()  function  breaks a string into a sequence of zero or more nonempty tokens.  On the first call to strtok() the
   string to be parsed should be specified in str.  In each subsequent call that should parse the  same  string,  str  must  be
   NULL.

You are only calling strtok() once, so it only parses the first value. You need to keep calling it until there is nothing left to parse.


You have the wrong device address. You've included the R/W bit in the address, which you shouldn't.  An I2C address is only 7 bits, not 8.  Drop one bit:

const byte device=0b0100000; //default addrress of IO chip


Arduino - fuse setting problem on ATmega328P-PU

The chips configured with a bootloader would also have the fuses set for an external clock (the factory default is the on-chip oscillator). Without an external clock they won't work.

I have a sketch that uploads files that also can provide an external clock for this eventuality.

As mentioned on that page an 8 MHz clock is provided on pin D8 of the programming board, so you can connect to D8 on the Uno which you are running the sketch on to pin 9 on the actual Atmega328P chip.

Alternatively find a 16 MHz crystal or resonator and connect that between pins 9 and 10 of your Atmega328P which will provide the clock that it is expecting. If you use a crystal you should also run 22 pF capacitors between each leg and ground, like in this image:


It sounds like this is nothing to do with an Arduino, just a general Electrical/Mechanical engineering question that you want to control from and Arduino.
I think you wan a device that when signalled by your Arduino can extend itself by up to 2 inches.

If that is right then I think what you are looking for is a Linear Actuator.  There are plenty out there and some do handle the small stroke you want, but most of them appear to be 9 to 12V.  This means you would require a Darlington transistor or relay to control them from an Arduino.

If you require an extremely precise stoke length then I would recommend a stepper motor with a screw axel.  This would allow you much finer control over how far you pushed, but it would impose limits on what you could do and how it could be mounted.

Can you provide more details on what you want to move?
List item
Is it heavy? Do you need lots of Torque?
Are you pushing straight or do you need to push in an arc (i.e. a door)?
What voltage supplies do you have available?
How fast do you want it to move?
Do you want it to move exactly the same distance every time?

The more info you can provide the better, but in answer to your original question Yes, it sounds like there might be so you plan is still on the rails.


I've got to ask here.  Why use a stepper?
This would be fairly easy with two button switches and a regular DC motor.  One switch provides power to drive the motor CW the 2nd motor drives it CCW.

You would still need to choose a motor with the right torque but IMHO this method would be WAY easier than using a stepper, and arduino, writing code, etc.


Why does static member std::map reset ESP8266 when outside the .ino file?

What happens if the Test() constructor is run before the map constructor? This is the problem: you are assuming order of execution.

Use a Singleton pattern or init() member function to force the ordering that is required.

Cheers!


If you don't care much about quality then all you need is two capacitors and a resistor. Use PWM to create the audio (there is a timerpcm pr something library that will do it). The resistor and pne capacitor form a low pass filter for the PWM, and the other capacitor removes the dc offset.

----/\/\/\----+----||------
              |
             ---
             ---
              |
              _
              -


Why not create a global brightness variable (e.g. cBrightness) so that you can adjust the brightness accordingly when the time comes? With a global variable, you can still maintain the brightness of the LED even after it exits the start() function.

For the start() function, you can include one argument (int/bool type variable) in the function to determine when to perform the brightening or dimming of the light depending on the RTC timing.

void start(int st)
{
  if(st==0)
  {
     //Brightness decrement function here
  }else if(st==1)
  {
     //Brightness increment function here
  }
}

For the brightness decrement function, it is the opposite of the increment function:

for (int i = 255 ; i >= 0; i--)
{
    analogWrite(led, i);
    delay(((fadeTime * 60000)/306));
}

To summarize, the code could look something like this:

#include <DS3231.h>

//Set Variables
int fadeTime = 15; //Fade Time
int onHour = 12; //Light On Hour
int onMin = 00; //Light On Minute
int offHour = 19; //Light On Hour
int offMin = 00; //Light On Minute
int led = 9; //Set pinout with with PWM
int cBrightness = 0;  //Current brightness

DS3231  rtc(SDA, SCL);
Time t;
void start(int st);

void setup()
{
  pinMode(led, OUTPUT);
  rtc.begin();
}

void loop()
{
  t = rtc.getTime();

  // Send Day-of-Week
  Serial.print(rtc.getDOWStr());
  Serial.print(" ");

  // Send date
  Serial.print(rtc.getDateStr());
  Serial.print(" -- ");

  // Send time
  Serial.println(rtc.getTimeStr());

  if (t.hour == onHour && t.min == onMin) //Check Time
  {
    start(1);
  }else if (t.hour == offHour && t.min == offMin)
  {
    start(0);
  }
  //Maintains brightness
  analogWrite(led, cBrightness);

}

void start(int st)
{
  if(st==0)     //Will decrement in brightness
  {
   for (int i = 255 ; i >= 0; i--)
   {
    analogWrite(led, i);
    delay(((fadeTime * 60000)/306));
   }
   cBrightness = 0;

  }else if(st==1)   //Will increment in brightness
  {
   for (int i = 0 ; i <= 255; i++)
   {
    analogWrite(led, i);
    delay(((fadeTime * 60000)/306));
   }
  cBrightness = 255;
  }
}


How to find the MAC address using NodeMCU when connecting to WiFi?

I don't believe you have an Wiznet Ethernet module connected to your NodeMcu. Ethernet library is for the Wiznet chips for wired LAN. You want to use the WiFi of the NodeMcu. For that the esp8266 core has the ESP8266WiFi library. It has the same API as other WiFi libraries based on Arduino WiFi library. So you can modify the WiFi examples of the Arduino pubnub library. Only change #include <WiFi101.h> to #include <ESP8266WiFi.h>. (And remove #include <SPI.h>.)


I had a similar problem. I solved it by using an oscilloscope to measure the arming sequence of an out-of-the-box RC remote controller and receiver.

The arming sequence through the controller-receiver was like this:

Connect ESC to battery (arduino is connected to signal and ground prior to this)
Wait for 3 beeps
Set the throttle to the lowest possible
Wait for another beep

I then adjusted my arduino code to output the same(similar) sequence.

Here is the code:

#include <Servo.h>
#define POT A0

Servo m1;

void setup() {
  m1.attach(6);
  Serial.begin(9600);
  delay(50);
  Serial.println("Serial ready:");
  arm(m1);
}

void loop() {
  int potValue = analogRead(POT);
  int s = map(potValue,60,930,1200,1700); //Map the pot values to motor values

  m1.write(s);
  Serial.println(s);
}

void arm(Servo m){
  Serial.print("Arming.");
  m.write(0);
  delay(100);
  m.write(1224); //A value at which the motor starts turning
  delay(2000);
  m.write(1024); //A value at which the motor stands still
  delay(3000);
  Serial.println(" Armed!");
}

You can also see a video of the whole thing in action here: A2212/13T brushless motor on a pivoting arm

EDIT: Further testing shows, that it suffices to output a low non zero value to arm this ESC. Simply doing Servo.write(1024); until you hear the confirmation beep seems to work.


How to implement multiple LED modes in a sketch with potentiometers?

Since you already know how to hook up a pot and read it's value, it's quite simple. You already have it hooked up in a voltage divider configuration and are getting a 10 bit (0-1023) value using analogRead(), you just need to decide what to do with it.

Assume potVal has the value of the pot.;

if (potVal < 256) {
    // Pot is one quarter turn or less
} else if (potVal < 512) {
    // Pot is between 256 and 512, so its more than quarter but less than half
} else if (potVal < 768) {
    // Pot is between half and 3/4ths of the way there
} else {
    // Pot is greater than 3/4 of it's full range
}

So I have broken it down into four quadrants for you, but you can do it however you like.


How does one **get** attributes for SD files?

You need to get an SdFile object for your file then use the SdFile::dirEntry method to get the directory entry for the file.

The directory entry (struct directoryEntry) has the timestamps.


Interrupting a servo sweep with a force sensor

I've written this code without access to a compiler,
so there might be errors. Use it as an idea how to solve the quest. Hopefully the comments are helpful. Don't hesitate to ask if you do not understand or correct me if you see an error.

#include <Servo.h>

Servo myservo;

// end positions of the servo
// declared as constant values
const int minPos = 10;
const int maxPos = 180;

int servoAngle;

int force;
char code;

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

  myservo.attach(4);
  // move the servo to minPos
  // or whatever you want/need
  servoAngle = minPos;
  myservo.write( servoAngle );

  // PPK: keep code as simple as possible -> sweep removed

  // PPK: removed - this makes no sense here
  // code = Serial.read();
}

void loop()
{
  // PPK: here you check if data is available (I added "> 0")
  if( Serial.available() > 0 )
  {
    // PPK: but you did not read the data
    // Let's do it
    char newCode = Serial.read();
    If ( newCode == '0' || newCode == '1' )
    {
      // only "0" and "1" are valid codes
      code = newCode;
    }
  }

  if ( code == '0' && servoAngle > minPos )
  {
    servoAngle--;
    myservo.write( servoAngle );
  }
  else if ( code == '1' && servoAngle < maxPos )
  {
    force = analogRead( A1 );
    Serial.println( force );
    if ( force > 300 )
    {
      servoAngle--;

      // PPK: the next line is only necessary if you want the
      // servo to go towards the min position
      // if a force > 300 is detected
      // remove the line if you wish to
      // hold the servo at the position where
      // the force exceeds 300
      code = '0':
    }
    else
    {
      servoAngle++;
    }
    myservo.write( servoAngle );
  }
  // a little delay to slow down the servo
  // remove it if you want
  delay( 10 );
}

EDIT

If you intend to stop the servo if force > 300, you can add a flag that indicates the exceptional state.

#include <Servo.h>

Servo myservo;

const int minPos = 10;
const int maxPos = 180;

int servoAngle;

int force;
char code;
int flagServoStopped = 0;

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

  myservo.attach(4);
  servoAngle = minPos;
  myservo.write( servoAngle );
}

void loop()
{
  if( Serial.available() > 0 )
  {
    char newCode = Serial.read();
    If ( newCode == '0' || newCode == '1' )
    {
      code = newCode;
    }
  }

  if ( flagServoStopped == 1 && code == '1' )
  {
    // The servo is frozen as long as the stop flag is set and
    // you have not entered a '0'.
    // leave the loop
    return;
  }

  // in case `code = '0'`, reset the flag if it is set.
  flagServoStopped = 0;

  if ( code == '0' && servoAngle > minPos )
  {
    servoAngle--;
    myservo.write( servoAngle );
  }
  else if ( code == '1' && servoAngle < maxPos )
  {
    force = analogRead( A1 );
    Serial.println( force );
    if ( force > 300 )
    {
      flagServoStopped = 1;
    }
    else
    {
      servoAngle++;
      myservo.write( servoAngle );
    }
  }
  delay( 10 );
}


Michel Keijzers pointed out the issues you have in your code. But then
there is also an issue with your circuit: if you press any of the push
buttons, the analog input pin gets connected to one of the nodes of the
resistor ladder, and you get a well defined voltage reading. Good.
However, if none of the buttons is pressed, the input is not connected
to anything: it is floating. In this case the reading you get is
unpredictable, as it depends on parasitic influences of stray
capacitances, environmental noise, etc. You should modify your circuit
to make sure that the input voltage is well defined even when no button
is pressed.
Then, regarding the program, I recommend you remove everything after
Serial.println(temp);. Just make it work like this, and take note of
the readings you get in each case. Make sure they are consistent. Once
you know the values you expect, you can decide on the threshold to
apply, which should be about halfway between the typical readings. E.g.
if the two lowest values you get are 0 and 240, you would set a
threshold at 120.


Can Bluetooth HC-05 Module detect other modules and relay data back to phone?

Correction - BLE devices give off RSSI, but not Bluetooth. BLE devices can be used as iBeacons. I have settled on the HM-19 Bluetooth 5.0 module. A phone acts as an iBeacon scanner.


The new Twitter 1.1 API requires OAuth authorization over SSL, for which Arduino is under-powered.

You will need to write a proxy application, which would parse the tweets and then send a RGB color value to your Arduino.

You should split your project into three parts.

Retrieving tweets with the Twitter API.
You can get some library to do it for you.
Communicating with your Arduino.
Just try to send an arbitrary color to your Arduino over internet.
And finally joining first two pieces of code together.

And if you get stuck somewhere, you can always ask for help here on StackExchenge.


Press on pressure sensor once, turn on LED for 6 seconds

Sensors which give a range of outputs need to have their outputs processed using a technique called hysteresis.  That is, normally, the turn on threshold is higher then the turn off threshold.

For example, the thermostat in your home uses hysteresis when controlling your HVAC system.  Otherwise your thermostat would constantly be turning on and off your HVAC system likely causing an early failure.

Here is a stackexchange Arduino question about hysteresis.


Once you know how to connect to any server and send messages to it, retrieveing emails is just a matter of sending right messages (=commands).

Here below follows an "IMAP tutorial", i.e. guide to which commands to send to an IMAP server to search and retrieve messages.

Note: once you connect to the IMAP server, the first command to send is the login command:

foo login user password

"foo" is just a session identifier, not a keyword. "login" is the keyword.

Once you get the welcome message, you can start sending more commands:

Select the proper folder:

. SELECT "INBOX"

Look for desired message (strings are always considered substrings, so no wildcards are needed):

. SEARCH FROM "user@example.org" SUBJECT "some keywords here"

This will result in list of matching messages, with search results formatted as follows:

* SEARCH 5 10 456

This means messages n.5, n.10 and n.456 match the query.

If examining just the subject (which may contain keywords and switch as required) is not enough, the whole body can be retrieved, both marking the message as read or leaving it untouched:

. FETCH 5  BODY[TEXT]

or

. FETCH 5  BODY[TEXT].PEEK

End IMAP session with:

. logout

For experiments from Windows using telnet:

telnet mailserver.domain.com 143

Reference:

https://www.skytale.net/blog/archives/23-Manual-IMAP.html


As Majenko says in their comments, a pin that's not connected to anything "floats" and gives unpredictable results.

You either need to connect such a pin to ground through a "pull-down" resistor or to +5V through a "pull-up" resistor. (10KΩ is a good value to start with.)

If you connect the pin to +5V through a pull-up resistor then you would ground it to change it's state. In that case the pin reads HIGH normally, and drops to LOW when triggered. Note that the Arduino has a special mode, INPUT_PULLUP, that connects the pin to an internal pull-up resistor. In that case you don't need an external pull-up resistor.

In your case, connect the pin to ground with a 10KΩ restistor. Then when you want the pin to go high attach the pin to +5V. That will swamp the connection to ground and pull the pin up to just below 5V.