text:
Writing and reading multiple values through serial
I am currently busy with a project that requires me to use an Arduino and 3 potentiometers (to change background in RGB format) to write values through the serial port and read and separate them in processing.
What I want to do is to be able to use my Arduino to write multiple values to a processing program. I am quite new to coding and its been a while since I worked with my Arduino. I know how to read and write one value, but not multiple values.
Also is there a way to write 20 values?
Thanks in advance!

something like: "value1,value2,value3,value4,value5,value6.."  might do?

The simplest way is to just print them as a single line and separate them with "something". That "something" could be as simple as a space.
Serial.print(val1);
Serial.print(" ");
Serial.print(val2);
...
Serial.print(" ");
Serial.println(val20);

743 234 34 599 2 ... 427 1013 48 2 409

Then in processing you just read the entire line into a String and split it on the spaces into an array.

What would I use to split the values up? Is there a comand or is the spacing interpreted as a type of break?

Well, Processing is Java. So maybe String[] bits = myIncomingString.split(" "); would do the trick...?

Thanks for your help! I finally got it to work and am now able to write up to 18 values (only had 3 potentiometers close so i did a little division to distinguish the values). Aparently when using myPort.read() the diffrent bytes automatically get split up, so all you have to do is read and assign them. Of course after spending all thia time did I realise its basically excactly what the one example in Arduino's IDE does :/


text:
Some questions about a RGB LED Strip project that Im planning to do
Good day all
So Im in the planning and research phase of a new project that I want to start for my car. I want to control a bunch of RGB LED strips independently from each other via a micro controller, preferably Arduino  of courese, with a breakout board or something. I am going to run this system off the car battery so the current shouldn't be an issue, I hope, but prolonged usage will most likely drain the battery quite quickly. The strips I want to control are of the following lengths:

6 x 30cm Pieces
3 x 2m Pieces

So I want to be able to control all of them individually as well as the colour and brightness individually. So here are my questions:
Is there a board that the arduino can talk to that has 27 PWM outputs?
Can one maybe use normal outputs and just HIGH Low them quickly in sequence and use an arduino MEGA?
What would the current draw be if all the colours are on full on all strips? Would  it rather be better to blink them in sequence,rather than full on, and lose some brightness to reduce current draw?
Could multiplexing here be an alternative to controlling them individually? Maybe get it so I switch all the Positive outs of the LEDs, and the connect the 3 colours together. So in that case I would have 3 + 9 outputs?
Would addressable LEDs actually work better?
If you could refer to me to similar projects so I can sniff around there that would be greatly appreciated. So far Im just trying to wrap my head around all the aspects of the project. And yes I know that I wil not be able to use this while Im on public roads, its just for show.... So not sure what the legal aspects there are... :P

There isn't any Arduino with 27 PWM Outputs ! Upto how much I know.  If you really want to use so much long RGB Led Strip that also individually all the LEDs than it's not possible I would prefer you to use NeoPixel Strips instead ! Now I can't really say much will be the current draw upto when you provide me a datasheet. Next I didn't understand that 3+9 output thing.

I think you didn't even research a bit Am I correct ?

Haha I did a little... I was looking for like a chainable breakout or some controlling device for the RGB. Yeah after thinking about it for a bit, the individually addressable LEDs might be the better, more expensive option. In that case I could just use a few pins for the data write to the different strips, and then just connect them all to power, if i understand everything correctly?

have you heard of Adafruit's NeoPixels? example

You could use chainable RGB drivers like these:

They are based on the P9813 chip and can be used with the FastLed library.
You can find them on Aliexpress or eBay, if you search for "STM32 rgb".

source: Stack Exchange

license: Creative Commons - Attribution Share-Alike - https://creativecommons.org/licenses/by-sa/3.0/

all_licenses: Creative Commons - Attribution Share-Alike - https://creativecommons.org/licenses/by-sa/4.0/

sort: votes


text:
Measuring LPO (Low-Pulse Occupancy)
I'm using an Arduino clone (Seeeduino Lotus) together with a Shinyei PPD42NS sensor to measure air quality. The sensor reports its measurement as Low-Pulse occupancy. What would be the best way how to collect the value with Arduino? Currently I'm simply looping for some predefined duration using pulseIn:
unsigned long starttime;
register unsigned long sample_time; // ms
register unsigned long lowpulseoccupancy = 0; // us

// Wait for the signal to return to HIGH
pulseIn(DUSTPIN, LOW);
// Now start measuring
starttime = millis();
while ((sample_time = (millis() - starttime)) < DUST_SAMPLE_TIME_MS) {
    lowpulseoccupancy += pulseIn(DUSTPIN, LOW);
}

ratio_pct = lowpulseoccupancy / (sample_time * 10.0);

