Serial Monitor is printing out weird values and skipping strings

int checkSum[] = {-1, -1};

const String stringPool[] = {
                        "Satz 1", "Satz 2", "Satz 3", "Satz 4",
                        "Satz 5", "Satz 6", "Satz 7", "Satz 8",
                        "Satz 9", "Satz 10", "Satz 11", "Satz 12"
                      };

const String& chooseRandom () {
  bool isMaybeThreeTimes;
  int randomInt;

  do {
      randomInt = random( 0, sizeof(stringPool) / sizeof(stringPool[0]));
      isMaybeThreeTimes = (randomInt == checkSum[0] && randomInt == checkSum[1] );

      Serial.print("Current random value: "); Serial.println(randomInt);
      delay(1000);
      Serial.print("Last random value: "); Serial.println(checkSum[0]);
      delay(1000);
      Serial.print("Last last random value: "); Serial.println(checkSum[1]);
      delay(1000);
      Serial.print("Three times in row?: ");
      Serial.println(isMaybeThreeTimes?"Yes":"No");
      delay(1000);
      checkSum[1] = checkSum[0]; // for next run
      checkSum[0] = randomInt;
  } while (isMaybeThreeTimes);
  return stringPool[randomInt];
}

void buttonPressed()
{  // has nothing to do with button presses, just a test
  const String& stringToPrint = chooseRandom();  // waits 3 seconds
  // Send the string to the adafruit printer.
  Serial.println(stringToPrint);
}

void setup() {
    Serial.begin(19200);
    delay(2000);
    Serial.println("Setup finished");
    randomSeed(analogRead(0));
}

void loop() {
    buttonPressed();
}

Some fixes, not tested.
Edit: some more fixes, tested.


How to perform action if two rfid tag UIDs have been detected?

What you can do is store the current time whenever a card is swiped, and then when another card is swiped check how long it's been since the last card was swiped

first create a couple of variables

unsigned long swipedTime;
int tag1 = 0;
int tag2 = 0;
int swipeTimeOut = 10000; // how much time in MS you have to swipe both cards

Next we'll jump down to where where you read the cards.

      if (mfrc522.uid.uidByte[0] == 0xA4 &&
           mfrc522.uid.uidByte[1] == 0xB8 &&
           mfrc522.uid.uidByte[2] == 0xB8 &&
           mfrc522.uid.uidByte[3] == 0x96) {

               ........

               if (tag2 == 1 && millis() - swipedTime < swipeTimeOut ){
                   // both tags have been swiped, print serial message here
                }

                tag1 = 1;
                swipedTime = millis();
        }

        if (mfrc522.uid.uidByte[0] == 0x03 &&
           mfrc522.uid.uidByte[1] == 0xFD &&
           mfrc522.uid.uidByte[2] == 0xBC &&
           mfrc522.uid.uidByte[3] == 0x02) {

               ........

               if (tag1 == 1 && millis() - swipedTime < swipeTimeOut ){
                   // both tags have been swiped, print serial message here
                }
                tag2 = 1;
                swipedTime = millis();

         }

You'll also want to come up with a system for resetting tag1 and tag2 to 0 or "checking them out".


Controlling amplifier using remote control jack

According to this thread on remotecentral the signal on the RCA connector is just the inverted signal that the IR-LED receives. So if you load an RC5 library and invert the output (0=1 and 1=0), you should be able to send codes to that connector with an arduino. Or even better, use an ESP8266 and control it over wifi ;)
The RC5 codes and their functions are in this  nice excel sheet or use this information if you want to send raw hex


You have not said what you motor is and that normally has a big bearing on the answer, but I think your problem is you need more power.

A 9V battery doesn't actually give you much current, you would be better off with a 'wall wart' aka a mobile phone charger.  The higher the amps the better normally, particularly with motors.  Try and find one that can put out 5Volts at 1Amp (assuming you have a 5V motor).

Also make more use of Serial.println() to show you what your program is doing.  If you had debug statements in the LDR if statements then you would know the switches are working.


The datasheet says:

  The SPI commands are 16 bits long with the 8 most significant bits (MSBs) representing the register address and the 8 least significant bits (LSBs) representing the data ...

Thus, you need to write address / data after selecting the chip.

digitalWrite (SS, LOW);  // select the chip
SPI.transfer (0x00);     // select address 0x00 (Video Mode 0)
SPI.transfer (bit (1));  // write bit 1 (Software Reset Bit)
digitalWrite (SS, HIGH); // done

According to the datasheet you need to wait around 20 µs for the operation to complete. You could, of course, just wait 20 µs but it might be nice to see if the bit gets cleared.

  byte result;

  do
    {
    digitalWrite (SS, LOW);      // select the chip
    SPI.transfer (0x80);         // select address 0x00 (Video Mode 0) - read mode
    result = SPI.transfer (0);   // read it
    digitalWrite (SS, HIGH);     // done
    } while (result & bit (1));  // loop while not reset yet

  Also, how would one verify that the chip indeed did reset itself and responds to the commands given to it afterwards?

I'm not sure, without the chip in hand, what other tests you can make, but if you added a counter into the above loop, you could probably verify that it was doing something. eg.

  // reset chip
  digitalWrite (SS, LOW);  // select the chip
  SPI.transfer (0x00);     // select address 0x00 (Video Mode 0) - write mode
  SPI.transfer (bit (1));  // write bit 1 (Software Reset Bit)
  digitalWrite (SS, HIGH); // done

  byte result;
  unsigned int counter = 0;

  // wait for it to become ready, or time-out
  do
    {
    digitalWrite (SS, LOW);      // select the chip
    SPI.transfer (0x80);         // select address 0x00 (Video Mode 0) - read mode
    result = SPI.transfer (0);   // read it
    digitalWrite (SS, HIGH);     // done
    if ((result & bit (1)) == 0)
      counter++;     // count times not ready
    } while ((result & bit (1)) && (counter < 1000) );  // loop while not reset yet

  if (counter == 0 || counter >= 1000)
    {
    // chip does not seem to be responding
    }
  else
    {
    // all OK!
    }


The behaviour of your program is undefined because you're reading past the end of your array.

In C/C++, the sizeof operator always gives you the size of something in bytes. It doesn't directly tell you the number of items in an array. Since int is usually 2 bytes for Arduino programming, the pinCount variable is actually being initialised to 10 (5 items x 2 bytes each).

The result is that each for loop is actually doing 10 iterations. The first 5 iterations are OK, reading correctly from the ledPins array. However, the rest of the iterations are reading whatever data happens to be in memory after that. This means it could be trying to initialise and switch on any pin, potentially including 0 and 1.

I can't guarantee that this is the source of the problem, but it's certainly very important to fix.

The solution is quite easy though. Divide the total size of the array by the size of a single element:

int pinCount = sizeof(ledPins) / sizeof(int);


How do software interfaces compare to hardware interfaces in therms of speed and reliability?

In your question you ask about all communication interfaces in general, so the answer will be as general as your question.

Hardware interfaces should always be preferred to software interfaces, though there are situations, where it is a better or needed to use a software interface due to limited resources.

  Because anyways the protocol is handled by the CPU

That is mostly wrong. The communication protocol is done by the hardware in most cases, if you use hardware interfaces. Serial (UART) for example automatically sends out the byte, that is placed in the hardware buffer, with the set configuration. It does not rely on any software for that. The same goes for SPI or I2C. The protocol of the interface is handled via hardware.

Though at least for Arduino Core/library users there is more to it, that get's handled automatically. Since the interface hardware is limited, the software have to take care of the resulting or needed data. For example: All the interfaces mentioned above use a 1 byte buffer for the data. The software must read or write this data, so that the hardware can work. If you don't read the byte of data, that was received by the Serial interface, it might get overwritten by the next byte. The hardware cannot provide a buffer, that is generally big enough, since the manufacturer cannot know, how long the transmissions will be. So the interfaces get a 1 byte buffer and the software has to do the rest. For this reason all the libraries use a bigger buffer in their software, that gets filled, when the hardware sends a corresponding interrupt.

So: Hardware interfaces implement the basic interface protocol (how the bits get transmitted) in hardware, thus the software only has to provide and read the byte data. The stability, speed and versatility is only determined by how the manufacturer build the hardware of that interface. This limit is clearly specified in the datasheet and does not change with the code.

For software interfaces, everything is done in software. This also involves monitoring and setting the corresponding pins with the correct timing. In the best case the software can utilize general hardware functions like a pin interrupt, but if it cannot do this, it has to constantly monitor (poll) the pins to receive something. Software interfaces are often called "bit banged", because the software manually pushes out each individual bit with the exact needed timing. That is a tedious task, which often blocks the execution of other code, since the timing often is critical. Especially the timing introduces limits, since doing things in software often involves many clock cycles more, than it could be done by dedicated hardware (consider all the code to poll a pin and the multiple if statements to react to specific situations). For example: When you write data with SoftwareSerial the call to the write function will block, because is manually pushes out bit after bit. Or with SPI: With hardware SPI you can go to incredible clock speeds in the MHz range. You won't every get near that with software, because the software simply cannot run this fast.

Note, that depending on the actual hardware of the used chip, a library may need to implement parts of the protocol in software. For example this is the case for using I2C on an ATtiny85, which does not have full I2C hardware support. Instead the USI (Universal Serial Interface) can be used to implement some functions of the protocol in hardware and the rest in software.

TL;DR

Hardware interfaces lift the heavy duty of handling the low level protocol (transmitting the bits by the needed standard) (which can be rather complex) from the software
The Software then only handles the byte data, not it's transmission
Translating complex protocols from dedicated hardware to software (bit banging the data through simple pins) imposes great limits on speed and reliability.


I have read a lot of materials, watched many videos and completed lots of searching to find great stater Arduino lessons. By far the best place I found was

opensourcehardwaregroup.com
Free to start learning Arduino site

Free initial course and if you like the lessons you can pay a small fee to get to the advanced course. You will learn a lot!


You can add ESP.restart() in the following line to make it restart.

ArduinoOTA.onEnd([]() {
Serial.println("\nEnd");
ESP.restart();
});

Now you can upload code each time without hitting reset.


Yes.  As given in the datasheets, normal ATtinyX4/X5 chips can run with a supply between 2.7 and 5.5V inclusive, whereas the low-power versions can run between 1.8V and 5.5V. Mind the speed restrictions when running at lower voltages though; see the "Electrical Characteristics" section of each datasheet to determine the maximum characterized speed for a given voltage.


Any suggestions? (On running two programs within one Arduino maybe)

Small excursion:

You are right to observe that the Arduino with its 1 core can only execute one instruction at any given time. However, there are ways with which we can achieve that the Arduino "does things in the background". We can e.g. use interrupts from hardware timers, which will interrupt the main CPU core to quickly execute a interrupt service routine, and then continue where it let off originally.

This is also how an RTOS (real-time operating system) works. You can only execute one thing at a time, but if you set up a timer interrupt every 20 milliseconds in which you switch between the executed functions, you get a "emulated" multi-task system. These are the basics of any operating system.

References:

https://www.sparkfun.com/tutorials/326
https://www.youtube.com/watch?v=QtyOiTw0oQc
https://arduino-info.wikispaces.com/Timers-Arduino
https://www.freertos.org/implementation/a00002.html

You will also notice that your Arduino Uno can't play music directly -- for that, you would need a digital to analog converter to produce the needed analog audio voltages, together with a audio amplifier for headphones or loudspeakers.

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

Fortunately there are many Arduino shields that do the job. Some of them are:

Seedstudio Music shield (documentation, library)
Adafruit Music Maker shield, with either headphone or loudspeaker output

Here, the work of playing music (from a file on an inserted SD card, for example), is offloaded to an external synthesizer chip. We do however need to supply the chip with the to-be-played music data in the background.

When you look e.g. at the library reference for the Adafruit Music shield, you'll see that it offers a function that will use interrupts to play a file from the SD card in the background.

Using the library in this interrupt mode will of course use an interrupt source (either timer or pin), which may conflict with your EMG code if it also uses that timers. In that case you will have to move either the EMG code or the music code to a different available timer.

In short:

Learn more about what interrupts and timers are
find a suitable shield (e.g. the adafruit shield above) and understand its library capabilites and limitations


I have to be honest after reading you description and looking at you code I have no idea how you arrived at the code you have arrived at.

For now lets try a much simpler bit of code, once that is working you can build on it.

#define PIN_BUTTON_1    2
#define PIN_LED_RED     5

void setup() {
    pinMode(PIN_BUTTON_1, INPUT);
    pinMode(PIN_LED_RED, OUTPUT);
}

void loop() {
    const int buttonState1 = digitalRead(PIN_BUTTON_1);
    digitalWrite(PIN_LED_RED, buttonState1);
    delay(200);
}

If that code doesn't work then there is something wrong electrically.

I think is the next step you were trying for:

#define PIN_BUTTON_1    2
#define PIN_LED_RED     5

int lastButtonState1 = LOW;
int functionNumber = 0;
int currentLedValue = 0;

void setup() {
    pinMode(PIN_BUTTON_1, INPUT);
    pinMode(PIN_LED_RED, OUTPUT);

}

void loop() {
    const int currentButtonState1 = digitalRead(PIN_BUTTON_1);
    if (lastButtonState1 != currentButtonState1)
    {   // If the button's state has changed
        if (currentButtonState1 == HIGH)
        {
            ++functionNumber;
        }
        lastButtonState1 = currentButtonState1;
    }
    DoFunction(functionNumber);
    delay(200);
}

void DoFunction(const int& function)
{
    switch (function)
    {
    case 1:
        if (currentLedValue > 0)
        {
            currentLedValue = LOW;
        }
        else
        {
            currentLedValue = HIGH;
        }
        digitalWrite(PIN_LED_RED, currentLedValue);
        break;
    case 2:
        currentLedValue = 128;
        analogWrite(PIN_LED_RED, currentLedValue)
        break;
    default:
    }
}


You need to declare it volatile in both places and shut off interrupts while reading it. The mainline  has to read it byte-by-byte, and an interrupt could otherwise occur between any two byte-reads, rendering the result of the 4-byte read as garbage.

