When it comes to UART to RS485 communication, what is the difference between the 'MAX485' and the 'HW-0519' module?

I did a bit of research and found others who use this particular component for their RS485 communication purposes. It is difficult to get clear info because the device goes by different names and the most commonly used name is MAX485 (name of the IC), which is used interchangeably for both the components shown in the question.
It seems the more I search for the 'HW-0519', the more names I find for it. So far, it goes by the name 'MAX485', 'XY-017', and 'XY-K485'. A clear advantage for this 'HW-0519' is that it does not require D or R enabling, just straightforward Tx and Rx. It also has LEDs to show the data transfers. I found a project that used this module here. I am unsure about their pin connections from the ESP-32 though. It looks like they've connected the ESP-32's TX2 to the HW-0519's Tx, and the RX2 to the Rx. I thought it should be the other way around.


how long should interrupting signal last?

If edge or toggle interrupt is selected, pulses that last longer than one clock period will generate an interrupt. Shorter pulses are not recommended to generate an interrupt.

Source (page 91, chapter 17.2.1 "External Interrupt Control Register A")


Basic Arduinos have no support for floating point in sprintf and related functions.
Instead you have to use dtostrf() to build up a string block by block.
However there is no benefit to building a string then outputting to serial "in one instance" compared to outputting the data a bit at a time.  Serial is slow. Very slow. When you "output" data to serial you aren't outputting data. You're merely putting the data into a buffer to be sent when it's possible.
In effect, by using multiple Serial.print() calls, you're building up the string to send in the Arduino's internal serial TX buffer.
By building the string first all you're doing is creating a buffer to copy data into a buffer to send it through serial. It's redundant, wasteful, and utterly pointless.


Beware, the industry standard pinout for CAN on DB9 connectors is different to what Sparkfun use on their shield:

pin 3/5 CAN bus shield schematic
pin 2/7 (Vector tools for example).

Which software have you been using on the Arduino? Any additional info on the ECU you're using, and the wiring in your system?


How do I know the IP address assigned to an ESP8266?

If you give your board a name with

WiFi.hostname("MyESP8266");

(for example) you can then look on your router in the section that lists DHCP assignments (on my Netgear it's Attached Devices). That should then show you the IP address of all the attached devices, including the ESP8266 which you will easily identify by its name.

Another option is to use mDNS. Look at some of the examples that come with the ESP8266 core and libraries to see how.


Just spotted this, but if any one else finds it: You have one CAN speed set to 125kb on MCP2515 the other to 100kb on the VP230.
That's why you won't get anything!
Mark


Programming arduino using avrdude from command prompt

can't open device "COM41": The system cannot find the file specified.

This means there is no device at COM41. This may be due to 2 reasons:

You may not have connected your arduino. If this is the case then you please connect the arduino and retry
Your arduino might be on a different COM port. If this is the case, then, go to device manager and check your arduino's COM port and replace COM41 with that and retry.


Does the Arduino deteriorate after shorting the voltage regulator?

Of course, if you can upload the code, you can continue to use it ;)

Even if the Arduino is cheap, it is really reliable. There are always some short circuit protections.

The Voltage Regulator (I think it is a simple LM1117) has a overcurrent protection too (see: http://www.ti.com/lit/ds/symlink/lm1117.pdf)

So, don't worry. You can continue, continue and continue to use it...

Edit: just a note: never drain more than 50mA on an output. This will destroy the pin on your Arduino.


config file for Arduino Uno installed on Raspberry PI

In Linux you can move things around in different ways. For example:

Hold ALT and click and drag anywhere in the window. The whole window will move and you can get to the edge to resize it.
Press ALT-Space then M and you can use the cursor keys to move the window around
Press ALT-Space then X and it will maximise the window to the screen size


Power Supply Problem with Arduino Yún: Using a log USB cable

The USB specification limits the length of a cable between two devices to 5 meters. When you make a longer cable, you're going out of spec, which means it is not guaranteed to work anymore.

Since you're only supplying power, the issue is (as you have guessed) the voltage drop in the cable. However, the voltage drop will depend on how much current Arduino is consuming at any given moment. Supplying it with a higher voltage without a converter is dangerous, because it will lead to overvoltage you won't be able to control.

I'd suggest trying better cables first: thicker and stiffer cables have thicker wires, and may have less voltage drop. You can also make your own cable (provided you can solder) using only two thick wires for power.

The ultimate solution, like you said yourself, is to deliver higher voltage over the wire (12V would do) and install a power converted (12V to 5V) near your Arduino. That way, the voltage drop in 5V line will be small, and the voltage drop in 10m 12V line will be compensated by the converter. Actually, the intermediate voltage may be higher: you can simply drop a mains line (220V or whatever you have) to your weather station and place the same USB charger near the Arduino.


Your uBlox LEA 6H is most likly configured to use the UBX binary protocol and not NMEA at all. This protocol, as well as how to switch your LEA 6H between NMEA and UBX is in this document, from the uBlox website:
http://www.u-blox.com/images/downloads/Product_Docs/u-blox6_ReceiverDescriptionProtocolSpec_%28GPS.G6-SW-10018%29.pdf

You may be able to use the code from the ArduPilotMega project to communicate in UBX, they use the UBX protocol and the code is open source, but I can't guarantee its very good quality.


This is because the output of the serial is buffered. It's still sending the first bit of data while you change the baud rate - and from then on it's just a complete mess.

You need to force it to finish sending before you can change the baud rate by using Serial.flush():

void setup() {
  Serial.begin(115200);
  Serial.println("Hello");
  Serial.flush();
}

void loop() {
  Serial.begin(115200);
  Serial.println("world");
  Serial.flush();
  Serial.begin(9600);
  Serial.println("world");
  Serial.flush();
}

That will wait after each print until all the data is sent out "onto the wire" before changing the baud rate for the next print.


Issues with Stacking Ethernet shield and USB Host shield

Both shields are SPI devices, and both shields seem to be hard-wired to use D10 as the chip select line.

In order for you to use both shields at once you will have to either modify one of them or connect the shield via jumper wires.

You will need to change the chip select connection on one of the shields from D10 to some other pin that is not currently used, and then modify your software (or the library) accordingly.


I want to get incomming call number and compare it

The Arduino Serial class member function readString() has a builtin timeout. The function will return on timeout. The default timeout period is 1000 ms. The timeout can be set with setTimeout().

The sketch needs to filter out empty lines (timeout). This can be done by adding a check of the string length. See below for an example of checking:

void loop()
{
  String d = Serial1.readString();
  if (d.length() == 0) return;
  Serial.print(d);
  if (d.indexOf("xxxxxxxxx") >= 0) {
    Serial.println(": call is from saved number");
  }
  else {
    Serial.println(": call is not from saved number");
  }
}

Cheers!


Why does a pull down resistor configuration not destroy the pin it's connected to?

When you have a pin in INPUT mode it is high impedance. That means that to all intents and purposes, to the outside world, the pin is not connected to anything internally.
In reality it is, but that internal connection is of such a high impedance (i.e., resistance) that it is almost equivalent to an open circuit.
It's simplest to think of an input pin as a voltmeter.  A pulldown resistor and button would look like this:

simulate this circuit – Schematic created using CircuitLab
When the button is opened the voltmeter reads zero, because one end is connected to ground, and the other end is connected to ground through the resistor.
However when you press the button the voltmeter reads the voltage across the resistor - that is, 5V - because one end is connected to ground and the other to 5V, with a resistor across it.
If you don't have the resistor then the voltmeter can't measure anything when the button isn't pressed - it's just waving around in the air without a clue what it's doing - and a wire waving around in the air is called an antenna...
The Arduino is that voltmeter. All it does is detect the voltage at the pin, it doesn't conduct any (or only a very very tiny amount of leakage) current through the pin.
Now the possibility of a short circuit comes when you set the pin to OUTPUT. If you drive the pin LOW then the pin is essentially connected to GND, and pressing the button will connect the 5V straight to GND through the LOW-driven IO pin.


About the fingerprint sensors from mobile phones: You might find the answers to this question useful. They explain in detail, why it is not really worth the effort to try interfacing such a fingerprint sensor with Arduino.

  How to use any module that has no library for arduino?

You need to read the datasheet of the module. It should explain in detail, how the module is used. When you understood, how it works, (and understanding it is really really important) you can start implementing it in code, for example by writing your own library. A library is just a wrapper around the interfacing code for that module. If the module uses common used interfaces or is even a commonly used component, you can often stand on the shoulders of giants by making use of other libraries in your library (for example using the Wire library in a library for a specific I2C sensor). That makes it easier.

  But how do they do it, and how do they know about microcontrollers and IC's that were never taught to them in any degree or course?

The engineers don't get taught to use specific controllers or ICs. They get taught the fundamental principles, including common interfaces like I2C, SPI, UART, I2S ... . In the end it all comes down to the datasheet of a component. It should explain all details, that are needed to use the component correctly, or at least reference to further documents. For example most microcontroller datasheets directly explain, how I2C is implemented in these microcontrollers. You can use that to implement I2C communication, even without a preexisting library. Yes, that can be a tedious and complex task, but it is totally possible. Keep in mind, that most Arduino libraries are not written by the manufacturer of the used component, but by third party people (sometimes the community, sometimes resellers like Adafruit, e.g.).

I would say "it is not rocket sience", but yes, it can be rather difficult to dig into the very detail of interfacing a component. Without considering myself an especially smart guy, I'm writing a library for multi-master I2C communication on Attiny's (without having any degree in that field). I could start with code from others, which made the entry easier. But it also involves much time, to dig into it, write the code and test it correctly. It is difficult, but it is possible.

  And by chance, if an IC or microcontroller is found then I barely understand the datasheet or the documentation which was written in Chinese or some other language.

Good manufacturers and resellers provide a datasheet in english for their products. That cannot be said for every product, that you can purchase. Writing documentation takes time and thus costs money. Chips directly from China (where most electronics is produced these days) might have less good or no documentation at all, though these chips are often way cheaper. As a hobbyist you should stick to the good documentated components, if you don't want to really dig into it.

  the IC's and Chips that they have on their PCB board were never found on google

PCB designs are only found in the internet, if they are published under some open source license (or if they were illegally leaked by someone). If a company doesn't want to publish it's product designs, that is totally ok.

About the components in consumer electronics: I think you refer to that the chips often don't have a googleable product number/marking to find a datasheet. That is because often these chips are custom chips, made maybe only for this company or even this specific product. Why would they want to publish a datasheet for it? They are not meant for public use for all. The design of components is often a good kept secret, that the companies are not willing to share, since it generates their revenue.

Hobbyists and small companies use publicly available, good and publicly documented parts to make their life and investment in the project easier. Big companies can easily hire people to design a custom chip, that will only contain the needed features. (With mass produced products you can save money this way, by not always needing to buy even the unused resources of a standard controller). Another reason to use a custom (maybe even a not programmable) chip is to keep the code in it secret.

All in all keep in mind, that the hobbyist world of Arduino and the world of consumer electronics like smart phones are rather different. Sure, they rely on the same principles, but the way, how things are done and created, is very different.


There is no absolute "best" way, there is only the way that "works best for your situation".

In a nutshell, the different methods that I can think of, and their pros and cons, are:

Simple HTTP GET with parameters

Quick to implement, light weight, but not very secure or robust. Perfectly fine for things like "send the temperature once a minute" etc, but crafting very long GET requests with lots of parameters can severely impact on both your RAM and your sanity.

HTTP POST request

Like the GET request it's fairly simple to implement, but needs more RAM since you need to know the size of the data you're sending first so you can send a Content-length header.  You can send much more that way though, assuming you have the resources for it.

SOAP

This is basically HTTP POST but with a specially XML formatted body.  It has the advantage that it's a standard protocol for transferring data and commands around the place, so there are plenty of resources to help you.  The main problem is crafting the XML at the Arduino side.

Custom TCP

Connect to a special port to communicate with your own software.  You define all of the protocol, but you have to write all (or most) of the software too.  This can be more like a serial connection to your computer but through the network.  Good for sending larger amounts of data, such as images from a camera, etc.

Custom UDP

If you want to send lots of small values very frequently this is probably the best bet.  Harder to implement than most of the others, but the light-weight nature of UDP means you can send data much more rapidly.  Of course, with UDP, you run the risk of losing packets since it's very much a "fire and forget" protocol - you send a packet and hope it gets there.  Fine if you don't mind missing the odd bit of data, say for higher speed temperature logging.  Of course, you have to write the server side software yourself, but there's plenty of resources to help you with that online.

So it's really not a case of "best" but "most suitable".  Define what the data is and how often you want to send it, then think about how complex you are willing to get with your programming.

Nine times out of ten a simple HTTP GET request fits the bill.


Disable other buttons while one of buttons is pressed

The best solution for this is a finite state machine. There are lots of tutorials on state machines, just google.

Finite state machines are a very important concept in coding. You will find the need for them everywhere. Do yourself a favour, and read up about them, practice them, understand them, love them. Understand when they will be useful, and when they are not. If you do not, you will be back here shortly, with another question, which could also be solved by a finite state machine.

I strongly recommend you use this task as a practice task for learning about finite state machines.

Note also that, in electrical circuits, you frequently get bounce - when you push a button, your arduino will see many "button presses" (from off, to on, back to off), until it settles down. See http://blog.kennyrasschaert.be/images/20140401/Bouncy_Switch.png for example. A state machine can also help you with this.

If you don't want to learn about FSMs, read on:

initialise last_button_pressed to 0 (meaning no button pressed)
if last_button_pressed>0
   if not(is_button_pressed(last_button_pressed) then
      last_button_pressed=0
else (no button is pressed)
   for each button_to_check (1,2,3)
      if last_button_pressed=0 and is_button_pressed(button_to_check) then
         last_button_pressed=button_to_check


RF receiver for integer only, how to cast uint8_t to int?

buf is a pointer to the received bytes. Try value = buf[0]; instead.


Call a class method from inside the same class

You need to include roundto() in your class declaration, e.g. something like this:

class cSpeedOfSound {
public:
    cSpeedOfSound(float *i,float *C);

private:
    float roundto(float x, float dp);

    float *C;
    float *a;
    float *i;
};

In C++, class structures are fixed. You can define the body of a function almost anywhere, but all member functions/data must be specified in the original declaration.

As a side note, it's worth pointing out that you have a naming conflict in your code. You have member variables called i and C, and you have totally separate function parameters called i and C. The compiler won't complain about this (the function parameters will simply mask the member variables), but it may not do what you expect.


Changing parameters of pulseIn() to sense different materials

pulseIn just returns the length of a pulse on a pin. That has nothing to do with materials and can have no concept of materials. It is just time. You cannot change time just to suit different materials.

Instead if you want to calculate the distance depending on different materials you need the actual time of the pulse to then calculate the distance in different ways.

That is down to your sketch to do that calculation using the time provided by pulseIn and your own adjustment values.


The ESP8266 doesn't have a hardware Two Wire Interface. I²C is done in software, so you can use any 2 pins, as long as you specify them in your code using Wire.begin(SDA, SCL).

My guess would be that there's another problem. 65500+ sounds like an integer overflow, for example. ((uint16_t) -1 == 65535)


What are the current limits on an Arduino Micro?

It's in the notes in section 29.2:

  Although each I/O port can sink more than the test conditions (20mA at VCC = 5V, 10mA at VCC = 3V) under steady state
  conditions (non-transient), the following must be observed:
  ATmega16U4/ATmega32U4:
  1.)The sum of all IOL, for ports A0-A7, G2, C4-C7 should not exceed 100 mA.
  2.)The sum of all IOL, for ports C0-C3, G0-G1, D0-D7 should not exceed 100 mA.
  3.)The sum of all IOL, for ports G3-G5, B0-B7, E0-E7 should not exceed 100 mA.
  4.)The sum of all IOL, for ports F0-F7 should not exceed 100 mA.
  If IOL exceeds the test condition, VOL may exceed the related specification. Pins are not guaranteed to sink current greater
  than the listed test condition.
  Although each I/O port can source more than the test conditions (20mA at VCC = 5V, 10mA at VCC = 3V) under steady
  state conditions (non-transient), the following must be observed:
  ATmega16U4/ATmega32U4:
  1)The sum of all IOH, for ports A0-A7, G2, C4-C7 should not exceed 100 mA.
  2)The sum of all IOH, for ports C0-C3, G0-G1, D0-D7 should not exceed 100 mA.
  3)The sum of all IOH, for ports G3-G5, B0-B7, E0-E7 should not exceed 100 mA.
  4)The sum of all IOH, for ports F0-F7 should not exceed 100 mA.