Is there a better way? In particular, this tight loop prevents Arduino from doing anything else for 30s (or a similar period).
I was thinking about using interrupts, either triggering on CHANGE, or (if that's possible) having two functions, one triggering on RISING and another on FALLING. Are there any caveats when doing so?

Seeed studio has some example code for gas sensors using LPO. 30s is way longer than necessary though. Interrupt could also work. The only downside is you can't use those interrupt pin for anything else. There is no way to have two kinds of interrupts on a single pin.

@Gerben For completeness (and not to pick nits), you could OR a couple of devices' interrupt lines (through a gate if necessary) to a single interrupt line. On an interrupt, the ISR could poll the devices which would need to be able to cooperate in some minimum way, or the interrupt lines could be latched and the latches presented on other, non-interrupt pins that the ISR could poll.

Some help: https://github.com/selfbuilt/ppd42ns-example-code/blob/master/particle_meter/particle_meter.ino

You can trigger on CHANGE, and check in your handler which case it is:
   attachInterrupt(digitalPinToInterrupt(my_pin), my_handler, CHANGE);
    (...)
    void my_handler(void) {
      if(LOW==digitalRead(my_pin)) {
        //do_falling();
      }
      else {
        //do_rising();
      }
    }

Another option would be to use a timer to poll your input, and implement a logic on top of this.

How long does it take between the change and the invocation of the handler? In particular I'm concerned if I could miss some pulses due to the delay.

authors: Pʌʀvɘsʜ ĸʌʀtoos

all_licenses: Creative Commons - Attribution Share-Alike - https://creativecommons.org/licenses/by-sa/3.0/


text:
Safe to control multiple power sources through a switch through the ground?
I've attached the breadboard layout and schematic of a circuit I'm constructing, which is a simple Arduino radio control car, with a 9V powering the Arduino Uno, and the 6 volt battery pack feeding power to the motors via the L293D. My question is regarding the switch where I've connected the ground from both battery power supplies to one side, and connected the ground of the circuit to the other side. Is this OK and safe to do? Is there anything I should be concerned about with this setup? Is there a safer or better way to do this? What components added or removed (if any) would improve this circuit in terms of power safety and battery longevity?
In case you are wondering why I have two switches, the reason is because I wanted to debug the radio receiver using the serial monitor when I wired this to USB, but I also wanted to prevent it from powering up the motors so my project doesn't try and roll away while it's still connected to the USB cable. The switch I'm asking about in my question is sort of a mains power switch, so when it's off USB I can just flip on both switches and set the robot car free...

Be very careful with those switches. If you remove the power from the motor driver chip, you must be sure all the arduino pins connected to it, are all LOW. Otherwise you will exceed the maximum input-voltage allowed for the L293D, and thing could get damaged.

Gerben your comment is interesting, would you mind elaborating? We definitely don't want to burn out any parts, but I'm not seeing the issue you see. Your comment about if I "remove the power from the motor driver chip" could refer to one of three sources of voltage feeding the chip. Based on this L293D datasheet, plus the fact that the Arduino pins output only 5V, I believe all the connections are within recommended operating conditions. Regardless, what would you add/remove to improve the circuit?

Input High voltage (Vih) shouldn't exceed Vcc1, which it does in an arduino pin is high, and you disconnect Vcc1. Secondly Vcc2 should be at least Vcc1. So if you disconnect Vcc2, while Vcc1 is connected, you fail this requirement.

You have the grounds of the batteries permanently connected together, so opening the switch won't remove them from the circuit altogether: it will leave a potential difference of 3v between the Arduino's power input at the L293's power input.
That would be exactly equivalent to having a 3v battery with its +ve terminal connected to the Arduino power input, and its -ve connected to the L293's power input, with their grounds connected together - so they're sort of wired in series, with one of them backwards, with a far-too-small supply voltage.
I suspect it won't kill anything but I would imagine it would drain the batteries and probably isn't what you want to do.

Thank you for your reply. What would be a better way to wire this up? What components added or removed (if any) would improve this circuit in terms of power safety and battery longevity? I think I provided enough information about the reason for the two switches, but if you have questions that would help clarify things, please let me know. Thanks!

You're welcome. You could put a DP (double pole) switch on the batteries -  switch both of them together. Or, you could drive the whole lot from the 9v battery and just be careful to limit the level you drive the motors at to 2/3 of their maximum -- check my calcs first though!


text:
How does serial communications work on the Arduino?
With reference to the Arduino Uno, Mega2560, Leonardo and similar boards:

How does serial communications work?
How fast is serial?
How do I connect between a sender and receiver?

Please note: This is intended as a reference question.

You might find this interesting about buffers on both sides of a Nano connected to a Raspian system running a Python data logger, using just a regular USB programming cable between the two:
https://arduino.stackexchange.com/questions/11710/does-data-came-on-serial-port-store-for-some-time

Asynchronous serial (usually referred to as serial) communications is used to send bytes from one device to another. A device could be one or more of the following:

Arduino
PC
GPS
RFID card reader
LCD display
Modem
Other

Clock rate and sampling of data
Unlike SPI / USB / I2C serial communications does not have a clock signal. The sampling clock is an agreed-upon sample rate (known as the baud rate). Both sender and receiver must be configured to be using the same rate or the receiver will receive meaningless data (due to the bits not being sampled at the same rate that they were sent).
The transmission is asynchronous which basically means that bytes can be sent at any time, with varying gaps between them. This graphic illustrates a single byte being sent:

The graphic above shows the letter 'F' being transmitted. In ASCII this is 0x46 (in hex) or 0b01000110 (in binary). The least significant (low-order) bit is transmitted first, thus in the above graphic you see the bits arriving in the order: 01100010.
The "idle" time between bytes is transmitted as continuous "1" bits (effectively, the transmit line is held high continuously).
To indicate the start of a byte, the Start Bit is always indicated by pulling the line low as shown on the graphic. Once the receiver sees the start bit, it waits for 1.5 times the sample time, and then samples the data bits. It waits 1.5 times so that it:

Skips the start bit
Samples half-way through the next bit

If the baud rate is 9600 baud, for example, then the sample rate will be 1/9600 = 0.00010416 seconds (104.16 µs).
Thus, at 9600 baud, after receiving a start bit the receiver waits for 156.25 µs, and then samples every 104.16 µs.

The purpose of the Stop Bit is to ensure that there definitely is a 1-bit between each byte. Without the stop bit, if a byte ended in a zero, then it would be impossible for the hardware to tell the difference between that and the start bit of the next byte.
To produce the above output on an Uno you could write this code:
void setup()
  {
      Serial.begin(9600);
      Serial.print("F");
  }

void loop ()
  {
  }

Number of data bits
In order to save transmission time (in the olden days, heh) you were allowed to specify different numbers of data bits. The AtMega hardware supports data bits numbering from 5 to 9. Clearly the less data bits the less information you can send, but the faster it will be.

Parity bits
You can optionally have a parity bit. This is calculated, if required, by counting the number of 1's in the character, and then making sure that this number is odd or even by setting the parity bit to 0 or 1 as required.
For example, for the letter "F" (or 0x46 or 0b01000110) you can see that there are 3 ones there (in 01000110). Thus we already have odd parity. So, the parity bit would be as follows:

No parity: omitted
Even parity: a 1 (3 + 1 is even)
Odd parity: a 0 (3 + 0 is odd)

The parity bit, if present, appears after the last data bit but before the stop bit.
If the receiver does not get the correct parity bit, that is called a "parity error". It indicates that there is some problem. Possibly the sender and receiver are configured to use different baud (bit) rates, or there was noise on the line which turned a zero to a one or vice-versa.
Some early systems also used "mark" parity (where the parity bit was always 1 regardless of the data), or "space" parity (where the parity bit was always 0 regardless of the data).

9-bit transmission
Some communication equipment uses 9-bit data, so in these cases the parity bit is turned into the 9th bit. There are special techniques for sending this 9th bit (the registers are 8-bit registers so the 9th bit has to be put somewhere else).

Number of stop bits
Early equipment tended to be somewhat slower electronically, so to give the receiver time to process the incoming byte, it was sometimes specified that the sender would send two stop bits. This basically adds more time where the data line is held high (one more bit time) before the next start bit can appear. This extra bit time gives the receiver time to process the last incoming byte.
If the receiver does not get a logical 1 when the stop bit is supposed to be, that is called a "framing error". It indicates that there is some problem. Quite possibly the sender and receiver are configured to use different baud (bit) rates.

Notation
Commonly, serial communication is indicated by telling you the speed, number of data bits, type of parity, and number of stop bits, like this:
9600/8-N-1

This is telling us:

9600 bits per second
8 data bits
No parity (you might see instead: E=even, O=odd)
1 stop bit

It is important that the sender and receiver agree on the above, otherwise communication is unlikely to be successful.

Pin-outs
The Arduino Uno has digital pins 0 and 1 available for hardware serial:

To connect two Arduinos you swap Tx and Rx like this:

Speed
A wide range of speeds is supported (see graphic below). "Standard" speeds are usually a multiple of 300 baud (eg. 300/600/1200/2400 etc.).
Other "non-standard" speeds can be handled by setting the appropriate registers. The HardwareSerial class does this for you. eg.
Serial.begin (115200);  // set speed to 115200 baud

As a rule-of-thumb, assuming you are using 8-bit data, then you can estimate the number of bytes you can transmit per second by dividing the baud rate by 10 (because of the start bit and stop bit).
Thus, at 9600 baud you can transmit 960 bytes (9600 / 10 = 960) per second.

Baud rate errors
The baud rate on the Atmega is generated by dividing down the system clock, and then counting up to a pre-set number. This table from the datasheet shows the register values, and error percentages, for a 16 MHz clock (such as the one on the Arduino Uno).

The U2Xn bit affects the clock rate divisor (0 = divide by 16, 1 = divide by 8). The UBRRn register contains the number the processor counts up to.
So from the table above, we see that we get 9600 baud from a 16 MHz clock as follows:
16000000 / 16 / 104 = 9615

We divide by 104 and not 103 because the counter is zero-relative. Thus the error here is 15 / 9600 = 0.0016 which is close to what the table above says (0.02%).
You will notice that some baud rates have a higher error amount than others.
According to the datasheet the maximum error percentage for 8 data bits is in the range of 1.5% to 2.0% (see the datasheet for more details).

Arduino Leonardo
The Arduino Leonardo and Micro have a different approach to serial communications, as they connect directly via USB to the host computer, not via the serial port.
Because of this, you must wait for Serial to become "ready" (as the software establishes an USB connection), with an extra couple of lines, like this:
void setup()
  {
      Serial.begin(115200);
      while (!Serial)
      {}  // wait for Serial comms to become ready
      Serial.print("Fab");
  }

void loop ()
  {
  }

However, if you want to actually communicate via pins D0 and D1, (rather than by the USB cable) then you need to use Serial1 rather than Serial. You do so like this:
void setup()
  {
      Serial1.begin(115200);
      Serial1.print("Fab");
  }

void loop ()
  {
  }

Voltage levels
Note that the Arduino uses TTL levels for serial communications. This means that it expects:

A "zero" bit is 0V
A "one" bit is +5V

Older serial equipment designed to plug into a PC's serial port probably uses RS232 voltage levels, namely:

A "zero" bit is +3 to +15 volts
A "one" bit is −3 to −15 volts

Not only is this "inverted" with respect to TTL levels (a "one" is more negative than a "zero"), the Arduino cannot handle negative voltages on its input pins (nor positive ones greater than 5V).
Thus you need an interface circuit for communicating with such devices. For input (to the Arduino) only, a simple transistor, diode, and a couple of resistors will do it:

For two-way communication you need to be able to generate negative voltages, so a more complex circuit is required. For example the MAX232 chip will do that, in conjunction with four 1 µF capacitors to act as charge-pump circuits.

Software Serial
There is a library called SoftwareSerial that lets you do serial communications (up to a point) in software rather than hardware. This has the advantage that you can use different pin configurations for serial communications. The disadvantage is that doing serial in software is more processor-intensive and more prone to error. See Software Serial for more details.

Mega2560
The Arduino "Mega" has 3 additional hardware serial ports. They are marked on the board as Tx1/Rx1, Tx2/Rx2, Tx3/Rx3. They should be used in preference to SoftwareSerial if possible. To open those other ports you use the names Serial1, Serial2, Serial3, like this:
Serial1.begin (115200);  // start hardware serial port Tx1/Rx1
Serial2.begin (115200);  // start hardware serial port Tx2/Rx2
Serial3.begin (115200);  // start hardware serial port Tx3/Rx3

Interrupts
Both sending and receiving, using the HardwareSerial library, use interrupts.
Sending
When you do a Serial.print, the data you are trying to print is placed in an internal "transmit" buffer. If you have 1024 bytes or more of RAM (such as on the Uno) you get a 64-byte buffer, otherwise you get a 16-byte buffer. If the buffer has room, then the Serial.print returns immediately, thus not delaying your code. If there is no room, then it "blocks" waiting for the buffer to be emptied enough for there to be room.
Then, as each byte is transmitted by the hardware an interrupt is called (the "USART, Data Register Empty" interrupt) and the interrupt routine sends the next byte from the buffer out of the serial port.
Receiving
As incoming data is received an interrupt routine is called (the "USART Rx Complete" interrupt) and the incoming byte is placed into a "receive" buffer (the same size as the transmit buffer mentioned above).
When you call Serial.available you find out how many bytes are available in that "receive" buffer. When you call Serial.read a byte is removed from the receive buffer and returned to your code.
On Arduinos with 1000 bytes or more of RAM, there is no rush to remove data from the receive buffer, provided you don't let it fill up. If it fills up then any further incoming data is discarded.
Note that because of the size of this buffer there is no point in waiting for a very large number of bytes to arrive, for example:
while (Serial.available () < 200)
  { }  // wait for 200 bytes to arrive

This will never work because the buffer cannot hold that much.

Tips

Before reading, always make sure data is available. For example, this is wrong:
if (Serial.available ())
  {
      char a = Serial.read ();
      char b = Serial.read ();  // may not be available
  }

The Serial.available test only ensures you have one byte available, however the code tries to read two. It may work, if there are two bytes in the buffer, if not you will get -1 returned which will look like 'ÿ' if printed.
Be aware of how long it takes to send data. As mentioned above, at 9600 baud you an only transmit 960 bytes per second, so trying to send 1000 readings from an analog port, at 9600 baud, won't be very successful.

References

Async (Serial) peripheral interface - for Arduino
How to process incoming serial data without blocking
RS-232 - Wikipedia
Arduino Reference - Serial

In the 1st graphic: with the arrows it looks like the stop bit is transmitted first. If you exchanged Rx/Tx and the direction of the arrows I'd think it's less confusing.

It was intended to be read from left to right (as is this sentence) and thus the things on the left happen first. Put it like this: on an oscilloscope, that is how you would see the trace.

Ok with the oscilloscope explanaion I buy that. :-)

However I've been thinking that your point makes a lot of sense. What do others think? Would it be clearer if the arrows were reversed, and I exchanged Rx/Tx?

I am thinking that starting at the Tx end (the left side) if you follow the path of the pulses (in the direction of the arrows) they first hit the "Start bit" notation, and then the data bits, and then the "Stop bit".

Hi Nick! Great post. I don't know why your use of the word "garbage" in the first paragraph is bothering me. I know I've used the term (and others like "gobledygoop") this way myself. Since this is a reference article I think there's a better, technical term that could be used.

It's not a word I use all that often ("rubbish" is more usual where I am) - I suppose I was thinking of "garbage in, garbage out" - not that it applies in this case). I think "gobledygoop" might be confusing to people who don't have English as a first language. I'll try to think of a better way of putting it. :)\

@linhartr22  I amended it to read "meaningless data" which is probably closer.

@NickGammon: Great post. Could you tell me why Arduino IDE's serial monitor (1.8.9) has no trouble communicating with my Arduino Micro, even if the two are configured for wildly different baud rates, e.g. 300 bps and 115200 bps, respectively? I assume this has to do with the direct usb connection, but, then, does the baud rate setting have any meaning at all for the Micro?

This seems to suggest it does not matter: https://arduino.stackexchange.com/a/31034 (unless I set 1200 bps, then exit the serial monitor, because that triggers a reset, as expected)

Yes, see Getting Started with the Arduino ... Micro On the Leonardo, Leonardo ETH and Micro, the main Serial class refers to the virtual serial driver on the board for connection to your computer over USB. It's not connected to the physical pins 0 and 1 as it is on the Uno and earlier boards. To use the hardware serial port (pins 0 and 1, RX and TX), use Serial1. The real serial port is Serial1, the USB port is called Serial. Using Serial on the Micro, you could set the baud rate to 1 and still get very fast serial printing.


text:
Using CD4053 for arduino
I would like to use CD4053 for multiplexing in arduino but the problem is that I don't understand how CD4053 works, is it the same as CD4051, can someone help me, provide example code and circuit??

Have you looked at the datasheet yet?

Yeah but I really don't understand how it works