'volatile' informs the compiler that the variable might not contain what it did last time (which the compiler might otherwise expect if the code being compiled doesn't change it. Turning off the interrupts protects the variable being changed while it's being read.

An even better way to protect the reads than turning off interrupts, is for the ISR to update the counter, then set a single-byte flag to indicate that there's a new count. The mainline would monitor that flag and read the counter only when the flag gets set, then clear the flag. This can work as long as the mainline checks the flag frequently enough that it will never not notice the flag until just before the next update by the ISR. But if you can keep to that constraint, this is a better idea than turning off interrupts.

If too many sub-tasks resort to turning off interrupts, it can have a negative effect on response time or even cause missed interrupts in some cases. This is less likely to be a problem for the relatively simple programs most of us write and run, most of the time. But when you get to tracking and controlling more complex processes and make heavier use of the interrupt system, bad habits have a way of coming back to bite you.


Yes, it's possible.

Just don't make a class. Just make functions instead.

Like a class-based one, have a .cpp and a .h file. In the .cpp file (or .c file if you don't want any of the C++ functionality or 90% of the Arduino API available to you) place your functions.

In the .h file place prototypes for them. I am in the habit of adding the extern keyword, but you don't actually need to for functions.

For example:

foo.cpp:

void doSomething() {
    // whatever
}

foo.h:

extern void doSomething();

Then you can include your .h file and call your functions:

#include <foo.h>

// ...

doSomething();


How do I configure WEMOS D1 R2 Vin pin to output max voltage?

You cannot. You are misunderstanding, what that pin is. Vin means Voltage In. It's a voltage input, connected to a voltage regulator, which will regulate the provided voltage at that pin down to 3.3V for the Wemos to work with. It is not an output. The regulator cannot convert the 3.3V from the Wemos to 12V. That is not, what it is build for.

To get 12V you either need a separate 12V power source, or you need to buy a stepup/boost converter, which brings the 3.3V (or 5V, if you are powering from USB) up to 12V. For the latter, be sure, that the converter and the source, where you get the input voltage of the converter, can provide enough current for your use case.


Simulation of Arduino Mega 2560 with GSM Module using Proteus

You should download this GSM Library for Proteus . You can use this library to simulate your GSM module in Proteus software. You should also check this example where they have discussed Hoe to Send SMS with GSM module in Proteus ISIS. I hope it will help you out.

Thanks.


What happen to the counter value if I do not input the statement (if previous state!=current state)

No, it will increment as long as there is a product and at the frequency your loop runs at. So, when the light is interrupted, it will count several objects within a second.
The line you want to ommit is very essential, it makes the sketch only detect edges rather than levels.


Simple Arduino - 74hc595 shift register construction [tmli5]

You have a number of problems here. The first is the wiring.

My wiring diagram above is for the Uno / Duemilanove. Since that is what you have, you should follow that.

The pins are fixed in hardware, except for the slave select pin. Thus D13 on the Duemilanove should go to pin 11 on the 595. D11 on the Duemilanove should go to pin 14 on the 595. And your slave select (which may as well be pin 10 on the Duemilanove) should go to pin 12 on the 595.

Your code looks more complex than it needs to be. This code will exercise the 8 LEDs:

#include <SPI.h>

const byte LATCH = 10;

void setup ()
{
  SPI.begin ();
}  // end of setup

byte c;
void loop ()
{
  c++;
  digitalWrite (LATCH, LOW);
  SPI.transfer (c);
  digitalWrite (LATCH, HIGH);
  delay (20);
}  // end of loop

As other responders have said, you should have a current-limiting resistor for each LED. You can't share it like that.

Also the 595 ground (pin 8) should be wired to the Duemilanove ground, not via a resistor.

Reference

Using a 74HC595 output shift register as a port-expander


Cannot get any readings from DHT22 Sensor connected to Arduino M0 Pro

Found what the fault was, it was a solder short between pins on a custom PCB that was sitting on top of the Arduino board. My bad! At least I have it working now!


Difference between /dev/ttyACM0 and /dev/ttyS0 (Arduino IDE ports under Linux)

/dev/ttyACM0 is a USB communication device (CDC) of sub-type "abstract control model" (ACM). That is what the Arduino is.

/dev/ttyS0 is a hardware serial port - the (typically) 9-pin D connector on the back of your computer.

If you want to use /dev/ttyS0 (why would you?!) you will require a special cable that converts the RS-232 voltage signals from the 9-pin D connector into the right TTL level signals for the Ardiuno and wire it in to the right pins on the board.


Are the GND pins of an Arduino identical to GND of its power supply?

"Ground" is just a lump of metal and each ground "pin" is connected to it. That includes the ground connection in the barrel jack. It's all one thing.
Wherever you connect your fan's ground to it's all ground.  That is, as long as all grounds external to the Arduino are connected, ultimately, to the Arudino.


You must set EN BEFORE you set DIR.  The datasheet says EN must be high for at least 5 microseconds before you set DIR.  You should probably just set EN high when your program starts, then not fool with it until your program ends.

The next thing is that I don't see you incrementing the variable "step" anywhere.  So, if you did get the stepper to turn, it wouldn't stop.

The updated code looks like it ought to work.

You should use DelayMicroseconds instead of Delay(0.005) though.  Delay takes an integer instead of a decimal value, so you won't get what you expect.  Curse the Arduino IDE for not throwing a fit when pass a float for an int.

It looks like anything working properly is purely luck.  The board you are using(NOT an Arduino) uses 3.3V logic levels.  The ST330 says a high must be at least 4V, so if it reacts to your control signals at all it is just luck.

The 8266 outputs are rated for 12mA, the ST330 inputs need about 20mA, so you are over doing it.  The 8266 might put up with, and might just die on you.

You might be able to drive the ST330 by switching the mode of the pins.

Low would be "set pin to mode output and set low."

A high would be "set mode input."

Input mode leaves the pin floating, which the ST330 will interpret as a high.

Other than that, you could use NPN transistors to drive the ST330 inputs, then invert your output signals.

The NPN would invert your signal (a high becomes a low) so you would have to set an output to low to get a high going into the ST330.

You can use NPN transistors like this to drive the ST330:

simulate this circuit – Schematic created using CircuitLab

Setting the  GPIO from the ESP8266 to high would cause a low on the ST330 input.

Setting the GPIO pin to low would cause a high on the ST330 input.

This is the solution I would prefer if I needed to use the ESP8266 with the ST330.

If you'd like to try a purely software solution, then do this:

To send a low to the ST330 input, set the GPIO to pin mode output and set the output to low. (pinMode(step_pin,INPUT) then DigitalWrite(step_pin,LOW))
To send a high to the ST330 input, set the pin mode to INPUT (pinMode(step_pin,INPUT)

When the GPIO pin is in input mode, it floats.  It doesn't have a voltage level of its own - it acts like it is disconnected.

If that works, I'd still prefer to use the transistors.

You can avoid all of this using the UNO.  It has 5V logic levels on the outputs.


HD44780 DDRAM addressing on the second line

Your confusion here is mixing "digit" and "byte". The two are not the same.

HD44780's can never have more than two rows. If you look at the block diagram you can see there are 16 "COM" connections. Those are the rows of the characters - 8 per line. That gives at most 2 lines of text.

20x4 displays are actually 40x2 displays but sliced in half and stacked. The 21st character of the first line is actually the first character of the 3rd line.

These two lines are split into two separate blocks of memory. One starts at 0x00 and the other at 0x40. The two blocks are pretty much completely separate.  There is nothing of any interest to you between 0x28 and 0x3F. In fact that memory may not even exist - however those addresses may map to other addresses within memory. This will purely be an artifact of how the memory is addressed internally.

For simplicity of decoding the addresses the two blocks of memory are distinguished purely by the most significant bits of the address. The lower bits, then, will always be the same for the same location in both lines of text. That is, for the same horizontal character position on the display the first row (COL0-COL7) will have the same address in memory as the second row (COL8-COL15) except the most significant bits.

Since the HD44780 operates in blocks of 40 bits (8 characters, 5 bits per character) for its displays and uses "extension modules" to give each extra block of 8 bits (which is why you get 8, 16, 20, etc widths) having the two lines of text with truly consecutive memory addresses would make decoding the addresses needlessly difficult. So they don't.

If you take an example of the 3rd character horizontally on the display the pixel address in memory will be (note: this is the pixel address, which is 5x what the character address would be after the data has been generated from the internal character set):

Line 1: 0x02 = 0b00000010
Line 2: 0x42 = 0b01000010

Since the memory itself is 80 bytes and designed to be no more than 40 characters wide with 1 or two rows, there necessarily has to be a dead zone between the blocks of addresses. If the addresses were completely contiguous, so that the first character of the second row (character 40) was the 40th address in memory, the memory addresses would look like this:

Line 1: 0x02 = 0b00000010
Line 2: 0x2a = 0b00101010

Mapping those two addresses to the signals COM0-COM7 and COM8-COM15 would be considerably harder and take far more complexity in the design of the chip - which the manufacturer certainly doesn't want.

It is far simpler to add a little bit of logic into the cursor control which says "If the cursor moves from position 39 to 40 then set the memory address to be 0x40".

So when writing successive characters to the display the cursor logic hides the segmented memory from you. But if you are directly manipulating that segmented memory then you have to take that segmentation into account.


In Arduino, just setting the pin as input already makes it high impedance.
Writing HIGH on an input pin actually enables its internal pull-up resistor.
This way, the voltage at the pin is always defined (instead of floating when the switch is open).
Just search for "pull-up resistor" if you need more information.
Note that this code:

pinMode(n, INPUT); // set as input, high-impedance
digitalWrite(n, HIGH); // activate the internal pull-up resistor

is equivalent to this (in recent Arduino IDEs):

pinMode(n, INPUT_PULLUP)


Interfacing with desktop computer console software

For debugging:

Configure the UART on the ATmega to output TTL serial. If you are using the Arduino libraries, then Serial is what you want. Connect the TX pin of the ATmega to the RX of the USB/Serial cable, and vice versa.

Open the serial device on your computer in the program of your choice. When you write to the UART on the ATmega, you should see the messages in your terminal.

Pretty straightforward.

For programming:

If you're going to be using C and flashing things manually, you'd best go and buy an AVR programmer so you can program the ATmega directly without messing about with a bootloader. A programmer is ~15USD, so you might as well buy one. Then you can use the GNU AVR toolchain, which is very easy to use. Compile code with avr-gcc, and program the device with avrdude.

If you really want to use programming over serial, you'll have to manually hit the reset button each time you program the chip, because (as Mikael pointed out), that serial cable lacks the lines necessary to automatically reset the chip (and drop to the bootloader).


Prevent hardware and library examples from showing in the Sketchbook menu

Looking at the code it is scanning all folders and there is no option to change that behavior. Also looking at the code, it looks like it dumps them into a sub-menu, hiding them away a little further, if the folder is named anything except "examples", which could be an alternative option for you.

The final option would be to fork your own version and come up with some exclusion logic, maybe with some kind of ".ignore" kind of logic where you can specify folders to exclude form the menu.


Sorry, figured it out.

In the "config.h" file I was pulling, I had a
 #define = 18;

instead of a #define 18

I might be wrong, but the compiler stopped complaining


Why the GSM Shield is discontinued? What options are available?

A retired product is just a product that isn't supported anymore. It doesn't mean that this product is not usable anymore. Because the GSM shield is discontinued by Arduino.cc itself, you could buy Arduino.org (link to the GSM shield 2), or even an other model by Adafruit. Here is a link for many options of GSM shields on Adafruits' website.

A last option would be to buy it from a chinese seller on Amazon or Ebay. Though they are cheap, they are usualy very crappy and there are not many libraries for them.


There must be something wrong with the simulator you're using, because your code works for me (Arduino IDE 1.8.9, OSX, Arduino Uno).

struct commands
{
  int   cmd;
  char  descr[25];
};

commands cmds[] =
{
  {16, "Hammond Organ"},
  {17, "Percussive Organ"},
  {18, "Rock Organ"},
  { 0, "" }                   // end of list marker
};

void setup(){
  Serial.begin(9600);
  Serial.write(cmds[1].descr);
}

void loop(){}


nodeMCU - Millis() - Simple Counter - How long is LED on?

Declare a global (or static) boolean variable to keep track of whether the timer is running or not, as well as a variable to hold the start millis() value. When the lux drops below your threshold, subtract the current millis() from the start value, and you have the duration in milliseconds, which is trivial to convert to mm:ss.sss format.

Example code (not a complete sketch)

uint32_t timer_start = 0;
uint8_t timer_running = false;

void loop() {
  if (lux>150) {
    if (!timer_running) {
      // Timer is not already running, so capture the start time
      timer_start = millis();
      timer_running = true;
    }
  } else {
    if (timer_running) {
      // The timer is currently running; stop it calculate/print the run time
      timer_running = false;
      Serial.print(millis()-timer_start); // format however you like here
    }
  }
}

  This now tells me how many millis the gymnast is in the air, divided
  by 1000.0 with 3 decimals. If I start the Serial Monitor when the
  gymnast is in the trampoline bed, then I can get the seconds of
  air_time the gymnast has. Is there a way to have this script running
  ONLY for 10 loops?

Certainly. If it is assumed that you want a cumulative total air-time, then you need to declare another global or static variable to hold the cumulative air-time, and you need to have another variable to keep track of how many cycles have passed.

void setup() {
   Serial.begin(9600);
// initialize digital pin 13 as an output.
}
uint32_t timer_start = 0;
int timer_running = false;
uint32_t total_time = 0;
uint8_t jump_count = 0;

void loop()
{
// Get LDR information
  int sensorValue = analogRead(A0);         // read the input on analog pin 0
  float voltage = sensorValue * (5.0 / 1023.0);     // Convert the analog reading (which goes from 0 - 1023) to a voltage (0 - 5V)
  float lux = voltage * 100;

  if (jump_count<10) {
    if (lux>150) {
      if (!timer_running) {
        // Timer is not already running, so capture the start time
        timer_start = millis();
        timer_running = true;
      }
    } else {
      if (timer_running) {
        // The timer is currently running; stop it calculate/print the run time
        timer_running = false;
        // Add this-jump air time to the cumulative total:
        total_time += millis()-timer_start;
        // Increment jump_count
        jump_count++;

        Serial.println((millis()-timer_start) / 1000.0, 3); // format however you like here
      }
    }
  } else {
    // Print the total air-time for 10 jumps;
    Serial.println((total_time)) / 1000.0, 3);
  }
}


LCD showing weird characters when using two 1-wire temperature sensors

After some more searching I have found Arduino forum topic LCD text corrupts after Arduino runs for length of time. I have followed this advice:

  In particular, try running the LCD ground wire directly to a ground pin on the Arduino (not to the breadboard) and keep it short.

This seemed to solve the issue, therefore it was likely some kind of interference on the ground wiring. (Before this, the ground to the LCD went trought the breadboard power bus).


Arduino Sainsmart uno communication problem

You are doing 2 things wrong in your program:

First is using serial.write(), which writes bytes rather than ASCII.

Second is you are declaring a string literal as a char instead, you must declare a string using  double quotation marks (which is ") so that your program should read:

Serial.print("Test!");

When you declare 'Test !'  you are doing it wrong, and it will only take the last char in the string, which is '!' - using single quote marks is for a single char declaration, like '!' or 'T', and you can make an array of chars into a string if you wanted, like this:

char array[] = {'T', 'E', 'S', 'T', '!' };
Serial.write(array, 5);

but why would you when the earlier one works better?


You start by taking the Uno and putting it aside, and picking up an AVR-based Arduino that has native USB device support such as a Leonardo or Esplora. You can then use the build scripts that come with LUFA to build the code for your device.


How can I split a string into multiple parts?

An array is 0 indexed, which means that number 5 is out of index. "Hello" should be index valued 0-4 and not 0-5.

Here is a better code to try out:

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

void loop() {

String recivedMessage = "";

// Read
while (Serial.available())
{
    recivedMessage += Serial.read();
}

// Print debug
Serial.print("recivedMessage: ");
Serial.println(recivedMessage);

//// Uncomment the row under if you are not sure that the splitting is working
// recivedMessage = "Hello";

// Split
char first  = recivedMessage.substring(0, 1)[0];    // H
char second = recivedMessage.substring(1, 2)[0];    // E
char third  = recivedMessage.substring(2, 3)[0];    // L
char forth  = recivedMessage.substring(3, 4)[0];    // L
char fifth  = recivedMessage.substring(4)[0];       // 0

// Print debug
Serial.print("Cut message: ");
Serial.println(first);
Serial.println(second);
Serial.println(third);
Serial.println(forth);
Serial.println(fifth);

}


Using two MIDI inputs with Arduino UNO (with one serial)

Use a Mega. SoftwareSerial is shaky at best and cripples everything else while it runs, and there really is no substitute for real hardware UARTs.

Alternatively look around and see if you can find a board based around the ATMega328-PB (note the "B") which has a second UART built in.


Your computer can not see what is going over the WiFiBoard serial connection because that connection has nothing at all to do with the connection to your computer.
If you want your computer to see what is being received on that port you must read the data from that port then send it to your computer.
It doesn't (much) matter about the difference in baud rates (only that if one sends too much data too fast for the other to forward it you will lose some data).
It's common to use something like:
while (WiFiBoard.available()) {
    Serial.write(WiFiBoard.read());
}

That will forward anything received from the WiFi board over the serial port to the computer.


Encoding an entire Byte for File Reading

This is a fragment (untested) of how you can do it:

char datafile[512];
int ch;
int index = 0;

while ((ch = file.read()) != -1) {
  datafile[i] = (char)ch;
  if (++i == 512)
    break;
}


How can I find the time taken while a function is being called?

There is micros() which returns the number of microseconds the board has been active. But it rolls over much more frequently (a bit over an hour vs the month and a half for millis())

unsigned long preFunction = micros();
foo();
unsigned long timeElapsed = micros() - preFunction;


What is Reverse Current through an Arduino?

It's current flowing "the wrong way".

The electronics inside the main chip are designed such that the + side (Vcc) must be at a significantly higher voltage than the - side (GND).  By significantly I mean 2.1-5.5V higher.

Because of that it is expected that the current will flow through the components in one direction (or in a couple of pre-determined directions depending on settings).  Any situation which causes a reversal of that current through the internals is bad, and as called "reverse current".

It could be caused by something as simple as connecting a power supply backwards, or more technical things like the "Back EMF" from an inductive load (motor, relay, etc) entering a pin that is an output and flowing backwards up to Vcc, or "Back Powering" where the chip is not powered but some external device connected to it is powered, and it "leeches" power backwards through IO pins to power the chip.

All of those situations are bad and should be avoided.


Storing data from Arduino without Serial print- High Sample rate

The Portenta has a beast of an  STM32H7 Cortex M7 and a minimum of 8M bytes of external SDRAM in addition to the 1M on-chip.
You need to capture 2channels x 2 bytes x 100K/s x 5s = 2M bytes of data, so storing it on the on-board RAM and spitting it out later seems like a viable and low-risk approach.
A slow serial link might take a few minutes to transmit 2M bytes of data, but you have various other options if that is objectionable.


I edited your question and changed ESP-12 to NodeMCU, based on the title and tag.

5.1 V will 'fry' a plain ESP12, but the NodeMCU is development board with esp8266 and the board has a power regulator for USB power or Vin pin. The parameters of the regulator depend on the regulator used by the manufacturer of your board.


Ethernet shield or Wifi sheild - Arduino?

If you are beginner with Arduino its better to start with Ethernet Shield. Its much more easy to connect with Arduino.

WiFi Module - ESP8266 required some more knowledge, that you will learn in future.

The bought products are cheap, so you can start with Ethernet and after that to switch to ESP.


Scope of RtcDateTime object when declared outside of a function

As was suggested by more 'native' friends here - I'm 'Answering my question' to make things clear.

After a check and debug - I've found a mysterious behavior that happened to my DS3231 module. Probably a mistaken initializing set of calls - made it stop working - not getting time updates and not counting the time at all. (Freeze at 1/1/2000, 00:00:00).

Disconnecting it from power source, and taking out the battery - returned it to normal behavior, able to get time updates, and answering the calls from the library.

When that part solved - everything else went as easy as it should.

The code sample I posted in my question (declaring the 'now' object outside of setup() and loop() functions) made that object global, so another function (WebServer) can read its current value and use it internally.

Thanks everyone who looked at my problem and helped,
It was a great lesson about how not to take anything as 'known' without double-checking.


How to connect an Arduino via an ethernet cable to a laptop directly?


The problem is that a 2ms delay is required after setting the ADMUX bits before starting the conversion.  Thank you Majenko for the link.

int readVBG(int _analogReference) {
  uint8_t low, high;
  ADMUX = (_analogReference << 6) | 14;
  delay(2); // Wait for voltage to settle
  sbi(ADCSRA, ADSC);
  while (bit_is_set(ADCSRA, ADSC));
  low  = ADCL;
  high = ADCH;
  return (high << 8) | low;
}

The above code is specifically for the Arduino UNO.  Majenko's link above has #ifdef statements which support other devices.


I cannot find which "SIM900.h" library you are using - none of the ones I found have "SimpleWriteln" in them, so this is pure assumption about what functions and overloads may be available.

Just split your string into chunks, like you would with any serial device:

gsm.SimpleWrite("AT+CUSD=1,\"");
gsm.SimpleWrite(command);
gsm.SimpleWriteln("\"");

Where command is a suitable container for your data - say const char *.


Is it safe to short two pins together for conditioning a sketch?

Firstly, why would you?

All you are doing is connecting the input pin 3 to either VCC or GND, since that is what setting a GPIO to HIGH or LOW gives you - why would you waste two GPIO pins for that purpose?

"shorting" an input pin with VCC or GND is what you do with a button or switch anyway. The resistor in that case is used to hold the pin in the opposite direction when the button isn't being pressed. The same effect can be created using a two-way switch connecting the pin to either VCC or GND with no resistor required.

So yes, you can "short" the input pin with an output pin safely - as long as that input pin never becomes an output pin at any time (hint: never use pin 13 on an Uno for this - it becomes an output to flash the LED during the bootloader over which you have no control. The same goes for the TX pin.)


while(1) loop blocks program to enter interrupt

The while loop should have no effect on interrupts. Where does run() get called? We'll need to see the code that sets up and calls the code you've shown. But as a sanity check, you could try replacing the entire contents of run() with a ;, that is make it an empty function. Then add in an empty while loop (contains only a ;, no __asm__ code) and try again. Then replace the body of the while loop with __asm("nop")__ and try again. At which of the above steps does your interrupt fail? That should lead you in the right direction.

Update:
What does your main() function do after display_init() returns? Because that won't ever happen when run() runs forever.

The job of main() is to create the C/C++ run-time environment. That may not have been completed (enabling interrupts, for instance) when display_init() and run() get called, but gets completed shortly after they returns - if run() is allowed to end.

Without seeing your main(), we can't know enough to be more specific, but I'd suggest you move all of your code out of main() and down into the Arduino setup() function because, by the time it gets called, the run-time environment will be complete.

Update 2:

  to avoid unnecessary code

If that is your entire main() function, you've left out the run-time environment setup and it's little wonder that your code behaves strangely. You've asked for help and we've made some suggestions: to show your entire code, not just selected pieces of it; and run your code in a standard way and let us know the result. Then you can optimize your code if you feel it's worth it to you. When you've done that test, and you still have questions, ask again. Until then, you're just asking us to guess. We did that. Once.


Read sensor and convert reading to const char*

The function dtostrf() is prototyped as:

char *dtostrf (double          val,
               signed char     width,
               unsigned char   prec,
               char           *sout);

Where:
   val      Your float variable;
   width    Length of the string that will be created INCLUDING decimal point;
   prec     Number of digits after the deimal point to print;
   sout     Destination of output buffer;

An example of usage is as follows:

/* OPTION ONE */

    char msgBuffer[20];           // make sure this is big enough to hold your string
    char *pointer_to_created_string;

    float testFloat = 123.45;

    pointer_to_created_string = dtostrf(testFloat, 6, 2, msgBuffer);
    client.Publish("...topic...", pointer_to_created_string);

/* OPTION TWO */

    char msgBuffer[20];           // make sure this is big enough to hold your string

    float testFloat = 123.45;

    client.Publish("...topic...", dtostrf(testFloat, 6, 2, msgBuffer));

Don't be put off by the code in the link you included in your question. The first argument sent to dtostrf (everything before the first comma) is nothing more than a some calculations bundled into one single line.


I am making a rubber band gun but i cant seem to get the button to work with my code to turn the servo?

Just put your button between pin3 and GND, and use the internal pullup resistor like this:

#include <Servo.h>
const int buttonPin = 3;
int buttonState = 0;

Servo myservo;
void setup()
{
    myservo.attach(2);
    pinMode(buttonPin, INPUT_PULLUP);
}

void loop()
{
    buttonState = digitalRead(buttonPin);
    if(buttonState == LOW)
    {
      myservo.write(90);
    }
    else
    {
      myservo.write(155);
    }
    delay(1000);
}


Mouser/DigiKey part number for female "stacking" headers?

They're actually called "Wire-Wrap Headers" and they pre-date the Arduino probably by at least 50 years or so.

They used to be used to create circuits between chips and components by wrapping wire around the pins and routing it to other connectors:

They have since been adopted as stackable headers on boards like the Arduino shields.

Being such old technology not many people make them any more, though thanks to their popularity on things like the Arduino they are starting to appear more and more from normal electronics supply companies.


Capturing interrupt on both edges when it's set on RISING or FALLING

I've solved the issue with the reply by eventHandler to another post. Here it is;

  The problem you are having is because the button glitches are
  producing many interrupts on each button press. You can find a good
  description and a way of solving it using hardware here.

  Let me explain, when you press the button, the mechanical contact will
  have a transcient state in which it will fluctuate ON-OFF for a short
  period of time. The same effect might happen when you release the
  button.

  One way of solving this problem is using a capacitor parallel to the
  load. Another "easier" way would be done by software. The idea is to
  set a fixed arbitrary time in which you don't allow new interrupts.
  You could use the millis() or micros() library to set this time. The
  code would look something like this.

unsigned long lastInterrupt;

void ngt()
{

  if(millis() - lastInterrupt > 10) // we set a 10ms no-interrupts window
    {

    state = !state;

    lastInterrupt = millis();

    }
}

  This way you don't process new interrupts until 10ms have elapsed.

  Note: adjust the time to your requirements.


Can ESP 32 use the wire library exactly like that was in Arduino?

Code using the Arduino Wire library is generally portable between processors, but there are pitfalls to watch for.  One that I'm aware of is a difference in the Wire libraries for the ESP32 and ESP8266. The TwoWire::begin() method for the ESP32 has prototype:
bool TwoWire::begin(int sdaPin, int sclPin, uint32_t frequency);

whereas for the ESP8266 it is:
void TwoWire::begin(int sda, int scl, uint8_t address);

So, a call to begin() using the ESP#2 library will set the clock using the third parameter, whereas on the ESP8266 it will truncate the third parameter and use it as an address.
If you wish code to be portable between the ESP32 and ESP8266, then the fix for this particular issue is to call TwoWire::begin( my_SDA_pin, my_SCL_pin ) (specifying only two parameters:the SDA and SCL pins), and use a separate call to TwoWire::setClock( my_clock_speed ) to set the clock.
There may be other differences I'm not aware of...


Read temperature (DS18B20) with the ATTiny85

I would suggest it has to be the clock speed or memory. Whilst you can program the ATTiny85 with the Arduino IDE, it will take up quite a lot of its flash memory. There is a thread on the Arduino form here which might help pinpointing the issue.

One solution is to write it in AVR-C but I don't know if there is an easy way (or a library) for the 1-wire. I think you'll have to do it with the 1-Wire library alone as the DallasTemperature library is too much for the 8Kb of memory you have to play with.

Please feedback any breakthroughs you make as this is a nice project, the ATTiny is an awesome little chip...


What transparent casings are commonly used for smaller devices with a display

So far we have used:

ABS cases (pic camdenboss.com):

Small pelicases (convenient to open, pic pelican-case.com):

3D printed cases with a clear perspex window (pic instructables.com):

I've seen other people use laser cut perspex (pic spikenzielabs.com):


Is it possible to directly set the registers that control the ADC clock on the Arduino?

I can see no problem with your pseudo-code. You should probably post a
complete testable code in order to get better feedback.

That being said, here are a few suggestions:

You should completely set the ADC registers to the values that suit
your application, instead of just changing a few bits here and there.
This is because you should not care about how the Arduino core
library initializes those registers, especially if this is a
prototype for a final product that will not use Arduino core. For
example, instead of

REG1 = REG1 | 0x01;

you can write something like this:

REG1 = _BV(FOO)   // use foo mode...
     | _BV(BAR);  // ...in the bar setting

where _BV(x) is a macro from avr-libc that expands to (1<<(x)),
   and the bit names are those of the datasheet, for better readability.

You may want to run the digital filter in the ADC interrupt service
routine. If you can split your processing into a fast filter
(processing every sample) and a slow filter (running on decimated
samples), then do only the fast one in the ISR and leave the slow one
to the main loop. I say this from experience: when I tried to do
all the processing in loop() I always lost samples, which did not
happen when I moved the filter to the ISR.
But then, make sure your filter is optimized to be fast. Avoid
floating point operations in the ISR if at all possible.

I have written a program that looks very similar to what you are trying
to do: it samples an analog input at 9.6 kS/s and runs an
homodyne detection
filter in order to extract the signal power in a very narrow band around
1 kHz. The ADC is set to free running mode. In the ADC ISR, I
retrieve the sample, run it through the filter, and store the result
into volatile variables. In loop(), I read these back from time to
time. Here is how I set the ADC:

static void configure_adc()
{
    ADMUX  = _BV(REFS0)  // ref = AVCC
           | _BV(ADLAR)  // left adjust result
           | analog_in;  // input channel
    ADCSRB = 0;          // free running mode
    ADCSRA = _BV(ADEN)   // enable
           | _BV(ADSC)   // start conversion
           | _BV(ADATE)  // auto trigger enable
           | _BV(ADIF)   // clear interrupt flag
           | _BV(ADIE)   // interrupt enable
           | 7;          // prescaler = 128
}

The complete program is available here:
homodyne.ino.
It was initially intended for an Arduino Uno, but it runs unmodified on
a Leonardo clone.


Very long range wireless communication between two arduinos(500-1000 KM)

What are options without GSM for that distance wireless communication(500-1000 KM)?

1) use the internet;

2) use narrow band transmission, like qrp;

3) use relays;