Note that the device will likely not fail if these are exceeded, but the rest of the numbers in the table may no longer apply.


Why does DHT-library (and others) only allow one object instance?

There is nothing wrong with the library. It does not allow just one object instance.

What is wrong is your way of using it.

It, and many other libraries, specify the pin numbers and other (under normal usage) static data in the constructor. You want to have two objects then create two objects.

But it seems you want to change that static data. So you need to construct differently.  Instead of statically declaring your objects you need to be dynamic. Use new and delete.

DHT *myDHT = NULL;

myDHT = new DHT(4,5);
// do something
// change pins
delete myDHT;
myDHT = new DHT(6,7);


I just scanned over the TAPR and CERN open hardware licenses and I didn't see such a provision. My quick take on OHLs is that they are specifications for building the hardware - and therefore, information - not the hardware itself. And it only makes sense when we consider the incredibly expensive and complicated (from an experimenter's point of view) infrastructure that is a chip foundry necessary to create the kinds of hardware we take for granted and have reduced to commodity parts, CPUs, & MCUs being a prime example.

Thus "Arduino" is an open source specification for building microcontroller boards or board-sets based on ATMEL MCU chips, as well as the products of the Italian company SmartProjects. That is why there are so-called Arduino clones, otherwise, why wouldn't any clone of an Arduino be an Arduino?


The interval variable is unsigned long.

In this example, we are using int that are 4 bits long (just to keep thing short) just to subtract 1 from 0:

    0b0000
   -0b0001
    ------
    0b1111

That is normal arithmetic, but in binary.

The result 0b1111 can read as a signed int, in which case we read the value '-1', or you can read as unsigned, and you read it as '15'.

The same thing is working in your case, only that your int are 32 bits long.

The unsigned keyword is not a promise that "0-1" will produce "0". It only indicates that whatever bit configuration is inside that variable, it will be treat as a positive value.


I tried the code from the link you posted and it worked:

struct Gyro_data_structure
{
    char command_name[6];
    int gyro_X;
    int gyro_Y;
    int gyro_Z;
};

struct Gyro_data_structure Gyro_data = {"Hello", 48, 49 , 50};

int size_gyro = sizeof(struct Gyro_data_structure);

void setup()
{
  Serial.begin(9600); // opens serial port, sets data rate to 9600 bps
}

void loop()
{
  send(&Gyro_data);
  Serial.println();
  delay(1000);
}

void send (const Gyro_data_structure* table)
{
  Serial.write((const char*)table, size_gyro);  // 2 bytes.
}

bool receive(Gyro_data_structure* table)
{
  return (Serial.readBytes((char*)table, sizeof(Gyro_data_structure)) == sizeof(Gyro_data_structure));
}

I changed the float type to int for easy representation. When you run the code the serial window will show: Hello012

Because Arduino IDE serial window shows ASCII characters. 0's ASCII value is 48 and so on.

Update

It depends on what you want from the read function. Let's break down what Michaël Roy's implementation is doing. First, he reads sizeof(Gyro_data_structure) number of serial bytes and put it in the variable that table points to:

Serial.readBytes((char*)table, sizeof(Gyro_data_structure))

The 2nd argument of readBytes() takes how many bytes you want to read. Also readBytes() return how many bytes it read. Let's say we stored that number in return_bytes. In the next part he did:

return (return_bytes == sizeof(Gyro_data_structure))

He is checking if the number of bytes readBytes() read is the same as the size of  Gyro_data_structure. If it is not, then return false.

This just tells you if you read more or less than what you are supposed to read. Regardless of true or false, the actual bytes that were read will be in the variable that you passed to the receive() function.

If you don't want the function to not return anything this is how it should be:

void receive(Gyro_data_structure* table)
{
  Serial.readBytes((char*)table, sizeof(Gyro_data_structure));
}


Getting RTK-precision GPS with arduino devices like NavSpark?

How about the http://www.navspark.com.tw/tutorial-4 tutorial?  It seems to indicate you need a couple of the more capable $80 NS-RAW units with carrier-phase info rather than the less capable $22 NAV-SPARC plain GPS units.

The RTK system doesn't transmit only its positional error, (which it knows from external information) but also communicates the phase information for the particular channels, and then the RTK software re-calculates the positions of both using common sets of satellites and the phase info.  With the same framework, it knows the relative positions accurately, and with assumptions about the location of the base station, it can correct mobile station

This isn't an arduino problem, unless you are asking about porting RTKlib to something arduino.


Why is Toolchain Not Updated with Arduino IDE Install on Mac

The boards packages maintained by Boards Manager and associated tools are installed in .arduino15 folder. The AVR boards package bundled with IDE is only used when there is no AVR boards package version in the .arduino15 folder.

To locate the .arduino15 folder open Preferences in IDE and there at the bottom of the window is displayed the location of the preferences file with full path to .arduino15 folder.

The content of .arduino15 folder is not changed with IDE update.


Problem to convert rotary encoder output to angle

Gerben's comment is mostly right. The shortest way to adapt the behavior of that sketch to your setup is by multiplying the result by 24 (not 12, since it is 15 pulses - 30 dents, but each channel varies 15 times) and then making the modulo:

if (digitalRead(encoder0PinA) == digitalRead(encoder0PinB)) {
    encoder0Pos += 24;
} else {
    encoder0Pos -= 24;
}
encoder0Pos = encoder0Pos % 360;

BUT... the code you posted has some problems.

"The joy of interrupts is that they take care of themselves" is true, but relying on interrupts always has some drawbacks you MUST take into account. Mainly you are blocking the rest of the program (screwing up the timings for instance). I prefer to use the interrupts only when strictly needed (and this is not the case)
You are performing a potentially long function (serial interaction) into an interrupt. Totally wrong
You are using HALF the steps you can potentially use (since you are checking only one input, you are ignoring half the transitions).

To fix these, I propose you to rewrite the program to check in the loop the buttons status. Then, since they are mechanical switches, I'm going to use the Bounce2 library to debounce the inputs.

This, alongside with solving the previous 3 points, will also allow you to use any arbitrary pin on the board.

#include <Bounce2.h>