You should tell us what you want to achieve, nit how you think it should be done. The 4053 may be a fine choice for your need - or may not be needed at all. Also - provide datasheet link to things you ask about to save need for N people to look up same thing to help you. What is the application? 4051 is a 1 of 8 bidirectional analog selector. You supply 3 address lines which can have 8 address states (000 001 010 011 ... ) and these connect 1 of 8 input / outputs to one master ouput/input. | A 4053 is 3 x SPDT switches. each switch is controlled by it's own enable lead. BUT

... if you do not know how a CD4053 works you cannot possibly know that you need to use one or how to do so in any meaningful way. SO tell us what you are trying to achieve. || CD 4051-53 data sheet

I am actually trying to add more IO pins for my arduino, so I researched and found out that I should use 4051. Then I went to my local electronic shop but they don't have 4051 instead they gave me 4053. Here is the link of the arduino tutorial: http://playground.arduino.cc/Learning/4051 :))

-1 for stating a vague problem and directly demanding a full solution (explanation, circuit and source code).

The 4053 can replace the 4051 (data sheet). To do that the three output pins on 4053 should be tied together (pin 4, 14 and 15, see logic diagram).
The device allows adding eight analog pins at the cost of three digital pins and one analog pin. The device will multiplex the eight new analog pins onto the arduino analog pin. Three digital pins are used to select which pin is multiplexed.
The arduino tutorial for 4051 will work just fine with the above modification of the wiring.
Cheers!

Consider one of the many I2C I/O boards (search for i2c expander on eBay) that can be purchased for a few bucks.  They are also available from many of the people that support Arduino.   It then only requires 2 pins from the Arduino for up to 8 external devices which can have from 8, 16 and sometimes more I/O per board.  They can be used as input or output.
You can also operate several displays on the same two pins as the I/O.
Have fun


text:
What is the Arduino Nano maximum wattage?
Hello,
I am currently working on a DIY project and I would like to know the Maximum Wattage of a Arduino Nano with a ATmega328 processor. If anyone know what it is it would be a great help.
Ricky

Look in the datasheets for all the major components, and add them together. There's your answer.

A typical Arduino consumes around 40-50mA. Not sure of the Nano, but it'll probably be somewhere in that ballpark.  It depends what it's doing, of course, and even if you're running it as 5V or 3.3V.  The most accurate answer you can get is to actually measure the current as it enters the board.


text:
PS4 controller too touchy on the arduino RC car i built
I recently built an RC car from scratch and I am using a PS4 controller to control it.  I have an ESC of course but my problem is I barely touch the joystick and the motor is going so fast I cannot control the car. Here is the code and any help would be much appreciated.
/*
 Example sketch for the PS4 Bluetooth library - developed by Kristian Lauszus
 For more information visit my blog: http://blog.tkjelectronics.dk/ or
 send me an e-mail:  kristianl@tkjelectronics.com
 */

#include <PS4BT.h>
#include <usbhub.h>
#include <Servo.h>

// Satisfy the IDE, which needs to see the include statment in the ino too.
#ifdef dobogusinclude
#include <spi4teensy3.h>
#include <SPI.h>
#endif

USB Usb;
//USBHub Hub1(&Usb); // Some dongles have a hub inside
BTD Btd(&Usb); // You have to create the Bluetooth Dongle instance like so
Servo servo1;  //Steering Servo
Servo servo2;  //DC Motor

/* You can create the instance of the PS4BT class in two ways */
// This will start an inquiry and then pair with the PS4 controller - you only have to do this once
// You will need to hold down the PS and Share button at the same time, the PS4 controller will then start to blink rapidly indicating that it is in paring mode
PS4BT PS4(&Btd, PAIR);

// After that you can simply create the instance like so and then press the PS button on the device
//PS4BT PS4(&Btd);

bool printAngle, printTouch;
uint8_t oldL2Value, oldR2Value;

void setup() {
  Serial.begin(115200);
#if !defined(__MIPSEL__)
  while (!Serial); // Wait for serial port to connect - used on Leonardo, Teensy and other boards with built-in USB CDC serial connection
#endif
  if (Usb.Init() == -1) {
    Serial.print(F("\r\nOSC did not start"));
    while (1); // Halt
  }
  Serial.print(F("\r\nPS4 Bluetooth Library Started"));

  pinMode (3, OUTPUT);
  pinMode (5, OUTPUT);
  servo1.attach (3);
  servo2.attach (5);
}
void loop() {
  Usb.Task();

  if (PS4.connected()) {

    {
    servo1.write(map(PS4.getAnalogHat(RightHatX), 0, 255, 50, 0));
       //map values from the x-axis of the right analog stick
    servo2.write(map(PS4.getAnalogHat(LeftHatY), 0, 255, 0, 180));
       //map values from the y-axis of the left analog stick
    }}

    else

    {
      servo1.write (25);  // set servo motor to 0 point
      servo2.write (90);  // Turn DC motor off
    }


text:
LED strip and SD card
My problem is simple yet extremely problematic. For some reason, I cannot interact with an SD card and a LED strip at the same time with my arduino. After hours of testing multiple scripts, I am 99.99% that the issue is due to the SPI.h library.
I have tried the simplest LED strip code, such as turning on led number 5. If I include SPI.h, the code does not work, the data LED of the arduino doesn't even light up, the arduino doesn't send anything to the strip data line. If I remove include SPI.h, the code works.
This is really odd, I have read about the SPI.h messing with the pins, so now I'm looking for a solution, to use the SD card module without the SPI library if it is possible.
Here is an example of a code that does not work due to the use of the SPI.h library.
Any help is greatly appreciated, this is extremely odd and problematic.
#include <Time.h>
#include <Adafruit_NeoPixel.h>
#ifdef __AVR__
#include <avr/power.h>
#endif
#include <SPI.h>
#include <SD.h>

Sd2Card card;
SdVolume volume;
SdFile root;

const int chipSelect = 4;

#define PIN            6
#define NUMPIXELS      400

Adafruit_NeoPixel pixels = Adafruit_NeoPixel(NUMPIXELS, PIN, NEO_GRB +   NEO_KHZ800);

boolean stringComplete = false;  // whether the string is complete
boolean readarray=false;
String inString = "";
int c=0;
int cc=0;
int led=0;
int i=0;
int j=0;
int pixel_n=0;
unsigned long start;
unsigned long endd;

//char* ledd[]={"", "", ""};
int ledd[3]={0,0,0};

File myFile;

void setup()
{
  // Open serial communications and wait for port to open:
  Serial.begin(9600);
pixels.begin();
while (!Serial) {
  ; // wait for serial port to connect. Needed for Leonardo only
}

Serial.print("\nInitializing SD card...");

// Now we will try to open the 'volume'/'partition' - it should be FAT16 or FAT32
if (!volume.init(card)) {
  Serial.println("Could not find FAT16/FAT32 partition.\nMake sure you've formatted the card");
  return;
}

// print the type and size of the first FAT-type volume
uint32_t volumesize;
Serial.print("\nVolume type is FAT");
Serial.println(volume.fatType(), DEC);
Serial.println();

Serial.println("Ok we're done");
delay(2000);

pixels.setPixelColor(5, (200,200,200)); // THIS DOES NOT WORK
pixels.show(); // THIS EITHER

  Serial.begin(9600);
}

void loop(void) {

}

I had the same problem with using the SD reader with a SPI SRAM. It turns out that the very cheap SD reader cards do not like multiple SPI components on the same port. Since the Arduino has only one SPI, the only thing that worked was to use a SD data logger card.
To add a tristate solution by using two resistors on the MISO line also did not work in my case.
See my post for the post I created regarding this probably similar problem.

thanks a lot for your help. So the only solution is to use a SD logger card as you say. What difference is this going to make? I looked it up and it seems like it does require the SPI.h library as well.

Please add this as a comment to my answer (and upvote if it helps).
I know it uses also the SPI library. However, it contains some hardware/circuit that makes it possible to have a second (and possibly more) SPI device on the SPI bus simultaneously. If you know what to 'add' to the non working SD part, please let me know.

Hi sorry, I wanted to do add this as an answer, but I didn't have enough reputation. Does it require a lot of tweaking to create another bus on the SD shield or does it automatically allocate it?

I don't think you can add another SPI bus. The Arduino (at least the most) only have one (hardware) SPI bus. The SD data logger can be used together with other SPI components, but the cheap SD readers cannot.


text:
Arduino Mega + XBee Shield + RAMPS 1.4 Is it possible?
Is it possible to sandwich an XBee shield between Arduino Mega and Ramps 1.4 without damaging any of the boards or lose of Ramps functionality ?
I am not trying to make a 3D printer it is rather a completely different project and I am afraid of burning my XBee or losing some functionality of ramps.
Since XBee shield has the form factor of Arduino UNO I had to 3D print the rest of the shield and use some connectors to completely cover the Mega.

IF The XBee module uses different pins from the RAMPS board then yes it will "work". However with it sandwiched like that wireless performance may be rather less than desirable. You may want to, if possible, add an external antenna.

Thanks, do you think there is no risk burning the xbee shield under normal circumstances, I'm a bit affraid of the 12v used in ramps, I burned megas before but it was because of the way I wired stepper motors and lose cable connections however I do not want to burn my shield if it is preventable

The only way you would burn it is if you let power go where it shouldn't.

Yes, it would seem like folks on the RepRap forums have gotten this to work with the following setup that should work in general:

Attach the XBee shield to the RAMPS board by attaching 4 pins on AUX-1 (namely, 5V, Gnd, D1 and D0) to the 5V, Gnd, Rx and Tx pins on the XBee Shield
Switch the UART / DLINE switch on the XBee Shield to UART

Source: RepRap Forum: Printing completely wirelessly - can it be done?
This forum thread may also be useful.

Hi, thanks for the answer, one of the links you provided links to a question I asked some time ago but what is different now is that I want my xbee shield to be between Arduino Mega and Ramps rather than on top of rams as I managed to wire it and get it to work, I am afraid not to burn it if Ramps plugs into this shield

Yes, and the answer is really simple.  You need to extend the connectors between the xbee shield and the ramps shield.  Either by adding another layer of the through pin connectors you have or by resoldering some longer ones on the RAMPS board.
You might have an issue with the RF signal, sticking that much metal near the xbee board might cause problems, but I think you can get external aerials for them, if that becomes an issue.

Hi, thanks, not sure if you noticed in the picture but I already did the pin extension as you suggested, however I was looking for someone who can tell me whether there is any risk of burning the circuits of any board by doing this, also as a bonus I was hoping to find if there are any pin clashes

authors: Александр Шокин


text:
How often can I ping an HC-SR04 ultrasonic sensor?
In my current project, I want the sensor to be continuously scanning for a value of less than 30cm. I was wondering how long of a delay I need (if any) between each call of the ping function. It currently works at 150ms between each ping call with no problem. The less the delay, the better for my project. This is the ping function:
void ping() {
  digitalWrite(trig, LOW);
  delayMicroseconds(2);
  digitalWrite(trig, HIGH);
  delayMicroseconds(10);
  digitalWrite(trig, LOW);
  duration = pulseIn(echo, HIGH);
}

For example, would having a delay of only 5ms be sufficient?

These are so minimally documented and widely sourced that you may do no better than experimenting with the ones you intend to use.  Certainly there is no point in triggering a new reading before the echo at your greatest intended range has had a chance.  After that it is more a question if the implementation forces a minimum, or if in highly reflective environments you could misread a delayed reflection of an old pulse as a new one.  5ms would be the roundtrip to a surface less than a meter away, so trying to re-read that quickly does seem like it could lead to such mixups.

Note that the microsecond delays in your current code are to form the trigger pulse, if you are using it as posted the inter-reading delay would be coming from the time waiting for the first echo (or the timeout waiting for it).

@ChrisStratton I am not worried about the microsecond delays. And I am aware that pulsein takes time. I was just wondering if I could decrease from 150ms.

How often can I ping an HC-SR04 ultrasonic sensor?

This ping() function is vulnerable to interrupts during the pulseIn(). This implies that a delay needs to wait for queued interrupts as from, for instance, Serial output. Input interrupts may still affect the results. This function only works in very simple sketches.
Possible solutions are to 1) disable during the pulse measurement (not the wait for pulse start), 2) use a more advanced method to allow concurrent events (such as timer capture).
Cheers!

