How to convert an hex string to an array of bytes?

There are indeed many methods (and they all work if done right).

Is it always a lenght of 8 ? That means it is 32-bit unsigned long number.
The strtoul can convert it to a long. Use '16' for the base. If you need the seperate numbers, you can shift the unsigned long and convert to bytes or use a union.

It is also possible to do with a for statement can convert each character of the input to a value: forum.arduino.cc: convert HEX (ASCII) to a DEC int

[ADDED]
Thank you @goddland_16 for providing a full sketch. I could not stay behind and wrote a sketch with strtoul.

char *CardNumber = "B763AB23";
byte CardNumberByte[4];

void setup()
{
  Serial.begin(9600);
  Serial.println("With strtoul");

  // Use 'nullptr' or 'NULL' for the second parameter.
  unsigned long number = strtoul( CardNumber, nullptr, 16);

  for(int i=3; i>=0; i--)    // start with lowest byte of number
  {
    CardNumberByte[i] = number & 0xFF;  // or: = byte( number);
    number >>= 8;            // get next byte into position
  }

  for(int i=0; i<4; i++)
  {
    Serial.print("0x");
    Serial.println(CardNumberByte[i], HEX);
  }
}

void loop()
{
}


Basically you can't. PWM value required to turn to a specific degree will depend on motors, on voltage, on hardware, in the current velocity of the car and probably on the surface under the wheel. Also keep in mind that real cars don't turn like that (at a fixed angle). Instead, driver constantly adjusts the position of the steering wheel, while looking at the road (i.e.a feedback system). Same is for RC cars, operator smoothly deflects the joystick looking at the vehicle.


How to get 38 Khz clock from Timer 0/2 in Arduino Mega 2560?

It appears that you didn't set any Clock Select bits.  Per datasheet,

  clkT0 can be generated from an external or internal clock source, selected by the Clock Select bits (CS02:0). When no clock source is selected (CS02:0 = 0) the timer is stopped.

That could account for getting no output at all, if that's what's happening.  [I had overlooked (1<<CS01) in your TCCR0B setup.]

You have the COM0A1 and COM0B1 bits set, and you apparently assume COM0A0 and COM0B0 are clear. (Note that in the code below, I say TCCR1A = ... and  TCCR1B = ... instead of using |=, because |= is not reasonable to use for initial setup).  In the #7 fast PWM mode that you selected via WGM bits, this would lead to OC0A and OC0B clearing on their respective Compare Matches and setting at BOTTOM, which looks more or less ok for the OC0B pin, if you have OCR0B set to about half of OCR0A.  If the OC0A pin clears, however, it probably gets set again a cycle later, if I understand correctly.  (However, I'd want to actually test the code, with oscilloscope connected, to say for sure.)

Note that the OCR0A count of 52 and prescaler of 8 will set up a counting frequency of 1600000/(52+1)/8 Hz, ie about 37735.85 Hz, while a count of 51 would give 38461.54 Hz.  If accuracy matters, you can use simpler and more accurate code like the following.  It uses a prescale of 1 and count of 209, to generate a toggle frequency of 1600000/(219+1) Hz, ie about 76190.48 Hz, and a square wave frequency of about 38095.24 Hz.   Note, this code is written for timer 1; it should be straightforward to adapt to timer 0, because 209 is less than 255, the upper limit of TCNT0.

// Generate a constant frequency on PB1, using Fast PWM - jw May 2017
enum { OC1Apin = 9 };    // Arduino digital pin #9 = OC1A = PB1

void setup() {  // Set up timer 1
  noInterrupts();               // Turn off interrupts during setting
  TIMSK1 = 0;                   // Turn off timer 1 interrupts
  // Set timer 1 to Fast Pwm mode with OC1A (dig pin 9) toggling
  TCNT1 = 0;                    // Zero the counter
  TCCR1A = 1<<WGM11 | 1<<WGM10  // for Fast Pwm with TOP from OCR1A
    | 1<<COM1A0;                // To toggle OC1A PB1 D9 on Compare Match
  TCCR1B = 1<<WGM13 | 1<<WGM12// for Fast Pwm with TOP from OCR1A
    | 1;                      // Start timer 1 with prescale 1
  // Set OCR1A *after* setting up TCCR1A & TCCR1B
  OCR1A = 209;                // Gen. about 38095.24 Hz
  pinMode(OC1Apin, OUTPUT);
  interrupts();
}
void loop() {}

Edit 1: Here are some of the differences between this code and that shown in the question, aside from using timer 1 instead of 0:

• Initialization of TCCRxA and TCCRxB registers here is done using Register = expression forms, rather than  Register |= expression forms.  Just OR-ing your bits in may be a problem if some other CS bits are set.  For example, in the Arduino environment, initialization for millis() will set a prescale factor of 64, by setting both of the CS00 and CS01 bits, so that when you say TCCR0B |=(1<<WGM02) | (1<<CS01); you end up with both of the CS00 and CS01 bits still set, and a prescale of 64 instead of 8.

• TCCR1B = ... | 1;  // Start timer 1 with prescale 1 sets the CS00 bit and leaves the CS01 and CS02 bits clear, selecting prescale 1, while TCCR0B |= ... | (1<<CS01); selects a prescale factor greater than 1.

• The code shown here generates a square wave because it toggles a pin at a constant rate.  The code in the question sets OCR0B to 26, which will give 27 clock-cycles to half of each output cycle, and 26 clock-cycles to the other half.

• The code shown here generates a frequency of about 38095 Hz, which is about 0.25% high, vs a frequency 0.7% low for the code in the question.

Edit 2: One way to get a fixed number of pulses is to set up an interrupt handler that is invoked once per toggle (or, once per cycle if appropriate).  It can decrement a counter, and shut off an output pin when the counter gets to zero.  Or could set the output pin low and the CS bits to 0 to stop the counter.  For example, if timer 1 is in use:

volatile byte TogCounter;
...
// In setup():
TIMSK1 = 1<<TOIE1;  // Enable timer 1 overflow interrupt at TOP
...
// Define a timer 1 ISR
ISR(TIMER1_OVF_vect) {      // ISR for timer 1 overflows
  if (TogCounter) {         // Don't decrease if not counting
    --TogCounter;
    if (!TogCounter) {
      pinMode (TogPin, INPUT); // Disable output when count runs out
      // If desired, set a volatile wavetrain-is-done flag here
    }
  }
}

To output a specified number of cycles n, set the mode of TogPin to OUTPUT and set TogCounter to 2·n.  Note, waveforms will be of more-consistent length if you also clear the counter register just before starting any pulse train.

To generate a sequence like m1 cycles on, n1 off, m2 cycles on, n2 off, etc, you could set up an array containing m1, n1, m2, n2, etc; then each time TogCounter runs down, toggle TogPin from INPUT to OUTPUT or vice versa, and load the next array entry into TogCounter.


ESP8266 + NeoPixel - Cannot set pixel color, I got "Exception 29: StoreProhibited"

Your "constructor" isn't doing what you think.

In the example you point to you have, efectively:

Class object = Class(parameters);

Whereas in your code you have:

Class object;

object = Class(parameters);

In the first form it results in a new object constructed at declaration time. In the second it first creates a new "empty" object and then at a later date tries to copy a newly constructed object into it - which may be failing if the class doesn't support copying.

Instead you should be working with new and pointers.

In your class definition you create a pointer to your Adafruit class:

private:
    Adafruit_NeoPixel *pixels;

Then you create a new object pointing to it:

pixels = new Adafruit_NeoPixel(numOfPixels, dataPin, NEO_GRB + NEO_KHZ800);

Accessing it is then done with -> instead of .:

pixels->setPixelColor(i, red, green, blue);


The library you linked to does not indicate it works for STM32 architecture. The display uses SPI, and each architecture has it's own way of implementing such peripherals.

There is this library: https://github.com/KenjutsuGH/Adafruit-PCD8544-Nokia-5110-LCD-library which is a port of the Adafruit 5110 driver to STMduino.


How do I get the Itead 3G shield to work?

What should I be seeing if anything?

Usually, a GSM module will not send (unsollicited) messages. Everything it sends will be an response to an received message.

Try sending AT (with a new line/carriage return (depending on the GSM module)) to the GSM module, it will send something like AT OK or just OK

And you didn't set the pin directions (output/input), might be doen by the serial libraries, but beter be safe if you're not sure.

Also check your wiring (jumpers on UART multiplexer in this case?) and share it with us, Rx/Tx wiring often gets messed up :)
If your GSM module has a USB connection, you might even test it with a terminal (taking out the Arduino in the middle, thus any wiring/code between.)

I also suggest you change the name of the serial connection to the GSM to something like gsmSerial rather than mySerial (which could be anything).

Be sure the 3G shield has enough power (amperes), otherwise they might reset when attempting to make an connection.
(Put the external supply in the Arduino, rather than USB powered)


“Multiple definition” means that you have something defined more than
once. According to the error message, some methods are defined both in
libraries\Adafruit_DRV2605_Library and in your sketch folder.
It looks to me like you are trying to use two copies of the
Adafruit_DRV2605 library. One of them is properly installed as a
library, and the other is within your sketch folder. You don't need two
copies. If the library is properly installed, there is no point in
copying its source files to your sketch folder. Get rid of that extra
copy and try recompiling.


Depending on what is setting the message on the topic, payload may, or may not be, a NULL-terminated string.  This is why they provide the length parameter.

You could consider comparing the data with memcmp() which is like strcmp() but doesn't look for a NULL termination - instead it takes a length parameter.  This is good if you may have NULL bytes in your payload.

An alternative is strncmp() which both looks for a NULL termination and also limits the length using a length parameter. Better for payloads you know are strings, but you aren't sure if they have NULL termination or not.

Here is a callback (for PubSubClient on ESP8266) I have in one of my projects which uses strncmp():

void callback(char *topic, byte *payload, unsigned int length) {
    if (!strcmp(topic, SUBTOPIC)) {
        if (!strncmp((char *)payload, "on", length)) {
            digitalWrite(POWERPIN, HIGH);
            powerState = true;
            client.publish(PUBTOPIC, "on", true);
        } else if (!strncmp((char *)payload, "off", length)) {
            digitalWrite(POWERPIN, LOW);
            powerState = false;
            client.publish(PUBTOPIC, "off", true);
        }
    }
}

Simply casting your payload to (char *) is enough for the functions to take it as a string, and the length parameter will prevent looking past the end of the payload if there is no NULL termination.

It's not perfect - a single byte payload of o will falsely match the first on, but if that is a critical problem I am sure you can find a way to work around it by checking what length equals.


Unable to configure Ethernet using Arduino Uno R3

I use more or less the same code to do my networked widgets and it has been quite reliable in my experience. Do you know if you have a DHCP server on the network segment that the Arduino is on? The absence of a server or a configuration that won't respond to the Arduino seem like the most likely explanation for the problem you're seeing.