4) use satellite phones;

5) use a high-powered lw transceivers.

6) ...


The capacitors are called decoupling capacitors and are used to provide current at very short notice.

The LEDs, when not fully on or fully off, switch rapidly on and off.  This switching needs current to be provided very rapidly at short notice, and batteries and power supplies aren't good at that - so you have the capacitors to act as a little reservoir of power that the LEDs can dip into.

The size of the capacitor (capacitance) can have an effect on how effective they are.  Bigger capacitors respond slower than smaller ones, but store more energy. So you need the capacitor to be small enough for it to respond fast enough. But if you have it too small it won't store enough energy to give to the LEDs and they will be unable to do their job.

0.1µF (or 100nF), aka "104" capacitors are usually reckoned to be a good rule-of-thumb value to use since they are small enough to respond rapidly and yet large enough to store enough power for most small high speed fluctuations.  The exact value though doesn't matter that much, however I would be wary about going below that, and going too high can be troublesome for other reasons as well as their slow response (google: "Inrush Current"). So you don't want to go too high. Around the 0.1µF to 1µF area is where you want to be, with maybe a 10µF for every group of 5 or so LEDs.

I would say 100µF is way too high to have on every LED, but maybe one of those on the breadboard where the power is fed in would be useful to provide a reservoir for larger low frequency demands from the rest of the board.


