Running light, without delay, and a potentiometer

Your Serial.print()s will print on every iteration of loop() even if that iteration doesn't operate on the LEDs. You'll be swamped with output on the terminal.

One improvement I'd make would be to get rid of the counter and the if/else if/.../else if segment. Rotate a bit through a byte variable for as many bit-positions as you have LEDs. Then call a function with that byte, that will set each LED on or off according to the state of its respective bit.

One more improvement can be had if you rotate the bits through bit positions 1 to 5 (in this case) of your byte variable, because you made the fortunate or perhaps intentional assignment of LED's to digital I/Os that are adjacent bits in PORT-B! One single PORTB = [your byte]; statement could set all 5 LEDS simultaneously.

Update:
PORTB is a register in the UNO's Atmega328p MCU, one of three (PORTB, PORTC, and PORTD) that connect to all of the I/Os on the UNO (or any other '328 based MCU board). By setting the (up to) 8 bits in one port, a single assembly-language instruction can set that many I/Os simultaneously. It is incredibly efficient. The downside of doing that instead of calling digitalWrite() is that the sketch is then tailored to that particular processor. digitalWrite() uses more program memory and execution time (by a lot, especially when setting multiple I/Os), but keeps your sketch processor independent; digitalWrite() knows which processor it was compiled for and how to translate a Digital I/O number to a physical external pin on that processor, so you don't have to.

For those interested in the low level details of the hardware, they are in the processor's datasheet.


I guess you have a DC motor in use. Likely a FET drives it on port 9.

This arrangement is enough to start or stop the motor, however to change direction, you need to swap the two wires on the motor.

I guess you may perfer to do this in software - and for that you need to replace the simple FET driver with a H-Bridge. H-Bridge is an arrangement of electric switches which allows you swapping motor polarity, and it usually comes pre-assembled to a chip.

There are a vast amount of h-bridge motor driver chips to choose from. Google for "pololu motor driver", or "adafruit motor driver".

You can find all the further details in the Arduino examples on the web, e.g.:

https://learn.adafruit.com/adafruit-arduino-lesson-15-dc-motor-reversing/overview


How can the Arduino check if it is connected to a PC and the PC is on?

As suggested by Paul & Gerben, you could check the 5V USB line to see if it has a voltage or not.

I am assuming from your question that the Arduino is not powered from the USB line. I am also assuming that the USB port is not powered when the PC is turned off.

All you have to do is connect VUSB to a digital input through a resistor like so:

Alternatively, you could have the computer send a pre-determined message telling the Arduino that its alive.

If the Arduino receives this message then it lights up the LED on pin 13. If the Arduino hasn't received the "I'm alive" message for a while (ie. a timeout) it then turns off the LED.

A simple PC program could be written to automate this task.


AMIS30543 | Data-Sheet understanding Status register

Most of the data is duplicated between the registers. Both registers contain MSP[6:2].
If MSP contains 111001001 the registers (ignoring the MSB "PAR" bit) would look like:
SR3: 1110010
SR4: 1001001

If we line those up it's then like:
SR3: 1110010
SR4    1001001

You can now see the overlap.
So taking SR3 and shifting it left two places (sr3 << 2) gives you:
SR3:   1110010
<<2: 111001000

Taking the lowest two bits of SR4 with & 3 gives you:
SR4:   1001001
& 3:   0000001

Then ORing the two results together:
SR3<<2: 111001000
SR4 &3: 000000001
-----------------
MSP   : 111001001


How fast is flash reading compared to SRAM?

On an Arduino Uno, or other AVR-based Arduino, reading a byte from RAM
takes 2 CPU cycles. Reading it from flash takes 3 cycles. So flash vs.
RAM is not such a high overhead. However, if you store a LUT in flash,
and the color indexes in RAM, then each pixel would require:

2 cycles for reading the color index from RAM
3 × 3 cycles for reading the RGB values from flash.

That's a total of 11 cycles, vs. 6 cycles it would take to read the RGB
values from RAM, as is done in the stock FastLED library.

It sounds bad, but it could be that the precise timing is not such a big
issue. I don't know the WS2815, but if they are similar to the WS2812,
then you don't need to be anywhere as precise with the timings as the
datasheet suggests. C.f. the blog post NeoPixels Revealed: How to (not
need to) generate precisely timed signals.

Edit: there will be a few more cycles needed for the pointer
arithmetic. I estimate something around 7 cycles. At low level, the code
for getting a color should look roughly like this:

uint8_t *pixel = ...;
uint8_t index = *pixel;            // read from RAM: 2 cycles
uint8_t pgm_p;                     // pointer to flash
pgm_p = &pgm_lut + 3 * index;      // pointer arithmetic: ≥ 7 cycles
struct CRGB color;
color.r = pgm_read_byte(pgm_p++);  // read from flash: 3 cycles
color.g = pgm_read_byte(pgm_p++);  // read from flash: 3 cycles
color.b = pgm_read_byte(pgm_p);    // read from flash: 3 cycles


LEDs on TX/RX lines interfering with the programmig of the device

I just found this reference (using ICSP for output as well as programming -- essentially the same thing), and it suggests a 4.7kOhm.

I didn't have a 4.7k handy, and used a 15k instead and it works.

In my scenario, I have run a sketch with a polarized buzzer connected between RX (digital 0) and GND. When connected directly (with no resistor) the sketch fails to load (but the buzzer works as expected).

If I put the resistor in series with it, the sketch uploads without fail.

You also probably realise, but mentioning for clarity/completeness, you will lose all serial port functionality for debugging purposes and won't be able to use Serial.[anything]. Make sure to not even initialise the port.


How did you set the amps on the http://www.schmalzhaus.com/EasyDriver/ to 0.5A?   What was the voltage at the test point?  The EasyDriver v4.5 schematic says the formula for coil current is A = V/6.  So rearranging, V=A*6, and to get 0.5A, the voltage should be 0.5*6=3V at the motor driver's test point.

The linked motor spec is 0.6A max per coil, and if things went wrong, you could have overloaded a motor.  The 18V battery could have easily provided 1.8 amps to the 10ohm coil in the motor for a bit, before 3x the rated current of the coils would burn it out, or the easydriver went into thermal shutdown or something.

The easydriver looks like it would be capable of controlling the current adequately, but if misconfigured, could easily overcurrent the motor.


ESP8266 WiFi Not Connecting to Internet Without Static IP

This is normal behavior. well not really, that address is called a apipa address.
It's normal behavior for alot of O.S's to give itself an address in the 169.254.x.x range when they fail to get DHCP responses.
My guess is your library is doing this for you.
It's kind of like the ad-hoc of addressing, if all devices fail to get a dhcp response they will all be assigned to the same subnet, and can communicate with those apipa addresses.
My suspicion is that it may be your router.
You can verify this by downloading a free DHCP server application for your OS. Plug in via Ethernet for the PC that's running the DHCP App, Turn off DHCP in the router. If it stops happening you know it's the router.
Edit: Also, this may be a firmware caveat in the router. Check the router manufacturers website and see if any firmware updates are available. if it hangs with DHCP, most likely every customer with that firmware revision has had this problem. This sort of thing usually gets patched very quickly.


The AdaFruit Trinket just doesn't have a lot of memory - 8kb, of which 3kb is used by the bootloader.
The order I look for things to reduce the footprint of an Arduino program are:

data (e.g. large strings)
libraries
your code (especially doing the same things several times, which might be combined into loops or functions).

In this case, you don't have much data. Most of your resulting program size is in the libraries you use.
It seems like you use the clock solely to detect the year - that seems like a lot of overhead just to figure out what year it is. It then does nothing for subsequent years (or prior years), if I read your code correctly. Maybe you would consider dropping this code? Then you can skip the entire RTC library. At least try it to see how much you save. I suspect that the RTC library will use another library to do the underlying work.
You use the <Wire.h> library, but don't reference it in your code. It should be optimized out (unless used elsewhere), but there's no reason to have it there.
You may also save a little space by replacing initialized variables which don't change to constants. Storing 25 in a variable takes 1 byte, plus 2 bytes every time you reference it; 25 in a constant gets optimized away, and will take up 1 byte every time you reference it.
As mentioned in the comments, you can also save a few bytes by specifying the size of your int's, especially initialized ones.
Another option would be to use a larger chip - the AtMega328p used in (for example) the Arduino has 32kb of flash - 6 times the (available) size.
You can also save some bytes by removing the clause  if(!rtc.isrunning()) {, once you have set it up once.
Additional: I have had some success reducing footprints by reimplementing a subset of a library. Usually, libraries are very well implemented, but if your needs are substantially different/simpler than what the library was designed for, or you are willing to forgo parts of it (e.g. error checking), then SOMETIMES this can help. WARNING! There is a HIGH price to pay (coding, debugging, loss of error checking, undetected bugs etc), and it may not save you anything in the end.
You can also (sometimes) move data (e.g. large strings) to eeprom. The Trinket has 512 bytes of eeprom. You may need one sketch to load the data into eeprom, to run before loading your main sketch. eeprom has it's own overhead, so may not be worthwhile for 512 bytes, it is slower (which probably won't matter for this), and you have a limited number of writes.
Another few bytes may be saved by doing all the maths for the tone frequency/time beforehand, and sacrificing something. For example, you beep for 50ms. If, instead of passing the frequency (between 262 and 349 hertz) and instead pre-calculate the delayAmount (for 262 hz, this would be 1,000,000/262 = 3817ms); your looptime for this is ((timeInMilliseconds1000)/(delayAmount2)) = (501000)/(38172) = 6.55 cycles. 7 cycles is probably "close enough" for all the tones you want to produce. So you can hardcode 7 cycles (using a constant of 7 for looptime), and get rid of that formula to calculate looptime.
In a similar way, if you don't care too much about the exact frequency (which varies between 3817ms and 2865ms depending on your random number), you might specify the delayamount as 2865+random(0,3)*238 (make sure you store at least the random number, you don't want it to change during the loop!).
You now have:
#define random_beep_length 7
void random_beep (unsigned char speakerPin)
{   // http://web.media.mit.edu/~leah/LilyPad/07_sound_code.html
    // Heavily modified!
  int x;
  unsigned char pitch = 2865+random(0,3)*238;
  for (x=0;x<random_beep_length;x++)
  {
    digitalWrite(speakerPin,HIGH);
    delayMicroseconds(delayAmount);
    digitalWrite(speakerPin,LOW);
    delayMicroseconds(delayAmount);
  }
}


The standard way of doing this is to use delimiters. Serial is a streaming protocol, you don't necessarily get data in fixed size chunks. Something suitable would be like:

<1.23,4.56>

Notice the delimiters "<", "," and ">".

The receiving end ignores incoming data until it gets "<". Then it reads until it gets a comma. Between those two are the first number. Then it reads again until it gets a ">". Between those are the second number. Now you validate that what you got are in fact numbers.