The way to troubleshoot this would be to get another machine on the same network segment and watch the traffic with tcpdump or Wireshark or a similar tool. If you're running on a "third party" machine (e.g. not the DHCP server) then you'll be able to see the Arduino's side of the DHCP exchange, but I'm not sure if you'll be able to see the server (the Arduino will be broadcasting since it can't know the address of the DHCP server, but I think the server's response is unicast). If you've got a Linux box or some other machine that you can log into where you could run the DHCP server you can watch both sides of the negotiation. But even if you can't get to the server it will help to see if the Arduino is starting the DHCP negotiation.

If you need a fixed IP address on the Arduino, the way to do it is to configure the DHCP server to reserve an address for the Arduino. That way you can have a known address on the Arduino without having to hard code an IP address (which will eventually bite you).


How can i read serial data into a string until a certain character is recieved?

What you need to do here is implement a small finite state machine.

Basically you need to look at each character as it comes in and make a decision what to do with it depending on what state you're in at the moment.

Basically the operational decisions you need to make are:

Is the character a < and am I currently not reading a string?

Yes, start reading the string.

Is the character a > and am I currently reading a string?

Yes, finish reading the string and process it

Is it any other character and I am currently reading the string?

Yes, add it to the buffer.

So you can see there some common questions:

What is the character?
What am I doing at the moment?

So you need to have a simple state variable that remembers if you're reading the string or not, and something to say where in the buffer you are so you know where in the buffer to add any incoming characters.

boolean readingString = false;

A simple true/false will suffice to depict if we're reading the string or not.  Start off not reading the string.

char buffer[80] = "";

A buffer to store the text - maximum of 80 characters (including the NULL terminating character)

int charPointer = 0;

Something to know where in the buffer are currently.

Now to read the characters:

First get the next character from the serial port:

loop() {
    if (Serial.available()) {
        int incoming = Serial.read();

Now decide what to do with it.  We have a number of possible situations, some of which can be combined into single options.  For instance, if we get a "<" while reading a string it's an error condition - but do we really care?  It could be that we lost the end of the last string and have just started a fresh one - so we can just treat it as the start of a string regardless of what state we're in.  Let's use a switch for this since it's nice and tidy:

        switch (incoming) {
            case '<':
                readingString = true; // Start reading string
                charPointer = 0; // Set the buffer pointer to the start
                buffer[0] = 0; // Make the string empty
                break;

            case '>':
                if (readingString) {
                    processBufferData(); // Do something with the buffer
                }
                readingString = false; // Finish reading
                break;

            default: // Anything that's not > or <
                // If we are reading the string and the buffer isn't full
                if (readingString && charPointer < 78) {
                    // Add the character to the buffer and increment the pointer
                    buffer[charPointer++] = incoming;
                    buffer[charPointer] = 0; // Don't forget to terminate the string
                }
        }
    }
}

So the reception of a < starts the string reading, the reception of a > stops it and triggers the processing of the string, and anything else (while we are reading the string) gets added to the buffer.


What if I detach AVR micro controller from the Arduino Board after uploading program?

The AVR µC got a flash memory that can store the code loaded in. That mean you can load the code with the arduino board, detach the avr and put it on another circuit. If the µC is powered well, it will behave just like the arduino.

Don't forget to set the /reset pin to high, if you do, the µC will be stuck to the 1st line of code ;)


I see two immediate problems:

The macros A0-A5 are the numbers 14 to 19, not the numbers 0 to 5 - so you're looking at (1 << 14) for CH1 not (1 << 0).
The analog pins are port C not port B, so you need to use PINC not PINB.
Your ch?Time variables should be volatile.


From the documentation:

Serial.print(round(Hz*60), 0);


Generally, we specify DC power supplies as constant voltage sources.  In order to do this, power supplies deliver more or less current as demanded by the load in an attempt to keep the voltage constant regardless of the load.

When a constant voltage DC power supply specifies a maximum current, it is saying the power supply can only maintain the specified voltage while the current demand is less than the specified maximum current.

To be clear, unless you need a constant current power supply, a power supply should be picked based on the required constant voltage.  And the capacity of that power supply, usually measured in Amps, should exceed the maximum combined current demand of all connected devices (loads).


Is it possible to increase the voltage on 3.3v output to 5v on an ESP board to power a DC motor?

You should not power a motor from a micro-controller, period, regardless if that is an ATmega or an ESP32.

Instead, you need to use a motor driver circuit - this isn't really so much about voltage amplification, as it is about current amplification. The actual I/O output voltage of your ESP32 is likely very close to 3.3v. If you are measuring 1.8v, that is only because you motor is loading the pin so heavily (and improperly) that the voltage sags.

Without the specs of your motor, it's not really possible to provide any specific advice. But you should seek an FET-based solution, not one based on bipolar transistors.  The old bipolar L293D, L298, etc parts are horribly lossy and extremely unsuited to low voltages motors. In some low-voltage, low-current cases, the FET-based TB6612FNG can be a good solution - but again, this depends entirely on the unstated requirements of your motor. Typically only very lightweight or weak "RC cars" could use such drive, for more serious ones you should look at hobby-grade Electronic Speed Controller (ESC) modules, or their equivalent circuitry.

These motor driver chips will have two supply inputs. One supplies the logic and would typically share the microcontroller's supply voltage. The other supplies the motors - it might in light duty cases be whatever is supply the microcontroller's regulator, but in more power-hungry cases would often be a unique supply. Both grounds should be connected together and connected to the microcontroller's ground, but in such a way that the ground current for the motors flows directly from the power supply, and never through the microcontroller board.


You need to re-think your layout, and your usage of the .h file.

You should never have code in a .h file unless it is either inline or part of a template class.

A .h file should only contain hints about where other things are. Those things should then be in .cpp or .ino files.
For example your IPmonitoring class would be declared in a .h file, and defined (or implemented) in a .cpp file (or .ino file if you prefer). Any place you want to use that class you #include the .h file. In one place you may choose to create an instance of that class. It is that instance that you then reference with extern.
In the Arduino world it is common to create a single instance of the class in the class's .cpp file and extern it in the .h file so everywhere that you include the .h file instantly has access to that single instance of the object.
This is how most libraries are written.
For example:
// IPMonitoring.h

class IPMonitoring {
    public:
        void doStuff();
};

extern IPMonitoring ipMon;

And:
// IPMonitoring.cpp

#include <IPMonitoring.h>

IPMonitoring ipMon;

void IPMonitoring::doStuff() {
    // Do something
}

And finally:
// mySketch.ino

#include <IPMonitoring.h>

void setup() {
    ipMon.doSomething();
}

void loop() {
}


You can use FreeRTOS on the AVR family:

http://www.freertos.org/a00098.html


Attiny85 SoftwareSerial not working on battery power

Unless you connect the ground of your ATTiny to the ground of your USB UART interface there is no circuit for the electrons to flow around.

It works when powered from the computer because everything shared the same ground connection.


I used lightweighted KissFFT (Mark Borgerding) at Arduino Mega and seems it is pure C code so should be running anywhere.


6 wire 3 digits 7 segment display and arduino question

What you have is a Charlie-Plexed display like the one in the picture below.  You need one more wire than this example because your display also includes the decimal point.  If you go through the electrical paths where for each pair one line is driven high, the other is driven low and all other lines are set to input, only one LED at a time will be forward biased.


This is (unfortunately) not an Arduino question. It is actually about the syntax of C++ which is a rather complex language.

The mechanism you have discovered is called default arguments. The function prototype or definition may contain the default values of the arguments. As this is a list the default values are restricted from right to left. It is not possible to use a default parameter for argument to the left of a given argument. The order is strictly right to left.

f(int x = 0, int y = 1, int z = 2)

f(1,2,3) binds x = 1, y = 2, z = 3
f(1,2) equals f(1,2,2) binds x = 1, y = 2, z = 2
f(1) equals f(1,1,2) binds x = 1, y = 1, z = 2
f() equals f(0,1,2) binds x = 0, y = 1, z = 2

There is a syntax for struct initialization (aka aggregate initialization) in C++ that allows naming of struct field values. This type of naming is not allowed for function calls.

Please read https://en.cppreference.com/w/cpp/language/default_arguments, https://en.cppreference.com/w/cpp/language/aggregate_initialization and https://en.cppreference.com/w/cpp/utility/functional/bind for more details. And a good C++ book.

There are languages that allow default arguments and named parameters e.g. C#, Python, Ruby and Smalltalk. Please see https://en.wikipedia.org/wiki/Named_parameter.

Cheers!

(Update)

Below is a rewrite of @VE7JRO Add function class using cast operator to perform the evaluation:

class Add
{
public:
  Add(int x, int y) : m_x(x), m_y(y) {}
  operator int() { return m_x + m_y; }
  void x(int x) { m_x = x; }
  void y(int y) { m_y = y; }
  int print(Print& outp) {
    int res;
    res = outp.print(F("Add(x="));
    res += outp.print(m_x);
    res += outp.print(F(",y="));
    res += outp.print(m_y);
    res += outp.print(F(")"));
    return res;
  }
private:
  int m_x, m_y;
};

Add func(1,2);

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

  func.print(Serial);
  Serial.print(F("="));
  Serial.println(func);

  func.x(12);
  func.print(Serial);
  Serial.print(F("="));
  Serial.println(func);

  func.y(13);
  func.print(Serial);
  Serial.print(F("="));
  Serial.println(func);
}

void loop() {
}


Why my serial message won't show on another when I try use 2 Arduino communication

I haven't tested this in a while but it has been my experience that even though you can have multiple IDE windows open, you can only have one Serial Monitor at a time. The way I got around this is to use a Terminal Emulator program for the second Arduino.


Unless properly filtered, an LDR has a spectral sensitivity very
different from the human eye, which makes it unsuitable for any kind of
photometric measurement. It is also typically very loosely specified,
so you won't know the illuminance it receives better than a factor two
even if you measure its resistance very accurately. Thus, if you really
need accurate illuminance measurements like, e.g., for complying with
legal requirements, then forget the LDR and get a real luxmeter with a
calibration traceable to the SI lux standard.

Now, if you only want to tell apart substantially different illuminance
levels, like sunny and cloudy, then the LDR is fine. And don't let
Majenko scare you into believing you really need to know the resistance
of your pullup: it doesn't really matter.

That being said, you will get the best sensitivity if your pullup has a
resistance in the same range as the resistance of the LDR in the typical
conditions you will use it. Thus, if your LDR is nominally 10 kΩ, I
would avoid pulling up with 220 Ω, as the sensitivity would be very
poor. A 10 kΩ pullup resistor would be ideal, but the internal
pullup of the I/O pin (20 – 50 kΩ, 30 kΩ typical) should
be fine.

Many tutorials on LDRs use the ADC reading to compute a resistance, for
which you need to know the resistance of the pullup. If you want to
follow this path, just assume a 30 kΩ pullup. All your numbers will
be somewhat off, but that makes absolutely no difference, because you
don't know how to relate the resistance to the illuminance anyway.

I would suggest you forget about computing the resistance. Just look at
the raw ADC readings instead. Take some test readings in the typical
conditions that are of interest to you: now you have a baseline to which
you can compare further readings against. Keep in mind, though, that the
ADC readings get lower as the illuminance gets higher. And beware
that the resistance of the pullup, and probably that of the LDR also,
can be sensitive to temperature variations. You may do a hairdryer test
to check whether it gets really bad.