Change css form color from esp32 if statement

First print everything up to the colour. Then print the colour, which you change depending on the state of the pin. Then print the rest.

client.print("<button style='background-color: ");

if (digitalRead(PIN) == HIGH) {
    client.print("#0CF30C");
} else {
    client.print("#F30C0C");
}

client.print("; color:#000;'></button>");


digispark - 2 pin push button to iterate through an hashmap

Even with a "clean" button, your while() loop will whip through all 5 hashmap values before you can release the button.
Switches and button aren't clean. They will (appear to) bounce, sending many pulses before they settle down to a fully on or fully off state. Read Nick Gammon's tutorial on de-bouncing switches.
I'm not familiar with your display but if it is a one-line display, and you .println() at it, will the newline character "scroll" the line of text off the display? This could explain why you didn't at least see the final line. You may need a plain .print() call in order not to do that.
Most LCD displays have a set of control codes to clear it, move the cursor, etc., which you would have to embed into the text string you send, or send using separate .print() calls. I don't see any provision in your code for including or sending those, so you'll need to fix that, too. Right now, I expect your display receives something like
test0\ntest1\ntest2\ntest3\ntest4\nIt probably needs to see something more like\033Etest0, e.g., for the first one, etc. That cruft at the beginning of the string is the VT52-code,escE, for "Clear the display". (I have no idea what command set your display uses, but the VT-52 commands have been in use for ... um, hmmph! well, a long time, anyway. :)  You'll probably to replace it with whatever your particular device uses.


What is differences in usage between a HC-05 bluetooth module and a Zigbee HC-05 module?

Bluetooth and Zigbee are two different communication protocols. The Xbee clones you are talking about a called BTbee.

As far as im aware the BTbee modules are the same hardware/firmware wise as the hc05/hc06 modules. The only difference being the BTbee modules are in the Xbee footprint, allowing you to plug them into Xbee/Zigbee sockets.


How to interpret accelerometer data to get decimals from -255 to 255

Use this code:

AcX = map(AcX, -32768, 32767, -255, 255);
AcY = map(AcY, -32768, 32767, -255, 255);

Of course, you won't be able to store the resulting value in int8_t since its range is from -128 to 127.

Here you can read more about Arduino map() function.


Strobe Frequency Calculation, how its done?

Why "hold" variable is calculated in the given way?

hold stores the intended delay between the strobe pulses, i.e. the
stroboscope period. It is computed as an affine function of the
potentiometer cursor position because... well, that's the simplest way
to make it user-adjustable. 400 µs is the shortest period that
(according to the program author) one may reasonably want to set.

  Why "microsCurrent", "microsPrev" and all other timings are executed?

See the Blink Without
Delay Arduino
tutorial.

  How "frequency is calculated"?

From the code:

frequency = 1000000/(microsCurrent - microsPrev);

The frequency is the inverse of the period. The period is the time
elapsed between this strobe and the previous one. The numerator is a
conversion factor to get the frequency in hertz from a period in
microseconds.

  What is "hold frequency" variable?

It's the intended frequency (inverse of the intended period),
disregarding the timing jitter that makes the actual instantaneous
frequency slightly different.


3 input (on/off/off with delay) to control 1device using ESP8266 as Web Server

You have various logic problems:
You block until WiFiClient has bytes available. Everything comes to a stop. So if you send a "/delay" command, it will receive and parse that command, turn on the device, then block again, indefinitely, until you send another command. Once you send another command, it will check the interval ONCE, and then lock up again. You need to rewrite your loop to check for bytes, read them if found, and do other work (like checking your time interval) if no bytes are available.
Next, your timing code is a mess. You only ever set currentMillis and previousMillis at the same time, so they will never be different. And you only ever check the times once when you first detect a "/delay" command.
Instead, refactor your logic. Only set previousMillis when you first detect the delay command, and then only compare if previousMillis to currentMillis if  previousMillis is not 0:
if (req.indexOf("/delay") != -1)
{
    previousMillis = millis();
}

if (previousMillis != 0 && millis() - previousMillis >= interval) {
    digitalWrite(device1, LOW);
    previousMillis = 0;
}