#define encoder0PinA  2
#define encoder0PinB  4
#define STEP_SIZE 12

byte encoder0Pos = 0;

Bounce debouncerA = Bounce();
Bounce debouncerB = Bounce();

void setup()
{
    debouncerA.attach(encoder0PinA, INPUT_PULLUP);
    debouncerA.interval(5); // interval in ms
    debouncerB.attach(encoder0PinB, INPUT_PULLUP);
    debouncerB.interval(5); // interval in ms

    Serial.begin (9600);
    Serial.println("start");                // a personal quirk

}

void loop()
{
    // Read the status of the inputs
    debouncerA.update();
    debouncerB.update();

    int8_t EncVariation = 0;

    if (debouncerA.rose())
    { // if input A changed from low to high, it was CW if B is high too
        EncVariation = (debouncerB.read()) ? 1 : -1;
    }
    else if (debouncerA.fell())
    { // if input A changed from high to low, it was CW if B is low too
        EncVariation = (debouncerB.read()) ? -1 : 1;
    }
    else if (debouncerB.rose())
    { // if input B changed from low to high, it was CCW if A is high too
        EncVariation = (debouncerA.read()) ? -1 : 1;
    }
    else if (debouncerB.fell())
    { // if input B changed from high to low, it was CCW if B is low too
        EncVariation = (debouncerA.read()) ? 1 : -1;
    }

    if (EncVariation != 0)
    {
        encoder0Pos = (encoder0Pos + EncVariation * STEP_SIZE) % 360;

        Serial.println (encoder0Pos, DEC);
    }
}

Disclaimer: I haven't tested this, but I'm pretty confident this will work.

I highly suggest you to use the Bounce2 library, since it also has many helper functions which shorten the code a lot. See here for instructions on how to get and use it. I'm just a happy user of this library, and I'm not linked in any way to the author ;)


Change