Example code? This one is pretty trivial:

/* Connect an LDR between A0 and GND. */

void setup() {
    pinMode(A0, INPUT_PULLUP);  // enable pullup for the LDR
    Serial.begin(9600);
}

void loop() {
    Serial.println(analogRead(A0));  // print out a reading
    delay(1000);                     // delay for one second
}


MAX232 chip fails to initialize properly with arduino

Datasheet for MAX232

  Section 7.3 Recommended Operating Conditions VCC Supply voltage

  MIN=4.5, NOM=5, MAX=5.5 (V)

The MAX232 has a minimum supply voltage of 4.5V, typically expecting 5V.

There are other alternatives, such as the MAX3232, which supports either 3.3V or 5V supply voltage.


Since you seem interested about RAM, rather than flash usage, I suggest
you look at the symbol table of your compiled program, which will be
more telling than the disassembly. On my Linux system, I usually do the
following:

avr-nm -Crtd --size-sort the_program.elf | grep -i ' [dbv] '

avr-nm is the utility for displaying the symbol table. It is normally
packaged with the Arduino IDE. It is invoked here with the following
options:

--size-sort is quite explicit
-C means “demangle the C++ names”
-r means “reverse sort”, i.e. sort from largest to smallest
-td means “display numbers in decimal rather than hexadecimal”

This will output the list of all symbols that have a size, in three
columns: size, type and name. You are only interested in the symbols
that consume RAM, i.e. those of type b (BSS, or uninitialized data),
d (initialized data) and v (vtable), either in upper or lower case.
The grep command is a standard Unix utility which is used here to
extract only the relevant lines from the output of avr-nm.

Example output for a small program:

00000068 B tx_buffer
00000068 B rx_buffer
00000034 B Serial
00000016 V vtable for HardwareSerial
00000004 B timer0_overflow_count
00000004 B timer0_millis
00000002 b loop::last_print
00000001 b timer0_fract

The first 4 entries come from the Serial object. The 3 entries
starting with timer0_ are used by the Arduino timekeeping functions
(millis(), micros() and delay()). The entry named
loop::last_print is a static local variable I declared in loop().


You can force the RadioHead library to use Timer 2 instead. This can be done by enabling the define RH_ASK_ARDUINO_USE_TIMER2 near the top of RH_ASK.cpp.

More details about how to do this may be found in the RadioHead library documentation. Please see https://www.airspayce.com/mikem/arduino/RadioHead/classRH__ASK.html.

Cheers!


Embedded systems typically use UART for logging, and Arduino is no exception. Logging to UART is as easy as calling Serial.begin() in the setup() and Serial.println() in the loop(), it works on all Arduinos, doesn't require any additional hardware and consumes much less resources than the SD card or networking library. Of course, you're limited in bandwidth (115200 kbit/s, sometimes more), so you won't be able to log in the fast-running cycles.

If you don't like the Serial Monitor feature of Arduino IDE, you can install one of the many terminal programs which will happily write the data from serial port to a log file. Some of these tools also have nice analysis features, including plotting of logged signals, formatting, data conversions etc.

If you're good with command line, creating a log file is as simple as

cat /dev/ttyUSB0 > log.txt

in Linux or

type COM1 > log.txt

in Windows.


I have 4 motors connected to their own ESC (that is connected to a power distribution board), how do I connect this to Arduino uno? (Drone)

Here are just some clarifications for you:

Signal pins don't have to be connected to PWM pins. AFAIK, any digital pins should work.
All grounds togheter! Glad you got that right!
Connect VCC of ESCs directly to the power supply.
Connect power supply to VIn of Arduino (not 5V because you are going to grill it!)

Uptdate

Yes, you can probably solder all the VCC wire of the ESCs togheter.
By power supply, I meant connecting it directly to the battery.

To power the Uno, connect the battery+ to the VIn pin of the UNO.


Can I have help interperting this code? char variable somehow storing big numbers

It's passed as a char*. This can be derived from either a string literal (e.g. "212555121") or from a String via its c_str() method.


Button that gives an Input, Has a small delay --- then gives another

A standard way to do this is to connect a digital i/o pin via a (normally open) push button to ground. Internally in the Arduino a pullup resistor can be activated to keep the pin on a high level when de button is open. For example when pin #8 is used: pinMode(8, INPUT_PULLUP). The program watches the state of the pin to detect whether the button has been pushed. An extensive tutorial about using switches for input to microcomputers you can find here: http://www.gammon.com.au/forum/?id=11955

Be sure to familiarize yourself with a phenomenon called "contact bouncing": when the button is pressed or released the contacts don't open or close immediately but go through a series of rapid open/close/open/etc. states. The best information I know about how to handle this you can find here: http://www.ganssle.com/debouncing.htm


Recording and storing Midi data with arduino and midi shield

The Arduino MIDI Library allows you to read and write MIDI messages, but only in real time.

Storing MIDI data makes sense only with timestamps, so you have to call millis() or micros() when you receive a message.

How to actually store the data is something that you have to design yourself; which data structure to use depends on what you want to do with the data later.


How can I adapt the DallasTemperature library to accept another 1-Wire class?

The typical way to achieve what you want would normally be to create your own subclass of OneWire class and override the methods you need to change, then pass a pointer to an instance of your class to the DallasTemperature constructor.

However, for this to work, the OneWire class must have been developed with extensibility (subclassing) in mind, i.e. use virtual methods that you can override.

Unfortunately, a quick look at OneWire.h shows that no method is virtual in there.

So that means in the end you will have to perform some hacks, just as you do now.