Documentation from elecfreaks.com recommends 60 milliseconds between measurements. That'll cut down your time by ~60% (from your 150ms delay). It works for me.


text:
Why does my servo execute an action in the beginning when the odds are almost 0?
I made a servo motor turn if the result of random(0, 10000) is less than or equal to 1. If that is the case, the motor turns to 130 degrees, to 50 degrees, and then to default position(90 degrees). It works well except whenever I turn on the Arduino, it automatically executes the turning maneuver. It usually takes dozens of seconds for the randomNum to be 1 or 0. However, the servo always turns right away at the beginning. Here is my code. I will make comments to help you understand what I was thinking. I used no delays.
#include <Servo.h>
Servo servo;
unsigned long timer=millis();//counter
unsigned long servoTimer;
boolean turned130 = false;
int randomNum;//will hold value 0-9999
bool backCheck = false;//variables to keep track which code block to call
bool checkingAllowed = false;
bool turned50 = false;
bool startChecking = false;

void setup() {
servo.attach(12);
servo.write(90);//set default position
servoTimer=millis();
}

void loop() {
timer=millis();//update counter each time
if(checkingAllowed==false){
randomNum = random(0, 10000);//random number generator
if(randomNum<=1){//small odds
  checkingAllowed = true;//makes this codeblock unable to run
  servoTimer=millis();
  servo.write(130);
  turned130=true;/sets variables to allow other if statements to run
  turned50=false;
}
}
if(timer-servoTimer>=1000 && turned130==true && checkingAllowed==true && turned50==false){//next codeblock that runs if random <= 1 after 1 second
turn50();
}
if(timer-servoTimer>=1000 && turned130==false && checkingAllowed==true && turned50==true){
turnBack(); one second later this runs
}
if(timer-servoTimer>=1000 && checkingAllowed==true && backCheck==true){
  backCheck=false;//servo turns back to 90
  checkingAllowed = false;//allows the main code block to be called
}

delay(2);//small delay
}

void turnBack(){
random50 = random(0, 160);
servoTimer=millis();
servo.write(90);
backCheck = true;
turned50=false;
}
void turn50(){
turned130 = false;
random130  = random(0, 160);
servoTimer = millis();
servo.write(50);
turned50=true;
}

It takes a while for the random number to be 1 or 0. I do not understand how 100% of the time, the servo executes the maneuver in the beginning. I will give any more information if you need it to aid me. The random() will soon be replaced by ping() of ultrasonic sensor. Then, the problem will probably disappear. I just want to be clear on what is happening here.

Recognise that, despite the name, random() does not produce a truly random number. Because a computer is basically determinate, every time random() is called it produces results in a fixed sequence - it is possible that this sequence includes 0 or 1 straight away.
If you want it to start at a different point, you need to "seed" the random number generator by calling randomSeed() and passing in an integer. Note that it can't be the same integer every time - that would just move the sequence to the same point every time. The Arduino reference for random() suggests reading an unconnected analog input with analogRead() (which would produce different numbers at different instances in time) to "seed" the random number generator with a new starting position.
randomSeed(analogRead(A0)); // Seed random() with random starting point


text:
How can I make push buttons react to being pressed instantly?
I am making an Arduino alarm clock. I am checking for the state of a button. If it is clicked, I increment the button counter. If the counter is divisible by 2, it is mode 0, if not, it is mode 1. I have small delays in the code for each mode to help the lcd clear itself. Those delays are preventing the buttons to reacting to my touch, because there is likely a delay during that time.
#include <LiquidCrystal.h>
LiquidCrystal lcd(12, 11, 5, 4, 3, 2);
int hours=0;
int minutes=0;
const int modePin=6; //button
int prevModeState=0; //prev state of button
unsigned long timer;
int modeState;//current state
int mode=0;//mode of alarm
int buttonCounter=0;
void setup() {
lcd.begin(16, 2);
lcd.setCursor(6, 0);
lcd.print("Time:");
lcd.setCursor(6, 1);
lcd.print("00:00");
pinMode(modePin, INPUT);
}

void loop() {
modeState=digitalRead(modePin);
if(prevModeState!=modeState){    //this is the part where I check for the state
  if(modeState==HIGH){
    buttonCounter++;
  }
}
prevModeState=modeState;
if(buttonCounter%2==0){
  mode=0;
}
else{
  mode=1;
}

if(mode==0){
  timer=millis();
  if(timer%600==0){
     minutes++;
    if(minutes==60){
        minutes=0;
        hours++;
        }
     if(hours==24){
        hours=0;
     }
    lcd.clear();
    lcd.setCursor(6, 0);
    lcd.print("Time:");
    lcd.setCursor(6, 1);
    writeTime();
    delay(200); //delay
    }
}
else if(mode==1){
  lcd.clear();
  lcd.setCursor(4, 0);
  lcd.print("Set Time:");
  lcd.setCursor(6, 1);
  writeTime();
  delay(500); //delays

}
}

void writeTime(){
if(minutes<10){

      if(hours<10){
        lcd.print(String("0")+hours+":"+"0"+minutes);
      }
      else{
        lcd.print(hours+String(":")+"0"+minutes);
      }
    }
    else{
      if(hours<10){
         lcd.print(String("0")+hours+":"+minutes);
      }
      else{
         lcd.print(hours+String(":")+minutes);//possibly split if problems arise
      }

    }
}

How can I edit my code?

The simple answer is, of course, don't use any delay() calls. There is no need for them in your code.

I cannot remove delays since lcd.clear(); would be done very often and nothing would be visible on the lcd.

So don't clear the LCD. There is no reason to clear the LCD. Just over-print the existing text with new text. Go on, have a go. Just remove the lcd.clear() calls and the delays from your program and see just how smoothly the screen updates.
On an LCD a cell can only hold one character at a time. Printing one thing and then printing something else in the same place replaces the characters that are already there with the new ones. There is rarely any need to use lcd.clear() for normal screen updates - only if you really need to clear the entire screen should you use it. Just updating a bit of text on the screen does not require clearing of the entire screen.
In fact, you don't even need to print Time: or Set Time: every loop - you only need to do that once when you change mode. If you are going to clear the screen that is the time to do it.  So a quick outline:

When button pressed:

Set mode
Clear screen
Print static text (Time: etc)

Every iteration:

Print the mode's dynamic text

You see the heavyweight screen clearing is only done once when you change mode. All the rest of the time it's just updating small portions of the screen. Not only does it look nicer (no flicker) but it's also considerably more efficient and allows your program to do more.

You have a few options, including using interrupts. But I believe the most important thing is: "do not use delay()" and you might not even need to use interrupts...
Have a look on this nice post from Nick Gammon: http://www.gammon.com.au/blink with some tips about non-blocking coding.
Also a very simple "Blink LED" example: https://www.arduino.cc/en/Tutorial/BlinkWithoutDelay

I will look into that. Also, I cannot remove delays since lcd.clear(); would be done very often and nothing would be visible on the lcd. Also, the clear takes time - that is why I need the delay.

Sure you can remove the delays. Have a look on the examples from the links and you'll understand how to do non-blocking coding.In your example, instead of using the delay to hold before "clearing" the LCD, you just define "when" in the future you'll be running clearing. You are already familiar with millis() so tou're on the right direction ;)

You don't need to clear the display at all. Just overwrite the existing text with the new text. Clearing an LCD is quite an "expensive" operation and if you don't actually need it then you should avoid it.


text:
How can I made my Arduino follow the time exactly?
I am making an Arduino clock. You can set time to it, and then it keeps on going. The problem is that it is always within a minute off. It is not a major issue, but one that I would like to fix. I use the millis function. The program checks if millis is evenly divisible by 60,000(1 minute). After I set the time, millis is NOT at 0, meaning that is ahead of what I set by a number of seconds. How can I fix this? Code:
#include <LiquidCrystal.h>
LiquidCrystal lcd(12, 11, 5, 4, 3, 2);
int hours=0;
int minutes=0;
const int modePin=6; //button
int prevModeState=HIGH; //prev state of button
unsigned long timer;
int modeState;//current state
int mode=0;//mode of alarm
int buttonCounter=0;
const int incrementPin=9;
const int switchPin=7;
int incrementState;
int switchState;
int prevIncrementState=HIGH;
int prevSwitchState=HIGH;
int switching=0;

void setup() {
lcd.begin(16, 2);
lcd.setCursor(6, 0);
lcd.print("Time:");
lcd.setCursor(6, 1);
lcd.print("00:00");
pinMode(modePin, INPUT_PULLUP);
pinMode(incrementPin, INPUT_PULLUP);
pinMode(switchPin, INPUT_PULLUP);
}

void loop() {
modeState=digitalRead(modePin);
if(prevModeState!=modeState){
      prevModeState=modeState;
   if(modeState==LOW){
    buttonCounter++;
  if(buttonCounter%2==0){
    mode=0;
    lcd.clear();
    lcd.setCursor(6, 0);
    lcd.print("Time:");
    writeTime();
}
  else{
    mode=1;
    switching=0;
    lcd.clear();
    lcd.setCursor(4, 0);
    lcd.print("Set Time:");
}

   }
  }
if(mode==0){
  timer=millis();
  if(timer%60000==0){
     minutes++;
    writeTime();
    }
}
else if(mode==1){
 incrementState=digitalRead(incrementPin);
  switchState=digitalRead(switchPin);
  if(prevSwitchState!=switchState){
    prevSwitchState=switchState;
    if(switchState==LOW){
    switching++;
    }
    if(switching==4){
      switching=0;
    }

    }

  if(prevIncrementState!=incrementState){
    prevIncrementState=incrementState;
    if(incrementState==LOW){
      if(switching==0){
        if(hours<14){
        hours+=10;
        }
        else if((hours>=14)&&(hours<20)){
        hours-=10;
        }
        else{
          hours-=20;
        }
        }

        else if(switching==1){
          if((hours==9)||(hours==19)){
            hours-=9;
          }
          else if(hours==23){
            hours-=3;
          }
          else{
          hours++;
          }
        }

        else if(switching==2){
          if(minutes<50){
             minutes+=10;
          }
          else{
            minutes-=50;
          }

        }
        else if(switching==3){
          if(minutes%10==9){
            minutes-=9;
          }
          else{
          minutes++;
          }
        }

    }

  }

  writeTime();
}
}

