How to use H3LIS331DL 3-Axis Linear Accelerometer with arduino to detect Harsh braking of vehicle

A harsh braking is nothing more than a strong negative acceleration, so you could compare your accelaration values to a threshold. Let's assume, that the positive x-axis is the moving direction of your vehicle. This means, that braking will give an acceleration in the negative x direction. Then you first define a specific threshold for the acceleration. An acceleration in the negative x direction above this level means, that it is a "harsh" braking (you will have to test yourself, what value you want for this). Then you test, if the read values are below the negative of our threshold (since acceleration in the negative direction will be presented by negative number).

int braking_threshold=1000;
...
void loop(){
    ...
    // Convert the data
    int xAccl = ((data[1] * 256) + data[0]);
    int yAccl = ((data[3] * 256) + data[2]);
    int zAccl = ((data[5] * 256) + data[4]);

    if(xAccl < -1*braking_threshold){
        // Do whatever you want to do at a harsh braking here
    }
    ...
}

Note, that often the accelerometer data is rather noisy, especially, when mounted on a vehicle, that will vibrate during the motion (due to motors and such). You might need to apply some filter to the read values, before you can use them. That can be as easy as averaging some values, but can also go on to more complex filter algorithms, depending on how noise free you need the data. You will have to test, what values you realistically get in your application and how noisy they are. But data noise reduction is a complete different topic and thus off-topic for this question.

Also note, that your accelerometer measures a range of 200g. That's quite much I would say. When measuring relatively low accelerations the signal to noise ratio will be rather bad. So I hope, that you really want to measure accelerations, that fill this range, rather than only using a very small percentage of the range.


All the factors mentioned in the question apply to make the cost so low.  However, with an exception or two as noted in the next paragraph, “low quality parts” is not much of a factor, as explained in two paragraphs after that.

Possible low quality parts include the USB mini-B socket, crystals or resonators, and the reset switch.  The socket and switch contain metal shapes that can be well made or badly (and more cheaply) made.  Those badly made will function but may have shorter lives and higher failure rates.  For example, the USB cable fit may be loose, or the switch may fall apart.  Crystal or resonator accuracy and stability can be poor while still allowing a Nano clone to appear to function ok.

However, SMT (surface mount technology) or SMD (surface mount device) parts on the board cannot be made significantly more cheaply than can good parts.  SMD LEDs, resistors, diodes, voltage regulators, and capacitors come off of automated assembly lines with little or no manual intervention.  See, eg, ceramic capacitor manufacturing at wikipedia.  Parts are automatically packaged into sealed reels of parts suitable for use on an automatic pick-and-place machine that populates PCBs.  In short, the dozen 0603-size SMD LEDs, resistors, and caps, and the nine other passive or small-scale-integration SMD parts on the board will cost about the same coming off a bad manufacturing line as from a good line, so there is little profit to be made producing bad parts.  The 20-odd passive parts probably cost a couple of cents, at manufacturing scale.

Active SMD parts like voltage regulators, the ATmega328P, and the 32U4 or CH340, likewise come off automated manufacturing lines.  As these parts are more expensive, there is more economic incentive for cheating, and from time to time fake parts get sold and used.  In the past (and perhaps still) there have been manufactories that specialize in removing labeling on the tops of cheap or non-functional chips, and putting accurately detailed fake labels for expensive chips on instead. (For example, NCP5318 buck regulators relabeled as ATmega328s.)  In short, most of the active SMD parts on a Nano either are genuine and work or obvious fakes that don't work and earn their sellers bad reputations or jail.

The CH340g USB-to-serial chip  vs. ATmega32U4 USB issue is more complicated.  Ie, some may think of the CH340 as a lower quality part than a 32U4.  The CH340 may need a different USB driver than the 32U4 and may not support 57600 BPS serial in some cases. 1, 2.  The ATmega32U4 seems to be available on Alibaba for $0.10 to $.20 in moderate quantities.  I think the CH340g is made only in China and is somewhat cheaper than the ATmega32U4, so its contribution to the BOM total cost may be a few cents.

The PCB probably costs 5 to 10 cents, and assembly is free except for amortized costs of pick and place machines and an IR reflow system with a conveyor.  Boards probably are processed (components placed and soldered automatically) in panels of several dozen units, tested automatically, and then separated for packaging.

Summary: Inexpensive parts and automated processing hold down the per-board costs, moreso than cutting corners on component quality.  Corners may get cut on assembly quality and on quality assurance inspections.


time.h is provided by the compiler (more specifically the C library in use in the compiler).

I believe the xtensa-esp32 compiler uses newlib as the C library. If that is the case, the documentation is here: https://sourceware.org/newlib/libc.html#Timefns


The comment form of a blog is not an appropriate place to publish source
code, as the content-management system (Wordpress here) quite often does
some destructive transformations. For example, here:
Serial.println(“2 Second LOCK OUT: No rapidly repeating readings”);