What you could potentially do (that's still a hack, but maybe a bit less dirty) is:

replace OneWire.h to make all methods virtual (at least those you need to override)
keep the original OneWire.cpp that should still compile with the newly adapted header file
create a new MyOneWire.h / MyOneWire.cpp to define your own OneWire subclass that overrides all necessary methods as you want

Then you can pass either a OneWire or a MyOneWire instance to DallasTemperature constructor.

NB: when I see my answer, this makes me think your question is more a general C++ question than an Arduino-related one.


How to clear of contents of string in Arduino?

In C and C++ a null terminated array of characters is a string (although not a String). Many routines for reading input terminate the result with a null as does an assignment like"

char foo[] = "This is a string.";

All you would need to do to "clear" this string is to assign a null to the first character. For example:

foo[0] = '\0';


What do these pins mean? Where should I plug them in?

This is called the SPI interface (See Serial Peripheral Interface, Wikipedia. The pin names typically used for SPI are:

GND : Power Ground
VCC : Power input
CS : Chipselect
SCK/SCLK (SD-Clock): SPI Clock
MOSI (SD-DI, DI) : SPI Master out Slave in
MISO (SD-DO, DO) : SPI Master in Slave out
CD: Card Detect (see comment of rollinger below (thanks).

On an Arduino Uno the SPI pins are:

CS – digital 10; this can be in principle any pin
SCK – digital 13
MOSI – digital 11
MISO – digital 12


firstly, the radio.write command is used for checking for the acknowledgement from the RX after the FIFOs are full for a single write. But radio.writefast will not wait for the acknowledgement from the RX and would continuously transmit the payload for a single write. Similarly for radio.startwrite and
radio.startwritefast commands.

Coming to the keeping the NRF in listening mode, even I haven't tried it before so I cannot suggest an exact solution for this problem. But as far as I know,  you can go for writestart command to keep the reading pipes open while you are sending. But I would personally suggest you to confirm this from datasheet again before experimenting.

For ACK payload, it depends upon the master unit controlling the SPI communication with the NRF chip and thus, by maintaining a mutual understanding between the RX and TX units, you can define the payload for acknowledgement signal as well.

Coming to best speed possibility, To increase speed, NRF has three speeds from which you can select the highest value available. Also see which pipe/channel works the best for you so that you can achieve the least number of lost packets.


Is it possible to run 2 functions, that communicate with 2 different serial devices, in parallel using FreeRtos library?

It is unlikely that FreeRTOS will allow you to do that. SoftwareSerial uses busy loops with interrupts disabled, which means it cannot be interrupted or preempted by the RTOS (or by anything for that matter).

If you want two serial connections in parallel, at least one of them should be done in hardware.


I think your Arduino got short or the transmitter-receiver in it is damaged so the device manager cannot recognize the COM port.It once happened with my Arduino Uno. Try changing the USB cable.If it does not help your Arduino is damaged.


Yes, it is possible. That is already supported by the IR library. Please see this tutorial for further details. The outline of the sender is:

 uint16_t sample = analogRead(A0);
 irsend.sendSony(sample, 16);

And the receiver:

 if (irrecv.decode(&decodedSignal)) {
    uint16_t sample = decodedSignal.value;
    ...
 }

Cheers!


Convert Hex to Decimal from signed 2's complement

For example – ff9d denotes a value of -99

The function you wrote returns an unsigned integer which, being
unsigned, cannot be negative. The simple fix is to declare it as
int hexToDec(String hexString)

That should be enough to get it working as expected. Note that the local
variable decValue still has to be unsigned, otherwise you would get a
signed overflow, which is undefined behavoir (i.e. “forbidden”) in
C++. Returning an unsigned number from a function that is supposed to
return a signed number is perfectly fine: you get an implicit conversion
which is guaranteed to do the right thing.
Now, if I may provide some more feedback about this function:

Use, if you can, plain C strings (char *) instead of String
objects, as the latter are not very friendly to your Arduino's memory.
Use fixed-length integers (uint16_t if your protocol dictates 16-bit
integers) instead of the generic int, otherwise your code will fail
if you move to a 32-bit platform, such as an ARM-powered Arduino.
Use character literals ('0' instead of 48) instead of hard-coding
ASCII code points, as that makes the code more readable.
Use a simple subtraction (nextInt - '0') instead of the quite
expensive map() function.

Here is my take at it. Note that it has a “classic C” accent you do not
need to replicate. You may prefer using indices to crawl the string.
int16_t hex2int(const char *hex)
{
    uint16_t value;  // unsigned to avoid signed overflow
    for (value = 0; *hex; hex++) {
        value <<= 4;
        if (*hex >= '0' && *hex <= '9')
            value |= *hex - '0';
        else if (*hex >= 'A' && *hex <= 'F')
            value |= *hex - 'A' + 10;
        else if (*hex >= 'a' && *hex <= 'f')
            value |= *hex - 'a' + 10;
        else
            break;  // stop at first non-hex digit
    }
    return value;
}

Example usage:
Serial.println(hex2int("ff9d"));  // prints "-99"

Edit: As revealed by the comments, the whole question is an XY
problem. You are asking help about your misguided solution rather
than your actual problem. The data you have is not hex: it's binary.
You have a 16-bit signed integer stored in a byte array, most
significant byte first. You figured out you can convert that to an
integer by converting it first to a string representation as
hexadecimal, then converting that representation back to a binary
number. Of course you can do that, but it's an overly complicated and
expensive way of doing something trivial.
The canonical way to recover an integer from a byte array is by
assembling the bytes together using bitwise logic and bit shifts. In
this case:
int16_t reactive_power = (uint16_t) data[dataSize - 5] << 8
                       | data[dataSize - 4];


Run motor for a set amount of depending of Pressure Sensor

Fairly easy.

You have to determine if the pressure has changed from its previous reading.

If it has, you can start to turn the motor for two seconds.

Once the time is up, turn the motor off.

Once you put your code in that framework, it would be much easier to code top down.


How to supply more than 500mA while powered by USB

Do not bypass the fuse. Drive your external components directly from the external 5V power supply. Do not pass everything through the Arduino.

You say you have a regulated 5V power supply. Assuming it provides enough current you should use it to drive your external components directly.

You might need to add a filter capacitor near the feed for the Pi/Arduino, to filter out fluctuations in the 5V supply as your high current components switch on and off. You should be able to google "Power supply filter capacitor" to learn more.


Will an ATmega2560 board be faster than a Uno for hard real-time data logging?

No, it will not be any faster. The extra instructions are to access the extra flash memory of the 2560. Instructions like EIJMP - Extended indirect jump, EICALL - Extended indirect call, etc.

The compiler option -O3 optimises the most, but there are other options you can enable, such as -funroll-loops which will cause major code bloat but speed things up.  Read the GCC manual pages to boggle at all the millions of optimisation options.

Or... use a faster chip, like an ARM or PIC32.


How do you convert a formatted print statement into a string variable?

To achieve what you want you probably want to use the "string format time" function strftime (docs). You would write the result in a character buffer, which you can also print directly without having to convert it to String object.

So, the following code should work:

void printLocalTime()
{
  time_t rawtime;
  struct tm timeinfo;
  if(!getLocalTime(&timeinfo))
  {
    Serial.println("Failed to obtain time");
   return;
  }
  char timeStringBuff[50]; //50 chars should be enough
  strftime(timeStringBuff, sizeof(timeStringBuff), "%A, %B %d %Y %H:%M:%S", &timeinfo);
  //print like "const char*"
  Serial.println(timeStringBuff);

  //Optional: Construct String object
  String asString(timeStringBuff);
}

The overload for Serial.print also does this exact same thing:

size_t Print::print(struct tm * timeinfo, const char * format)
{
    const char * f = format;
    if(!f){
        f = "%c";
    }
    char buf[64];
    size_t written = strftime(buf, 64, f, timeinfo);
    print(buf);
    return written;
}


How to make the motor move after a certain period of time?

You will need to add a logic level mosfet of the appropriate size and specs to control the power to the motor.  You can drive the gate of the mosfet from a pin through a current limiting resistor with a larger bleed resistor.  For a brushed motor you'll need a ceramic RF supressor cap plus flyback diode for back EMF protection:

simulate this circuit – Schematic created using CircuitLab

For greater RF supression (if your motor is pretty beefy) you can use a 0.1uF between each input lead and the motor case.

When you turn the pin on, motor turns on, low turns off.  Using analog and appropriate R values you can control motor speed (setting 0-255):

int motorControl = [your pin];

void setup()
{
  pinMode(motorControl, OUTPUT);
}

void loop()
{
  delay(10000); // delay 10 seconds plus board boot time
  analogWrite(motorControl, 255); // turn motor on full
}

You can time the delay with a stop watch and adjust to be exactly 10s by dropping the delay() call to compensate for the boot up time of the board.

More about MOSFETS here:

https://electronics.stackexchange.com/questions/81935/mosfet-usage-and-p-vs-n-channel


Documentation on the controller you are using is pretty scant, but it looks like you just need to make a GET request to the URI corresponding to the action you need to take.

  http://192.168.1.4/30000/00 : Relay-01 OFF

  http://192.168.1.4/30000/01 : Relay-01 ON

  http://192.168.1.4/30000/02 : Relay-02 OFF

  http://192.168.1.4/30000/03 : Relay-02 ON

  http://192.168.1.4/30000/04 : Relay-03 OFF

  http://192.168.1.4/30000/05 : Relay-03 ON

  …

  http://192.168.1.4/30000/14 : Relay-8 OFF

  http://192.168.1.4/30000/15 : Relay-8 ON

  http://192.168.1.4/30000/41 : Enter

  http://192.168.1.4/30000/40 : Exit

  http://192.168.1.4/30000/42 : Next Page

  http://192.168.1.4/30000/43 : Next Page

For example If I wanted to turn off relay 3, I would simple make a GET request to http://192.168.1.4/30000/04 and close the connection. Example code:

IPAddress server(192,168,1,4);
EthernetClient client;
client.connect(server, 80);
client.println("GET /30000/04 HTTP/1.1");
client.println("Connection: close");
client.println();
client.stop();


Why can't I use 3V output of arduino pro mini?

NEVER drive a motor directly from an Arduino IO pin.  You will kill the Arduino.

It's not a question of voltage, it's a question of current, and that is where the transistor comes in.  If you have a 3.3V Arduino (as it sounds like you have) then you may be able to drive the motor using the 3.3V output of the Arduino (VCC pin? Not sure with that model) and a transistor. That is the simplest arrangement.

simulate this circuit – Schematic created using CircuitLab


It depends on the core, but most provide the macro NUM_DIGITAL_PINS which tells you the number of digital pins the board has.  In general this doesn't equate to the actual number, but to one more than the highest number (there are boards with gaps in the pin number sequence).

So you can use:

if (pinNumber < NUM_DIGITAL_PINS) {
    digitalWrite(pinNumber, HIGH);
} else {
    Serial.println("Invalid pin number");
}

In tandem with that you also usually have NUM_ANALOG_INPUTS.


Serial.read() returns -1 if no data is available. It doesn't wait for the byte. Test for -1 or use Serial.available() as any example does.

Replace Serial.print(data) with Serial.write(data) to get the data echoed back unchanged.


Try this...
Go to your Arduino IDE.
Under the Tools tab, go to "Board" and select Arduino Leonardo.
Then in the Tools tab, go to Port and check to see if a port is selected.
Use this link to try and find which Serial Port you should have: https://www.arduino.cc/en/Guide/MacOSX
Try plugging in the cable in different USB ports on your computer and see if the port number changes automatically.

Also, could you please say what peripherals or other things are connected to the arduino? Because for example, I know what using a Bluetooth slave with the Arduino while connected with the cable to your computer, doesn't let you upload your program. There could be similar problems to this.


Manually added boards doesn't work in 1.8.5…?

Newer versions of the IDE (after 1.5) have a different folder structure where there is additional subfolders for maintainer and architecture.

<Arduino sketch folder>/hardware/<custom name>/avr/boards.txt

https://github.com/arduino/Arduino/wiki/Arduino-IDE-1.5-3rd-party-Hardware-specification


Return mean of observations for a given sample time

I have this:

int readElSens() {
  long sum = 0;
  int n = 0;
  long start_time = millis();
  while(millis() - start_time < 400) {
    sum += analogRead(ELSENS_PIN);
    n++;
  }
  return sum / n;
}


You could try the intel galileo or the intel edison with arduino shield. They can be programmed with a variant of the arduino ide, but it is possible to call also programs from the native linux os. Or you could have a look at the esp826.
At least on the edison it is possible to run node.js, while the esp supports lua.


Mode: AP

In access point mode. Can also be STA or STA+AP for Station or dual role modes.

  PHY mode:N

Physical interface mode. At the moment it's in 802.11n mode. Depends on the AP you are connecting to if any.

  Channel: 1

Which WiFi channel you are communicating on

All the following are meaningless in AP mode. They only pertain to STA mode:

  AP id: 0

Internal ID of the access point you are connecting to, if any.

  Status: 255

Connection status

  Auto connect: 1

Automatically connect to an access point.

  SSID (0):

Name of the access point currently connected to.

  Passphrase (0):

Password used to connect to the current access point

  BSSID set: 0

BSSID (kind of like the MAC address) of the access point connected to.

As you can see, much of it is meaningless for access point mode, since it mostly is to do with connecting the ESP8266 to an existing network.  In AP mode there's not a lot of debugging information you can get - "is it running?" is really all there is.


You have a timer conflict.

tone() uses a timer, and analogWrite() on certain pins uses the same timer.

Quite why you're using analogWrite() though, with HIGH (which equates to 1) as the duty cycle I don't quite understand. I would have though digitalWrite() would be a better choice. A duty cycle of 1 would be pretty much invisible anyway...


Is it possible to split project into several folders?

I will try to give an answer as it is not easy to understand what you mean.

Probably it is also better if you know how the Arduino IDE works, before try to make complex projects.

Short answer:
Yes, it is possible

Normally, you have an ino-file, some other files and many libraries. If you want create something for your project, you can just create a folder inside the library folder.

But this is not what you want right?

You can create many folders inside your project and include any header inside your folders just with
#include "subfolder/yourfile.h"

The files will not be opened with your Arduino IDE.

You can also create your "mini library", so the compiler will compile it with your project. This library need to be in a subfolder called src. At this point it will be converted and compiled for your project.

Simple working example:
testsub.ino

#include "src/test.h"
Test *test = new Test();
void setup(){
  Serial.print(test->number());
}
void loop(){
}

Create a subfolder src and place your files:
test.h

class Test
{
public:
  Test();
  int number();
};

and
test.cpp

#include "test.h"
Test::Test() {
}
int Test::number() {
  return 95;
}

If you want another "library", you can create another subfolder called src.


Hardware serial not working, SoftwareSerial is

There may be several reasons

Be sure uC pin connect pin header
In setup part, you write Serial.begin(xxxx);
After serial begin, don't change this pins IO features(Input, output)

Please check that after if not solve, please share code


Do ultrasonic sensors sense through transparent materials?

I'm assuming you mean a "normal" sensor, like this:

Ultrasonic sensors work by sending out sound waves. Obviously, sound waves don't care whether a material is transparent or opaque, so they are blocked just as easily by acrylic as by a brick wall.

Side note: If you look on the front of an ultrasonic sensor, you will notice that it is covered by a screen, not glass or plastic. This is why.


I just fried my Arduino on a breadboard. Can I still use the breadboard?

you can test the breadboard if you have a multimeter. Even if you don't, you can place an LED, a resistor and a power source across the suspect portions of the breadboard. If you locate a trace or two that appear unreliable, you should be able to mark them appropriately and continue to use the board.


Decreasing Arduino pro micro power consumption

Bringing Down power consumption by taking the LED out and lowering the
  clock ?

Yes, you can do that! And you are okay with Arduino unless you want to complicate things more...If you want to check out other methods then you can check out the Microcontrollers Schematics and also the datasheets of their Components...


How to expand program memory on an arduino?

An ATmega2560 is the chip to add for more memory when you run out of program memory on an Uno.  Referring to the Memory webpage at arduino.cc, you'll see that it has Flash=256KB, SRAM=8KB, EEPROM=4KB, where the ATmega328 chip on the Uno has Flash=32KB, SRAM=2KB, EEPROM=1KB.

When you run out of program memory on an Uno, you have about three choices that are practical:  make the program smaller; remove the bootloader (to free up one or two KB); use a different board with a more-capable processor.  The CPU on an Uno board doesn't have a way to access program bytes from places other than the on-chip 32KB flash.  The CPU on a Mega2560 board starts out with 8 times as much flash, so it can hold bigger programs than an Uno can.

If you remove the bootloader, you could instead program using a USBASP board, as described in a
“Program AVR chip using a USBASP with 10 pin cable” article at learningaboutelectronics.com.


This problem is usual if you are in shortage of RAM.
Adafruit's libraries wastes lots of memory. You should be very careful to run their stuff if you are in shortage of memory.

I suggest you to try another library which quite old, but uses much lesser memory to read DHT sensor’s data:
https://github.com/markruys/arduino-DHT


Why is there a need to ground a circuit?

Electric circuits need to be closed. The hydraulic analogy might help you in this sense: suppose you have a garden fountain and want to recycle its water;  if you want water to circulate by means of a pump, you need a way to put the water back in the pump. That's what the ground connection is for.

Sometimes you have closed circuits using other wires, and a ground connection (or a shorter, direct ground connection) might be required to keep at bay the effect of EMI (electro-magnetic interference).
For example, this is the output of an Arduino Nano sensed by connecting only the tip of the oscillocope probe to pin 13.

And this is the same output when I connected the ground tip to Arduino's GND (actually to the USB frame):


Nano + ESP8266 control pins with REST API

You can use Firmata to control the Arduino pins, just having the ESP8266 publish a web page exposing the Firmata operations you desire to expose and sending the user actions to the Arduino via serial using the Firmata protocol.

To make your life easier you can consider your ESP8266 an equivalent of your serial console: everything you write from the ESP82667 becomes input data on the console for your Arduino and the other way around.

In Firmata, each command can be read from a generic Stream, with Serial being the default implementation.


How to serial connect arduino galileo to alarm system

First of all, you'll need to make sure this is UART and not another protocol. Don't worry, if it's not UART the worst thing that could happen is jumbled data.

After that, you will need a 12v to 5v (or 3.3v) logic level shifter. When you have that you'll need to connect the Arduino to the system through the level shifter to pins 0/1.

You won't know what you'll receive or can send without looking at the serial output and doing a little tinkering. You don't even know what the serial port does. It could just be for setting up the system.


How do I call functions sequentially without using the Delay function?

I'm assuming you want to run each colorWipe for 200 ms, one after another.

You need a state machine to timing each colorWipe, like this:

void loop()
{
    static int state = 0;
    static unsigned long previousMillis = 0;
    unsigned long currentMillis = millis();

    if(currentMillis - previousMillis >= 200) {
        previousMillis = currentMillis;

        switch(state) {
        case 0 :
            colorWipe(strip.Color(255, 0, 0), 50); // Red
            state++;
            break;

        case 1 :
            colorWipe(strip.Color(0, 255, 0), 50); // Green
            state++;
            break;

        case 2 :
            colorWipe(strip.Color(0, 0, 255), 50); // Blue
            state++;
            break;

        case 3 :
            colorWipe(strip.Color(0, 0, 0, 255), 50); // White RGBW
            Serial.println("Done");
            state = 0;
        }
    }
}

void colorWipe(uint32_t c, uint8_t wait)
{
    for(uint16_t i=0; i<strip.numPixels(); i++) {
        strip.setPixelColor(i, c);
        strip.show();
        //delay(wait);
        Serial.println("Light");
    }
}

In each loop you will be waiting 200 ms before doing anything. When the times comes, you will enter the if with state==0 and you will execute the first 'colorWipe'. After that, you advance the state by adding 1 to state variable.

Then you will be entering loop and doing nothing for another 200 ms. When that time pass, you will enter the ìf with state==1. Now the second colorWipe will be executed.

When the last colorWipe is executed, you set state to zero and begin again.


The ATtiny85 is an 8-pin AVR device with 3 PWM channels available in DIL and SO packages. The Arduino core can be downloaded from arduino-tiny. It can be programmed via ISP using either ArduinoISP or a dedicated programmer.


4-20 milliamp to volts to pressure maths

If I understand your question correctly, when the sensor is on,

4 mA (1 V on the Arduino) means 0 bar
20 mA (5 V on the Arduino) means 100 bar.

Is that correct?

If that is correct, there you just have to linearly map the voltage
range to the pressure range. The equation is

P = (v − 1 V) / 4 V × 100 bar

or, in C++:

float v = analogRead(A0) / 1024.0 * 5.0;  // in volts
float p = (v - 1) / 4 * 100;              // in bars


How do I print the reading serial data sending from Arduino

You have no warranty that Qt will receive the whole message in a single
chunk. It may receive "no se" as the first chunk, and then "q pasa" as
the second chunk. Since dataBuffer is dynamically allocated, it
initially contains garbage, and you are printing the part of this
garbage that you did not overwrite.

An easy fix would be to simply NULL-terminate the buffer:

dataBuffer = new char[size + 1];            // + 1 byte for '\0'
c = m_serialPort->read(dataBuffer, size);
dataBuffer[c] = '\0';                       // terminate the string


Arduino not connecting, but running the code I wrote last

Well you are very unclear about what exactly happened.  I find the statement "somehow power jumped" to be very questionable.  Almost certainly you accidentally touched something with your "probe" and shorted a higher-voltage signal, like your 12V power, to something that cannot tolerate that voltage.
There are many things on the board that fit this from the USB interface chip to the AVR chip itself.  Chances are quite good that you destroyed an input at least.
If you have an Arduino Uno with a socketed AVR chip, you can get a replacement with the bootloader pre-programmed.  Search your favorite search engine for one of these.
Otherwise it's time to buy a new one.  Sorry!


Issues in interfacing relay with Arduino

what i would do is test the parts one by one.
so first look if you're signal is good by attaching a led to it.
then test you're relay with 5v.

now you should know what the problem is the arduino or the relay


There is a fairly inexpensive solution, but it's not Arduino based.

All you need is:

the Google Cardboard sdk
a fairly modern and powerful Android phone (I have a OnePlusOne and it works well with Cardboard apps) - assuming you already own something similar, this is where the big saving happens :-)
a compatible head unit: there are many available on ebay (on some you might have to drill a hole where the camera of the phone is located.) price got from about $5 to $25
some high level programming skills to write your augmented reality application, but there's no way around it :-) - you might even find some demo on the net.

Here the basic of the solution I'm proposing is to take the video stream from the front camera on the phone, use the CardBoard API to create a view for each eye (yes, you will loose stereoscopy, since each eye will see the same image from the camera) and overlay it with whatever info you would like to show. The simpler case could be a compass, where you show N-W-S-E at the top of the field of view. Or you could even add a map, like in a FPS :-)

The part where the arduino might come useful is if you want to create some (bluetooth, for example) sensor and/or controller (using the usb port from the phone requires both a phone with HW that supports host mode and a rooted device).


What does (byte*)variable_name mean in C++?

It means "Interpret this pointer as a pointer to byte data".  It's called "Casting" and allows you to fool the compiler into thinking that one type of data is another.

For example, your function expects a byte * (a pointer to byte data), and if you have char * as your variable you can change it on the fly to byte * by casting it like that.


WiFi.begin() in ESP8266WiFi library doesn't wait until the connection completes, it returns immediately.

You can check if the connection to WiFi network is established using WiFi.status() as most of the examples show. And it is not mandatory to wait for the connection in setup().

BTW: You can use a separate sketch to set the SSID and password in esp8266 and then in all other sketches not use WiFi.begin(), only wait for the connection to WiFi network to finish.


I keep getting this error exit status 1 expected ';' before 'DigiKeyboard'

You forgot the semi colon after

DigiKeyboard.print("Camera")

It should be:

DigiKeyboard.print("Camera");


There's an error I don't know how to fix

Putting all other possible issues aside such as pin and timing conflicts.

Rename the sketch setup() and loop() functions, for instance, rgb_led_setup() and rgb_led_loop(), and peizo_setup() and peizo_loop(), then rewrite:

void setup() {
  rgb_led_setup();
  peizo_setup();
}

void loop() {
  rgb_led_loop();
  peizo_loop();
}

Cheers!


Arduino code is not working for unipolar stepper motor

I have mentioned in the comments that you should read the buttons with analogRead(). But you can do it other way by simply connecting the button pin to digital inputs on arduino(any from 0-13). Analog pins are mostly used for accessing the sensor data as far as I know. I am correcting your code as below:

#include <Stepper.h>

#define STEPS_PER_MOTOR_REVOLUTION 32

#define STEPS_PER_OUTPUT_REVOLUTION 32 * 200 //2048

Stepper small_stepper(STEPS_PER_MOTOR_REVOLUTION, 9, 8);
int  Steps2Take;
int buttonApin = 4; //connect button to digital pin 4 on arduino
int buttonBpin = 5; //connect button to digital pin 5 on arduino
int dirpin = 8;
int steppin = 9;
void setup()
{
  pinMode(buttonApin, INPUT);
  pinMode(buttonApin, INPUT);
  pinMode(dirpin, OUTPUT);
  pinMode(steppin, OUTPUT);
  small_stepper.setSpeed(1900);
}
void loop()
{
  int valA = digitalRead(buttonApin);

  if (valA == HIGH)
  { digitalWrite(dirpin, HIGH);
    for (int x = 0; x < 100; x++)
    { digitalWrite(steppin, HIGH);
      delayMicroseconds(1000);
      digitalWrite(steppin, LOW);
      delayMicroseconds(1000);
    }
  }
  int valB = digitalRead(buttonBpin);

  if (valB == HIGH)
  {
    digitalWrite(dirpin, LOW);
    for (int x = 0; x < 100; x++)
    {
      digitalWrite(steppin, LOW);
      delayMicroseconds(1000);
      digitalWrite(steppin, HIGH);
      delayMicroseconds(1000);
    }
  }
}


I have to make an LED with an ultrasonic distance sensor, the idea is to make the LED blink faster when getting closer to at an specific distance

I would say the way to go is using non-blocking code with millis(). Look into the BlinkWithoutDelay example, that comes with the Arduino IDE. It doesn't use delay(), which is considered bad coding practice, since it is just busy waiting. Nothing else can happen during a delay, except for interrupts. Instead of waiting it is better to regularily check the clock, if it is time to do something (much like you would do in real life for example for baking a pizza).

The clock is provided by millis(), which returns the number of milliseconds since startup. Below you see the BlinkWithoutDelayexample. The variable interval controls the blink frequency. If you remove the const keyword before it and change it according to the measurements from the ultrasonic sensor, you will get a changing blinking frequency with changing distance.

Try to combine the codes into one. Remove all delay() calls, except for the delay(1) (it is needed to trigger the ultrasonic sensor and it is small enough to not matter greatly).

const int ledPin =  LED_BUILTIN;// the number of the LED pin

// Variables will change:
int ledState = LOW;             // ledState used to set the LED

// Generally, you should use "unsigned long" for variables that hold time
// The value will quickly become too large for an int to store
unsigned long previousMillis = 0;        // will store last time LED was updated

// constants won't change:
const long interval = 1000;           // interval at which to blink (milliseconds)

void setup() {
  // set the digital pin as output:
  pinMode(ledPin, OUTPUT);
}

void loop() {
  // here is where you'd put code that needs to be running all the time.

  // check to see if it's time to blink the LED; that is, if the difference
  // between the current time and last time you blinked the LED is bigger than
  // the interval at which you want to blink the LED.
  unsigned long currentMillis = millis();

  if (currentMillis - previousMillis >= interval) {
    // save the last time you blinked the LED
    previousMillis = currentMillis;

    // if the LED is off turn it on and vice-versa:
    if (ledState == LOW) {
      ledState = HIGH;
    } else {
      ledState = LOW;
    }

    // set the LED with the ledState of the variable:
    digitalWrite(ledPin, ledState);
  }
}

The rest is up to you. If you need more information about the BlinkWithoutDelay example, you should google it. There are tons of tutorials. This is a great coding excerise, so have fun :)


Sketch does not work without delay() or other complex functions like digitalWrite()

As majenko answered in the comments, the blinking rate will be so fast you can not see it.
Also it is possible that without the delay the optimizer removes the whole counting. So increasing the number as proposed by majenko may not even work due to compiler optimisations.
Using a method based on counters is a very unreliable way to use timings.

Look at the blinkwithout delay example as proposed by Dirk.
It boils down to using millis() for timing. millis tells you how many millis the arduino is running.

void loop() {
  // here is where you'd put code that needs to be running all the time.

  // check to see if it's time to blink the LED; that is, if the
  // difference between the current time and last time you blinked
  // the LED is bigger than the interval at which you want to
  // blink the LED.
  unsigned long currentMillis = millis();

  if (currentMillis - previousMillis >= interval) {
    // save the last time you blinked the LED
    previousMillis = currentMillis;

    // if the LED is off turn it on and vice-versa:
    if (ledState == LOW) {
      ledState = HIGH;
    } else {
      ledState = LOW;
    }

    // set the LED with the ledState of the variable:
    digitalWrite(ledPin, ledState);
  }
}


Can I disable the TX pin by setting its mode to INPUT while still receiving data on the RX pin of a UART?

Well, I ended up answering my own question in a few minutes of forum research.

You can disable the TX pin of the hardware UART with:

UCSR0B &= ~bit (TXEN0);


Arduino Mega, Ubuntu, Time.h: No such file or directory

ok. It seems that the Ubuntu arduino package does not contain this library. The file Time.zip has to be downloaded from the authors website: http://www.pjrc.com/teensy/td_libs_Time.html and added in the Arduino GUI menue bar: Sketch -> Import Library -> Add Library


Hardware vs Software Serial: Most microcontrollers/Arduinos have at least 1 hardware Serial interface. That means, that for this Serial interface the actual communication protocol (the transmission and receiving of the actual data) is implemented in dedicated hardware inside the microcontroller (which also means there are fixed pins, where you can connect to them on the board). That way you don't need code for doing the complex communication protocol. Instead the main CPU is only involved to handle the received and to-be-transmitted data, which need to be placed in a buffer register. The dedicated hardware then automatically sends and received the data.

As the number of hardware Serial interfaces is limited and fixed for the Arduino board/microcontroller, it happens, that you need more Serial interfaces, than you have in hardware on your board/in your microcontroller. Then you can use SoftwareSerial. That is a library, which handles the complete communication protocol in software, by directly setting and reading the electrical pin states according to the protocol. The advantage is, that you can use this on any digital pins for such an interface. Disadvantage is, that doing such things in software is complex. You can only listen on 1 SoftwareSerial interface at a time and the baudrate is limited (depending on the actual used microcontroller, e.g. it's frequency).
UART vs Serial: UART is the technical term for the used communication interface. Serial is an Arduino term, which is not used that way in other contexts. The real interface type is UART and the Arduino framework just names that Serial to make it simpler.
Connecting over USB cable or pins: Let's take the Arduino Uno as example. It has 1 hardware serial interface. This interface is connected to the pins 0 and 1 (RX and TX), but also internally to an extra chip. That chip handles the USB connection and behaves as a USB-Serial bridge. When communicating with the Serial Monitor in the Arduino IDE, you are actually using this USB-Serial bridge to talk to the microcontroller on the Arduino. But you could also use the RX/TX pins to do that.


How do I make LEDs lights up one by one according to how long the button was pressed and hold

There are multiple errors in your code.
In the loop, the first if might not have the use you intended it to have. You are checking for previous == low, but you never set previous to high. Therefore this check can be removed entirely, or you could restructure your code a bit and add a previous = high.
Secondly, this if is also flawed:
if (millis_held >= 1000 && firstTime <2000){
    digitalWrite(3, HIGH);
}

You are checking for firstTime < 2000 which means you need to press the button within 2 seconds of the power-up of the Arduino or else this code will not run.
Lastly, for this to run you probably only want to set firstTime = millis() once when you press the button, and not every time the loop() runs thereafter while you keep the button pressed. You would need to move the bracket on line 32 to line 22, that is from just above the else to the line above millis_held = (millis() - firstTime); and then add previous = HIGH; in the first if.
I am leaving it to you to fix your code, since that would be good practice to get some feeling for it. Happy coding!
Lastly you still need to add the last 5 leds, but once the first few work you should be fine.


Arduino for Weather and Air Monitoring: Casing and Power Source

I'd say, use a IP-54 protection plastic case. The IP is a standard, that tells you, how big particles can(not) come into the case.

About powering, depends, how often can you go and switch batteries.
If you can, you can plug the cable in the case - drill the hole through and use watertight silicone plug to ensure, it is water resistant.

In case of batteries - use some LiPo batteries with DC-DC converter to minimum voltage.
Maybe you could even add a solar panel or two for addional life extension of batteries.


The lcd.print() method takes a string or a number as an argument, but not both at once. Using the + operator for concatenation is not native to C strings. C strings are basically stored as pointers to the first character of the string. So when you tried lcd.print("1234 " + number) and got "34 ", what most likely happened is that you advanced the pointer, pointing to the first character of "1234 "(i.e. '1') by number (i.e. 2), thus making the pointer point to the 3rd character in the string and thus making lcd.print() display "34 ".
In order to print something that contains both strings and integers, the most straightforward way is to convert each piece to an Arduino string and then concatenate them, using the + operator like you did earlier.

    lcd.print(String("1234 ") + String(number));
    lcd.print(String(number) + String(" plus ") + String(number) + String(" equals ") + String(result));

These are some examples. You could also use create a sufficiently large char buffer and use sprintf() from stdio.h to build a string made up of integers and strings. Look up a textbook on C/C++ for more details.


How can I break the loop if it hasn't finished in 10 seconds?

This is just a rough, incomplete and untested code.
void singleclick1() { startTimer = true; }      // this only sets a flag

void singleclick2() { runTimer   = false;}      // this only clears a flag

void loop() {

   button1.tick();
   button2.tick();

   if startTimer {                 // this occurs once every click 1

      mode        = millis();
      runTimer    = true;
      startTimer  = false;         // run this block only once every click 1

      digitalWrite(led1, HIGH);
      digitalWrite(led2, LOW );
      digitalWrite(led3, LOW );
      digitalWrite(led4, LOW );
   }

   unsigned long currentMillis = millis();

   if (currentMillis - mode > 10000) {
      runTimer = false;                      // 10 second timer expired
   }

   if (runTimer) {

      Serial.println("TRIG");

   }
   else {
      // optional stuff to do
   }
}


If the file is in your sketch folder then you use this syntax:

#include "foo.h"

All source files in the root of the sketch folder are shown as tabs in the Arduino IDE. In some cases that might not be desirable. If so, you can put the file in the src subfolder of your sketch folder and use this syntax:

#include "src/foo.h"

Or you might want to group files together into separate subfolders:

#include "src/foo/foo.h"

If you want to access the file from multiple sketches then you should turn it into a library and use this syntax:

#include <foo.h>


Corrupted output from HC-05 Bluetooth module

First thing to try:

Connect a 2.2k - 10k resistor from the arduino RX pin (the hc-05 tx pin) to ground.

If that didn't work, I recommend getting everything into a known state and eliminating some complexity. So, first let's remove the Android software from the equation.  And second, let's put the module into a known baud rate.

To do this wire up the arduino and module like this:

Notice that the Key pin is connected to 3.3v.  That will ensure the module is at 38400 baud on power up.

Connect the arduino to your computer with the FTDI cable.  Upload the following sketch:

/* Serial Loop */

#include <SoftwareSerial.h>

#define rxPin 8
#define txPin 9

SoftwareSerial mySerial(rxPin, txPin); // RX, TX
char myChar ;

void setup() {
  Serial.begin(9600);
  Serial.println("AT");

  mySerial.begin(38400);
  mySerial.println("AT");
}

void loop() {
  while (mySerial.available()) {
    myChar = mySerial.read();
    Serial.print(myChar);
  }

  while (Serial.available()) {
    myChar = Serial.read();
    Serial.print(myChar); //echo
    mySerial.print(myChar);
  }
}

With the sketch now uploaded and running, open the Arduino serial console and enter these AT commands. The serial console baud rate should be set to 9600 and line endings should be "Both NL & CR"

AT+ORGL //back to factory settings
AT+ROLE=0 //slave role - transparent serial bridge
AT+UART=9600,0,0 //default baud rate
AT+INIT //init module

You should get "OK" back from the module after each command. If you've gotten this far, we know the module is working fine and we know what baud rate it will default to now.

Hook the module back up the way you had it before.  Make sure 3.3v is disconnected from key pin and make sure you have added the pulldown resistor on the RX line. Cycle the power to the module. The module should start up running 9600 baud, slave mode. Delete the module from the Android pairing list and re-pair it.  The name probably will have changed.  Hopefully it works correctly now.

Cheers


How can I make this button toggle the position of a servo?

Do something like this:

int angles[2] = {0,180}
bool state = 0;

then:

if(button == PRESSED)
  state = !state;

finnally, to control the servo:

Servo.write(angles[state]);


Retrieve value from ThingSpeak using ESP8266 with Arduino setup

Connect to the server as usual with espClient.connect(). The following request should return a JSON object containing your channel description and the first 2 entries in your feed:

espClient.println("GET /channels/CHANNEL_ID/feeds.json?results=2 HTTP/1.1");
espClient.println("Host: api.thingspeak.com");
espClient.println("Connection: close");
espClient.println();

If it's a private channel, then you must supply your Read API key like this:

espClient.println("GET /channels/CHANNEL_ID/feeds.json?api_key=<your API key>&results=2 HTTP/1.1");

Notice that I use println() and not print() in order to implicitly terminate each request line properly. You should end each line not with \n but with \r\n. You only need to type this yourself if you use print().

To read the returned JSON data:

while (espClient.available() == 0);  // wait till something comes in; you may want to add a timeout here

unsigned long lastRead = millis();  // keeps track of last time a byte was read
while (millis() - lastRead < 2000) {  // while 2 secs havent passed since a byte was read
  while (espClient.available()) {
    Serial.print(espClient.read());
    lastRead = millis();   // update last time something was read
  }
}
client.stop();  // close socket

To parse the JSON string, you either get a library from GitHub or you parse the string yourself.


My first thought was what about relays.  I've done a quick search and found this http://www.geofex.com/article_folders/relays/relays_for_switching_audio_signa.htm and this https://electronics.stackexchange.com/questions/110750/is-it-possible-to-turn-an-audio-signal-on-off-using-a-solid-state-relay so maybe it's not such a stupid idea, but like optocouplers it probably is a bit OTT.


The exact time for functions or CPU cycles for any function

Method summary

(section added on 2018-01-28)

There are several methods available for timing code. I am adding this
preliminary section to my answer in order to provide comparative data on
several methods. The methods covered in the table below are those
proposed as answers to both this question and a duplicate question of
this. As this question has been tagged “arduino-uno”, all
this data assumes an AVR-based board clocked at 16 MHz.

Method comparison:

| method         | resolution    | max. time       | typ. overhead  |
|----------------|---------------|-----------------|----------------|
| `millis()`     | 1 – 2 ms      | 49.7 days       | 0.69 – 1.3 µs  |
| `micros()`     | 4 µs          | 71.6 min        | 2.8 – 2.9 µs   |
| Timer 1        | 0.0625 µs     | 4.096 ms        | 0.25 – 0.5 µs  |
| pin toggling   | scope-limited | ∞               | 0.125 µs       |
| cycle counting | 0.0625 µs     | boredom-limited | 0              |
| looping        | N.A.          | N.A.            | 0.25 µs        |

The methods are characterized by the following criteria:

Resolution is the granularity of the measurement, the smaller the
better.
Maximum measurable time: any method that does timing arithmetics
on the Arduino is prone to overflows if measuring too long times. Note
that a timer rolling over to zero during the measurement is not a
problem, as long as the period being measured is less than
the rollover period.
Typical measurement overhead: the code used to measure the timings
takes itself a finite time to execute, thus one ends up measuring the
execution time of the “instrumented” code, which is slightly larger
than the time taken by the code one is trying to profile. This
overhead should in principle be subtracted from the result, but it is
often not known exactly, as it depends on how the compiler optimizes
both the instrumented and the non-instrumented code.

The methods listed in the table are:

millis(), which may be the most obvious choice, as it is so well
known. Its low resolution, however, makes it ill-suited for timing
code execution. It should be noted that the millis() counter is
incremented every 1024 µs. Most of the time it is incremented by
1 but, every 43 ms (roughly) it is incremented by 2 in order to
avoid creeping drift. This is why its resolution is stated as
“1 – 2 ms” in the table.
micros(), as proposed in ratchet freak's answer, is usually
a good choice, the main caveat being the 4 µs resolution, when
one could naively expect 1 µs. It also has a significant
overhead.
Timer 1, which is discussed in the second part of this answer, is
my favorite: it has single cycle resolution and low overhead. However,
it is incompatible with other uses of the timer (PWM, Servo
library...). It is also limited to measuring small delays.
Pin toggling, as proposed by 4ilo, and by myself in the third
part of this answer, is ideal if you have an oscilloscope handy. Any
half-decent scope should provide single-cycle resolution. It is also
minimally invasive on the code being measured and has minimal
overhead.
Cycle counting, as proposed in Majenko's answer, is arguably
the “perfect” method: it is cycle-accurate, does not modify the code
and has zero overhead. However, for anything beyond a handful
instructions, it quickly becomes tedious. And it requires some
understanding of the AVR assembly.
Looping, as proposed in Michel Keijzers' answer, is not a
measurement technique per se. It is meant to be used in conjunction
with another technique in order to improve the resolution and dilute
the overhead. However, lopping carries it's own overhead, which is
typically 4 CPU cycles per iteration, assuming a 16-bit loop
counter.

Using Timer 1

(original answer of 2017-10-23)

One technique I often use is to make Timer 1 count at the full CPU speed
and use it to time the code I want to profile. For example:

volatile uint8_t pin = 2;
volatile uint8_t value = HIGH;

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

    // Set Timer 1 to normal mode at F_CPU.
    TCCR1A = 0;
    TCCR1B = 1;

    // Time digitalWrite().
    cli();
    uint16_t start = TCNT1;
    digitalWrite(pin, value);
    uint16_t finish = TCNT1;
    sei();
    uint16_t overhead = 8;
    uint16_t cycles = finish - start - overhead;
    Serial.print("digitalWrite() took ");
    Serial.print(cycles);
    Serial.println(" CPU cycles.");
}

void loop(){}

Note the volatile variables used to prevent the compiler from
optimizing them as constants.

Note also that when you profile some code you are inevitably slowing it
down, because of the time taken by the profiling operations themselves.
This is what the overhead variable above accounts for. In order to
know the exact overhead, I start with a guess, compile and disassemble,
and then count the number of clock cycles spent in profiling that will
be counted by the timer. Then I adjust the overhead value, compile and
disassemble again, and make sure the overhead has not changed. This is
also when you have to ask yourself what exactly you want to count. Here
I am counting the time needed to execute call digitalWrite, but not
the time needed to get the arguments in the proper registers, as I am
artificially slowing this down by making them volatile.

This method is good for anything that takes more than roughly a dozen,
and less that 65,536 clock cycles. Less than that, clock counting would
be simpler, since you still have to clock-count the overhead. More than
that, the count would overflow, and you could instead just use
micros(), and live with its inherent inaccuracy.

Toggling a pin

(section added on 2017-10-23)

If you have a scope, there is another method that is minimally
invasive on your code: toggle a pin just before and just after the thing
you want to time. E.g., assuming you have previously
pinMode(13, OUTPUT):

// Set pin 13 HIGH.
PORTB |= _BV(PB5);

// The thing we want to time.
...

// Set pin 13 LOW.
PORTB &= ~_BV(PB5);

This will create a pulse that you can measure on the scope. Note that
using direct port access, like here, the overhead is only two CPU cycles,
or 125 ns. Also, direct port access won't use any CPU register, so
chances are the compiler will not generate less efficient code than when
not including the timing part.


Getting no such directory file error when compiling

The ESP8266WiFi library is for programming the ESP8266 directly. You are trying to compile source code for the ESP8266 for the Arduino UNO, that obviously won't work.

A Beginner's Guide to the ESP8266


Is it possible to control the speed of DC motors with Arduino's analogWrite() using analog pins?

No, you can't.  As it says in the Arduiuno reference page for analogWrite(): "The analogWrite function has nothing to do with the analog pins or the analogRead function."

You can use the "analog input pins" (A0..A5) of Arduino for analog input, or as digital inputs or outputs.  They cannot be used for PWM(digital)-output.  Only digital pins, and only those specifically stated for PWM-output, can actually be used for PWM output (unless you go down the path of software-PWM, though I would hesitate to do that for an H-bridge).


An accelerometer is the way to go. There will be a fair amount of math to go thru in order  to convert the acceleration value into speed. I can't explain it better than this answer.

An gyro would give you the angular rate on the ball and the magnetometer could give you the ball orientation relative to the magnetic north.


Arduino to send sms one time only when a button is pressed

You are resetting count every time you enter the function.

static int count; // initialized to zero, once.

Adding the static statement should initialise the variable once and preserve its value between calls.


SLEEP is an assembly instruction.  You can execute assembly with GCC's Inline Assembly facility.

In short:

asm volatile("SLEEP");

will do what you want.

The avr/sleep.h file has sleep_cpu() defined as:

#define sleep_cpu()                              \
do {                                             \
  __asm__ __volatile__ ( "sleep" "\n\t" :: );    \
} while(0)

Which is essentially the same thing - just wrapped in a block to isolate it from the rest of your code somewhat.


Print when echo is read by HR-S04 sensor

A couple things:

1) I believe your code for the trigger pin is wrong. An example I found sets it up as LOW for 2 microseconds, then HIGH for 10 microseconds, then LOW. (Note that the units are MICROseconds so you must use delayMicroseconds()

2) digitalRead(echo1) does nothing. Use the pingTime1 instead. You will always be receiving an 'echo' so it's not a HIGH or LOW but rather a changing variable stored as pingTime1.