This allows you to easily expand in the future to larger numbers, and more decimal places, eg.

<42.213,674.50326>


How to set the sampling frequency in Arduino without using a delay

Use the concept of blink without delay.

Instead of using delay() to set the timeout you use a timestamp and check micros() against that to see whether your interval has passed:

const unsigned long READ_PERIOD = 4000;  // 4000 us: 250 Hz

void loop() {
    static unsigned long lastRead;
    if (micros() - lastRead >= READ_PERIOD) {
        lastRead += READ_PERIOD;
        if (digitalRead(10) == 1 || digitalRead(11) == 1)
            Serial.println('!');
        else
            Serial.println(analogRead(A0) * (3.3/1024));
    }
}


Multiple VL6180X distance sensors interactive problem

You can use an I2C multiplexer (TCA9548A). One I2C input can be output to one of the eight I2C outputs.

It has 8 configurable addresses, so you can connect 64 I2C devices with the same address by using 8 multiplexer chips.


Differential voltage measurement using Arduino

As you do it with the multimeter: connecting ground to the lower potential (4.95 Volts in your example) and the volt probe to the higher potential (in your case 5.0 V), you can also connect the Arduino between the two potentials: Arduino GND to the lower (!) potential and A0, A1, ... or A7 to the higher (!) potential.
As long as you use the correct polarisation and the difference between the potentials is less than VCC of the ADC (5V Arduino ADCs) you should be save.
The resolution of the Arduino might be a problem. I don't know what resolution you need; 5V divided by 1024 is about 5 mV per step.
You might want to provide a reference Voltage at Vin of -let's say- 1 Volt if you need a better resolution. That would improve the resolution to about 1 mV per step. But then the meassured voltage must no exceed the 1 Volt reference voltage.
EDIT (Gerben's comment)
You could use the 1.1V internal reference of the ATMega328P (analogReference(INTERNAL))
And please let me give you a security advice: If the resistence in any part of your meassuring setup is significantly lower than the resistance between the messuring points (e.g you shorten the probe wires), then there is a chance that 90000 A running through this setup. That could burn away your hand, arm or even your life. Amperes kill; not Voltage. I've seen a wrench that was vaporized (ok, melted, ok glowing ;-) ) in a second, when it had fallen between the poles of a car battery (12 V; 300 Amps). An you operate with 90000 Amps. !


Setting the sampling rate for timer interrupt

// = 16000000 / (8 * 50) - 1 (must be <65536) that 8 in the formula refers to the prescaler. So this formula expect you to have a /8 prescaler. But four lines below you used a /64 prescaler. So your timer runs 6.25 Hz.

When you changed it to /8, you got the correct frequency.


Removing CH340g chip from Arduino Nano clone.. any issues?

No problem whatsoever as long as you aren't powering the board over USB. You may still be able to do that though depending on what role the CH has in managing the power.

Personally I think all CH chip should be removed from all boards. They are horrible chips and cause no end of problems.

I assume you have an FT232 adapter board (or similar) to then use for the programming of your Arduino.


How to measure room light without LEDs interfering?

Normally you should be able to switch LEDs off, make a measurement and switch LEDs back on without a noticeable delay. Brightness variation is noticeable below 100Hz, which translates to 10ms period.

What you need is a photodiode with fast response time (under 0,1ms or so, though there are devices responding in nanosecond range). Phototransistors and LDRs are considerably slower.

LEDs response time is in single-digit microseconds even for white LEDs, and RGB LEDs are even faster. Below is a response of typical LEDs to a 200ns pulse:

Regular AnalogRead takes about 0.1ms (and, again there are faster alternatives), so you can easily achieve kHz measurement frequencies where brightness variation is completely unnoticeable.


You could use lots of options to control it from Mbed boards to the Uno with a wifi shield, to a raspberry pi to .... the list goes on.  But if it were me I would use the something like the ESP8266 which cost less than $10 usd and can be programmed with the arduino IDE (I'm assuming that is useful given the community this was posted in).  There are also lots of tutorials available online for this kind of thing.

To trigger the button you have two options: a non-destructive one and a destructive one.  For the non destructive one, use something like a solenoid in a custom mount or a servo and small lever arm to push the button.  The benefit to this is that if you change your mind you just have to move the device and you still have a perfect unharmed kettle.  Plus, you can still use it if your device breaks or malfunctions.

For the destructive option, open up the kettle to get at the buttons or button pads and solder a wire to each side.  If you're lucky you can do this so that it can still be put back together and the original button still work.  One option is to use a relay to connect them.  You can use a small solid state relay or a larger coil relay; both would be under a couple of dollars and not large enough to be too obtrusive.  Using a relay is nice since you don't have to worry about which voltages are being used on which side of the button and it isolates the microcontroller from the kettle better.  (Actually some relays are polarized so if it doesn't work, switch the wires and try again).  Another option is to use an  optoisolator like this one.  It is polarized so if it doesn't work switch the wires.  Another option is to use a mosfet.  I believe it will work if you get an N channel mosfet with a Vgs (gate to source voltage) less than 3.3V.  Hook up the Source pin to the more negative of the two button leads and the Drain to the other.  Hook up the gate to a pin on the micorcontroller.  Also, you should put a resister between the gate and the source pins.


There are a few files in the Arduino Due core that you should have a look at. They give great insight into the SAM register set up; variant.h, variant.cpp and chip.h

After that you can dive into the libsam and the many components (include/source).

The SAM code has a very different structure and style compared to AVR.

Cheers!


TQFP Atmega328pu-th cant upload sketch sync error (breadboard)

Hey guys I managed to figure it out I had to remove the dtr pin from pin 29 , I made a video to help anyone else looking to do it, I don't know if it breeches any self promotion? But hope it helps because i found it difficult to find any resources. https://youtu.be/5CPYz6Kde7M


What is the difference between the revisions of the Arduino Uno board?

Here is a summary from the official site:

Revision 2 of the Uno board has a resistor pulling the 8U2 HWB line to
ground, making it easier to put into DFU mode.
Revision 3 of the board has the following new features:

1.0 pinout: added SDA and SCL pins that are near to the AREF pin and two other new pins placed near to the RESET pin, the IOREF that
allow the shields to adapt to the voltage provided from the board. In
future, shields will be compatible with both the board that uses the
AVR, which operates with 5V and with the Arduino Due that operates
with 3.3V. The second one is a not connected pin, that is reserved for
future purposes.
Stronger RESET circuit.
Atmega 16U2 replace the 8U2.

A more detailed list of changes can be found here.
R2:

The rotation of the ATMEGA8U2 (the little chip near the USB port) was changed by 45 degrees.

Four solder pads (JP2) were added, connecting to pins PB4 to PB7 of the USB ATMEGA."

Instead of R1's solder pads, R2 adds header pins to the USB ATMEGA ICSP.

An LED connected to pin 13 was added. It turns on when pin 13 is HIGH, off when LOW.

The main microchip was changed from an ATmega168 to an ATmega328.

A resistor was added between the DTR (HWB) line and the ATMEGA PD7 pin.

R3:

The rotation of the ATMEGA8U2 was changed back by 45 degrees.
The ATMEGA8U2 was changed to an ATMEGA16U2.
A diode was added, wired from +5vdc to the reset pin, cathode to +5vdc.

The 8 pin connector that contains Arduino pins 8 was changed to 13, GND and AREF for a 10 pin connector. The extra 2 pins are connected to AD4/SDA and AD5/SCL. Also, the 6 pin connector that has the reset pin connected to it changed to an 8 pin connector. One of the new pins on this header is the IOREF pin that allows shields connected to the board to adapt to the voltage of the board. The second pin is not connected and reserved for future use.


Yes, it sounds like you fried something.

I can't quite make out what it was you did from your description (I'm sure it makes perfect sense to you with the hardware in front of you), but the symptoms do sound somewhat fatal.

What actually happened depends very much on the Arduino you have - if it's a genuine one or a cheap Chinese clone. Either way the USB circuitry seems to not be functioning. Whether that is because the USB chip (varies depending on if it's a real Arduino [ATMega16U2] or a clone [CH340G]) or one of the voltage regulators is unknown.

You should power the board up normally and test the voltages at the 5V and 3.3V pins. Also if a component is still getting hot you should note which component it is, and that will give more of a clue as to what went wrong.


Can't upload sketch to arduino Uno board

In Arduino IDE check that

correct port number is selected in Tools -> Port
correct programmer is selected in Tools -> Programmer (should be AVRISP mkII if you upload the code via USB cable)
correct board is selected in Tools -> Board (Arduino/Genuino Uno)

If above doesn't help, install the latest version of Arduino IDE.


Powering Arduino with 12V AC-DC Adapter Jack

You can use that to power the Arduino through the barrel jack or the VIN pin.  The only way you end up with smoke is if you try to pull too much current through that setup.  Don't power any motors or solenoids directly off of output pins for example.


Noise in Analog Read Serial from an instrumentation amplifier(ina122p)

"noisy most of the time" - good news: if it's not all the time, that's a sign it can be fixed.
"bandpass filter is also not really helping" - INA122P circuit likely has something wrong.  check any resistors involved. Edit: if this was about U2.2, see below as that doesn't look like a band pass...
"regular solid core wire and alligator clips to connect to the electrodes" -
basically 0 shielding with mini-rabbit ears at each end and a big loop area between the wires.
Eventually you will want something better than gator clips.
My main recommendation is that as far as wire goes, if you form twisted pairs they tend to be pretty darn good at rejecting noise at least for that part of the wire.  You will want to twist a signal along with its reference (such as a +V and a ground).
Some explanation of the circuit:
U2.1 is creating a 2.5V source that it uses as the reference 'ground' for U1.  Reason for this is to treat 0 as "-2.5" and 5 as "2.5" as op amp math is generally done on a +V, -V basis.  (Personally, I prefer to use voltage regulators to make power buses instead of this. As a result, I give a stink eye to circuits that use the op amp method and claim something about reducing part count.)
U2.2 is a capacitor shy of an active band pass.  It's a high pass filter that is helping preserve and even promote some of the high frequency noise you are picking up. So yes, you may wish to modify or even ditch it until you have high frequency noise under control.
If possible, you may also wish to look into operating at a higher voltage.  This can help improve your signal to noise ratio.  If your signal is essentially +/-2.5V, 250mV of noise would be 10:1, but if you can run at +/-5 V, that same 250mV noise contribution gets dwarfed 20:1.


No, you cannot. A DAC cannot provide enough current to either directly drive a motor or to power a motor driver (which is basically driving the motor directly through a switch anyway).

A motor driver requires a PWM signal to rapidly switch a high current source on and off to set the motor speed.

You could feed the DAC output into the input of a voltage-to-PWM converter chip which would then feed the motor driver's EN pin, but that is pretty pointless when you could just use a small microcontroller to receive the digital speed value and directly generate a PWM signal.

After all, that is the kind of job that small microcontrollers are designed for...


Can the 2nd MCU on the UNO R3 be used for keyboard emulation?

Yes, it is possible. using LUFA, you can burn new firmware to the Serial converter. The only problem is that you need to re-burn the USB-Serial converter to upload another program.

Info: http://www.fourwalledcubicle.com/LUFA.php

Specific page: http://mitchtech.net/arduino-usb-hid-keyboard/


How to initialize digital output pin as low

There are two solutions:

Use the pin as a open-collector pin as in the answer of VE7JRO.
Switch the pin between input (high) and output with low. I prefer
to use the INPUT_PULLUP.
Write the output value before setting the pinMode.

All the microcontrollers of the AVR family (ATtiny and ATmega chips) allow to set the output value before setting the pin as output. This will enable the pullup resistor, but when it is done in the right order, that is fine.

Because this is a common way to use the microcontrollers and processors, the Arduino libraries allow to use that. The Arduino libraries for the SAMD processors (Arduino Zero, M0 and MKR) are written to allow that as well.

void setup() {
  digitalWrite(pin,HIGH);     // pre-set output value to HIGH
  pinMode(pin,OUTPUT);        // set to output, it will be HIGH
}

void loop() {
  digitalWrite(pin,LOW);
  delay(1000);
  digitalWrite(pin,HIGH);
  delay(1000);
}

When the relay module has floating inputs (as far as I know they do not) then you need extra hardware to pull the signal high with a pullup resistor to keep the relays disabled during reset.


Function declared in another file not recognized (undefined reference to)

The compiler didn't have a problem; the linker did. That is, once your main function was compiled (correctly) to call pin_init(), the loader tried to put together all of the compiled modules and link up calls that were not satisfied locally - within the same file - to functions defined in another module. That is when this message got generated. No such function definition was found, despite the declaration of it in main.ino.
If you can compile this with the Arduino IDE, watch what it does: It will compile each of your source-code modules, one at a time. Then link all of your modules' compiled versions together to produce the .hex file (that will eventually get uploaded to the Arduino). You need to mimic that when you're compiling & loading from the command line.
Update:

today I rebuilt the project with different names

Is your .cpp file in the same folder as your .ino file? Or in another folder, such as the folder containing your .h file? I suspect it's the latter. When I built your project it in the Arduino IDE, it succeeded when the .ino and the .h were in the same folder, failed exactly as you described when I moved the .cpp file to where the .h file is.
The solution goes back to what I suggested earlier; that no definition of pin_input() was found, as the .cpp file containing it wasn't seen by the IDE (or your command-line compiler) and therefore not compiled and linked. Each of your files needs to be compiled and all of them together need to be linked, for the external calls to be satisfied.
With the IDE, put your project's .ino and .cpp files in the same folder so the IDE will see and compile each of them and know what to files to link. The IDE won't give you much flexibility for locating your .cpp files.
With the command line compiler, you can put your files wherever you will, make a separate[1] compile only run for each of them, then make another run of the linker component[2] naming all of the compiled units (the IDE names them as .d) and provide the path to your library folder(s).
[1] I'm not familiar with the command-line compiler's command-line syntax; maybe you're able to specify a number of compiles with one command.
[2] Again, IDK whether you need invoke the linker with the same command but with a link-only option switch, or you'll need to invoke the linker yourself, on the command line.


I have two suggestions.

Get rid of the delay(1000); in the loop and replace it with code from the BlinkWithoutDelay example that comes with the Arduino IDE: https://www.arduino.cc/en/Tutorial/BlinkWithoutDelay.
Debounce the buttons. There are several libraries on Github that simplify this, for example: https://playground.arduino.cc/Code/Bounce.


I have several clone Pro Minis I got from several sources on ebay for ~ £2 ($3) each. I also use Ubuntu (10.04 on this old PC but it's fine).

I started with a USB converter similar to yours and it was a bit hit-and-miss choosing when to press the reset to upload. Once I got connections right and worked out when to press reset it became a more reliable procedure but still a pain.

I realised that it would be better to use the auto-reset from DTR so I got a cheapo USB to serial from ebay which claimed to be FTDI (or compatible?) though I didn't know what that meant at the time. With a small converter board to make the right connections it works well.

Your connections look good so if you haven't damaged anything it's probably a matter of when to press reset. Windows won't help!

You must choose the correct board in the Tools menu of the Arduino IDE - Pro Mini with correct AVR chip, speed and voltage. I use programmer AVR ISP (I think)


Arduino Mega: Interrupt not working? Use any pin for interrupt?

You are right when you say "technically they aren't interrupt pins".

The only pins you can use as interrupts are 2, 3, 18, 19, 20 and 21. There is no way of changing that. You can't magic more interrupts out of thin air.

However there is a different interrupt system that may help you out - the pin change interrupts.  These are harder to work with since they are grouped into sets of pins that share the same interrupt, but there are far more pins with this kind of interrupt available. Note that you still have to be careful which pins you choose.

There are a couple of libraries available to help you configure the PCINT registers should you need it.


Why send my Arduino sometime Hex and sometimes the wrong?

I have found several problems with your program, although they may not
be related with your primary problem:

while (!Serial & !Serial1 &! Serial2)

You mean while (!Serial || !Serial1 || !Serial2), although this is
only useful with virtual serial ports, like on the Leonardo. On the
mega, all of these ports are real hardware ports.

void sendBinaryValue(short incomingByte)

The way you name the parameter is misleading: a short is not a byte,
it's two bytes.

int temp = (incomingByte & 0xFF00)>>8;

You are bit-shifting a signed number, which is going to do a sign
extension. This is probably not what you want.

Serial.print(temp, DEC);

You are printing several numbers one after the other with no separator.
This is going to cause ambiguities: you cannot know whether "345" means
"3 45" or "34 5".

Finally, I don't get the purpose of your functions. Why don't you just
print the numbers like this?

Serial.println(incomingByte, HEX);
Serial.println(currentMillis);


Don't. Instead just access the underlying C string:

Serial.print(F("Name -> "));
Serial.println(founded_dev.getName().c_str());


About maximum length of matrix can be use for matrix invertsion on atmega32

Floats in the Arduino IDE are normally 4 bytes. So you can work out with a calculator that your matrix will take at least 15 x 15 x 4 bytes (900 bytes). That is out of a total of 2048 bytes of RAM on the Atmega32.
That may seem to be enough RAM, but other things, like the libraries, will also take RAM. I did an answer to a question about RAM a while back. Even a very simple sketch (in this case) took 346 bytes.
Also, your library, or whatever-it-is you are using for matrix inversion, may require RAM for variables, etc.
My suggestion would be to make your code invert a very small matrix (eg. 1 x 1) and see how much RAM that uses. Then you can extrapolate out fairly simply to how much would be needed for a larger matrix.


Under normal operation the + connection of  any inductive component (motor, relay, etc) is at a higher potential than the - connection.

During a "back EMF" event (the collapsing of the magnetic field) a large voltage of the opposite potential is generated.  That means that the - connection suddenly becomes a much higher potential than the + connection.

That is very bad for anything connected to the - pin of the inductive load.

With the diode connected backwards like that across the inductive load, under normal operation, it does absolutely nothing.  However, when the - pin becomes a higher potential than the + pin the diode will become forward biased and start to conduct.  That allows a very low resistance path for all the energy stored in the coil of the inductive component to flow from the high potential to the low potential, which is what it wants to do.

Without it, the only way for that energy to get from the high potential to the low potential is through the rest of your circuit, which it won't like.

The excess energy at the - side of your motor wants to get to the + side. That's the only place it wants to go.  It'll (crudely speaking*) take the shortest, quickest, route to get there.  That means it goes through the diode and nowhere else.  Straight from the black wire to the red wire of your motor.

* Note: In actuality the energy will take all possible routes at once, but in varying proportions depending on the resistance of the route.  The lower the resistance the greater the proportion. Because the diode is such low resistance it gets the majority of the energy and only a very negligible proportion takes the other possible routes through your circuit. Unless your circuit is incredibly sensitive it won't even notice it's there.


Is the MKS GEN V1.2 compatible with Arduino IDE as Arduino MEGA Board?

It features an onboard ATmega2560.

This means that it is internally compatible with the Arduino Mega 2560. This does not mean that it is completely compatible with such since of course there is no way to use Mega shields with the board. This also means that there may be a core that provides better facility with the board, supporting its connections (LCD, positioning, heater/fan, etc.) better than the generic Mega core would.


What do the TinyGPS++ output parameters mean?

As you can see when you look at the source code of the FullExample.ino that is part of the TinyGPS++ library, the values you marked are:

Course Speed Card*: The current speed (in km/h), course (in degrees) and cardinal course (which is the course translated to a cardinal direction on a compass, i.e. N,S,E,W, NE, NNW, etc.) of the GPS receiver (i.e. you).
Distance Course Card**: The distance (in km) and course and cardinal course to some location or waypoint (London in this example).

After the information you added in your edit, this means the following:

0.00 is your current course over ground (i.e. due North)
0.06 is current current speed over ground (i.e. as good as stationary)
N is your current cardinal course
2365 is the distance to London (km)
294.06 is the bearing to London from your location
WNW is the cardinal bearing to London

* this is also known as SOG (Speed Over Ground) and COG (Course Over Ground, which is used in (aero)nautical navigation) or Bearing.

** this is also known as DTG and CTS (Distance to Go and Course to Steer) when navigating to a GPS waypoint.


HC-05 Module not receiving commands and not pairing

You have seen contradictory statements, because there are many variables here, that might be different for each of the tutorials.

some connect the RX and TX pins in reverse to the Arduino, some don't, some specify other pins on the board

There are basically 2 ways to communicate between the Serial Monitor and the HC-05:

You can connect the HC-05 directly to the USB Serial chip on the Arduino board, thus you would communicate directly with the HC-05. In that case the TX and RX pins are used, since they are connected to the USB Serial chip. But the labels TX and RX are referring to the Arduinos chip (Atmega328p at the Arduino Uno). Since serial connections need to be connected alternating (RX to TX and TX to RX), the pin labeled TX leads to the RX pin of the USB Serial chip and vice versa.
Thus you would connect TX of HC-05 to the TX pin on the Arduino and RX of HC-05 (through the voltage divider) to the RX pin on the Arduino. Also you should program the Arduino with an empty sketch before doing that, so that the Arduino does not interfere in the Serial communication with its own Serial usage.

Or you can use a SoftwareSerial interface and let the Arduino code translate between the devices. The Arduino received from the PC and sends the data to the HC-05. Also it receives from the HC-05 and sends that data to the PC. This is what you were trying. But you absolutely need to specify a different set of pins for the SoftwareSerial interface, than 0 and 1. These pins are doing the hardware Serial interface, which is connected to the PC. So change these pin numbers (for example to 2 and 3).
In fact: Whenever you see a code for Uno, Nano or Mega using SoftwareSerial on pins 0 and 1, you can be sure, that it is garbage.

I connect my Arduino to my PC, upload the code, connect my module, set the serial monitor's baud rate to 38400 and...a bunch of gibberish appear on screen

Even when you change the pins as described above, your code still uses 9600 baud for the connection to the PC. When you set the Serial Monitor to 38400 while the code uses 9600 baud for that interface, you will get just gibberish. Either change your Serial Monitor to 9600 baud or change your code to Serial.begin(38400). The last option is better, since that makes sure, that you are using the same baudrate for both interfaces.

some don't bother with the ENABLE pin entirely

The ENABLE pin seems to have a pulldown resistor on the HC-05 board, which pulls it to ground, when nothing is connected. Ground means data mode, HIGH command mode. So when they don't connect anything, they want to stay in data mode. Though this also depends on if the specific HC-05 board has a pulldown or pullup resistor there. Pulldown is more likely, but since there is no one single producer of these modules, you cannot be sure. Since you want to get into AT mode, you should use command mode and connect it to 3.3V. For normal operation it would go to ground. Though you can also connect it to a digital output pin of the Arduino and let the code decide in which mode the module should be.

some don't use a voltage divider

The chip on the HC-05 board is a 3.3V device. The actual breakout boards, that can be bought everywhere, mostly only add a voltage regulator from 5V to 3.3V, an LED for status display and break out the necessary pins. The data pins are mostly directly connected to the chip. There are many resources, that claim the HC-05 to be 5V tolerant, but also many that antagonize that. To be sure not to destroy the HC-05, you should also use a voltage divider.

some connect VCC pin to the 3,3V instead of the 5V

This is only done, when the used board does not have a 5V to 3.3V voltage regulator. Depends on the exact board, that you own.

some even skip the AT-Command setup entirely!

When they don't need to configure the HC-05 in a special way, why would they go into command mode. That might be different for you.


Among all the options mentioned, using a master/slave should be the last resort, especially when you are new to embedded programming or Arduino, it is not only more complicate but also more expensive to implement.
One potential solution that could free up the precious digital i/o pins that were used by the 5 buttons is using analog input to detect the status of the buttons.

simulate this circuit – Schematic created using CircuitLab
When sw1 is pressed, the voltage at the A0 will be around 0.83v, and when sw5 is pressed, the voltage at the A0 will be 2.5v. You can write a simple switch...case to determine which switch has been pressed.
The only problem of this circuit is that it can't handle more than one button been pressed simultaneously, but that could be solved by double the value of each resistor like 10k, 20k, 30k...
This will free-up 5 digital pins that can be used for control (such as servo, relay, etc.).


Read encoder output by using an optocoupler

People sometimes use optical couplers when anticipating large voltage differences or the potential for large voltage differences.  This may always be the case as in a light dimmer.  Or may preventative as in ground loop mitigation for MIDI connections.  If you anticipate these types of situations then an optical coupler may be a good design choice.
Alternatively if the signal is changing between 0 volts and 5 volts and the fan out of the signal is larger then the existing load and the new load combined and the new load is 5 volt tolerant then the signal might be able to drive both loads.
You might seek out the specifications of the 3 connected devices in question.  At the very least, discover the current the encoder output will support.  Then measure the resistance to ground of the input to the motor controller and the resistance to ground of the input to the video equipment.  Find the parallel resistance of these two resistance and calculate the current at 5 volts.  If the current is substantially less then the specified capacity of the encoder, the encoder might be able to drive the 2 loads.  This assumes many things such as no ground loops being present.  There are so many variable it is difficult to be predict the outcome.


Serial isn't a keyboard. When you send 'A' you send 'A'. Whatever that source is - if you send a single A you send a single A, and you receive a single A.

You will have to come up with some other protocol and write some special software on your computer that monitors the keys directly, and sends something along the lines of "I Pressed A" and "I Released A".


Can I make a USB Device with only data output

USB is a host-managed protocol. A USB device must be able to receive in order to operate, since the host notifies the device when it should send data back to the host.

The D+ and D- lines are not independent; the signaling state of the line is determined by examining both lines regardless of whether the host or the device is transmitting.

USB Made Simple


The mp3 audio coding is not just one mathematical calculation. To decode every mp3 file you need a complete package and enough memory. That is not something for a simple arduino board.

There are libraries to decode for example a jpg file or a mp3 file. They have restrictions and you need a faster processor.
Adafruit has made a start: https://learn.adafruit.com/native-mp3-decoding-on-arduino/, but you need a powerful non-standaard arduino-compatible board. That library does not use I2S yet.

I suggest to use a Raspberry Pi.


Is the arduino hackable when using communication shields?

You should be pretty safe, at least as long as your code handles the
incoming data properly.

When you upload a new sketch through USB, the USB-to-serial interface
uses the Arduino pins TX0, RX0 and RESET. Your Ethernet shield, on
the other hand, does not control the RESET pin. Pulling the RESET pin
LOW is needed to make the processor enter the bootloader, which in turn
is needed in order to upload a new program. For pulling this pin low,
the malicious code would need not only to break into the Ethernet
shield's firmware, it would also need a hardware hack to access the
pin.

Now, if your own code is not safe, it is conceivable that the malicious
payload tricks your program into jumping to the bootloader or, as
suggesting by Juraj, into triggering a watchdog reset (which ends up
being equivalent). Thus you should treat anything coming from the
network as potentially malicious.


We don't really answer "shopping questions".
You could contact several suppliers like Adafruit, sparkfun or maybe even Digikey, Farnell etc (ebay?).

If you search for: "15A dual h-bridge" you will find some motor drivers which should work for you.

If a driver can control a dc motor in 2 directions can it control 2 dc motors in one direction each?

Where are you going to use them for?
If you're only going in one direction, you won't need a motor driver.

An MOSFET (per motor) is good enough if you only drive one direction.
If you want both motors to be able to turn each direction, a dual h-bridge will do.


Is it possible to execute a code in runtime when gets updated over the air (OTA)?

On many Arduinos the processor is only a few dollar part.  You are asking for a feature that only starts appearing on platforms where the processor is over an order of magnitude higher in price.  Further, such inexpensive processors normally run a single program.  Running a sketch while managing a download & update would best be done by two programs existing in an operating system.  Again, likely requiring a processor an order of magnitude higher in price.

Instead, consider implementing your design using two different Arduinos.  Swapping one out for the other after updating.   Hot swapping may not be trivial.  This really depends on how your application interfaces with the world. But likely will be much easier than solving the problem of designing the supporting software to make sketch updates transparent to the Arduino user.


Motor cutting out when using HC-05 Bluetooth module

Previously I was powering everything off of the 5V line on the Arduino, but I just switched to using an external battery pack of 4 AAs and that seems to work fine.

That suggests, that your power source was not strong enough. You didn't say, how you are powering the Arduino, but I guess you are doing so via USB. The USB port of a PC can only give you 500mA of current (at least without any extra configuration to get more). Also the parts on the Arduino (for example the diode between USB power and the 5V pin) can only give you a limited amount of current. Especially when the motor is starting, the needed current is rather big. That might have caused a short voltage dip, deep enough to irritate the HC-05 module.

Using an extra battery as power source for the motor eliminates that problem. Though I think you should be able to connect all parts to the same power source, as long as it is powerfull enough to power all parts (plus some overhead). In that case be sure to connect the power for the L293D and Arduino in parallel, so that the motor current does not have to flow through the Arduino (which could kill the voltage regulator or the diode).

Depending on your motor, it also might generate a huge amount of EMI (Electromagnetic Interference) either though air transmission or through the power lines, which might irritate the HC-05 enough. In that case the easiest option would be to add a second power source. Though I think the problem is with the power source as described above.


Counter on my coin acceptor goes up without a coin input, any advice?

I'm also complicated by that. The advice I saw here was to connect a COIN wire also against an electric "R" 10K and connect  to the second hole on the left in the Arduino "IOREF" now it works.


WiFi you either need a WiFi router or for either the iPhone or Arduino to create a network.

RF transceiver you need external circuitry.

The common way to do this at the moment is using Bluetooth Low Energy. Using a Bluetooth Low Energy (BLE) shield you can directly connect the Arduino to a modern iPhone or Android phone (supporting Bluetooth 4.0).

Check out redbearlabs, who have a range of shields and BLE-enabled Arduino clones. There are example sketches and iOS apps on the net. I have made a BLE controlled RGB light using the redbearlabs BlendMicro and example OSX application.


Sounds like the COM port is not setup. Opening the Arduino IDE probably does this automatically.

Try running the following command, only once, after turning on your pc to initialize the COM port.

mode COM3 BAUD=9600 PARITY=n DATA=8

Ps. I'm not a windows user, so this is an educated guess - reference.

Pps. I think you're winning the award for the most complicated way to ring a bell. :)


Fading from color to color using for-loop FastLEDs

If you want to fade all the LEDs form blue to red at the same time, I think you want code like this (explanatory comments embedded)...

#include <FastLED.h>
#define DATA_PIN 6
#define NUM_LEDS 7

#define COLOR_ORDER GRB

CRGB leds[NUM_LEDS];

void setup(){
  FastLED.addLeds<WS2811, DATA_PIN, GRB>(leds, NUM_LEDS);

}
void loop(){

  // Let's take 256 steps to get from blue to red
  // (the most possible with an LED with 8 bit RGB values)

  for( int colorStep=0; colorStep<256; colorStep++ ) {

      int r = colorStep;  // Redness starts at zero and goes up to full
      int b = 255-colorStep;  // Blue starts at full and goes down to zero
      int g = 0;              // No green needed to go from blue to red

      // Now loop though each of the LEDs and set each one to the current color

      for(int x = 0; x < NUM_LEDS; x++){
          leds[x] = CRGB(r,g,b);
      }

      // Display the colors we just set on the actual LEDs
      FastLED.show();

      delay(10);
  }

}


How to connect Flora 2 and nRF8001 BLE Breakout

The SPI bus can be accessed using a 6 pin header located next to the embedded processor.  Look at the embedded image below. Locate the 6 pin header just to the right of the processor.  Note the white dot indicating pin1 of the header.  Now look at the bottom of the embedded image to see the definitions of the 6 pins.  MISO, MOSI and several other SPI signals are listed.


table filled

 * Typical pin layout used:
 * ------------------------------------------------------
 *             MFRC522      Arduino       NodeMCU
 *             Reader/PCD   Uno/101       ESP8266MOD
 * Signal      Pin          Pin           Pin
 * ------------------------------------------------------
 * RST/Reset   RST          9             any, recommended 5
 * SPI SS      SDA(SS)      10            any, recommended 4, possible 15
 * SPI MOSI    MOSI         11 / ICSP-4   13
 * SPI MISO    MISO         12 / ICSP-1   12
 * SPI SCK     SCK          13 / ICSP-3   14

io 15 is SS if esp8266 is slave. but this pin must be LOW at boot. you can use it as SS if SS pin of reader doesn't pull-up.

io 4 and io 5 are untroubled pins.

io 0 and io 2 are with io 15 boot configuration pins and can be used only if they don't change the required boot state.

io 1 and io 3 are Serial interface

io 16 is RTC pin and is used for wake up from deep slepp

warning: does the reader work with 3.3 V?


Arduino Serial data communication with NodeJS

As Look Alterno wrote in a comment, you need to parse the incoming data on the receiving side. In this instance, you have to look for the line terminators. The Node.js serialport module provides a parser for this called Readline. Read that doc and use it.


How to read response from server using an Ethernet shield?

There are, obviously, a great number of ways that this can be achieved. The simple brute force way would be to have a series of if statements, looking for a sequence of eight consecutive 0s and/or 1s, and loop through the string containing the response.

Or you could loop through the response, using strcmp(), similar to what is described here: how to do like a grep in a sketch?

However, a more intelligent method would be to use pattern matching and regular expressions.

From New regular expression library released, Nick has provided a Regexp library. It uses Lua for the expression syntax, see string.find, for more details.

I am still playing with this code, but your sketch would need something like this:

#include <Regexp.h>
void setup ()
{
  Serial.begin (115200);
  Serial.println ();

  unsigned int index = 0;
  char buf [100];

  MatchState ms;
  ms.Target ("HTTP/1.1 200 OK\
Date: Sun, 02 Jul 2017 07:53:29 GMT\
Server: Apache/2.2.14 (Win32) DAV/2 mod_ssl/2.2.14 OpenSSL/0.9.8l mod_autoindex_color PHP/5.3.1 mod_apreq2-20090110/2.7.1 mod_perl/2.0.4 Perl/v5.10.1\
X-Powered-By: PHP/5.3.1\
Content-Length: 13\
Content-Type: text/html\
\
\
<10110110>");  // what to search

  while (true){
    char result = ms.Match ("^<([01][01][01][01][01][01][01][01])", 0);  // look for an eight bit binary digit
    if (result == REGEXP_MATCHED)
    {
      Serial.println ("-----");
      Serial.print ("Matched on: ");
      Serial.println (ms.GetMatch (buf));
      Serial.println ("Captures:");
      for (int j = 0; j < ms.level; j++)
         Serial.println (ms.GetCapture (buf, j));
      // move past matching string
      index = ms.MatchStart + ms.MatchLength;
    }  // end of match
    else
      break;  // no match or regexp error

  } // end of while

}  // end of setup

void loop () {}

This code assumes that you are looking for a line beginning with < and captures an eight digit binary thereafter - as determined by the expression within the inner (), in the line:

    char result = ms.Match ("^<([01][01][01][01][01][01][01][01])", 0);  // look for an eight bit binary digit

So, it should output:

-----
Matched on: <10110110
Captures: 10110110
-----

Obviously, instead of just outputting the captured binary digits to the serial monitor, you need to save them for your relay control.

For neatness, you could replace

 ms.Target ("HTTP/1.1 200 OK\
Date: Sun, 02 Jul 2017 07:53:29 GMT\
Server: Apache/2.2.14 (Win32) DAV/2 mod_ssl/2.2.14 OpenSSL/0.9.8l mod_autoindex_color PHP/5.3.1 mod_apreq2-20090110/2.7.1 mod_perl/2.0.4 Perl/v5.10.1\
X-Powered-By: PHP/5.3.1\
Content-Length: 13\
Content-Type: text/html\
\
\
<10110110>");  // what to search

with

  char * str = "HTTP/1.1 200 OK\
    Date: Sun, 02 Jul 2017 07:53:29 GMT\
    Server: Apache/2.2.14 (Win32) DAV/2 mod_ssl/2.2.14 OpenSSL/0.9.8l mod_autoindex_color PHP/5.3.1 mod_apreq2-20090110/2.7.1 mod_perl/2.0.4 Perl/v5.10.1\
    X-Powered-By: PHP/5.3.1\
    Content-Length: 13\
    Content-Type: text/html\
    \
    \
    <10110110>";

  ms.Target (str);

Note the use of the backslashes at the ends of the lines. I've included them here, in order to get the test sketch to compile. You probably will not need them as you would be receiving the response from the server, and not providing an example string for testing.

Here is a working version, along with multiple test strings (input_str) and example match strings (match_str):

#include <Regexp.h>
void setup ()
{
  Serial.begin (9600);
//  Serial.begin (115200);
  Serial.println ();

  unsigned int index = 0;
  char buf [100];

// Simple test pair
//  char * input_str = "RGB:123";
//  char * match_str = "(%a)";

// Simulated MySQL responses
// Most basic
//  char * input_str = "<10110110>";
// Over two lines
//  char * input_str = "http\\n<10110110>";
// Full response
  char * input_str = "HTTP/1.1 200 OK\
    Date: Sun, 02 Jul 2017 07:53:29 GMT\
    Server: Apache/2.2.14 (Win32) DAV/2 mod_ssl/2.2.14 OpenSSL/0.9.8l mod_autoindex_color PHP/5.3.1 mod_apreq2-20090110/2.7.1 mod_perl/2.0.4 Perl/v5.10.1\
    X-Powered-By: PHP/5.3.1\
    Content-Length: 13\
    Content-Type: text/html\
    \
    \
    <10110110>";
// Full response with newlines
//  char * input_str = "HTTP/1.1 200 OK\\n\
    Date: Sun, 02 Jul 2017 07:53:29 GMT\\n\
    Server: Apache/2.2.14 (Win32) DAV/2 mod_ssl/2.2.14 OpenSSL/0.9.8l mod_autoindex_color PHP/5.3.1 mod_apreq2-20090110/2.7.1 mod_perl/2.0.4 Perl/v5.10.1\\n\
    X-Powered-By: PHP/5.3.1\\n\
    Content-Length: 13\\n\
    Content-Type: text/html\\n\
    \\n\
    \\n\
    <10110110>";
// Shorter version of full MySQL response with newlines
//  char * input_str = "Content-Type: text/html\\n\
    \\n\
    \\n\
    <10110110>";
// Shorter version of full MySQL response with newlines with no preceeding spaces
//  char * input_str = "Content-Type: text/html\\n\
\\n\
\\n\
<10110110>";

// Match strings for MySQL response, containing an eight bit binary number
// Match at beginning of line
//  char * match_str = "^<([01][01][01][01][01][01][01][01])";
// Match at beginning of line with multiple newline characters
  char * match_str = "[\n]*<([01][01][01][01][01][01][01][01])";
// Match at beginning of line with zero or one newline characters
//  char * match_str = "[\n]?<([01][01][01][01][01][01][01][01])";
// Match at anywhere
//  char * match_str = "<([01][01][01][01][01][01][01][01])";

  MatchState ms;

  while (true){
    char result = ms.Match (match_str, 0);

    if (result == REGEXP_MATCHED)
    {
      Serial.println ("-----");
      Serial.print ("Matched on: ");
      Serial.println (ms.GetMatch (buf));
      Serial.println ("Captures:");
      for (int j = 0; j < ms.level; j++)
         Serial.println (ms.GetCapture (buf, j));
      // move past matching string
      index = ms.MatchStart + ms.MatchLength;
    }  // end of match
    else
      break;  // no match or regexp error

  } // end of while

}  // end of setup

void loop () {}

For the match_str line,

char * match_str = "[\n]*<([01][01][01][01][01][01][01][01])";

you may or may not need the caret (^) to match at the start of the line, and the [\n]* or [\n]?. See which combination works for you.


I guess you have commented the command:
 //client.stop();

If you allow it, I guess you will have your code running


I tried to use MIDI (which is quite slow: 31,250 bps), and that didn't work reliable with the software serial on the Arduino Uno. Since I wanted multiple ports, I switched to the Arduino Mega which has FOUR harware serial ports. I would suggest this above using so many software serial ports; it also will relieve your processor to use hardware serials.


Sparkfun also sells FSR's and they explain it better: "Use them to sense if it’s being squeezed, but you may not want to use it as a scale".

On that Sparkfun page is also a datasheet. It's inaccuracy is 25%, and that is only when the force is applied evenly. When someone presses it with a finger, the inaccuracy is 50% or more.

The quick-and-dirty calculation in the Adafruit example is just for fun, it is not serious measuring the force in Newton.
There are two different calculations, for 'fsrConductance' above and below 1000. When it is above 1000, the 1000 offset is substracted to start the calculation at zero. The difference in calculation is that for one the value is divided by 80 and in the other divided by 30. It's just a rough calculation to get some kind of force value.

To measure weight or force, you need a load cell.


UPDATE: Fault in processing code - doesn't receive correct data from Arduino

You're sending your lightval twice - once as a textual representation of the number, and once as a character representing the lower 8 bits:

Serial.println(lightval);
Serial.write(lightval);

For example:

Q308
R304
Q306

If you take the 308 and AND it with 255 you get 52.  52 as an ASCII character is R.

So you print 308, including a newline, then you print "R".  Then you print 304, which would be 48 after ANDing with 255 - which of course is a Q.


Sleep mode and months of operation on small battery

Have a read through the Jeelabs blog which documents the author's very successful attempt at making a very low power wireless sensor node that can run for months off coin cells.

http://jeelabs.org

There is also a library based on this project called Jeelib:

http://jeelabs.net/pub/docs/jeelib/

Jeelib contains a class called Sleepy that allows for easy sleeping.

Rocketscream did a thorough test of the current consumptions with the different modes here:

http://www.rocketscream.com/blog/2011/07/04/lightweight-low-power-arduino-library/

According to them, you can get the ATMega328P down to 1.7uA.

Unless you do something about the power supply on a normal Arduino board you won't be able to extend the battery life by much at all. See my answer here for some more details:

Arduino powering from 9V battery


Mega 2560 & smoking/burning 5v requlator, probable cause?

They are using the same SOT223 LDO as every other product.  These have a very low limit of output current when run from an input voltage such as 12V.  If you replace the LDO with a switching regulator, you can eliminate the waste heat regardless of the output current (Except for the 5V to 3.3V secondary LDO which is a constant).  The PDF linked below shows a comparison between the LDO and drop in switcher.  Not that the switcher performance at 1900mA is equivalent to the LDO at 250mA... at 250mA the switcher temperature rise would only be 8.5C.

https://www.sugarsync.com/pf/D3258881_07979653_7526812


I finally figured it out, the Arduino was entering a current protection mode causing it to reset. The pins driving the MOSFETs were pulling too much current once the regulation started because of the BUZ11's input capacitance.

To fix the problem I just had to add 120 ohm resistors in series with the gate. This made the activation and deactation slower resulting in less current flow.


Don't let that pin float undefined: If undefined (INPUT), pull it to GND to have the led OFF.

If ever possible, try to use the LED_BUILTIN pin as an OUTPUT pin.

And signal some information there. On an UNO (or other 328-based Arduino), this hint might collide with the SPI_SCK pin, which is D13 (PB5 on an atmega328). But as an SPI Master, this pin is at least OUTPUT (and thus will signal SPI activity).


Arduino reading serial data non-blocking

Unfortunately your code could end up dropping data quite easily, or parsing it incorrectly.

Let's say your code has successfully read the first couple of bytes into NumberOfIncomingBytes. However, when it reaches begin two, let's imagine the sender hasn't finished sending all the data yet.

Your code will drop through to end two, discarding the NumberOfIncomingBytes value it just read. Next time round, it will start all over again from scratch, and attempt to read NumberOfIncomingBytes again. However, that data isn't there anymore. The next data waiting on serial will actually be the timestamp from the previous message.

From there, it could end up parsing arbitrary data with unpredictable results, getting completely out-of-sync with the sender.

A way to fix it would be to store the NumberOfIncomingBytes value outside the function (e.g. as a global variable), along with a flag indicating if you're still waiting for the rest of the data to arrive. At the start of CheckSerialData(), the code should check that flag. If it's true, then it should skip trying to read NumberOfIncomingBytes. Instead, go straight on to begin two.

An alternative approach would be to avoid using NumberOfIncomingBytes at all. Each call to CheckSerialData() would read whatever serial data is available, and accumulate it in a buffer. As soon as it hits a newline character, it will stop reading, and parse the data it's accumulated. If it runs out of serial data before it hits a newline, it should stop and carry on from there next time it's called.


The IDE says my (brand new) Arduino UNO is on COM 1

Here are a few troubleshooting tips:

First check if the board is listed as Arduino Uno in the IDE by going to Tools --> Board
Check this site.
Also, try reinstalling the driver.
Check your cable.
As a last resort you can try re uploading the bootloader.


Pass changing analog value from void loop to library .h file

How would I go about passing a void loop analog read value to a library .h file?

What you wanted to do makes little sense. But it is certainly doable. The simplest would be to use an "extern" variable as a bridge.


Setting pinMode(pin,input/output) as per user requirement

Now my question is , calling this function 4 times and writing pinMode() function 4 times will result in same thing or separate? Also is this doable, like can i write like this?

you can call pinMode anytime

And to add something more to pinMode. It is not just some preparation of the pin. It changes things for the connected circuit. Setting to INPUT lets the attached circuit rule. If there is a pull-up circuit the state will be HIGH, if pull-down LOW. INPUT_PULLUP holds the state HIGH but lets the attached circuit to pull it down. pinMode OUTPUT sets the pin LOW.

In two cases for now I use setting a pin to OUTPUT only for the time I want to control the attached circuit and the I set it back to INPUT. In first case I reset an esp8266 with EN pin connected by setting the pin LOW, then I let the external pull-up hold the EN pin HIGH. Second case is amplifier module for the tone() function. I set the pin to INPUT after tone() otherwise it catches noise.


Read from analog then cast not showing the correct value

Max value for int is 32,767. But 100 * 1002 = 100,200. You are overflowing the int. Use unsigned long. Or float and cast to int when printing.


Connecting a LSM9DS0 9DoF module to Arduino Uno

I might be missing the part of the hookup guide you're looking at but I can't see it being hooked up to 5V.

In the "Simple Hardware Hookup (I2C)" section they show two possiblilities a 5V Arduino hooked up via a logic level converter and a 3.3V Arduino hooked up directly. The logic level converter will need a 5V & 3.3V connection from the Arduino, but not the IMU.


Reading SMS using Arduino Uno and SIM800L and print on LCD (16x2 alphanumeric) using serial connection NEED HELP

The PP3 battery you are trying to use is far from powerful enough to run a SIM800L. It's barely powerful enough to run an Arduino by itself for more than a couple of hours if you're lucky.

The SIM800L, as the datasheet tells us, must be powered by a supply which can provide at least 2A.

  The power supply range of SIM800L is from 3.4V to 4.4V. Recommended voltage is 4.0V. The transmitting burst will cause voltage drop and the power supply myst be able to provide sufficient current up to 2A.

The Arduino's on-board 5V regulator can't provide more than 800mA if you're lucky (far less if the incoming voltage is more than around 7V due to heat dissipation). Running from USB may allow peaks of up to 2A on a DCP USB socket without the Arduino's PTC fuse blowing.

A typical PP3 battery has an impedance of 1.7 ohms. That means a dead short circuit across the terminals would theoretically allow 9/1.7 = 5.2A maximum ever to flow. That kind of current would dissipate about 46W in heat inside the battery causing it to explode. Also at that current, given the typical low capacity of about 154mAh, the battery would be flat within about 100 seconds.

The maximum rated current for one of these batteries (at least, the maximum current shown on any of the graphs in the datasheet) is 250mA.

You need to power your SIM800L in a completely different manner, including two important things:

You need a power source that can provide 2A at the rated input voltage of your module (5V?)
That source needs to either be separate from the Arduino (except the ground, which must connect to the Arduino as well as the module) or if it is 5V may be used to directly power the Arduino through the 5V pin.


How to pass variables to custom callback functions

The function you are trying to call is a template function:

template<typename TArg>
void attach_ms(uint32_t milliseconds, void (*callback)(TArg), TArg arg)
{
    ....
}

So, you need to tell it what type of parameter you are passing:

change_pin.attach_ms<uint8_t>(100, [](uint8_t state_to_change_to) {
//                     ^- tell the compiler about the parameter
    ....
}, desired_state);

To pass more than one parameter: Since the library only allows one parameter, I would create a struct and pass a pointer to it.

struct callback_parameter {
    int i;
    char *p;
};

Then create one of these structs and pass the address of it. You just have to make sure the struct is valid the entire time the timer is running. So either use new, static, or make it global.

callback_parameter param; // global variable

...

change_pin.attach_ms<callback_parameter *>(100, [](callback_parameter * state_to_change_to) {
    ....
}, &param);


The problem you are seeing here is that the Arduino can provide nowhere near as much current through I/O pins as it can power. Quoting from the Arduino website:

  DC Current per I/O Pin: 40 mA

This means that each pin can power maybe a couple of LEDs, and that's it. Additionally, motors provide "back-EMF": When opening (cutting power) an inductive load (e.g. a motor), the current wants to keep going. This will damage whatever just opened unless protection is used. So, I wouldn't be surprised if you damaged your Arduino by attempting to drive a motor with it.

So, what can you do? Use an H-Bridge. This circuit will allow you to easily control a motor & its direction. Many circuits can be found online, but an easy solution is a cheap L298N module, which can be as cheap as $3 a piece. This will safely & easily control the arm. Connecting your Arduino with the following circuit & using your existing sketch will make it work.

simulate this circuit – Schematic created using CircuitLab


What should the frequency reading of the SPI clock be with this code?

Yes, the clock speed should be (and most probably is) 8 MHz.  However, you're not generating an 8 MHz clock.

What you are in fact generating is 8 clock pulses of 8 MHz, then you have a delay while it deals with the rest of your code, and then it generates another 8 clock cycles of 8MHz.

The overall frequency is evidently sensed as 3.439 MHz.

To generate a pure 8 MHz clock you would have to use a different transfer method. I don't know if the 328P has DMA available, but if it does, that would give you much faster transfers.  Also, you could write a more non-blocking version of SPI.transfer().

The normal SPI.transfer() first starts the transfer, then waits for the transfer to finish, and returns the results of the transfer.  If you're only interested in transmitting, and not receiving, or the transmitted and received data don't need to c correlate completely, you can instead change the order of how it works:

Wait for there to be no transfer in operation
Store the result of the last transfer
Start the new transfer
Return the results of the last transfer.

That way it runs much smoother as it's doing the current transfer at the same time as running your other code.


Problems Sending Signals to the Arduino-Uno via Keyboard

Keyboards cannot be used quite like you wish - the keyboard will send a key (scan) code when a key is pressed and then repeat that code if the button continues to be pressed. There is a different code sent when the same key is released.

The scancode for key release is obtained from it by setting the high
order bit (adding 0x80 = 128). Thus, Esc press produces scancode 01,
Esc release scancode 81 (hex).  For sequences things are similar:
Keypad-/ gives e0 35 when pressed, e0 b5 when released. Most keyboards
will repeat the make code (key down code) when the key repeats.

From: https://www.win.tue.nl/~aeb/linux/kbd/scancodes-1.html


Probably because x is an array of integers (although in the code you posted you miss the '[]'), thus memcpy_p should run over rawlen integers, each integer occupies sizeof(uint16_t) bytes, hence rawlen * sizeof(uint16_t) bytes in program memory space.


You can use the serial monitor in this way, as long as you ensure you do not send anything from the serial monitor out to the Arduino or peripheral, only to monitor data.

That said, if you try to send debug prints from the Arduino to the serial monitor, they will also be sent to the peripheral device, where there may be conflict, depending on the peripheral.

So you technically can, but it's not advised because there are several ways it can go wrong.

One alternative is to use the SoftwareSerial library to create a second, bit-banged serial port. Note, however, that this library can't operate at high speed (probably best to keep at 9600 bps) reliably.


What's the smallest Arduino board with wifi capabilities?

From your question it implies that the Spark IO use the Arduino IDE - it's not. It has two different IDE's, one is web based and the other is downloadable. In addition, it's not an Arduino per-se. It is based on the Wiring library, which is similar to the Arduino library but not exactly the same. And of course the MCU is not Atmel, but that is also the case with Intel's Galileo board.

As to the size question in hand - my believe is that the Arduino products are designed for prototyping, so the size of the product is less important. This is the case for several reasons:

Costs -  the different Arduino products are pretty expensive for mass production.
Peripherals - the Arduino boards come with different peripherals (such as the FTDI chip) which will probably be omitted in an end-user product, and which makes its size larger.
Pins - almost every (official?) Arduino product comes with pre-built male/female header pins, which are excellent for prototyping but not for production, because of the large vertical space they take.

There are many more reasons, but you get the point.

When moving to production with an Internet of Things product, it makes sense to fabricate your own PCB, and design it with a small Atmel chip you used for prototyping (such as ATtiny85) and small Wifi chip, such as the ESP8266. This is an example for such fabricated PCB, although the size is not the 'smallest' possible.

However, for beginners, or a one-time project, it would absolutely make sense to use a pre-fabricated Arduino product, in a small scale that could provide both easy coding capabilities, various libraries and a WiFi included. For that purpose, the Spark IO seems to be at the bleeding edge at the moment - but you never know what will be there tomorrow...


Is it possible to do an OTA update using a GitHub link

It may be possible if you can write your own bootloader, but it certainly won't be easy.

The normal way of doing OTA updates is to use a chip that has segmentable and remappable flash memory (such as the ESP32, ESP8266, PIC32MZ, etc) where your sketch is running from one segment, and that loads the new code from whatever source into the other segment. It then changes a single boot flag and resets the MCU, and the MCU then maps the second segment into the place of the first (swaps the two segments over) and runs the new code.

That can't be done with the SAMD21 since it has no remappable flash memory segments.

So the best you could hope for would be to reboot into a custom bootloader which then connects to the internet to download new code to flash into the main portion of the flash memory. And of course that would replace the existing bootloader and take a lot of work to create.

Addendum:

Apparently there is the "WiFi101OTA" library which allows over-the-air updates on SAMD21 boards. By all accounts this receives the new code and stores it away somewhere (a chunk of the internal flash, SD card, etc) and then copies that data to the main portion of the flash using a function running from RAM.

While this sounds good, I would not recommend using it in a live situation. For development it's fine, but not "in the field".

This is simply because there is no protection against "bricking" a unit.  Once the copy from storage to main flash starts you are at the point of never being able to go back. If that write should fail for whatever reason (there is a power outage, or the sketch crashes, or any of a myriad of other unpredictable reasons) the unit is dead.  You would have to manually reprogram the unit with a cable to bring it back to life.

By having the programming done by the bootloader (incidentally, some devices, such as AVR based boards, can only write to flash from the bootloader) the code that does the writing never gets overwritten, so a simple manual reset of the unit can restart the programming and recover the board.

If you were to adopt this library you would of course have to modify it to "pull" the update, not receive a "pushed" update. This should be trivial, but some level of network programming ability would be needed.


UNO Timer 1 CTC mode not resetting TCNT1

It sounds as though timer 1 has not in fact been set to wavegen mode 4. You can ensure that it is by also clearing the other bits of WGM1:

TCCR1A &= ~(_BV(WGM10) | _BV(WGM11));
TCCR1B &= ~_BV(WGM13);


Need Help with Switch Case commands/receiver and lcd screen project?

Too many pieces of the puzzle are missing for us to venture a guess on what is going wrong:

The output you get (both in the LCD and the serial console)
The message sent

One thing that strikes me as a potential problem is the

switch(message[1])

line. If you want to check the first character received, it should be

switch(message[0])

That said, it would perhaps help you if you tried to split the program into pieces and make sure each one works before advancing to the next. Are you sure the LCD pin connections and initialisation line match? (I know from experience it is very easy to mess up and put the pin numbers in the wrong order). It would help to put the following code right after the lcd.begin line (in your setup() function):

  lcd.setCursor(0, 0);
  lcd.print("Initialised!");

Now if this line doesn't display correctly, you will know it is the lcd connection/initialisation code that is at fault. Otherwise, you will concentrate on your communication code.

Give us more information and we 'll be able to help more.


Improvement security in a domotic project

First of all, a quick rule that you should follow... It is called Kerckhoffs's principle. Wikipedia states it as this:

  A cryptosystem should be secure even if everything about the system, except the key, is public knowledge.

So, you're never going to reach "full security."

If the attacker can physically access your Arduino, all bets are off. They can upload new code, replace the Arduino, or just simply rewire your circuit so the door opens.

Also, they may be able to remove the RFID module and replace it with another Arduino board that sends random data in the right format hundreds or thousands of times a second. If they find the key code, they can make a new RFID tag with that ID. Thus, it is essential to keep that ID private.

So here's what you should do (in this scenario, password = RFID key's ID):

Make sure they can touch or access as little as possible. If you can, embed the RFID receiver inside a wall so they don't know where the receiver is and would have to break the wall to access it. If they break the wall, they could break the door, so this isn't necessarily a major security flaw. Of course, remember the sensitivity of your receiver.
Obfuscate your code: If you do something where you combine only certain bits/bytes of a few different strings to get a passcode to be compared to the sensor value. Of course, the compiler will remove most of this in an attempt to optimize your code. Note that this isn't actual security, just making the intruder having to do more work. A lot of people discourage this since it gives you a false sense of security, but I encourage it because it will take a little bit longer to hack into your application if they get your code. Remember that at any time they can use Serial.println(finalPasswordHere);.
If you're really worried, hash it. AVR chips probably don't have enough power to do advanced hashes like SHA-512. There seems to be a few MD5 hash algorithms for Arduino. MD5 isn't really secure with only a few digits, but if you have a 30 character hash that would take a long time to brute-force it. Add a salt with a ton of random characters (ex: lsjJK399!$%^&flk2) that aren't normally found in lookup tables. You'd combine the salt and the ID for the tag into one hash and put that in the code. Then, you'd hard code that hash into the main code. When you want to check if the ID being scanned is correct, you'd hash it with the salt and then compare that to the known hash. If you have more than one ID in the system, it's a good idea to have a different salt for each.


Reprogram Atmega 16u2 on Arduino Mega with Arduino IDE?

Yes, you can recover the firmware in 16u2 only with Arduino IDE installed. In subfolder hardware/arduino/avr/firmwares/atmegaxxu2/ of the IDE installation folder is the hex file of the firmware Arduino-COMBINED-dfu-usbserial-atmega16u2-Mega2560-Rev3.hex. The README.txt file in that folder has sample command line to upload the firmware with avrdude.


Creating WebServer ip:port on esp8266 module

As @Juraj mentioned, martyncurrey.com/arduino-esp8266-web-server , I need to start server with command: AT+CIPSERVER=1,5000, IP is IP of the esp8266 and reserve it on router or use the AT command to set static IP.


An RS232 port wired via a level converter (as you mentioned max232) and a 1uF capacitor between RTS and "Arduino reset pin" Getting started with Arduino.

The capacitor is to trigger a reset on the Arduino so the bootloader kicks in and awaits a "Arduino sketch" via the serial port.

Your setup is AKA "Arduino Bare bone".


Since the ATTiny can easily run at 5V I don't see any problem with programming it at 5V levels and then run it at 3.3V. Is that correct?

Yes. But if there are any components on the board that can't run at 5V then you must provide some way of protecting them from the excessive voltage.

  If I change the fuses on Tiny to run it at 3.3V can I still use the 5V Arduino to program the tiny?

There are no fuses required to change the actual operating voltage of the device. There is the BOD threshold, but you can still operate the device at a higher voltage without issue regardless.


Why is there a need of use delay() after using Serial.flush() in the program

The Serial.flush() is doing nothing. It delays until all bytes have been sent out of the UART. Since nothing has been sent it's not got anything to wait for.
The delay after the available call is very bad practice. It's a really really bad way of dealing with serial reading.
You should read this for a better understanding of serial communication.


Is an Arduino Uno made in the USA compatible with SunFounder shields?

Use the latest official Arduino IDE : Arduino IDE

Every Arduino Uno and all the clones are compatible. Some clones have the CH340G usb-serial chip and require an extra driver. If you look very hard, you might find an Arduino Uno board that is not version 'R3' and does not have SDA and SCL near the USB connector, or does not have the polyfuse for USB 5V, or uses an ATmega328 instead of a ATmega328P. There is a chance of maybe 1 in 10,000 that you find a wrong Uno board, and in most cases those are still compatible.

Do you mean the SunFounder RGB Matrix Driver Shield? That should be no problem.


Switching methods/functions with a button

In your loop() function, the statement buttonPressed == false; doesn't do anything; it is simply an expression that evaluates to 0 or false (because buttonPressed is equal to true). Your while() loop will never end which is why you can't stop the counter by pressing the button again.

You probably meant buttonPressed = false;, which is an assignment statement setting the value of buttonPressed.  But doing that within the while loop makes the loop contents iterate once which it would do anyway, so there is no need for the surrounding while statement. The for() statement will still be executed once, without the while (the loop contents will be iterated 10 times in that one execution).

So you can reduce your loop() function to:

void loop() {

// Check button status.
   int buttonStatus = digitalRead(buttonPin);

   if (buttonStatus == HIGH)
   {
      // Calls displayCounter method 10 times.
      for (int i=0; i<10; i++){
         displayCounter();
         delay(30);
      }
   }
   else
      displayZero();
}

which will check the button state on each call to loop() and either run the counter or zero it, once, depending on the state.

You'll need another refinement, that of debouncing the button. Push buttons (and some other kinds of switches don't have a clean 0 -> 1 (or vice versa) transition but take some amount of time during which their state appears to bounce between 0 and 1 before finally settling to the new state. Read Nick Gammon's excellent article about contact bounce to see why and what to do about it.


Calculate power requirement for 64 rgb led ws2812b

If all LEDs are in full bright white, assume 60mA per LED. 64 would mean a maximum current draw of 64*60mA=3840mA. This figured would not include the Arduino itself.

a 500mAh battery could power this for no more than 7.8 minutes (500mAh / 3840mA = 0.17 hours = 7.8 minutes)

If your usage will not be full bright 100% if the time, then you could run longer.

You didn’t say how long you want it to run. Perhaps start with the design goal before specifying parts.

For a more realistic view of how much power it takes, measure with a multimeter the current draw from the battery or bench power supply to your boost converter while displaying a typical usage on the matrix. Use calculations as above to determine the expected battery lifespan.


Is it possible to use more than 1 device that needs to use SDA for I2C with a mini?

Yes, provided they have unique I2C addresses.

  Would you use a different analogue pin with a 10k pull up resistor and tie all of the devices to the SCL?

No. All of the devices must be tied to both SDA and SCL. You may need a smaller resistor depending on how many devices there are; see NXP document UM10204 for details.


The Dimmer library doesn't support Atmega128/164/16/32. It has

#if defined(__AVR_ATmega1280__) || defined(__AVR_ATmega2560__)
#define DIMMER_TIMER 4
#elif defined(__AVR_ATmega32U4__)
#define DIMMER_TIMER 3
#else
#define DIMMER_TIMER 2
#endif

For the Atmega128/164/16/32 it will use timer 2. The main errors are:

'OCR2A' was not declared in this scope
'TCCR2A' was not declared in this scope
'TCCR2B' was not declared in this scope
'TIMSK2' was not declared in this scope

Possible solution:

You could try to use timer 3. Only you need to change the timer number in Dimmer.h and in Dimmer.cpp on line 159 change TIMSKx(DIMMER_TIMER) = 0x02 perhaps to bitSet(ETIMSK, 3);. Check the datasheet. I can't test it, I don't have the chip.


Use only one pin as serial output/input with arduino

AVR304, "Half Duplex Interrupt Driven Software UART on tinyAVR and megaAVR devices" describes how to implement a half-duplex software UART using 2 pins. Simply omit the half of the UART that you do not need in your own implementation.


Concatenation of non constant character array with a string

char clat[10+11+1] = "Latitude: ";
dtostrf(gps.location.lat(), 11, 6, clat+10);

Since you've named the buffer 'clat' I'm assuming it will always be used for latitude, so we've pre-initialized its size and contents, and we know where to begin the latitude value.

By the way, don't forget to size string buffers one more byte than the length of the maximum length string you intend to put in it.

Update 6/23/14:

From your other question and your comment to this answer, I'll revise my suggestion to this. The ..printf() functions are particularly easy to use, saves you (mis)counting buffer positions, and don't add much lot more code than the Serial() object already includes:

char outbuf[40+1];      // wider than nec, easier than counting
char clat[15+1]; clong[15+1]; // workspaces

sprintf(outbuf, "Latitude/Longitude: %s %s",
    dtostrf(gps.location.lat(), 10, 6, temp),
    dtostrf(gps.location.lng(), 10, 6, temp) );

This works because dtostrf() returns the address of the buffer you gave it; sprintf then takes that string (two of them in this case) when building your final output string.

The printf() functions are often deprecated for embedded systems. They're large (but see my comment about that above); and they're non-reentrant, so don't do that! In these low-end systems we don't often multi-thread anyway - just be aware of that if you do. And even if you have to remove them later and go back to printing piece by piece, they can save you a lot of headaches during development.

Here's another way that avoids both printf and the 32 bytes of work buffers:

char outbuf[40+1];

 strcpy(outbuf, "Latitude/Longitude: ");
 dtostrf(gps.location.lat(), 12, 6, outbuf+strlen(outbuf));
 dtostrf(gps.location.lng(), 12, 6, outbuf+strlen(outbuf));

We can't initialize outbuf unless it is 1) static, and 2) not going to be used more than once, since its initial conditions won't be the same the second time around. I've increased the field-widths of dostrf() to be sure the outputs of the won't be run-together for large values.


Arduino Pro Mini interrupts timer not working

In untested (pseudo-)code

unsigned long lastSerialInput = millis();

void loop()
{

    if(!myFile)
        myFile = SD.open(filename, FILE_WRITE);

    while(Serial.available())
    {
        incomingByte = Serial.read();
        myFile.println(incomingByte,HEX);

        lastSerialInput = millis();
    }

    // check for 25 seconds of inactivity
    if( myFile && (millis()-lastSerialInput > 25000 )
    {
        myFile.close();
        fileNo++;
        filename = "datalog";
        filename += fileNo;
        filename += ".txt";

        //save new fileNo to config.txt (though I'd personally find the file with the largest number in setup instead of relying on a config.txt file)
    }

}


First be sure your voltage on the analog input is less then 1V and greater then zero, that is the range for the input. If nothing connected no guarantee what you will get. Just guessing, no circuit or definition.


HUGE deviation in Sharp IR sensor values if other pins are defined in void setup()

Not sure why commenting out those two lines makes a difference.  I think we need to see a schematic to resolve this.

However...

You do not use "pinMode" to setup an analog input!

Look at the examples on the "analogRead" page.  Notice there is no setup needed for the analog pin.  Just call "analogRead" like you are doing and everything should be fine.


How to access GPS location without internet

If you want to send data to a server on the internet, you will need an internet connection, or at least a connection to a internet gateway.
Which type of connection you use, and how you set up that connection, depends on distance, speed, and coverage you need.
Probably the most universal for your application, in the sense that it will work wherever a phone would work, is to use a GSM/GPS module with an Arduino. You can google around for such modules; there are many. Note that you will need a SIM card for every module you use.
The GSM-bit of the module can then be used as a modem to communicate with your server over TCP/IP. There are many examples showing how to do that on the interwebs, so I won't go there.
If this doesn't help you enough, please add more detail to your question and I will edit the answer.


storing 600 unsigned int values in an array and find minimum and maximum values

The Atmega 2560 has 8K of static ram, more than enough for your 1200-byte array.
Reading-, and especially, writing EEPROM are very slow, and EEPROM has a rather limited lifetime-number-of-write-cycles, so it is not a good candidate for active use but rather for storing data that change infrequently and need to survive a power-down. These would typically per-system preferences, or data that needs to be stored to let the system resume at the next power-up, where it had left off when the power went down. This latter function requires that the system store enough power (capacitor or tiny battery) to keep it running long enough to sense the main power failing and still have run-time enough to write to EEPROM.


Is the Arduino Due compatible with a Dual VNH5019 Motor Driver Shield?

ok so I went ahead and bought the arduino due and officially tested it out and the Arduino Due is compatible with the Dual VNH5019 Motor Driver Shield!

hope this helps!


If the list is a static list you could conceivably pass a pointer to it in the constructor. Example:

class myClass {
  const int num_;
  const int * values_;

  public:

  // constructor
  myClass (const int num, const int * values) : num_ (num), values_ (values) { }

  // other stuff here

  // demo
  void printThem ();
};  // end of class myClass

void myClass::printThem ()
  {
  for (int i = 0; i < num_; i++)
    Serial.println (values_ [i]);
  } // end of myClass::printThem

const int NUMBER_OF_VALUES = 6;
const int myValues [NUMBER_OF_VALUES] = { 22, 33, 44, 55, 66, 77 };

// make an instance of the class with the wanted values
myClass foo (NUMBER_OF_VALUES, myValues);

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

  foo.printThem ();
  }  // end of setup

void loop ()
  {

  }  // end of loop

That is the simple method. The values in the list are passed to the constructor as a pointer, the class remembers the list and uses it when necessary.


Majenkos comment (above) solved the problem:

"You need to wait after opening the serial port for the board to finish resetting and the bootloader to run and exit before you can send any commands."

import serial
import time

ser = serial.Serial(port="/dev/cu.usbmodem144231", baudrate=9600, timeout = 0)
time.sleep(1)
ser.write("200+")
print ser.read()


I will not give you code, only clues on how to write the code yourself.

The way to tackle this is to (at first) remove the Arduino from the equation. Replace it, instead, with you.

Imagine you are doing the timing yourself. How would you go about doing it?

This is how I would set about the task:

When the first button gets pressed I would look at the clock and jot down the current time.
When the second button gets pressed I would again look at the clock, and subtract the first time from the current time to find out how much time has elapsed. I would jot that down.
When the third button is pressed I would do the same again - look at the clock, subtract the start time, and jot down the difference.
And I would keep going until I had run out of buttons.

So now you need to find the right code to read what buttons are doing, get the current time, and finally send the times somewhere useful.

For all those there are many many many examples on the web.


Vin pin vs USB vs Barrel connector: Wemos D1 R2

The D1 R2 uses the same power supply arrangement as the Arduino Uno (albeit with a better switching regulator for the 5V instead of the Arduino's basic linear regulator).

So it should be safe to use both the USB and the barrel jack at the same time.

The NodeMCU doesn't include a 5V regulator and doesn't have the power switching circuitry of the Uno / D1 R2, and thus is a completely different arrangement.


Printing elements of char array from PROGMEM

Among many others, check out pgmspace.h utilities at
AVR-libc


Arduino always store the last sketch you have uploaded. Even if you disconnect your board and then replug it then it follow the same commands that you gave earlier.


Don't you mean:

  PCICR  &= ~bit (digitalPinToPCICRbit(pin));


I think you should go with 3 lithium batteries in series and for proper balance charging of batteries, you can use an off the shell 3s lithium charging circuit like this here.So you will get 4.2*3 = 12.6V on full charge and on full discharge you will get 3.7*3=11.1v out of the battery.

So still I think your pump motor would work on 11v and ther are chances that your solanoid also work on 11v it will just draw more current then usual.


Error on Arduino Code (unknown type name 'LiquidCrystal')

Using "extern" when instantiating a class is unusual.  We can not tell what your intentions are because this is only part of your code.  However it would be my guess that this code:

// Declare external global lcd
extern LiquidCrystal lcd;

Should actually be written like this:

// Declare external global lcd
LiquidCrystal lcd((12, 11, 5, 4, 3, 2);

This is making a BIG assumption that you are using an LCD similar to the one used in the HelloWorld example and you have connected it using the same pins!  Comments from the HelloWorld example to help you out:

 * LCD RS pin to digital pin 12
 * LCD Enable pin to digital pin 11
 * LCD D4 pin to digital pin 5
 * LCD D5 pin to digital pin 4
 * LCD D6 pin to digital pin 3
 * LCD D7 pin to digital pin 2
 * LCD R/W pin to ground
 * LCD VSS pin to ground
 * LCD VCC pin to 5V
 * 10K resistor:
 * ends to +5V and ground
 * wiper to LCD VO pin (pin 3)

Background:

Arduino sketches are written mostly in C while the libraries take advantage of C++.  As such the libraries can use a C++ feature called "overloading".  This is where you can have several different functions with different parameters all with the same name. The advantage is that you can call upon slightly different functions (or in this case different classes) simply by altering what is passed.  The LiquidCrystal class has defined all these possibilities:

  LiquidCrystal(uint8_t rs, uint8_t enable,
        uint8_t d0, uint8_t d1, uint8_t d2, uint8_t d3,
        uint8_t d4, uint8_t d5, uint8_t d6, uint8_t d7);
  LiquidCrystal(uint8_t rs, uint8_t rw, uint8_t enable,
        uint8_t d0, uint8_t d1, uint8_t d2, uint8_t d3,
        uint8_t d4, uint8_t d5, uint8_t d6, uint8_t d7);
  LiquidCrystal(uint8_t rs, uint8_t rw, uint8_t enable,
        uint8_t d0, uint8_t d1, uint8_t d2, uint8_t d3);
  LiquidCrystal(uint8_t rs, uint8_t enable,
        uint8_t d0, uint8_t d1, uint8_t d2, uint8_t d3);

But in none are there no parameters.  That is why the compiler could not find the class in your code.  You needed to match one of the above class types.


Where am I supposed to get an I2C BUFFER_LENGTH defined?

BUFFER_LENGTH is set in I2Cdev.h depending on the target. BLE nano is not directly supported (what I can see).

Cheers!


The logic of your second attempt is perfectly correct.

If you put resistors in series with the LEDs you may get more joy out of it. Having two LEDs in parallel without resistors often results in one LED lighting and the other not.


Global variable changes its value when loop starts again

This:
sprintf(stringBuffer, "Calibration accomplished with value: %d", calibrationValue);

is a buffer overflow: the function sprintf() is writing a 40-byte
string into a 30-byte buffer. Whatever happens to lie in memory right
after the buffer will be overwritten by sprintf(). Apparently this
happened to be calibrationValue. You should use
snprintf() rather that sprintf(), as the former is designed to
prevent this kind of overflows.
Or better yet, stick with Serial.print[ln]():
Serial.print("Calibration accomplished with value: ");
Serial.println(calibrationValue);

Edit: You may notice that 13108 is the same as 0x3334, which on a
little endian architecture is stored in memory as 0x34 0x33. These are
the ASCII codes for "43", which is part of what sprintf() wrote past
the end of the buffer.