Wordpress tried to be “helpful” and replaced the ASCII quotes (") with
typographic quotes (“ and ”), which makes the line non-compilable.
As for the line you are asking about:
if ((touch_sensor_value  (TOUCH_timeSeconds * 1000)))

it is likely missing a less-than sign (<), as those are often stripped
from user-generated content for security reasons. I don't know why some
of those signs went through the filter, maybe it has something to do
with the white space surrounding them, but this is pure guess.
Given that the code has been destructively mangled, your options are
either to guess from the context, or post a comment asking for
clarification.


Solution to your problems.

Use println instead of print.
Change char c = Serial.write(Serial.read()); to char c = Serial.read();


Arduino Pro Micro, get data out of Tx pin?

You appear to have a "pro micro" style board in which the USB communication is directly sourced from the main ATmega32u4 processor, rather than generated as serial data and then forwarded to a distinct USB-serial converter as on traditional Arduinos.   Your question could have been resolved much more quickly if you had clearly stated the type of board you were using in words, rather than only as a product link (so I edited that into your question).

According to the documentation for the official Arduino Pro Micro:

  Serial: 0 (RX) and 1 (TX). Used to receive (RX) and transmit (TX) TTL serial data using the ATmega32U4 hardware serial capability. Note that on the Micro, the Serial class refers to USB (CDC) communication; for TTL serial on pins 0 and 1, use the Serial1 class.

Therefore to generate output on the hardware UART you will need to change all occurrences of Serial to Serial1

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

void loop(){
    Serial1.print("HelloWurld");
}

The transmit data will be sourced from ATmega32u4 pin 21 which is "D1" (digital pin 1) on the headers.  If you wish to probe it, that would be the best place to do so.

If you wish to transmit data out of a different pin which is not connectied to the ATmega32u4's UART (as your example with digital pin 5 hints you might) you must instead use SoftwareSerial or similar implementation to bit-bang the serial data out of a general purpose I/O pin.

For example (inspired by this example):

SoftwareSerial mySerial(4, 5); // RX, TX

void setup(){
    mySerial.begin(9600);
}

void loop(){
    mySerial.print("HelloWurld");
}


Reading and comparing data from Arduino Uno EEPROM

There is a HUGE difference between "string" and 'c' 'h' 'a' 'r'.

You are comparing address of string "T" with the numerical value of character 'T'.

The expression: if (value == 'T') will be much better.


I think you misunderstood this example: it is not expected to automatically blink!

The LED is suposed to change state at every change of level on pin 2. This supposes that you wired something (e.g. a push button) to pin 2 and that this will make pin 2 change level when something happens (e.g. you press the button or you release it).

On your diagram, there is nothing wired on pin 2, so what you observe is just normal.

If you want to see attachInterrupt in practice, then connect pin 2 to a button with the other button lead connected to GND.

Then you can observe what happens when you play with that button.


Arduino Nano memory issue. SD card and LCD screen together

Your code is using in the neighborhood of 150 bytes for text-strings in RAM, much of which can be moved to PROGMEM quite easily.  For example, replace

Serial.print("Initializing SD card...");

by

Serial.print(F("Initializing SD card..."));

Changes like that to Serial.print() arguments should free up about 140 bytes of RAM.  To free up another 8 bytes, instead of SD.open("test.txt" ...), write SD.open(FileName ...) with FileName previously declared via char *FileName = "test.txt"; so that the text test.txt appears in RAM once instead of twice.

In short, if 150 bytes will make the difference, that much memory reduction is easy.

I briefly examined the source code behind the Adafruit_SSD1306.h and SD.h headers, to see if they use some large arrays in RAM, such as 512 bytes of sector data, or some hundreds of bytes for frame buffers.

Ordinarily, such arrays are difficult to get rid of without a rewrite from scratch or without major loss of functionality.  For most one-off projects, the effort involved isn't worthwhile:  one can instead use an Arduino Mega2560 system, which has 8 KB of RAM, vs the Arduino Nano's 2KB RAM; or can use an Arduino Due with 96KB RAM; or a Teensy, with 8, 16, or 64KB RAM.

However, if you plan a production run and are trying to hold down costs by using Nanos, consider the following approach:   Carefully arrange the processing so that you are done with SD buffers before needing a display frame buffer; and revise the libraries so the SD buffer and frame buffer overlap.  That is, place the smaller buffer within the same region of memory holding the larger buffer.  If processing can't be neatly separated, blank the display while using the shared buffer area for accessing SD data.

[Note, I edited this answer and expanded discussion of buffers in the libraries.]


Underwater positioning system (swimming pool)

How about a tilt switch?  The bottom corners of a pool should allow the car to ride up the wall a little, when it tilts past 5 or 10 degrees, turn it left.....


How to "implement" an Arduino prototype?

with the breadboard

That phrase right there makes the solution a non-starter. Solderless breadboards are good for prototyping, but are too fragile for use in a final project.

As for whether or not you should use an actual Arduino or reduce the circuit to a minimum, that is between you and your wallet. It is possible to make a basic AVR board (including MCU) for under $6 in parts, but the time investment is not entirely trivial.


Flashing ATmega8U2 using another Arduino

There is an official guide. Arduino as ISP and Arduino Bootloaders

But you need to add the 2x3 ISP pin header since some of the signals isn't available on D0-D13 or any other pins.


Writing a single byte is really bad. You are causing a page write with each bye, and each page has a limited lifetime (100,000 - 1,000,000 cycles) so use block instead.

  When writing any amount of data, including a single byte using this
  function,   the EEPROM will refresh the entire page (128 bytes) of
  data.   EEPROMs have a limited write endurance (often 1 million cycles
  per page).   Therefore, if you write one byte at a time, instead of
  writing a full block   at once, you are wasting the chip's lifetime
  (doing so is also MUCH slower).   ONLY use this if you really only
  need to write ONE byte, and avoid it   when you can.   Using a block
  write (below), you can write 128 bytes and only use a single   page
  write (or at most two, if the write is not aligned to a page
  boundary).

This library should do the trick for you:
https://github.com/exscape/electronics/tree/master/Arduino/Libraries/EEPROM/EEPROM_24XX1025


This seems to be the simples form of the Arduino M0 I could find.

From this tutorial site

The ICE programmmer makes it very easy to program and all you need is the SWD pins to program the bootloader.

ISP is for AVR chips where as with ARM chips like SAMD21 you will need to use JTAG/SWD to program it.

I am also try to make a home brew Zero but I am getting stuck after the bootloader where the board just does not want to expose a Serial port.


I was having the same kind of problems (even with new modules) when supplying them by mistake with 5v instead of 3,3V. It even happened that the system was working fine for days after the communication problems due to wrong power supply started to appear.

Also many people have reported similar problems(sometimes communicating, sometimes not) with this module due to poor built-in decoupling especially when using relatively long cables between arduino and module. Just to make sure, put a decoupling capacitor near the module's power and ground pins.

(this is more of a comment but I cannot comment due to reputation.)


Why are my sensors not working (the reaction time is so slow)?

Have you tried with a different trimmer?

I dont seem to be able to find any issue with your code or your schematic, so can you please cross verify that the trimmer is not spoilt.

Can you also check if, when A0 is left floating (nothing connected) it give a random value.


how to build rc transmitter and receiver with an old rc transmitter

If you are controlling an RC plane, you should probably just buy a transmitter and receiver specifically designed for that. They are cheap and reliable and will generate PWM signals on their own.

If you must use an Arduino for some reason, NRF24L01 are not going to cut it as they are not powerful enough to reach 1 km. You should probably look into something like an XBee Series 1. With about 60 mW transmit power, its range is up to 1.6 km.


Merely expanding on what ConnorWolf has said (which I saw yesterday), look at the link he gave you, it gives you a run down on the command you're after.

  The dtostrf() function returns the pointer to the converted string s.

  char* dtostrf ( double          __val,
                signed char     __width,
                unsigned char   __prec,
                char *          __s
  )
  The dtostrf() function converts the double value passed in val into an ASCII representationthat will be stored under s. The caller is responsible for providing sufficient storage in s.

  Conversion is done in the format "[-]d.ddd". The minimum field width of the output string (including the '.' and the possible sign for negative values) is given in width, and prec determines the number of digits after the decimal sign. width is signed value, negative for left adjustment.

From that, I wrote a short sketch that divides millis() by 1000 and saves this in a float, we then use this float as a source for dtostrf() to do it's work and store the result in a char array.

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

void loop(){
  char c[12];
  float f = millis()/1000.0;
  dtostrf(f,11,3,c);
  Serial.println(c);
  delay(111);
}

I have picked arbitrary values, you're going to have to do the calculations on the size of the array to create (don't forget the leading negative sign, the digits before the decimal, the decimal and your precision digits as well as the null terminator!


ADXL345 hangs the micro-controller as vibrations increase

There is a known issue with the default "Wire" library, where if a certain transition is missed, the code goes into an infinite loop (rather than timing out). You possibly are reaching that situation. A possible reason is your printing of numbers at quite a high baud rate. The printing could be taking up so much time (itself causing serial interrupts as the serial buffer empties) that the I2C code doesn't execute in time the I2C interrupt.

You could try dropping the printing baud rate (something I wouldn't normally recommend) which means the serial interrupts would occur less frequently.

There is a library by DSS Circuits that has a time-out for I2C which may work around this issue to an extent:

http://dsscircuits.com/articles/arduino-i2c-master-library

Another thing you could try would be to summarize the data (eg. sample for 500 ms and then send the average), which would reduce the amount of serial comms.

Also you might try lower values for the pull-up resistors, like 4.7k.

So, my recommendations are:

Drop the baud rate (eg. to 9600 baud) and see if the hanging goes away
Summarize data rather than sending each reading
Try 4.7k pull-up resistors

If you have a logic analyzer you could look at the I2C signals and see if you can work out if the data is being transmitted as expected when the vibrations occur.

Saleae sell logic analyzers, the cheapest being $US 109. I use their (more expensive) analyzers extensively for debugging this sort of thing.


How to map 6 bytes of raw data to long long type?

The trick is to use a union data type and get full control of the mapping. The issue of data representation and endian is now under your control:

uint64_t foo(uint8_t* A, uint8_t* B, uint8_t* C)
{
  union {
    uint64_t X;
    struct {
      uint8_t A[2];
      uint8_t B[2];
      uint8_t C[2];
      uint8_t D[2];
    };
  } map;
#if defined(MSB_ORDER)
  for (int i = 0, j = 1; i < 2; i++, j--) {
    map.A[i] = 0;
    map.B[i] = C[j];
    map.C[i] = B[j];
    map.D[i] = A[j];
  }
#else
  for (int i = 0; i < 2; i++) {
    map.A[i] = A[i];
    map.B[i] = B[i];
    map.C[i] = C[i];
    map.D[i] = 0;
  }
#endif
  return map.X;
}

void setup()
{
  Serial.begin(9600);
  while (!Serial);
  uint8_t a[] = { 0x12, 0x34 };
  uint8_t b[] = { 0x56, 0x78 };
  uint8_t c[] = { 0x9a, 0xbc };
  uint64_t res = foo(a, b, c);
  Serial.print((uint32_t) (res >> 32), HEX);
  Serial.print((uint32_t) res, HEX);
}

void loop()
{
}

Cheers!


How to convert my Arduino setup to a PIC setup?

The PIC32 has full (or nearly full) support for the Arduino API through the chipKIT project.  If you want to use one of the smaller PIC chips (PIC16 / PIC18 etc) then you're out of luck. There just isn't a freely available C++ compiler for those chips, so the Arduino API can never really be ported to them.
I have, in the past, cobbled together an Arduino-style API layer for a handful of selected PIC18s which uses structs to emulate a couple of the Arduino C++ objects, but it only worked in a very basic way with no function overloading for things like Serial.print().
One of the problems from a low-end user's perspective is that the PIC32 only comes in harder to use TQFP and QFN etc packages in anything larger than 28 pins. That means you can't breadboard without a development board. Fortunately there are some breadboard friendly options in the chipKIT ecosystem, such as the Fubarino series of boards. For more pins though you'd be wanting one of the bigger boards, such as the MAX32 which is in a Mega footprint (but with even more pins).
It's important to note though that the PIC32 is a 3.3V device and, owing to physical differences in the way that some of the internals work, there are incompatibilities in some of the libraries and functionality (such as no "LOW" or "CHANGE" interrupt support, only "RISING" and "FALLING").


Unable to use Keyboard library with Arduino UNO even after changing the firmware

If I open the rar library file, than I see a file called Keyboard.h. I'm sure you need to include Keyboard.h, than the class Keyboard is known and you can use it in your sketch.


Why the MPU6050 gyroscope read write register value is 0x08 for a full scale of 500 degrees per second?

The i2c address is 0x68 or 0x69. Some modules with the MPU6050 have indeed 0x69, but most have 0x68.

When searching the datasheet for the word "sleep", this sentence is easy to find: "Note: The device will come up in sleep mode upon power-up".

When the MPU6050 powers up, the SLEEP bit is 1 and the sensor is in sleep mode. Therefor writing a 0 is to get it out of sleep mode. After that you can set the sensor as you want.

The FS_SEL[1:0] is a notation that is used a lot in datasheets. It is an indication that only two bits are used. It is not the bit-position in the register. Those bits are located at Bit3 and Bit4. To turn on the lower bit of FS_SEL, Bit3 has to be set to 1, thus a value of 0x08 is needed for the register.


Arduino ESP8266 direct/fast control of the digital pins

After a weekend of searching and trying, here is what I was looking for:

It is slightly different than for the AVR chips. There is one register for setting the pins to HIGH and another one to set the pins to low.

Setting the pin HIGH:

GPOS = (1 << PIN_OUT);

Setting the pin LOW:

GPOC = (1 << PIN_OUT);

using this, I managed to speed up my code by a factor of three. It is not as dramatic as for the AVR chips, since the digitalWrite function is much more simple for the ESP8266.


Can I use LiFe PO4 batteries in a 18650 battery shield?

In my opinion it is NOT SAFE, if your 18650 Battery Shield also charges the battery.
Anyhow some pages state that it is possible to charge LiFePo4 batteries with 4.2V instead of the recommended 3.65V. https://www.powerstream.com/lithium-phosphate-charge-voltage.htm
LiFePo4 batteries have a smaller energy density and therefore capacity. Thus those are not as explosive as Li-Ion batteries. But you are risking damaging the battery and shorten its lifespan.


First off, as a general debugging tip: Always use a minimal example to only test one component to make sure it works. You should have tested the temperature sensor on its own, then the ESP8266 WiFi connection.

Second, regarding this code:

  /* as global variable */
  float val=0;

void loop () {
  val = analogRead(temppin);
  volts = val * 5.0;
  volts /= 1024.0;
  tempC = (volts - 0.5) * 100;

  String string = (String) tempC;
  data = "data=" + string;
  httppost();

  delay(30000);
}

The line String string = (String) tempC; looks very suspicious to me. You are casting a float to a String object, i.e., you re-interpret it with a cast operator. That should not work because a float is not a String object.

What should work is creating a new String object using its constructor, i.e., write

 String string(tempC);

If this is does not work, use the sketch at https://learn.adafruit.com/tmp36-temperature-sensor/using-a-temp-sensor, change sensorPin to 2, double check your wiring and remove the ESP8266.

And as 3rd note: You are hooking up your Arduino's TX directly to the ESP8266's RX pin, according to your schematic. This will damage the ESP8266 module, because it is a 3.3V device and should only receive 3.3V signals -- your Arduino Uno outputs 5V as a logic 'high'. You need a voltage divider or a logic level shifter between them.


Using 3.3V XBee with Arduino Pro Mini 5V Version

This is part of a Fritzing circuit I used to control the x'mas tree lights (the relays and sensors have been snipped out) with an XBee. This circuit uses a 3.3v LDO you may have to change the capacitor values depending on your regulator specs. I chose to use a separate 5V regulator (not shown) but it will work off the Pro Mini's +5V power rail.

There are two FETs that do the actual level shifting, the bonus transistor allows you to reset the Arduino and thus gives you the ability to program it over the air via the XBee (beyond the scope of the question, but if you want to go wireless, go wireless all the way - do the Google for wireless programming over XBee if needed). Note the 0.1uF across the XBee power pins, I recommend this capacitor be placed as close to the XBee as possible to minimize noise (I solder it across the back of the XBee interface board).


Programmed device causes issues between computer and ISP

With  the Tiny AVR programmer, the D+ and D- lines are connected to there own input pins on the ATtiny84, see below:

This means that the pins from the target chip do not interfere with the function of these.

Whereas the digistump board has the outputs of the USB connected to pin 3 and 4, these pins are also connected to pin 3 and 4 of the target, as you know,

This means that as soon as you have your outputs active on 3 and 4 these interrupt the function of the USB lines.

By adding the 2.2k you are increasing the resistance before the Zener regulator circuit(thus decreasing the effect of the voltage from the target on these lines) and allowing the main tiny to have 'control' over the bus lines.

This is actual done on the SPI buses as well when a ISP is programming a target, while the target has other SPI chips on the bus, you add series resistors on the SPI bus, as seen below:

The R is usually between 1k - 4k7ohm. So you method is not a workaround, but normal procedure.

Another method to use instead of the resistor would be to cut the traces on the target board for pins 3 and 4, thus preventing it from going back onto the USB line. This is as I see no need to have control over the USB lines from the target.

  Am I missing something? It seems like a programmer should be able to work without worrying about what the pins on the target device are doing. I assumed poorly, that was the purpose behind the RESET pin. Is there a better solution?

The programmer only toggles reset when programming, and once the target is flashed with your firmware that uses the same lines as USB and the PC then does not recognize the programmer because of this, the programmer won't be able to issue a RESET to the target, as

the PC can't issue it,
the programmer won't know to do that on its own.


How to put together an HKT30 optical rotary encoder?

It's not hard...

The sensor screws into the screw holes.
The disc slots into the gap in the sensor
The case clips on the outside

As to what the wires are, only the datasheet / manual / manufacturer can tell you that. Maybe if you trace them on the sensor board you can work out what is what.


Those 9v batteries are not known for their ability to supply current. Their best uses are long-term powering of low-current standby devices like smoke detectors. I'd first try replacing it with 4 double- or triple-A cells, whatever you can scrounge up for a quick test. My guess is when you cover the robot the Xbox receiver's current demand increases just enough to crash or reset something. A-cells may supply enough more current without the voltage sagging.


ESP8266 Programming using ESP-01 to USB converter

Finally I made a breadboard connection joining ESP8266's GPIO 0 and GND to Programmer's GND for flashing the chip

For more info

Additional Reference:
Programming ESP8266


Building Multidimensional Arrays from simple arrays

As Mikael Patel said, the compiler is already hinting you about what is
wrong. But there are other issues.

In get_quat(), there is no point in returning anything, as the
function is already putting the relevant info in the quatArray
parameter.
Then, when calling get_quat(), you don't want to assign the return
value to anything.
You cannot assign an array like you did, unless it's an
initialization. I would explicitly copy the sub-arrays with
memcpy():

void get_quat(Adafruit_BNO055 ref, double quatArray[])
{
    imu::Quaternion quat2 = ref.getQuat();
    quatArray[0] = quat2.w();
    quatArray[1] = quat2.x();
    quatArray[2] = quat2.y();
    quatArray[3] = quat2.z();
}

void Calibrate()
{
    get_quat(bnoABC, quatCalib_ABC);
    get_quat(bnoGHI, quatCalib_GHI);
    memcpy(quatCalib_mat[0], quatCalib_ABC, sizeof quatCalib_ABC);
    memcpy(quatCalib_mat[1], quatCalib_GHI, sizeof quatCalib_GHI);
}

It could be noted that storing the calibration array twice (as both one
2D array and two 1D arrays) is a waste of RAM. You could get rid of the
1D arrays and have instead get_quat() fill the lines of the 2D array
directly:

void Calibrate()
{
    get_quat(bnoABC, quatCalib_mat[0]);
    get_quat(bnoGHI, quatCalib_mat[1]);
}


Yes, there is a possibility to configure ADC to run faster, as it can handle 1Msps. For four ADC channels it means 250ksps each (with 1us time difference between samples). It's not possible with Arduino wrappers as they are way too slow and also waits for conversion end. You have to configure it directly in MCUs registers, so start with SAM3X8 datasheet.

In short: free running mode, sequenced readings like: 0 1 2 3, with interrupt on 4th sample, interrupt handler and some processing.


I have found a way to tackle this.
Here is my arduino code:

char buf[100];
const double coefficients[28] = {
-0.006416610121367, -0.01179616274682, -0.01212859343535,-0.001491136183145,
 0.0175211951058,  0.03193599126761,   0.0259553014052,-0.004580133449276,
-0.04206485416456, -0.05260424218688,-0.007566809377484,  0.09242896920118,
 0.2100842841173,   0.2894365184419,   0.2894365184419,   0.2100842841173,
 0.09242896920118,-0.007566809377484, -0.05260424218688, -0.04206485416456,
-0.004580133449276,   0.0259553014052,  0.03193599126761,   0.0175211951058,
-0.001491136183145, -0.01212859343535, -0.01179616274682,-0.006416610121367
};

int order_of_filter = 27;
int sample_array[28] = {};
double output_sample = 0;
void setup()
{
  Serial.begin(9600);
  Serial.setTimeout(50000);
}
void loop()
{
  int  sample_in;
  int num_read = Serial.readBytesUntil('\n', buf, 100);
  buf[num_read] = '\0';
  sscanf(buf, "%d", &sample_in);
  for (int i = order_of_filter; i > 0; i--)
  {
    sample_array[i] = sample_array[i-1];
  }

  sample_array[0] = sample_in;

  for(int i = 0; i<=order_of_filter; i++)
  {
    output_sample = output_sample + sample_array[i]*coefficients[i];
  }
  Serial.println(output_sample);
  output_sample = 0;
}

And here is my Python Code:

    import matplotlib.pyplot as plt
  from scipy.fftpack import fft
  from scipy.io import wavfile # get the api
  import serial, time
  import numpy as np
  import sounddevice as sd

  arduino = serial.Serial('COM4', 9600, timeout=1) #COM port depends on the USB port
 time.sleep(3) #time to get connection ready
 # %%

 fs, data = wavfile.read('hfsound.wav')
 samples = len(data)
 #Plot the signal
 plt.plot(data[:samples])
 plt.ylabel("Amplitude")
 plt.xlabel("Time")
 plt.title("Time Domain Response of the Input Signal")
 plt.grid()
 plt.show()
 #Plotting fft
 fft_input = fft(data)
 half_length = int(len(fft_input)/2)
 omega_axis = np.linspace(0, fs/2, half_length)
 fft_n = fft_input[:half_length]
 plt.plot(omega_axis,abs(fft_n))
 plt.xlabel('frequency')
 plt.ylabel('Amplitude')
 plt.title("Frequency Domain Response of the Input Signal")
 plt.grid()
 plt.show()
 # %%

 #Declare an Array of zeros
 outputArray = np.zeros(64000)
 #Sending data to aurdino
 for i in range(samples):
     number = data[i]
     string = str(number).encode(encoding='utf-8') + b'\n'
     arduino.write(string)
     byt = arduino.read_until();
     print(byt.strip())
     outputArray[i] = byt.strip()

 arduino.close()
 # %%

 #Plotting Output waveform
 #Plot the time-domain output signal
 plt.plot(outputArray[:len(outputArray)])
 plt.ylabel("Amplitude")
 plt.xlabel("Time")
 plt.title("Time Domain Response of the Output Signal")
 plt.grid()
 plt.show()

 #Plotting fft of output
 fft_out = fft(outputArray)
 half_length = int(len(fft_out)/2)
 omega_axis = np.linspace(0, fs/2, half_length)
 fft_n = fft_out[:half_length]
 plt.plot(omega_axis,abs(fft_n))
 plt.xlabel('frequency')
 plt.ylabel('Amplitude')
 plt.title("Frequency Domain Response of the Output Signal")
 plt.grid()
 plt.show()
 # %%

 #Playback code
 sd.play(outputArray, fs)
 # %%


Problem with programming digispark ATtiny85 board with Arduino IDE

i=i++;                          //increment by one

The result of the above statement is not defined. That is, it is not necessarily "i + 1".
See:

http://en.wikipedia.org/wiki/Sequence_point
http://c-faq.com/expr/seqpoints.html

Instead use:
i++;

Or:
i = i + 1;

A note about "undefined behavior":
http://en.wikipedia.org/wiki/Undefined_behavior

When an instance of undefined behavior occurs, so far as the language specification is concerned anything could happen, maybe nothing at all.


Arduino's Serial Monitor Showing Constant Value

In your initialisation where you declare each variable and 'connecting' them to a pin you make a mistake. Now you say that senRead is a digital pin instead of a analog pin. Change the value to A0 so you will get

int senRead = A0;

Also in your void Setup() you forget to declare your analog pin as an input. Add a pinMode command that sets senRead as an input.

If this doesn't fix your problem then it is probably hardware related. Check the connections on your breadboard will most of the times solve alot of problems.


First of all your if statement will always be false. You ask if 6 equals 1 (from arduino.h).
It schould be digitalRead(button1) == HIGH. Also it looks like your button should start an impulse of 5ms. Am I right?
In this case you will attach the Interrupt to the Button. Also don't put delays in the Interrupt function. Another thing, that isn't important in small Projects only for you, is to increase the readability by typing "define constants" uppercase, so you know where to find them and that they aren't changeable variables (For this reason HIGH, LOW, INPUT, RISING, ... are all uppercase).

All in all the code should be look like this:

#define BUTTON1PIN          6
#define TRIACPIN            5
#define TRIACPULSE          5                       // [ms]

bool doPulse = false;
long triacStartTime = 0;

void setup(){
  pinMode(BUTTON1PIN, INPUT);
  pinMode(TRIACPIN, OUTPUT);
  attachInterrupt(BUTTON1PIN, pulseISR, RISING);    // attach a Interrupt once!
                                                    // pulseISR is called everytime the button is pressed
                                                    // ISR: Interrupt service Routine (only for Readability)
}

void loop(){
  if(doPulse){
    digitalWrite(TRIACPIN, HIGH);
    triacStartTime = millis();
    doPulse = false;
  }
  if(millis() > triacStartTime + TRIACPULSE){        // Shut down after 5 ms
    digitalWrite(TRIACPIN, LOW);
  }
}

void pulseISR(){
  doPulse = true;                                    // NO delays in ISR! And as short as possible
}


Is it possible to exit a loop on the change of an input state?

figured it out:
void brakeFade2() {
pixels.clear();
pixels.setBrightness(255);
pixels.fill(16711680, 0, 0);

for(int i=255; i>=10; i-=1) {
  if (digitalRead(brakeFeed) == LOW){
  pixels.setBrightness(i);
  pixels.show();
  delay(5);
  }
  else {
    break;
  }
}
for(int j=10; j<=255; j+=1) {
  if (digitalRead(brakeFeed) == LOW){
  pixels.setBrightness(j);
  pixels.show();
  delay(5);
  }
  else {
    break;
  }
  }

}


Try updating the Serial Driver in your system or try using lesser baud rate, i.e. 9600 instead of 115200.


I am not so sure the command that you used to turn all pixels on is right. It might say it in the document but you should try to manually turn a couple of pixels on yourself. check the link bellow if you need more assistance with LCDs.

Also be sure that you connected some power and a potentiometer to the contrast pin and/or backlight of the LCD.

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


If you plan to continuously take data at a fixed rate, I suggest you
don't timestamp the individual records. Instead, store the initial
timestamp and the data sampling period in a binary header, followed by
fixed-size binary records. Then, when you want to retrieve the record
for time t, you can fseek() right to

uint32_t offset = header_size
                + record_size * (t - initial_time) / sampling_period;

If there is a slight chance that you may fail to record some data
points, you may want to have a boolean in each record that tells whether
the data is valid. You can then fill the missing data with invalid
records.

If your Arduino is likely to be turned on and off unpredictably, then
timestamping every record may be a better option, but finding a specific
record will likely be very slow.


nRF2401 communication (extended vs normal)

I've run both version fine together

Your symptom of receiving the same value 30 times would be related to a failed ACK, so the sender thinks it hasn't been received and resends it.

I've had potentially similar problems with the power amplified version running at full power causing interference in nearby circuity, try dialling down the power setting on it.


As you said, the DS18B20 uses One-Wire interface. I2C is a Two-Wire interface. Pratically, you can't use the Arduino to translate that, BUT I found the  DS28E17, a module that could translate the the 2 methods of communication. It should work but I havent tested it.

The DS28E17 is a 1-Wire slave to I2C master bridge device that interfaces directly to I2C slaves at standard (100kHz max) or fast (400kHz max). Data transfers serially by means of the 1-Wire® protocol, which requires only a single data lead and a ground return. Every DS28E17 is guaranteed to have a unique 64-bit ROM registration number that serves as a node address in the 1-Wire network. Multiple DS28E17 devices can coexist with other devices in the 1-Wire network and be accessed individually without affecting other devices. The DS28E17 allows using complex I2C devices such as display controllers, ADCs, DACs, I2C sensors, etc. in a 1-Wire environment. Each self-timed DS28E17 provides 1-Wire access for a single I2C interface.

Hope I helped you.


How to use output from Arduino in C++ code?

Unfortunately, C++ doesn't have native support for serial I/O.

You could use the Windows API directly if you're feeling adventurous. It can be a little complicated to get to grips with, but not insurmountable. You can get basic information about it here. There's an example of using it with Arduino here.

As an alternative, you could use a 3rd party library. This one looks good, although I haven't actually used it myself.


Download and install the open-source, Fritzing CAD software for electronics hobbyist and open the .fzz file with that.

Versions are available for Linux, Mac, and Windows.

Installation instructions are on the downloads page.


Your logic is a bit off. For example, when it is raining and rainSensor < 650, only that part of the if gets executed and the else if parts never happen.

You could just wait for the roof to open/close in a loop. Also, you will find it helpful to break your code into smaller functions. (I'm not sure what the enable_motor pin is for, so that part may need fixing).

// This function determines the current status of the roof
enum {OPEN, CLOSED, OPENING, CLOSING, UNKNOWN};
byte get_roof_status()
{
    if (digitalRead(stop_close) == LOW) return CLOSED;
    else if (digitalRead(stop_open) == LOW) return OPEN; // Fixed typo
    else if (digitalRead(motor_open) == HIGH) return OPENING;
    else if (digitalRead(motor_close) == HIGH) return CLOSING;
    return UNKNOWN;
}

// Helper functions
void open_roof() {
    digitalWrite(alarm, HIGH);
    digitalWrite(enable_motor, HIGH);
    digitalWrite(motor_close, LOW);
    digitalWrite(motor_open, HIGH);
    // Loop until roof is open
    while (OPEN != get_roof_status()) /* NULL */;
    stop();
}
void close_roof() {
    digitalWrite(alarm, HIGH);
    digitalWrite(enable_motor, HIGH);
    digitalWrite(motor_open, LOW);
    digitalWrite(motor_close, HIGH);
    // Loop until roof is closed
    while (CLOSED != get_roof_status()) /* NULL */;
    stop();
}
void stop() {
    digitalWrite(alarm, LOW);
    digitalWrite(enable_motor, LOW);
    digitalWrite(motor_open, LOW);
    digitalWrite(motor_close, LOW);
}

void setup() {
  // Set the pinmodes
  pinMode(enable_motor, OUTPUT);
  pinMode(motor_open, OUTPUT);
  pinMode(motor_close, OUTPUT);
  pinMode(stop_close, INPUT_PULLUP);
  pinMode(stop_open, INPUT_PULLUP);
  pinMode(alarm, OUTPUT);

  digitalWrite(enable_motor, HIGH);
  digitalWrite(motor_open, LOW);
  digitalWrite(motor_close, LOW);
  digitalWrite(alarm, LOW);
}

void loop() {
  // This function is much simpler now
  if (analogRead(rainSensor) < 650) {
    close_roof();
  }
  else if (analogRead(rainSensor) > 850){
    open_roof();
  }
}


Try strptime from the time.h.
void setup()
{

  struct tm tm = {0};
  char buf[100];

  // Convert to tm struct
  strptime("2001-11-12 18:31:01", "%Y-%m-%d %H:%M:%S", &tm);

  // Can convert to any other format
  strftime(buf, sizeof(buf), "%d %b %Y %H:%M", &tm);
  Serial.printf("%s", buf);
}

void loop()
{
    yield();
}


The MPU-6050 is a 3.3V chip. When you are using a 5V Arduino board, you should take care that you don't put current into the SDA and SCL pins of the MPU-6050.

Start with a i2c scanner.
This one: Arduino Playground I2C scanner
Or this one: Nick Gammon I2C scanner
If the I2C scanner halts, then there is a hardware problem with the I2C bus. It might be a shortcut of SDA or SCL to GND, or the MPU-6050 module is not powered.

If the I2C scanner is working, then you know the address (0x68 or 0x69). With that address you can try the Short example sketch to read data from the chip.

If that is working, then you can try the Jeff Rowberg library.


the SCK lines are tied to ground via a 0.1uF capacitor (to smooth the clock signal)

Get rid of that for a start.

  The other three slaves are floating their MISO lines (third state)

That's your problem. They should all be outputs. From the datasheet:

  When the SPI is configured as a Slave, the Slave Select (SS) pin is always input. When SS is held low, the SPI is activated, and MISO becomes an output if configured so by the user. All other pins are inputs. When SS is driven high, all pins are inputs, and the SPI is passive, which means that it will not receive incoming data. Note that the SPI logic will be reset once the SS pin is driven high.

As you can see from that, you should configure all the MISO pins as outputs. However the SPI hardware will turn them into inputs if SS is high. Thus only one slave (the one you set MISO as an output) is capable of responding at present.

You should probably set them as outputs after turning on SPI slave mode. eg.

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

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


attach tells the servo library which pin it should be writing to, this is stored somewhere in ram and write will look it up and communicate with the correct pin.

It's possible that you are using the other pwm capable pins for other purposes and suddenly having that library interfere with that is not a good thing.


How to Connect Dc motor with encoder (pololou) with motor shield and Arduino Mega 2560?

A quick look on Pololu's website reveals that:

    Color   Function
  --------  --------------------------------------------
    Red     motor power (connects to one motor terminal)
    Black   motor power (connects to the other motor terminal)
    Green   encoder GND
    Blue    encoder Vcc (3.5 – 20 V)
    Yellow  encoder A output
    White   encoder B output

Thus: Red goes to M1A and Black goes to M1B on the motor shield.
The remaining wires are for the encoder and go to Arduino pins.
Green goes to Arduino GND, Blue goes to 5V, Yellow and White go to the
digital i/O pins of your choice.

Note: Your motor shield has extra 5V and GND pins so you can connect the Blue and Green wires there.


"Is it possible to do it?"

Well... everything is possible :-)

"Does GPS require Internet connection?"

GPS doesn't require internet. A GPS receiver (e.g. http://www.modulestek.com/prodts/GPS/Mars740-mini/Mars740-mini_SPEC.pdf) is connected to the reading unit via USB or a RS232 interface. The protocol is very simple. However it only provides latitude and longitude. If you want to have an address, map data is required (for this you would need internet - or a large memory).

And of course such a system requires good signals from the GPS satellites.

"What do I need?"

First you need a GPS receiver (see above).

Second, you need a microcontroller unit which runs your application and does all the control of the external units.

Third, you need a GSM module (e.g. http://www.exp-tech.de/Shields/Wireless/GSM-GPRS/adafruit-fona-mini-cellular-gsm-breakout-sma.html) to send a message.
Don't forget the antenna for connection to the mobile communication network.

Fourth, you need a power supply. Ideally it has a battery which can be reloaded when driving.

As you may see, if you put all this together you are far from the "smallest thing possible".

Actually any modern smartphone could be enough. Mount it "invisible" under your saddle, connect it to a bike charger, find the proper App and that's it - although it might not be the smallest solution.

I don't know any, but I'm sure there are products off the shelf that fulfil your requirements, designed and developed by experienced engineers, and thus smaller and maybe cheaper than what you ever could achieve on your own.


Print 2 numbers stored in 24-bits in decimal format

Your code loops from the high order byte to the low order byte, printing each byte as 2 hex digits.

If you want instead to print the first byte as a decimal value, and then the remaining bytes as another decimal value, then do this:

Print byte 0 in base 10:

    Serial.print(data[0]);  //first byte
    Serial.print(":");

Then loop through the remaining bytes, building a result as a decimal value, and print that:

unsigned long total = 0;
for (int i=1; i<bytes; i++) //Skip the first byte
{
    total = total << 8;  //Shift the previous total by 8 bits.
                         //(The same as multiplying by 256, but faster)
    total += data[i];    //Add in the new value
}
Serial.println(total);

The sample code you posted is written to handle a variable number of bytes. The code above does the same thing with decimal results. It's much simpler if you know you will always have 3 bytes or 4 bytes:

For 3 bytes:

    Serial.print(data[0]);  //first byte
    Serial.print(":");
    long total = long(data[1])*256 + data[2]);
    Serial.println(long(total);


The problem was with timer timer settings in library. I checked different timer configurations with different pins and its working now. I found out that timer4 uses pin 13 which is not used in Pro Micro board so I am now using timer 3.


HC-SR04 Echo Pin Fails To Go Low After Trigger Pulse

After many hours of research, I discovered that the problem is related to the fact that there is (apparently) a well-known bug in the HC-SR04 which is a Chinese clone of a Devantech SRF04.  I replaced the HC-SR04 with an SRF04 and the problem was solved.  Now, the ECHO pin always goes low after a trigger and after a time-out (i.e. the object is beyond the maximum measurement distance).


Arduino stopped showing up in /dev and dmesg without response

Ok, I have no idea what the hell is this, but when I double-press the reset button (while connected/powered on ofc) it works again.
This can be seemingly cycled - press once and it goes wrong, press twice and it's ok again... round and round. Seems more like some retarded "feature"


Pull-up resistors are used to define the state of an otherwise "floating" input by pulling the voltage at the pin to a set voltage.
The most typical example is a switch - let's say you have some signal, which is connected to your input through a switch. If the switch is open, the state of your input is "floating". If you try to digitalRead or analogRead that input, the value will be pretty much just noise.
But, if you have a resistor connected from your input to ground (pull-down) or VCC (pull-up) your reading will be consistent (HIGH or LOW, depending on where the resistor goes) while the switch is open.
When the switch is closed, the voltage at the pin will be pulled to the voltage at the other end of the switch.  Because of the lower resistance of the switch relative to your pull-up resistor, this is the input level that will be read by the microcontroller. Pull-up resistors are usually pretty big value (5k-100k) in order to be much higher resistance than the switch and to decrease the current that is used by the switch to produce a signal.
If, for example, you have a pull-up resistor and a switch that connects your input to the ground, when the switch is open you will read HIGH and when it is closed you will read low.
Note that many components act similar to switches, for example transistors, open-drain / open-collector devices and many more, so the switch was just an example.

You can use external pull resistors (just add a resistor from your pin to ground or VCC) or use the internal pull resistors of your MCU.
The Arduino only has internal pull-up resistors (no internal pull-downs) - their value depends on the model, but usually is between 20K-150K.
To activate the internal pull-up resistor for a given pin on Arduino, use the following code:

pinMode(N, INPUT);
digitalWrite(N, HIGH):

where "N" is your pin number or with recent IDEs:

pinMode(N, INPUT_PULLUP);


Turn Arduino on only by double tapping switch?

You can use something like the ATtiny25/45/85 then have a button cell battery to power it, make it a sleeper that listens to the button, and when clicked it activates the Arduino.

The Arduino is then turned on keeping a capacitor alive holding a transistor active, then add another button that drains the capacitor, thus closing the transistor and turning the Arduino off. Or you can program the ATtiny to drain the capacitor if the button is held down.

A button cell on an ATtiny in sleepmode should last around a year or so.

Just some information to get you going further:

http://playground.arduino.cc/Learning/arduinoSleepCode : The sleeper code, it is power saving using interrupts.

http://www.instructables.com/id/Program-an-ATtiny-with-Arduino/ : How to burn an ATtiny using Arduino. Fairly simple, did it myself a few times.


Does the Arduino Yun have to be powered exactly at 5V?

It is fine. That is only 2% too high. The microcontroller is the ATmega32U4 and it can have 5.5V. The wifi module runs at 3.3V, and it has a voltage regulator. Some voltage is also lost in the cable. If the voltage is 6V, then you are in the danger zone, but not with 5.1V.

There are clones and shields of the Arduino Yún. Each has its own power supply demands. You should read what the specifications are for your board. The official Yún board requires 5V from the USB cable or 5V at the VIN pin.


Why this code for ESP8266 goes into STA+AP mode?

It goes into STA+AP mode because your code is telling it to do that.

If you want it to just go into STA mode then your line:

WiFi.mode(WIFI_AP_STA);

should be

WiFi.mode(WIFI_STA);


What could make an LCD stop working permanently after being connected for 5 seconds to Arduino?

It's unlikely that you have killed the unit as this is pretty hard to do from the data interface and your picture is typical for an LCD that has not gone through the initialization sequence.  A dead LCD driver will usually display nothing and what your picture shows is that the LCD controller itself is operating.  If anything is dead, I would suspect the I2C interface board as this would yield the same result you are seeing.  It may also be that the timing of the I2C interface is right on the edge which may explain why a long cable'd setup is working.

Note that if the initialization is not done, no other commands will work.  Note also that the initialization timing and sequence of events is ABSOLUTELY CRITICAL and missing any single step or time requirement will give the result you are showing.

Starting at page 10 of this instructional PDF is my favorite and the basis of my driver that I have been using since the 80's.

The driver I use works on every display I have ever hooked to it, regardless of changes in the particular project's processor clock speed because I paid strict attention to the worst case timing requirements.  If the timing of the I2C interface violates one LCD it may not violate another, i.e. one display can tolerate bad timing while another can't.  There are also issues if the LCD driver uses the busy flag or not:  Blind data transmission without reading the LCD's busy state will work if the LCD is fast enough and the driver is slow enough, otherwise 'No bueno!' plus the interface is not going to operate at its maximum speed.  When using the busy flag (Bit 7 of the interface) there is solid handshaking which confirms (Instead of "Trusts") that the LCD is ready for the next cycle and allows operation right up to the limit of performance.

What I would suggest is that you put the interface on a logic analyzer and verify that the timing is not being violated.

Timing tolerances and variation between parts is like lug nuts on a car... If you car has 5 lug nuts per wheel, it will probably work with 3 or even 2 but NOT UNDER ALL CONDITIONS.  SOME LCDs will be happy with bad timing but ALL LCDs NEVER will be.


Problem to Setting up i2c OLED wemos D1 mini shiled (64*24)

The main problem is, that the module does not get any supply voltage. You connected the Unos 5V to the OLED boards 5V. But this pin doesn't seem to be connected on the OLED shield. It is marked with 5V there, because this board is a shield to be stacked onto the Wemos D1. When you do this, you have 5V on this pin from the Wemos and can access it on the OLED shield for adding further components. (This is the principle of shields. Making even unused pins available on the shield, so that these pins don't get covered by the shield)

The shield needs to be supplied through the 3.3V pin, as it is a 3.3V device and it does not have an own voltage regulator (see the schematics of the shield).

Thus the shield cannot be found, because it is not turned on. It does not have a supply voltage.

That said, you may also get into trouble because of the communication voltage. The Uno works with 5V on the I2C lines, while the OLED shield works with 3.3V. The shield might get damaged by the higher voltage. The schematics the shield don't mention part names, so I cannot know, if they are 5V tolerant (there are 2 ICs in the schematics).

If the shield is not 5V tolerant on the I2C lines, you need to use a bidirectional level converter for both lines (or you can build your own with 2 MOSFETS for each line).


Coin recognition using Coin Accepter in Arduino Uno

Your code is faulty in a number of respects.

pulse should be declared volatile, i.e.

volatile int pulse = 0;

That is because it can change in an interrupt service routine.

You should only do attachInterrupt once, in setup.

Your code to display the count will be timing dependent. What if you happen to display the count after one pulse has arrived, but before they all have? Then you set the count back to zero.

Better would be something like this, untested however:

volatile int pulse = 0;

void coin_value() {
  pulse = pulse + 1;
}

void setup() {
  Serial.begin(9600);
  pinMode(2, INPUT);
  Serial.println("Ready to be collected");
  attachInterrupt(0, coin_value, FALLING);
}

void loop() {

  if (pulse > 0)
    {
    delay (1000);   // let the other pulses arrive
    if (pulse == 3) {
      Serial.println("50");
    }
    if (pulse == 2) {
      Serial.println("20");
    }
    if (pulse == 1) {
      Serial.println("10");
    }
    pulse = 0;  // clear for next time
  }

}

(Edited to add)

Even then your test for 1/2/3 might fail if the coin acceptor sends the pulses twice. Then you might get 2/4/6 pulses. You probably need to display something if there is another count, eg.

  if (pulse == 3) {
    Serial.println("50");
  }
  else if (pulse == 2) {
    Serial.println("20");
  }
  else if (pulse == 1) {
    Serial.println("10");
  }
  else {
     Serial.print ("Unexpected number of pulses: ");
     Serial.println (pulse);
  }


Arduino Attiny 85 IR library compiler error

RAWBUF is defined in IRremote.h. Make sure you include that header before including IRremoteInt.h.


How do I generate a graph from Arduino sensor data?

Perhaps the built-in Arduino Serial Plotter is all you need to visualize your data.  I wrote a tutorial a while back that might help you.


Yes you can, and the solution is very simple. It's in two parts, and they make up part of the absolute fundamental building blocks not just in C, but in almost any programming language.

You can read good information on arrays here, and 'for loops' here (it's about half way down the page). Without wishing to offend, it seems like you are missing some really basic concepts and I recommend starting at the beginning of the tutorial series that the two aforementioned links are part of.

I'll just cover the basics. If you don't understand anything, refer to the tutorials. If you still don't understand then please comment, but make sure you can convince us that you've really given it a good go. We're here to help as long as you're here to learn.

To declare an array of N variables, all of which are the same type, you use:

<type> <name_of_variable> [<number_of_elements>];

or:

long turns[15];

Now you have an array of 15 longs. Ta da!

You now have to set the values of each turn. As your values are all the same (if you ignore the fact that random() ultimately leaves you with different values) you can use a for loop:

for (int x=0; x<15; x++)
{
    turns[x] = random(sizeof(turns) / sizeof(char*));
}

I won't explain how a for loop works; I gave you a link to the tutorial to save me writing it all out myself.

That covers shrinking of part 1 and 2. Part 3 requires a little more thought. That said, as you didn't complete your if statement, I don't actually know what you plan to do if any two adjacent turn elements are the same. I shall assume that you would 're-randomise' one of the duplicates. For this you can again use a for loop, starting at the beginning and running to N-1 th element, where N is the total number of elements:

for (int x=0; x<14; x++)
{
    if (turns[x] == turns[x+1])
    {
        turns[x+1] = random(sizeof(turns) / sizeof(char*));
    }
}

You need make sure that turns[x+1] is not outside of the array, which is why the for loop runs for one iteration less than there are elements.

The fourth shrinkable part is just a matter of swtiching multiple print statements into single for loops:

for (int x=0; x<NUMBER_OF_PRINTS_IN_1st_BUNCH; x++)
    lcd.print(turns[x]);
lcd.setcursor(0,2);
for (int x=WHERE_YOU_LEFT_OFF; x<NUMBER_OF_PRINTS_IN_2nd_BUNCH; x++)
    lcd.print(turns[x]);
lcd.setcursor(0,3);
for (int x=WHERE_YOU_LEFT_OFF_AGAIN; x<NUMBER_OF_REMAINING_PRINTS; x++)
    lcd.print(turns[x]);

All done.


No such file or directory compilation terminated

Please learn how to install a library from here. And see if error is coming or not.


Sending command through SPI on Arduino UNO

Not sure about the int valuex and using the SPI.transfer() function.

A couple of things to know:

You are storing an unsigned 16-bit literal into a signed 16-bit variable. You should be using uint16_t value1 = 0x8026; etc. Also, unless you are planning to change the values, they should be const.
SPI.transfer() transfers only 8 bits of data. You are only sending the lowest byte of your valuex variables. SPI.transfer16() sends an unsigned 16-bit value.

To illustrate, this is how your program should look:

#include <SPI.h>

const uint16_t value1 = 0x8026;
const uint16_t value2 = 0x0801;
const uint16_t value3 = 0x8027;
const uint16_t value4 = 0x0000;

void setup(void) {
    Serial.begin(9600);
    Serial.println("Starting");
    digitalWrite(SS, HIGH);  // ensure SS stays high for now
    // Put SCK, MOSI, SS pins into output mode
    // also put SCK, MOSI into LOW state, and SS into HIGH state.
    // Then put SPI hardware into Master mode and turn SPI on
    SPI.begin();
    // Slow down the master a bit
    SPI.setClockDivider(SPI_CLOCK_DIV4);
}  // end of setup

void loop(void) {
    // enable Slave Select
    digitalWrite(SS, LOW);
    SPI.transfer(1);    // initiate transmission
    SPI.transfer16(value1);
    SPI.transfer16(value2);
    SPI.transfer16(value3);
    SPI.transfer16(value4);
    // disable Slave Select
    digitalWrite(SS, HIGH);
    Delay(1000);
}

That will transfer the stream of 8-bit values:

0x01 0x80 0x26 0x08 0x01 0x80 0x27 0x00 0x00


Can a connection of HC-05 and Arduino Nano receive audio and display waveform on computer?

No, it can't.  The HC-05 is a Bluetooth Serial device, Bluetooth speakers are Bluetooth Audio Sink devices.

It's like asking "Can my bicycle fly?"

I think you'll agree the answer is "NO".

The only possible way of doing it using the HC-05 is to receive the audio using your computer then pre-process it and send the important information to the Arduino through the HC-05, so the Arduino can then send it back to the computer for displaying.  But then, what really is the point of the Arduino...?!


Is it possible to check for correct architecture on OTA update (ESP32 or ESP8266)?

I assume you are the one creating the OTA update.  If so, then why don't you just include a "signature" in the code that is the architecture, i.e. ESP8266 vs. ESP32 and then check for that in your updater code so that it will not install an update for the wrong CPU.


That has a 5V pin (Vcc) but no 3.3V. Also the 5V pin can't provide more than a few hundred mA.

Better specifications are here: https://www.sparkfun.com/products/12640


What are the fundemental differences of different Bluetooth modules for beginners?

As far as simplicity is concerned, HC05 would be the way to go. It is by far the most popular and there are a tonne of tutorials on using it (just a quick google search).
As for the differences:

The HC-05 module can build a connection to other modules. E.g. a Robot being a master and connecting to slave bluetooth module. Or in slave mode to make a wireless bridge to a notebook.
The HC-06 module only can be a slave. This makes it only useful for say connecting a notebook as a master to a robot with a slave module e.g. for a wireless serial bridge.
As for the HC07, support seems low so I would recommend sticking with HC05 or HC06

At the end of the day it comes down to your requirements. If you are only wanting to talk between the phone and your arduino than the HC06 would work fine, however if at some point in time you want to talk to another arduino, than hc05 would be the way to go.


How to use php file_get_contents with ESP8266

To process the request by php, you must send valid HTTP response. The browser tolerates too much.

String webpage = "HTTP/1.1 200 OK\r\nConnection: close\r\n\r\n";
webpage += "
Hello
";


Detect button press inside a for() cycle

You could use the Bounce2 library.

Call the update() method regularly and then check the state with read().

e.g.

for (...) {
  button.update();
  if (button.read() == HIGH) {
     //change pattern
     break;
  }
  // Do strip stuff.
}

As an added bonus the bounce library will debounce your button.


Looks like you are swapping the use of Serial and dbgSerial. I think you mean to use Serial to print to the computer and dbgSerial to communicate with your module. Serial.println should display the message in the terminal on your computer.


Pin Mappings from Arduino Metro M4 Express Board to SAMD51

Edit: Since writing my answer, I found this Google Sheet that does a much better job.

Arduino has some schematics on their website. Here's an image I used to build the following list below.

There are in this format: Arduino Pin | SAMD51 Pin | SAMD51 Description

Analog

A0  3   PA02/EINT2/AIN0/VOUT0
A1  14  PA05/I5/AIN5/VOUT1/SERCOM0.1
A2  15  PA06/I6/VREFC/AIN6/SERCOM0.2
A3  13  PA04/I4/VREFB/AIN4/SERCOM0.0
A4  11  PB08/I8/AIN2/SERCOM4.0
A5  12  PB09/I9/AIN3/SERCOM4.1

Digital

D0  44  PA23/I2C/I7/SERCOM3.1 +5/SOF/I2SFS1
D1  43  PA22/I2C/116/SERCOM3.0+5.1/I2SDI
D2  40  PB17/SERCOM5.1/I2SMCK0
D3  39  PB16/I0/SERCOM5.0/I2SCK0
D4  26  PB13/I13/SERCOM4.1/I2SMCK1
D5  27  PB14/I14/SERCOM4.2/PCC8
D6  28  PB15/I15/SERCOM4.3/PCC9
D7  25  PB12/I12/SERCOM4.0/I2SCK1
D8  42  PA21/I5/SERCOM3+5.3/I2SDO
D9  41  PA20/I4/SERCOM3+5.2/I2SFS0
D10 37  PA18/I2/SERCOM1+3.2
D11 38  PA19/I3/SERCOM1+3.3
D12 36  PA17/I2C/I1/SERCOM1.1+3.0
D13 35  PA16/I2C/I0/SERCOM1.0+3.1
GND
AREF    4   PA03/I3/VREFA/AIN1
SDA 63  PB02/I2/AIN14/SERCOM5.0
SCL 64  PB03/I3/AIN15/SERCOM5.1

SPI

MOSI    29  PA12/I12/I2C/SERCOM2.0+4.1
SCK 30  PA13/I13/I2C/SERCOM2.1+4.0
MISO    31  PA14/I14/SERCOM2+4.2


currentMillis = millis();
  previousMillis = currentMillis;

So currentMillis and previousMillis will always be exactly the same, right?

  if (currentMillis - previousMillis >= interval) {

So if 0 >= interval (which it won't be) do something?

Therefore your fading code will never be executed.


How to get serial data in Arduino from a barcode scanner?

Assuming your Arduino has only one hardware serial connection (it's something like an Uno rather than a Mega) you're quite right in using software serial, the Arduino will already be using pins 2 and 3 to communicate via USB to the Serial monitor so you can't use them to communicate with the scanner.

However carefully look at your first line of code, you've asked software serial to use pins 6 & 7 yet hooked the barcode scanner to pins 2 & 3. Move those pins over to the one's you've specified.

Secondly in your setup function you've begun communication with hardware Serial but not software serial. You'll need to add something like mySerial.begin(XXX) where XXX is the baud rate for the scanner.

Finally you haven't told the Arduino what pinMode to use for 6 and 7. You'll want pinMode(6, INPUT) and pinMode(7, OUTPUT) in there too.


The right way to find and understand the libraries

You should break your problem down into simple parts, which it seems you are on-track to do. Your ultimate goal appears to break down into the following sub-tasks (not in order):

Read sensor value
Connect to a WiFi network
Connect to a MySQL server
Send sensor data to MySQL database

You are unlikely to find a single library to do all of these tasks, but as progress in solving each step, any library that works is the "Right" one, in general. Choose a library that solves an individual task.

You say you tried to upload a simple program to only connect to WiFi, but that it did not compile. The clue to why it did not compile will be found in the actual compile error message. If you can update your question with the error message and the code to the simple program, you can get some guidance from the users of this site to solve that problem.


Converting hexadecimal string to floating point value

If you do indeed have an ASCII string of hexadecimal numbers (and not a
raw binary float), then your best option may be to do the conversion in
two steps:

convert the string to a 32 bit unsigned number using
strtoul()
reinterpret the binary pattern of this integer as a float.

For example, the following program:

void setup() {
    const char modbus_data[] = "416F0000";
    union {
        uint32_t i;
        float f;
    } data;
    data.i = strtoul(modbus_data, NULL, 16);

    Serial.begin(9600);
    Serial.println(data.f, 4);
}

void loop(){}

prints 14.9375.

Note that for strtoul() to function properly, the hex string must be
followed by a character that is not a valid hex digit (a \0 in the
example above).


What is a simple way to measure the ambient light?

Perhaps a LDR and a 10k ohm resistor might work.

#define LDRpin A0
unsigned int LDRvalue = 0;

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

void loop(){
  LDRvalue = analogRead(LDRpin);
  Serial.println(LDRvalue);
  delay(1000);
}


First off, congratulations on entering the world of robotics.  I hope you enjoy it as much as I have.  You are correct that the L298N has a voltage drop that is between 1.8V and 3.2V (at 1 Amp) or 4.9V (at 2A).  This is a problem I sometimes see in older generations of H-bridge designs.  After you figure this problem out and move on, I'd recommend switching to something a little newer like the TB6612FNG or maybe the DRV8871, both of which are pretty common, smaller, and more efficient.  But that's a future step.  First lets get this current project powered.

I'm having to make some assumptions based on the images that you linked to but I'm going to assume that the motor board can take up to 12V and that it ouputs 5V that you are using to power the arduino.  I'm also going to assume that those yellow motors are the familiar cheap hobby motors that run at 3-6V.  If any of those are not true, please comment and we can see how things change.

Now as to what kind of batteries to use; there are literally thosands of ways to power this.  One option is AA batteries as you are doing now.  I would use maybe 6-7 AA batteries to account for the voltage drop of the hbridge but remember that they start at 1.5 but can quickly drop voltage.  And the more current you pull from them, the faster they will drop.  This will be cheaper if you only want to run it a few times since AA batteries are like $0.50 a piece in bulk.  But if you want to run it a lot to experiment, it's going to get expensive (and annoying) fast.  Another option is to use NiCad or NiMH batteries that are rechargable.  The batteries will be a little more expensive initially and you'll have to buy a seperate charger but this will save money in the long run and be able to supply more current to your motors.  NiCad and NiMH batteries are 1.2V (nominal) but come packaged in battery packs so I'd recommend probably an 8.4V pack.  Finally there is the Lipo battery packs, also called Li-Ion (which is a much better and more accurate name but I won't get started on that).  Li-Ion are rechargable like NiCad and NiMH but are much smaller and lighter for the same energy capacity (mAh).  Because of this they have become very popular and have become pretty economical.  For instance you can get a decent li-ion for under $20 on hobbyking and be very happy for several years.  Li-ion do have an inherant risk but as long as you don't do anything stupid, you'll be fine.  They also require a special charger but as long as you aren't worried about super fast charging this isn't too expensive.  Li-ion come in individual cells of 3.6V nominal (sometimes advertised as 3.7V) but also come in packs of 7.2V, 11.1V, or 14.4V.  Remember that these are the nominal values.  A 7.2V pack will start at 8.4V and drain to 6V before it is "dead"  If you go this route, I'd go with the 7.2V pack.

I would highly recommend you go with one of the three rechargable options since that will be more economical in the long term and will also allow for longer run times and will supply more current to the motors.  Hobbyking.com is a great resource for cheap rechargable batteries as is amazon.

I can't explain everything but here are some further quesitons you should google to get started:

-LiPo safety

-Lipo C rating

-Lipo voltage range

-Lipo mAh rating

I just want to fix a couple misconceptions from other answers:

1) Lipos are not expensive as hell if you take into acount how long they last and their other benefits such as size, weight, and ability to supply current.

2) For a given battery capacity, a LiPo will be smaller and ligher than AA batteries and will provide more current and longer battery life than AA batteries.  The ammount of current the Arduino draws will be tiny compared to the current of the motors so don't worry much about it.

3) Not only are Lipos recommended by many people for ground (and air and water) robots, they are becoming the standard for RC cars of almost every size.  The motors you are using here are 6V max so 7.2V lipo is a good way to go.  Later you might use motors that are 12V and will move up to a 11.1V or 14.4V lipo.  Some of the nicer lipos can deliver hundreds of amps to motors and are commonly use in battlebots and similar competions.  But you aren't there yet so you're going to use smaller lipos with these smaller motors and maybe someday you'll use big lipos with big motors.  Every project has different needs.

4) Sometimes a rechargable battery back will get hot if you are pulling a lot of curernt from it.  But as long as you respect the "C" rating (google it) you will be absolutely fine.


How to rotate two or more steppers simultaneously by giving ARRAY of angles?

(Half a year ago, but what the hey...)

Your motor1() and motor2() are currently written as:

do until done:
  take a step
  wait
end

, so yeah, one finishes before the next one even starts.

Each motor function needs to do:

if motor's current-position is not the final position,
   if it is time to take a step,
      take a step
      calc when to take another step
      calc motor's new current-position
   end
end

Now call your motor functions as frequently as possible. Notice that either if test can cause the function to return without doing anything - that is intentional.

This is non-blocking programming - coding in such a way that nothing keeps control while waiting for something to happen (clock ticks, in this case), it just does something, or does nothing, right now, if there is or is not something to do right now, but it does release the processor (the function returns immediately) whether it did something or not.

I call these functions "maybe-do" functions:

maybe step a motor (if, and only if, a certain interval has passed, step the motor);
maybe light an LED (if, and only if, the button is being pressed and it wasn't pressed the last time we looked, turn on the LED;
maybe read the terminal keyboard (if there is at least one character in the Serial input buffer, collect a character).

Then your loop() function should do nothing but call each maybe-do function, in sequence, as fast as possible. And it follows from the above that your maybe-do functions need to execute as quickly as possible and do no more than is necessary to (1) decide whether to act, and if so, (2) to carry out its action, and (3) in either case, return immediately.

And - Bang-Boom! - right there is a half-semester course in block-free programming without interrupts!


Using both a stepper motor and a DC motor with Arduino motor shield R3

You are right: Motor Shield R3 can drive two DC motors or one step motor. So, there are 2 (maybe  3) solutions:
1. Have another shield - now you can drive 2 step motors, or one DC motor(using 'half' of shield, and one step motor using another whole shield.
2. Replace your step motors with DC motor. This option can be more complicated, as no precise position control will be possible when you try to use DC motor for steering. (DC motor are hard to select and hold position, when stepper motors are quite easy to 'go to certain position' AND 'hold'). There is also good mechanical skill needed to remove/place it precisely.

optional option 3. Instead of Motor Shield R3 you can try to use cheap Easy Driver to drive your step motor.


the code and the actual output didn't match

You wrote:

  when i simulate it on proteus, it seems not the same as i mean

The attached picture is not very clear, but it seems to me that it's
doing exactly what you asked for: a PWM output that switches between two
different output pins. The program should work as expected, with only a
few caveats. Let me comment it in some detail:

ICR1 = 100000;

Here you are setting ICR1 to 34464 (i.e. 100000 modulo
216). This is likely not what you mean...

Serial.begin(115200);

There is no point in initializing the serial interface if you are not
going to use it.

for (z = 0; z <= hasil; z++)
    reado = map(hasil, 0, 255, 0, ICR1);

There is no point in calculating many times the exact same value.
Actually, there is no point in calculating it even a single time, since
you are not using the result anywhere in your program.

analogWrite(9, hasil);

Here you are setting the duty cycle to some number between 31 and 1023.
Given that the top value of the timer is 34464, the actual duty cycle
will always be less than 3%. This is the reason why it looks like a
series of narrow spikes on the virtual scope.

But maybe what you really meant is

reado = map(hasil, 0, 1023, 0, ICR1); // note: 1023, not 255
analogWrite(9, reado);

I would not recommend using analogWrite() with a non-standard top
counter value. There is a special case handled in analogWrite() where,
if the argument happens to be 255, you get instead a
digitalWrite(pin, HIGH). This is most likely not what you want. Now
that you started controlling the timer with raw IO access, you should
continue this way.

else if (hasil < 30)

Did you consider what the program should do if hasil happens to be
exactly 30? None of the if/else cases would then match. You probably
meant

else if (hasil <= 30)

but, as suggested by user11249082's answer, a plain else is the best
way to ensure you did cover all possible cases.


"I wanted to understand what factors limit the speed. And how fast can I rotate this motor?"
Read through the data sheet for your motor-the answers are there. Each different motor has its own data sheet. This will require some work on your part to find the data sheet and the info from it you require. Which can be used to deduce the answer your question.


Arduino connection websocket always fails

With the help of the library developer, I found out that it was a problem on the handshake version. So, I just downgraded my socket.io app from 1.0 to v 0.9.11 and it worked.


which is the most efficient way to save power with battery using Arduino UNO?

There is an even greater article on this topic: http://www.gammon.com.au/power

It shows how to reduce your power usage for the Uno from about 50mA to 350nA (0.000350mA) - at this point, you need to factor in the natural drain of batteries.

Also, I have had good success with a project that was activated by a pushbutton, by using a latch - the push button turned the power on; once the power is on, it latched. Then the Arduino can switch itself off, using one of it's pins. As far as I can tell from a simulator, there is no leakage (while it is off, to within the accuracy of the simulator, assuming a perfectly spherical transistor in a vacuum ;) ).

Just in case anyone is interested, my latch circuit can be seen at: http://i.imgur.com/sDvW4rd.png - the two resistors and the switch at the bottom represent the Arduino - +5V coming in the top, GND at the bottom, and one of the pin to switch it off is the switch - this pin should be INPUT to keep the power on; when you are ready to switch of, set it to output -> high. You should get switched off immediately. The switch at the top will switch it on. In the startup part of your sketch, set the pin to INPUT first.


ESP8266 I2C datasheet pins not the same as several examples

Many modules don't have the right pins for I2C available. Thus it was decided that the sensible option would be to use a bit-banged implementation of I2C using software only.

Also GPIO2 has a special meaning for booting, and using it is risky at best, and should be avoided.

Doing it 100% in software has the advantage that any pin combination can be used for I2C.


Each character will be 6 bits (so let's use a byte to store it) and we'll use the following bit to LED mapping

bit0   bit1
bit2   bit3
bit4   bit5

Now you just need an array of bytes where each byte signifies an ASCII character.
Your code will get the letters to display and for each one will do something like this:

byte BrailleBytes[] = {0x01, 0x05, 0xD, etc etc}; // only done the first 3 chars

byte getBrailleForCharacter(char c)
{
    int index = asc(c) - asc('A');
    return BrailleBytes[index];
}

The key to decoding it this way is to make sure you sequence your bytes in BrailleByte the same way the ASCII table does - so if you want punctuation/numbers etc then you'll have to start lower and adjust the asc('A') accordingly

Now you have the byte it is just a case of checking what bits are set and turning on the relavant LEDs.


When debugging a problem like this one, print out values of the variables that the calculation depends on.

In this case, you may find that both windClicks and deltaTime are 0 or 0.0.  The IEEE 754 floating-point-operations specification dictates a result of NaN (not-a-number) for various zero over zero calculations.  It dictates a result of +Inf or -Inf for calculations like 7/0.0 or -13/0.0.  [See, for example, the stackoverflow question, Why does division by zero with floating point (or double precision) numbers not throw an exception.]

If arithmetic generates a NaN or +Inf result, subsequent arithmetic using that result will also produce NaN or +Inf results.

To deal with the problem, you could use deltaTime > 0 as a required pre-condition for calculation of windSpeed.  That is, have an if-statement protecting the calculation block.


What is better approach for non blocking pid algorithm?

The main issue you have is that pulseIn() is completely blocking - and your while loop doesn't help much either.

The "proper" (or what I would consider the "proper") way of dealing with this is to use a timer in gated mode. Actually you need two timers, but the Arduino already provides you micros() that will do for one of them.

Basically your pulsed signal is input into the gate input of a timer. That timer, when the gate input is HIGH, will count the number of ticks from whatever clock source you configure it for (system clock, etc, with or without prescaler, etc). It also needs to be configured so that the timer triggers an interrupt at the falling edge of the gate.

That interrupt reads the count from the timer and resets the count to 0 ready for the next pulse. It also uses micros() to work out the time between successive falling edges (should be about 1100us).  A little bit of maths is needed to calculate the time from the count.

It's not something I have ever done with an Arduino - I have only used a PIC32 for it - though I assume that AVR timers have a gated mode (they should have; they are fairly comprehensive timers). Check the datasheet to be sure - as well as for how to configure it.  On the PIC32 I used two timers both running at the same speed from the same clock source - one in gated mode to count the HIGH time and one in free-running mode to count the full period time. The duty % is then the ratio of the two counts and you don't care about the actual time in human-created units.

Of course, it goes without saying that you need a gated timer for each servo you want to sense...


I want to code a depth sensor for arduino

Your code has several problems:

You are including the MS5837 library twice. That just doesn't pose a problem, because the library has include guards, that make sure it is only included once.
At global scope you use float currentdepth = sensor.depth();, which calls the function sensor.depth(). This will be done before the setup() function, so at that time the sensor library does not have any valid depth data. So it's useless. You can just set it to zero.
In your loop() you are doing sensor.read(), but then you are never actually getting the new depth value from the library. You are just again using currentdepth without changing it ever. You should set the variable to the new value by using currentdepth = sensor.depth(); after the sensor.read().
You are using the statement if ( error=0). Using only a single = means an assigment. So here the variable error get's set to zero and the if statement will not compare it so zero. You have to use a double =: if(error == 0).
if( error >-0): Why are you checking for error being greater than MINUS ZERO. Sure, -0 is a valid integer, but mostly senseless. Also it is questionable, if the logic is correct here, since first you check for error being different than zero. Then you check for it being zero and then (if it is not equal zero) you check for it being greater than zero. If error really happens to be greater than zero, you will first write pwm to the servo and then directly 1400, which is submerging and resurfacing directly after another in only one loop.
The whole if structure seems quite off. You should rethink the logic of the program.

That said, for reaching a set point of whatever kind it is good to use a PID controller, that will get you to the setpoint rather fast and will keep you there. A PID controller can be done in hardware or software. For implementing a software PID controller on Arduino you can use one of the various PID libraries, for example this one. Most libraries also contain examples, that show how to use them.


Restoring all fuse bits on AtMega328P-PU

The following is from:
https://www.allaboutcircuits.com/projects/atmega328p-fuse-bits-and-an-external-crystal-oscillator/

"The two bits to be avoided unless you are absolutely certain you know what you are doing are bit7, the RSTDISBL (external reset disable) bit and bit 5, the SPIEN (Serial Peripheral Interface Enable) bit. Disabling either one is often the cause for "bricked" Atmel µCs; "leave them alone" is good advice."

According to the article SUT0 and SUT1 are clock start up time related bits. It doesn't seem as though it is necessary to use anything special to change them.

You will find the information at the website very usefu. I know I have.

The High Voltage (other names too) programmer you have mentioned should not be necessary if you only changed the SUT0 and SUT1 fuses.

HOWEVER, if you did change the SPIEN or RSTDISBL fuses, you should either get one of the special programmers or just purchase another 328P microprocessor.

If you search the internet for "AVR High Voltage programmer" you will find many ideas for how to build one.

This link :https://electronics.stackexchange.com/questions/33/arduino-as-avr-programmer/71
provides good information.


I'm trying to upload a sketch to my arduino uno, but I get the Error-Message "avrdude: stk500_recv(): programmer is not responding"

The problem was an Bluetooth extension I connected to the board. I removed it, uploaded the program, reconnected it, and that worked!


Including an arduino library in Eclipse Neon (undefined reference to)

I don't have eclipse handy right now, so I may not have the menu options verbatim here, but with eclipse there are more steps to including a library than just writing the line in the code.  Go to the project in the project explorer and right click the project name.  Hit import and select the option for importing Arduino libraries into the sketch.  It should bring up a dialog with a list of all the libraries you have installed and you can choose from there.  Then there will be a folder in your project called includes IIRC and it will have a link to the library that you imported.  Now when you compile it will find the library.


SIM800L - AT Commands not doing anything on Arduino Serial Monitor

Do not use SoftwareSerial on a Mega2560 unless you absolutely know what you are doing.

SoftwareSerial does not work on many of the pins of the Mega2560, and since there are other hardware serial ports available there is seldom any reason to resort to using SoftwareSerial anyway.

Connect your SIM800L to the TX1/RX1 pins of the Mega2560 then communicate using the pre-defined Serial1 object.


The ESP32 uses FreeRTOS to run everything, and that includes the Arduino API. Your code is running in a thread of its own ("loopTask"), and that task by default has 8192 bytes of stack allocated to it.

xTaskCreateUniversal(loopTask, "loopTask", 8192, NULL, 1, &loopTaskHandle, CONFIG_ARDUINO_RUNNING_CORE);

You cannot create local variables and other stack data that totals more than 8192 bytes.

Instead you will either have to have the variable as a global variable (or static local) so it gets allocated in the global data segment, or use new or malloc to create it on the heap (and don't forget the corresponding delete or free call when you're done with it).


Just a math exercise really.

Say you had a 5V source, two Resistors R1 and R2, and an Arduino.
5V - R1 - R2 - Gnd, with R1/R2 junction feeding the Arduino.
R1 is unknown.

Vout is what the Arduino sees. Vout = 5VxR2/(R1+R2)
Vout (R1+R2) = 5VxR2
R1+R2 = 5VxR2/Vout
R1 = 5VxR2/Vout - R2

Vout = ~ 0.00488mV x Analog In reading. (5V/1024)
If you select R2 of say 5K ohm, and you determine Vout to be 3V (analogRead returns 615), then you can calculate R1:
(5V x 5000)/3V- 5000 = 3333 ohm.

Checking with Vout = 5VxR2/(R1+R2), 5V x 5000/(3333 + 5000) = 3.000V


Weight Measurement System using arduino and load cell

You need to use a load cell amplifier between the Arduino and the load cell. Load cells are around 350 Ohms. Four wire. And the signal that needs to be measured are very small.

The current will not be too high. The question indicates that you don't understand the application. (and therefore you are looking for help)

Here are some useful links.

https://www.hackster.io/MOHAN_CHANDALURU/hx711-load-cell-amplifier-interface-with-arduino-fa47f3

https://circuits4you.com/2016/11/25/hx711-arduino-load-cell/

A typical load cell has an output of 2 millivolts per volt of excitation voltage at the full rated weight. For example, if 5 volts were used for the excitation voltage, and the output is 2 mV/volt, then the voltage out would be 10mV at full scale. The voltage difference (compared to the unloaded load cell) is what is measure.

If the excitation voltage (just a technical name for applied voltage) were 5 volts, the voltage at the output terminals, measured from the negative terminal, would be 2.5 volts, half of the applied voltage. But this 2.5 volts is not the measured output. What is measured is the difference between the +signal and the -signal wires.


I bought ATmega328p with bootloader and I can't erase it

Your connections to the ATmega328p are incomplete.
You are missing the connection of ground to pin 22, and you must supply power to AVCC on pin 20.
You should also place the capacitors much closer to the crystal with a very direct route to ground, and try to place the crystal itself closer to the chip.
Additionally you should use supply bypass capacitors.
Please see the minimum wiring at Arduino on a Breadboard, however this document itself is erroneous as it neglects to show the high frequency 0.1 uF bypass capacitors you should have directly across each pair of power pins.
That's not to say that there may not be additional issues as well - but you need to fix the circuit problems first.


Why are my thermistor readings backward?

The voltage Vo is not the over the termistor it over R1! Change place on termistor and R1.
/Mikael


ESP8266 with RTC DS1307 shield - WS2818B shield won't blink - I2C issue?

According to your code, you’ve connected the Neopixel to D2. The RTC is an I2C device, so it’s also connected to D2. How is that supposed to work? The Neopixel isn’t an I2C device.
Move the Neopixel to a different pin that’s not used by anything else - so not D1. Try D3. Update your code to use D3. There may be other issues but at least you won’t be trying to use the same pin to talk to two very different devices.


Measuring lenght of time light levels peak using photoresistor

It is unlikely a photo resistor can be used to time an event with sub second granularity.  This is because the electrons in such a device have many conductive states which they migrate into when exposed to light and out of when left in the dark.  It takes time for the electrons to drift into and out of these conductive bands.  In some cases it may take a good portion of a second. As described in the 2nd paragraph in the Design Considerations section of the above wikipedia page:

  Photoresistors also exhibit a certain degree of latency between
  exposure to light and the subsequent decrease in resistance, usually
  around 10 milliseconds. The lag time when going from lit to dark
  environments is even greater, often as long as one second. This
  property makes them unsuitable for sensing rapidly flashing lights,
  but is sometimes used to smooth the response of audio signal
  compression.


You can use the NRF51822 as module with AT firmware attached to Arduino. Then you need only the AT commands reference and some examples how to send AT commands and parse the response.

Or you can use the 32-bit ARM cortex-m0 micro-controller inside NRF51822 with Arduino nrf5 package. It requires a programmer/debugger hardware for sketch upload.


Is there an Adafruit function to invert the colors of my screen for Arduino language?

There is a function that invert the colors of your screen, you can pick either black on white or white on black, I have tried it and I have quite experience with your display, I think you should try this piece of code.

At the beginning of your Arduino code be sure that you declared the object using the same name.

Adafruit_SSD1306 display(SCREEN_WIDTH, SCREEN_HEIGHT, &Wire, OLED_RESET);

To invert the display

display.invertDisplay(true);

To return the display again

display.invertDisplay(false);

As you said that you want a button to invert the display you might use this code I made

if(digitalRead(BUTTON_PIN)){
    display.invertDisplay(true);
}
else{
    display.invertDisplay(false);
}

Or you might use Interrupts for better performance depending on your code.

As you couldn't find on the internet, I am student and I learn alot from the internet, to for example search for such a function in an Arduino library, try searching it's documentation or it's page on GitHub then afterwards see the function you want through the pages, but don't just search the function directly it will sometimes won't work as they are not that popular.

As a last thing Here is the documents where I got the function with it's parameters from.

I hope I've helped you out. any edits in the answer is well appreciated, as I am a student.


In addition to seconding the FFT approach, I'd like to point out why the F-V approach is problematic.  The circuit you linked to (and F-V circuits in general) depend on having a single-frequency input.  That is most definitely not a description of most music.  About the only thing it would work for would be solos of certain instruments that have repeating waveforms.  That rules out pianos, guitars, and all other plucked or struck string instruments (for example) since their "harmonics" are not true integer multiples of the fundamental during most of the note.  This means you can't extract the fundamental from the waveform to drive the F-V using any simple method.  (Or even any not-so-simple.)  And of course solo instruments have only minor parts in most music.  Yes, the guy in the YouTube got his LEDs to light up, but that doesn't mean he was visualizing the music in any but the crudest sense.


How to clear output buffer of Arduino Uno?

You can't.

The data you are seeing has already been sent by the previous execution of the sketch before the main MCU was reset. That data resides in a small buffer within the USB interface chip (or even within the USB CDC/ACM / USB UART driver itself, depending on your OS) to which you have no access.

You just have to ignore that data. The simplest way is to put a marker at the start of your program to indicate that whatever is receiving the data should start its receiving from this point on. Something like:

Serial.println();
Serial.println("START");


Arduino i2c communication between another arduino and a sensor

Can the following scenario exist?
  Yes. Such a scenario is called Multi-Master.

  If such a scenario is possible, then how would the pseudo code for microcontroller 2 receive-event be?

MCU 2 would just be set up as any other slave. It waits, as normal, for an instruction in whatever for you like. Once it receives that instruction in then switches into master mode and makes a normal request exactly as you would from MCU 1 if you wanted it to read the sensor.

On receive:

Set "run as master flag"
Disable slave mode

In loop:

If "run as master flag" is set:

Perform request to get data from sensor
Clear "run as master flag"
Enable slave mode

Running a multi-master system does have its own set of caveats and things you have to watch out for. You can read more about it here:

https://www.hackster.io/chipmc/arduino-i2c-multi-master-approach-why-and-how-93f638


Send Strings via SPI both ways using two Arduino UNOs(Master to Slave & Slave to Master)

It's not trivial to have both arduinos communicating "with each other" as SPI is a master-slave bus. That means the slave cannot start a transmission, communication must always be initiated by the master instead. Another thing with SPI is that you can't read the slave without writing to it. SPI works like a shifting register: on every clock cycle both devices transmit the byte in their SPDR to each other. So, to read a long string from the slave the master has to transmit the exact same number of dummy-bytes and simultaniously read the incoming stream. This is great if only a specific number of bytes need to be transmitted (e.g. exchanging variables which always consist of the same number of bytes), but becomes complicate when the number of bytes varies. You will then need to implement some protocol that is able to read a variable amount of bytes from the slave (e.g. you will have to tell the master the number of bytes that have to be read).

I think serial communication like UART is perfect for your purpose as communication is real full-duplex, it's no master-slave-system and the common protocol uses a terminating character to end a data stream which makes it ideal to transmit strings. Also the arduino can run several serial interfaces (you might need another for debug output).


C++ Adding Two 16 bit binary numbers together

A few issues here:

The way you “rename” the arrays is wrong, and furthermore there is no
point in doing such renaming.
There is no reason to divide by 10 (ten, in decimal) within your
code: as everything you do is binary, the number ten has nothing to
do with what are trying to accomplish.
While doing the addition, you forgot to loop over the bits.
You shouldn't return 0 in a function of type void. In fact, you
shouldn't return any value.

Fixing those issues should give you something similar to this:

void Solution() {
    lcd.clear();
    lcd.setCursor(0, 0);
    lcd.print("Solution");
    lcd.setCursor(0, 2);

    // Compute the sum.
    int sum[16];
    int remainder = 0;
    for (int i = 0; i < 16; i++) {
        int s = binaryOne[i] + binaryTwo[i] + remainder;
        sum[i] = s % 2;
        remainder = s / 2;
    }

    // Print it.
    for (int i = 15; i >= 0; i--) {
        lcd.print("%d", sum[i]);
    }
}

Note that there is no point in computing a 32-bit result if you can only
print 16 bits: just accept that the computation is done modulo
216, just like a 16-bit ALU would do, or the unsigned int
data type in the Arduino.

Of course, the whole idea of doing the computation one bit at a time is
highly inefficient. See Majenko's answer for a more idiomatic and
efficient way of managing numbers bit-wise in C and C++.