3) echo1 is the variable for the pin. That's why Serial.println(echo1) prints the pin number. You could try Serial.println(ECHO1) but I don't think it will work because of what I said above.

4) If you want a HIGH or LOW to print to screen you must set a cutoff value for pingTime1 then use an if statement to print the appropriate value.

I'm not sure what exactly you're trying to do, but given the points above I do not believe a while loop is necessary.

Try this code. You can keep the first Serial.println() to see the duration of the pulse and/or you can keep the if statement if you want a HIGH or LOW to print to screen.

// Send a pulse out through trig pin
digitalWrite(trig1,LOW);
delayMicroseconds(2);
digitalWrite(trig1,HIGH);
delayMicroseconds(10);

//Receive pulse through echo pin
pingTime1=pulseIn(echo1, HIGH);
pingTime1=pingTime1*1000;

// Serial print
Serial.println(pingTime1);

//Serial print (for HIGH or LOW)
if (pingTime1 > cutoff) {
    Serial.println('HIGH');
}
else {
    Serial.println('LOW');


How to toggle LED and motor on button press?

Here is a program that should fade the LED as you specified. Initially the LED is off. If you press the button the LED starts fading within the time frame to its maximum. Then it switches to zero waits a couple of seconds and starts fading from new. If you press the button a second time the LED stops fading and is set to darkness. ;-) This happens emediately, but of cause, you can only see it if the LED is in the fading phase.

