I used to have my own String class with a member method called Chomp which did exactly what you are requiring.  The body was something similar to this untested code:

String chomp(String& pSrc, char pMatch)
{
    int matchPos = pSrc.indexOf(pMatch);    // Find the first occurrence of the separator
    if (matchPos < 0)   // Separator was not found.
    {
        String ret = pSrc;  // Return the remainder of the source string.
        pSrc = "";          // Clear the source string
        return ret;
    }

    String ret = pSrc.substring(0, matchPos - 1);   // "Chomp" the start of the string up to the separator into the return value
    pSrc.remove(0, matchPos);                       // Remove everything up to and including the separator.
    return ret;
}

Hopefully the above code should be pretty understandable and fixable if there are any errors.  Our version worked on a "this" pointer rather than passing in the source string, so we would have something like:

String sourceCoords = "12,47,292,85";
int x1 = sourceCoords.chomp(",").toInt();
int y1 = sourceCoords.chomp(",").toInt();
int x2 = sourceCoords.chomp(",").toInt();
int y2 = sourceCoords.chomp(",").toInt();

Hope this is of some use.


Do I need to pass a parameter to SD.begin()?

Yes, you need to pass the Chip-Select (CS/SS) pin number. What number depends on how you have it hooked up, the default is 10. (yours might be 4)

n.b. according to the docs a standard arduino can't use the WiFi, and the SD at the same time; presumably the mega has enough memory.


Does serial speed affect performance of other tasks?

It depends. Serial data is received into, or sent from, buffers (one for sending and one for receiving). If you have a processor with 1024 bytes of RAM or more, then the buffer size is 64 bytes, otherwise it is 16 bytes. (See the HardwareSerial.h file in your distribution).

If the buffer fills up when sending, it will block (that is, the code will wait for the buffer to empty). If it fill up when receiving the extra bytes will be discarded.

If the buffer does not fill up, then the baud rate will not affect performance. That is because data is sent, or received, by an interrupt service routine, in the background.

As a rule of thumb, you can expect data to be sent or received at the baud rate divided by 10. That is because each byte is 8 bits, plus a start and a stop bit (10 bits in total).

So, for example, at 9600 baud you can send 960 characters per second. If you are sending something simple, like a temperature which is 20 bytes, every second, then the baud rate won't affect performance at all. If you are trying to send thousands of bytes per second, it will affect performance, because the Serial.println will probably block once the buffer fills up.

  For instance, when I call Serial.prinlnt("test"), how does that get to the serial line?

If the buffer is not full, then "t" "e" "s" "t" are copied into the buffer, and the code returns immediately. If the buffer is full then it waits for it to become not-full.

As an efficiency measure, if you are sending a single byte, and the buffer is empty, then the byte is placed in the hardware register immediately (saving a small amount of time). In this case, if the buffer was empty, "t" would be sent immediately, and "est" would be sent afterwards, as a "byte has been sent" interrupt is raised.1

This is described in the code comments:

size_t HardwareSerial::write(uint8_t c)
{
  _written = true;
  // If the buffer and the data register is empty, just write the byte
  // to the data register and be done. This shortcut helps
  // significantly improve the effective datarate at high (>
  // 500kbit/s) bitrates, where interrupt overhead becomes a slowdown.
  if (_tx_buffer_head == _tx_buffer_tail && bit_is_set(*_ucsra, UDRE0)) {
    *_udr = c;
    sbi(*_ucsra, TXC0);
    return 1;
  }
  tx_buffer_index_t i = (_tx_buffer_head + 1) % SERIAL_TX_BUFFER_SIZE;

  // If the output buffer is full, there's nothing for it other than to
  // wait for the interrupt handler to empty it a bit
  while (i == _tx_buffer_tail) {
    if (bit_is_clear(SREG, SREG_I)) {
      // Interrupts are disabled, so we'll have to poll the data
      // register empty flag ourselves. If it is set, pretend an
      // interrupt has happened and call the handler to free up
      // space for us.
      if(bit_is_set(*_ucsra, UDRE0))
    _tx_udr_empty_irq();
    } else {
      // nop, the interrupt handler will free up space for us
    }
  }

  _tx_buffer[_tx_buffer_head] = c;
  _tx_buffer_head = i;

  sbi(*_ucsrb, UDRIE0);

  return 1;
}

Notice that the byte is not placed in the buffer at all if it is empty, and nothing is being sent.

For more information see my question and answer about serial processing.

Strictly speaking, after discussing this in the comments with Majenko, the interrupt that is raised is really that the hardware "send" buffer is empty. When the send buffer empties then the interrupt is called so that the interrupt code can put a new byte into it.


Hiding WLAN password when pushing to GitHub

You could commit the following file into your project, named
credentials.h:

// Replace with your actual SSID and password:

#define WIFI_SSID "Your SSID here"
#define WIFI_PASSWD "WLAN AP password here"

Near the beginning of your sketch, you add:

#include "credentials.h"

const char ssid[] = WIFI_SSID;
const char password[] = WIFI_PASSWD;

Now, you can edit credentials.h to add your real SSID and password, and
go on with your normal git workflow, with one exception: never
git add credentials.h again, nor git commit -a.

Now, git will always remind you that credentials.h has been modified and
is not staged for commit. It will do so even if you add the file to your
.gitignore. If you always review your changes before committing, this is
only a minor inconvenience. If, on the other hand, you tend to
git commit -a without reviewing what you are committing, then this
solution is likely not for you.

Edit: An idea I got from reading Chris Stratton's comments. If
you use a Makefile in your own workflow (this has already been discussed
in this site a few times), you could commit this credentials.h to your
repo:

#ifndef CREDENTIALS_H
#define CREDENTIALS_H

// Replace with your actual SSID and password:
#define WIFI_SSID "Your SSID here"
#define WIFI_PASSWD "WLAN AP password here"

#endif

Make a copy of this file named true-credentials.h and put the real
credentials there (but do not rename the include guard). Then add to
your Makefile

CFLAGS += -include true-credentials.h

Keep true-credentials.h and the Makefile out of the repo. You can add
them to your .gitignore or, better yet, to .git/info/exclude.

Now you have a compilable version with dummy credentials in the
repository, you have the true credentials when you compile on your own
machine, and git does not bother you about credentials.h being changed.


Is it possible to print client IP or MAC address from Arduino WiFi web server?

***** Assuming it is an ESP8266 based WI-FI shield: *****

Wifi shield > PC

Open serial monitor. Baud rate 155200. Also check COM ports.

Test AT commands by typing AT.

If it responds OK, you're good.

Type AT+CIFSR for IP adress.

Full list of AT commands in this link:

http://www.pridopia.co.uk/pi-doc/ESP8266ATCommandsSet.pdf


Detecting distance moved by accelerometer?

This is normally referred to as Dead Reckoning.  The processes of determining position using known values, such as acceleration.

First we have to relate acceleration, velocity and position mathematically.  Velocity is the integral of acceleration with respect to time:

Similarly, position is the integral of velocity with respect to time:

Here is an explanation that should tie this all together.  However, it appears this explanation goes in the reverse order.  That is using derivatives of position to find velocity.  And derivatives of velocity to find acceleration.  Simply put, finding a derivative is the opposite process of finding an integral.

A final note, this all works well on paper.  In reality Dead Reckoning based only on acceleration does not work very well.  For instance, I believe most vehicle GPS systems tend to use steering and speed if Dead Reckoning is to be used for guidance.

Added later...

Found this web site where someone talks specifically about Dead Reckoning using an Arduino. He is simply using the deltas of filtered acceleration readings:

velocity(i) = velocity(i-1) + acceleration (i)
position(i) = position (i-1) + velocity (i)

But goes on to say accumulated errors causes drift and positioning errors.


Processing error with processing-arduino examples

Note: I am testing this on OS X, so my paths may differ slightly from yours.

I have managed to reproduce your issue, by incorrectly copying the arduino directory, from the unzipped processing2-arduino.zip package, to the libraries directory under the Arduino directory in my home directory, thus

/Users/user/Documents/Arduino/libraries/arduino

Then opening the Arduino IDE and running the arduino_output example, via the menu, File -> Sketchbook -> Libraries -> Arduino -> arduino_output. When I hit the compile button, in the Arduino IDE, the compiler throws up the exact same errors that you describe in your question.

However this is not the correct usage of this package. This package is intended to be used in conjunction with the Processing application, not the Arduino IDE. You should download Processing and then follow the instructions again:

  Unzip the library and copy the "arduino" folder into the "libraries" sub-folder of your Processing Sketchbook. (You can find
  the location of your Sketchbook by opening the Processing Preferences.
  If you haven't made a "libraries" sub-folder, create one.)

Thus, on OS X, the path should now be

/Users/user/Documents/Processing/libraries/arduino

However, as usual, the documentation on the Arduino website leaves a lot to be desired. Pay careful attention to the following paragraph if you are running OS X or Linux:

  Note: if you run Linux, you need to change Arduino.jar into
  arduino.jar, because Linux is case sensitive and it does not work if
  you don't change this letter (Arduino.jar is in the folder "library"
  of this Processing Library).

So,

/Users/user/Documents/Arduino/libraries/arduino/library/Arduino.jar

becomes

/Users/user/Documents/Arduino/libraries/arduino/library/arduino.jar

Relaunch the Processing application. File -> Examples..., opens up a window, scroll down to Contributed Libraries, open that, open Arduino (Firmata), open the arduino_output example. Hit the Run button, and after compiling you should see the window below:

HTH.


GSM Modem with MAX232 to Arduino Serial?

Yes, with another MAX232, or bypass the MAX232 somehow.