(Also note that you were declaring a second, independent variable  previousMillis inside your if statement, which only exists inside the curly braces for that if statement. Don't do that. Use the existing global variable you defined, as I show in my edited code.)


Ah, the problem seems to be in the IDE - Something with the fuses when programming the mega (I won't even pretend to understand that yet).
I upgraded to 1.6.12 and everything works like a charm.

Best regards
Stefan


After test some other K-type thermal couples on this I am now thinking I just got a bad board. I was able to order a new one and it worked without issue


How to detect if running Arduino or bare Atmega328p?

Bare vs Stock is nearly impossible to detect at compile time. Where it depends on what you think you are trying to determine versus detect.

The best I can think of is creating a different Board definition; one for your bare and the other being the stock (i.g. UNO). Where now in IDE 1.5 see github.com/arduino/Arduino/wiki/… the parameter uno.build.board=AVR_UNO, which provides is used to set a compile-time variable ARDUINO_{build.board} to allow use of conditional code between #ifdefs. So you can create bare board definition with e.g. bare.build.board=MY_BARE and then have some #ifdef's for ARDUINO_MY_BARE

Otherwise wrap some #ifdef's around F_CPU as @sechleen points out. This is viable and done often in the core libraries.


Declare the updateMux() function by copying it from your first sketch into your second sketch:

void updateMux1 () {
  for (int i = 0; i < 8; i++){
    digitalWrite(pin_Out_S0, HIGH && (i & B00000001));
    digitalWrite(pin_Out_S1, HIGH && (i & B00000010));
    digitalWrite(pin_Out_S2, HIGH && (i & B00000100));
    Mux1_State[i] = analogRead(pin_In_Mux1);
  }
}

And do the conversions on the stored Mux1_State[] values during printing like:

  for(int i = 0; i < 8; i ++) {
    Serial.println(Mux1_State[i]*5.0/1024.0);
    if(i == 7) {
       Serial.println();
    } else {
       Serial.print(",");
    }
  }


Cannot get esp8266 - 12 wifi module to always read analogRead incoming voltage accurately

Analog to Digital conversion is one aspect1 where the ESP8266 is very poor. It has a single ADC pin which can read a maximum of 1V.

That pin is the only pin you can use with analogRead(). Any attempts to use any other pin just use that pin instead. The parameter (pin number) to analogRead(pin) is ignored and no matter what you do that one single ADC pin is what is being read. Also the pin cannot be used for anything else. None of the digital functions can be used with it since the pin doesn't have a GPIO number associated with it.

Some boards include a simple voltage divider on the ADC pin to allow higher voltages to be read, such as the NodeMCU:

If your board doesn't have such a divider you will have to implement it (or something similar) to be able to read the 3.3V incoming voltage.

1 The ESP8266 is great for WiFi but pretty poor for everything else. It is seriously starved of internal peripherals (it doesn't even have I²C). For a more feature-rich solution you might consider upgrading to the ESP32.


Pinball - "All Lanes Lit" Bonus score is not behaving as expected

Looks like a timing issue.

Which ever order you hit the buttons in the last one always stays lit (and you get an extra 10 points added).

I set a breakpoint at:

rewardScore(allLaneActiveBonus);

...and just waited a sec and then continued and your code worked as expected.

So I think that you are setting all lines to LOW in checkAllLanesLit() and then only have a short delay (5mS) before looping round and checking again (at which point the button is still HIGH as you haven't taken your finger off it quickly enough) - resulting in the additional 10 points and that lane being lit again.


My two slave SPI setup on arduino not working correctly

The ADXL345 uses SPI_MODE3 and DPS310 the SPI_MODE0. The libraries for these devices don't use SPI transactions, but set the settings only in begin(), so they can't be used together.
Your options to solve this is either to put one sensor on software SPI or to put one or both sensors on I2C.
The ADXL345 can be used as I2C device. Its library supports I2C with the constructor when no parameters are provided. Does your module have an option to wire it to I2C?
The Adafruit library for DPS310 has built-in software SPI, so you can use it with any set of pins. And it too supports I2C.


Arduino uno PWM CTC mode - strange behaviour on interrupt

This isn't the only ISR in the Arduino, there is at least the one counting millis. Counter 0 overflow ISR is not as short as yours, so every 1024us it'll cause some jitter (or as in your case, skipping the edge and basically inverting the phase). It'd be also several clock cycles delayed (against HW generated signal). Pushing and poping the registers into the stack are the deterministic delays, but the latency between setting the ISR flag and calling the ISR routine depends on currently executed instruction (some of them takes 2cycles, and there are also longer ones).

There is not much time to do anything else either. Your ISR might take less than 20 cycles, but you only have 64 cycles (ISR is called at 250kHz rate so it generates 125kHz signal).
So if anything else prevents your ISR to be called (another ISR, disabled interrupts), you can miss them, as there is only one interrupt flag.

If you want the same waveform on pin 7, just use a wire and let the pin mode as INPUT.

BTW: You don't have to use PORTB = PORTB ^ _BV(PB7);, the PINB = _BV(PB7) toggles PB7 without read-modify-write access.


How can I control 2 servos without an external power supply?

The power wire is just needed, well, to power the servo. The control is done via the third wire (the other wire being Ground).
You can connect the second servo's power in parallel, only the control wire must be separated from the first servo's control wire.
Note: You need to make sure that the current consumption of both servos does not exceed the provided power.


Arduino due - Getting 0xFF (garbage) from serial

Check baud rate, voltage levels. Better check your signals with a oscilloscope or at least check it with a serial dongle like this https://www.sparkfun.com/products/11814


1) Diagram seems to be fine. However we don't see pin numbering on LCD. Sometimes pins are like:  15 16 1 2 3 4 ... 14 (at least pin 1 is usualy marked).

2) Library should take care of inputs or outputs. So you can remove pinModes for them. Also change variables to constant variables and use them for lcd initialization: LiquidCrystal lcd(rs, enable, d4, d5, d6, d7);

3) Potentiometer in diagram is contrast setting. You have to preset correct value for it. Start with everything is black and find value where this black is almost invisible. If you've something displayed on LCD, it would be even easier to find right position as text just shows up.

Edit: I've just tested it and it's working fine. With the same wiring and contrast pot adjusted to the right position


Need some explain before desigin my own custom Arduino Due board

Because it is not needed. The chip comes with the bootloader pre programmed in  ROM, not in Flash. It cannot be replaced, upgraded, removed, etc like other more sensible chips. So there is no real need for ICSP since the main use for that is putting the bootloader on.
Unknown.
Unlike the AVR chips, whose bootloader always runs first for about 2 seconds, the SAM3X's boot loader only runs if the flash is empty. As a result there is a way to empty the flash built in to the Arduino code, so that it can be erased by software. That means that the software has to be working right though, which isn't always the case, since people write bad code which crashes the chip. As a result they added a erase button to the board so you can manually erase the chip and get the bootloader to run.

I have always maintained that the SAM3X is a really idiotically designed chip and I wouldn't ever use it in a design of my own.


Can I run more than 2 servo motors smoothly, connecting their power to regulated limit voltage and signal wires to the digital pins of the arduino?

So now my question is, How many servos will I be able to run when I power them parallel-ly using a standard 9 volts battery (HI-WATT, Blue and white one), if no, Which will be the best battery for doing it?

Unfortunately: Zero motors with your current circuit. Maybe one motor with a better circuit and the same battery. Here is the explanation.

You should ditch the standard 9V block battery. These batteries are made for low power applications (like IR remotes or smoke sensors) and cannot provide enough current for driving all those motors. They might be able to drive one servo, but still will be drained very fast. You should use a battery, that can provide much more current. Which battery you choose also depends on your other requirements. A series of AA alkaline batteries can give you enough current. Or you can directly buy a LiIon or LiPo rechargeable battery (including a fitting charger board). They can provide way enough current.

You cannot just use simple resistors as voltage regulators. That just doesn't work for loads, that can draw a changing amount of current (like a motor).

The voltage, that the motor gets, depends on the current, that the motor draws. When the motors stands still, it will draw very little current. Thus the motor is getting the full 9V in that case. As the drawn current rises, the voltage will go down, until the motor gets not enough voltage to operate correctly.
The resistor of 750 Ohm restricts the current draw of the motor. Even when we (for the sake of calculation) treat the motor as a short circuit, the maximum current through the resistor with 9V will be only 12mA, so way way lower than the 400mA, that you stated in your question. You won't be able to move the motor much with that little current.
Even if you used a smaller value, you need to be careful with the current. I guess you are using standard resistors there, which typically have a power limit of about 0.25W. These are meant for rather low current circuits. With the 400mA @ 6V, that your motors need, you are in the region of 2.4W (that is not necessary the power for the resistor, just a value for you to see the relation). You can easily burn away a little resistor that way. When you need a resistor with a higher power limit, you need to buy one, which can handle it (and these are typically multiple times the size of a standard "signal" resistor and still can get very hot, when used in the realm of their power limit).

Instead you should buy a proper voltage regulator. At that current, buy a switching buck regulator, as they are way more efficient than linear regulators. Which regulator you need to buy also depends on the voltage of the battery, that you choose. Be sure to buy a regulator, that can provide significantly more current, than we need in total for your circuit. This is important, because regulators are typically described with a maximum current, at which they already need extra measures for cooling. When you stay well below that, you can avoid thinking about fitting cooling for it.

So , will it control the motors as good as 16 channel servo drivers?

Yes, it can. Though you need to think about how you are controlling the servos on the Arduino. The standard Servo library supports up to 12 servos with one timer. When you can change the library to use 2 Timers for supporting more servos, then you have it. You could also try to search for other libraries, which support more servos, or write your own library. I would say, using the driver would be simpler. The driver does not switch the power for the servos. It has a chip, which can output 16 servo control signals and is controllable over an interface like I2C or SPI.
If you want to use such a driver is up to you. You might find it more important to have as few electronic parts as possible.


This is an ordinary method (function) which can not be instantiated. It is necessary to write a class with 1 or more methods in it in order to instantiate multiple copies of that class and the method(s) with in that class.

The integers "LastState", "BeginState" and "r" only have scope within the method and will not survive after returning from the method.  There are several approaches to preserve these variables from one call to the next.  They can be declared as static integers.  Or they can be defined globally.

It appears you are recreating the existing Bounce library.  I encourage you to continue if you are learning.  However, you may want to look at the Bounce library's code for guidance.


Is RX1 and TX0 the same thing as TX and RX? Will there be a difference in the way I program it?

It's not RX1 and TX0 but RXI and TXO

That is receive input and transmit output,

Exactly the same as RX and TX just with the data direction explicitly shown in the lettering.


Only return button state once in X amount of time?

To avoid this problem you can use a boolean variable as a flag that permit to enter inside the if only once.

bool flag = true;

void loop() {
  passButtonState = digitalRead(passButton);

  if (passButtonState == LOW && flag) {
    Serial.println("PASSED!");
    flag = false;
  }
}


Hacking old car dvd monitors with arduino

Your best bet is to try to take the casing off until you find a company name so that you can get a lead on where to look for documentation. Because until you find out more about how that screen works, it's a black box to you and you don't know what to put in it. No one else will be able to help you until you provide more information to this extent because no one else can hold it in their hands, and the photo of the socket that you showed us doesn't look like a common display format either.

Also, you're very unlikely to make a PC-type thing out of this. That depends on the power of the computer behind the display and an arduino isn't that powerful. You want a Pi. Or maybe I'm misunderstanding what you want. You could easily get a scrolling text type thing going or maybe even a game (if you figure out how to make it work).

Edit: I just looked up a sample LCD screen and it has 6 signal pins and power and ground. Yours looks like it has a lot more. So you definitely have some digging to do.


If your supply is regulated (put a 47ohm resistor across it and measure the AC voltage with a DMM; it should be almost nothing if properly regulated) then you can use it for both the Uno and the NeoPixels. The ATmega328P has a maximum input voltage of 5.5V, and the WS2812B has a maximum voltage of 5.3V, putting the supply within the proper range to run them.


YUN. How to reset the micro controller from linux?

According to the Yun schematic, GPIO18 of the SoC is connected to the MCU reset circuitry. Toggling it should allow you to reset the MCU.


Implementing AT commands with Arduino and ESP8266

You don't give a circuit diagram or very much detail about what you've done, but if I guess correctly...

You have flashed the code in your link to the ESP-01 (perhaps using the Arduino as a serial port adapter). That code is now running on the ESP itself - it's not running on the Arduino and controlling the ESP.

Flashing the ESP erases the stock firmware, so the ESP can no longer respond to AT commands.

I don't know of a way to reprogram the 'AT' firmware into the ESP but perhaps Google will help.

If I've guessed incorrectly, please explain exactly what you have done - with circuit diagram, setup steps and code.


How I can use multi sensor in one code in Arduino?

just duplicate the parts of the code that handle the sensor.

int redLed = 12;
int greenLed = 11;
int buzzer = 10;
int smokeSensor1 = A5;
int smokeSensor2 = A4;
int smokeSensor3 = A3;
// Your threshold value
int sensorThres = 400;

void setup() {
  pinMode(redLed, OUTPUT);
  pinMode(greenLed, OUTPUT);
  pinMode(buzzer, OUTPUT);
  pinMode(smokeSensor1, INPUT);
  pinMode(smokeSensor2, INPUT);
  pinMode(smokeSensor3, INPUT);
  Serial.begin(9600);
}

void loop() {
  int analogSensor1 = analogRead(smokeSensor1);
  int analogSensor2 = analogRead(smokeSensor2);
  int analogSensor3 = analogRead(smokeSensor3);

  Serial.print("Pin A0: ");
  Serial.println(analogSensor1);
  // Checks if it has reached the threshold value
  if( (analogSensor1 > sensorThres) || (analogSensor2 > sensorThres) || (analogSensor3 > sensorThres) )
  {
    digitalWrite(redLed, HIGH);
    digitalWrite(greenLed, LOW);
    tone(buzzer, 1000, 200);
  }
  else
  {
    digitalWrite(redLed, LOW);
    digitalWrite(greenLed, HIGH);
    noTone(buzzer);
  }
  delay(100);
}


This (inside your for loop) does not do what I think you think it does:

byte bfr[2] = {7,7}; // clear buffer

You think it sets the contents of the bfr array you declared at the top to {7,7} but what it actually does is declare a new byte array in that scope, containing the values {7,7}. It's not used and is immediately thrown away again.

I would expect the compiler to warn about it -- does it?  (If so, take it as a lesson not to ignore compiler warnings!)

I think you want to replace it with

bfr[0] = 7;
bfr[1] = 7;

or something equivalent.


LED and Switch Compolation Error Arduino 101

I notice that your pinMode function calls are not quite correct:

pinMode(Sender = OUTPUT); // Setting pin two to output
pinMode(Reader = INPUT); // Making pin 12 set to read switch data

Should be:

pinMode(Sender, OUTPUT); // Setting pin two to output
pinMode(Reader, INPUT); // Making pin 12 set to read switch data

Refer to https://www.arduino.cc/en/Reference/PinMode for more information.

And the whole section where you configure your I/O should be wrapped inside the setup() function.

//configuring I/O
void setup()
{
    pinMode(Sender, OUTPUT); // Setting pin two to output
    pinMode(Reader, INPUT); // Making pin 12 set to read switch data
    digitalWrite(Sender, HIGH); //Making pin two hot
}


Digital Band pass filter arduino 1100-1300 Hz

You cannot use ^ as mathematical power symbol in C. Ini C it means the exclusive-or bit operation (hence the error showing it is a bit operation).

For the mathematical power function, you should use the math C library. See library explanation. To include it, use:

#include <math.h>

The power function has the following prototype:

double pow(double x, double y)
Returns x raised to the power of y.

However if you only need to write a float/double in exponential format, you can use

3.01e-8


Maximum sampling rate of Arduino Mega2560

The beginning of section 26 of the datasheet for the ATMega2560 gives the following data:

  • 13µs - 260µs Conversion Time
  • Up to 76.9kSPS (Up to 15kSPS at Maximum Resolution)


8X8 LED not lightning up according to matrix assignment on a Arduino Nano

I don't see any program statements in the code as shown to cause the described behavior, and imagine it is some hardware problem.  (I'm assuming you put some non-zero values into the image[][] array; it looks to me like nothing should light up when image[][] is all-zeroes.)