I used interrupts in order to have a well defined state transition I can work with.

Aquiring the button pin in the loop, would be more complex to handle. That would require a state variable and some state transition rules. And I was too lazy to work that out. If interupts can't be used for any reason, I would change the answer. (No Mum I don't want to ...)

I removed the motor pin as it makes no sense for the answer. I also think that one pin would not be enough if your motor (stepper, dc with feedback or a servo) should spin a certain amount of degrees.

I tested the program on a Arduino UNO. The button I used is of low quality so I had to debounce it.

If there is something not clear to you, please ask within a comment.

// Attache the LED to a PWM pin UNO -> 3,5,6,9,10,11
const byte ledPin       = 9;

// UNO -> only pin 2 or pin 3 are interrupt pins
// as we use pullups the button should be connected to GND
const byte interruptPin = 2;

// in milli seconds - The time the LED needs to fully light up
const int timeFrame  = 5000;

// in milli seconds
const int aCoupleOfSeconds = 2000;

const int fadeAmount =    5;

volatile boolean fadeOn = false;
volatile long debounceTime = 800;
volatile long actTime = 0;

int brightness =   0;

int stepCount = 256       / fadeAmount;
int stepDelay = timeFrame /  stepCount;

void setup()
{
  pinMode( ledPin,       OUTPUT       );
  pinMode( interruptPin, INPUT_PULLUP );

  attachInterrupt( digitalPinToInterrupt( interruptPin ), pressed, CHANGE );
}