void writeTime(){
  lcd.setCursor(6, 1);
   if(minutes>=60){
        minutes=0;
        hours++;
        }
     if(hours>=24){
        hours=0;
     }
if(minutes<10){

      if(hours<10){
        lcd.print(String("0")+hours+":"+"0"+minutes);
      }
      else{
        lcd.print(hours+String(":")+"0"+minutes);
      }
    }
    else{
      if(hours<10){
         lcd.print(String("0")+hours+":"+minutes);
      }
      else{
         lcd.print(hours+String(":")+minutes);//possibly split if problems arise
      }

    }
}

Three things you can do - any combination of these is good, but the more the better:

Use an RTC module to keep more accurate track of the time.
Connect the Arduino to the internet and use NTP to get the exact time.
Use the time provided by GPS.

The RTC chip can keep track of time when there is no external power, using just a very small button cell.
The GPS and internet time are both very accurate.
Using either or both of those sources to set and maintain the correct time in the RTC chip is the best and most accurate way of keeping the right time on the Arduino.
To increase the accuracy of your existing method you should count seconds, not minutes.
Start by recording the current millis. When 1000 of them have passed you can increase your seconds.  Don't rely on millis() % 1000 since you may miss it whilst doing other things. Also don't rely on your millisecond counter check executing at exactly 1000ms intervals - work on the principle of "at least 1000ms" and move the next check to 1000ms from where it should have happened, not where it did happen.  This can help to combat some clock drift.
static unsigned long mscount = millis();

if (millis() - mscount >= 1000) {
    mscount += 1000;
    seconds ++;
}

Then every 60 seconds you can increase your minutes:
if (seconds == 60) {
    seconds = 0;
    minutes ++;
}

I am completely satisfied with the accuracy of the method I am using. What I need is a way to have the program to start at 0 milliseconds once I set the time.

@NickSolonko You could count in seconds instead of minutes - that would increase your accuracy to 1 second.  Every 1000ms increase a seconds counter by 1. Every 60 seconds increase the minutes by 1. You control the seconds then, and decide where 0 seconds starts from. You can even include it in your display if you want. Also, don't look for "exactly % 1000" since you may miss it. Instead look for "at least 1000ms since I last ticked" and subtract 1000 from your tick counter.

I am doing %60000 now and it works fine. I have been testing the clock for the last 3 hours and it is still only 7 seconds off. Is there a reason why doing %1000 will not work?

You only have a 1 millisecond window with %, and there is now way of saying only to execute it once for that millisecond. It is very unsafe. Do it the way I have shown you.

@NickSolonko If your loop takes less than 1ms to execute then you may execute your % 60000 more than once, thus incrementing multiple minutes together. If your loop takes more than 1ms to execute then you may miss out on a % 60000 altogether and not increment a minute at all.

Will there be a difference if I declare unsigned long timer before the setup? You declared it using the static keyword inside the loop.

@NickSolonko: On the Uno, millis() does not count every millisecond: it is updated only every 1024 µs, which means it has to skip roughly one out of 43 milliseconds.

The GPS and internet time are both very accurate.; GPS is actually 36 seconds ahead of UTC.

@Gerben But it is very accurately 36 seconds ahead. Or is UTC 36 seconds behind GPS?

@Majenko :-) . I think the word you are looking for is precision. GPS is very precise, but 36 seconds from being accurate. As GPS doesn't do leapseconds, and was already 10 seconds ahead at launch, it's safe to say UTC would be the more appropriate time unit.

@Gerben No, UTC was 10 seconds behind at launch, and keeps leaping around the place :P

It seems the Time Wars have started :-P. We should just strap some rockets to the earth to make it spin at a consistent speed, so we don't need leap seconds anymore.

@Gerben Nah - we should decimalize time. 100 seconds to the minute, 100 seconds to the hour, 10 hours to the day :P

First of all, let me second Majenko in suggesting the use of an RTC. The
Arduino Uno is clocked from a ceramic resonator, and these are nowhere
accurate enough for proper timekeeping. C.f. the answers to How do I
get an accurate time?.
Next, instead of counting seconds, I suggest you instead count
milliseconds. I know it sounds like overkill, but it's actually
simpler because you already have millis() returning a millisecond
count:
void loop()
{
    uint32_t now = millis();
    static uint32_t last_minute;

    // Increment the time every minute.
    if (now - last_minute >= 60000) {
        last_minute += 60000;
        if (++minutes >= 60) {
            minutes = 0;
            if (++hours >= 24)
                hours = 0;
        }
    }

    // Do not advance the seconds when the user sets the time.
    if (time_is_being_set_by_the_user()) {
        last_minute = now;
    }
}

Oh, wait! No! Do not count milliseconds, instead count microseconds:
void loop()
{
    uint32_t now = micros();
    static uint32_t last_minute;

    // Increment the time every minute.
    if (now - last_minute >= 60000000) {
        last_minute += 60000000;

        // The rest does not change...
    }
}

Why? Because, as I said before, the ceramic resonator of your Arduino is
not very accurate. You will eventually find out that it drifts
significantly. However, if you compare to a good reference, you will be
able to calibrate the drift. If, for example, you find that it drifts
forward by 0.0025% (about 15 seconds per week, quite optimistic), you
will be able to fix it simply by replacing 60000000 by 60001500. The
same would work if counting milliseconds, except that you would only be
able to do a coarse tuning. Oh, and do not worry about micros()
overflowing.


text:
Why doesn't the time update?
I am making an arduino clock/alarm. I use an LCD screen to display the time.
void loop(){
    static unsigned long timing=micros();
    if (mode == 0) {//mode 0 is when the time should show
        timing=countTime(timing);
        writeTime(minutes, hours);//display time
  }
}
  unsigned long countTime(unsigned long timing){
            if (micros() - timing >= 59946970) {
              return timing += 59946970;//more precise because Arduino timing is not perfect
              minutes++;

    }
        else{

         return timing;
        }

      }

    void writeTime(int minute, int hour) {
      lcd.setCursor(6, 1);
      if (minute >= 60) {
        minute = 0;
        hour++;
      }
      if (hour >= 24) {
        hour = 0;
      }
      if (minute < 10) {

        if (hour < 10) {
          lcd.print(String("0") + hour + ":" + "0" + minute);
        }
        else {
          lcd.print(hour + String(":") + "0" + minute);
        }
      }
      else {
        if (hour < 10) {
          lcd.print(String("0") + hour + ":" + minute);
        }
        else {
          lcd.print(hour + String(":") + minute); //possibly split if problems arise
        }

      }

  }

I used to do all this within the loop, but decided to make it separate. Why isn't this code working?

This statement:
static unsigned long timing=micros();

...only gives it an initial value.  It is not executed during loop.  These kinds of variables should be assigned an initial value in an executable section, perhaps when the alarm time is set.
This requires the definition to be pulled out, to the file scope:
static unsigned long timing;