Hardware problems break into several categories:  A wiring problem (which we can't see without much better pictures); incorrect software setup of HW; temporary misbehavior of the processor; or permanent damage.  For the sake of discussion, suppose temporary misbehavior applies.

Temporary misbehavior can be caused by overheating.  Overheating can be caused by drawing or sinking a lot of current for too long a time.  (If a large current is a fast transient event, it may have little effect.)

Note that most Arduino I/O lines are rated to sink or source at most 40 mA current each.  Ground and Vcc lines have higher limits, like 200 or 100 mA.  For more details see the spec sheet for your processor; also see ArduinoPinCurrentLimitations at arduino.cc, and Real maximum current for ATmega328? on Electronics SE.

If an LED is directly connected to 5V, it is likely to draw several times more current than nominal.  Connecting  an LED directly to an Arduino digital line also will allow it to draw too much current.  Connecting 8 LEDs to a single processor IO line is likely to cause enough overheating to damage the processor permanently.  You may need to add 8 or 16 resistors to your circuit.

Anyhow, instead of trying to debug while using a 100 μs multiplexing delay in your program, and instead of turning on lots of lights at the same time, try turning on one at a time for a brief but visible period each, and see if the array of lights scans ok, via code like the following:

int rowPins[]    = {19, 18, 11, 7, 12, 5, 4, 16}; //assign row lines
int columnPins[] = {13, 17, 9, 10,  2, 8, 3,  6}; //assign col lines

void setup() {
  int i;
  for (i=0; i<8; ++i) {
    pinMode(rowPins[i], OUTPUT);
    digitalWrite(rowPins[i], HIGH);
    pinMode(columnPins[i], OUTPUT);
    digitalWrite(columnPins[i], LOW);
  }
}
void loop () {
  int x, y;
  for (y=0; y<8; ++y) {
    digitalWrite(rowPins[y], LOW);
    for (x=0; x<8; ++x)  {
      digitalWrite (columnPins[x], HIGH);
      delay(250);     // wait about .25 seconds
      digitalWrite(columnPins[x], LOW);
    }
    digitalWrite(rowPins[y], HIGH);
  }
}

If multiple lights are on there may be miswiring on your project board, or the chip might be damaged, or there may be some roundabout leakage path from columns to ground or from rows to Vcc.  If you make the delay longer or add a pushbutton to advance manually, you can check voltages on LEDs and wires, or measure currents in wires, and perhaps deduce what the path is.


Circuit with a tip120 works with a Led but, don't with a vibrator motor

The TIP120 is possibly the worst transistor you could choose for this job. It is a Darlington Pair transistor, and those have a (relatively) massive forward drop of between 2 and 4 volts. It works with the LED because an LED needs a tiny amount of current to operate compared to the motor and has a fixed forward voltage of its own. The motor doesn't, and is being starved of power by that huge voltage drop (it's getting maybe half the voltage it should be getting).

Throw away that TIP120 and replace it with a decent N-channel MOSFET - one with a "threshold voltage" (VGS) of 2.5V or less ideally.


How to have an Arduino communicate with 3 other Arduinos?

You could use: U(S)ART, I²C or SPI. You should check this post for information on these protocols.

Some quick googling gave me this:

SPI: mainly for high data rates, approx 25 MHz clock but only bus has to be on same voltage level, single master (can be done through software), data arbitration not possible.
I2C: mainly for control and low data transfer (limited by bus capacity, etc...), but can be interfaced to different voltage levels and multimaster bus environment, inbuilt arbitration etc...
UART: single P2P comm, 115 kbps max.

http://www.edaboard.com/thread53139.html

I don't fully agree with it. You can send via UART to multiple devices, but then you have to handle the addressing in software. But other than that, UART is very easy to debug as Arduinos often have an USB connection.

"I²C is somewhat complicated at the physical level, but all that complication is handled by the hardware (the TWI interface of the AVR chips). At the user level, it may be the simplest to use". I don't yet have a lot of experience with this protocol, but if you want to use it, check out the other answer.

SPI would be a fair shot as it does enable master with multiple slaves in its standard.

Summary:

All protocols have different pros and cons. It's not really up to us to choose one for you. And you should look them up and learn about them by yourself.

Then try to choose which one applies most to your needs, and get started with that protocol. They are well documented and if you really can't get out of it, you can post another question ;D


In line following robot do this code work perfectly as iam unclear about the right and left moving programing lines

This depends on how the sensors are arranged. However, assuming they are setup like eyes on our heads, then the code would be correct.

If the left sensor does not see the line, but the right sensor does, then that means the line is on the right side of the robot, and thus turning to the right would bring the line back into view of the left sensor.


Reading Digital Pins and Outputing on entire Ports

You have some coding errors.  You likely meant to write something like:

void loop() {
  x = digitalRead(inpin); //read the input pin
  if (x == HIGH) PORTB=B11111111; // if digital input is high, all Bport high
  if (x == HIGH) PORTC=B11111111; // if digital input is high, all Cport is high
  if (x != HIGH) PORTB=B00000000; // if digital input is low, all Bport is low
  if (x != HIGH) PORTC=B00000000; // if digital input is low, all Cport is low
}

Which could be simplified to:

void loop() {
if (digitalRead(inpin) == HIGH)
{
  PORTB=B11111111; // if digital input is high, all Bport high
  PORTC=B11111111; // if digital input is high, all Cport is high
}
else
{
  PORTB=B00000000; // if digital input is low, all Bport is low
  PORTC=B00000000; // if digital input is low, all Cport is low
}
}


Read sensor data repeatedly after specified time?

You store the time (millis()) of the last measurement. Then wait till 5ms have past since the last measurement. Do your measurement, and update the time.

Something like:

unsigned long lastMeasurement = millis();

void loop()
{
  while( (millis()-lastMeasurement)<5 ){/* do nothing */}
  lastMeasurement = lastMeasurement + 5; //or use `lastMeasurement=millis();` depending on whether you want accuracy between measurement, or accuracy over time
  auto measurement = analogRead(A0);
}


I would highly recommend splitting it into two parts: back end (C++) and front end (JS). You'll probably want to connect to a router, so your clients, like a phone and laptop need not be on that AP hotspot w/o internet.

You first build an API with arduino using GET params to control, example pin values int level = server.arg("level").toInt(); analogWrite(2, level);, or whatever you need to do. Put that in a function called handlePin, and subscribe it in setup(): server.on("/pin", handlePin);. Then just add CORS to the server response: server.sendHeader("Access-Control-Allow-Origin","*"); and you can now hit it from any computer on the network. To test, just enter it's URL and some params into a browser URL bar; http://192.168.2.123/pin?level=512 to dim halfway.

Once you have the URLs working, the interface part is built completely separately using whatever tools you want. All you need to do is have your UI hit the API using simple ajax calls. As a quick and dirty example: Level:<input type=range id=val max=1024> <br> <button onclick="fetch('http://192.168.2.123/pin?level='+val.value)">update</button>

That's hows the pros do it, you just swap C++ for PHP or C# or whatever, and use any UI framework you want. Once you have the source of your client app ready, you can upload it to the SPIFFS of the ESP, but I find it easier to host and update system-wide on a "real" server.

If you don't want to write the UI code yourself, you can use node-red to make a quick and dirty "control panel", just like HTML but with drag and drop functionality (more or less). You still use the same API on the ESP, and you can use more than one system at a time; all the ESPs care about is hitting the right URL.


How to create a smooth change in voltage?