void loop()
{
  if ( fadeOn )
  {
    delay( stepDelay );
    brightness += fadeAmount;
    if ( brightness >= 255 )
    {
       brightness = 0;
       analogWrite( ledPin, brightness );
       delay( aCoupleOfSeconds );
    }
    analogWrite( ledPin, brightness );
  }
  else
  {
    brightness = 0;
    analogWrite( ledPin, brightness );
  }
}

void pressed()
{
  // the debouncing does not work perfectly

  if ( digitalRead( interruptPin ) == LOW )
  {
    if ( millis() - actTime > debounceTime )
    {
      fadeOn = !fadeOn;
    }
  }
  else
  {
    actTime = millis();
  }
}


How do you remove an item from array arduino?

There is no such concept in C. Arrays are a fixed size and that size can never be changed. You can't "delete" an entry. You can replace one with something else, and you can introduce the concept of a variable that says how many entries the array has, but you can't delete one.
So you could:

Keep a count of how many entries are in the array
Shuffle down all the entries one space so the unused one is at the end
Decrement the count of entries

So in your example {3, 5, 3, 6} becomes {3, 5, 6, 6} and your "count" holds 3 to say the first three entries are valid and to ignore the last.
Alternatively you can introduce the concept of "end of array". C strings do this with the NULL character (0). Anything before that character is valid, and anything from that character onwards is ignored.  So say you nominated the value -1 to be "end of array" you could have, after again shuffling down the values: {3, 5, 6, -1}.
You could also have -1 (or whatever you chose) indicating an "invalid" entry, so your array would be {3, 5, -1, 6} and you would ignore the -1 entry in your code.