(I haven't used this library, but this looks like a general C(++) question...)

The important part of what you're doing is this:

Wire.write(~((uint8_t)1<<cnt));

Let's break it down.

It calculates a value by taking the number 1 and shifting it left cnt times. Then it takes the complement of that number - changes 0s to 1s and 1s to 0s.  This number is sent to Wire.write() and lights up light number cnt.

Example: Let's say you start with cnt==2, to light LED 2.  It will shift the number 1 left by two digits, giving you the binary number 00000100.  Then it will invert this, giving you 11111011.  This is given to Wire.write().

We can see from this that to light an LED, we need to put a '0' in the right place.

How can you make several numbers light up?  We need to put several zeros in, at the right places.

Here's an example of how you might like to do this - which isn't the prettiest code but I hope it shows you what's going on.

// How we would like the LEDs to appear
boolean led0 = true;    // LED 0 ON
boolean led1 = false;   // LED 1 OFF
boolean led2 = true;    // LED 2 ON
boolean led3 = false;   // LED 3 OFF

// Start with all LEDs off
uint8_t value = 0;

// Put a 1 in place for each LED we want to be ON
// The | symbol means "logical OR" (Google it)
if (led0) value = value | 1<<0;
if (led1) value = value | 1<<0;
if (led2) value = value | 2<<0;
if (led3) value = value | 3<<0;

// Invert this value
value = ~value;

// Write it to Wire
Wire.begin(SDA_PIN,CLK_PIN);
Wire.beginTransmission(0x20);
Wire.write(value);
Wire.endTransmission();

Since it appears you have to send values for all the lights every time, you need to remember the value you sent last time, and modify only the bits you want to change.  Here's a way you can do that:

void setLight(int lightNum, boolean lightOn) {
  // Remember the last state of the lights.
  // Start with all lights OFF.
  static uint8_t lightsOn = 0;

  // We only have four lights (0-3).  Only respond for lights
  // we we have.
  if (lightNum<4) {
    // Get a bitmask with a single 1 in the right
    // position for this light
    uint8_t position = 1<<lightNum;

    // Clear (to 0) that bit in the state
    lightsOn &= ~position;

    // Set (to 1) the bit if we want the light on
    if(lightOn) lightsOn |= position;

    // Write out the value of all lights
    Wire.begin(SDA_PIN,CLK_PIN);
    Wire.beginTransmission(0x20);
    Wire.write(~lightsOn);
    Wire.endTransmission();
  }
}

Call it with something like

setLight(0, true);    // Switch the first light ON
setLight(3, true);    // Switch the fourth light ON (first stays on)
setLight(0, false);   // Switch the first light OFF (fourth stays on)


Unable to Configure MQTT Client ID using Adafruit MQTT Library

The Client ID is expected to be stored in flash memory (it is read using pgm_read_byte). However, on the Arduino, unless told otherwise it first copies the string literal into RAM.  That means that the function is getting the address of the string in RAM, not in flash, and using it as if it were the address in flash, and that gets gibberish.

You need to force it to be in flash by creating a PROGMEM string:

const char clientid[] PROGMEM = "clientfoo";
Adafruit_MQTT_Client mqtt(&client, "10.116.10.191", 1883, clientid);


Is it possible to use Adafruit's Circuit Playground Express's 2MB storage in Arduino IDE?

In their guided tour of the Adafruit Circuit Playground Express, it specifically states:

You can use this in Arduino or CircuitPython to store files.

So yes, it is possible. As far as the how, according to this guide (also from Adafruit), that they have also made a library, Adafruit SPI Flash, which has a bunch of examples showing how to read from, write to, and format the SPI flash whilst retaining compatibility with CircuitPython, among other things.


Serial.read(); and state machine for AT commands

When checking value of smsvalid you use assignment operator = instead of comparison operator ==.

            else if (serialdata[pointingfinger] == '$') {
                if (smsvalid == 1) {
                    searchcharpos = pointingfinger;
                    searchchartype = 2;
                    futstat0 = 2;
                }
                if (smsvalid == 0) {
                    stat0 = futstat0;
                    pointingfinger = 0;
                }
            }

And also you increment pointingfinget prior writing to serialdata buffer. This means that the first character will be written at index 1. So the first character serialdata will be zero, which means empty string.

      pointingfinger++;
      serialdata[pointingfinger] = Serial1.read();

There are many issues with your code, I pasted your code to online gdb c++ compiler, so you can play with it and see what is going on.

Those AT state machines aren't easy to finetune on Arduino. I spent a lot of time debugging similar code and found out that the best way is to unit test all possible situations in visual studio or xcode. Arduino is just C++ and if you copy/paste some portions of your code to C++ IDE, after implementing few functions or classes it should work. For example, to make your code working in XCode, I had to implement some dummy Serial1 class and simplify the loop code:

class _Serial1
{
    std::string buffer{"OK\r\n"};
public:
    int available()
    {
        return (int)buffer.size();
    }

    char read()
    {
        char c = buffer[0];
        buffer.erase(0, 1);
        return c;
    }
} Serial1;

void loop() {
    if (enabled == 1) {
        if (stat0 == 0) {
            if (Serial1.available () > 0) {
                pointingfinger++;
                serialdata[pointingfinger] = Serial1.read();
                if (serialdata[pointingfinger] == '+') {

                    searchcharpos = pointingfinger;
                    searchchartype = 1;
                    futstat0 = 1;
                }
                else if (serialdata[pointingfinger] == '$') {
                    if (smsvalid == 1) {  // ==
                        searchcharpos = pointingfinger;
                        searchchartype = 2;
                        futstat0 = 2;
                    }
                    if (smsvalid == 0) { // ==
                        stat0 = futstat0;
                        pointingfinger = 0;
                    }
                }
                else if (serialdata[pointingfinger] == '\n') {
                    stat0 = futstat0;
                    pointingfinger = 0;
                    enabled = 0;
                }
                else if (serialdata[pointingfinger] == '\r') {
                    stat0 = futstat0;
                    pointingfinger = 0;
                    enabled = 0;
                }
                else {
                    stat0 = 0;
                    pointingfinger = 0;
                }
            }

            if (pointingfinger == 255) {
                pointingfinger = 0;
                enabled = 0;
            }

        }
    }
}

And the compiler immediatelly pointed me at the incorrect assignments and also I was able to debug the code step by step and see what is happening inside.

In my situation I was interfacing SIMCOM900 gprs module and I made a state machine that allows me to write code like this:

virtual void Program()
{
    switch (Pc())
    {
        case 0: _ASSERT(strlen(mApn)>0);
                Stream() << "AT+CSTT=\"" << mApn << "\",\"\",\"\"\r\n";
                break;
        case 1: Expect("OK\r\n");
                if (Expect("+CME ERROR")) { Error("CME Error when attaching apn"); Return(false);}
                if (Timeout(25000)) Return(false);
            break;
        case 2: Stream() << "AT+CIICR\r\n"; break;
        case 3: Expect("OK\r\n");
                if (Timeout(15000)) Next(); break;
        case 4: Stream() << "AT+CIFSR\r\n"; break;
        case 5: if (ReadIpAddress()) Next();
                if (Timeout(2000)) Return(false); break; // longer?
        default: Return(true);
    }
}

Here is a bit older version of it:
https://gist.github.com/gabonator/88b80d9c6b16d699d6f4234ebc3a2587


REST API on Industrial 101 (Yún family) lags, then crashes

First of all you should try changing the delay(50);. Try using millis(); instead and see if the problem still persists.

int borderMillis = 50;
int startMillis = millis();

void loop()
{
  int nowMillis = millis();
  if(nowMillis >= borderMillis)
  {
    //ask for new client etc.

    startMillis = millis();
  }
}

If that doesn't help, try adding the yield(); method after the delay(50); / at the end of the loop. Sometimes the board just needs time to get the background duties finished, so this comes in handy.

My very last guess would be a memory leak. You could try to get the amount of heap you have left, and see if it continuously drops and won't get released. There are libraries that can help you to retrieve the amount of memory you've left.


With the arrangement you have described I would say it's very very hard to do what you want.

You know where the robot is
You know where the robot has to get to
You can easily calculate the direction the robot has to go in (simple trigonometry from school)

But:

You don't know what direction the robot is facing, so you don't know how to turn the robot to get it to drive in the direction you need.

So either you need some kind of calibration procedure whereby the computer moves the robot in different directions and watches what the IR LED does to determine what direction the robot is facing so it can move it to face the right way (tricky to do, and rather messy), or some way for the computer to visually calculate the direction of the robot.

The latter is probably the easiest.  Instead of just one IR LED on the top of the robot you would need an array of IR LEDs on top of the robot forming a shape.  What that shape is can be up to you, but there is one big constraint: It must have a clear direction to it (i.e., it must have no rotational symmetry.  Triangles are good since they only need 3 LEDs.  An equilateral triangle though wouldn't work since in three different rotations it would look the same.  However, a single LED at the front of the robot, with two LEDs at the back of the robot, with the two back LEDs closer together than the distance from the front to the back, would not have any rotational symmetry.

You could then, (theoretically, assuming you have control over the camera software), get the three points from the play area and calculate the direction the robot is facing (tangent from mid-way between the two close points passing through the distant point) so you can then calculate the angle the robot would need to turn through so it is facing the direction you need it to.

Remember in math class, doing trigonometry (sin, cos, tan, pythagoras, etc) thinking "Why the hell do we need to know this stuff?!", well, now you know.


Unable to upload to Arduino Due using version 1.6.8 of SAM tools; bossac.exe throwing an error

I finally figured out the problem. This occurred on both a Mac and PC (Windows 10).

This error occurred because of the true after the -w switch. To fix it I modified the package to tell the IDE not to use that switch.

Go to: %USER_PROFILE%\AppData\Roaming\Arduino15\packages\arduino\hardware\sam\1.6.8 (where %USER_PROFILE% is your windows user directory, for me it was C:\Users\user) in Windows Explorer.
Make a copy of the platform.txt file (I called it platform_backup.txt).
Open the file platform.txt with Word Pad (it had Unix line endings in my environment), search for the string:

tools.bossac.upload.pattern="{path}/{cmd}" {upload.verbose} --port={serial.port.file} -U {upload.native_usb} -e -w {upload.verify} -b "{build.path}/{build.project_name}.bin" -R
This was 3rd line from the bottom for me, and remove the text between the quotes "{upload.verify}". It should now look like this:

tools.bossac.upload.pattern="{path}/{cmd}" {upload.verbose} --port={serial.port.file} -U {upload.native_usb} -e -w -b "{build.path}/{build.project_name}.bin" -R
Restart the IDE so it can re-read the file you just edited. You'll now be able to upload to the Due.


to increase the reading and writing/printing speed of data from Arduino Nano to Raspberry Pi 3B+

parseInt reads digits and stops after a non-digit characters occurs or the function times out because no next characters arrives. The timeout is at default 1 second. So this is where you loose time.

Simplest solution for your code is to send some non-digit character after the number sent from Raspberry. This will terminate parseInt immediately. Usual is to send a new line character. It will separate the numbers nice if you debug the communication with prints to serial terminal.

Not a very good option, but I mention it, is to set the timeout of blocking read functions like the parseInt to a smaller time with Serial.setTimeout(ms).

To really speed up the communication you would send the numbers in binary form and not as text like you do now.


Arduino Uno to drive 2 unipolar stepper motors

No problem. Just use two ULN2003 chips, one for each stepper.

No need for a motor/stepper shield on these unipolar steppers.

It will not harm the arduino (if wired correctly).


I don't know if I got the exact error (maybe another sync error), but what helped in my case (in this order, try again every time):

Reinsert the USB cable
Use a different (shorter) USB cable
Put the USB cable in another USB port
Restart the Arduino IDE
Restart the computer
Reinstall the Arduino IDE
Go to device drivers (control panel), check for COM ports, remove Arduino and reinstall


Making servo spin and able to detect angle

The way I'd do it is the following:

use an optical encoder with an endstop, they come @ 1€ on ebay, bought 4 today :-) - this will tell you the angular speed and incremental position
use a photo transistor to detect a specific point on the wheel (make a small hole or paint a spot in a different colour) - this will give you
the absolute position of the wheel, to calibrate the previous step.

With this solution you do not even need a step motor, a DC motor will do it and probably has better characteristics, for the same cost.
So you could explore the DC option if it turns out that the stepper is not good enough.


what pins are attached to ethernet shield SD card?

Arduino communicates with both the W5100 and SD card using the SPI bus (through the ICSP header). This is on digital pins 10, 11, 12, and 13 on the Uno and pins 50, 51, and 52 on the Mega. On both boards, pin 10 is used to select the W5100 and pin 4 for the SD card.


handling array from post data on espwebserver

The ability for PHP to do this is special to PHP. The PHP program parses the field names as PHP arrays if they are named thus:

<form ....>
<input name="[colorsarray][0]" value="#ff0000" />
<input name="[colorsarray][1]" value="#2d67ea" />
<input name="[colorsarray][2]" value="#000000" />
<input name="[colorsarray][3]" value="#7cf325" />
[...]
</form>

But since the ESP8266's core doesn't use PHP or understand PHP arrays, you will have to use the literal field name [colorsarray][3], parse it yourself, and determine at run-time the length of the array and how much memory is needed, etc.


Maximum frequency of digital signal in Arduino Uno?

Yes, use the hardware timers.
You can achieve 8 MHz.

Example sketch which outputs 8 MHz on pin 9 on a Uno:

#ifdef __AVR_ATmega2560__
  const byte CLOCKOUT = 11;  // Mega 2560
#else
  const byte CLOCKOUT = 9;   // Uno, Duemilanove, etc.
#endif

void setup ()
  {
  // set up 8 MHz timer on CLOCKOUT (OC1A)
  pinMode (CLOCKOUT, OUTPUT);
  // set up Timer 1
  TCCR1A = bit (COM1A0);  // toggle OC1A on Compare Match
  TCCR1B = bit (WGM12) | bit (CS10);   // CTC, no prescaling
  OCR1A =  0;       // output every cycle
  }  // end of setup

void loop ()
  {
  // whatever
  }  // end of loop

If you change OCR1A you can get lower frequencies. If you change the prescaler you can get lower frequencies again.

See my page about timers for more details.


Can I use a mobile charger (output 5V) to power an Arduino Uno?


What is the difference between Nano 328p-au and 328p-mu?

The AU and MU on the chip just refer to the shape of the chip. AU is TQFP and MU is VQFN.

You can see the full list of suffixes here (select the red "Buy Now" tab for a table).


Arduino nano ATmega328p with CH341 won't upload

If you are using a fairly recent version of the Arduino IDE, try using the old bootloader for the 328P.
Go to Tools --> Processor:"ATmega329P" --> ATmega328P(Old Bootloader)


ESP8266 - AT Command for Network Requiring Username AND Password

We can't tell without more information but it sounds rather like you will need a [WiFi_SSID, WiFi_PASSWORD] pair for the ESP to connect to the WiFi, and a [Network_USERNAME, Network_USERPASSWORD] pair for their network to let you use the network (as if you were logging onto it by hand from a terminal).

If so, you'd provide the first pair as you do now, with the AT+CWJAP... command, to get your device connected to the WiFi. For the second pair, your Arduino will probably need to interact with a user logon screen to provide the second pair. You'll need to get those details from the school's IT department, and possibly mimic a terminal.

Update:
As above, you need to find out whether the network requires 2 sets of credentials - the SSID and WPA2 key and network username and password. If it requires the latter, then your ESP can get you onto the WiFi but your Arduino will then have to mimic a user sitting at a terminal - read the network ID and Password challenges and provide the appropriate responses. Without know that, you can't know how to write the login code, nor can we. It sounds as if there are people on site who have already done what you're trying to do. They and their experience can be far more helpful than we, who have no knowledge of the school network.


OV2640 with 18 Pins - No XLCK System Clock

In this specific OV2640 module, it's supposed to have a 12MHz oscillator in the board connected to XLCK pin (you can all time adjust the PLL trough SCCB interface as usual). Remove the plastic lens and see near the CMOS.
Regards


ESP01 and Arduino - Serial port confusion

The Arduino UNO only has one serial port. That is pins 0/1 (RX and TX), which is mapped to the Serial object.

Those pins and that object are also used for communication with the PC through the USB connection. That means you can't easily use them for both PC communication and ESP8266 communication. It's possible, but it gets messy.

That is why many people use SoftwareSerial because that can work on any combination of pins on the Arduino that you like.

  ... Also, as an aside, if I get this all working, do I still need the USB programmer, or can I then program directly from the arduino?

Again, that is possible, but very messy. You could possibly get things to pass through from Serial to a SoftwareSerial instance, but it's not reliable (SoftwareSerial in general is not reliable for sustained transfers of data), and using the Arduino as a dumb UART interface would entail changing the wiring to pins 0/1 when you wanted to program.

So it's far simple to just use your USB interface for programming. Either that or set up OTA programming for the ESP8266 so you don't even have to use wires.


I can't upload my program to Arduino Uno

Checks:

Check if the board has power (probably it will).
Check if the board is shown at the ports in the IDE (i.e. COM3: Arduino Uno).
Check if you put the correct board in the IDE (e.g. Uno, Mega etc.).
Check if you have multiple versions of the IDE running.
Check if you have multiple IDEs installed.
Check if you don't have the RX pin used while uploading a sketch.

Try the following:

Use a different USB port on your computer
Use a different USB cable
Reinstall the Arduino IDE


Error with Arduino/Processing Serial Communication

It seems like you need to do some basic debugging:

Put a println() in setup. If this does not appear, you have a major problem talking to the Arduino board.
Put a println() statement in the loop() that prints out the sensor reading. That should separate hardware problems from software defects.


Are there any Analog pins on the mega that can not be used as Digital?

No, the ATmegaXXX0 has no analog pins without GPIO capability.

Additionally, the ATmegaXX8PB adds GPIO capability to the other analog pins plus a couple of the supply pins, so if you can convince someone to slip one of those on instead then you will gain two GPIOs (a respin will be required to access the ones on supply pins). Note that the core will also need to be modified, but it's only a couple of quick changes.


Why do most arduino function return a -1 instead of a 0

I cannot assert anything for sure, as I was not involved in the design
of the Arduino APIs. However, just like Elliot Alderson, I suspect this
was inspired by the traditional C APIs. The manual page for getchar(),
which is a very old function from the standard C library, states:

  fgetc(),  getc() and getchar() return the character read
  as an unsigned char cast to an int or EOF on end of file or
  error.

Given that EOF is usually defined as -1, this is consistent with the
behavior of Serial.read().

Being beginner-friendly is also a major goal of the API. Pointers are
known to be a huge difficulty for beginners.

There may also be some efficiency considerations involved. Arduino
started on the AVR platform. This is a RISC architecture, with a large
number of generic CPU registers (namely 32). The compiler usually
manages to allocate most local variables to registers. The calling
convention ensures that in most cases function parameters and return
values also go through CPU registers. This means we can avoid many RAM
accesses, which are inherently much slower than register access. Using a
return-by-pointer convention defeats these optimizations.

Lastly, it is a good thing that simple things are easy to write. For
example, an interpreter for single-character commands can be very easily
written as:

switch (Serial.read()) {
case 'a':
    do_command_a();
    break;
case 'b':
    do_command_b();
    break;
// etc...
}

with no need to explicitly test for the serial buffer not being empty.
Obviously, a more complex command language will need a full-blown
interpreter, but the focus of Arduino has always been on simple
programs being easy to write.


Can a motherboard be a simple circuit between arduino uno and a set of devices (ie: motors)

I would call it an "interface" or "driver" board. You don't need to get too hung up on the exact name.
The word "shield" is one of the Arduino-peculiar words (like "sketch" for "code") which now has a generally-understood meaning. That meaning is, something that plugs directly onto the Arduino board, with the pins on the shield matching the sockets on the Arduino board.
Whilst a shield is a quick and easy way of getting started (because you don't need to wire anything) they can have their disadvantages. One being, what if you want two different functions, like a motor driver and an Ethernet interface? Two shields, one on top of the other? What if they both use a certain pin for different purposes?
I made up a radio-controlled car, see photo:

The only shield I used was a generic "put whatever you want onto it" shield, which let me mount some MOSFETs, a radio receiver board, and other components, as required by the design. There is a Uno underneath it, not particularly easy to see. Adjacent on the right is a motor driver board. A LiPo battery is slung underneath.
This kept things reasonably compact, without requiring a specific purpose-made shield which only does one thing.

and a custom circuit board (hence my question) will act as the interface between the uno and the motors, providing electricity from a dedicated source to the motors.

It sounds like your project is similar to my car. Just assemble things in a way that makes sense to you.


Message Interpreter and Handler - How to store a function name in a struct?

typedef void (*MessageHandler)(void);   // def messagehandler as pointer to func

struct AvcInMessage {
  MessageHandler  msgHandler;
  byte            dataSize;
  byte            data[8];
  char            description[20];
} InMessage[] = {
   {
      function1, <datasize>, {<byte0>, <byte1>, ..., }, "DescriptionHere"
   },
   // etc, for however many elements InMessage[] has.
};

The typedef defines a "pointer to function of void returning void" - fix up the argument count and types, and the return type to your needs. We're assuming each element's function has the same kind of arglist and return type. (Update: Sorry for the bug in my first iteration).

The next statement both defines the array of struct and initializes N of them. Provide an element count in the [] if you don't have a full set of initializers at compile time.


digital pin's current limit, ohm's law and DC motor

The ATmega (or any other processor that could reasonably be used on an Arduino) output pins consist of a Totem Pole driver with a PMOS transistor which can drive the output towards Vdd and an NMOS transistor which can drive it towards ground.  Each of these can be modeled as a switch which has a small resistance when "on", and due to device physics the PMOS transistor has a higher resistance than the NMOS.

The 40ma figure is an "Absolute Maximum" rating - a limit above which damage could be possible.  At some current less than that, it is likely the voltage drop across the PMOS transistor will start to be great enough that the output voltage can only marginally be considered a logic "high" - it will be notably less than the supply.

Connecting your motor to an ATmega pin is an extreme, far out of spec.  When you do that, the voltage drop across the PMOS transistor is much larger, making the output voltage quite low.  Additionally, the current flowing through the resistance produces heat within the chip, which can (at least as a rule-of-thumb concern) lead to damage.  Finally, your motor will produce inductive kickback, "spike" voltage possibly high enough to pierce the gate oxide of the MOS gates in the chip, destroying it.  Latchup is another possibility - a sometimes temporary condition where the bulk of the die ends up biased to conduct in the wrong direction and the chip effectively shorts out its power supply, turning it into a miniature space heater.

There really are no components on your typical Arduino board designed to directly control a motor.

Instead, for unidirectional control you should use a circuit with an NPN bipolar transistor, NMOS FET, magnetic relay, or solid state relay.  The latter are commonly available pre-assembled on shields.  With a transistor solution driving the motor in only one direction, it is generally advisable to pick an NPN transistor or NFET and place it in the negative lead of the motor, as the N devices work better due to the greater mobility of electrons than electron-holes.

For bidirectional control, look for a motor shield based on an H bridge IC such as the TB6612FNG or the less efficient bipolar L298 or L293/SN754410.  This basically puts a high current Totem Pole driver on each lead of the motor, allowing you to drive them high & low for one direction or low & high for the other.


Arduino Simple Task - sweeping a buzzer and led, not working as expected

From Arduino.cc:

  Use of the tone() function will interfere with PWM output on pins 3 and 11 (on boards other than the Mega).

Simple solution is to use a PWM that isn't an output from Timer2 :

Timer      OCxA pin    OCxB pin
  0           6        5
  1           9        10
  2           11       3


I think µProg – tiny, fast, portable AVR programmer with SD does what you want. You can store multiple files in the SD card (hex, eep etc) and select from the device menu which one to write to the target MCU without any need for a PC.
The best part is that it's available for free (PCB, schematic, firmware etc).

One of a kind, portable AVR programmer! Helps wherever you need to
update the device firmware, where target device is in a hard-to-reach
location and you can’t (or don’t want to) bring your laptop with a
bunch of wires with you. Trivially easy to use, super cheap to make,
super small, super fast, uses SD cards…
Features:

super small – dimensions 44 x 39 x 5,5 mm
super fast – write up to 12,5kB/s, read up to 14,5kB/s
uses cheap storage medium – small MICRO SD cards
supports FAT16 and FAT32 file systems
can read, write, verify flash and eeprom memory
can read, write, verify fusebits and lockbits
write and read to BIN, HEX, and TXT files
can set default values of fusebits, erase memories
cheap, easy to obtain, LPH7779 graphic display
shows funny animations after every operation
standard programming header – Atmel 6-PIN ISP
has a function of auto-update its own firmware (from SD)
very simple to use, 4 buttons navigation
user-setting menu
programming speed auto-selection (up to 4MHz)
Operates at 3V, programs chips supplied from 3V to 5V

Supported chip list


Class Print is a base class of Arduino streaming. Stream is a derived class and adds reading capability. Print has only one abstract method write to write one byte to output or buffer. It is easy to implement a derived custom class.

The classes derived from Stream are classes for hardware and software serial like HardwareSerial for Serial singletons and different software serial implementations. From Stream is derived class File of the SD and SPIFFS library, TwoWire class for Wire singleton object, etc.

Class Client is derived from class Stream and is a base class for Arduino standard TCP networking. Examples of derived classes are EthernetClient, WiFiClient. For UDP, class UDP is derived from Stream, of course with implementations like EthernetUDP, WiFiUDP.

You can see this in the source code in local source file folders or in GitHub repositories.


Can I program AVR Microcontrollers using Arduino Development board with AVR Studio?

You can use Atmel Studio to write code for the MCU(s) on the Arduino boards. If the IDE itself does not support uploading the code to the Arduino then it is still possible to use AVRDUDE or BOSSA to upload it via the command line.


Wrong data from DS18B20 temperature sensor after long power off

I researched this once when I was getting consistent, exactly 85 degC readings from my sensors. The Maxim DS18b20 data sheet (rev 042208, page 4, in a footnote to Table 1) says:

  "The power-on reset value of the temperature register is +85°C.

Double check that the Arduino code is follows the sensor communication protocol correctly.


Program got so many errors about expected ) or ; before either

Here's the first line of your code:

#define dw 8; //buttons down

Here's the first error line:

pinMode(dw, INPUT);

Let's put them together and see what we get:

pinMode(8; //buttons down, INPUT);

That's not valid C++. Using the output I've shown you, modify the input until it looks correct. And then keep doing it until the code compiles.


Controlling the Serial Monitor for 10 seconds

Using micros() is very much like boiling an egg.

When you want your egg to be cooked just right you know that it needs to be in the boiling water for a certain amount of time. There's three ways you can achieve that:

Use an egg timer to alert you when the time has passed,
Sit and stare at the boiling pot counting the seconds as they slowly tick by (booooooring..... ...zzzZZZzzz...)
Remember what time you put the egg in the water and glance at the clock every so often to see how much time has passed.

Using millis() is like option 3. It tells you how many milliseconds have passed since the board was turned on (or since the last millis() rollover at roughly 49 days). So when you put the egg in the water you record the current time. Then you periodically compare the recorded time to the current time (a simple subtraction will suffice) to see if enough time has passed. When it has you remove the egg and chow down.

So to put that more in a coding context - when you start some operation, or want to measure a period of time from a point, you just save the time in a variable:

start = millis();

(start must be uint32_t, aka unsigned long). To find if enough time has passed you just subtract that saved time from the current time and it gives you the elapsed time, which you can compare to your required elapsed time:

if (millis() - start >= 100) {
}

1/10 of a second is 100ms, so if you hit a difference of 100ms (or more) then your time has arrived and you can do something.

If you want it to do it again after that then just set the "start" time to the current time again.

For instance, for your requirements:

void loop() {
    // Record the start time - the static means it
    // only happens once the first time loop() is run and
    // it remembers the value between iterations
    static uint32_t start = millis();

    // Somewhere to store the number of values we
    // have given - again, static so it remembers across
    // iterations of loop()
    static uint8_t count = 0;

    if (count < 100) { // No more than 100 counts
        if (millis() - start >= 100) { // Tick
            start = millis(); // Do it again in 100ms time

            // Add whatever you need for your readings here

            count++; // Add one to the count
        }
    }
}


What is the purpose of '&' while passing bool as a function parameter

If you have a boolean b you normally assign it to true or false. If you pass in a function a boolean (or integer, char and most other simple types), a copy is made. So if you change it in the function, when the function returns, the copy is destroyed and the original value is kept.

However, you do not want a copy, so you need a reference (pointer) to that boolean. That is where the & is for. So bool &change is not a boolean, but a reference to a boolean. Whenever you change that reference, the original value of the boolean is changed, which is what you want.

Note, this is a C++ feature, it does not exist in C (there you use pointers instead: bool* change).


thank you for your suggestion. The issue isn't with the code but was with the button. I changed the button and it worked fine. Thanks for the help!


NTP rollover-safe design with ESP8266 (Curiosity)

This implementation is perfectly fine. The calculations are done with
unsigned numbers, so they are naturally rollover safe. The day NTP time
rolls over, secsSince1900 will become a very small number, and
subtracting SEVENZYYEARS from it will cause an extra roll over. Owing
to the rules of modular arithmetics, these two rollovers compensate and
you are guaranteed to get the correct result modulo
232 s.

In the end, you get a Unix time as an unsigned 32-bit integer. Unix time
is traditionally signed, which makes the 32-bit representation roll over
in January 2038. The authors of this library have instead chosen to
represent it as an unsigned number, which means it will roll over in
February 2106.


The millis() function is based on a counter which is incremented by
the Timer 0 overflow interrupt. Since you reconfigured
that timer to never overflow, that counter is not incremented anymore.

If you want to configure an Arduino timer for your own purposes, you
have to either:

use any timer other than Timer 0, or
loose the Arduino standard timekeeping functions: millis(),
micros() and delay().

I would favor the first option, especially on the Mega which has quite a
few spare timers.


I would consider using HoodLoader2 instead of that LUFA project. If you can't do that, you can compile parts of the Arduino Core together with the LUFA project.

The main steps:

Add the necessary Arduino source files to the SRC variable in the Makefile.
Add the Arduino core folder to the include path by appending to the CC_FLAGS and CXX_FLAGS variables.
Move the main function to a new main.cpp file and add it to the Makefile SRC as well.
Include the Joystick.h file in your main file in an extern "C" block.
Include the HardwareSerial.h file in your main file as well.

My files after these changes:

Makefile

# Set the MCU accordingly to your device (e.g. at90usb1286 for a Teensy 2.0++, or atmega16u2 for an Arduino UNO R3)
MCU          = atmega16u2
ARCH         = AVR8
F_CPU        = 16000000
F_USB        = $(F_CPU)
OPTIMIZATION = s
TARGET       = Joystick
SRC          = $(TARGET).c Descriptors.c main.cpp $(LUFA_SRC_USB)
LUFA_PATH    = ./lufa/LUFA
CC_FLAGS     = -DUSE_LUFA_CONFIG_HEADER -IConfig/
LD_FLAGS     =

ARDUINO_PATH = ${HOME}/.arduino15/packages/arduino/hardware/avr/1.8.1/cores/arduino
SRC         += $(ARDUINO_PATH)/HardwareSerial.cpp
SRC         += $(ARDUINO_PATH)/HardwareSerial1.cpp
SRC         += $(ARDUINO_PATH)/Print.cpp
CXX_FLAGS   += -I$(ARDUINO_PATH) -I./HoodLoader2/avr/variants/HoodLoader2
CC_FLAGS    += -I$(ARDUINO_PATH) -I./HoodLoader2/avr/variants/HoodLoader2

...

main.cpp

extern "C" {
#include "Joystick.h"
}

#include <HardwareSerial.h>

// Main entry point.
int main(void) {
    // We'll start by performing hardware and peripheral setup.
    SetupHardware();
    // We'll then enable global interrupts for our use.
    GlobalInterruptEnable();
    // Initialize the UART
    Serial1.begin(115200);
    Serial1.println(F("Hello, world"));
    // Once that's done, we'll enter an infinite loop.
    for (;;)
    {
        // We need to run our task to process and deliver data for our IN and OUT endpoints.
        HID_Task();
        // We also need to run the main USB management task.
        USB_USBTask();
    }
}

Joystick.c
Deleted the main function.

To get it to compile after these changes:

# (inside of the snowball-thrower folder)
git submodule add https://github.com/NicoHood/HoodLoader2.git HoodLoader2
make

This compiles without problems for me, but I have no idea if it actually works.

Edit:

You'll notice that the program uses more RAM than the ATmeg16U2 has available. You could solve this by moving the step array to PROGMEM, or by shrinking the Serial buffers.

avr-size --mcu=atmega16u2 --format=avr Joystick.elf
AVR Memory Usage
----------------
Device: atmega16u2

Program:    5076 bytes (31.0% Full)
(.text + .data + .bootloader)

Data:        527 bytes (102.9% Full)
(.data + .bss + .noinit)

 [INFO]    : Finished building project "Joystick".


Send them avrdude (including the config file) and the hex file. Look at the commands the IDE runs to see the right command format. You can then put that into a batch file if you like.


Connecting to the 5v/2A power supply would cause no trouble at all. Taking 4 minutes to compile is strange but unlikely to be related to the Arduino board. "programmer is not responding" errors are communication errors.

Did the program compile without errors?
Are any LEDs lit or blinking on your board?
Is the correct board selected in the Tools | Boards menu?
Is the correct port selected in the Tools | Ports menu?
Is the correct programmer selected in the Tools | Programmer menu?
Try another USB cable.
Try pressing/releasing the board's reset button right after you click the upload button.


km is never reset but continously incremented.

km = km + circ;

This leads to an overflow of the value after some time.

When you declare int km;, then int  on an Arduino Uno is int16_t, it thus has a maximum positive value of 2^15 - 1 = 32767. Since circ is constant 1854, after executing the ISR a total of CEIL(32767 / 1854) = 18 times, km becomes greater than that maximum positive value. Thus an integer overflow occurs which takes you back to the maximum negative value of the int16_t. (See https://en.wikipedia.org/wiki/Integer_overflow)

You might want to use uint32_t or similiar from stdint.h if you want to cover a greater value range. I think however your underlying algorithm is flawed, since even then km will  overflow after some later time. You must reset it at some point or only store the number of revolutions, which is a much smaller number. If you want to get the traveled distance then, you take the number of revolutions and multiply it by the circumference.

Also you should not not use any Serial printing within in interrupt service routine! And you should also declare your used interrupt variables as volatile. Read this article for more info.


To include \ in a string so it can be printed you have to escape it.  \ is itself the escape character, so doubling it up "escapes the escape character" so it is interpreted as a normal character.

So to print "c:\windows" you would actually have to type "c:\\windows" and the \\ gets changed by the compiler into just \


ESP12E motorshield analogWrite issue when powering DC motor

This answer is the summary of the comments of the question. The idea of the solution was originally mentioned by @Majenko.

You powered the shield with about 6 Volts. The statement analogWrite(PWMA, 5); gives you (5/1024) ~ 0.5% of this 6 Volts at the output pin PWMA. This 0.03V are not enough to drive the motor.

You should use at least 3 Volts to drive the motor (as of the specs).
This can be achieved by using a duty cycle of the PWM signal of about 50%.  analogWrite(PWMA, 512); should do the trick.


Connect it to an IO port and set it to OUTPUT and LOW. That's what it means to "pull low".

It helps if you understand how an IO port works. This may help you.


Arduino with 12 bit DAC (MCP4725) Not Working

you want to make sure that there are pull-ups on the SCL/SDA lines;
you want to make sure that the address is correct. some routines use 7-bit notation for that, and others use 8-bit notation for that. end of the day, you want the transmission to be 0xc0 | (A2:A1:A0:R/W). so check the write.write() and see what it expects. I suspect that it expects 0xCx, rather than 0x6x.

having said that, here is your code running on an uno, with the dac configured as per sparkfun spec.

so I think it is fair to say that the code is ok but something happened on your end that prevented it from working.


DHT11 and Liquidcrystal setting cursor issue

I guess it because you use

if(temp >= 0.00 || temp <= 5.00){ // writes over 0 OR under 5 which will always be true for all values measured

and not

if(temp >= 0.00 && temp <= 5.00){   // writes over 0 AND under 5 which you want


Problem with piezo readings and Arduino Due

The problem is timing.  When you tap or hit the sensor it produces an impulse response: a signal that increases to a peak, then decays back to zero.  You are expecting the code to capture the peak value.  Your code is spinning in loop() as quickly as possible, but captures just the first point above the threshold. The signal can still be increasing when you capture and print.

So imagine this stream of signal values

time  signal   analogRead()
      at pin   occurs
----  ------   --------
 1     190      190
 2     190
 3     199
 4     210
 5     220      220 - trips threshold, prints and then waits
 6     230
 7     260
 8     280
 9     320      (this point occurs during delay())
 10    280
 11    260

The same exact signal, but at a slightly different time could be read different by the code:

time  signal   analogRead()
      at pin   occurs
----  ------   --------
 1     190
 2     190
 3     199      199
 4     210
 5     220
 6     230
 7     260      260
 8     280
 9     320      (closer, but still did not read the peak)
 10    280
 11    260

So the strategy of catching the first point above the threshold makes it unlikely you can capture the peak value.  There are two ways forward: hardware or software.

You could use electronics that latches the maximum value.  If you search "peak hold circuit" you will find many circuits that would capture and hold the peak.  That frees the Arduino to somewhat lazily spin in the loop and still be able to accurately capture the peak.  Once it sees the value is no long increasing, it resets the peak hold and goes back to waiting.

You could use code to capture the peak. Something along the lines of this psuedo code:

lastreading = analogread()
if(lastreading > threshold) {
  peakreading = lastreading
  keeplooking = true
  while(keeplooking) {
    nextreading = analogRead()
    if(nextreading > lastreading) {
      // the signal is increasing, save this and see if next point is even higher
      peakreading = nextreading
      lastreading = nextreading
    }
    else {
      //signal is decreasing, the peak is over
      keeplooking = false
    }
  }

This software approach could still miss a sharp peak that occurs between analogRead()'s, but may be good enough for your use.


Yes, people have done this before, and they have documented it on their own blogs and similar sites.  Maybe you should have asked Google first before you came here?  You'd most likely have ended up on instructables, where someone has documented exactly what you want to do and how to do it. and saved yourself this entire step.


sending room temp data from multiple esp8266's to Mega 2560 to control CH gas boiler

I am also in the middle of converting the control of my heating, multi-zone, but using Ciseco / Wirelessthings units as temperature sensors both inside and out. See https://www.wirelessthings.net

Simple serial interface is all you need from the Arduino to run these on a network. The coin cell battery lasts for over 1 year running 1 sample / 10min - the sample rate is configured but obviously the more samples you send the more the battery drains. Range seems to be OK and gets through 3 floors in the house and from the outside. I do use external antenna on the Arduino wireless unit to ensure I get all of the sensor readings.

However sounds like your house is BIG if running 3x WIFI extensions where as a single WIFI base station does me fine.


How to send signal ONCE when within constant range of sensor?

You have to add a (global) variable that stores the last send command (to open/close).

When you send a command, you save it in the global variable.

And you only send a command when it is different than the command send the last time, so only CHANGES are sent.

The best way to do this is to make a specific function, e.g. SetSolenoid(bool open);

#define SOLENOID_OPEN  TRUE
#define SOLENOID_CLOSE FALSE

bool _currentSolenoidStatus = false; // Assume closed

In your loop:

...
if  ... condition when solenoid should be be opened
{
    SetSolenoid(SOLENOID_OPEN);
}
...
if  ... condition when solenoid should be be closed
{
   SetSolenoid(SOLENOID_CLOSE);
}

Function to open/close solenoid open (only when changed):

bool SetSolenoid(bool status)
{
    if (_currentSolenoidStatus != status)
    {
        // Send status to solenoid
        _solenoidStatus = status;
    }
}


How do I read numbers from a serial sequence

I don't have a separator to use

You do. There is a space before the integer part of the frequency, and a
decimal point just after it. You can use strchr() to find them. Then,
you will have to prepend a zero if needed, and terminate the string one
character before the decimal point.

The following code does this by overwriting the original string. If you
need to keep that string, you will instead have to copy the relevant
characters to another buffer:

char * get_freq(char *message)
{
    char *space = strchr(message, ' ');
    char *dot   = strchr(message, '.');

    if (!space || !dot || dot - space < 5)
        return NULL;    // invalid message

    if (dot - space == 5)
        *space = '0';   // prepend a zero

    *(dot - 1) = '\0';  // terminate the string

    return dot - 5;
}


RFM95 digital io to control mute on PAM8403 to get rid of hiss while receiving

No, there is no way you can use the DIO pins to indicate sleep mode. They can only be set to indicate certain events, and sleep/idle is not one of them.
However the nRESET pin is optional, and you can use the setPins() function in the LoRa library to change which pin it's connected to - and one option is to set it to -1 in which case the library ignores it (this must be run before .begin() is called) as it's only used during begin() to initially reset the LoRa module.
You could either tie nRESET HIGH (to 3.3V) to never reset it, or couple it with the reset signal of another peripheral so it gets reset at the same time - just be careful with your initialisation order in this case so you don't reset the module after configuring it...


Generating PWM using Arduino Uno and Simulink (interfacing) pins 5 and 6. What's the maximum frequency?

See my page about timers. The maximum frequency the hardware can output is 8 MHz if you are running a 16 MHz clock.

10 kHz should be easily achievable if you tweak the hardware registers, as Gerben said.


How do I listen for a sound that matches a pre-recorded sound?

About the simplest starting point is to use an FFT (fast Fourier transform) library (like ArduinoFFT at openmusiclabs.com) to characterize the spectrum of an audio stream.

[Edit: An alternative method (digital bandpass filter) is mentioned below.]

Audio typically is made up of many frequencies of many amplitudes and phases, mixed together.  FFT sorts some of that out; it estimates the amplitudes of the various frequencies that make up a bit of audio.

The general idea is to use an Arduino ADC to take readings of an audio voltage for a fraction of a second, then use FFT to convert the large set of readings to a small set of numbers, in eg a set of 32 or 64 frequency-bins, to represent amplitudes in given frequency ranges.  For example, if the sound during a sample is a mix of five sine waves at five frequencies, the bins those five frequencies are in should have large numbers assigned, while other bins should have small numbers.

The approach would amount to sampling at 10KHz for 0.1 second or so, computing an FFT with 32, 64, etc. bins in the next 0.1 second, and comparing bin counts to a training pattern.  Whenever bin count patterns match reasonably well, start a three-second timer; if several seconds of matching samples occur, declare a match.

If the bell is electronically generated and mostly a mix of pure sine waves, then its sound will have an easily recognized spectrum.  But if the sound source is buzzy and there is background noise, it may be difficult to compare spectra.  See eg
• Comparing an audio signal with a previous 'taught/profiled' signal
• How do I compare chords played on a guitar with a known sample?
• How do I compare 2 audio files, returning a percentage of difference
• What does the phase of a FFT bin of an audio signal represent?
• Sound pattern matching using Fast Fourier Transform in Windows Phone
• How do I go about detecting whistles, pops and other sounds in live audio input?
• The Frequency Domain
Section 3.4: The DFT, FFT, and IFFT

An alternative: digital bandpass filter

Digital bandpass filters are based on processing a signal in a way that detects the amplitude of the signal's frequency component within designated limits.

For theoretical background see wikipedia's Digital filter article.  Also see Vaseghi, Chapter 5, Digital Filters, (eg section 4.6.6, Design of Band-Pass FIR Filters) pdf file and
ECE438 digital filter design lecture notes
pdf file.

You can use MatLab or Octave to do most of the work of designing a filter.  For example, if you have the Signal package installed and loaded into Octave, commands like

v=cl2bp(30, 0.48*pi, 0.52*pi, [0.02, 1.02, 0.02], [-0.02, 0.98, -0.02], 2^11);
freqz(v);
v

will compute coefficients for a Constrained L2 bandpass FIR filter, plot the freqency response (as below), and display the 60 coefficients.  To use the filter, copy the 30 non-zero coefficients into a program, set up a rolling array of readings, and at each sample compute a new filtered value.  If at some point high filtered values occur, and if they recur for about three seconds at the bell's frequency or twice its frequency, then the bell is ringing.  Note, there are other kinds of bandpass filters; the Constrained L2 bandpass FIR filter is shown for convenience, but other kinds may be better.

If you are unfamiliar with signal processing, you might need to try the following approach:
1, On your development system, obtain a few seconds of audio to use for tests. (Eg, allocate two buffers of several dozen bytes each; fill one buffer while using the other buffer to send data from the Uno to your development system.  Use (eg) Serial.write(buf, len) and a high data rate, eg 115200 bps, to send binary data, with three ADC readings packed per four bytes.)
2, Use Octave or similar software to try out several different FFT or filter approaches.  You would use FFT to determine the bell's fundamental frequency and then could try out digital bandpass filters while developing a recognizer.  You can also use mkfilter to design filters to try out in C programs on your system, and should be able to iterate more quickly while developing your approach than if you were developing it using the Uno.  When you get satisfactory results on your development system, you then can code a sketch to test the technique on your Uno.

Note, for a given filter order, filters implemented using fixed-point integer arithmetic on an Uno can handle more samples per second than those implemented using floating arithmetic.  An Uno might support 50000 to 100000 floating multiplies and adds per second (1,2,3,4), vs. two to four times as many fixed-point operations per second.  If your filter uses a dozen floating point ops per sample, your sample rate probably would have to be under 5000 samples per second.  If it uses half as many floating ops or uses fixed point instead of floating point, your sample rate could be twice as much.


It seems that the problem with the GPS was caused by my usage of the arduino delay(...) method in my loop.

I'm assuming that by using delay, the connection to the GPS module was being severed, and in effect, every loop was forcing a reconnect and a new download of satellite details.

In summary, when needing high sample frequency interaction with the GPS, using delay in the sketch won't work.

EDIT:

I've done a lot of digging since originally posting this question/answer and wanted to add my findings for others that are struggling to make the MKR GPS module work for higher than 1Hz sample rate use cases.

I had to make the following two changes to the Arduino_MKRGPS library:

increase baud rate of the GPS connection.  In the very last line of GPS.cpp...

GPSClass GPS(Serial1, 460800, serialDDC, 400000, 7);

In GPS.h, make the sendUbx method a public member of the GPS class.  This allows me to send low-level commands to the SAM-M8Q from my sketch.

After this, I can construct low-level messages in my sketch and configure the GPS to my liking.  Here's what I did to increase the sample rate to 3Hz in my sketch's setup method:

  Serial.println("Configuring GPS refresh rate...");

  //  UBX-CFG-RATE (0x06 0x08) Navigation/Measurement Rate Settings
  //  See UBX-13003221 section 32.10.23.1
  byte payload[6];

  memset(payload, 0x00, sizeof(payload));

  uint16_t measRate = 333;    // ms between gps data publish  (min of 100)
  uint16_t navRate  =   1;    // ratio between measurements and nav solution calculations
  uint16_t timeRef  =   1;    // The time system to which measurements are aligned (0: UTC, 1:GPS, ...)

  // write out the unsigned shorts in little-endian form
  payload[0] = measRate & 0xff;
  payload[1] = (measRate >> 8) & 0xff;
  payload[2] = navRate & 0xff;
  payload[3] = (navRate >> 8) & 0xff;
  payload[4] = timeRef & 0xff;
  payload[5] = (timeRef >>8) && 0xff;

  GPS.sendUbx(0x06, 0x08, payload, sizeof(payload));

  Serial.println("  > done");

Hope this helps someone else struggling with higher data rate use cases.  There's still room for improvement, I think, in particular by reducing the number of sentences returned by the GPS.  I haven't been able to get the sample rate higher than 5Hz, while technically the GPS is supposed to be capable of doing 10Hz.  I'm not sure where the bottleneck is.


Not knowing what virtual breadboard does on a normal Arduino it would do the following:
Serial.flush() clears the buffer  and this needs some time normaly you wait minimum for around 100 ms to write/read to that buffer again. As your code runs in setup (so just once) the serial is not available as its still flushing and so your result.
As the name setup says this should only be used to setup HW/SW but not to run routines as you may get all sorts of weird results. If you use "\n" aka newline terminators in your communication you can go for them and flushing would be only necessary if the connection is interrupted and you have to resend data.
EDIT

Waits for the transmission of outgoing serial data to complete.

If you send a character, it is placed in a buffer for transmission. It takes time for each character to be sent because serial is slow. Once it is in the buffer, it will be sent automatically in the background while the program immediately moves on to the next statement. This is done so the program won't waste time waiting for characters to be sent.

flush() is a way to wait for it to be sent, instead of immediately moving on in the user program.

So after calling flush() you can be sure that all data has been sent, and the buffer is empty. So in your case where you placed it it makes no sense.


Do motors need to have capacitor even if being used with motor shield

If the motors have a lot of "brush noise" you need to add capacitors to the motor. It is written in the FAQ.

The noise must be suppressed at the source or the motor leads will act like antennae and broadcast it to the rest of the system link.


Okay so i figured it out. The problem is that the for loop is starting at 0 and counting all the way up to the midpoint. What I wanted is for it to light all the LEDs that are at j and below. So I changed it to iterate down instead of up. Here's the new loop:

for(int l = j; l < midpoint & l > -1; l--){
   leds[l] = CRGB (R, G, B);
}

The extra qualifier l > -1 is to make sure that it doesn't try to go below leds[0]


How long does it take for a servo to change rotation?

Normal servos don't provide any feedback. Their speed depends on the servo's specs and the load.

You could measure the time it takes to rotate a certain angle and use that to calculate the time, then add some safety margin. But if the load isn't constant, the times will be off.
You could change the position slowly, but that still doesn't guarantee that the servo will do what you told it to.

If you want to know servos's position, you need a servo that outputs it. There are servos that expose the signal from their internal potentiometer.

Adafruit sells them and has a useful guide about them.

You can also modify a normal servo yourself, by attaching a feedback wire to the potentiometer's wiper pin.


Uploading Sketches from Windows Command Line

Turns out that the Ignoring Bad Library Name error that I had been receiving regardless of if I ran Arduino IDE through command line or standalone was the issue. For whatever reason it was blocking the script with a dialog that then failed the upload regardless of if I manually moved through the popup.

Final setup for those looking for this in the future:

Windows 8.1 x64 with Arduino IDE version 1.5.6-r2(I will revert to 1.0.5 and test with that, and report results) using a Leonardo board. Command is as follows:

Working Directory: C:\Program Files (x86)\Arduino

arduino --board arduino:avr:leonardo --port COM14 --upload C:\Users\Dev\Documents\Arduino\sketch_jun06a\sketch_jun06a.ino

EDIT: As promised, I attempted this with version 1.0.5-r2 and was unsuccessful. Potentially a 1.5.+ feature.


How much current can arduino ground absorb?

No your gnd won't get damaged if you source current through it. If u need explanation let me know


HC-SR04 distance measuring without delay?

delay() causes the processor to do nothing but wait.  You need to switch to millis().

In your code, you need to "grab" the current time using millis() and store it in a variable.  Add the number of milliseconds that you want to wait to this variable - you will have to consider the case where this value will overflow for a complete solution. Then, in your code, you need to create an infinite loop where you check what millis() returns.  When your stored value and millis() match, it is time to execute the code that would normally come after the delay() call.

Here, Arduino Playground - How and Why to avoid delay(), delay() and millis() are discussed in detail.

So that this answer will cover your question, consider placing all your events which need to be timed into this one infinite loop.  Also, consider keeping independent variables, one for each timed event, such that different events are timed independently.


The 5V regulator is only used when you are powering from external power (>5V). The 3.3V regulator is only used by things that you power from the 3.3V pin on the Micro.

So if you aren't using external power you don't need the 5V regulator. If you aren't using any 3.3V devices then you don't need the 3.3V regulator.

You can use any micro USB or even mini USB connector you like. If you ignore the "ID" pin you can even use an old-fashioned chunky USB B connector like on the Uno.

The circles are fiducial markers and are special patterns on the board used for aligning a pick-and-place machine when manufacturing.


Attempting to monitor serial output for a string to trigger function, apparently matching string is output but the function doesn't trigger

You're confusing readlines() with readline().  The former returns an array of lines, the latter a single line.  You need to drop the [0] since you're not working with an array of lines, and you need to include the line endings that the Arduino sends:

while True:
    message = ser.readline()
    print(message.decode('utf-8'))
    if message == 'MOVEMENT\r\n' :
        send_email()
        time.sleep(0.5)


Assuming the speed of sound is of the order of 330 m/s, you expect
the round-trip to the target and back to last about 1.8 ms. Then

recieved = pulseIn(echo, HIGH);

should give a value close to 1,800, and

recieved = recieved * 1000000.0;

should make received something like 1.8 × 109.
Then

speed_of_sound = (2*target_distance)/recieved;

gives a speed of sound of 3.3 × 10−10. It is the
correct value if you want that speed in meters per picosecond, but this
is inconsistent with your program printing “m/s” after the value.

The Arduino's Serial.print() is quite dumb with floating point
numbers. It defaults to printing two digits after the decimal point,
irrespective of the order of magnitude of the number. Thus, anything
smaller than 0.005 gets printed as “0”.

I don't quite understand why you got ∞ on the first loop. Looks like
pulseIn() missed the pulse and returned zero, in which case the speed
is computed as 0.6 ÷ 0 = ∞.

The solution is to compute received as

recieved = pulseIn(echo, HIGH) * 1e-6;

This can be remembered by thinking that a quantity (round-trip time) is
a numeric value (pulseIn(echo, HIGH)) multiplied by a unit (1e-6,
which stands for “microseconds”).


Generating and reading a PWM signal at the same time on Arduino Uno R3?

You are declaring the variables prev_time and pwm_value as int, which has (on a standard Arduino) 16 bits. Since you use the signed variant, you get a range of values from -32768 to 32767. But micros() is returning an unsigned long, which has 4 bytes (32 bits) and is not signed. With int there are only 32.767 ms (since it represents microseconds here), without letting the variable overflow. Even the full range would give you only about 65 ms. It simply cannot hold a value like 1000000. If you assign this value to an int, it will directly overflow (which - I think - would give you the value modulo 2^16), effectively loosing big parts of the information. You cannot get meaningful results with this in such a high time scale.

When measuring time (with millis() or micros()) you should always be sure to use unsigned long as type to prevent these problems.

Apart from the variable type, why do you use micros() here? You are measuring times in the hundreds of milliseconds, so why not use millis()? This would keep the values lower.


Yes, the output will be a pwm. You can see it from the schematics.
you have few options, with different precision and complexity:

Configure one of the PWM HW blocks
Do it by sw in a loop
Use a timer to trigger a sw function - but it might be simpler to just configure the PWM HW block.
Use some existing library that will implement one of the methods I listed

I would recommend Option 1: it's not so difficult, you will learn something of the AVR internals and it will be the solution with the least overhead. You can have a look at this tutorial. There are also many others floating around.


After some trial and error, I think I can answer this one myself.

The circuit schematic from the Seeed module is actually broken and the Apotec model is built almost identically. The PN532 chip has an SVDD output pin to power an optional security access module for cryptography support. In the Seeed design, this pin is connected to the 3.3V input voltage from the voltage regulator, which is simply wrong and the pin sinks an essential amount of current.


SIM900 AT command HTTP GET request not show the web page

From what I can see in your results, it seems AT+HTTPINIT returned an error. This means the HTTP service wasn't even successfully activated. So there's no way the commands you issued later would have been successful. From the AT command manual, AT+HTTPINIT is necessary before you can do any HTTP-related stuff.
You need to run the command AT+CGATT=1 to attach GPRS, even if your query shows its value is already 1.
It could also be that your APN requires authentication, using a username and password. So once you find out the username and password authorized by 'indosatgprs' (customer care?), you can use them in the following commands.

    AT+SAPBR=3,1,"USER","Enter the username here"
    AT+SAPBR=3,1,"PWD","Enter password"

Both commands should return OK if successful. To view all the parameters you have set, you can use AT+SAPBR=4,1. If all the parameters are satisfactory, and you have sufficient airtime in the SIM, then you can attempt AT+HTTPINIT. Only if this command returns OK, should you proceed to run AT+HTTPPARA-related commands.


This is probably way to late, but with newer editions of the Micro you have to "double-press" the reset (input).

I have had some experiences today where playing with low-power modes that shuts down the usb interface, and the only way I got it back was activating the reset input twice fast, and then uploading a new scetch (this time with a 10sec delay before any usb-chaning stuff takes place!)

Richard


How to run atmega328p at 8, 4 and 1 mhz?

If you run your MCU at 8 MHz, everything will run at this frequency: not
only the CPU core but also the timers, including Timer 0 which is used
for millis(), delay(), etc. So you will have to use a modified
version of the Arduino timing functions in order to cope with this clock
frequency.

Fortunately, such version already exists. Actually, it is even supported
by the standard Arduino core, since it supports the 3.3 V version
of the Arduino Pro Mini, which uses an ATmega328P clocked at 8 MHz.

I thus suggest you install an 8 MHz crystal, burn in the bootloader
for the 3.3 V Pro Mini, and tell your IDE that you are using that
board. In the Tools menu:

set board to "Arduino Pro or Pro Mini"
set processor to ""ATmega328P (3.3V, 8 MHz)"


TX code

#include "sha256.h"
#include <Arduino.h>
#include "./printf.h"

#include <SPI.h>
//~ #include <TMRh20nRF24L01.h>
//~ #include <TMRh20RF24.h>
#include <nRF24L01.h>
#include <RF24.h>

#define CE_PIN   9
#define CSN_PIN 10

// NOTE: the "LL" at the end of the constant is "LongLong" type
// These are the IDs of each of the slaves
const uint64_t slaveID = 0xE8E8F0F0E1L  ;

RF24 radio(CE_PIN, CSN_PIN); // Create a Radio

unsigned long currentMillis;
unsigned long prevMillis;
unsigned long txIntervalMillis = 1000;
int txVal = 0;
int ackMessg[6];
byte ackMessgLen = 4;

uint8_t* hash;
uint8_t copy[32];
void printHash(uint8_t* hash) {
  int i;
  for (i=0; i<32; i++) {
    Serial.print("0123456789abcdef"[hash[i]>>4]);
    Serial.print("0123456789abcdef"[hash[i]&0xf]);
      copy[i]=hash[i];
  }
  Serial.println();
}

void setup() {
  printf_begin();

  uint32_t a;
  unsigned long ms;

  Serial.begin(9600);

  radio.begin();
    radio.setDataRate( RF24_2MBPS );
    radio.enableAckPayload();
    radio.setRetries(3,5); // delay, count

  // SHA tests
  Serial.println("Test: FIPS 180-2 B.1");
  Serial.println("Expect:ba7816bf8f01cfea414140de5dae2223b00361a396177a9cb410ff61f20015ad");
  Serial.print("Result:");
  ms = micros();
  Sha256.init();
  Sha256.print("abc");
  printHash(Sha256.result());
  Serial.println();
  for(int x=0;x<32;x++)
        {   Serial.print(copy[x]);
            Serial.print(" ");
                                  }
            Serial.println();

  Serial.print(" Hash took : ");
  Serial.print((micros() - ms));
  Serial.println(" micros");
  Serial.println();

  }

void loop() {

  currentMillis = millis();
    if (currentMillis - prevMillis >= txIntervalMillis) {

    radio.openWritingPipe(slaveID);
    bool rslt,rsltt;
    rslt = radio.write( copy, 32 );

    if ( radio.isAckPayloadAvailable() ) {
        radio.read(ackMessg,ackMessgLen);
        Serial.print("Acknowledge received: ");
        Serial.print(ackMessg[0]);
        Serial.print("  ");
        Serial.println(ackMessg[1]);
    }
    prevMillis = millis();
 }

}

Rx code

// HandController - the slave or the receiver

    // http://tmrh20.github.io/RF24/

    //~ - CONNECTIONS: nRF24L01 Modules See:
    //~ http://arduino-info.wikispaces.com/Nrf24L01-2.4GHz-HowTo
    //~ 1 - GND
    //~ 2 - VCC 3.3V !!! NOT 5V
    //~ 3 - CE to Arduino pin 9
    //~ 4 - CSN to Arduino pin 10
    //~ 5 - SCK to Arduino pin 13
    //~ 6 - MOSI to Arduino pin 11
    //~ 7 - MISO to Arduino pin 12
    //~ 8 - UNUSED

#include <SPI.h>
//~ #include <TMRh20nRF24L01.h>
//~ #include <TMRh20RF24.h>
#include <nRF24L01.h>
#include <RF24.h>

#define CE_PIN   9
#define CSN_PIN 10

// NOTE: the "LL" at the end of the constant is "LongLong" type

const uint64_t   deviceID[2] ={ 0xE8E8F0F0E1LL,0xE8E8F0F0E1LL}; // Define the ID for slaves

int valChange = 1;

RF24 radio(CE_PIN, CSN_PIN);
RF24 radioo(CE_PIN, CSN_PIN);
uint8_t  dataReceived[32];

int ackData[2] = {12,23};

void setup() {

    Serial.begin(9600);
    Serial.println("Hand Controller Starting");
    radio.begin();
    radio.setDataRate( RF24_2MBPS );
    radio.openReadingPipe(1,deviceID[1]);
    radio.enableAckPayload();
    radio.writeAckPayload(1, ackData, sizeof(ackData));
    radio.startListening();

}

void loop() {

 unsigned long startTimer = millis();

    if ( radio.available() ) {
        radio.read( dataReceived, sizeof(dataReceived) );
        radio.writeAckPayload(1, ackData, sizeof(ackData));
        Serial.println();
        //Serial.println(startTimer);
        Serial.println();
        for(int x=0;x<32;x++)
        {Serial.print(dataReceived[x]);
        Serial.print(" ");}}
        ackData[0] += valChange; // this just increments so you can see that new data is being sent

    }

it is fully working now with both outputs on the same size


According to the source code implementation of analogWrite function
(Arduino analogWrite source code explanation).

You can use OCRnx register for reading PWM value.


It's a pull-down resistor.

A pull-up or pull-down resistor is used the make sure that the input of a digital device is confined to strict logic levels, i.e +Vdd (positive, or HIGH) or GND (Ground, or LOW).

With the switch open and no resistor present, the Arduino pin is neither high nor low. It will probably read as low if you tried digitalRead(), but there's no guarantee. The probability of the pin being one or the other changes according to the layout of the PCB and other external factors; the pin is termed 'floating' because it could be at any voltage between Vdd and GND.

However, if you apply a pull-(somewhere) resistor you force the Arduino pin to one of either Vdd (up) or GND (down) until you press the switch, at which point the Arduino pin switches state.

If you removed the resistor and joined the switch directly to ground, what happens when the switch contacts close?

Think about it...

One side of the switch connected to Vdd.

The other side is connected to the Arduino and GND.

Close the switch, I dare you.

Vdd is now connected to GND


How precise can I get Arduino using rotary encoders?

Interrupts are what you would use in this situation.

The rates that you have mentioned are slow enough where you probably would be able to count it inside of a loop, however this is not recommended, as a typical loop will take many clock cycles to complete, and depending on the number of instuctiuons per loop, you may miss some counts.

Interrupts are made for this purpose, as they can be triggered at any time, regardless of the state of the loop.

There is a function named attachInterrupt() which will take three arguments.

Interrupt Pin
Interrupt Service Routine
Mode

Below is an example for counting an interrupt

volatile int myCounter = 0;

void setup(){
    attachInterrupt(0, count, RISING);
}

void count(){
    myCounter++;
}

The Modes are as follows:

  LOW, CHANGE, RISING, FALLING

More information about using interrupts can be found here.

Depending on the encoder you use, you will need to tailor the code your needs, and do some more calculations to determine your position, but this should be a good starting point.

Edit
Here is some example code from Arduino Sandbox for using a rotary encoder.


Sending Large Packets and Reassembling over Serial

Let me dissect your program and show you precisely what is going on and why your approach is completely wrong:

Your first step is to throw 30,000 bytes at the serial port. Those go via the TX ringbuffer, which is (as you have changed it for some reason) 256 bytes:

buf = (char*)calloc(1,30000);

Serial.println("Writing to Serial3");
  for(i=0;i<30000;i++){
    Serial3.write((byte)i);
    cksum+=j;
    j++;
    if(j>255){j=0;}
  }

At this point 29744 bytes have left the hardware UART. 256 are still sat in the TX ringbuffer being sent out by the TX interrupt routine.  The first 256 bytes that were sent out were picked up by the RX interrupt routine and stored in the RX ringbuffer. The next 29488 bytes were discarded (they are now all over the carpet with your marbles).

 Serial.println(cksum);
 Serial.println("Reading from Serial2");

Now you try and read 30,000 bytes from the 256 byte RX ringbuffer. While you are doing that the remaining 256 bytes in the TX ringbuffer are being slowly sent out. You are now making some room in that RX ringbuffer since you are removing bytes from it, so some of the remaining 256 received bytes can now be stored in it. The first one of those happens to be 0x30.

 Serial2.readBytes(buf,30000);

Now you go and print out your array, which has only a tiny fraction of the 30,000 bytes you sent in it.

 cksum = 0;
  Serial.print("Buf is: ");
  for(i=0;i<30000;i++){
    if(i<300){ //only print out the first 300 characters
      Serial.print("[");
      Serial.print(buf[i],HEX);
      Serial.print("]");
    }
    if(buf[i] != j){
      Serial.print("\nMismatch at i = ");
      Serial.print(i);
      Serial.print("\nBuf is: ");
      Serial.print(buf[i-1],HEX);
      Serial.print(",");
      Serial.println(buf[i],HEX);
    }
    cksum+=buf[i];
    j++;
    if(j>255){j=0;}
  }
  Serial.println("\n\nEnd");
  Serial.println(cksum);

}

The simple fact is, you are transmitting, en-masse, far more bytes than the Arduino's RX ringbuffer can hold. In order to receive more than the 256 bytes of the ringbuffer you have to read the bytes from that ringbuffer to make room for more to arrive. And since you are the one that is transmitting that means you have to do your receiving at the same time as the transmitting.

The only possible way that your arrangement of program could work would be if you increased the RX ringbuffer to greater than 30,000 bytes so it can store all the received bytes as you transmit them for you to then, afterwards, copy the contents of that ringbuffer into your own buffer.


How to keep track of millis during sleep mode

The only way to keep millis() running is sleep mode is to sleep in
SLEEP_MODE_IDLE. Switching to Timer 2 would make no difference, as
all timers but the watchdog are stopped in other sleep modes. The
watchdog is horribly inaccurate, so you do not want to rely on it for
any kind of timekeeping.

  I don't see much advantage to sleeping for 1 ms.

Sleeping for 1 ms saves a little bit of power. But if you do that
60 times every 80 ms you will save a lot of power. I suggest
you do just that: sleep when you are done with your calculations. When
you wake up, if you see that the waking up came from the external
interrupt, the you process it. Otherwise you just go back to sleep.

Note that if the 80 ms period of the external interrupt is
consistent enough, you could use that as time source.


How to use Atmega1284AU with Arduino IDE

Please check out MightyCore library by MCUdude.

https://github.com/MCUdude/MightyCore

I have used it and can verify it works pretty well with ATmega1284.


What is the difference between delay() and delaymicroseconds()

There is a more important difference between the two functions other than the unit of time the accept as parameters
the function delay() calculates time using the time interript of the arduino. However Delaymicroseconds() does not use the time interrupt
As you may know once an interrupt is called it stops all other interrupts
So the real difference is you can not use delay() in a program in which you are using an interrupt and instead, use delaymicroseconds() but be aware that it has a range where it is accurate and it is between 3 and 16383 micro seconds


How to use 503 Thermistors for temperature?

First of, 503 means 50 x 10^3, ie 50K Ohm: that is the maximum resistance of this thermistor (the higher resistance occurs for lower temperatures). However, having just that without any precise reference may prove difficult to find a relevant datasheet that could help you calculate the temperature from the measured voltage.

I think what could work well is just simple calibration by establishing a mapping between
the value returned by analogRead() and the temperature measured by a real, good precision, thermometer.

Establighing the mapping for 2 extreme temperatures would provide a first approximation on computing any temperature from the read value.

However, such an approximation would not be very accurate because thermistors are not linear, ie their resitance don't vary linearly with temperature.

What you can try to do then, is to increase the number of mapped value<->temperature with regular intervals of temperatures; then you can use linear approximation between two consecutive mapped values, which would provide better results.

The difficulty here is to "produce" the temperatures for which you want to find the mapped value: if you can spend one year for that, then just let the chqanging seasons operate that for you :-) otherwise use what you can find at home: fridge, oven, fan, heater...


as far as I can determine uploading to SPIFFS via the Arduino IDE is broken as of the beginning of 2018. The files are uploaded but are corrupted on a read. There are a few fixes reported.  I am using a core from Dec 2017 and that works fine.


how does serial port communication work under the hood?

The first question already got a perfectly good answer. I am answering the other ones.

  i couldn't find any function call to the one for UART.

There are no "UART functions" in the MCU. The UART is controlled by reading and writing into special registers. These come by names like UCSR0A, UCSR0B, UCSR0C (USART 0 Control and Status Registers A, B and C), UBRR0L, UBRR0H (Low and High bytes of the USART 0 Baud Rate Register) and UDR0 (USART 0 Data Register). These registers are all referenced in HardwareSerial.cpp. You can check the datasheet for their meaning.

  where is the definition of this Serial?

In HardwareSerial.cpp, by the end of the file, right after the comment "Preinstantiate Objects".

  There seem to have ring buffer for serial buffer. So, when data is being sent then, what and who fill the data into this buffer inside Hardware.cpp?

There are actually two ring buffers: the receive buffer (_rx_buffer) is filled by an interrupt service routine and is emptied by you calling Serial.read(). The transmit buffer (_tx_buffer) is filled by you calling Serial.write(), Serial.print() or Serial.println() (the line _tx_buffer->buffer[_tx_buffer->head] = c; in HardwareSerial::write()), and is emptied by an interrupt service routine.

These interrupt service routines are defined in HardwareSerial.cpp. They start with lines like ISR(SOMETHING_vect). They are triggered by the hardware UART. The transmit ISR is triggered when the UART is ready to accept a new byte to transmit (when it is done transmitting byte n, it starts transmitting byte n+1 and is ready to accept byte n+2 in its TX buffer). The receive ISR is triggered when a new byte has been received.

  when does it get initialised?

When you call Serial.begin().


As Juraj wrote, you need an MPU, which is a module, that consists of an 3-dimensional accelerometer and a 3-dimensional gyroscope. With the first you can sense acceleration in each of the 3 dimensions (up-down, left-right, forwards-backwards), with the seconds you can sense rotation around these three directions. Sometimes (depending on the module) there is also an magnetometer included, which can be used as a compass.

Note, that you cannot sense the actual speed of a device directly, without using some external reference. With an accelerometer you have to do some maths on the data to get the speed (basically integrating). But since you just want to sense the direction, without bothering about the exact speed, you don't have to think about this.

How exactly you have to program this is out of scope for this side, since it is a rather big topic. Also it depends on the module and library you use. The link, that was provided by Juraj, is a good starting point for reading about this. There are also some further links, for example to a library for controlling the MPU-6050 (if you have one of these) at this github site.

Basically you will have to regularly measure the acceleration in all three dimensions with the MPU. If for an axis the acceleration gets greater than a threshold value, you can count this as direction. To get a more precise direction (not only directly along the axis) you will have to combine the values of the dimensions as a vector. How this is to be solved depends greatly on what you want to achieve.


PWM Control, How to stop LED from Flickering?

Your code doesn't make much sense.

You set the LED to 2 different brightness values that don't have anything to do with each other: The pot brightness and the button-based brightness. You only adjust the LED based on switches once every 5 mS. Thus the LED is going to flicker between 2 different brightness values.

What do you want it to do? How do you want to control the brightness based on input from both the pot and your switches? (What is the relationship between the buttons and the pot? Should the button input alter max/min value of the pot up and down? Should holding the button down change the brightness by 1 value per a specific time unit? Say 2 increments/decrements per second?)

Describe the user interface you want to achieve, and then think through how you would do that in code.


I'd recommend you go to cplusplus.com. Plenty of tutorial pages and topics to further your knowledge. However, be aware that Arduino uses a variant of C designed for microcontrollers (the exact flavour depends on the microcontroller type/family), rather than C++, so do be aware that some of the topics are not implementable on an Arduino. That said, I can't think why you'd be using some of the more elaborate C++ exclusive features in a fairly middle-of-road embedded system.

The only thing you need to ignore in C++ is memory allocation specifics - you're limited to the 'original' malloc() based functions rather than the all-singing-all-dancing operator new from C++. If you are in need of memory allocation functions, malloc is well-documented and a tutorial is only a quick Google away.

Of course I must also point you in the direction of the highly popular Stack Overflow site, part of this Stack Exchange network. While they don't have tutorials, there are plenty of great answers to common questions.


If you want Fooa() to be defined in a header that can be included in more than one .cpp file, you would need to declare it as an inline function like so:
#ifndef Foo_H
#define Foo_H

class Foo
{
    public:
    Foo();

    public:
    inline bool Fooa();
    bool Foob();
};
#endif

Alternately, you can provide the function definition directly inside class definition; this also makes the function inline despite not requiring the inline keyword.
Or if you want to keep Fooa as a non-inline function, you'd need to move the definition out of the header and into a .cpp file as you did with Foob().
Making a function inline has a second effect beyond implying that you want a function's code to be generated at the call site; it informs the compiler (or more accurately the linker) to expect to see multiple definitions (that are required to be identical) of the code for the function.  Without that advanced noticed, you will get the multiple definition of error when a function definition is inserted into multiple .cpp file by way of an #include.
As a side note: #include is an automated form of copy-and-paste.  It logically plants the contents of another file (and all of its reachable #include uses transitively) into place where the #include directive appeared.  It does not behave the same way that many similar looking directives in other languages do.  E.g. #include does not behave like the import keyword does in say Java or python for example.


How does the speed work in VirtualWire Library

I think that is used for receiving. By setting the speed, it knows how often it needs to read the input pin. It does this using timer interrupts, so it will run "in the background" without interfering with the main (loop) code.

The TCCR stuff is the set the interval for the timer interrupt.


Problem reading in Arduino serial port with 5K potentiometer

It sounds like it might be a wiring problem. Check that you have the potentiometer connected correctly. Your circuit should look something like this:


Why does the arduino respond so slow to serial input

It's because you're using Serial.parseInt().  It uses a timeout to find the end of the data on the serial port, and while it's waiting for that timeout it can do nothing else.

You would be better off manually reading the serial data a character at a time to build up an input string (C-string, not Arduino String) with a proper line terminator (line-feed, \n) and then convert that into an integer with atoi().


When a button is connected in that configuration, the input is what's called floating, meaning it's not a 0 or a 1. When the button is pressed, it is connected to ground, so that's definitely a 0, but when it's not pressed down, we don't know the value of the pin.

Pull Up Resistor

We need to include what's called a "pull-up" resistor to pull the signal up to a logic 1 when the button is not pressed.

Image from Sparkfun

What this means is when the button is not pressed, the Arduino reads a logic 1. When the button is pressed, the current flows through the resistor to ground and the Arduino reads a logic 0.

Internal Pull Up Resistor

The Arduino also has internal pull up resistors so you don't necessarily have to add an extra component to your circuit. There are a couple of ways to use this.

You used to have to do it like this:

pinMode(pin, INPUT);           // set pin to input
digitalWrite(pin, HIGH);       // turn on pullup resistors

Now we can do it simply in one line:

pinMode(pin, INPUT_PULLUP);

This enables the 20k pull up resistor on that pin. The input will no longer be floating when the button is not pressed.

Note: This only works when the other end is connected to ground.


User configuration file does not exist or is not a regular file, skipping

Finally i found answer for my question, It happen because of uploading sketch in selected pin.

// Neopixel
//#define PIN            6   /* Pin used to drive the NeoPixels */
#define PIN            13   /* Pin used to drive the NeoPixels */

I Changed Pin 6 to 13 , it's worked for me.