As a general rule, any modern electronic device with computational ability has to use DC. The reason is that they use specific voltage levels to indicate binary/logical states (i.e. 0's and 1's).

In theory, an ideal DC supply (Direct Current) should provide a constant voltage. That allows the circuit to effectively turn it on an off to represent binary states. (In reality, there's no such thing as truly "off" though, because voltage is relative.)

However, the voltage from an AC supply (Alternating Current) is constantly varying. If you plot it on a chart, you should see a nice sine wave, flowing smoothly between positive and negative several times per second. Hypothetically, if a digital circuit tried to use AC then it would get very confused, because everything would seem to be turning on and off all the time.

With all that said, it's very common to turn AC into DC through a process called rectification. For example, that's what allows DC devices to get power from an AC outlet (e.g. to run your computer or charge your phone).


Will the 3.3V regulator on an Arduino Leonardo work when powered from USB?

Yes, provided that

it is an "official" Leonardo or a competent clone and
as long as you do not load the power supply excessively with external loads.

Official circuit diagram here

The USB supply feeds the 3V3 regulator via MOSFET T1 at the bottom of the sheet and U3, an LP2985 LDO regulator. If your board has the same circuitry as this it should provide 3V3 from USB.


Arduino's digitalWrite, precautions for direct port manipulation?

I figure they don't want an interrupt to possibly change any of the bits in the output register while it executes *out = *out & ~bit?

Correct. That is known as a critical section.

  And what would the SREG have to do with it? Could the code affect SREG and why would that matter?

SREG is where the flag that says if interrupts are enable or not is stored.  Basically that is storing the current state, disabling interrupts, then restoring the current state.

The upshot is:

If interrupts are enabled to begin with, they are disabled, then re-enabled.
If interrupts are disabled to begin with, they are again disabled, and they remain disabled.

It's a way of restoring the previous state without actually having to check what the state was and set or clear accordingly.


Output works on UNO Pin 13, but not on 2?

void SendCode() {
  // This is the code for my FIOS FF
  Serial.println("FIOS- FFwd");
  pulseIR(9220);
  delayMicroseconds(4540);

Personally I would be putting the cli() around everything in SendCode (apart from the Serial.println) because the serial print will cause interrupts, and they could occur between successive function calls there.

I checked your code using IDE 1.6.9 and got this pulse width for pin 2:

And this pulse width on pin 13:

You'll notice they are virtually identical and that neither show a frequency of 38 kHz. The measured period of 30.71 µs gives a frequency of 32.563 kHz.

Unless your version of the compiler generates different code than mine, I suggest you need to tweak your timing loops.

  I am wondering if there is a latency difference from pins 2 and 13?

No, I think not. The problem may be elsewhere, such as electrical. I suggest you try to measure the frequency of your timing loops using whatever external equipment you have to hand. For example, just call your pulseIR function constantly and measure with a frequency meter. I measured 32.555 kHz on my meter, for example.

Use a timer to generate 38 kHz

You will get a more accurate 38 kHz signal if you use the hardware timers, properly configured. For example:

const byte LED = 10;  // Timer 1 "B" output: OC1B
const byte buttonPin = 4;

// Clock frequency divided by 38 kHz frequency desired
const long timer1_OCR1A_Setting = F_CPU / 38000L;

void setup()   {
  pinMode(buttonPin, INPUT_PULLUP);
  pinMode (LED, OUTPUT);
  Serial.begin(115200);

  // set up Timer 1 - gives us 38.005 kHz
  // Fast PWM top at OCR1A
  TCCR1A = bit (WGM10) | bit (WGM11);                // fast PWM
  TCCR1B = bit (WGM12) | bit (WGM13) | bit (CS10);   // fast PWM, no prescaler
  OCR1A =  timer1_OCR1A_Setting - 1;                 // zero relative
  OCR1B =  timer1_OCR1A_Setting / 2 - 1;             // duty cycle
}

void loop()
{
 if (! digitalRead(buttonPin)) {
    // button down
    Serial.println("Sending IR signal");
    SendCode();
    delay (200);
  }
}

// This procedure sends a 38KHz pulse to the IRledPin
// for a # of microseconds.
void pulseIR(const unsigned int microsecs) {
  TCCR1A |= bit (COM1B1); // clear OC1B on compare
  delayMicroseconds (microsecs);
  TCCR1A &= ~bit (COM1B1); // don't clear OC1B on compare
  digitalWrite (LED, LOW);
}

void SendCode() {
  // This is the code for my FIOS FF
  Serial.println("FIOS- FFwd");
  noInterrupts ();
  pulseIR(9220);
  delayMicroseconds(4540);
  pulseIR(540);
  delayMicroseconds(4560);
  pulseIR(520);
  delayMicroseconds(4560);
  pulseIR(540);
  delayMicroseconds(4540);
  pulseIR(540);
  delayMicroseconds(4560);
  pulseIR(520);
  delayMicroseconds(4560);
  pulseIR(540);
  delayMicroseconds(4540);
  pulseIR(540);
  delayMicroseconds(2260);
  pulseIR(540);
  delayMicroseconds(2260);
  pulseIR(520);
  delayMicroseconds(2260);
  pulseIR(540);
  delayMicroseconds(2260);
  pulseIR(540);
  delayMicroseconds(2260);
  pulseIR(520);
  delayMicroseconds(2260);
  pulseIR(540);
  delayMicroseconds(2260);
  pulseIR(540);
  delayMicroseconds(4560);
  pulseIR(520);
  delayMicroseconds(4560);
  pulseIR(540);
  delayMicroseconds(4540);
  pulseIR(540);
  delayMicroseconds(22320);
  pulseIR(9200);
  delayMicroseconds(2240);
  pulseIR(540);
  delayMicroseconds(24664);
  pulseIR(9220);
  delayMicroseconds(2240);
  pulseIR(540);
  delayMicroseconds(24684);
  pulseIR(9200);
  delayMicroseconds(2260);
  pulseIR(520);
  delayMicroseconds(24684);
  pulseIR(9200);
  delayMicroseconds(2260);
  pulseIR(540);
  delayMicroseconds(24664);
  pulseIR(9220);
  delayMicroseconds(2260);
  pulseIR(520);
  interrupts ();
}

This sets up Timer 1 to output 38 kHz, and then for the timing of the pulses you just turn its output on and off.

Note that you have to use D10 on your Uno because that is where Timer 1 outputs to.

For more information see my page about timers.

I have a graphic which shows a lot of the useful registers:


How do I change number and bracket colors in the arduino IDE?

Inside path C:\Program Files (x86)\Arduino\lib\theme\syntax there is file default.xml where I made some changes and the following lines are as follows:

  <style token="SEPARATOR" fg="ffffff" />
  <style token="LITERAL_NUMBER_DECIMAL_INT" fg="ffffff"/>
  <style token="LITERAL_NUMBER_FLOAT" fg="ffffff"/>
  <style token="LITERAL_NUMBER_HEXADECIMAL" fg="ffffff"/>

After this brackets and numbers occur white.


Powering Arduino with reverse car lights?

It depends very much on the car and your Arduino. There are two factors to consider:

Leeching power off lights can have an adverse effect on the car's ability to sense a blown bulb.
Many Arduinos have a 2 second delay while the bootloader executes (some even have 8 seconds).

If your car doesn't sense blown bulbs (most modern ones now do, even cheap ones) and you can work without a bootloader (programming directly with a USBasp for example) to avoid the power-on delay, then it may be possible, yes.

As has been mentioned by others, using a switching regulator is the best method for powering the board as it avoids excess power loss through heat (which can especially be a problem in confined spaces). I would recommend not using one of the cheap eBay modules, but instead using a proper "cigarette lighter" to USB adaptor (available from all good gas stations priced $5) which is designed to work with automotive voltages. A car's 12V power has transients in excess of 50V sometimes (back EMF from the spark generation) and the electronics have to be able to cope with that - those cheap eBay modules aren't designed for that and could die taking your Arduino with it.


How to allow cross-domain requests on ESP8266WebServer

Add the CORS header to every response, not only for 'preflight' OPTIONS request. The OPTIONS support is optional, but the response returning the 'shared resource' must contain the CORS header

"Access-Control-Allow-Origin: *"


Arduino Nano 3.0 and Arduino Uno Benchmarks

ATmega16U4/ATmega32U4, ATmega48A/PA/88A/PA/168A/PA/328/P, ATmega2560, and numerous other Atmel AVR 8-Bit microcontrollers have an instruction set typically with “135 Powerful Instructions – Most Single Clock Cycle Execution” per datasheets.

That is, many of the AVR instructions, including almost all of the logic and arithmetic instructions, execute in 1 cycle.  A fair number of memory access instructions take 2 cycles.  A few instructions (eg JMP) take 3 cycles, and some (RCALL, CALL, RET, RETI, et al) take 4 or 5 cycles.  Others (eg SBRC) take 1, 2, or 3 cycles, depending on operand values and whether a branch occurs that disrupts the pipeline, which is shallow.  For an overview, see the instruction set summary in any AVR-part datasheet. For details, see Atmel's AVR Instruction Set Manual, doc0856 at atmel.com.

Overall, the average instructions per second in a typical compiled C program probably is between 1.5 and 2, so a 16 MHz system might do 8 to 11 MIPS on average, while carefully tailored do-nothing code can easily achieve 16 MIPS.


What is the best way to init wifi communication between two devices (get IP address)?

One is a server and the other is a client.
The server do not need to know IP of the client, but the client need to know IP address of the server. See more in communication between two Arduino


Faster TimerOne with Teensy 4.0 (600MHz)

You can use the TeensyTimerTool for this. It provides a generic interface to the hardware timers (TMR, GPT, PIT) and 20 software timers. Since the coupling of the timer peripherals to the ARM core is rather inefficient, the software timers might be a better fit for sub micro second interrupts.
If you prefer the hardware timers I suggest to use a GPT timer (also supported by the lib). You can configure it to use a 150MHz clock instead of the standard 24MHz clock. So something like 2MHz interrupt rate should be feasible.

Documentation can be found here: https://github.com/luni64/TeensyTimerTool/wiki


Check the L293x datasheet.

The L293D IC has two power supply pins. Pin 16, VCC1, is to power the IC itself, ei., its internal logic. Pin 8, VCC2, is to power the motors.

The maximum logic current (ICC1 MAX) drawn by the driver IC at pin 16 is 60mA. Thus, provided you do not have other things connected to the Arduino that can take the current draw above the limit, it is safe to connect VCC1 of the driver IC directly to the Arduino's 5V pin.

The maximum current you can draw from the 5V pin is around 400 mA, or 900 mA, when the Arduino is powered by an external power adapter.

The maximum current sourced or sinked by each driver input pin (xA) is 100 μA, and by enable pins (EN), it is 10μA, which is well within the limit of the Arduino digital pins, 40mA (not 50 mA!). So you can also safely connect Ax and EN directly to the Arduino.

Coming to the last point, the maximum power current supply by driver outputs (xY) is 600 mA. You cannot source or sink more than 600 mA from the 1Y, 2Y, 3Y and 4Y pins. All of this current will be drawn from pin 8 (VCC2), which is connected to the power supply for the motors, which can be a 9V battery. Note that ICC2 MAX is 1.2 mA. Thus, if the supply voltage of the motors is 5V, you must use another voltage source, like 7805 and not the 5V pin of the Arduino to provide VCC2.

To summarize,

You can connect pin 16 of L293D to Arduino's 5V pin.
You can connect pins 1, 2, 7, 9, 10, 15 of L293D to Arduino's digital pins.
You cannot connect pin 8 of L293D to Arduino's 5V pin.


Analog vs Digital Accelerometers - pro's and con's?

The biggest difference is where the measurement (the conversion to digital) is done.  On the digital accelerometer, it is done in the accelerometer itself. On the analog one it is done at the MCU.

For simple arrangements where the accelerometer is near the MCU that makes no difference. However the analog one is more susceptible to noise. With longer wires / traces between the accelerometer and the MCU you can get less accurate results with an analog one since it picks up noise which you are then sampling and including in your results.

The digital one is more immune to that kind of interference - instead it is susceptible to digital noise - corruption of the data as it traverses long wires. But that is less of a problem since it takes far more induced voltage to corrupt a digital signal than an analog one.

One other main difference is that you are limited to the ADC that is in the digital accelerometer. If you want a different resolution you have to use a different accelerometer. With analog, since it has no inherent resolution, you sample at the resolution of your MCU's ADC.

Digital is also easier to interface in modern systems.  Many SoCs don't have analog inputs. So adding an analog accelerometer would mean adding an ADC chip as well - and you don't really want to do that in something like a mobile phone.

So in summary:

Digital is the most convenient, reliable and suitable for current basic uses
Analog is more of a niche product that is rarely used in consumer electronics


Can I use this power supply with my Arduino?

Yes, that power supply is ideal for powering an Arduino (an Arduino doesn't care if it's linear or switching, and a linear regulator that goes from 220V to 5V is called a furnace, and you don't want one of those...)

HOWEVER unless you have a very strange wiring setup in your house, under normal circumstances there is no 220V supply in the switch.  You normally have live in, switched live out and NO neutral connection.

That means you don't have the connections you need to wire your power supply up to.

By the way: if you didn't already know that then you are not qualified to mess around with home wiring and you should leave it to the professionals.


You can do this by simply calling the right registers:

Example 1, using a MASK

D0/D1 are mapped to to PA10 & PA11 on the M0

/* The following ports where selected
    PORT_PA11
    PORT_PA10
    */
#define MYMASK 0x00000C00

int main (void)
{
    system_init();

    REG_PORT_DIRSET0 = MYMASK; // Direction set to OUTPUT
    REG_PORT_OUTSET0 = MYMASK; // set state of pin(s) to TRUE (HIGH)
    //REG_PORT_OUTCLR0 = MYMASK; // set state of pin(s) to FALSE (LOW)

    while(1){

    }
}

Here is another simple example:

/* The following ports where selected
    PORT_PA11
    PORT_PA10
    */
#define MYMASK 0x00000C00
#define LED1 PORT_PA10
#define LED2 PORT_PA11
int main (void)
{
    system_init();

    REG_PORT_DIRSET0 = LED1 | LED2; // Direction set to OUTPUT
    REG_PORT_OUTSET0 = LED1 | LED2; // set state of pin(s) to TRUE (HIGH)
    //REG_PORT_OUTCLR0 = LED1 | LED2; // set state of pin(s) to FALSE (LOW)
    while(1){

    }
}

In the Arduino IDE you can do something like:

#define MYMASK 0x00000C00
void setup() {
  REG_PORT_DIRSET0 = MYMASK; // Direction set to OUTPUT
}

void loop() {
   REG_PORT_OUTSET0 = MYMASK; // set state of pin(s) to TRUE (HIGH)
   delay(1000);
   REG_PORT_OUTCLR0 = MYMASK; // set state of pin(s) to FALSE (LOW)
   delay(1000);
}


If I run a function in loop() or setup(), and the function doesn't work after some time, is there a way to escape the function and return to the code?

In general, the right thing to do in such a situation is to fix the
initialize() function so that it always returns. If there is a timeout
to be handled, it should be handled within that function. This is likely
to be the easiest and cleanest solution.

However, if for whatever reason that is not feasible (maybe it comes
from a library that is too opaque to edit), then the idea suggested by
Michel Keijzers is a viable alternative:

  [...] set up a timer interrupt and start it just before you initialize
  the device/component you want to initialize. When the timer interrupt
  triggers and the device is not initialized, behave the same like a
  timeout has occurred.

The issue with this is that you would want the ISR (interrupt service
routine) to return to the point where initialize() was called. This is
not trivial, but it can be done. Actually, and contrary to what my own
comment says, it can be handled without resorting to assembly hacks, by
using the setjmp “non-local goto” feature of the avr-libc. Here is a
proof of concept:

#include <setjmp.h>

jmp_buf env;

// Simulate an initialization that can hang. Connect pin 8 to ground if
// you want the function to ever return.
void initialize()
{
    pinMode(8, INPUT_PULLUP);
    while (digitalRead(8) == HIGH)
        ;  // wait
}

// This fires when the initialization times out.
ISR(TIMER1_OVF_vect)
{
    TIMSK1 = 0;       // disable timer interrupt
    longjmp(env, 1);  // go to where setjmp() was called
}

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

    // Configure Timer 1 to fire an interrupt in about 4 seconds.
    TCCR1A = 0;           // reset timer
    TCCR1B = 0;
    TCNT1  = 0;
    TIFR1  = _BV(TOV1);   // clear interrupt flag
    TIMSK1 = _BV(TOIE1);  // enable timer overflow interrupt
    TCCR1B = _BV(CS10)    // clock at F_CPU / 1024
           | _BV(CS12);   // ditto

    // Attempt initialization.
    if (setjmp(env) == 0) {

        // This is the normal program flow.
        Serial.println("Attempting initialization.");
        initialize();
        TIMSK1 = 0;  // disable timer interrupt
        Serial.println("Initialization succeeded.");
    } else {

        // We get here through longjmp() in case of timeout.
        Serial.println("Initialization aborted on timeout.");
    }

    Serial.println("Moving on to the rest of the program.");
}

void loop(){}

If pin 8 is grounded, the initialization succeeds and the program prints

Attempting initialization.
Initialization succeeded.
Moving on to the rest of the program.

If pin 8 is left floating, the initialization hangs and the program
prints

Attempting initialization.
Initialization aborted on timeout.
Moving on to the rest of the program.

with a 4 second pause between the first and second lines.


I think you are totally misunderstanding, about variables and types and how using multiple servos with 1 function can work, and that this is your real question and not the thing with inserting variables (whatever you mean by that).

You are trying to put together a string and use it as variable name. That does not work. A string is only a variable/instance of type/class String. It cannot have methods of the Servo class. Also function parameters each have their own type. You cannot provide a value of a different type to this parameter. Servo.write() takes an integer value. It cannot use a String value. Thus the code inside the for loop is nonsense and won't compile. I would suggest doing some C++ tutorials from the web, that explain, how variables work in C++.

Instead you have to use multiple variables of the type Servo, one for each servo motor, that you are using. These variables are instances of the Servo class, which implements all the servo related functions (like write) Each motor gets it's own pin on the Arduino. You can put these Servo objects into an array, so that they can be indexed by an integer number. For example you can define the following variable in the global scope:

#define N_SERVOS 6
Servo servos[N_SERVOS];

This creates an array of type Servo with 6 elements. Each element is one independent servo object. (Note, that I used a define to easily change the number of attached servos when changing the code). You can reach an individual servo object by indexing it:

servos[3].write(pos);

This would write a new position to servo 4 (4 because array indices are starting from 0). Now we need to attach each Servo object to one pin of the Arduino. I would create an extra array, which contains the corresponding pin numbers - also at global scope:

int servo_pin[N_SERVOS] = {6, 7, 8, 9, 10, 11};

Here I used pins 6 to 11, but you can change them, as you like. Then in the setup() function we loop over our servo elements and corresponding pin numbers and attach the servo objects to the pins:

for(int i=0;i<N_SERVOS;i++){
    servo[i].attach(servo_pin[i]);
}

And now you can rewrite your openValve() function corresponding to that. I don't understand, what you wanted the servo to do in the for loop, so I will leave this to you. First you need to correct the syntax at the function declaration. You didn't specify the type of the parameter n. It has to look like:

void openValve(int n){

And then you shouldn't declare a new variable with the same name, so delete the line int n=3;. Then you can delete all the weird string concatiation. Then you need to fix the for loop (as I wrote I will leave that to you, since you didn't explain, what the servo should actually do there). And finally you need to rewrite the servo write line like described above:

servo[n].write(new_pos);

Note, that new_pos is just a placeholder here, for whatever values you need to write to the servo (as already said, I don't understand, what exactly you want the servo to do).

  what I then should use instead of the String object?

The String class from the Arduino framework can get you into memory trouble (to be exactly memory fragmentation). You can read Majenko's blog post about Arduino Strings for further explanations.

Instead you should use char arrays aka C-Strings. You create a buffer with a fixed length, that is big enough to hold the biggest chunk of data, that you need to process. Let's say you need at max 30 characters. Every C-String is terminated by a zero ('\0'). This zero also needs space in the buffer. So the actual buffer size is 31.

char string_buffer[31];

You can even directly initialize it with a string value:

char string_buffer[31]="Teststring";

You can use sprintf() to put a formatted string into the buffer. For example a string with a number:

sprintf(string_buffer, "Number: %d", 50);

will put the string "Number: 50" to the buffer and will terminate it with a zero.


Your memcpy is backwards.

SYNOPSIS
   #include <string.h>

   void *memcpy(void *dest, const void *src, size_t n);

So the line:

memcpy(data, dataTerminated, NUM_MFR_BYTES); //Copy the bytes into the new array

should be:

memcpy(dataTerminated, data, NUM_MFR_BYTES); //Copy the bytes into the new array


analogRead() returns an integer between 0 and 1023. Using 30 and 400 in the map() function, then passing in a value outside of that range will cause strange results. Here is a sketch to illustrate my point.

void setup(){

  Serial.begin(9600);

  // Prints -20 to 684
  for(int i = 0; i < 1024; i++){
    Serial.println(map(i, 30, 400, 0, 255));
  }
  Serial.println();

  // Prints -7 to 255
  for(int i = 0; i < 1024; i++){
    Serial.println(map(i, 30, 1023, 0, 255));
  }
  Serial.println();

  // Prints 0 to 255
  for(int i = 0; i < 1024; i++){
    Serial.println(map(i, 0, 1023, 0, 255));
  }
}

void loop(){}


You are speaking of porting. The arduino environment is built around a set of libraries and commands that are designed to abstract the low level access to a simpler high level language. In order to make arduino code work on a new microcontroller, you would have to rewrite and recreate the libraries using the low level access of your target microcontroller.

For example, Energia is a port of the Arduino libraries to the Texas Instruments MSP430 line of microcontrollers. Since not all features are the same, some code does not just drop in directly but additional code or libraries could be added to fix that. Even the Arduino IDE, the program used to write code and program the arduino was ported.

It would not be a trivial thing to port an entire library base.

As to your other questions, you would code your new microcontroller in any language it's programmer and compiler can use. Likely C or C++. Arduinos are typically programmed in C++. You should look into the manufacturer of your MCU to find out what software to use, and what libraries they offer. They likely do not offer something like the serial monitor right out of the box.


Check out https://learn.sparkfun.com/tutorials/xbee-shield-hookup-guide/example-communication-test
Essentially you need to set up Software Serial for your xbee to communicate on a couple of digital pins, instead of using hardware serial. When using hardware serial (the RX and TX pins) only one device works on it at a time, hence why you can't use the xbee and the serial monitor at the same time.


The problem was solved with a "soft restart" loop. Posts #10 and #11 are all I needed:
http://forum.arduino.cc/index.php?topic=49581.0


ISO C++ forbids taking the address of an unqualified or parenthesized non-static member function to form a pointer to member function

When you move the setPRUCallback function into your class you change the prototype (well, C++ changes the prototype) from:

void setPRYCallback( const std_msgs::Empty& toggle_msg) {}

to:

void setPRYCallback( ROSController *this, const std_msgs::Empty& toggle_msg) {}

That is now not what the callback registering function expects, and so it breaks.

By making the method static it removes that *this parameter, but also means that the function can only access static data within your class (variables also marked static) and there is only one copy of the function (and static variables) shared between all instances of the class (maybe not what you want).


Make Piano keys on Webpage create sound on Arduino (w/out Shield)

You are asking for something that sounds simple, but it's far from simple.

The security of modern web browsers is based on simple premise. Websites cannot in any way interact with the system of the user. Unless you are a hacker ant you are using an exploit you cannot make a website that will send data to the PC it's opened upon, or even read anything (like files and folders from hard drive) except the things that browser tells it (like what fonts are installed)

You can write a browser plugin that will break that rule, but it's a bad practice to deliberately make suck an awful backdoor.

Websites can only communicate with the server they were opened from. You can use AJAX made easy by a javascript library like jQuery. This means that You will have to write your own plugin to any of the existing http servers like apache (for php), or create your own server using for example flask framework (for python) and use it to communicate through serial protocol with the hardware.

The arduino code will be the simplest task in your project.

The code should read from serial a string value. Since You can only press one key at the time with a mouse you just need to read a value of key that was pressed like "12". Then play correct sound using for example a buzzer

The ethernet shield can help only by allowing you to install server on the hardware itself, connecting it to your wifi and forwarding it outside to be accessible by everyone on the web. For that I suggest using raspberryPi, omega2 or even esp8266 and not an arduino.


ArbotiX-M Problem uploading to the board

I figured why my board wasn't responding! Apparently, the power pin was connected to the 5V supply instead of usb. Silly me!


If you don't tell it to turn off, it behaves "as it wants". If you don't write a 0 on its pin, how can you force it to stay shut down?

If you want it to be in an off state, force it: in your setup function write

pinMode(13, OUTPUT);
digitalWrite(13, LOW);

No need to refresh it every loop, just in the setup.


It means "Micro Controller" - you know it as "Arduino".


Determing approximate bicycle speed for distancemeter

I have built many years ago a device nearly identical to what you describe. I did not have the additional requirement of a minimum speed of 10 kph, however. As noted in the comments, that is likely best resolved with GPS as you are detecting motion, not absolute speed figures.

I used "arduino gps library" as the search terms and found many options. One of them, TinyGPS++ appears to have what you require and much more:

  TinyGPS++ is a new Arduino library for parsing NMEA data streams
  provided by GPS modules.

  Like its predecessor, TinyGPS, this library provides compact and
  easy-to-use methods for extracting position, date, time, altitude,
  speed, and course from consumer GPS devices.

  However, TinyGPS++’s programmer interface is considerably simpler to
  use than TinyGPS, and the new library can extract arbitrary data from
  any of the myriad NMEA sentences out there, even proprietary ones.

I would definitely appreciate the "considerably simpler" aspect, as well as the "extract arbitrary data" portion, which seems specific to your project.

There may be other libraries that provide your objective, this was the first on the search returns.

The device I constructed used the common ultrasonic detector with a transmitter and receiver pair, coupled to a set of seven-segment LED display blocks. When the slightly-less-than-one-meter distance was presented, my device would trigger a pair of cameras. For your beep purpose, it would be straight-forward to redirect the camera trigger to a piezo speaker module or any other suitable audio device. I did not require GPS or other speed information.


How can I understand which arduino I need to run some code?

In this case, the description on Github says specifically that it is compatible with the Uno:

  Based on the work in
  http://www.instructables.com/id/Use-an-Arduino-with-an-N64-controller/
  here comes a comfortable library for usage with e.g. Arduino Uno.

If you know in advance that you intend to write a very large body of code, of which this library is only a part, you can anticipate needing an Arduino with more memory at some point, but an Uno will get you a long way there. And, with all due respect, the fact that you're asking this question also suggests that an Uno will be more than adequate.

Genuine Italian Unos just barely exceed U$D 20 and Uno clones are about 2/3 of that price. Some of the clones may not be quite up to quality of the genuine boards, but reputable board makers' products are usually quite good. The best advice I can offer would be to buy a genuine Uno for your first board, both for the most likely best experience starting out, as well as to support the folks who did the upfront work and released the design as open source. Then maybe branch out to other board-makers' products for price, or especially, for added features (assuming those are useful to you) that some of them have engineered into their versions of the product.

Update:

  My final goal is to put it into a Nintendo 64 so its size is really
  important. Something like this could be ok?
  kiwi-electronics.nl/beetle-arduino-leonardo

The Beetle's processor, AtMega32U4, has a similar memory complement as the Uno's AtMega328. In fact it has a little bit more RAM than the Uno. It should be quite doable to compile it for the Beetle.


I would suggest two things. First You could put electrical tape around the receiver in such a way that it will only pick up signals from a certain direction. Also you could use low and high pass filters to accept input only in the 38khz range(range of most infra red remotes).  Keep in mind that you will need a couple of rounds for it to work effectively.


Powering Arduino Pro Mini + Driving LED Strip

According to the schematics, the Pro Mini uses the MIC5205, which is a linear regulator.
Using it directly with 12V is not a very good idea, in terms of power efficiency, as it will dissipate 35mW vs 25mW provided to the ATMega board.

From this perspective, I'd recommend a step-down converter for powering the Arduino.

However it will not cause any damage, at least at room temperature, as the power dissipation is well within operating margins, see calculation at page 8 of the MIC datasheet.

Edit: detailed pros and cons, power wise.


Greyed out port for Raspberry pico in Arduino IDE - Ubuntu 20.04

I've come across this and this is how I worked around it (on Windows, but I suspect the problem and solution is the same).
A brand new Pico or one not programmed by the Arduino IDE does not have a serial port, which is why you can't see one. Arduino sketches are compiled with a serial port automatically, so once a serial port exists, it can be used for future uploads.
The Arduino solution is to use the 'Export compiled binary' option (for any sketch) and upload the UF2 file (which should be generated into the sketch folder) using virtual USB drive interface. When the sketch starts, the serial port will be available and can be used for future sketch uploads.
Another solution is to use an alternative Pico core. This one does not need the port selected, but will find and upload to a Pico in bootloader mode via the virtual USB drive.


Relay for controlling a water pump motor

Fairly cheap and quite reliable relays which operate at 5V (5mA to switch closed/open) can be had at a decent price. Mine have an upper limit of 10A, either 250VAC or 30VDC.


Limited to 1MP still captures with OV5642 ArduCam Mini + Arduino Uno

The Arducam Mini Shield is limited to 512kb frame buffer, so photos of larger resolution easily overflow the buffer. You can fit higher resolution photos onto the frame buffer by increasing the compression or adjusting other settings on the camera that reduce the file size of the resulting image (reduce saturation, windowing, etc).

To change the compression, adjust register 0x4407. The higher the number the more compression there is. The camera's default is 0x0C and the Arducam sample code sets it to 0x04.  myCAM.wrSensorReg16_8(0x4407,0x09);

To adjust other settings on the camera (including the ones listed above) check out the detailed list of camera registers at http://www.dragonwake.com/download/camera/ov5642/OV5642-DS.pdf

Also, Arducam is releasing the Arducam Mini Plus which has an 8 MByte frame buffer and is available on advanced order for $35 USD by contacting Arducam directly.


What are the Arduino hardware options for experimenting with IoT?

There are many options; which one is "best" for you I leave up to your own research, that could start here:
There's a list of Arduino's based on the SAMD21 that are supported by the FreeRTOS_SAMD21 library here; pick any one with WiFi and BLE.
There are probably a zillion clones out there that could also do what you want, and there is also a FreeRTOS port for the ESP32 (ESP-IDF FreeRTOS, and maybe other ones as well).


You get this memory leak because you overflow the variable right. This does not happen in the for loop itself even though this could be implemented more straight forward. But it's the while loop that doesn't come to an end (charBuf doesn't change and will not become 0) and in the second iteration n will be 1 initially (due to n++ at the end of the for loop). That causes the overflow at right[n] += charBuf[i];.

So: remove the while loop (and use strtok()).


Why echo "R" > /dev/ttyUSB0 doesn't work, but on the same PC Serial Monitor in Arduino IDE works?

I had the same issue.
After entering command that Majenko suggested:
stty -F /dev/ttyUSB0 -hupcl

I still wasn't able to send commands to Arduino nano.
Strangely, when I open Arduino IDE Serial Monitor and send command it works.
When I close it, I can send commands in terminal to Arduino for some time. Then it stops working again :/


How can I reference an object from another file?

The best way is to provide the myGLCD object as a parameter to the constructor:

touchButton::touchButton(UTFT &glcddev, int x, int y, int xs, int ys, char myuse) {
  x1 = x;
  y1 = y;
  xsize = xs;
  ysize = ys;
  use = myuse;
  glcd = &glcddev;
}

Then in your header you provide a:

private:
  UTFT *glcd;

Your library code then uses the glcd pointer to the object:

glcd->drawRoundedRectangle(...);

Note the use of -> since glcd is a pointer to the object (as created by the & operator when it was assigned in the constructor).

Of course, as Miagma mentions, you need to ensure that anywhere that references any UTFT functions or objects has the UTFT.h header included or it won't know what you're talking about.

You can also do the same with the UTouch class - pass that object as a parameter, then each widget can have its own routine to deal with the touch events.

You can see all this kind of thing in action in the same context in the Widget class of my DisplayCore system for chipKIT boards:

https://github.com/MajenkoLibraries/DisplayCore/blob/master/DisplayCore/DisplayCore.h#L464
https://github.com/MajenkoLibraries/DisplayCore/blob/master/DisplayCore/DisplayCore.cpp#L1587


Most libraries will either take one array of samples as input and then fill two other arrays of real and imaginary data, or it will take one array of samples and one empty array as input, and the sample data will be replaced by the real data and the empty array filled with the imaginary data.

You will have to first choose a library to use and then read the examples or documentation to see what the format of the functions are.


Interleave Assembly and Source for avr-objdump

First make sure you add -g to all your compilation commands.

Then you can run avr-objdump -S build/spi.elf (for instance).

Also I see you're missing the MCU definition in your link command. Without that it won't link in the proper C startup routines and your program will most probably not run.

Here is a makefile I use:

PREFIX=avr-
CC=${PREFIX}gcc
CXX=${PREFIX}g++
LD=${PREFIX}ld
AS=${PREFIX}as
OBJCOPY=${PREFIX}objcopy
OBJDUMP=${PREFIX}objdump

BIN=blink
MCU=atmega328p
OBJS=blink.o

CFLAGS=-g -mmcu=${MCU} -ffunction-sections -fdata-sections
CXXFLAGS=-g -mmcu=${MCU} -ffunction-sections -fdata-sections -fno-exceptions
LDFLAGS=-mmcu=${MCU} -Wl,--gc-sections

${BIN}.hex: ${BIN}.elf
    ${OBJCOPY} -O ihex -R .eeprom $< $@

${BIN}.elf: ${OBJS}
    ${CC} ${LDFLAGS} -o $@ $?
    ${OBJDUMP} -S $@ > ${BIN}.dis

install: ${BIN}.hex
    avrdude -C ./avrdude.conf -c usbasp -p ${MCU} -U flash:w:${BIN}.hex
 -qq

clean:
    rm -f *.o *.elf *.hex

fuses:
    avrdude  -c usbasp -p ${MCU} -C avrdude.conf -U lfuse:w:0xff:m -U h
fuse:w:0xd6:m -U efuse:w:0x05:m -qq


How to properly link an Arduino and its sensors

You could solder those modules to a prototype shield.  If you replace the header with a right-angle one (or even just bend the pins on the existing one) you could even mount it vertically to save space.

Prototype shield:

Right-angled headers:


In plain C, structs are identified by "struc tags", which do not live in
the same namespace as type names. Thus, if you declare

struct RGB {
    ...
};

a variable of this type should be declared as

struct RGB led;

In order to avoid the inconvenience of repeatedly typing struct, a
common idiom is to define it as a type:

typedef struct {
    ...
} RGB;

RGB led;

The Arduino environment, however, is based on the C++ programming
language. In C++ struct tags are types, and you thus do not need the
typedef:

struct RGB {
    ...
};

RGB led;

This is the recommended idiom in C++: just remove the typedef.


Your button is configured as an input with a pullup.  Therefore, except when the button is depressed to ground that input, this nested loop

while (digitalRead(button) == HIGH){
   lcd.setCursor(0,0);
   lcd.print("druecken");
}

will endlessly repeat, preventing execution from advancing.

Given that your question fails to state what you are hoping to accomplish it's not possible to make any corrective recommendations.  If you do want to make use of the button, you should probably first search and read the existing questions here having to do with debouncing.


Using C# Program to Interpret Keystrokes

The answer is actually, surprisingly, yes! C# requires .NET CLR for execution, I had assumed that .NET exists only in microsoft desktop land, but it has in fact been ported to microcontrollers and released open source as .NET micro, it can even run baremetal with no OS.

However this is not possible on an 8 bit regular arduino, it requires one of the larger 32 bit models. There is a prebuilt clone that has the .NET micro CLR framework ported to it on an STM32F4 cpu called the netduino

Unfortunately the footprint for .Net Micro is too large to run on a regular 8bit arduino and probably hasn't been built for 8bit systems. It is possible with the arduino Due (in theory) and on other micrcontroller platforms that support .NET micro to run C# code outside of the windows platform.


Arduino Sketch: NodeMCU compilation error

Do a full uninstall of Arduino, then delete the Arduino folder and
  Arduino15 (back them up first if you have any sketches in there!!!!),
  as well as any Arduino folders under Temp. Make sure the folders and
  all contents are really gone, reboot and try again if not. Then, do a
  clean install of the IDE.

Cited from here.


Recommendations for limit switches for Arduino

A $2 microswitch with a roller would be OK for a million revs or so.

You would put a little ramp on the diameter and use it to trigger the switch.

Non-contact magnetic or optical could be better for more cycles or faster operation.


First, you are creating/destroying the AccelStepper stepper1() object at every call. This is not right, as the library can no longer keep track of the stepper position and state.

The stepper object should be created in the global scope (that is, outside of setup() or loop()).

Second, you can call stepper1.setEnablePin(enPin) and stepper1.setPinsInverted(false, false, true) after you create the object to have the AccelStepper library control the enable pin and to set the enable pin to operate active-low. Then the driver is enabled or disabled with calls to stepper1.enableOutputs() and stepper1.disableOutputs(). In practice, you would not disable the driver except for power saving, as the stepper can no longer hold it's position when the outputs are not enabled. It will lose it's position.

Third, do not set the speed to a negative value. The direction of the stepper is determined by the library based on the current position and the desired end position. When the library is created, the position is zero. You can set the new position in several ways:

stepper1.move(): Set the target position relative to the current position. This means to go backwards you pass this function a negative value. It will add this (negative) number to the internal target position, and then run() will work to get it there.
stepper1.moveTo(): Set a new absolute position. If you initially set the position to 100 and move there, then set it to 50, the stepper will run in reverse to be able to reach position 50. If you start in position 0 and run to 50, it will run forward. If you start at 0 and set to -50, it will run in reverse to get there, and so on.


Help with LCD's menu and seeing values continuously

As Gerben implied in a comment, menuChangeEvent is called only when the menu selection changes.  Thus, your voltmeter readout will print only whenever you change the menu selection to Item2SubItem3.  The code shown below illustrates how to modify your loop() so that it checks the menu selection once per second.  Each second the main loop will do whatever function is currently selected, such as displaying a current voltmeter reading.  Note, you can make the menu decoding shorter and less tedious as shown in the answer, and can put variable declarations near where they are used instead of in random places.

void setup() {
}  // setup()...

// DC voltmeter reading
void volt () {
  const float vPow = 4.7, r1 = 100000, r2 = 10000;
  lcd.clear();
  float v = (analogRead(0) * vPow) / 1024.0;
  float v2 = v / (r2 / (r1 + r2));
  lcd.setCursor (0,0);
  lcd.print("DC Voltmeter");
  lcd.setCursor (0,1);
  lcd.print (v2);
  // Don't delay(1000) since loop() takes care of delay.
}

long int second = 0;
uint8_t itemcode = 0; // Will be number nm for Item n, Subitem m
int passnumber = 0;
void menuChanged(MenuChangeEvent changed) {
  MenuItem menuitem = changed.to; //get the destination menu
  String itemname = menuitem.getName();
  lcd.clear();        // Make printing spaces at line ends unnecessary
  lcd.setCursor(0,1);         //set lcd printing position = second row
  if(newMenuItem.getName() == menu.getRoot()){
    lcd.print("Main Menu");
    itemcode = 0;
  } else {
    lcd.print(itemname);
    itemcode = 10*(itemname[4] & 7);
    if (itemname.length() > 5)
      itemcode += itemname[itemname.length()-1] & 7;
  }
  passnumber = 0; // Actions can test passnumber if they like
  second = 0; // Cause actions to take place now
}

void loop() {
  long int now = millis()/1000; // Get elapsed-seconds
  if (now == second) return;    // Only do stuff once per second
  // Update to current second and do chosen menu item
  second = now;
  switch (itemcode) {
  case  0: break;
  case 10: break;
  case 11: break; // Fill in with code for different cases
  case 12: break;
  case 20: break;
  case 21: break;
  case 22: break;
  case 23:    // Item 2, subitem 3, read voltmeter
    volt();
    break;
  case 30: break;
  case 40: break;
  }
  // You can test passnumber to control for cases that only go once
  ++passnumber;
} // end of loop()

Edit: I moved the declaration of second and added second = 0 within menuChanged() to decrease latency between a menu item being selected and its action taking place.  Without second being zeroed in menuChanged(), up to a second could pass between an item's selection and its action; latency would average 0.5 seconds, which is undesirable in a user interface.


This is due to a specific feature of the AVR microcontrollers, where the
same register (PORTB, PORTC or PORTD) is used for controlling both
the output value of the pin and its optional internal pullup resistor.
The command digitalWrite(pin,HIGH) sets to 1 the bit of this register
corresponding to the selected pin.

If the pin is set to INPUT (which is the default), the effect of
digitalWrite(pin,HIGH) is to turn on the internal pullup.
If the pin is set to OUTPUT, the same command sets the output to
HIGH.

The internal pullup is about 30 kΩ, which lets flow a very small
current through the LED. You may notice that the voltage at the pin is
5 V if nothing is connected to it, but significantly less when the
LED is connected. Notice also that the preferred way of enabling the
pullup is pinMode(pin,INPUT_PULLUP).


You are trying to measure with 2 ultrasonic sensors at once. You cannot do that so easily. You need to measure sequentially for 2 reasons:

The ultrasonic sensors might get confused by the others signal
You will miss the pulse of the one sensor, while you are reading the pulse of the other via pulseIn().

So the order of actions is like this:

Trigger sensor 1
Read sensor 1 with pulseIn()
Trigger sensor 2
Read sensor 2 with pulseIn()


Serial - Send data to Arduino while Arduino sending data

Following up on what Nick Gammon says, don't try to use the serial output to debug serial.  Perhaps try using the built-in LED instead; you can use an oscilloscope to find out how much time it is spending reading characters.

The following is how I've been reading a line at a time using non-blocking operations:

const int SERIAL_BUFFER_LENGTH = 100;

// The +1 assures we'll always have room for null termination
char g_serial_buffer[SERIAL_BUFFER_LENGTH+1];
int g_char_count;         // index into serial buffer

void setup() {
  Serial.begin(9600);  // or 115200 if your host supports it
  pinMode(LED_BUILTIN, OUTPUT);
  digitalWrite(LED_BUILTIN, LOW);
  g_char_count = 0;
}

void loop() {
  while(Serial.available() > 0) {
    digitalWrite(LED_BUILTIN, HIGH);
    char c = Serial.read();   // won't block because Serial.available() > 0
    if (c == '\n') {
      g_serial_buffer[g_char_count] = '\0';  // null terminate
      process_buffer(g_serial_buffer);
      g_char_count = 0;
    } else if (g_char_count < SERIAL_BUFFER_LENGTH) {
      g_serial_buffer[g_char_count++] = c;
    }
  }
  digitalWrite(LED_BUILTIN, LOW);
  Serial.print(".");
}

// process_buffer: do whatever it is you intended to do with a
// line of received text...
void process_buffer(char *buffer) {
}


A look at HardwareSerial_private.h shows incoming bytes are always read (interrupt-based), regardless of what your code is doing. So we can't set up a hardware interrupt to notify us when the chip's RX register has overflowed, because such an interrupt would depend on overflow flags but these flags never become set because, like I said, bytes are always read. It also shows that while all incoming bytes are read, not all are added to the 64-byte Serial buffer i.e. a byte may be read but if the buffer is full, nothing else happens; it is simply read to clear hardware flags. So the only (direct) way I can think of is to constantly poll Serial.available() in loop() to check if the number of bytes available for reading is equal to 64. If this condition yields TRUE, then you may safely conclude that the Serial buffer is full and about to overflow. This should suffice:

    void loop(){
        //your code
        if (Serial.available() == SERIAL_RX_BUFFER_SIZE){ // Just to be general, 64 bytes in most cases
            //buffer is overrun, do what u will
        }
    }

You could make some changes to HardwareSerial_private.h to get something like the overflow() method of SoftwareSerial. The relevant lines are:

    if (i != _rx_buffer_tail) {
        _rx_buffer[_rx_buffer_head] = c;
        _rx_buffer_head = i;
    }

The snippet above ensures that the current write position is not equal to the tail of the ring buffer (i.e. if we are about to overwrite a character in the buffer), before writing the incoming byte to the buffer. An else block could be added to set some global variable to indicate overflow. This global variable would have to be cleared when Serial.read() is called.


It is probably because you are using the only Serial to communicate to both the devices - your PC and XBee. At any instant, you can communicate to only one device. So you might need an extra serial to get you go.

And, may be due to this conflict you can see TX led blinking. May be it's communicating with anyone of them, and the other one is receiving garbage.


Tiny RTC module doesn't work properly when connected to an Arduino Uno together with 16x2 LCD

An I2C scanner sketch can help to identify the actual addresses in use. I would use a sketch like on this page https://playground.arduino.cc/Main/I2cScanner or on this page http://gammon.com.au/forum/?id=10896&reply=6#reply6 . Or google 'arduino i2c scanner'.

Hook up the RTC by itself and run the scanner, then hook up the LCD by itself and run the scanner. The output will be on the serial monitor. If the devices have the same address, then that is your problem.

If one of the devices does not show up at all, then perhaps it is defective.


Fastest communication between Arduino and PC

Switch to using SerialUSB instead and use the other USB port. The baud rate is meaningless then - it runs at the speed of the USB port, which is a lot faster than serial (Linux reports it as 480Mbps, though I can't see an 84MHz chip doing that...).

void setup() {
    SerialUSB.begin(115200); // The number is irrelevant but it needs something in there
}

void loop() {
    SerialUSB.println(millis());
    delay(100);
}

For greater throughput you could devise some packet-based binary protocol to optimize your data flow to use less bytes.


Long range wireless communication between two arduinos?

Your range of options depends strongly on what your budget is, what country you are in, whether you are a licensed radio operator, whether cell service is available, etc.

If you aren't licensed:

In the USA, unlicensed (or lightly licensed) radio options include GMRS (General Mobile Radio Service), FRS (Family Radio Service) and CB (Citizens band radio).  GMRS and FRS range typically is at most a few miles – ten miles is too much to hope for.  CB range would be ok but CB radios often are fairly large and antennas would be large, eg nine feet long.  I don't know whether it is legal to transmit digital data over GMRS/FRS/CB radio.

If you are licensed:

2-meter band radio might be a good choice.  Frequencies are 144 MHz to 148 MHz in the Americas and Asia, or 144 MHz to 146 MHz elsewhere.  Per wikipedia,

  The license privileges of amateur radio operators include the use of frequencies within this band  for telecommunication, usually conducted locally within a range of about 100 miles (160 km).

If cell service is available:

Consider a GSM shield, eg the Arduino GSM Shield.

To access the cell network you would need to buy a SIM card for each GSM shield.

GPRS (General Packet Radio Service) on GSM provides data rates between 10 and 240 kbs.  Other GSM protocols may be faster or slower.  Data rates depend also on whether 3G service is available or only 2G.


How to send Arduino Yún Post Request to localhost?

There needs to be an empty line between HTTP headers and data.

You need to end the Content-Length header line with

client.println(data.length());

so that the client.println(); inserts an empty line.


Why does my wired button always read HIGH?

You read the button once, in setup(). The function is not called every time the variable's value is read, only when the line is executed and the variable assigned to. Move the digitalRead() call and assignment into loop(), before you check the variable's value.


The analog read is not giving the correct waveform as that of an oscilloscope

Your sampling rate is far too low for the signals you are looking at; you're not getting enough data points for drawing something that looks like the original signal.
The Arduino library's analogRead(), while slow, can do better, up to about 9000 samples/s; the ADC in the atmega2560 in free-running mode can do about 75000 samples/s at 8 bits resolution. This would require programming it at the register level.
There is only one ADC, so if you want 16 channels, this leaves about 4700 samples/s for each channel. In that configuration, however, the first measurements aren't valid and the second ones should be used, further reducing the sample rate per channel to about 2300 samples/s.
With a perfect reconstruction filter, this would limit you to measuring signals up to only 1150Hz.
All this doesn't even consider the time it takes to store or transmit the results.
So, an Arduino mega 2560 will not do for making a usable 16-channel oscilloscope for your signals; it's not even close.


For strings with a fixed format like that (I assume it's a fixed format...) I normally just do a manual strtok of the whole thing into a set of pointers. No need for a loop.  You can then just test the last one to see if the whole thing tokenised properly, since if anything before that fails then all other subsequent ones will fail and the last one will have failed.

void setup()
{
    char input[] = {"id,port,password,ssid,delay,flag,class,category"};
    char *ptr;
    Serial.begin(115200);

    char *id = strtok(input, ",");
    char *port = strtok(NULL, ",");
    char *password = strtok(NULL, ",");
    char *ssid = strtok(NULL, ",");
    char *delay = strtok(NULL, ",");
    char *flag = strtok(NULL, ",");
    char *class = strtok(NULL, ",");
    char *category = strtok(NULL, ",");
    if (category != NULL) { // Everything up to and including category worked
        Serial.print("Flag: ");
        Serial.println(flag);
    }
}

void loop(){}

As an aside: if there is ever a chance any of the fields could be empty ("flag,,category" for example) then you should use strsep() instead of strtok() as I detail in my tutorial on splitting strings in C.


If you can use Wi-Fi, I suggest you to use ESP8266-01, it's cheap and usefull ! With this chip you can send all data to your server!


The most efficient way is to read the file byte-by-byte into a small character array until you get a comma or the end of file - ignoring any characters that aren't of interest (line feeds, etc).

Then for each chunk that you read you then convert it to an integer.

For example (untested):

char temp[5] = {0}; // should be more than enough
int pos = 0;
int bno = 0;

const char *hexchars = "0123456789abcdefABCDEFx";

while ((int ch = myFile.read()) >= 0) {
    if (ch == ',') { // We found a comma
        logo[bno++] = strtoul(temp, NULL, 16); // Base 16 conversion
        pos = 0;
        temp[0] = 0;
    } else if (strchr(hexchars, ch) != NULL) {
        if (pos < 4) {
            temp[pos++] = ch;
            temp[pos] = 0;
        }
    }
}

Of course, you have to know how big the logo array has to be beforehand.

One does, though, have to ask "Why are you storing a graphical logo as a textual representation of binary data" in the first place?  It would be far easier to just store it as a simple binary file and read the data directly into the logo array with a single File::read(void *buf, size_t nbyte); function call.  Using text as an intermediate format is both wasteful and needlessly increases complexity massively.


I would go for a normally open read switch (should cost >$0.1) and a magnet on the shutter (again should cost >$0.1).  There are formulas to work out the distance that the reed switch will operate at, and it depends on the magnet, but the common ones are about 40mm.
(If you can wait 2 weeks for delivery you can get the parts off AliExpress.com)


Powering Arduino Uno and Ardumoto Motor Driver Shield

Do not supply power to both the Arduino barrel jack input and VIN on the shield!

There goes the simple answer. Choose one.

If you power the system through arduino barrel jack input, you will have polarity protection, but the voltage output on VIN pin (which also used by Ardumoto shield) is slightly lower, about 0.6V lower than the input voltage because of the voltage drop on the protection diode.

If you have want to differentiate the supply for Ardumoto and Arduino (as described on your plan), you have to tamper the Ardumoto shield to isolate both supply. Although I never try it myself, it seems possible if you understands how L298 works.


Getting Bluetooth addresses of connected devices via Arduino Uno?

The HC-05 has an AT command, AT+BIND?, that will tell you which slave device it is connected with currently. Since you can connect to one device only at the same time, your array is going to be a very short one.

AT+INQ will provide you with a list of nearby devices, to which it can connect.


I am looking into putting sound files onto an Arduino Nano without a microSD card

Uno and Nano uses the same Atmel MCU, so pin 11 is the same on both.
And a for the speakers, Arduino CAN'T driver 8ohms load! You need a amplifier.


Conditional compilation depending on sizeof(double)

The double data type is almost universally 8-bytes long, so you could
simply
#if !__AVR__
# define HAS_64_BIT_DOUBLE
#endif

Gcc provides a more specific macro though: __SIZEOF_DOUBLE__, which
has the same value as sizeof(double). But I do not know whether it is
provided by other compilers.


Unable to read data with 16 serial clock cycles

This is not an answer to your question but I cannot add it as a remark since it involves code.

You can greatly reduce your code by using for loops, e.g.:

   pinMode(5, OUTPUT); //LED 3
   pinMode(6, OUTPUT); //LED 4
   pinMode(7, OUTPUT); //LED 5
   pinMode(8, OUTPUT); //LED 6
   pinMode(9, OUTPUT); //LED 7
   pinMode(10, OUTPUT);//LED 8

to

   int n;
   for (n = 5; n < 11; n++)
   {
      pinMode(n, OUTPUT);
   }

And

digitalWrite(5,bitRead( myValFromTempSensor,0));
digitalWrite(6,bitRead( myValFromTempSensor,1));
digitalWrite(7,bitRead( myValFromTempSensor,2));
digitalWrite(8,bitRead( myValFromTempSensor,3));
digitalWrite(9,bitRead( myValFromTempSensor,4));
digitalWrite(10,bitRead( myValFromTempSensor,5));

to

int n = 0;
for (n = 0; n < 6; n++)
{
    digitalWrite(n + 5,bitRead( myValFromTempSensor, n));
}

And

  digitalWrite(5,0);
  digitalWrite(6,0);
  digitalWrite(7,0);
  digitalWrite(8,0);
  digitalWrite(9,0);
  digitalWrite(10,0);

to

int n;
for (n = 5; n < 11; n++)
{
    digitalWrite(n, 0);
}

Instead of hardcoded values 5 and 11 you can use defines, e.g.

#define LED_MIN 5
#define LED_MAX 11

and change

for (n = 5; n < 11; n++)

to

for (n = LED_MIN; n < LED_MAX; n++)


Although not strictly required, maybe use parentheses around millis() - sendDataPrevMillis for readability;
I guess you will have initialised sendDataPrevMillis to 0 but
the first time you assign sendDataPrevMillis to millis() some time will have elapsed since you evaluated. So calling millis() twice will give different results. That makes it less easy to see what is going on.

Suggestion to try:
long HALFHOUR = 30 * 60 * 1000L;

if ( (millis() % HALFHOUR ) == 0L ) {
    //measure and send
    //....
}

Hope this helps.
NB: % is what is called the 'modulo operator' see: https://www.geeksforgeeks.org/modulo-operator-in-c-cpp-with-examples/


One arduino can control multiple relays. Beyond that, how many you need will depend on the details of your project.

Once you have a working example, you can build it using less expensive alternatives than regular Arduino boards.


Problem with a function having a parameter with a default value

It's just a failing of the Arduino build process to generate prototypes (function declarations) for functions that have default argument values.  There's otherwise nothing wrong with what you're doing.  Not in my opinion anyway.  The build process sometimes chokes on function or class templates as well.  The answer to these sorts of problems is probably that these features are not considered part of the Arduino "language".
Just a reminder: In C++ a function declaration needs to have been seen in order to generate a call to it.  A definition will serve as a declaration.  In either case, one must have been seen before the call site.  Generating declarations where needed is, perhaps, the greater part of what the Arduino build process does that can be said to make the Arduino "language" different from plain C++.
The following were generated by working out of /tmp/default-param with the "input" being default-param.ino, running:
arduino-cli -b arduino:avr:uno build --build-path /tmp/build

and inspecting /tmp/build/sketch/default-param.ino.cpp which I'm calling "output".  You can use the same process if you want to see exactly what the build process is doing to your code.
Non-default argument
This input:
void setup() {
    func(11);
}
void loop() {}
void func(int xyzzy) {}

generates:
#include <Arduino.h>
#line 1 "/tmp/default-param/default-param.ino"
#line 1 "/tmp/default-param/default-param.ino"
void setup();
#line 4 "/tmp/default-param/default-param.ino"
void loop();
#line 5 "/tmp/default-param/default-param.ino"
void func(int xyzzy);
#line 1 "/tmp/default-param/default-param.ino"
void setup() {
    func(11);
}
void loop() {}
void func(int xyzzy) {}

The build process has inserted a valid C++ function declaration prior to the call site, so the compiler is happy.
With default argument
But this input:
void setup() {
    func(11);
}
void loop() {}
void func(int xyzzy = 7) {}

generates:
#include <Arduino.h>
#line 1 "/tmp/default-param/default-param.ino"
#line 1 "/tmp/default-param/default-param.ino"
void setup();
#line 4 "/tmp/default-param/default-param.ino"
void loop();
#line 1 "/tmp/default-param/default-param.ino"
void setup() {
    func(11);
}
void loop() {}
void func(int xyzzy = 7) {}

No declaration prior to the call site this time, so the compiler is not happy with this generated code.
Build process
The build process is a rather ugly... process... that scrapes the output of the compiler and generated ctags to build include paths and to try to generate forward references for things.  Sometimes, it just gets it wrong.  I'm not sure what the exact error is in the build process, but it is probably just a failure to match the error caused by calling an undeclared function with its matching entry in the ctags.  You can try reading through the build process documentation to make sense of this.  Ultimately though, you may have to read the source to arduino-cli/arduino-builder to get to exact cause.
Non-.ino (and non-.pde) files more or less go through the build process unscathed.  So, if you really want default arguments, you can make use of and .h file for your function prototype/declaration and a .cpp file for its body and follow the normal rules of C++.
Using your own declaration
You can just make your own declaration for it.  Doing so makes it not detect an error on that line.
void func(int xyzzy = 7);

void setup() {
    func(11);
}
void loop() {}
void func(int xyzzy) {}

Output:
#include <Arduino.h>
#line 1 "/tmp/default-param/default-param.ino"
void func(int xyzzy = 7);

#line 3 "/tmp/default-param/default-param.ino"
void setup();
#line 6 "/tmp/default-param/default-param.ino"
void loop();
#line 7 "/tmp/default-param/default-param.ino"
void func(int xyzzy);
#line 3 "/tmp/default-param/default-param.ino"
void setup() {
    func(11);
}
void loop() {}
void func(int xyzzy) {}

As you can see it generates a proto type for whatever reason.  But not one that conflicts with your own.

It is probably better if you want to make use of default arguments to just use headers and .cpp file for those functions that have them so that you're not subject to changes in the ability of arudino-cli/arduino-builder to handle them.


I see one problem with the global structure of your program; everytime loop() is run, it:

checks if an SMS is present, and gets the originating phone number if present, otherwise it just goes on, ie smss() function returns without modifying remoteNumber
send an SMS to remoteNumber

One problem here is that your loop() will repeatedly try to send an SMS to the same remoteNumber even if no SMS was received; actually, to solve this issue, you should modify smss() to:

either wait (forever) for an SMS to be received and return only in this situation
or return a value (eg bool) that indicates whether an SMS was received or not; then an SMS should be sent if and only if an SMS was just received.

Here is an example:

void setup()
{
    GSM and GPRS initialization
    Connection to server
}

void loop()
{
    if (smss())
    {
        Reading the txt file content in server

        sms.beginSMS(remoteNum);
        sms.print(txtMsg);
        sms.endSMS();
    }
}

bool smss() // I just want phone number
{
    if (sms.available())
    {
        Serial.println("Message received from:");
        sms.remoteNumber(remoteNum, 20);
        Serial.println(remoteNum);
        sms.flush();
        Serial.println("MESSAGE DELETED");
        return true;
    }
    return false;
}

Note that this code does not integrate error support as it should; indeed sms.remoteNumber() may return error codes (any value >1), in which case you should consider no SMS was received at all.


Declare for loop as an array of variables

You don't even have to add any lines, just modify a couple!

unsigned long ultrasoundValue [2]; //creates an array of unsigned longs of size 2

...and inside your for loop:

ultrasoundValue[i] = ping(i);

It appears you are acquiring 2 separate ultrasound values. If you'd like to store multiple sets of these 2 values, you could use a two-dimensional array:

unsigned long ultrasoundValue [10][2]; //an array of 10 pairs of long unsigned values

...and you could modify your for loop to have a pair of nested for loops:

 for (int i = 0; i < 10; i++)
 {
   for (int j = 0; j < 2; j++)
   {
      ultrasoundValue[i][j] = ping(j);
      //do whatever else
   }
 }


Problem with using pure C code to program default UART (UART0) in Arduino Mega

I suggest to use existing code and copy that or use that.

This is the Arduino HardwareSerial : HardwareSerial.cpp
You can find more code at avrfreaks.net. Click on "Projects", search for "uart" and "usart" and try to find code that is compatible with the ATmega2560. Some projects have buffers and many functions, others are very simple.

The result might not be compatible with other Arduino code (for example with interrupts). Why do you not want to use the Arduino Serial library ?


ledPin is not defined. You should define it somewhere.
if (state == 1 && reading = LOW){ is not valid syntax. You need to use == not = to compare values.


avrdude: stk500_rcv :programmer is not responding

try this site: https://github.com/Makeblock-official/Makeblock-USB-Driver/ , it works for me. This is a driver for arduino, and command for bash


ESP8266 problem with recieved data trasmission via TCP

You assume all 5 bytes of 959\r\n are received by the server at the same time. The data is sent byte after byte, based on the client.print(data) in the ESP code and assuming the underlying library doesn't buffer bytes before transmitting, so there's no way they'll arrive at the server simultaneously. Most likely, your first pass with conn.recv(1024) grabs the first byte 9 and times out. And then on the second pass, the others (at least 2) arrive and are read. The newline between the packets is typical Python 2 print behaviour.

What you need to do is parse the data at the server. Basically read data till you get CRLF i.e. \r\n, which is a good enough delimiter and you're sending it already anyways, and then use that to know when to write to your database.


Trouble using lcd.readButtons() in RGBLCDShield library

IMO, your post doesn't provide enough information to allow definitive problem diagnosis.

Why do you say noInterrupts(); at line 5?  Some versions of the Wire library might be interrupt driven[1].  If interrupts were off, such a library wouldn't detect any button presses on a TWI-interfaced shield like Adafruit's RGBLCDShield.

[1]: Per arduino.cc's WireLibraryDetailedReference page,  “"The AVR TWI is byte-oriented and interrupt based...." (section 21.6 on p. 224) ... The TWI module sends an interrupt when it finishes, to notify the processor of the change in conditions ... However, notice that the Wire library has blocking I/O. ” [Ie, the usual Wire library doesn't take advantage of TWI interrupts.]


How can i develop a fish tank automation using arduino

You're starting from the wrong end of the problem (the electronics).
First, you need to decide the requirements for your system.

Write down what your system is supposed to do: measure something? When & how often? Save or display the measurements? Control something based on the data? How precise must that control be (e.g. +/- .5 degC) (precision can be expensive)? Control something based on something other than measurements (except, perhaps, time?

Once you understand the requirements, then you can write down the steps the system should take to meet them; it doesn't need to be code (and probably shouldn't be, just yet).

Decide on what to measure and how to measure it. Can't figure out a sensor for something? Maybe you can infer it from something you can sense. Or perhaps learn how quickly or how often that 'something' goes out of spec and restore it without a measurement (e.g. you presumably already know how often and how much to food to dispense).

Now you can start thinking about electronics, sensors, and code, having a pretty good idea of what you will need to know, to acquire, and to create, to build your project (whether or not you'll be expected to actually build one).

This is an Engineering approach to design and it is almost certain your project is intended to show that you know how to do this, much more than to show you can run a fish tank.


Reading I2C sensors with a timer interrupt

Try putting sei(); at the start of the ISR. I think I2C needs interrupts enabled to work.


Which Arduino is the most suitable for my project?

Both Mega 2560 and Due can handle 4 channels of 1,440 samples per second A-to-D and the least significant byte of the system time stamp sent as a continuous stream of vectors through the USB port to Linux.

In the lab I train at, we see almost no variance in time increment between samples or between receiver read operations, indicating that the bottleneck is our deliberate delays between samples.

The Due is running at full resolution too and communicates via the native port. The receiver process is running in normal user process priority, not boosted for real time.

We use C++ for both endpoints, the embedded Arduino code and the receiver, but the C++ on the Arduino side runs just as fast as the same loop in Arduino sketch language. Python low-level reads are generally able to handle this same level of throughput with ease too, so it is not likely that your hardware or speed goals that are the problem.

I can see a few design issues right away.

Don't use libraries for what one can do in just a few low level lines of code.
Don't place numbers in strings. Keep them as numbers.
Send the numbers as messages placed carefully into byte arrays using bitwise operations.
Don't convert raw samples to voltages on the Arduino. That can be done in the receiver or elsewhere on the Linux side.
Most importantly, find the various code examples that people posted on the Arduino blogs when testing USB baud rates (speed).

The lab engineers started with that speed testing code, replicated the throughput published with it, and then added A-to-D conversion and other features one step at a time.

It is recommended that you place the code under version control and then, with each change, test the speed again. That way you'll notice any bottleneck you introduce immediately and can see the exact changes that must have caused it.


How do I send multiple variables via stream to Unity?

What you need to do is define a communication scheme/protocol. You appear to be using the Serial UART via USB.

Your first example has a simple scheme its simply the ASCII representation of the variable followed by a newline. i.e. :

float x = 123.45;
Serial.println(x);

this simply outputs

"123.45\n"

you could continue this pattern

float x, y, z,
... // assume x, y and z have values in them
Serial.print(x);
Serial.print(' ');
Serial.print(y);
Serial.print(' ');
Serial.println(z);

this outputs something like:

"123.43 23.34, 42.24\n"

then your receiving code will do do something like

string line = stream.ReadLine();
string[] parts = line.Split(' ', StringSplitOptions.RemoveEmptyEntries)
float x = float.Parse(parts[0]);
float y = float.Parse(parts[1]);
float z = float.Parse(parts[2]);

but this is very inefficient, since the arduino needs to convert the float to an ASCII string, then transmit that over the serial port, where its read on the other side, then parsed back into a float. One doesn't need to do this, you can do in binary, it won't be human readable, but it will use much less transmission space.

float x, y, z; // assume these are valid
Serial.write(&x, sizeof(float));
Serial.write(&y, sizeof(float));
Serial.write(&z, sizeof(float));
// n.b. one should write an end of message here or something else to frame the data

and on the other side

byte[] data = new byte[12];
stream.Read(data, 0, 12);

float x = BitConverter.ToSingle(data, 0);
float y = BitConverter.ToSingle(data, 4);
float z = BitConverter.ToSingle(data, 8);

You will generally also want some way to frame the data, so you might want to start with a simple message header, i.e.:

struct head
{
  int length;
  int code;
};

and you write it like:

head header; //assume this is valid
Serial.write(&header, sizeof(header));

then you can write you message.

You might also want to implement some sort of checksum, so you can verify that you got the data correctly.

You can create multiple message structures this way, i.e.

struct vect3d
{
  head header;
  float x;
  float y;
  float z;
}

just fill and send

vect3d v3;
v3.head.length = sizeof(vect3d); // one could subtract sizeof(head) off so the reader can always read the first 8 bytes and read the rest of the message from there
v3.head.code = VECT3D; // assume this is defined somewhere
v3.x = 123.5;
v3.y = 23.4;
v3.z = 42.24;

Serial.write(&v3, sizeof(v3));

On the other side one would read in the first 8 bytes, then read in the rest of the message based on the length, and parse it based on the code.


Consider using a Sharp Distance Sensor in addition to your shoot / confirm-hit inferred LED & receiver.

This Sharp distance sensor is specified to detect objects that reflect IR light from 100 cm-500 cm.

  How can I change the range of an IR transmitter with as little
  hardware as possible, or at best, completely in software?

I believe the sensors produce an analog output that can feed into an Arduino's ADC.  So software (by itself) can be used to adjust the threshold distance.

Similar devices I have used have a narrow sensing field.  They only reported the distance to objects directly in front of them.  Also, I found they were effected by defective (burning out?) florescent light sources.  We assumed failing florescent light sources produced IR radiation similar in frequency as used by the sensor's IR emitter.  Also, the analog output is slightly stair stepped in the unit we tested.  I say this in case you were expecting to use increase relative accuracy of several readings if not precision of any given reading.


How to send volume +/- on Mac/OSX from Leonardo

Could you just untick the "Use all F1, F2, …" in System Preferences -> Keyboard?

Just wondering if that would be an option and if doing so would create the desired outcome.


activate a relay with two esp8266 -12e pins

That is not a good idea.

Isolating the relay from the IO pin is not just about the current limit of an IO pin, it's also about preventing back-EMF spikes from the relay coil(s) from damaging the delicate internals of the chip.

Instead you must at least use a transistor and a back-EMF protecting diode.

However - if you did want to theoretically have two pins safely controlled to provide double the current (though I stress again, do not do this for driving a relay), it is possible.

But it's not straight forward.

It's not possible on the ESP8266 to use port manipulation to make two pins change state at the same time. However it is possible to go via a third state that makes it safe.

Note: this will only be "safe" for IO pins that do not do strange things at bootup, and many of the pins on the ESP8266 do strange things.

IO pins actually have three states, not two:

High
Low
High Impedance

The latter is the state the pin is in when in INPUT mode. And we can use that to our advantage.

When in High Impedance mode it's like the pin is disconnected.  So we could:

Make sure both pins are in INPUT mode
Switch one pin to OUTPUT and set it to the desired state
Switch it back to INPUT mode (keeping the desired state latched)
Switch the other pin to OUTPUT and set it to the desired state
Set the first pin back to OUTPUT mode again.

This can be slightly compressed as we don't really need to set both pins to INPUT at the start, only one.  So here's some code that might do it:

void digitalDoubleWrite(int pina, int pinb, bool level) {
    pinMode(pina, INPUT);
    pinMode(pinb, OUTPUT);
    digitalWrite(pinb, level);
    pinMode(pinb, INPUT);
    pinMode(pina, OUTPUT);
    digitalWrite(pina, level);
    pinMode(pinb, OUTPUT);
}

You might ask why we'd want to switch to OUTPUT just to latch a level into the pin. Well, that's because of a quirk of the Arduino API. A historical artefact that is lingering in there to this day:

digitalWrite() on a pin set to INPUT mode was used to turn the internal pullup resistor on and off

It's actually how the AVR's IO ports control the pullup resistors internally, and that has most often been copied in software for other chips to maintain backward compatibility with old code. So as a result we have to switch to OUTPUT mode so that the API code knows that we mean to set the output latch state and not the pullup resistor state.


ESP8266 NodeMCU first WS2812 LED lights up green

So here comes my solution: I was playing around with NeoPixelBus by Makuna and the examples. I noticed in one of his examples, it said:

// You can also use one of these for Esp8266,
// each having their own restrictions
//
// These two are the same as above as the DMA method is the default
// NOTE: These will ignore the PIN and use GPI03 pin
//NeoPixelBus<NeoGrbFeature, NeoEsp8266Dma800KbpsMethod> strip(PixelCount, PixelPin);

So I tried outcommenting that line and used that instead, and then it worked! I've always used Neo800KbpsMethod whenever I saw NeoPixelBus being used, because that was what other people did. Notice it also said:

These will ignore the PIN and use GPI03 pin

That pin is the RX pin on my board. No other example I have seen, has used the RX pin on the board.
After 6+ hours of constant troubleshooting, I can finally power on my strip and control each LED!


AT command XBee from atmega to disable DIO5 (associated led)

finally I solved the problem with this code:

uint8_t atdCmd[]={'D','5'};
uint8_t value[]={4};///pongo DIO5 a output LOW
uint8_t length=1;
AtCommandRequest atRequest = AtCommandRequest(atdCmd, value, length);
xbee.send(atRequest);

The problem was that I tried to put command with 5 caracters,... and only accepts 2 caracters for "AT command"


The datasheet you have found is not for the same display. Yes, it's similar, and yes, it has the same actual OLED display unit on the board, but the PCB is different. So you cannot assume that the pinout is the same.

The fact that it's getting hot tells me that you have probably wired something wrong and you are injecting voltage into it somewhere where voltage doesn't want to be injected.

To find if an OLED is working you have to actively wire it up.  With an LCD you can just give it power and you should be able to see some visual indication that it's working (back light, some shadowing of the display matrix, etc). But with an OLED you can't do that.  An OLED is made up of a matrix of LEDs which are either on or off. By default they are off, and when they are off it's no different to there being no power. That's the big benefits of OLED displays - low power consumption and true black.

To get any kind of indication that the display works you both need to wire it 100% correctly and program the Arduino in the right way to actively drive it by displaying something on the screen.  My usual test program when working with a new screen is to simply print millis() in the top left corner.


How can I connect to an Arduino using WiFi?

You have a few options for connecting your Arduino to the network/Internet.

Ethernet

Something like the Arduino Ethernet Shield allows you to plug in an Ethernet cable from the wall or router into your Arduino. Obviously, the main limitation is that your device is now tethered by the cable. For outdoor use, I wouldn't do this.

WiFi

The Arduino WiFi Shield allows you to connect to your home WiFi network. This is just like the Ethernet except its now wireless.

The ESP8266 is a cheaper alternative that, with the default firmware, has the same functionality as the WiFi Shield. Be careful that you power it with 3.3V and not 5V as the rest of the Arduino. It also uses 3.3V logic levels so don't connect the Arduino's TX pin directly to the ESP's RX pin; use a voltage divider.

RF

If you have a lot of sensors or other devices that need to communicate with each other, the best option is usually an RF module. You have many options here, XBee being one of them. Check out the Sparkfun XBee Buying Guide to look at all the options available. And that's just XBee. There are many other wireless options available, at all sorts of prices.

The thing with RF is that none of these will connect to the Internet. You will have all your devices communicate with each other or a base station, which will then be connected to the network by either a WiFi or Ethernet module.

Wireless Router Serial

Depending on what kind of wireless router you use, you can have the Arduino communicate directly with it and use that as your connection to a network.

Arduino - Cheap wifi connectivity
Converting your Ethernet Shield to a wireless shield


What are the benefits or advantages of Arduino CLI?

Simple: you can program the Arduino without needing a GUI.

One good example: You have an Arduino connected to a Raspberry Pi built into a robot. You SSH into the Pi, edit the Arduino's program, and upload the new code. All from wherever you happen to be.

A second example: You can integrate Arduino compilation into your own software. Such as a web interface for compiling your code.  I know of one such project where the creator has made a custom website for editing their robot code and using UECIDE's CLI (which pre-dates Arduino's) to compile and upload the code to the target board.

And yes, you have an outdated context of Arduino development, as evidenced by your use of the phrase "fooling around with". Arduino is not a toy. It's a development platform and educational tool. Maybe back when you were "fooling around" with it, it was little more than a toy, but things have moved on a long long way since then. The Arduino ecosystem boasts boards with chips from every manufacturer you can imagine to fill every niche you can conceive. The API and available libraries have certainly matured.


Using of this sensor is a bit more complicated than that. You must cycle through 60 seconds of heating and 90 seconds of measurement cycles, during heating you need to provide 5V on its heater pins, during measurement you need to provide 1.4V, so you'll need transistor or some other PWM-controlled current limiter (Arduino pin can't provide enough current for sensor heating).
I've tried to explain all details and calibration process here: https://www.instructables.com/id/Arduino-CO-Monitor-Using-MQ-7-Sensor/


Not able to build program with arduino program under clion

I found a github issue fixing this error : https://github.com/vsch/CLionArduinoPlugin/issues/36
It worked for me


I solved this problem. The reason for this is because main Arduino is c++ and simplesample_mqtt.c is c code and we have to use c++ code in c code:

In main Arduino file you have to declare function like this :

extern "C" void TurnOn();
void TurnOn()
{
    digitalWrite(RELAY_SONOFF, HIGH);
    digitalWrite(LED_SONOFF, HIGH);
}

and use this function in c code:

void TurnOn();
EXECUTE_COMMAND_RESULT TurnOn(ContosoAnemometer* device)
{
    (void)device;
    TurnOn();
    (void)printf("Turning fan on.\r\n");
    return EXECUTE_COMMAND_SUCCESS;
}


Can Arduino uno adjust input square wave duty, phase and frequency with just timer-counter?

this makes heavy use of CPU, and I need to use CPU for something else

The issue with this code is that is heavily uses the CPU for busy
waiting rather than for doing useful work. You should try to get rid of
those waiting loops:

Serial.readString(): see Majenko's blog post Reading Serial on the
Arduino

delayMicroseconds(): for this, you can indeed use a timer.

For the pulse generation, you can keep roughly the same logic as your
existing code: output a single pulse every other time a rising edge is
sensed on the input. This pulse can be conveniently generated by
Timer 1 on pin 9 by using a PWM mode and stopping the timer
after a single cycle. I would use inverting PWM mode, with the timer
starting at zero on the input pulse:

at t1 microseconds, a compare match sets the output HIGH

at t1+t2 microseconds, the timer overflow sets the output LOW, and
the overflow interrupt stops and resets the timer

Here is a tentative, untested implementation:
// Set the pulse timings. To be called from loop() on user's request.
void set_timings(uint16_t t1, uint16_t t2)
{
    uint16_t ocr1a = t1 * 16 - 1;        // initial time in LOW state
    uint16_t icr1 = (t1 + t2) * 16 - 1;  // timer period
    noInterrupts();  // protect critical section
    OCR1A = ocr1a;
    ICR1 = icr1;
    interrupts();
}

// Configure Timer 1. To be called from setup().
void setup_timer() {
    DDRB  |= _BV(PB1);    // set pin digital 9 = PB1 = OC1A as output
    TCCR1A = _BV(COM1A0)  // PWM on OC1A, inverting mode
           | _BV(COM1A1)  // ditto
           | _BV(WGM11);  // mode 14: fast PWM, top = ICR1
    TCCR1B = _BV(WGM12)   // ditto
           | _BV(WGM13)   // ditto
           | 0;           // stopped
    TCNT1  = 0;           // reset
    TIFR1  = _BV(TOV1);   // clear overflow flag
    TIMSK1 = _BV(TOIE1);  // enable overflow interrupt
    set_timings(235, 5);  // initial timings
}

// Interrupt triggered by a rising edge of the input.
void on_rising_edge() {
    static uint8_t count;
    if (++count % 2) return;   // divide by 2
    TCCR1B |= _BV(CS10);       // start timer, clock @ F_CPU
}

// Stop and reset the timer when it overflows.
ISR(TIMER1_OVF_vect) {
    TCCR1B = 0;  // stop
    TCNT1  = 0;  // reset
}


What is the purpose of putting a data type in brackets before a calculation?

It's called casting. It changes the data type temporarily. In this instance it's being used to change an integer type into a floating point type, which means that the whole calculation is done using floating point mathematics. However acc_y is supposedly already a float, but maybe it wasn't at the time the author wrote that line. Maybe things, as they often do in a program, evolved. Only the author knows.


Arduino to Arduino Communication using HC05

lcd.write(waitTime);

This line prints a single byte, whose (ASCII) value is the number in waitTime. You probably should write:

lcd.print(waitTime);

instead, which prints the number in waitTime using one ore more digits as needed.

This doesn't 100% explain the "both digits end up in the same place" symptom, since I'd expect random junk to be printed instead. But I'm pretty certain this is a problem, perhaps there's more problems :-)


Compiling source with Arduino.h with avr-g++

You need to do a whole lot more than just run the one command.

You need to compile each individual source file for the libraries you want (using -c to just compile and not link), then (ideally) archive them into a library file. Do the same for the core. Then you need to add paths to your sketch compilation command pointing to where the header files are for those libraries, and compile the sketch to an object file (again with -c). Finally you need to link everything together into an ELF file, and convert that to a HEX file.

TBH you're best off using an already-existing Makefile project, or arduino-builder.


According to this schematic, no. The LED is connected directly to power.

You will need to physically remove the LED to turn it off.


Alternate between 2 relays with one button

The way you have it, both if blocks will be evaluated each time you call to loop(). Instead, you need to create a variable that remains "alive" in between each call to loop() to keep track of which relay you want to activate:

const int ledPin = 2;
const int ledPinA = 3;
int active_relay = 2;   // State variable for current relay pin

void setup() {
    pinMode(ledPin, OUTPUT);
    pinMode(ledPinA, OUTPUT);
    Serial.begin(9600);
}

void loop() {
      int sensorValue = analogRead(A0);

      Serial.println(sensorValue);

      delay(1);    // This delays for 1ms, not 1s ??

      if (sensorValue > 500) {   // Pulse received
          digitalWrite(active_relay, HIGH);  // Relay on
          delay(1000);                       // Wait 1 second
          digitalWrite(active_relay, LOW);   // Relay off

          // Update variable for next call to loop
          if (active_relay == ledPin) {
              active_relay = ledPinA;      // Swap
          }
          else {
              active_relay = ledPin;       // Swap
          }
      }
      // Remove 2nd if block
}


maximum interrupt-based PWM frequency at 500 Hz

You wrote:

  Using [...] the atmega's hardware pwm is not very suitable because I
  need two 50/50 square waves with a phase difference of pi

I believe hardware PWM is the best solution to your problem. The PWM
outputs can be set to either “inverting” or “non-inverting” mode.
Set the two channels of a single timer to the same duty cycle, with one
in non-inverting mode and the other one in inverting mode, and you have
your complementary outputs.

Example using Timer 1:

const float SIGNAL_FREQUENCY = 24e3;
const uint16_t HALF_PERIOD = round(F_CPU / SIGNAL_FREQUENCY / 2);
const uint16_t PERIOD = 2 * HALF_PERIOD;

int main()
{
    /* Set the PWM pins as outputs. */
    DDRB |= _BV(PB1);  // digital  9 = PB1 = OC1A
    DDRB |= _BV(PB2);  // digital 10 = PB2 = OC1B

    /* Configure Timer 1. */
    ICR1   = PERIOD   - 1;
    OCR1A  = PERIOD/2 - 1;
    OCR1B  = PERIOD/2 - 1;
    TCCR1A = _BV(COM1A1)  // non-inverting PWM on OC1A
           | _BV(COM1B0)  // inverting PWM on OC1B
           | _BV(COM1B1)  // ditto
           | _BV(WGM11);  // mode 14: fast PWM, TOP = ICR1
    TCCR1B = _BV(WGM12)  // ditto
           | _BV(WGM13)  // ditto
           | _BV(CS10);  // clock at F_CPU, start timer
}


How to make an RC mixer with the arduino

You do not need to use long for values from pulseIn, using int will be sufficient.

Your code is not complete, at least there is a missing '}' at the end of setup.

The slower the baud rate (9600) actually the more it interferes with timing code, to a point.  PWM is all timing code.  I would suggest 57,600.

You never set the servos to any pins.  And is using Servo lib needed? I have always used analogWrite with no problems.

You are not using parenthesis on your math (currently commented). It will not give you the result you expect. But you are somewhat on the right track, subtract 1500 from each pulse read, that will give you -/+ range. How you mix that depends on how your radio is setup (servo reversing, which channel is which). Keep in mind ailerons is 1 channel, so left aileron = -rightAileron.  Elevator up = that + elevator.  so;

aileronLeft = airleronChannel + elevatorChannel
aileronRight = -airleronChannel + elevatorChannel

You do realize this a $3 part?

update: I have always used analogWrite, but I also always use good equipment. I see cautions that cheapo servos might be damaged with analogWrite. You can read more here. It has always worked for me.


That is a perfect printout of a GPS system that can see zero satellites.

The fact that the timestamps are one second apart shows that you have correctly interfaced with the GPS device. Now, the GPS device has to 'interface' with the satellites!

Many people don't realise two things:

The GPS antenna really does need a clear view of the sky. A tiny view through a window may show one or two satellites, but you need a minimum of three, and preferaby four or more at a number of points around the sky to get a fix.
If the GPS unit has been completely powered off (called 'cold'), when it first powers on it has NO idea where anything is. It simply listens for any signal anywhere until it "hears" the current time. It can then guess where satellites might be, and listens for updates on satellite positions.

All of this listening, guessing and waiting takes time before it can start to actually lock on to satellites and start to get a fix. This time could easily be 90 seconds or more - you need to be patient. Check your GPS device specifications for "cold start" times.

Edit

I'm impressed! The GY-NEO6MV2 that you list has a cold-start of 27 seconds - but that assumes it has a clear view of the sky.


LCD display and ultrasonic sensor not functioning

There doesn't appear to be anything wrong from a quick glance.  Have you got the right library for the LCD?

The chances are there is something wrong with your LCD.  So check your connections again.  Now create a new sketch that just prints hello world on the LCD, or better still use an example.  If that works, then the problem is an interaction between components.

So write a sketch that spins the servo back and forth while printing a message on the LCD.

Did that work, now add in the ultrasonic sensor and the code.

Now the other bits, and if that works, then you could look at what you have done differently, or just thank your lucky stars :)


The problem of not saving the previous value when sending it from bluetooth

C has an "Exclusive Or" operator which is ^.  You can use that instead of | so that it toggles the bit rather than always setting it:

case 'A' :
    bt_leds_activated ^= 1;
    break;

With ^ if you OR a 0 with a 1 you get a 1. If you OR a 0 with a 0 you get a 0. If you OR a 1 with a 1 you get a 0.

That means every time you send A bit one of bt_leds_activated will invert. If it's 0 it will become 1. If it's 1 it will be come 0.

Also you seem to have two sets of states - the button states, and the bluetooth states. Instead you only want one set of states, and both the buttons and the bluetooth toggle bits in that single state set.

Because of that if either of the methods of turning an LED on has turned the LED on then the other method will have no chance at all of turning the LED off.

So just drop bt_leds_activated completely and use ledstates:

case 'A':
    ledstates ^= 1;
    break;

Now both the button and the character through bluetooth will toggle the LED.


Why my light meter's values are blank on Arduino Serial Monitor?

Use Serial.println(x); to print a number as text. Function write() sends the raw byte and Serial Monitor shows the character with that ASCII code, which is not valid or a not visible control character.

For the z = (y, DEC); from Wikipedia:

  In the C and C++ programming languages, the comma operator (represented by the token ,) is a binary operator that evaluates its first operand and discards the result, and then evaluates the second operand and returns this value (and type).

so z is always 10 (value of constant DEC), which is ASCII code for the new line character


Square wave based on falling edge of alternative pulse of upcoming RPM square wave

There are some things you shouldn't be doing within an interrupt service routine (ISR) like countRPM():

Don't call the millis() function. It depends on other interrupts which will be disabled during the execution of your ISR.
Don't call digitalWrite or any other functions
Don't use execution cycles hungry operators like % (modulo). To obtain modulo 2, just use a bit mask for the LSB.

What you should actually be doing within the ISR is just setting/resetting a flag or variable. Then, do all your stuff in the loop() function according the value of the flag or variable.


Which Protocol to use to control WiFi (ESP8266) enabled Led Light

UDP :D

Seriously though, ESP8266 is limited in resources, AND you want to send 50-60 updates a second, just UDP will be the most lightweight, and you won't run out of connections (5 I think on ESP), because UDP has no connection state.

This is what was used here to control a RGB strip: https://github.com/cnlohr/esp8266ws2812i2s , it just listens for UDP packets on port 7777, and each packet contains rgb values, one byte for R,G,B, etc.

MQTT is nice, but it doesn't work well for 60hz updates, I Tried :D
It resulted in un-smooth animation, and frames out of order.