I solved my own problem. Wiring was completely OK, so was flashing.

The problem was RESET pin (4th physical pin). As soon as I disconnected it after flashing, LED started blinking. If someone knows why, I'd appreciate some info.


Porting code from Arduino IDE to other IDEs - expected code size reduction

You don't need to abandon the Arduino IDE.

Let me quote from my forum post about sketch sizes.

Introduction

Every now and again this subject pops up on the Arduino forum. Why does it take 1000 bytes to blink an LED? Why, oh why? It is obviously very bloated, eh?

Example: blink

Let's check that claim first.

The "blink" sketch, as shipped with the IDE (and stripped of comments) is:

int led = 13;
void setup()
{
  pinMode(led, OUTPUT);
}

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

Compiled:

Binary sketch size: 1,084 bytes (of a 32,256 byte maximum)

OK, over 1000 bytes to "blink an LED".

Well first, as someone on the Arduino forum humorously pointed out, it doesn't take 2000 bytes to blink two LEDs!

int led1 = 13;
int led2 = 12;
void setup()
{
  pinMode(led1, OUTPUT);
  pinMode(led2, OUTPUT);
}

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

  digitalWrite(led2, HIGH);
  delay(1000);
  digitalWrite(led2, LOW);
  delay(1000);
}

That takes:

Binary sketch size: 1,140 bytes (of a 32,256 byte maximum)

So the overhead for the second LED is only:

1140 - 1084 = 56

So you could argue that it only takes 56 bytes to blink an LED (providing you are already blinking another one).

It does more than blink

The first relevant rejoinder here is that the example sketch does more than blink an LED. Rather importantly, it also waits for a second between turning the LED on and off (the "delay" function call).

If we remove that, the sketch is somewhat smaller:

int led = 13;
void setup()
{
  pinMode(led, OUTPUT);
}

void loop()
{
  digitalWrite(led, HIGH);
  digitalWrite(led, LOW);
}

Code size:

Binary sketch size: 882 bytes (of a 32,256 byte maximum)

So we saved 202 bytes by not doing a delay. This isn't totally unreasonable, as doing delays requires the library to configure a timer, and have code to check that timer.

The pins numbers are variables

The code in the Blink example uses (wrongly in my opinion) a variable to hold the pin number (13) when a constant would do. And if you use a constant there is a library called
digitalWriteFast that generates more efficient code.

#include <digitalWriteFast.h>

const int led = 13;
void setup()
{
  pinModeFast(led, OUTPUT);
}

void loop()
{
  digitalWriteFast(led, HIGH);
  digitalWriteFast(led, LOW);
}

Code size:

Binary sketch size: 470 bytes (of a 32,256 byte maximum)

Now we are down to 470 bytes to "blink an LED".

We can use port manipulation

If all we want to do is blink the LED, we can omit using setup and loop, and go straight into using the processor registers. For example:

int main ()
  {
  DDRB = bit (5);
  while (true)
    PINB = bit (5);
  }

That blinks pin 13, believe it or not*. And now it only takes 178 bytes:

Binary sketch size: 178 bytes (of a 32,256 byte maximum)

* very rapidly indeed

Interrupt vectors

Well, you may be thinking "Pfft! Still 178 bytes. Why not 10 bytes?"

The answer to that lies in the way the hardware works. The Atmega328P has 26 interrupt vectors, at the start of program memory. Each one is 4 bytes (it jumps to a handler for each interrupt). So 26 * 4 = 104 bytes.

Thus there is an unavoidable overhead of 104 bytes in any piece of code. (Unless you know in advance you aren't going to use all those interrupt vectors, but this is rather specialized).

You can see these vectors if you add handlers for them:

EMPTY_INTERRUPT (INT0_vect)
EMPTY_INTERRUPT (INT1_vect)
EMPTY_INTERRUPT (PCINT0_vect)
EMPTY_INTERRUPT (PCINT1_vect)
EMPTY_INTERRUPT (PCINT2_vect)
EMPTY_INTERRUPT (WDT_vect)
EMPTY_INTERRUPT (TIMER2_COMPA_vect)
EMPTY_INTERRUPT (TIMER2_COMPB_vect)
EMPTY_INTERRUPT (TIMER2_OVF_vect)
EMPTY_INTERRUPT (TIMER1_CAPT_vect)
EMPTY_INTERRUPT (TIMER1_COMPA_vect)
EMPTY_INTERRUPT (TIMER1_COMPB_vect)
EMPTY_INTERRUPT (TIMER1_OVF_vect)
EMPTY_INTERRUPT (TIMER0_COMPA_vect)
EMPTY_INTERRUPT (TIMER0_COMPB_vect)
EMPTY_INTERRUPT (TIMER0_OVF_vect)
EMPTY_INTERRUPT (SPI_STC_vect)
EMPTY_INTERRUPT (USART_RX_vect)
EMPTY_INTERRUPT (USART_UDRE_vect)
EMPTY_INTERRUPT (USART_TX_vect)
EMPTY_INTERRUPT (ADC_vect)
EMPTY_INTERRUPT (EE_READY_vect)
EMPTY_INTERRUPT (ANALOG_COMP_vect)
EMPTY_INTERRUPT (TWI_vect)
EMPTY_INTERRUPT (SPM_READY_vect)

Now the start of the object code is:

00000000 <__vectors>:
   0:   0c 94 34 00     jmp 0x68    ; 0x68 <__ctors_end>
   4:   0c 94 51 00     jmp 0xa2    ; 0xa2 <__vector_1>
   8:   0c 94 52 00     jmp 0xa4    ; 0xa4 <__vector_2>
   c:   0c 94 53 00     jmp 0xa6    ; 0xa6 <__vector_3>
  10:   0c 94 54 00     jmp 0xa8    ; 0xa8 <__vector_4>
  14:   0c 94 55 00     jmp 0xaa    ; 0xaa <__vector_5>
  18:   0c 94 56 00     jmp 0xac    ; 0xac <__vector_6>
  1c:   0c 94 57 00     jmp 0xae    ; 0xae <__vector_7>
  20:   0c 94 58 00     jmp 0xb0    ; 0xb0 <__vector_8>
  24:   0c 94 59 00     jmp 0xb2    ; 0xb2 <__vector_9>
  28:   0c 94 5a 00     jmp 0xb4    ; 0xb4 <__vector_10>
  2c:   0c 94 5b 00     jmp 0xb6    ; 0xb6 <__vector_11>
  30:   0c 94 5c 00     jmp 0xb8    ; 0xb8 <__vector_12>
  34:   0c 94 5d 00     jmp 0xba    ; 0xba <__vector_13>
  38:   0c 94 5e 00     jmp 0xbc    ; 0xbc <__vector_14>
  3c:   0c 94 5f 00     jmp 0xbe    ; 0xbe <__vector_15>
  40:   0c 94 60 00     jmp 0xc0    ; 0xc0 <__vector_16>
  44:   0c 94 61 00     jmp 0xc2    ; 0xc2 <__vector_17>
  48:   0c 94 62 00     jmp 0xc4    ; 0xc4 <__vector_18>
  4c:   0c 94 63 00     jmp 0xc6    ; 0xc6 <__vector_19>
  50:   0c 94 64 00     jmp 0xc8    ; 0xc8 <__vector_20>
  54:   0c 94 65 00     jmp 0xca    ; 0xca <__vector_21>
  58:   0c 94 66 00     jmp 0xcc    ; 0xcc <__vector_22>
  5c:   0c 94 67 00     jmp 0xce    ; 0xce <__vector_23>
  60:   0c 94 68 00     jmp 0xd0    ; 0xd0 <__vector_24>
  64:   0c 94 69 00     jmp 0xd2    ; 0xd2 <__vector_25>

The "real" code has to start at 0x68 (decimal 104) which is where the reset vector takes us (the first vector).

So now, our code is really 178 - 104 bytes of useful code. That's 74 bytes to blink an LED.

However even some (most) of that is overhead, generated by the C compiler to initialize global variables, call class constructors, etc. Let's test that by blinking two LEDs.

int main ()
  {
  DDRB = bit (5);  // pin 13
  DDRB |= bit (4);  // pin 12

  while (true)
    {
    PINB = bit (5); // pin 13
    PINB = bit (4); // pin 12
    }
  }

Code size:

Binary sketch size: 186 bytes (of a 32,256 byte maximum)

Eight bytes difference. So really, you can blink an LED in 8 bytes. That is the bottom line. And you can do it in the Arduino IDE.

The libraries are designed to make things easy

The fact is that the default behaviour of the Arduino libraries is to simplify things for beginners. Thus they do some things which take up a bit of memory;

You can pass variables to pinMode and digitalWrite. Not just constants. Thus, at runtime, code has to convert the variable value to an actual processor port.
You get an automatic set-up of Timer 0, so you can use millis(), micros(), and delay() function calls.
You get Timer 1 and Timer 2 set-up, so you can do PWM output easily.

So you are trading off program space, to an extent, for ease of use. But if you want to code around it, as I did above, you can trim that program space right down.

Tests on an Arduino Uno board type, IDE 1.0.5.


Potentiometer with switch wiring question. Not reading correctly

From your description of switch wiring, it sounds like you have one of the switch leads attached to +5 V and the other switch lead to an input.
As noted in comments and answers to  “Why all unset pins of my Arduino Uno are outputting 2 volts?”, such an input will read high when the switch is closed, and will read randomly when it is open, because an input is a high-impedance device that can accumulate charge:

... input impedance typically can be taken as 100 MΩ for design purposes. ... Each pin has a few pF (5-10?) of capacitance ... which in general is small compared to stray capacitances of attached wiring.
When stray electromagnetic fields charge the pin and stray capacitances, a small voltage develops on the pin. You could connect a 1 to 10 MΩ resistor between the pin and ground, to avoid the [voltage] you are seeing.

The easy fix for the problem is to attach one switch-lead to ground, one to an input pin, and initialize the pin with INPUT_PULLUP pinmode instead of just INPUT.