void loop(){
    if (mode == 0) {//mode 0 is when the time should show
        timing=countTime(timing);

Here, the static keyword has a different meaning, although I usually use it to reduce the chances of colliding with other global variable names.
Make sure to give it an initial value in executable code somewhere:
void setup()
{
  ...
  timing = millis();  // Just once?  When the alarm is set?
}

... and update it as you do in countTime.

UPDATE  It's not clear from your snippet as to when the timing variable should be initialized, so I originally avoided addressing that.  If it is really initialized just once, at program startup, you can set it in setup.  Otherwise, it should be set when the initial timing value is finally known.

Why have it static if you assign every loop? Also, as a matter of form, you should always assign a static variable with a default value.

LOL, that should be inside the if statement, and initialized in setup.


text:
How to Serial read two consecutive chars sent by computer to Arduino?
My program reads the input and plays the appropriate note for 500 milliseconds. If I type in 'a', tone(8, 440, 500) will be called. I now want to add different note lengths so that in the future, I can play songs by sending code to Arduino. I was thinking that if 'a' is typed in, the program checks the next character. If it's a 1, it's a whole note. If it's a 2, it's a half note. My code doesn't work. What is wrong with it?
    if(Serial.available()>0){
    char character=Serial.read();
    if(character=='a'){
    char leng=Serial.read();
    if(leng=='1'){
    tone(8, 440, 1000);
    delay(1000);
    }
    else if(leng=='2'){
    tone(8, 440, 500);
    delay(500);
    }

    }
    }

Welcome to Arduino SE! Could you please include the full code?

Presuming that code is the interior of loop(), your Arduino will spin until a character arrives, that is, until Serial.available()>0 becomes true.
It then reads the character with Serial.read() and if it's an 'a' immediately does another Serial.read().  In general, some delay occurs between characters arriving via a serial interface.  Whenever the serial buffer is empty, an immediate Serial.read() will return -1 instead of an ASCII character.
To fix this problem, test for availability of a character before doing the second read.  For example, you could add
while (!Serial.available()){}

before the read, to delay until a character is available.


text:
Why does Serial.print print out the wrong thing?
I am using a flame sensor. I am reading the state and then printing it. Here is my code:
void loop(){
 flameState = digitalRead(flamePin);//variables already defined and are global
existsFire();//calls the void
delay(1000);
}

void existsFire(){

Serial.println("Flame: " + flameState);

}

Before, this printed out the right thing. Today, it was printing out "lame:". The "F" and the flameState were missing. I changed it to:
void existsFire(){

Serial.print("Flame: ");
Serial.println(flameState);

}

Everything worked fine. Is there a problem with my Arduino Mega. What do I need to do to fix this?

You've stumbled across the difference in the C++ language between a String and an "array of characters". What you gave Serial.println() was an array of characters:
Serial.println("Flame: "...);

and then tried to add a number to it.
Serial.println("Flame: " + flameState);

If it had have been a String, then what you typed would have been fine:
String flame = "Flame: ";
Serial.println(flame + flameState);

Adding (literally +) a number to a String adds characters to the String to represent the number. Unfortunately you didn't start with a String, you started with an array of characters:
"Flame: "

Adding a number to THAT changes where the array starts. flameState must have been 1, and "Flame: " + 1 would have been "lame :" - as you found out!
The version that worked did so through a little bit of magic:
Serial.print("Flame: ");
Serial.println(flameState);

The first line called a version of print() that accepted an array of characters and printed each of them out. The second line called a different version of println() that accepted a number and printed out its representation as a series of characters (digits) - followed by a new line (the ln part of the name).


text:
SD-Card-Module doesnt work with external power supply
Problem description
I am trying to build a datalogger with an Arduino UNO. I have connected a SD card module to the Arduino. I have planned to catch the measurement data from the analog input pins. Everything works fine if connected to the usb port. But if I run the Arduino over an external power supply, the SD.open-method fails (It simply returns false).
The problem occurs even, if I connect the external power supply additional to the USB connection. So the problem can't be a missing serial connection.
Note that the problem only occurs, if SD.open is in WRITE-mode.
(File dataFile = SD.open("datalog.txt", FILE_WRITE);)
What I've already tried:

running the SD-card example code, which is included in the SD card library.
trying different types of file-system formattings (FAT, FAT32, with different cluster-sizes)
powering the sd-card reader with 3.3V instead of 5V

Arduino wiring
Look at the pictures to check if there are some mistakes with the wiring:

Specifications of the power supply
And here are the specifications of the power supply:

Manufacturer: MyVolts
Model: DD282MU
Input: 100-240V (AC) - 50-60 Hz
Output: 9V, 1A (DC)

I hope you can help me with my problem. And of course, I hope there is a solution for the problem at all. Thank you.

Have you tried connecting the SD card module 5V pin directly to the PSU through a 7805 regulator? How do you know SD.open() returns false when you arent connected to the PC over USB?

Thanks for your reply.
I don't have a 7805 regulator - so I didn't try it. I know that SD.open() returns false, because I have connected a LED and let it flashing in this case. Secondly I saw it in the Serial monitor: The error also occurs if both, the usb cable AND the PSU, are connected.

Scratch what I said about the 7805; just remembered theres no need for one since the Arduino 5 V output is from an internal regulator anyways. SD cards draw a lot of current (at least 100mA) when reading or writing. So it could be that with the current drawn by both Arduino and SD card causes the PSU voltage to dip and and cause dropout, Try another PSU if you have one (one with 2 A max draw); a 100uF cap from 5V to GND would help.  Also did you check the return value of SD.begin()?

Okay, thank you all for your efforts.
Finally, after changing the PSU and connecting the Arduino to another usb-port without operating system, I found the solution.
The problem was the SD-Card itself:
I swapped the SD-card with a newer (maybe more expensive(?)) one and it just works now. No matter if you connect the Arduino with the PSU or over an usb connection.
My assumption is, that there could be a different clock speed of the sd-card module on different voltages, which causes the problem. The old sd-card can't handle the fast speed and runs into an error (or just rejects it) on a write attempt...
Anyway, thank you again for your efforts!

I had this problem too, SD card not initiliasing on external power.
Having read this I turned down my external power voltage to 5.1 V
(from 7.5V ish)  and suddenly my SD card initialises on external power.
So a 'solid' 5 V must have the SPI running at a higher speed ( I guess) make sense.  The drawback is TFT is not as bright as should be.
...  better get a more 'expensive' SD card module LOL.
Ps - After some testing I had found that the SD card would work up to 6.4V on the power jack, above that the card would not initialise.   BTW I am not convinced it is a speed issue only because the SPI speed is locked by a divider to the Mega clock, so the Mega clock needs to change first.
Hope this helps


text:
Arduino Pro Micro troubles
I recently bought a brand new Arduino pro micro from Amazon, I set it up according to the instructions on sparkfun, except that when I plug it in, Windows doesn't even show that it tried to install device driver software. I figured it might just be a windows 10 thing because the tutorial was written on windows 7, so I forged ahead, and updated the device driver for COM3 in device manager, and attempted to upload a simple test for HID emulation:
#include <Keyboard.h>

void setup() {
  Keyboard.write('z');
}

void loop() {
  Keyboard.write('a');
  delay(5000);
}

It compiled just fine, and the IDE said it started uploading to the device, However, as it was uploading (or so I thought) I read a little farther and realized that the IDE wasn't set to use the right voltage (3.3V instead of 5V) I closed the IDE and reopened my sketch, changed the voltage to match up, and tried uploading it again. Here, it got stuck on the Uploading... text and so again, I closed the IDE.
Only the LED closest to the USB port is on, and it's solid green. I've connected to my computer using a Micro USB to USB adapter, and I initially plugged the board into a USB 3.0, but then switched to 2.0 to see if it made a difference. I have also tried it on Ubuntu 14.04 with no luck. I don't think it's bricked because if it was, my computer would still recognize it, but not know what it was (according to sparkfun), and as a result, I have yet to try the debricking method they suggest. Any thoughts?

Just to check, which method did you use to reset the pro micro mentioned by sparkfun, did tou use the double tap of the RST pin?

@RSM yes, I connected a jumper cable to the gnd pin and tapped the reset pin twice with the other end of the wire.

Ok, do you have another arduino board you can use as an ISP programmer

@RSM no, but I can easily get one

or you can get an ISP programmer. Also the LED by the USB is power it will always be on. Does the PC make a sound when you reset the board. And adding to this the board does not have the Pro Micro bootloader but the leonardo, try switching to that board in the IDE and let me know what happens

@RSM switch the board to Leonardo? And no, it doesn't make any sounds or recognize that a device has been plugged in.

the board you bought does not have the pro micro bootloader, but the Leonardo's. This means double press of RST won't do anything. So changing the board option in the IDE won't do anything. Also if there is no sound from the PC when a board is connected then it is bricked or at least corrupted the boot section in someway.

@RSM So should I get a refund? When I plugged it in for the first time, there wasn't any sound or recognition that I had plugged something in.

if it never showed up as a device the first time you used it it is probably faulty. IMO I would probably get a refund if it is possible. Although if you are able to get an ISP, possibly one you can borrow, and see if the board will take to having its bootloader being re-flashed as then you can tell if the whole board is faulty. Also before re-flashing, for interest sake, get the ISP to dump the flash data, you will need to use avrdude, there are TUTs on this, and if the data looks garbled then its possibly a bad board

You have to retrieve the VID/PID numbers your board actually has and change your boards.txt accordingly. On my Linux computer I made a USB connection with my corrupted pro micro clone, "lsusb" does not show it, but if I pull rst-pin down (pulse) "lsusb" does show it for a few seconds. Now I know the vid:pid numbers. I edited boards.txt (~/.arduino15/packages/Sparkfun/hardware/avr/1/1/5/:
promicro.build.vid=0x1b4f      (edited 1b4f with vid outcome of "lsusb")
promicro.menu.cpu.16MHzatmega32U4.build.pid.0=0x9205  (9205 edited)
Then in Arduino IDE I gave a reset pulse, the port showed up. I loaded the sample blinky script from sparkfun (https://learn.sparkfun.com/tutorials/pro-micro--fio-v3-hookup-guide#faq-change-pid), clicked "upload" and once again gave a reset pulse. The upload succeeded and my pro micro clone is back to normal.

That "reset > upload > reset > done" procedure actually resurrected my stuck Micro Pro. Upvote :)

The Pro Micro, like the Leonardo, cannot automatically reboot into the bootloader like boards such as the Uno and Mega.  Instead it relies on the sketch running on it listening for a special combination of events (open the serial port, set the baud rate to 1200 baud, close the serial port) to activate the bootloader.
If, for whatever reason, you don't have a working sketch installed on the board (such as you aborted the upload part way through) then there will be nothing there to listen for the "reboot into bootloader" instructions.
So you need to manually enter the bootloader. Fortunately it should be easy enough, but timing is all important.
When you first plug the board in, or when you press the reset button, you get a few seconds where the board is in the bootloader.  On the Leonardo that is signified by the LED glowing and pulsating - I don't know off hand what is shown on the Pro Micro.
As long as you press the reset button just before you compile and upload your sketch, and as long as the upload portion doesn't take too long to start (tip: compile it before uploading, it makes it faster) it should then install the sketch into the board and from then on the auto-reboot should start working.
(Note: I haven't used a Pro Micro - this is all from my experience with the Leonardo which I believe uses the same bootloader.)

Still no luck, I followed the instructions that sparkfun gave for resetting, using a piece of wire I had, and there was no change in the LED. I did accidently touch the other end of the wire to the "RAW" connector, and the LED turned off, but otherwise there was no change, I'm still stuck on Uploading...


text:
Arduino and 2 Adafruit Fingerprint modules working together
I want to do a project with fingerprint access control. But my client wants one on both sides of the door (inside and outside). Now I am using this product Adafruit Fingerprint module but I don't want to enroll each person on each fingerprint module. I want to look at enrolling each employee on 1 of these modules and then via arduino "SYNC" the fingerprint models between each other. Is this possible? Can someone maybe point me in the right direction or am I just insane HAHAHA. Look I can do the route of programming/enrolling each person on each module. But we life in a real world and at some point the fingerprint model/id's are not going to match up. And then there is going to come a problem with my online software. As well sorry for my bad lanuage  :)

How many Arduinos are you using? Describe your current setup. How are the Arduino(s) achieving internet connectivity? What is the nature of your web server?

Current setup is each fingerprint module has its own arduino uno. But ideal I just want to use 1 arduino and have both connected. I am using a ESP8266 loaded with the arduino IDE which connects to my Linux Server/Website

TisteAndii Is that using an adafruit fingerprint library, another one or are those direct commands that can be sent over serial to the fingerprint module?

You should get an Arduino Mega, if you arent using one already. You'll need the SRAM and Serial ports.
When I used this module, I didnt have enough time to experiment with it but here goes:
The enroll command for the FPM10 sensor takes an image of a fingerprint, processes it and finally creates a 512-byte model/template that is stored in flash memory with a unique ID (PageID) and used for future comparisons. However, it is also possible to read those templates from the flash memory with a few commands.
You have not said much about the role your web server plays here, so I'll assume its possible for you to store data easily and that its responsible for authorizing fingerprint enrollment and deletion. Since you have more than one sensor, a general solution to your problem would be:

The server must keep a record of available fingerprint IDs
When instructing the Arduino to begin enrollment, the server must also send along a fingerprint ID, based on its records of what ID is free. IDs may be assigned sequentially at first but templates may be deleted, leaving holes, hence the need for the server.
The Arduino begin()s the current sensor where the user is located and performs the normal enrollment. As soon as enrollment is done, the template that was just stored, should be loaded by the Arduino from the module's flash library and into one of its character file buffers using the LoadChar command. The only parameters for this command are the BufferID and the PageID.
Then the Arduino should download the template from the character file buffer into a 512-byte buffer that you will create in the Arduino SRAM. The command needed here is the UpChar command and its sole argument is the BufferID of the buffer to be read from. As soon as confirmation is received from the module, the sensor begins sending the 512-byte template in packets of 32 bytes (by default), each with a packet identifier of 0x02 until the last packet which has a package identifier of 0x08.
Then the Arduino begin()s the other sensor and sends the DownChar command to the module, which tells the sensor to expect a template to be stored in one of its character buffers (must be specified in the command). Once the Arduino receives confirmation, it should start sending the template to this sensor, using the same packet size and format that has been set for that sensor 9or the default I mentioned before if it hasnt been changed).
Finally, the Arduino sends the Store command to the sensor, to store the template in the buffer you just wrote to, into its flash library using the same fingerprint ID it was stored with in the first sensor.
The Arduino may then send confirmation to the Linux server, which then adds the fingerprint ID to the list of used IDs.

Now both sensors have identical fingerprint libraries and may be used to match fingerprints and get the same results. Deletion of fingerprints may also follow the same process: the server commands the Arduino to delete a print with a given ID and the Arduino sends the DeleteChar command to both sensors. All the commands I mentioned here are in the sensor's datasheet, which you must have downloaded along with the Adafruit library.
Use 57600 baud to communicate with the sensors, for reliable results. This is my fork of the Adafruit library with more functions available and without the buffer overflow issues. It should make the interfacing tasks a lot easier.

This is excellent. Thank you so much! I now have a clear line to work with!

Yes, you can easily do that. This finger Print sensor works over Serial communication.
You can have multiple Serial devices connected to your Arduino UNO using SoftwareSerial library.
All you have to do is to create multiple instances of Adafruit_Fingerprint initialized with different SoftwareSerial objects. i.e.
// pin #2 is IN from sensor1 (GREEN wire)
// pin #3 is OUT from arduino to sensor1  (WHITE wire)
// pin #8 is IN from sensor2 (GREEN wire)
// pin #9 is OUT from arduino to sensor2  (WHITE wire)
SoftwareSerial mySerial1(2, 3);
Adafruit_Fingerprint finger1 = Adafruit_Fingerprint(&mySerial1);
SoftwareSerial mySerial2(8, 9);
Adafruit_Fingerprint finger2 = Adafruit_Fingerprint(&mySerial2);

Now, you can use finger1 and finger2 for your finger print operations. (previously referenced as only finger)
In order to understand Serial Communication with multiple serial devices, have a look at this Arduino.cc Offical tutorial.
Hope it helps.


text:
Arduino Digital Input. Trigger HIGH by 12V to 36V
I want to build a small circuit that will switch a LED on (for arguments sakes) when the cars ignition gets switched on. But I want to make it versatile so I can work with between 12V - 36V (Cars, Trucks, etc). What would be the best to read the Ignition status via the arduino. Know I have thought of an idea by working with voltage divider. Basically taking the principal of reading voltage Instructable Example and working from there. Any thoughts?

An Arduino seems a bit of overkill to just light an LED when the power is turned on...

Hi Majenko. My circuit will do more then just switch an LED on. Like I said (for arguments sake) I actually want to do a Vehicle Tracking unit but I must be able to to handle all voltage inputs between 12V - 36V

Even easier:

input - series 220 ohm resistor, and a 78L05 voltage regulator (check for maximum voltage). This allows you handling like 4..30V and get a solid "1" on digitalRead. (4V input makes like 3V output which is still logic high).

HAHAHA Gee Bee its you again. You always seem to come to my rescue. Tell me would something like this work 7805 SMD

Sure, it works up to 35V input out of the box, no series resistor. LM317HV works for much higher input voltage (you need two resistors to set up the output to 4.5Vish to get a stable 1 level).
These solutions are clear overkills - you could do this with series resistors, zeners, NPN transistor, etc. - but a voltage regulator is only one component to solder.

you can use transistor bias circuit, opto-couples circuits, op amp circuit or a simple relay circuit, to get 5V output signal when 12V-36V signal is triggered.


text:
Why isn't there bus contention on the MISO line during SPI-based programming?
Consider this image from sparkfun:

Let's say I have this setup, a master and n slaves, plus a programmer connected to the SPI lines.
When I program the master (Arduino), the Arduino is reset. This means that all the data pins go low.
Since SS is active low, all the SS pins on the slaves go active.
I believe this means that all the slaves start driving the same MISO line (blue arrow from slaves to master), either high or low.
Doesn't this result in bus contention on that line? If not, what's the mechanism that prevents bus contention from happening?

This means that all the data pins go low. They don't go LOW, but high impedance input.

And since the ports go high impedance, put a pull-up resistor on the SS line to drive it high when the MASTER is reset

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

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

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

in the code that accesses SPI device #2,

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

SPI bus contention can also occur during device programming (loading the bootloader or firmware image), if there is an attached SPI slave device, and its chip select (SS) is not pulled inactive by a pullup resistor.
I had a problem with this on one of my designs a few weeks ago. I was trying to burn the bootloader into some blank ATmega328-AU chips post-assembly, and my device programmer wasn't able to successfully program the chips because my one slave device had its chip select connected only to an ATmega328 pin.
I had previously breadboarded this design using an Arduino Pro Mini board, and it was working fine; but when I moved to first prototype PCB there was bus contention on MISO -- the blank ATmega328 wasn't driving the slave device's chip select high or low, but it floated low (active), causing MISO contention.
My solution (workaround) was temporarily contacting the chip-select to VDD 3.3V through a 10kohm resistor. This made my SPI slave device inactive, allowing the device programmer to successfully load the bootloader.
I think there would be no harm in leaving the pullup resistor on chip select (since it's an active-low signal), but it was only really necessary when using the device programmer. After I had the prototype boards initialized with the bootloader image, I was subsequently able to load firmware images as usual.
(One minor unrelated issue was that my assembler purchased ATmega328-AU when I had specified ATmega328P-AU -- they are almost the same, and it doesn't make a difference for my application, but it was annoying that I had to use a slightly different command line argument than then one I used with the Arduino Pro Mini board.)

Really my question applies both ways. If there is bus contention that the programming should fail. But I think what you're saying is that my assumption that pins are driven low on reset (or blank) is false. Rather, they  float.

I think the ATmega328 PORTB pins are initially configured as inputs at power-up reset, will check datasheet...

Confirmed. Section 13.2.1 Configuring the Pin: "The port pins are tri-stated when reset condition becomes active, even if no clocks are running."


text:
Arduino serial port eats data for 3 seconds before it sends?
With the source code below, I'm getting what I think to be strange behaviour with the serial port output.
void setup() {
  Serial.begin(9600);
}

int c = 0;
void loop() {
  Serial.println(c++);
}

Presumably what this will do is starting printing incrementing numbers, one on each line, starting from 0. However, my serial monitor only starts printing these numbers after the 3000 mark. I found this behaviour only after discovered in another sketch that I was losing data at the beginning.
Is this normal Arduino behaviour? Or a serial monitor problem? Or something else?

Is it consistent? Does it always begin at 3000? And does it continue as expected (3001,3002,...) after that?

There are many Arduino models. It helps considerably to state in the question which one you are using.

Is this a Leonardo or Yun?  If it is, you have to wait until the Serial object says the USB connection is really ready:
void setup() {
  Serial.begin(9600);
  while (!Serial) {
    ; // wait for serial port to connect. Needed for native USB
}

Read this.
Because you did't wait, your loop is able to execute 3000 times before Serial actually sends something back to the PC.


text:
Possible to use the hardware serial port for peripheral on ATmega32u4 when using USB for programming?
I have a Arduino Pro Micro and use the USB port for programming. Is it possible to use the hardware serial port for connecting with a peripheral while I'm using the USB port (and hence the hardware serial port) for programming? Or must I disconnect the USB cable or otherwise reconfigure the hardware?

I have a Teensy 2.0 with a ATmega32u4 and I can use both, with the USB as Serial.* and the hardware UART as Serial1.*
For the Arduino Pro Micro it is the same.  See Arduino Pro Micro, get data out of Tx pin?
For Teensy, see https://www.pjrc.com/teensy/td_uart.html


text:
Trying to verify that Arduino Pro Micro ISP is working
I'm trying to program an Arduino Pro Micro with another Arduino Pro Micro. The purpose is to verify that I can use this Pro Micro board reliably as an ISP to program another Arduino device that does not have a USB interface.
These are actually Pro Micro clones but they seem to work quite well using the Arduino Leonardo profile. I'm following this pinout.
Here is the photo of the setup:

The "red" Pro Micro is set up as ISP using the stock ArduinoISP sketch (didn't think anything needed changing). The "white" Pro Micro is the one I'm trying to program.
The pins are connected, 5V - 5V, GND - GND, MISO - MISO, MOSI - MOSI, SCLK - SCLK, Pin 10 - Pin 10 (reset? this might be wrong).
I've confirmed the ISP sketch is running by the green heartbeat LED. The three LEDs on the red board are connected to pins 7 (top), 8, 9 (bottom), with 9 being the heartbeat.
I loaded the Blink sketch and changed the LED pin to pin 9 since the default pin 14 on the white board is being used as the MISO pin for programming.
In the IDE, I set the board to Arduino Leonardo, port to the red board's port, programmer to "Arduino as ISP" and ran "Upload Using Programmer".
The only output I get is:
avrdude: Yikes!  Invalid device signature.
         Double check connections and try again, or use -F to override
         this check.

Since I'm really just beginning all of this, I'm a bit confused what might be wrong and what could be a next troubleshooting step. Any help appreciated.

"Pin 10 - Pin 10 (reset? this might be wrong)." yepp, should be Pin 10 - RST (on target).

As Mikael Patel notes, pin 10 on the programmer Pro Micro should run to RST on the target.
That might or might not fix the problem.  In some previous instances of the “Yikes! Invalid device signature” [1,2] bad breadboard connections turned out to be the problem.  I suggest you run a second (or even a third) set of jumpers in parallel with the first set.  Of course use matching colors to avoid confusion.

I've done that to no avail. Doesn't seem to make a difference.


text:
Cheapest Arduino wireless solution for home automation
I am from programming background and newbie to this field.
Couple of days ago I brought Arduino Uno (5V). I want to control light bulb and fan from my Android. So I thought, I will buy relays and ESP8266 module and its done.
But now read somewhere that ESP8266 works with 3.3v and my Arduino supplies 5v.
Should I go for different Arduino board (like Arduino pro or Arduino mini) or is there any reliable & cheap solution that will work my Arduino Uno (5V) ?

Millions (well, hundreds or thousands) of people use the ESP8266 with the Arduino. There are trillions (well hundreds) of tutorials. Wiring it up requires two resistors. Is discovering that through google beyond your capabilities?

There are in fact around 300,000 hits on "ESP8266 Arduino" Google search. The top ones describe how to interface with a Uno, as this is a common problem. Did you check any of those before posting your question?

@Majenko I know there are 'There are trillions (well hundreds) of tutorials' and every article has something which contradict to the content of other. They left me more confuse thats why come to this forum, so if you don't want to help me its fine but keep your arrogant comment to yourself.

If you want to go for cheap just use a ESP8266 no arduino needed.

To elaborate this answer: Actually, you can download your own code to an ESP8266 module, as it comes with (a really powerful) microcontroller. Actually you can program it from Arduino IDE directly via an USB-serial cable. See https://learn.sparkfun.com/tutorials/esp8266-thing-hookup-guide/installing-the-esp8266-arduino-addon and http://makezine.com/2015/04/01/installing-building-arduino-sketch-5-microcontroller/ as a full example.


text:
Wire.h not found newliquidcrystal
The arduino IDE can't seem to find the wire.h file when i'm using the new liquid crystal library. Does anyone know how to solve this? here is the code i'm using and the error message:
/*-----( Import needed libraries )-----*/
#include <Wire.h>  // Comes with Arduino IDE
#include <LiquidCrystal_I2C.h>

/*-----( Declare Constants )-----*/ /*-----( Declare objects )-----*/ // set the LCD address to 0x27 for a 16 chars 2 line display // A FEW use address 0x3F // Set the pins on the I2C chip used for LCD connections: //                    addr, en,rw,rs,d4,d5,d6,d7,bl,blpol LiquidCrystal_I2C lcd(0x27, 2, 1, 0, 4, 5, 6, 7, 3, POSITIVE);  // Set the LCD I2C address

/*-----( Declare Variables )-----*/ //NONE

void setup()   /*----( SETUP: RUNS ONCE )----*/ {   Serial.begin(9600);  // Used to type in characters

  lcd.begin(16,2);   // initialize the lcd for 16 chars 2 lines, turn on backlight

// ------- Quick 3 blinks of backlight  -------------   for(int i = 0; i< 3; i++)   {
    lcd.backlight();
    delay(250);
    lcd.noBacklight();
    delay(250);   }   lcd.backlight(); // finish with backlight on

//-------- Write characters on the display ------------------ // NOTE: Cursor Position: (CHAR, LINE) start at 0     lcd.setCursor(0,0); //Start at character 4 on line 0   lcd.print("Hello, world!");   delay(1000);   lcd.setCursor(0,1);   lcd.print("HI!YourDuino.com");   delay(8000);

// Wait and then tell user they can start the Serial Monitor and type in characters to // Display. (Set Serial Monitor option to "No Line Ending")   lcd.clear();   lcd.setCursor(0,0); //Start at character 0 on line 0   lcd.print("Use Serial Mon");   lcd.setCursor(0,1);   lcd.print("Type to display");

}/*--(end setup )---*/

void loop()   /*----( LOOP: RUNS CONSTANTLY )----*/ {   {
    // when characters arrive over the serial port...
    if (Serial.available()) {
      // wait a bit for the entire message to arrive
      delay(100);
      // clear the screen
      lcd.clear();
      // read all the available characters
      while (Serial.available() > 0) {
        // display each character to the LCD
        lcd.write(Serial.read());
      }
    }   }

}/* --(end main loop )-- */

Here is the compiler output

Arduino: 1.6.7 (Windows 10), Board: "Arduino Nano, ATmega328"
C:\Users\martin\Documents\Arduino\libraries\LiquidCrystal\I2CIO.cpp:35:26:
  fatal error: ../Wire/Wire.h: No such file or directory
#include <../Wire/Wire.h>
                      ^

compilation terminated.
exit status 1 Error compiling.
This report would have more information with   "Show verbose output
  during compilation"   enabled in File > Preferences.

I’m close this question because this Q&A pair is obsolete.

The liquid crystal library has to be installed in the same folder as the wire library:
libraries/Wire/Wire.h (etc)
libraries/LiquidCrystal/LiquidCrystal_I2C.h (etc)

There is a hard-coded path in the liquid crystal library pointing to the wire library that is relative to where the liquid crystal library is, which is done to get around the problem that the Arduino library doesn't recurse libraries. It's not actually needed since including the Wire library in the IDE is enough to tell it where to find it for the liquid crystal library, so I don't really know why they did it that way.

Thanks! i copied the whole Wire folder from C:\Program Files (x86)\Arduino\hardware\arduino\avr\libraries and put it in the documents/arduino/libraries folder and it worked!
Is there any cons with solving it this way?

An upgrade to the IDE or Arduino core could leave your two copies of the wire library out of step. Just so long as you keep your copy up to date it should be fine.


text:
Pin 0 (62) you are trying to use is not supporting interrupts
Using RCLib (github) I'm getting this error. The trick is that the RCLib example works on it's own but does not work in my program (github).
Serial Output "Error"
Pin 0 (62) you are trying to use is not supporting interrupts
Pin 1 (63) you are trying to use is not supporting interrupts
Pin 2 (64) you are trying to use is not supporting interrupts
Pin 3 (65) you are trying to use is not supporting interrupts
Pin 4 (66) you are trying to use is not supporting interrupts
Pin 5 (67) you are trying to use is not supporting interrupts

It is quite right. Those pins aren't interrupt pins. What you want to do is make it use PinChange interrupt pins instead.
This can (by the look of things) be done by including the PinChangeInt.h library before including the RCLib library.

Does that make the Arduino use software interrupts instead of hardware interrupts?

No. That makes a different kind of hardware interrupt available to that library.

Hmm, well I have NO idea how you came to this conclusion and the quickness at which you did it is disorienting. I'm sure much of it chalks up to experience but can I bother you to open my mind to your troubleshooting technique(s) ?

Simple: I looked at the source code for RCLib.h and found the bit where the error message is. Then I saw that it's wrapped in a test to see if PinChangeInt_h was defined (which is done by the PinChangeInt.h library) and that by including that library it will change the behaviour accordingly.


text:
Trouble reading analog (PWM)
I'm trying to test my analog signal before I send it to an actual analog device. I've written some code and considering the analog square I have expected to see a digital ON or OFF during a single duty cycle but I'm either seeing all OFF for analog values 0-127 and all ON for values 128-255.
My expectation is that I would see 51 ON and 49 OFF thus getting a value closer to 128 of 255.
What am I missing? Is this even possible?
int OUTPUT_PIN = 2; // digital 2 (PWM)
int INPUT_PIN = A0; // analog 0

void setup() {
  pinMode(OUTPUT_PIN, OUTPUT);
  pinMode(INPUT_PIN, INPUT);

  Serial.begin(9600);
}

void loop() {

  analogWrite(OUTPUT_PIN, 128);

  float j = 0;
  for(int i = 0; i < 100; ++i) { // get 100 reads per duty cycle
    float v;
    v = digitalRead( INPUT_PIN );
    if(v >= 1) Serial.println("ON");
    if(v <= 0) Serial.println("OFF");
    j += v;

    delay(12); // trying to match the duty cycle
  }
  j /= 100; // average out the 100 reads

  Serial.println(j);

}

Seeing all on for 128+ and all off for 127- is indicative that you are using a pin that can't do PWM.
If you use a non-PWM pin with analogWrite it goes "Is this less than 128? Yes? Then I will turn it off. Otherwise I will turn it on.".
case NOT_ON_TIMER:
default:
    if (val < 128) {
        digitalWrite(pin, LOW);
    } else {
        digitalWrite(pin, HIGH);
    }

Since you don't mention what board you are using I can only assume that you have picked a pin that can't do PWM. Change to a pin that can do PWM and you should get a PWM signal.

I tried on both Mega 2560 and Uno. I see now on the uno that some digital pins have a ~ in front of the number. Coincidentally these are the only pins which send a PWM signal. Moving from outpin pin 2 to 3 solved the issue.

That's not coincidental. The ~ is used to denote which pins can do PWM. Like it says on the board: DIGITAL (PWM ~)

You are completely right. You've certainly made me very aware of my rookie mistake. Thanks for your time in helping me track down my issue.


text:
Why are my objects losing their member's values?
I have a Channel class which on instantiation receives a _type via new Channel("type", ...). I can read the type back out via channelObject->getType() which returns a string.
This has always worked fine until today. I have no idea what changed but if I Serial.print(channelObject->getType()) I get a nasty amount of garbage in the terminal:
���QQ���� 00@��������'����������������������(�����������b���������������������������������������H���E���������������������������������������������������������������uD��DESC  initializedOoops, no LSM303 detected ... Check your wiring!Ooops, no BMP180 detected ... Check your wiring!Setting IMU ground: Setting front: !! set ground kalman initConnect Powerbooting up...SWATBOT SETUP COMPLETEtype_xelevatoraileronthrottlerudderaux1aux2serial in: DISARMED!E;1
B��LSM303(>.a+a+8L.�S2E/��BMP085.qL3GD20���T �4&�'�%�%�%&
naninfovf�!,�!H�!��!��!Њ!�D�s6/&������?)m((a&l1=#k2���_
X� +�����+����=� ��J�5�.d�6s'���z :����������-/�type_xtype_x    elevatoraileron    throttlerudderaux1aux2�F�OX4Vjx 7���2�?�xr����:~aileronaux1
�:~  elevator
 ~ throttle:):~rudder������=�@��>�̀?��=�=�@��>�����=�=�@��>�f�B��=�i�?�k��BMP085QF��D�C
�#<}D������D]v� ,B����^v�QF����P}D .?P���f�B.s�D2m .?�oIB��P��(=:@���A�A�@9�@ A@�@�?�A0SB0N�>dC9�@ A@�@�?�A ��A��dC��L?��L>s����C�B(��"�  (�  �"��
(�

"elevator", "aileron", "throttle", and "rudder" are types for objects that I know exist but why is it coming out like this? I'm also seeing other unrelated parts of my program being spit out too like "Ooops, no LSM303 detected ...". This is all so strange.
If I had to guess, there must be an awry pointer somewhere in my application but I'm having no luck finding it. Worst case I'll rollback my application and retrace my last implementations (a couple days worth of work).
Can anyone give me a clue as to what is going on here?
My broken application is online at: https://github.com/jacksonkr/SwatBotSpine/tree/master
Emphasis on Channel.h:68 which is where all the garbage is coming from.
Related code:

RemoteControl.h:37
RemoteControl::getChannel

You might be running out of RAM. I suggest you change all lines like this:
 Serial.println("SWATBOT SETUP COMPLETE");

to use the F macro like this:
 Serial.println(F("SWATBOT SETUP COMPLETE"));

There seem to be a lot of places you could change.

Also I would not put code (implementation) into the .h files. That belongs in .cpp files. The .h files are for declarations.

Inside a class function, using this-> all the time just makes things look cluttered, eg.
StabilityController::StabilityController(RemoteControl* rc, ROSController* ros, IMUController *imu) {
  this->_rc = rc;
  this->_ros = ros;
  this->_imu = imu;

The F() macro is a life saver and certainly thwarted these goofy lockups. I must have been lower on memory than I realized. Thanks for introducing me to this. Also, I use this-> and other tactics to keep track (visually) of where my data is coming / going; everyone has their style.

authors: Женёк Семёнов