if(Serial.available())
    user_name = Serial.readStringUntil('\n');
{

to

if(Serial.available()) {
    user_name = Serial.readStringUntil('\n');

Edit: The reason why it didn't work properly was because all subsequent ifs were evaluated repeatedly regardless of whether there was anything new in the serial buffer or not. The modification fixes that problem.


It is any DS2482 I2C to 1-Wire bridge functional library?

I guess to solve the first error, you also need this library, which contains the DallasTemperature.h file. The file get's included, but is not contained in the DS2482 library. Unfortunately there is no clue for that in the readme of the library. The author didn't commit anything since 2014, so the development of the library can be considered dead from that side. Though some people have forked the library to make little changes.

And the solution to the second error is described in this issue of the DS2482 library (just adding an include of "Arduino.h" in the OneWire.cpp file).


It looks as though there may be material between at least one USB pin and the ground layer. This may be flux of solder 'splash'.

If visual inspection shows that this may be the case I would try carefully scratching with a sharp poibt (eg scriber) along at least the green arc on the image below. Be careful not to break intended conduction paths (eg as shown in black).


You can use header files with an absolute name, like:

#include "c:\Temp\x.h"

Another way that might help is to make the include path like:

#include "q:\x.h"

And use Windows to map driver letter Q to the path you need.


readIMU() is called by the library from an ISR (Interrupt Service Routine). While the ISR runs, other interrupts cannot be handled. The IMU sensor works over I2C, which relies on interrupts being serviced. So, when initiating the communication inside an ISR, the transmission can never be finished correctly, since the needed ISRs are not executed. At least the library doesn't seem to block in that case, so the code runs, but the values are never updated.
You should not do interrupt dependent things inside of an ISR. Instead you can define a global flag variable, which you set inside the ISR. Then in your main code you just constantly check this flag and execute the ISR dependent code, if the flag is set. After the execution you reset the flag.
The response time is dependent on the speed, that your loop runs in. But this shouldn't be a problem here, since you don't have any other code in loop() and your frequency is just 1Hz, so a delay of a few microseconds should not be relevant.

Note, that using Serial is also interrupt dependent. So writing or printing to Serial inside an ISR is also not very good. Though you can get away with it, when you make sure, that you never send more data, than the Serial buffer can hold, and that you leave enough time between the interrupts for the actual transmission. Inside an ISR the printing and writing statements will just fill the buffer. The data will then gets send in the background via interrupts.


Why a servo doesn`t move to angles properly

Every servo is different, they can have varying specifications:

Angular speed
Rotation range
Stall Torque
Size
Gear material/quality

Servos will vary based on brand; in addition each servo is going to have some individual variance.  So one has to characterize the servo, and discover what the proper control values are. Once the control values are established these are used to initialize the library so angular control will be accurate.

  For instance, the 0 degree angle was getting a bit bigger

I have found that errors in repeatability, like this, are usually found in the mechanism the servo is driving, especially the connection between the servo and the driven mechanisms. Check the connection for slop, see if everything is tightened properly.

  I observed that every servo (that I've tried) creates a buzzing noice for angles bigger than 170 degrees.

The typical maximum range of a servo is 160-190 degrees of rotation. The noise you are hearing is the servo trying to drive the motor to set the angle, but it is stalled as it can't turn that far.

  Should I try with a more powerful Arduino, like the Mega, which I think will be the perfect option having more GPIO than the UNO.

IIRC the servo library can control 12 servos with a basic Arduino, and 48 with the MEGA. This difference is more than just pin count, the MEGA has 4x the hardware timers of the 328p; 12 x 4 = 48

If you need more features you can move to the MEGA, i.e. you need more PWM channels, and the servo library reduces PWM pins from 6 to 4 on the 328p. Another example could needing more timers.

Read the Arduino Servo examples for more information on usage of the servo library and control of servos, etc.


Can't turn off fan using PWM and analogWrite(x, 0)

If you are working with the AC motor, then it is probably works even PWM cable is not attached. In this case there is no reason to use "analogWrite(PIN, 0)".  It will not work.
"An external resistor divider connected to the VMIN input sets the minimum fan speed by fixing the minimum PWM duty cycle (1.25V to 2.65V = 0% to 100%, typical).  It depends on controler card manufacturer. check datasheet"
If you cant find datasheet like me then check how others do. There is diagram of "HW-753 Signal Generator Module" below. As you can see between VIN+ and PWM there is 1k Resistor and both wired to an NPN, also the mid leg of NPN passing 1k resistor while going to pwm to protect the card. Also 3rd leg is wired to gnd. So it is not the same thing I was doing before. If you work with AC then you must always consider that and just forget what people say. Do not drown like me. I hope it will helps someone.


Replacing large lookup table with switch statement

214 is 16384 entries. Each entry takes 2 bytes. That's 32768 bytes. That's all the flash the ATMega328P has.

The most efficient storage will be an array in flash, and that will take 100% of it. Using a switch will take more space.

So in short: no. Just no. It won't work whatever you try. You need to come up with a radically different storage solution (external flash memory?) or use a larger chip.

As a side note, with "bit packing" you could reduce the storage to 20480 bytes, but doing a lookup of the data within that packed data (4 10-bit entries taking 5 bytes) will be slow to do since you have to work out exactly what combination of bits and bytes you need to reconstruct your 10-bit value.


Writing "theremin" outputs to a MIDI file on an SD card

The short answer would be "yes, it is possible". There are lots of gadgets around that record MIDI. They would have microprocessors in them, and they would have something like an SD card, which itself is like EEPROM in concept.
You may possibly have problems with storing the notes in RAM, and then writing them to the SD card fast enough not to lose some. Knowing the rate at which notes would arrive, the speed of the SD card, and the type of Arduino would help to answer if your specific case was likely to work.
I wrote a sketch that reads MIDI which shows that it is certainly possible to receive MIDI data and display it. Video of it running is here.
I don't personally know the format of MIDI files, but it is well documented.
(Edit) I do now - see further down.
Writing to SD cards is well documented. Making your idea work would be a case of taking stuff (like my code to decode MIDI), code to write to SD cards, and knowing the correct format.

(Edited to add)
See Standard MIDI-File Format Spec. 1.1 for an example of producing MIDI data. Also see The MIDI File Format and the Standard MIDI File (SMF) Format
Your basic technique would need to be (as suggested by gabonator):

Write a header chunk to the file, for example:
  4D 54 68 64   // MThd
  00 00 00 06   // chunk length
  00 00         // format 0
  00 01         // one track
  00 60         // 96 pulses per quarter-note

Write a track chunk to the file (the length will be updated later)
  4D 54 72 6B   // MTrk
  00 00 00 00   // <-- length to be updated later

Write instrument configurations (with time delta values of zero), as an example from that page:
  00  FF 58 04  04 02 18 08  // 4 bytes; 4/4 time; 24 MIDI clocks/click,
                             // 8 32nd notes/ 24 MIDI clocks
                             // (24 MIDI clocks = 1 crotchet = 1 beat)
  00  FF 51 03  07 A1 20     // 3 bytes: 500,000 µsec/ quarter note
                             // = 120 beats/minute (500000 in hex is 0x07A120)
  00  C0 05                  // Ch.1 Program Change 5 = GM
                             // Patch 6 = Electric Piano 2

When the player plays something, subtract the time that s/he last did something from the time now. This will give you the delta time.

Convert the time difference to ticks. From the header line above we have 96 pulses per quarter note (PPQ), and 500,000 µs (500 ms) per quarter note. Thus one second would be two quarter notes (2 beats per second, and therefore 120 beats per minute) and one second is therefore 192 ticks). Therefore the number of ticks, based on the time difference in milliseconds, would be:
  unsigned long ticks = (time_difference * 192) / 1000

Output the delta time as a variable length number, where the high order bit is set for each byte, as necessary, until what is left is <= 0x7F. The page above gives sample code for that. For example, for a delta time of 199 ticks:
  Decimal time of 199 ticks -> 0xC7
  0xC7 -> 0b11000111
  Since that exceeds 127, split into two bytes:

  10000001  (the high order bits)
   ^^^^^^^  <- high order bits (the MSB must be one)
  01000111  (the low-order 7 bits)
   ^^^^^^^  <- low order bits (the MSB must be zero)

  Result is 0x81 0x47

Longer times may require even more bytes.
Something like this should do it (adapted from the linked page). Just change the Serial.write line to output to your disk file.
  void WriteVarLen (unsigned long value)
    {
    unsigned long buffer;

    buffer = value & 0x7f;
    while ((value >>= 7) > 0)
      {
      buffer <<= 8;
      buffer |= 0x80;
      buffer |= value & 0x7f;
      }

    while (true)
      {
      Serial.write (buffer & 0xFF);
      if (buffer & 0x80)
        buffer >>= 8;
      else
        break;
      }
    }   // end of WriteVarLen

Follow the delta time immediately by the "note on" or "note off" byte (depending on whether they started or stopped playing a note). For example, "note on" for channel 1 would be 0x90 because 0x9n is a note on command and n is the channel number, zero relative. A "note off" for channel 1 would be 0x80.

Follow the "note on" or "note off" by the note number (in other words, which note was just played or released) - one byte.
  Octave #  Note Numbers in decimal
            C   C#  D   D#  E   F   F#  G   G#  A   A#  B
  -1         0   1   2   3   4   5   6   7   8   9  10  11
  0         12  13  14  15  16  17  18  19  20  21  22  23
  1         24  25  26  27  28  29  30  31  32  33  34  35
  2         36  37  38  39  40  41  42  43  44  45  46  47
  3         48  49  50  51  52  53  54  55  56  57  58  59
  4         60  61  62  63  64  65  66  67  68  69  70  71
  5         72  73  74  75  76  77  78  79  80  81  82  83
  6         84  85  86  87  88  89  90  91  92  93  94  95
  7         96  97  98  99 100 101 102 103 104 105 106 107
  8        108 109 110 111 112 113 114 115 116 117 118 119
  9        120 121 122 123 124 125 126 127

Typically middle C is considered to be C4 (C in the 4th octave), however apparently that can vary between devices.

Then output the velocity (one byte). A velocity of (decimal) 32 would be soft, 64 would be medium, 96 would be loud. The range for velocities is 0 to 127.

Repeat the above (except for writing the chunks and the configuration) until the player decides to stop playing.

Write an "end of track" marker:
  00  FF 2F 00    // Delta time zero, end of track

Then seek back to the start of the file + where the length bytes are (18 bytes into the file by the looks of it) and update the length bytes (4 bytes).

Example of producing a MIDI file
This example code writes out a MIDI file. As an input device I used a 16-key keypad like this:

The columns were connected to pins 0, 1, 2, 3 of the Arduino Uno, and the rows to pins 4, 5, 6, 7. This makes the ribbon cable from the keypad keep the pins in a natural order. If you use different pins just change the keys array in the sketch.
The library for keypads that I used is available at https://github.com/nickgammon/Keypad_Matrix
This particular library supports n-key rollover and key-down and key-up events. That is particularly useful for music, because it lets you hold multiple keys down at once, and the appropriate events will be generated. Obviously you need a key-down event to generate "note on" and a key-up event to generate "note-off".
I laid out the keys like this:
C     C#    D     D#
E     F     F#    G
G#    A     A#    B
Down  Soft  Up    Record

There is a "recording" LED connected to A0 which lights up when you start recording (by pressing the Record button).

Press the Record button again to stop recording and finalize the file. It is important to stop recording properly and not just power off the device, because the length of the file needs to be written near the start.

Press (and hold) Down alongside with another note to play an octave lower. Press (and hold) Up alongside with another note to play an octave higher.

Press (and hold) Soft alongside with another note to play at a softer velocity.

Using a keypad matrix is logical, because most keyboard devices would use a matrix, to reduce the number of wires you have to run.
Note that the matrix needs diodes wired for each switch as described here because otherwise if you press 3 or more keys at once you will get "ghost" keys.
In my case I opened up the commercial keypad and soldered in the diodes.

I also used a Micro-SD breakout adapter, connected to the SPI pins of the Arduino, like this:

The SDFat library was an archived one that I keep here: http://gammon.com.au/Arduino/SdFat-master.zip (2.2 Mb)
Unzip that file, and from within the folders inside it, copy the SdFat folder into your "libraries" folder (which is under your Arduino sketchbook folder - not inside the Arduino application folder). Then restart the Arduino IDE.
The code definitely compiles with that (with a handful of warnings). The later library from https://github.com/greiman/SdFat may be an improvement but I haven't tested that.

To keep track of file numbers I used the EEPROMAnything library, a copy of which can be found at http://gammon.com.au/Arduino/EEPROMAnything.zip
Each time you start a new recording it adds one to the file number, which wraps around to 0000 once it reaches 9999.

If there is an error initializing the file system (eg. no SD card) then the LED blinks slowly. If the file can't be created the LED blinks rapidly.

You can choose a MIDI instrument by changing the line:
const byte PATCH_NUMBER = 4;   // electric piano 1

Code
/*
 Sketch to write to a MIDI file from an instrument.
 Author: Nick Gammon
 Date:   10th May 2018

 Copyright 2018 Nick Gammon.

 PERMISSION TO DISTRIBUTE

 Permission is hereby granted, free of charge, to any person obtaining a copy of this software
 and associated documentation files (the "Software"), to deal in the Software without restriction,
 including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense,
 and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so,
 subject to the following conditions:

 The above copyright notice and this permission notice shall be included in
 all copies or substantial portions of the Software.

 LIMITATION OF LIABILITY

 The software is provided "as is", without warranty of any kind, express or implied,
 including but not limited to the warranties of merchantability, fitness for a particular
 purpose and noninfringement. In no event shall the authors or copyright holders be liable
 for any claim, damages or other liability, whether in an action of contract,
 tort or otherwise, arising from, out of or in connection with the software
 or the use or other dealings in the software.

*/

#include <Keypad_Matrix.h>
#include <SdFat.h>
#include <EEPROM.h>
#include <EEPROMAnything.h>

// For MIDI numbers see: http://www.pjb.com.au/muscript/gm.html
const byte PATCH_NUMBER = 4;   // electric piano 1

const byte RECORDING_LED = A0;

// bottom row changes things
const char DOWN_OCTAVE  = '-';
const char SOFT         = 's';
const char UP_OCTAVE    = '+';
const char RECORD       = 'r';

// how the keypad has its keys laid out
// capital letters are for sharps
const byte ROWS = 4;
const byte COLS = 4;
const char keys[ROWS][COLS] = {
  {'c', 'C', 'd', 'D'},
  {'e', 'f', 'F', 'g'},
  {'G', 'a', 'A', 'b'},
  {DOWN_OCTAVE, SOFT, UP_OCTAVE, RECORD},  // - = down octave, s = soft, + = up octave, r = start/stop record
};

const byte colPins[COLS] = {0, 1, 2, 3}; //connect to the column pinouts of the keypad
const byte rowPins[ROWS] = {4, 5, 6, 7}; //connect to the row pinouts of the keypad

// Create the Keypad
Keypad_Matrix kpd = Keypad_Matrix( makeKeymap (keys), rowPins, colPins, ROWS, COLS );

// file system object
SdFat sd;
const byte chipSelect = SS;

// the current file we are recording to
SdFile myFile;
// are we recording right now?
bool recording = false;

const byte MIDI_META_EVENT = 0xFF;
const byte MIDI_SET_TEMPO  = 0x51;
const byte MIDI_TIME_SIGNATURE = 0x58;
const byte MIDI_END_OF_TRACK = 0x2F;
const byte MIDI_PROGRAM_CHANGE = 0xC0;
const byte MIDI_NOTE_ON = 0x90;   // channel 1
const byte MIDI_NOTE_OFF = 0x80;  // channel 1

struct
  {
  char magic [4]; // MThd
  uint32_t length;
  uint16_t format;
  uint16_t tracks;
  uint16_t PPQ;    // pulses per quarter note
  } chunkHeader;

struct
  {
  char magic [4]; // MTrk
  uint32_t length;
  } trackHeader;

unsigned long trackHeaderPosition;
unsigned long timeLastAction;
int           nextFileNumber;

uint32_t changeEndianness32(uint32_t val)
{
  return (val << 24) |
        ((val <<  8) & 0x00ff0000) |
        ((val >>  8) & 0x0000ff00) |
        ((val >> 24) & 0x000000ff);
} // end of changeEndianness32

uint16_t changeEndianness16(uint16_t val)
{
  return (val << 8) | ((val >> 8) & 0x00ff);
} // end of changeEndianness16

void showError (const int delayTime)
  {
  while (true)
    {
    digitalWrite (RECORDING_LED, HIGH);
    delay (delayTime);
    digitalWrite (RECORDING_LED, LOW);
    delay (delayTime);
    }

  } // end of showError

void startRecording ()
  {
  EEPROM_readAnything (0, nextFileNumber);
  if (nextFileNumber > 9999 || nextFileNumber < 0)
    nextFileNumber = 0;

  char name[15];
  sprintf (name, "SONG%04d.MID", nextFileNumber++);

  // open the file for writing
  if (!myFile.open(name, O_WRITE | O_CREAT | O_TRUNC))
    showError (100);  // fast flash - never returns

  // update EEPROM for next time
  EEPROM_writeAnything (0, nextFileNumber);

  recording = true;
  digitalWrite (RECORDING_LED, HIGH);
  memcpy (chunkHeader.magic, "MThd", sizeof (chunkHeader.magic));
  chunkHeader.length = changeEndianness32 (
                       sizeof (chunkHeader.format) +
                       sizeof (chunkHeader.tracks) +
                       sizeof (chunkHeader.PPQ));

  chunkHeader.format = changeEndianness16 (0);
  chunkHeader.tracks = changeEndianness16 (1);
  chunkHeader.PPQ = changeEndianness16 (96);
  myFile.write (&chunkHeader, sizeof (chunkHeader));
  memcpy (trackHeader.magic, "MTrk", sizeof (trackHeader.magic));
  trackHeader.length = 0;   // to be filled in later
  trackHeaderPosition = myFile.curPosition ();
  myFile.write (&trackHeader, sizeof (trackHeader));

  struct
    {
    byte deltaTime = 0;
    byte metaCode [2] = { MIDI_META_EVENT, MIDI_TIME_SIGNATURE };
    byte length = 4;
    byte sig [2] = { 4, 2 };  // 4/4 time (denominator of 2 is 2^2)
    byte clocksPerClick = 24;  // MIDI clocks/click
    byte clocksPerBeat  = 8;
    }  timeSignature;

 struct
    {
    byte deltaTime = 0;
    byte metaCode [2] = { MIDI_META_EVENT, MIDI_SET_TEMPO };
    byte length = 3;
    byte usPerQuarterNote [3] = { 0x07, 0xA1, 0x20 };  // that is: 500000 µs per beat
    }  tempo;

 struct
    {
    byte deltaTime = 0;
    byte message =   MIDI_PROGRAM_CHANGE;
    byte patchNumber = PATCH_NUMBER;
    }  programChange;

  myFile.write (&timeSignature, sizeof timeSignature);
  myFile.write (&tempo, sizeof tempo);
  myFile.write (&programChange, sizeof programChange);
  timeLastAction = millis ();
  } // end of startRecording

void stopRecording ()
  {
  struct
    {
    byte deltaTime = 0;
    byte metaCode [2] = { MIDI_META_EVENT, MIDI_END_OF_TRACK };
    byte length = 0;
    }  endOfTrack;

  // write out "end of track" message
  myFile.write (&endOfTrack, sizeof endOfTrack);
  // find where we are
  unsigned long finalPosition = myFile.curPosition ();
  // go back to where the track header is
  myFile.seekSet (trackHeaderPosition);
  // work out how long the data was (excluding the headers)
  trackHeader.length = changeEndianness32 (finalPosition - trackHeaderPosition - sizeof (trackHeader));
  // update the file length
  myFile.write (&trackHeader, sizeof (trackHeader));

  myFile.close ();
  // ensure flushed to disk
  myFile.SdBaseFile::sync();

  // no longer recording, turn off recording LED
  recording = false;
  digitalWrite (RECORDING_LED, LOW);
  } // end of stopRecording

void writeVarLen(unsigned long value)
{
  unsigned long buffer;

  buffer = value & 0x7f;
  while ((value >>= 7) > 0)
  {
    buffer <<= 8;
    buffer |= 0x80;
    buffer |= value & 0x7f;
  } // end of while

  while (true)
  {
    myFile.write ((byte) (buffer & 0xFF));
    if (buffer & 0x80)
      buffer >>= 8;
    else
      break;
  } // end of while

}   // end of writeVarLen

// turn the keypad code into a note number
byte codeToNote (const char which)
{
  char notes [] = "cCdDefFgGaAb";
  char * pos = strchr (notes, which);
  if (pos == NULL)
    return 0;
  return pos - notes + 60;  // start at middle C (C4)
} // end of codeToNote

// do a note on or note off
void doNoteAction (const char which, const byte action)
{
  // we need to work out how many milliseconds have elapsed
  unsigned long now = millis ();
  unsigned long deltaTime = now - timeLastAction;
  // remember when we did this
  timeLastAction = now;
  // write out the delta time
  writeVarLen ((deltaTime * 192) / 1000);

  // note information
  struct
    {
    byte noteOn;
    byte whichNote;
    byte velocity;
    } playNote;

  playNote.noteOn = action;
  playNote.whichNote = codeToNote (which);
  if (kpd.isKeyDown (DOWN_OCTAVE))
    playNote.whichNote -= 12;  // one octave down
  else if (kpd.isKeyDown (UP_OCTAVE))
    playNote.whichNote += 12;  // one octave up

  playNote.velocity = 64;      // medium velocity
  if (kpd.isKeyDown (SOFT))
    playNote.velocity = 32;    // softer

  myFile.write (&playNote, sizeof (playNote));
} // end of doNoteAction

void startPlaying (const char which)
  {
  doNoteAction (which, MIDI_NOTE_ON);
  } // end of startPlaying

void stopPlaying (const char which)
  {
  doNoteAction (which, MIDI_NOTE_OFF);
  } // end of stopPlaying

void keyDown (const char which)
  {
  switch (which)
    {
    case 'c':
    case 'C':
    case 'd':
    case 'D':
    case 'e':
    case 'f':
    case 'F':
    case 'g':
    case 'G':
    case 'a':
    case 'A':
    case 'b':
      startPlaying (which);
      break;

    default:
      break;
    } // end of switch on which key
  } // end of keyDown

void keyUp (const char which)
  {
  switch (which)
    {
    case RECORD:
      if (recording)
        stopRecording ();
      else
        startRecording ();
      break;

    case 'c':
    case 'C':
    case 'd':
    case 'D':
    case 'e':
    case 'f':
    case 'F':
    case 'g':
    case 'G':
    case 'a':
    case 'A':
    case 'b':
      stopPlaying (which);
      break;

    default:
      break;
    } // end of switch on which key
  } // end of keyUp

void setup()
{
  kpd.begin ();
  kpd.setKeyDownHandler (keyDown);
  kpd.setKeyUpHandler   (keyUp);
  pinMode (RECORDING_LED, OUTPUT);

  if (!sd.begin (chipSelect, SPI_HALF_SPEED))
     showError (500);  // never returns

} // end of setup

void loop()
{
  kpd.scan ();
} // end of loop

I am recording from a self built replica of a theremin, which is basically two ultrasonic sensor readings for volume and pitch. Is this "too basic" for a MIDI file type?

It looks like this could be possible by using the MIDI "pitch bend" message. You would need to determine where your note value was (presumably most of the time between the natural notes like C and C#) and then send a bend message or "Pitch Wheel Change" (0xE0 for channel 1) to modify the main note. The main note would need to be updated if you moved more than a couple of semitones away.
See:

https://en.wikipedia.org/wiki/Pitch_wheel
http://sites.uci.edu/camp2014/2014/04/30/managing-midi-pitchbend-messages/


Cannot directly connect Arduino Ethernet to PC

Network problems can be complex.  If these suggestions are not right I can change the answer later if other solutions present themselves.

If you are connecting two Ethernet devices directly you may need a cross over cable.

To test your connection with out using IP addresses, try to follow what is discussed in this answer where the MAC address is used on a Ubuntu system instead of the IP address.

You also might try using wireshark to monitor the Ubuntu box's Ethernet port.


How can I get the source files for Arduino libraries?

The code is also available online for those times you don't have the IDE installed:

https://github.com/arduino/Arduino


Arduino uno + cnc shield v3 + Stepper Motor Driver A4988 + AccelStepper?

Manually set the ENABLE pins as OUTPUTs, i.e. add in the setup() function:

pinMode(MOTOR_A_ENABLE_PIN, OUTPUT);
pinMode(MOTOR_B_ENABLE_PIN, OUTPUT);


I don't see any objection to using DSS Circuits I2C Master Library.

It may not have been updated for a couple of years, but if it works it doesn't need to be. It's not as if libraries for micro-controllers have to support new printer drivers, video drivers, etc.

If it works, it works.

The chip hasn't changed, and the only real reason for updates these days is if the IDE changes (or the compiler changes) in such a way that it introduces compile errors. Such things have happened fairly recently with things like PROGMEM having tighter rules, for example.


How to use pyserial to write two separate message?

If you want a quick, cheap, and easy solution, you could just use sleep() in your Python script to put a delay between the commands. This obviously isn't a perfect solution, but it's not difficult to implement.
Or, like you said, you could use a delimiter. It's not as easy to implement, but it'll work better.
If you go the delimiter rout, you'll probably need to use Serial.read() instead of Serial.readString(). That way you can examine characters individually as they come in. You can store your characters in a String or char array until you detect your delimiter and then execute your command.
Hope that helps!


Use MQ2 Sensor with Arduino Uno without breadboard?

This is point-to-point wiring, a technique loved by high-end audio amplifier fans:


Problem with SIM800L GSM module and servo

You SIM800 module will pull 2Amps when its transmitting.  If your servo is also trying to overcome the inertia at the start of a movement it will pull 4+ times its normal running current.

A 9 volt battery will let you pull a couple of hundred milliamps.  So when the GSM transmits you system will shutdown.

You need a proper power supply or a battery pack that can put out these levels of peak current (3+Amps)


Control a 5 volt water pump with an Arduino

To use an NPN, connect a power rail of 5V to the pump's positive terminal, and from its negative terminal wire it to the transistor's collector pin. Wire emitter to GND, and place a >=220 ohms resistor between your arduino control pin and the transistor base.

If instead using an N-channel MOSFET, wire load to drain, source to GND, and use a 4K7 pull-down on gate.

Also add a diode, with its anode at the pump's negative terminal, and cathode (white ring) at the positive terminal.


Atmel atmega32u4 not recognized when connected by usb after attempting to flash new bootloader

You cannot load the bootloader over USB, that job needs to be done with an in-serial-programmer (ISP).  You could have stopped the board working if you wrote the wrong fuses, e.g. different clock frequency.

Flashing the bootloader via ISP can be done with the Arduino IDE and there are lots of tutorials on the web.  Try it, will probably work for you.


What is the best and most reliable way to detect if a book is pulled out of a book case?

As Majenko stated in the comments, an easy and discrete way would be using IR proximity sensors behind each book. The IR light from them is invisible to the eye, they are easy to read with an Arduino and often the casing of the IR LED and IR sensor are black, so that you could easily hide them in a black backplate of your book case.
The IR sensor will output one pin state (HIGH or LOW depending on the sensor), when something (the book) is near it (on most sensor modules you can change to threshold to your liking), and the other, if nothing is near it (empty place in the book case)
Searching "ir proximity sensor" at amazon gives multiple good looking results for ready to use sensor boards.

Another - more hacky - way would be to build your own switches at the top of the book case. As a switch is nothing more than 2 electrical contacts with some mechanic suroundings, you could add a small piece of cardboard above each book, which falls down a bit, when the book is removed, but not enough, that it is easily spotted (a few millimeters should be enough). At the top of the case and on the cardboard piece you put some piece of tinfoil or aluminum tape. When the book is put in the box, the tinfoil pieces get pressed together by the book, thus make contact. Wire one piece to ground, the other to an Arduino pin.
I find the IR sensor solution better, but I wanted to include a solution, where you don't need to buy extra sensor modules.


Based on this:

Note: The Arduino UNO stopped responding when I mistakenly
short-circuited a connection, I mistakenly passed 12v to one of the
header pins of sensor shield mounted on the board.

There are no I/O pins on the Arduino that are 12V tolerant.  You have almost certainly "fried" your Uno board.  It's possible the only casualty is the ATMega chip itself and replacements are available from a number of sources or you can purchase a "raw" one from an electronics reseller and use your programmer setup above to burn your own boot loader.
It's also quite likely that your sensor board is damaged as well.
From the Microchip datasheet:

You want something like this:
Adafruit Pre-programmed ATMega168p
Buy several, accidents happen!


Help to delimit and read specific contents of incoming HTTP string

I have this

if (client.connected()) {
  if (client.available() && client.find(' ')) { // GET /fn HTTP/1.1
    char fn[20];
    int l = client.readBytesUntil(' ', fn, sizeof(fn));
    fn[l] = 0;
    while (client.read() != -1);
    Serial.println(fn);
    client.stop();
  }
}


Comparing button presses to correct sequence

I found that I did not need the pull down resistors for each button since I had declared the pinMode for each button to be INPUT_PULLUP. So instead of the schematic above, I took out the resistors for the buttons and instead wired one side of the buttons to ground.


How do I deal with this Arduino IDE installation error?

Delete (or edit) your preferences.txt file - it most likely has your sketchbook folder set to your home directory.

You may find it in ~/.arduino15 for the "real" Arduino IDE, or in (I think) ~/.arduino for the arduino.org one.

Unless you have a specific reason for wanting to run 1.8.0, which is actually 1.0.6 re-numbered, you should be using the version from arduino.cc which is currently 1.6.13.


I've had a look round and spotted this:

https://electronics.stackexchange.com/questions/117970/why-is-my-analog-temp-sensors-signal-so-unstable

In summary it says that the fault maybe that the Arduino's 5V isn't stable enough, so you need to decouple it.  For once it seems that running from batteries may have been a better idea.

I've also seen posts saying there should be a 500Ohm resistor between the Ground of the LM35 and Ground.  Apparently it says 499Ohm on the datasheet.

And as a final resort I saw said that the 'Data Direction Register' influenced the analog pins.  If it was set to digital output this could lead to unstable readings for the ADC.  Basically it implied you needed to set the analog pin's to pinMode (A0, output). But I really don't think this will work


Unable to connect ESP8266 to WPA2+Enterprise network

The clear commands are not useful until after you have connected.
I use these commands just before setting user ID and password:

wifi_station_set_enterprise_identity((uint8*)username1, strlen(username));
wifi_station_set_enterprise_ca_cert(ca_cert, sizeof(ca_cert));

It is necessary that the radius server have default_eap_type set to TTLS or PEAP for username/password authentication. Perhaps there is another possibility, but there is a bug in ESP8266 so it does not properly search for supported EAP types.

const char* username1 = "anonymous"; //works for me

u8 ca_cert[] = "-----BEGIN CERTIFICATE-----\n"
"MIIFETCCA/mgAwIBAgIJAO0ntD34r/+QMA0GCSqGSIb3DQEBCwUAMIGiMQswCQYD\n"
"VQQGEwJVUzEXMBUGA1UECAwOTm9ydGggQ2Fyb2xpbmExDzANBgNVBAcMBkR1cmhh\n"
"bTEeMBwGA1UECgwVTWl0Y2hlbGwvVHJhbXBlciBJbmMuMR8wHQYJKoZIhvcNAQkB\n"
"FhBidXJ0bXNAZ21haWwuY29tMSgwJgYDVQQDDB9CdXJ0IFNlbGYgQ2VydGlmaWNh\n"
"dGUgQXV0aG9yaXR5MB4XDTE4MDEyMzE1NTgxOFoXDTE4MDMyNDE1NTgxOFowgaIx\n"
"CzAJBgNVBAYTAlVTMRcwFQYDVQQIDA5Ob3J0aCBDYXJvbGluYTEPMA0GA1UEBwwG\n"
"RHVyaGFtMR4wHAYDVQQKDBVNaXRjaGVsbC9UcmFtcGVyIEluYy4xHzAdBgkqhkiG\n"
"9w0BCQEWEGJ1cnRtc0BnbWFpbC5jb20xKDAmBgNVBAMMH0J1cnQgU2VsZiBDZXJ0\n"
"aWZpY2F0ZSBBdXRob3JpdHkwggEiMA0GCSqGSIb3DQEBAQUAA4IBDwAwggEKAoIB\n"
"AQC2O2m4JCmqimeztaZ8JasIuZqksrxvCjyWpkykoGzoR6v1/kDSuLgdp7EmtLKN\n"
"vOJPQ2ea0yVvkFf0dQYcgDhNdAsXcqskMOprS+jefzlLQUbU1jTk+AOSiOcmxWT1\n"
"H8uYhSp/1TkkWDM8dVO9RRIQyigVinsJNhdPyUVsTaQh3s29AL8CboixUNZWngOo\n"
"d1+66lwy4N+3hXACJWlurgvc0q7RfqSqfJY/+lugfID0ANpGQqqu1Dq2IXZbLyx9\n"
"roOPpC+fqX2wn5g9+RuA18OY/GPtkHc6clAoiJDGXsTRpffgsI5spdJ26WknbhO/\n"
"3Q2vQJ2Q5m/QvSp55qOM5nevAgMBAAGjggFGMIIBQjAdBgNVHQ4EFgQUT3hChU84\n"
"EEXHesDdKOtPqfhrg68wgdcGA1UdIwSBzzCBzIAUT3hChU84EEXHesDdKOtPqfhr\n"
"g6+hgaikgaUwgaIxCzAJBgNVBAYTAlVTMRcwFQYDVQQIDA5Ob3J0aCBDYXJvbGlu\n"
"YTEPMA0GA1UEBwwGRHVyaGFtMR4wHAYDVQQKDBVNaXRjaGVsbC9UcmFtcGVyIElu\n"
"Yy4xHzAdBgkqhkiG9w0BCQEWEGJ1cnRtc0BnbWFpbC5jb20xKDAmBgNVBAMMH0J1\n"
"cnQgU2VsZiBDZXJ0aWZpY2F0ZSBBdXRob3JpdHmCCQDtJ7Q9+K//kDAPBgNVHRMB\n"
"Af8EBTADAQH/MDYGA1UdHwQvMC0wK6ApoCeGJWh0dHA6Ly93d3cuZXhhbXBsZS5v\n"
"cmcvZXhhbXBsZV9jYS5jcmwwDQYJKoZIhvcNAQELBQADggEBADNmDxddEh1XSo8J\n"
"fanCRuYqngpVFtKCzRNCtQ7aOAPrj6gRMtMAqQhlYmcbxjaVOCboAvJ8evY8x5We\n"
"YU6eIAmg95PlDws8EvcVQhO2ZYcuOHTvdu5Q4Ior0oXaCfqdS35YcPW7pRGprY/x\n"
"w7kbG84FFatpXPuDGQB65haqQ2KXPrILiE/jAKpTu9EBLEEN4uIAuxbB6unARovX\n"
"YoXIQHFc32bZAjihquvs4J7FNkcSr3lJpuv03dryqMB+Qn3G8yM7PFLNL2QyS0Zu\n"
"UbS5kDO7UqbTjtrUDolp5sUNvyrkX5ILYfZeEeaHqAlA20SFqNG7BcTY222NsCft\n"
"yNXqX1c=\n"
"-----END CERTIFICATE-----";

works for me. I have to go back and check whether those \n's are needed.

I think I found the enterprise_identity command important for both TTLS and PEAP, and I found I needed a ca_cert to do PEAP but not necessary for TTLS. I am not certain why.


The example code uses cmdMessenger.readFloatArg(); (source) to read an argument.

void OnSetLedFrequency()
{
  // Read led state argument, interpret string as boolean
  ledFrequency = cmdMessenger.readFloatArg();
  // Make sure the frequency is not zero (to prevent divide by zero)
  if (ledFrequency < 0.001) { ledFrequency = 0.001; }
  // translate frequency in on and off times in miliseconds
  intervalOn  = (500.0/ledFrequency);
  intervalOff = (1000.0/ledFrequency);
  cmdMessenger.sendCmd(kAcknowledge,ledFrequency);
}

That function will set ArgOk to false if there was no next argument.

float CmdMessenger::readFloatArg()
{
    if (next()) {
        dumped = true;
        ArgOk = true;
        //return atof(current);
        return strtod(current, NULL);
    }
    ArgOk = false;
    return 0;
}

Thus you should try to use public function

bool isArgOk();

/**
 * Returns if the latest argument is well formed.
 */
bool CmdMessenger::isArgOk()
{
    return ArgOk;
}

of the CmdMessenger object (which will return ArgOk) to check if the read argument was okay. You could e.g. modify the code as follows

void OnSetLedFrequency()
{
  // Read led state argument, interpret string as boolean
  ledFrequency = cmdMessenger.readFloatArg();

  //Did we just read garbage because the argument wasn't there?
  if(!cmdMessenger.isArgOk()) {
      //Using Serial might be a bad idea because that cmdMessanger operates on the same Serial stream.. but you get the idea.
      Serial.println("You didn't supply a correct argument! Error.");
      return; //goodbye
  }

  // Make sure the frequency is not zero (to prevent divide by zero)
  if (ledFrequency < 0.001) { ledFrequency = 0.001; }
  // translate frequency in on and off times in miliseconds
  intervalOn  = (500.0/ledFrequency);
  intervalOff = (1000.0/ledFrequency);
  cmdMessenger.sendCmd(kAcknowledge,ledFrequency);
}


From the Arduino website:

  shiftOut()

  Description

  Shifts out a byte of data one bit at a time. [...]

  Note: if you're interfacing with a device that's clocked by rising
  edges, you'll need to make sure that the clock pin is low before the
  call to shiftOut(), e.g. with a call to digitalWrite(clockPin, LOW).

You need to pull clockPin low before each shiftOut() call, as the documentation says.

Also, you have misunderstood the behaviour of the latchPin. This can be high or low at any time; it's the change from low to high that latches the data into the output cells.


Not sure if logic analyzer shows an error or perhaps just a 'relay bounce'

According to your plot, the pulse length is 50 microseconds. Typical mechanical relay switching time is 10 milliseconds, which is 200 times longer. It's next to impossible that the pulse is due to your software powering the relay back on for a moment, since the relay simply could not react to such a short input pulse.

So yeah, it's just a bounce. You can safely ignore it in most cases, unless you're counting events or doing something similar. In the latter case, there are both hardware and software debouncing techniques, which share the basic idea of a low-pass filter.


How fast should I be able to write to AT45DB321D flash memory?

"Data will continue to be loaded into the buffer until a low-to-high
  transition is detected on the CS pin."

The dataflash.bufferWrite command writes the opcode and address bytes and then in the for loop you write 256 data bytes. The data bytes are written at once, without preceding each single one with the opcode and the address. (So it does already what you want to do.)

It doesn't matter whether you write the byte at once or each with a single SPI write. SPI can only send them sequentially. And the initial opcode and address is only send once with the dataflash.bufferWrite command.

BTW: There are two buffers to write to 1 and 2. So I'm curious why the command dataflash.bufferWrite(0, 0); works. IMHO that should be dataflash.bufferWrite(1, 0); or dataflash.bufferWrite(2, 0);.

You also not start the internal writing to the pages. There is no command e.g. dataflash.bufferToPage(1, 7);. The data are only transfered into the flash's buffer.

Because data is not written into a memory page, you'll lose it, if you switch off the power.

UPDATE

I fear I understood your question not completely. As I now see, you wondered why you need 48 µs in average for 256 Bytes when the SPI Bus is driven with 4MHz.

I looked a little in the codes and docs. And that's what I found:

The DataFlash lib selects a different Clock divider:

/* Setup SPI */
SPI.setDataMode(SPI_MODE3);
SPI.setBitOrder(MSBFIRST);
SPI.setClockDivider(SPI_CLOCK_DIV2);

SPI_CLOCK_DIV2 results after some computation to a frequency of Fosc/2. The computation are very difficult to follow, because they use an 8 bit number which is divided into 2 nibbles each of them defines a part of a register content. But I'm quite sure the result is Fosc/2. But that would result in a clock frequency of 8 MHz. That can not explain your observed timings.

BTW: There is also in interesting deprecation note about setting the clock speed this way. ;-)

  // This function is deprecated.  New applications should use
  // beginTransaction() to configure SPI settings.
  inline static void setClockDivider(uint8_t clockDiv) {
    SPCR = (SPCR & ~SPI_CLOCK_MASK) | (clockDiv & SPI_CLOCK_MASK);
    SPSR = (SPSR & ~SPI_2XCLOCK_MASK) | ((clockDiv >> 2) & SPI_2XCLOCK_MASK);
  }

But then I saw another thing that could be a problem. There are to single value transfer functions. One for bytes (uint8_t) and one for integers (uint16_t). Your count variable is an integer so the two byte transfer method is used, resulting in two byte per transfer and therefor 512 bytes. But that also no explanation for the observations. And writing buffers works only with uint8_t[] so ??.

What else could have happened?

The MCU could be clocked by a lower frequency then 16MHZ. I think there are fuses that can be configured to reduce the master clock speed for using the MCU with lower voltage (like 3.6 Volt).

The missing beginTransaction / endTransaction (DataFlash doesn't use this) of the SPI bus could have impact on the interrupts which could distort the timing. (But that's a very wild guess ;-))

The observation that, transferring twice the amount of data with the single int transfer method does take roughly the same time than the buffered method gives us a hint, that possibly the SPI speed is not the problem.

In the function dataflash.bufferWrite(0, 0); there is e.g. a wait function
waitUntilReady(); that could cause a long delay of ~12 milli seconds. You can easily try that, by taking the dataflash.bufferWrite(0, 0); out of the timing.

void DataFlash::waitUntilReady()
{
    while(!isReady()) {};
}

uint8_t DataFlash::isReady()
{
    return status() & AT45_READY;
}

uint8_t DataFlash::status()
{
    uint8_t status;
    reEnable();     // Reset command decoder.
    SPI.transfer(DATAFLASH_STATUS_REGISTER_READ);
    status = SPI.transfer(0);
    disable();
    return status;
}


TinkerCAD switch seems to be not working (always closed)

As  Sener said, "use a pull-down resistor (10K) from pin8 to GND."

And in case anyone notices, yes, I'm aware of clear().

TinkerCAD must be assuming a floating input reads high instead of an intrinsically floating ground. The most simple solution is adding pinMode(pin8, INPUT_PULLUP); to the setup() function. Then, tie the opposite (than with a resistor) side of the switch to ground: Modified circuit TinkerCAD simulation.


It is quite OK to use millis() or micros() inside an ISR. In fact that is an excellent time to do it, because you are recording the time of the event shortly after it happened. Make sure the variable you are saving it to is unsigned long and volatile. Eg.

volatile unsigned long whenItHappened;
volatile bool eventHappened;

void myISR ()
  {
  whenItHappened = millis ();
  eventHappened = true;
  }

Now in your main loop you can test the eventHappened flag, so you will know if this event has happened, and whenItHappened is when.

It is not a good idea to use pulseIn() because that can wait quite a long time for a pulse. The default timeout for pulseIn is 1 second, which is far too long to wait inside an ISR.

If you want to time something (eg. how long it takes a ball to cross a sensor) use the interrupt twice, once to find the first event, and again to find the second.

Example

Example code which times how long a ball passes a sensor:

const byte LED = 12;
const byte photoTransistor = 2;

unsigned long startTime;
volatile unsigned long elapsedTime;
volatile boolean done;

void ballPasses ()
{
  // if low, ball is in front of light
  if (digitalRead (photoTransistor) == LOW)
    {
    startTime = micros ();
    }
  else
    {
    elapsedTime = micros () - startTime;
    done = true;
    }

  digitalWrite (LED, !digitalRead (LED));
}

void setup ()
{
  Serial.begin (115200);
  Serial.println ("Timer sketch started.");
  pinMode (LED, OUTPUT);
  attachInterrupt (0, ballPasses, CHANGE);
}

void loop ()
  {
  if (!done)
    return;

  Serial.print ("Time taken = ");
  Serial.print (elapsedTime);
  Serial.println (" uS");
  done = false;
  }

That code used micros() for a more accurate timing.

Reference

Interrupts


I was having similar problem (but not the same )
And it was due to software serial pins which keep on filling the buffers of MCU.

Some times it happen that pwm pins keep on receiving data e.g. GPS also keep filling the buffer and due to that arduino freeze .

To solve this problem I open new dummy software serial port.( select any pins which is free ) and do listen to your software serial pins when you want to read it otherwise make dummy listen.


Sending data from Processing and receiving as uint32_t

I recommend studying up on bitwise shifts (<< and >>), along with the bitwise OR and AND. They're what you're going to need, especially since atoi() would only give you a 16 bit, signed integer.

Let's say that your variable's binary is this (split up into 4 segments):

10010010 10110101 01010010 10010100

Sending

uint32_t myVarCopy = myVar;
for(int i = 0; i < 4; i++) {
    Serial.write(myVarCopy & 255);
    myVarCopy = myVarCopy >> 8;
}

The first line in the loop modifies the variable by bitshifting right eight to allow us to read the data eight bits at a time. We have to, whenever sending data through the serial port, "trim" any data that is in the 9th digit or above using the & 255 part. This allows us to split this int up into four bytes.

How the myVarCopy variable would look over the four iterations:

After 1: 00000000 10010010 10110101 01010010 (sent 10010100)
After 2: 00000000 00000000 10010010 10110101 (sent 01010010)
After 3: 00000000 00000000 00000000 10010010 (sent 10110101)
After 4: 00000000 00000000 00000000 00000000 (sent 10010010)

Reading

uint32_t buffer = 0;
for(int i = 0; i < 4; i++) {
    buffer = (buffer >> 8) | (Serial.read() << 24);
}

This code works by adding the newest data onto the digits 25-32 after it moves everything else over eight bits.

This is how the buffer variable would look over the four iterations:

After 1: 10010100 00000000 00000000 00000000
After 2: 01010010 10010100 00000000 00000000
After 3: 10110101 01010010 10010100 00000000
After 4: 10010010 10110101 01010010 10010100

Depending on how Processing works, you might have to worry about little/big endian encoding to ensure that your data is in the right order. Warning: I haven't tested these yet as an IDE isn't installed on the computer I'm typing this on. Also, I don't know the exact function calls for Processing, so it might not compile.


Is my Arduino destroyed or are the pins destroyed?

Try running the blink LED, on a different terminals.
If the LED is working properly, then most likely the pins are destroyed.
Why are they destroyed?
Most likely, you've withdrawn more current than the pins can actually provide.

According to the datasheet of the Arduino uno, the IO pins can handle up to 40mA.

The only possible way to solve this problem is to change the IC (Atmega328) by another one. It's not guranteed that it will work, but the microcontroller is reletively cheap.

The definite answer can not be determined unless you showed us a schematic of your connection.


Use Arduino Uno to program the on-board Atmega328 in C

Yes, the Uno is designed to be very simple to program. The only extra hardware you need is a USB cable to connect it to your computer.

If you're completely new to this then the simplest way to start is by following the official "Getting Started" guide. Note that the section on drivers is particularly important.

The guide explains how to use the official Arduino IDE for programming the microcontroller. It automatically handles compiling and uploading your code via gcc and avrdude. It's technically configured to compile as C++ code, but plain C code should be fine too.

I don't recommend that IDE for long-term use though as it's really only aimed at beginners (it has a number of limitations and other problems). Using the command-line tools directly is certainly possible if you'd prefer that. However, you may also like to consider alternative IDEs which have support for Arduino plug-ins.


Arduino UNO/ZERO PRO, enough computing power for PID-controller?

Assuming you're not doing anything too fancy, yes, it should be fine.

There's even a library to do all the work for you: http://playground.arduino.cc/Code/PIDLibrary


Perhaps you have asked the wrong question. Because there is a library for those cheap 433MHz modules: RadioHead.
Use the RH_ASK mode, and try the 'ask' examples

You might see VirtualWire used a lot with those 433MHz modules. That is the same as RadioHead. The RadioHead is newer and has a few bugs fixed, but it uses also more memory.

The RadioHead library uses a far more superior protocol than anything else, that makes the range better than with other libraries. It also has a (simple) CRC checksum in the protocol. That means that when you receive something, you can be (almost 100%) sure that the data is correct.

Other protocols require that a message is transmitted 10 times, to be sure that it will be received. With the RadioHead library, sending a message just once is good enough.

Those cheap 433MHz modules have a disadvantage: they can only be turned on and off (ASK modulation) en you need a library for the protocol. That means that if the Arduino is doing more things that uses interrupts or code that disables interrupts, then the protocol is disturbed and it will not work very well.
The RF transceiver modules have a chip on the module itself that takes care of the protocol, that is so much better. Sparkfun has a Wireless Buying Guide and Adafruit uses the RFM69 a lot.

Those cheap modules require an antenna, or else the range could be less than the size of the table they are on. Solder a 16cm piece of wire to the antenna pin. Any piece of wire of any length is better than no antenna.


Arduino LCD Display 2x16 custom char byte limit

there was a limit to how may byte arrays I could declare.

If the problem was that you ran out of free RAM, then the fix is to move those byte arrays into program space.

Atmega 328 processors (Uno) are very RAM-limited. Fortunately you can assign constant data - fixed character strings, lookup tables for math, fonts, CRC calculation, etc - to be stored in program space which is much more generous. The upside is you can free lots of RAM in an application like yours that needs lots of constant data. The downside is that access to the data is a little bit slower:

// Definitions for data in program space
#include <avr/pgmspace.h>

// Place the character table in Flash
byte const Ghost[8] PROGMEM = {
   0b00000,
   0b01110,
   0b01110,
   0b10101,
   0b11111,
   0b11111,
   0b11111,
   0b10101
};

// Read a byte of character data
OneByte = pgm_read_byte(&Seg7_segtbl[index]);

Update:

  LCD version: QAPASS 1602

If that has an Hitachi HD44780 controller on it, its datasheetsays it has a 64-byte character RAM - more than enough for a full display of 2 x 16 unique characters, but if you need a wider choice of characters than a set of 64, you may need to re-load the RAM with a custom sub-set for any given screen-full. For animating, though, you'll probably need all of the individual parts of each animation in the LCD RAM at once; reloading during animation will most likely disturb the smoothness. One possibility is to load part of a subset between animation frames - if that's even possible. (I haven't studied this controller to that level of detail).


Powering a 5V Arduino Pro Mini with 3.3V

Pro Mini 5V has voltage regulator for 5V and 16MHz quartz.
Pro Mini 3.3V has voltage regulator for 3.3V and 12MHz quartz.

According to manufacturer specification Atmega328 chip powered by 3.3V cannot run 16MHz and needs at most about 13MHz. But it's official specification. Some chips are better than specification (faster) some are worse (slower). So you can try whether your Pro Mini is better or not. Or you can change quartz to 12MHz, if you can solder SMD parts.

Or better look for cheaper 3.3V clone, they are not much more expensive as 5V version...


First off a comment on your variable types. It's not the cause of your problem, but just something to watch for in future:

int impulsi =  0;

This should be voltatile (Edit: I see you updated that, that's ok).

unsigned deltaT[3];
unsigned vel = 0;

These lack a type. As such the default to int. Your deltaT array should be unsigned long since it stores time. It will overflow very rapidly otherwise.

Now on to your problem.

The core of your problem is your methodology of calculating the speed. This bit:

if (impulsiOld == impulsi || impulsi > impulsiOld)
{
  ...
}
impulsiOld = impulsi;

is going to be running pretty much always. That's because impulsiOld and impulsi will either always be the same (since you set them to be the same) or impulsi is going to be greater than impilsiOld since you received a pulse in the brief interlude when it's not running that bit.

And that means that all your deltaT entries are going to be the same most of the time.  Which leads me on to the next bit:

int t1 = (deltaT[1] - deltaT[0]);
int t2 = (deltaT[2] - deltaT[1]);
int dividi = t1 + t2;
vel = (((690 * 2000 / dividi) * 3.6) / 10) * 0.85;

If delatT[1] and deltaT[0] are the same, then t1 will be 0. The same goes for t2. 0 + 0 = 0, so dividi will also be 0.

And that means:

690 * 2000 / 0

Which will be a divide by zero exception and will cause the MCU either to lock up or to reboot. If the latter you will see the bootloader run for a couple of seconds.

There are two normal methods of calculating the speed from pulses, and I am not sure what your method is trying to be.

The simplest one is to just count the number of pulses over a given period. Increment the count in your ISR, and after a second has elapsed (or longer, or shorter, depending on the frequencies you are working with) you reset the count to 0 (after storing it elsewhere) and calculate the speed from that stored count.

The other way is to just take the time between two successive pulses. You can average it, maybe with a rolling (AKA moving) average, or just take the raw value depending on what you are measuring.  This method is a little harder since you need to do more work per pulse.

The two methods differ in critical ways when it comes to outputting the results. The first method will always give you a value every second (or whatever time period you use), but it can't cope with pulses that are further apart than the time period you use. The second method doesn't much care about the time between the pulses, but you can only get a meaningful reading if a pulse arrives, which if that is a while means you get no reading for a while. It's harder to determine "not moving" from that.

Also you should look at the use of critical sections when accessing your impulsi variable outside the interrupt routine. It more than 8 bits, so all access to it will be non-atomic and could be interrupted by the ISR.


Every time the Arduino detects motion, I want a sound to be played on the phone of the person with the app. In order to do this, I plan on using a HC-05 Bluetooth Module.
Does anyone have any suggestions for how I should build the circuit and what code I should use?

The Arduino sketch above is a good start.
The first step is to connect the Bluetooth module so that the Serial output can be sent. The circuit is simply connecting the Bluetooth module to RX/TX on the Arduino. I am assuming that you have written an app that can read from Bluetooth on the phone and write to the screen.
The second step is to parse the output and play the sound. That is also part of the app and not the code on the Arduino. To make this easier the sketch output statements can be changed to something easier to parse (detect).
All and all the work is mainly app programming.
Cheers!


How can I read this digital pin for Nano by using AVR's Atmel Studo?

Read the port state with PIND
Isolate the bit you want with &
Profit

if (PIND & 0b0100000) {
    val |= 1;
}

Or, as a ternary:

val |= ((PIND & 0b01000000) ? 1 : 0);


I suggest you turn this into a simple 1D table by using two different
separators, for example ‘:’ between joint and direction, and ‘,’ between
consecutive movements. Then, instead of “B,CCW,S,CW” you would type
“B:CCW,S:CW”. For parsing the string, you split at the commas, and
consider the pieces between the commas as single items. In other words,
“B:CCW” would be the name for relay 2, and you do not try to split it
further.

Here is a simple method to map the strings to the relays:

const char * const relay_names[] = {"", "B:CW", "B:CCW", "S:UP",
    "S:DN", "W:CW", "W:CCW", "E:UP", "E:DN", "G:OP", "G:CL"};

// Return the relay number.
int get_relay(const char * name)
{
    for (int i = 1; i <= 10; i++)
        if (strcmp(name, relay_names[i]) == 0)
            return i;
    return -1;  // meaning invalid
}


How to add the -F switch for avrdude in Arduino IDE

The error probably means that you have selected a wrong configuration.

To modify the IDE to insert the -F seems to be the hard way,
however the easy way is to make a wrapper to avrdude:

$ cd ./arduino/hardware/tools/
$ mv avrdude avrdude.orig
$ cat >avrdude.sh
  #!/bin/sh

  ./avrdude.orig -F $@
  ^D
$ chmod +x avrdude.sh
$ ln -s avrdude.sh avrdude


Use Unix terminal instead of the Monitor on Arduino IDE

You'll need to condition the serial line with the stty command to get this to work. One of the easier ways to do it is to start by using the Serial Monitor and running the command:

stty -g < /dev/tty.usbmodem1d112

That will show you all of the settings that the Serial Monitor used to conditions the line. The -g flag to stty tells it to give you the results in a form that can be used as the arguments to another stty command. You could do this like this:

echo -n 'stty ' > stty.arduino ; sudo stty -g -f /dev/tty.usbmodem1d112 >> stty.arduino

chmod +x stty.arduino

The first line creates a shell script to condition the serial line. The second line makes it executable so that you can run it as a shell command – ./stty.arduino. The sudo runs the command as root (with elevated privilege) which allows you to open the port even though the Serial Monitor will already have it open.

If you want you could move the command into a directory on your $PATH (for example ~/bin) so that it can be found regardless of where your current directory is.

After getting set up you can see the output from Serial.println() on the Arduino by doing:

./stty.arduino

cat < /dev/tty.usbmodem1d112

Depending on what you are trying to do, you might find the expect or script commands helpful. Expect (man page) lets you automate interactions with a text based application or process. Script (man page) creates a transcript of your interactions on the command line with another program or process.


Why can't the OCR1A register be set to 1 to get a 8MHz PWM?

Because then you only have 1-bit PWM. And there aren't an awful lot of applications for 1-bit PWM.


433Mhz transmitter interference when using long cable, only on Arduino Due

I think I found the problem. It seems that there's an anomaly with the Due where when a pinmode is set as OUTPUT, it sets the pin as HIGH by default, whereas with the other Arduinos it's set as LOW. This forum page is discussing the problem: http://forum.arduino.cc/index.php?topic=154869.0

Likewise this page suggests the problem is a bug with the wiring_digital.c file: http://forum.arduino.cc/index.php?topic=185230.0

In RCSwitch.cpp, this is the enableTransmit code:

void RCSwitch::enableTransmit(int nTransmitterPin) {
  this->nTransmitterPin = nTransmitterPin;
  pinMode(this->nTransmitterPin, OUTPUT);
}

It seems the code sets the pin as OUTPUT, which would cause an anomaly on the Due alone.

I solved the problem by calling the enableTransmit function just before sending a signal, and then calling disableTransmit() immediately afterwards. Can anyone think of a cleaner/better solution?

Out of curiosity, can anyone suggest what a standard transmitter might be sending when the data line is constantly held at HIGH?


The code appears to be looking for an SMS that says #a0 or #a1. The logic doesn't look very robust, though. It reads a character, then waits 10ms and tries to read another. What does SIM900.read() do if there is no next character? Will it return something? Or wait until there is another? If it waits, the code can get out of sync with incoming, badly-formed commands.


How do I write the codes in #define in an IR Receiver circuit?

Your problem is that you don't know how to form hexadecimal numbers.

In your code (in future, if you have an error in the code please post the code that is causing the error, not something else entirely - it makes it nigh on impossible for people without my psychic abilities to answer your question) you have defined a macro containing what you think is a hexadecimal number. In fact it's just a random string of characters and the compiler doesn't know what to make of it:

#define code1 DE74847

So in your switch construct, when code1 gets replaced with the content of the macro, you end up with:

switch (value) {
    case DE74847:
        ....

The compiler has no idea what a DE74847 is.

Numbers other than decimal numbers (0-9 and the decimal point) are identified by the use of a prefix:

0b... is binary
0 is octal (in your completely different code you have the number 0575, which is actually octal, and represents the decimal value 381)
0x is hexadecimal.

So adding 0x to the start of your hexadecimal value will tell the compiler to treat it as hexadecimal:

#define code1 0xDE74847


Cannot convert 'String' to 'uint8_t {aka unsigned char}' in initialization

uint8_t first  = atoi (tmp1.substring(1, 3).c_str ());

Or even:

String data = "#255101987";
uint8_t first  = atoi (data.substring(1, 3).c_str ());


How to detect the direction of rotation with a sensor encoder timing disk (photoelectric speed sensor)?

It seems to be a A/B coding : if A gets high before B, it's one way (count for exemple), and if B gets high before A, it's other way (decount).
So, connect power and ground. Then connect the two wires to input pins :

    int P_A=2; int P_B=3; //Inputs
    long int position = 0; //Position of wheel
    long int lastPosition = 0; //last position of wheel : for speed computing

Notice that one pin must be an hardware interrupt pin (Uno 2 an 3 are interrupt pins. Then attach interrupt in the stup :

    attachInterrupt(2, wheel, RISING);  //wheel is arbitray

Then create the interruption code :

    void wheel(){
        int sB = digitalRead(P_B);
        if (sA == sB)   { //Clockwise
        position++;
        }
        else   { //Counterclockwise
        position--;
        }

Then, in your loop, you can print position when it changes to read current position :

    if(lastPosition != position){
        Serial.println(position);
    }

i hope it will help...
Notice that if you use both interruptions, you get a better resolution, but speed limit is lower.


What is touch_pad_get_status() supposed to return?

As pointed out from people in the comments, things need to be different.
If you use the function touchAttachInterrupt, things are a bit simpler.
The example that comes with the ESP32 library is enough to make you understand.
If you want to do what I did, this is how:
  touch_pad_init();
  touch_pad_set_fsm_mode(TOUCH_FSM_MODE_TIMER);
  touch_pad_config(TOUCH_PAD_GPIO2_CHANNEL, 500);
  touch_pad_config(TOUCH_PAD_GPIO15_CHANNEL, 500);
  touch_pad_config(TOUCH_PAD_GPIO13_CHANNEL, 500);
  touch_pad_isr_register(TouchButton, NULL);
  touch_pad_intr_enable();

Put this code in the setup(). Of course needs the init(), but also needs to be set to timer mode, or otherwise you're going to need to start() probably.
The config() is to configure the pin as an interrupt. I've set 500 in the threshold because the readings of touch_pad_read() told me it went from 800 untouched to 50 touched, so the midterm I chose 500.
isr_register is the function that tells to call TouchButton(), with NULL as argument to it.
void TouchButton(void *arg)
{
  uint32_t touch = touch_pad_get_status();
  touch_pad_clear_status();
  Serial.print("Button ");
  Serial.println(String(touch));
}

This is the declaration of the callback function I've done. It should be noted that clear_status() should be called as soon as possible after the get_status(), preventing the system from panicking (that's the name). You'll also see in the serial monitor that each button represents a power of 2. That's because the get_status() returns the pin mask in binary. So just do something similar to this
for (int i = 0; i < TOUCH_PAD_MAX; i++) {
    if ((pad_intr >> i) & 0x01) {
        s_pad_activated[i] = true;
    }
}

and you'll get a vector of which one was pressed.


How far can a HC-SR04 can stand from the microcontroller?

I have a couple measuring the liquid level of two tanks.

The units are distanced from the microcontroller by 12' of 18ga solid-core copper cable.

Testing was done with another microcontroller with the sensor attached by 6" cable to ensure accurate readings.

That's the longest I needed, so I haven't tested beyond that.


These tutorials often forget to tell you to place the ATmega chip in RESET if you want it to function as a UART-USB-pass-through. This is easily done by connecting the RESET pin to GND with a jumper. Also consider powering the ESP from a more powerful source, like the Arduino 5V pin through an LM1117 regulator. Don't forget to set your Serial Monitor to Both NL & CR. Use a voltage divider between the Arduino's RX pin and that of the ESP, to reduce the 5V signals to 3.3V.


You could start by drawing a time graph, like this:

LED 1   # # # # # # # # # # # # # # # # # #
LED 2    ##  ##  ##  ##  ##  ##  ##  ##  ##
LED 3      ###   ###   ###   ###   ###   ###
        <-period 1-><-period 2-><-period 3->

As you see on the graph, the whole sequence repeats itself every
12 seconds. Then, you can just write down all the pin toggles for
12 seconds and let the loop repeat itself:

void loop() {
    digitalWrite(ledPin1, HIGH);
    digitalWrite(ledPin3, LOW);
    delay(1000);
    digitalWrite(ledPin1, LOW);
    digitalWrite(ledPin2, HIGH);
    delay(1000);
    digitalWrite(ledPin1, HIGH);
    delay(1000);
    digitalWrite(ledPin1, LOW);
    digitalWrite(ledPin2, LOW);
    digitalWrite(ledPin3, HIGH);
    delay(1000);
    digitalWrite(ledPin1, HIGH);
    delay(1000);
    digitalWrite(ledPin1, LOW);
    digitalWrite(ledPin2, HIGH);
    delay(1000);
    digitalWrite(ledPin1, HIGH);
    digitalWrite(ledPin3, LOW);
    delay(1000);
    digitalWrite(ledPin1, LOW);
    digitalWrite(ledPin2, LOW);
    delay(1000);
    digitalWrite(ledPin1, HIGH);
    delay(1000);
    digitalWrite(ledPin1, LOW);
    digitalWrite(ledPin2, HIGH);
    digitalWrite(ledPin3, HIGH);
    delay(1000);
    digitalWrite(ledPin1, HIGH);
    delay(1000);
    digitalWrite(ledPin1, LOW);
    digitalWrite(ledPin2, LOW);
    delay(1000);
}

This was the simple, albeit tedious solution.

The smart solution is to go through the Blink Without Delay Arduino
tutorial. You will see that, once you start using millis() instead of
delay() for managing your timings, blinking three LEDs instead of one
is completely trivial.


ESP8266 (connected to Arduino) only works when plugged into USB power

It sounds like your power supply is inadequate to the task.

The ESP8266 is notoriously finicky about having a noise free power supply capable of delivering a lot of instantaneous power. If you are using a wallwart style supply it should promise at least 1A and more is better. Even though the actual use is more like 250 mA.