I'm not sure that there exists a perfect solution for what you want.  Generating the correct output voltage for time is easy.  Just keep track of time and use the formula you wrote to compute the correct voltage you should be at.  Then you can use a PWM output.  However, this isn't going to be perfect since it is made with pulses rather than a continuous output.  On the Uno the pulses are at 490Hz or 980Hz depending on which pin you use.  Use an RC filter and you can then make it continuous - when you tell it output 2.5V you get 2.5V rather than 0 then 5 then 0 then 5 in short bursts.  But, you're still going to get discrete steps based on the resolution of the ADC - for an Arduino Uno, it's 255 steps I believe.  You could get a separate DAC chip to increase this and can probably get enough steps that their small enough you won't notice.  Some versions of the arduino like the due have 12bit analog output and higher frequency, which should help.


How to filter data of ultrasonic sensor using arduino

Having noise in the sensor data is common and normal, especially on low end sensor.

As you can imagine there is a "data science" to clean up the values, mostly based on statistic.

One of the easiest trick is to remove all values that have a difference > Xt from previous value; as you can imagine the tolerance Xt is calculated by a factor X, let's say a bit more the maximum speed you think the system will operate in time multiplies by the time since the last valid measure.

For example you expect a max distance chance of 10m in one second, so we use as tolerance 15m/s. If we don't read valid value, after 6 seconds our tolerance is 15m/s * 6s = 90m

Of course after much time maybe you just want to accept the first reading that seems valid, so you analyze 10, 100, 1000 value and see if they seems correct.

Then for a quick and dirty smoothing and cleaning if the remaining data, you can run a average on the value, there are different forms, and more value you use more stable are your output, but also less fast to follow changes.

A kallmann filter is the most common but also complex way to clean the data, but I guess in most hobbyist application is just overkill.


There is only one execution unit in this MCU so you can not truly run multiple tasks concurrently.

However, you can achieve the appearance of concurrency by running a higher priority task through an interrupt. For example, you cannot afford to have flickering disspplay. So set up a timer that invokees the display routine periodically. If you set the timer interrupt sufficiently small (over 25hz for example), the display will not flicker.

Your other routines can be run in other isr or in the main loop so they are interrupted by the display routine periodically. In a way that's fully transparent to you.


why were they able to carry out setColor before expanding upon what it means later

You are correct in C that is the case. However the Arduino IDE adds "function prototypes" to the top of your code automatically. That means you no longer have to abide by the "define before use" of C and C++.

I know what 255 would indicate maximum brightness, but why do you have to subtract the color from 255?

This is for if your LED is "common anode" instead of "common cathode". With a common anode LED you write a LOW to turn it on and a HIGH to turn it off - this is the exact opposite of a common cathode.
So to set the brightness of a common anode LED you need to use the opposite value, and since PWM goes from 0-255 the opposite is 255-0: 255 is off, and 0 is fully on.


How to programmatically choose "board model" and "port number" in Arduino IDE?

You can't in the Arduino IDE, it's not designed that way (you can't even have different board/port settings in different windows - it's stored in the Java equivalent of a single global).

Instead you will have to switch to a different programming environment.

Personally (since I am the author) I would suggest switching to UECIDE. That has far more advanced facilities than the Arduino IDE, yet still retains most of the simplicity of use.

In UECIDE you can not only have different ports and boards selected in different windows, you can also configure individual sketches to automatically select their board and port.

Sketch -> Sketch Properties... -> Objects tab


Arduino can't find my custom library: fatal error, Motor.h not found etc

I wanted to vote for the answer from trpropst, but I don't seem to be authorised to do so.

I had the same problem as Caleb. It turned out that the problem was that the user library directory /Arduino/libraries/ contained a library with a missing ".h" file. The Arduino IDE stopped loading the user libraries when it reached the library with the missing ".h" file.

i.e.

the folder "/Arduino/libraries/libraryA" existed

the file "/Arduino/libraries/libraryA/libraryA.h" existed

but the file "/Arduino/libraries/libraryA/libraryA.h" had an include

"#include <libraryB>" for which the folder "/Arduino/libraries/libraryB" existed but it did not contain a file "/Arduino/libraries/libraryB/libraryB.h"

I was trying to compile a program using libraryC, but not using libraryA or libraryB. I guess the lesson is do not develop libraries using the production tool chain.

edited to print < and > correctly


In your first sketch, you have

int ledPin = 13;
int rcvPin = 13;

Did you mean both those to be assigned to the hardware LED on the Nano? (Pin 13 is the on-board LED). If so, why? With all the pins available to you.

The other thing I don't understand is your use of:

byte message[VW_MAX_MESSAGE_LEN]; // a buffer to store the incoming messages
byte messageLength = VW_MAX_MESSAGE_LEN; // the size of the message

It will always just be one byte, won't it?

Why not use available()?

http://arduino.cc/en/Serial/available

I see this was posted six months ago - no doubt you have already solved it.


I have no experience with OCaml or with writing compilers, but I would
suggest that you first learn how to program the Arduino, then teach
your compiler to do so.

You may start by using the Arduino IDE and a couple basic tutorials.
There is an option in the IDE for displaying all the commands it runs to
get your program compiled and linked. Take note of these commands, then
throw the IDE away. Alternatively, you can download one of the few
Arduino Makefiles that float around the Web.

You will see that the basic toolset you need is the following:

The AVR flavor of GNU GCC and the binutils. This allows you to program
the AVR in assembly, C and C++. Calling these tools from your own
compiler should be as easy as calling them from the command-line.
The avr-libc, which is a port of
the libc for the AVR, together with some AVR-specific stuff, and the C
runtime. It does not provide a hardware abstraction layer.
The Arduino core library, a beginner-oriented C++ library built on top
of avr-libc. It does provide a hardware abstraction layer and is
source-level compatible with non-AVR based Arduinos.

In terms of language and API, your main choices are: AVR assembly, C +
avr-libc, C++ + avr-libc, C++ + Arduino core + avr-libc. There are
others, of course, these are just the better known. Pick your favorite,
learn how to use it, then teach your compiler.


Error declaring two-dimensional array: 'x' was not declared in this scope

Without quotes, a, b, c etc. are just names. You didn't declare any of them, so the compiler complains.
Put single quotes around the letters to let the compiler know that they are char literals.


What are the benfits of global variables over static class members?

I can see no specific drawback in using static class members instead of global variables on Arduino. They will be managed the same in the end program.

The only difference I can see may arise based on how you design your classes (if design is correct, then no special problem shall arise):

Let's suppose you decale a class A:

class A {
    public:
    void f();
    void g();
    ...
    static void z();

    private:
    static int myStaticField;
    ...
};

if you need an instance of A for method f(), which does not need myStaticField, then that field exists anyway in your SRAM space.

But this is a corner-case, as in good OOD, myStaticField should be needed as soon as you need to work with class A (whatever method youwant to use).


Somewhere along the line you have to tell your program how to map names to actual variables. Once you have compiled your program it forgets the names of the variables - those only exist in the source code.

So you have to have some other manual list of those variable names - be that in the form of if(...) statements, or an array of structs with the name in them, or whatever.

There's no getting away from it - you need that manual mapping in some form or other.

The closest you could get would be to set up some kind of hash system using structs and linked lists, whereby you could set any key/value pair, but then of course your program would still have to know to look for certain keys in the hash to do things with them, so that would be pretty pointless since you've just moved the variable mapping from one place to another.


Many "expected `)' before ';' token" errors

You have two #define statements at the top of your code

#define trigPin 3;
#define echoPin 2;

The way #define works is that it replaces every instance of the name with everything after it on the line so trigPin is being replaced with 3; as opposed to 3 as intended.

Fixing this should solve some of your problems.


I need to restart Arduino IDE after each compilations

I finally solved the problem, but it's really specific and I don't know if should be on Stack Exchange. Maybe it could give some clues if someone has a similar problem one day...

I was using pin 20 and 21 on my Arduino Due which are supposed to have built-in pull-up resistor. That's what I've read everywhere and it has been said again recently in the answer of an another question I've asked : How to chooce SDA/SCL pair on Arduino Due ?.

Solution : Since I'm using SDA1 / SCL1 with Wire1 everything works like a charm. The value I get from the device are correct, no need anymore to restart the board and I can recompile again and again without any problems.

Edit : In fact, it work significantly better but I still had to use pullup resistors with these inputs. The goal was to use the MPU 9250 and it seems more stable now.


Can we use serial communication in arduino only for RX pin

HardwareSerial takes over the Tx and Rx pins. However you can use SoftwareSerial.

Arduino forum user whiteglint143 made an adaptation of SoftwareSerial that does read-only.

http://gammon.com.au/Arduino/ReceiveOnlySoftwareSerial.zip

See Receive Only Software Serial  - Arduino Forum

  You can regain control over the TX or RX pins by unsetting the TXENn or RXENn bit in the UCSRnB register.

Like this?

const byte LED = 1;

void setup ()
  {
  Serial.begin (115200);
  Serial.println ();
  UCSR0B &= ~bit (TXEN0);  // disable transmit
  Serial.println ("Testing");
  pinMode (LED, OUTPUT);
  }  // end of setup

void loop ()
  {
  digitalWrite (LED, HIGH);
  delay (500);
  digitalWrite (LED, LOW);
  delay (500);
  }  // end of loop

Gerben's suggestion works, in a sense. The pin flashes, but rather disconcertingly, the Tx LED on the board also flashes, out of sync with pin 1. Clearly the signal is making its way to the ATmega16U2 chip, which then flashes the indicator LED. This may not be desirable if you have something connected to the serial port, as it may be interpreted as low-speed serial communications.


How to Home a stepper and make it move 45 degree after that

You need to call run more often. From the documentation:

  You must call this as frequently as possible, but at least once per minimum step time interval, preferably in your main loop. Note that each call to run() will make at most one step, and then only when a step is due, based on the current speed and the time since the last step.

So a single run call and then a delay, will make the motor move only one step. So you need to rewrite for example:

stepperX.run();
delay(3000);

to

unsigned long startMillis = millis();
while( millis()-startMillis<3000 )
{
  stepperX.run();
}

Secondly, move only works on integers, stepperX.move(22.5); will actually become stepperX.move(22);

Lastly, why are you using a totally different method from the rest, to move the motor 10 steps? I'd use a moveTo(10), like you are using everywhere else.


A good water flow meter to monitor home usage with Arduino

I've used an arduino with an irrigation flow meter.

I think I'm getting accurate results, but I haven't checked against a bill. It can handle high flow, and the sensors will attach to any size pvc line. The sensor are a bit expensive, however. $150 for the sensor and $35 for the T junction that it plugs into.

However, as you are living in an apartment, you'll probably need a non-invasive sensor. Perhaps an acoustic one.