text:
Reducing Memory Usage lots of Floats
Im using an Arduino Uno - All code at github.com/robbrad/AirQuality
Current sketch usage:
Sketch uses 23186 bytes (71%) of program storage space. Maximum is 32256 bytes.
Global variables use 1428 bytes (69%) of dynamic memory, leaving 620 bytes for local variables. Maximum is 2048 bytes.

I wouldn't normally just spam code for a optimisation - but im looking to get about 10% memory back from this sketch
It basically checks a bunch of sensors sets the values to floats, build a string and posts that to a php page where some more processing happens.
I have tried everything to my knowledge but I just cant think of a smarter way to use less memory.
I tried an array, a function to build the data string, using one float and concatenating it to the string when it set
I even thought of reducing the Math.h include to just the math functions I was using
Maybe im just reaching the little boards limits (which are pretty good anyway :) ! )
#include <SPI.h>
#include <Ethernet.h>
#include "DHT.h"
#include <math.h>
#include <Wire.h>
#include "MutichannelGasSensor.h"
#include "HP20x_dev.h"
#include "KalmanFilter.h"

unsigned char ret = 0;

/* Instance */
KalmanFilter t_filter;    //temperature filter
KalmanFilter p_filter;    //pressure filter
KalmanFilter a_filter;    //altitude filter

// Enter a MAC address for your controller below.
// Newer Ethernet shields have a MAC address printed on a sticker on the shield
byte mac[] = { 0xDE, 0xAD, 0xBE, 0xEF, 0xFE, 0xED };
// if you don't want to use DNS (and reduce your sketch size)
// use the numeric IP instead of the name for the server:
IPAddress server(192, 168, 0, 30); // numeric IP for Google (no DNS)
//char server[] = "www.google.com";    // name address for Google (using DNS)

// Set the static IP address to use if the DHCP fails to assign
IPAddress ip(192, 168, 0, 40);

// Initialize the Ethernet client library
// with the IP address and port of the server
// that you want to connect to (port 80 is default for HTTP):
EthernetClient client;

#define Vc 4.95
//the number of R0 you detected just now
#define R0 35.54
#define DHTPIN A1     // what pin we're connected to

// Uncomment whatever type you're using!
//#define DHTTYPE DHT11   // DHT 11
#define DHTTYPE DHT22   // DHT 22  (AM2302)
//#define DHTTYPE DHT21   // DHT 21 (AM2301)

DHT dht(DHTPIN, DHTTYPE);

int pin = 8;
unsigned long duration;
unsigned long starttime;
unsigned long sampletime_ms = 2000;//sampe 30s ;
unsigned long lowpulseoccupancy = 0;
float ratio = 0;
float concentration = 0;
String data = "";

void setup() {
  Serial.begin(9600);
  while (!Serial) {
    ; // wait for serial port to connect. Needed for native USB port only
  }

  delay(150);
  HP20x.begin();
  delay(100);

  /* Determine HP20x_dev is available or not */
  ret = HP20x.isAvailable();

  pinMode(8, INPUT);
  starttime = millis();//get the current time;
  //Serial.println("power on!");

  pinMode(4, OUTPUT);
  digitalWrite(4, HIGH);

  //if (Ethernet.begin(mac) == 0) {
  //  Serial.println("Failed to configure Ethernet using DHCP");
  // try to congifure using IP address instead of DHCP:
  Ethernet.begin(mac, ip);

  // give the Ethernet shield a second to initialize:
  delay(10000);
  // Serial.println("connecting...");
  //}
  // give the Ethernet shield a second to initialize:
  //delay(1000);
  //Serial.println("connecting...");

  // Serial.println(Ethernet.localIP());

  gas.begin(0x04);//the default I2C address of the slave is 0x04
  gas.powerOn();
  //Serial.print("Firmware Version = ");
  //Serial.println(gas.getVersion());
  //Serial.println("Particles\tRS\tHCHO (PPM)\tNH3 (PPM)\tCO (PPM)\tNO2     (PPM)\tC3H8 (PPM)\tC4H10 (PPM)\tCH4 (PPM)\tH2 (PPM)\tC2H5OH (PPM)");
  dht.begin();
  delay(10000);

}

void loop() {

  if (client.available()) {
    char c = client.read();
    //  Serial.print(c);
  }

  float HATemp2;
  float HAPres2;
  float HAAlt2;
  float d;

  if (OK_HP20X_DEV == ret)
  {
    unsigned long HATemp = HP20x.ReadTemperature();
    d = HATemp / 100.0;
    HATemp2 = t_filter.Filter(d);

    unsigned long HAPres = HP20x.ReadPressure();
    d = HAPres / 100.0;
    HAPres2 = p_filter.Filter(d);

    unsigned long HAAlt = HP20x.ReadAltitude();
    d = HAAlt / 100.0;
    HAAlt2 = a_filter.Filter(d);

  }

  duration = pulseIn(pin, LOW);
  lowpulseoccupancy = lowpulseoccupancy + duration;

  if ((millis() - starttime) >= sampletime_ms) //if the sampel time = = 30s
  {
    ratio = lowpulseoccupancy / (sampletime_ms * 10.0); // Integer percentage 0=>100

    d = 1.1 * pow(ratio, 3) - 3.8 * pow(ratio, 2) + 520 * ratio + 0.62; // using spec sheet curve
    //Serial.print("concentration = ");

   lowpulseoccupancy = 0;
    starttime = millis();
  }

 //Serial.print("\t");
  //HCHO

  int sensorValue = analogRead(A0);
  double Rs = (1023.0 / sensorValue) - 1;

  double ppm = pow(10.0, ((log10(Rs / R0) - 0.0827) / (-0.4807)));
  //Serial.print("HCHO ppm = ");

  //MultiChannel Gas
  float NH3 = gas.measure_NH3();
  float CO = gas.measure_CO();
  float NO2 = gas.measure_NO2();
  float C3H8 = gas.measure_C3H8();
  float C4H10 = gas.measure_C4H10();
  float CH4 = gas.measure_CH4();
  float H2 = gas.measure_H2();
  float C2H5OH = gas.measure_C2H5OH();

  // Reading temperature or humidity takes about 250 milliseconds!
  // Sensor readings may also be up to 2 seconds 'old' (its a very slow sensor)
  float h = dht.readHumidity();
  float t = dht.readTemperature();

  data = String("dust=") + d + "&rs=" + Rs + "&hcho=" + ppm + "&nh3=" + NH3 + "&co=" + CO + "&no2=" + NO2 + "&c3h8=" + C3H8 + "&c4h10=" + C4H10 + "&ch4=" + CH4 + "&h2=" + H2 + "&c2h5oh=" + C2H5OH + "&temp=" + t + "&hum=" + h + "&HATemp=" + HATemp2 + "&HAPres=" + HAPres2 + "&HAAlt=" + HAAlt2;

  //Serial.println(data);

  if (client.connect(server, 80)) {
    Serial.println(F("connected"));
    client.println(F("POST /air_add.php HTTP/1.1"));
    client.println(F("Host:  192.168.0.30"));
    client.println(F("User-Agent: Arduino/1.0"));
    client.println(F("Connection: close"));
    client.println(F("Content-Type: application/x-www-form-urlencoded;"));
    client.print(F("Content-Length: "));
    client.println(data.length());
    client.println();
    client.println(data);
  }
  else
  {
    Serial.println(F("could not connect"));
  }

  Serial.println(data);

  if (client.connected()) {
    client.stop();
  }

  delay(300000);
}

For which Arduino board? Are you trying to reduce ram or flash memory? What does the compiler say about ram and flash memory usage? Those few float variables on the stack are not the problem. The libraries might use a lot of memory. If no library uses the 'String' object, then you should try to avoid that. You can also send bare sensor data, and do the calculation and processing in the server.

It’s an Uno. The compiler didn’t complain but it’s right on the 70% and 69% limi for both respectively. I had a quick look at the libraries but not seeing anything jumping out at me. Maybe I’ll make a sketch with just the libraries to see just their usage

Please update your question with the extra information. You could add links to the used (non-Arduino) libraries, so we can have a look at them. For an Arduino Uno, you better get rid of the 'String' object. Even though that would result into 20 lines of code or more. The Ethernet shield is mostly used with an Arduino Mega 2560 or a Arduino Due, because the Uno has not enough memory.

Done - https://github.com/robbrad/AirQuality

Thanks, but those are only the *.h files, not the used libraries. I suggest to remove the 'String' class, and if that is not enough then replace the Arduino Uno with a board that has more memory (you probably are going to do that some day anyway).

Just added the cpp files

Why do you want to get 10% back? Even if the program memory is 99% full it won't cause any problems, unless you want to add more things. Even using 70% of RAM isn't outrageous. The linker tends to optimize heavily, so it is (probably) only including the routines you actually reference.

@NickGammon 10% was an arbitrary number, as I noticed intermittent issues when I got to this level of usage, of course that might not be related. The issue I saw was some times it would output all the values other times it would output nothing.

Is this your KalmanFilter? I can't quite make sense out of it. To me, it looks silly and very memory intensive. Couldn't you use a basic first-order low-pass instead?

You haven't replied to the first comment. Do you want to save RAM or PROGMEM? They have quite different purposes. You may have heap fragmentation due to your use of the String class which I suggest you stop using (as others have advised).

@NickGammon I have stopped using String and it seems to have improved the stability - I was trying to save PROGMEM

@EdgarBonet - yes thats the one, I dont have the experience on this - it was recommended as part of the sensor implimentation

Even if you used 99.9% of PROGMEM, that would not affect stability. However with string fragmentation (particularly caused by the String class) even 50% of RAM used might be too much. It looks like you have found the problem.

@NickGammon +1 your spot on. This looks like the root cause of the issue. I’m exploring alternative methods of sending the data now

@Rob. As you talk about PHP I think you're a software dev (like me). I suggest to have a look at the diff. between Harvard and Von Neumann architecture. Arduino is NOT a computer. Optimizing PHP code will give you more space (Von Neumann architecture) but optimizing the sketch will NOT give you more space for variable (Harvard architecture).

@Peter your too kind sir, I’m more a jack of all trades master of none. But your right I’m fast realising it’s quite a different arena to  work in and not all initially learned principles apply

Your use of the F macro (eg. Serial.println(F("connected"));) is very sensible. Without it, the compiler copies the string into RAM, further reducing available RAM. Done with the F macro the compiler generates code to pull the constant data directly from PROGMEM.

Two basic approaches:
1) use fixed point math. or
1) use int16_t or int32_t in lieu of the floating types. for example, you can use x10 or x100 to designate variables with some decimal points. use x16 or x128 or even x256 for speed gains as well. you will need to make sure that it doesn't overflow.
edit: here is an example that hopefully will help you get it going.
void setup() {
    Serial.begin(9600);
    var1=100;               //var1=1.00
    var2=123;               //var2=1.23
}

void loop() {
    var1+=var2;             //increment var1
    Serial.print("var1 = "); Serial.print(var1 / 100); Serial.print("."); Serial.print(var1 - (var1 / 100) * 100); Serial.println(".");
    delay(100);
}

var1 (1.00 initially) is incremented by var2 (1.23), both are int32_t types.
here is the printout.

Ok so what you're saying is I can use int16_t  instead of a float? do I have to cast the result in some other way? doing more reading now

That’s pretty cool, never done this before. So var1 is of type int32_t. So when it’s taken to the string it’s only converted to the correct precision at the point - is this the essence of fixed point math?

@dannyf What software are you using in the last picture?  Is that an emulator?

" is this the essence of fixed point math?" yeah. fixed point math is in base 2, and what I have shown is in base 10. using base 2 speeds up calculation and using base 10 is more intuitive.

I second the advice that has already been given to you about avoiding
String. Other than that, using fixed-point math could be a big win,
but given the math you do it won't be any easy.
Assuming you stick with floating point, I just found a couple of easy
optimization opportunities:

Do not use pow to evaluate a polynomial. Use the Horner's
method which is way
cheaper: d = ((1.1*ratio - 3.8)*ratio + 520)*ratio + 0.62.
The expression of ppm can be simplified:
ppm = 2500.33 * pow(Rs, -2.0803).

Edit: You could also try to implement chunked transfer
encoding. This
way you could send the data to the server on the fly, as you collet it,
instead of storing everything in memory and sending it in one go.
Example:
void send_chunk(Print &connection, const String &chunk)
{
    connection.println(chunk.length, 16);
    connection.println(chunk);
}

void loop() {
    // ...

    // last header sent to the client:
    client.println(F("Transfer-Encoding: chunked"));
    client.println();

    // Now the data:
    String chunk;
    chunk = "dust=";
    chunk += ((1.1*ratio - 3.8)*ratio + 520)*ratio + 0.62;
    send_chunk(client, chunk);
    chunk = "&rs=";
    chunk += Rs;
    send_chunk(client, chunk);
    chunk = "&hcho=";
    chunk += 2500.33 * pow(Rs, -2.0803);
    send_chunk(client, chunk);
    chunk = "&nh3=";
    chunk += gas.measure_NH3();
    send_chunk(client, chunk);
    // and so on...
    chunk = "";
    send_chunk(client, chunk);  // Empty chunk means end of message.

    // ...
}

Notice that there is no "Content-Length" header. Instead, each chunk is
preceded by its size in hex. And, most importantly, notice that this way
you can get rid of lots of variables.

Edit 2: I came out with a better (more generic) way to implement
chunked encoding, which involves sending the data through a “chunker”
filter that does the encoding and outputs to the client. Here is my
Chunker class:
/*
 * Transfer a message using the HTTP/1.1 "Chunked Transfer Coding".
 * C.f. https://tools.ietf.org/html/rfc7230#section-4.1
 */
class Chunker : public Print
{
public:
    Chunker(Print &downstream) : downstream(downstream), pos(0) {}

    virtual size_t write(uint8_t c)
    {
        buffer[pos++] = c;
        if (pos == BUFFER_SIZE)
            send();
        return 1;
    }

    void end()
    {
        if (pos) send();
        send();  // empty chunk means end of message
    }

private:
    static const uint8_t BUFFER_SIZE = 32;
    Print &downstream;
    uint8_t buffer[BUFFER_SIZE];
    uint8_t pos;

    // Send the buffer as a chunk.
    void send()
    {
        downstream.println(pos, HEX);
        if (pos) {
            downstream.write(buffer, pos);
            downstream.println();
            pos = 0;
        }
    }
};

And here is how you would use it:
Chunker message(client);  // instantiate the filter
message.print(F("dust="));
message.print(((1.1*ratio - 3.8)*ratio + 520)*ratio + 0.62);
message.print("&rs=");
message.print(Rs);
message.print(F("&hcho="));
message.print(2500.33 * pow(Rs, -2.0803));
message.print(F("&nh3="));
message.print(gas.measure_NH3());
// and so on...
message.end();  // terminate the chunked message

The main advantage of this method is that you completely avoid using the
String class, which means no dynamic memory allocation (a very
desirable thing). Also you can choose your buffer size. I've set it to
32 bytes, but you can make it smaller if needed.

@Rob: I added another suggestion about the usage of the HTTP protocol.

Thats really cool - thank you for spending some time on this - I think im edging towards this approach

@Rob: Here is a more generic way of using chunked encoding, which avoids String, or even the need to guess how mush space you need to sprintf() a number.

Thats pretty amazing ... I just need to work out the particulars like the connection part. My Endpoint is a php page/server which does a load more things with the POST request - would this be a good place to start https://dancingmammoth.com/2009/08/29/php-stream-filters-unchunking-http-streams/

@Rob: I don't know much about PHP. Not sure whether you have to take for the encoding yourself. The link you provide is for adding chunked support to PHP streams, which are a useful tool for handling very large payloads. You payload is tiny, so you don't need them. Also, I assume your web server will take care of the decoding step, at least if using mod_php. Note, however, that there is a PHP bug that prevents this to work in fast CGI mode.

Thank you so much for your help it’s really helped my understanding of what’s going on. I have found a link to send as a char array https://github.com/tttapa/Projects/blob/master/ESP8266/HTTP/HTTP-POST-char-array/HTTP-POST-char-array.ino - which should cut down my redevelopment of the receiver. This question has helped me hone in on the issue which I now believe was directly related to the dynamic allocation of the string. This was either blowing the dynamic memory or fragmenting the string variable, I noticed some times only half the string was posted. Thank you


text:
What does map() do?
Regarding the following code:
mpu.getMotion6(&ax, &ay, &az, &gx, &gy, &gz);
ax = map(ax, -17000, 17000, -1500, 1500);

I know the reason for taking 17000 as value - that's 1g.  But I am not getting how and why 1500 value is taken.

The map() function is well explained here.
In short, it maps one range of numbers to another.  In this case it will map ax from the range (-17000:17000) into the range (-1500:1500).
Imagine a ruler with both inches and cm on.  If you have a measurement in inches, you can represent that same measurement (point on the ruler) in cm.  Your "ruler" here has one scale ranging from -17000 to 17000, and another scale ranging from -1500 to 1500.  You're finding the reading on the second side at the point ax on the first.
If you mean specifically why are those numbers used -- then I have no idea since you give no context.

.Thanku so much. now i understood. your exampple of ruler just nailed it.

You're welcome. If the answer was helpful you can accept it and optionally up-vote it :-)

source: Stack Exchange

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

sort: votes


text:
Arduino Code hang
I am working on a project to dim/brighten the LED lights between each hour. To make the program readable i have only kept the code for few hours.
For example if T1 is at 255 PWM and T2 is 20 PWM, the code calculates the moves required to dim the LED by One PWM every few second such that by T2 the PWM is at 20.
I have Included DS1307 RTC for keeping track of time, further i have used a HC-05 Bluetooth module to communicate with the Arduino, using Android phone, so that i can change the PWM values between T1 and T2.
When i run the code it works perfectly for some time post which it freezes, and the LED starts flickering.
#include <Wire.h>
#include "RTClib.h"
String fromAndroid;
////////RTC
int h = 0;
int m = 0;

int hours;
unsigned long interval = 1000;

////////////Millis
unsigned long currentMillis;
unsigned long White_previousMillis;
unsigned long previousMillis;//for clock
unsigned long Hr_interval = 3600000;
unsigned long white_each_interval;

int pwm02 = 2;
int pwm03 = 3;
int pwm04 = 4;
int pwm05 = 5;
int pwm06 = 6;
int pwm07 = 7;

/////////////////Peak Keeper
int white_t24 = 10;
int white_t1 = 233;
int white_t2 = 18;
int white_t3 = 189;
int white_t4 = 12;
int white_t5 = 255;
int white_t6 = 19;
int white_t7 = 199;
int white_t8 = 2;
int white_t9 = 177;
int white_t10 = 2;
int white_t11 = 245;
int white_t12 = 12;
int white_t13 = 252;
int white_t14 = 0;
int white_t15 = 255;
int white_t16 = 50;
int white_t17 = 239;
int white_t18 = 20;
int white_t19 = 253;
int white_t20 = 1;
int white_t21 = 252;
int white_t22 = 2;
int white_t23 = 255;

/////Secondary time
int white_Secondary;

int white_steps; //new

int white_move; //New

RTC_DS1307 rtc;
void setup() {
  Serial.begin(9600);
  rtc.begin();
  if (! rtc.begin())
  {
    Serial.println("Couldn't find RTC");
    while (1);
  }
  if (! rtc.isrunning())
  {
    Serial.println("RTC is NOT running!");
  }
  Serial.println("Start");
  //  rtc.adjust(DateTime(2017,12,17,11,52,00));
  pinMode(pwm02, OUTPUT);
}

void loop() {
  while (Serial.available() == 0)
  {
    DateTime now = rtc.now();
    currentMillis = millis();
    hours = now.hour();
    if (currentMillis - previousMillis >= interval)
    {
      Serial.print(now.year(), DEC);
      Serial.print('/');
      Serial.print(now.month(), DEC);
      Serial.print('/');
      Serial.print(now.day(), DEC);
      Serial.print(" (");
      Serial.print(now.hour(), DEC);
      Serial.print(':');
      Serial.print(now.minute(), DEC);
      Serial.print(':');
      Serial.print(now.second(), DEC);
      Serial.println(')');
      previousMillis = currentMillis;
    }

    if (hours == 12)
    {
      if(now.minute()==00 && now.second()<=1)
      {
        white_Secondary = white_t24;
        analogWrite(pwm02, white_Secondary);
      }
      white_steps = white_t1 - white_t24;
      if (white_steps == 0)
      {
        white_move = 0;
        white_each_interval = 1800000;
      }
      if (white_steps < 0)
      {
        white_move = -1;
      }
      else
      {
        white_move = 1;
      }
      if (white_steps != 0)
      {
        white_each_interval = Hr_interval / abs(white_steps);
      }
    }

    if (currentMillis - White_previousMillis >= white_each_interval)
    {
      white_Secondary = white_Secondary + white_move;
      analogWrite(pwm02, white_Secondary);
      Serial.print("PWM02: "); Serial.println(white_Secondary);

      White_previousMillis = currentMillis;
    }
  }

  while (Serial.available() > 0)
  {
    Serial.println("In Input Loop");
    fromAndroid = Serial.readString();
    if (fromAndroid.startsWith("White"))
    {
      fromAndroid.replace("White", "");

      if (fromAndroid.startsWith("time18"))
      {
        fromAndroid.replace("time18", "");
        white_t18 = fromAndroid.toInt();
        Serial.print("white_t18 VALUE: ");
        Serial.println(fromAndroid);
      }
      if (fromAndroid.startsWith("time19"))
      {
        fromAndroid.replace("time19", "");
        white_t19 = fromAndroid.toInt();
        Serial.print("white_t19 VALUE: ");
        Serial.println(fromAndroid);
      }
      if (fromAndroid.startsWith("time20"))
      {
        fromAndroid.replace("time20", "");
        white_t20 = fromAndroid.toInt();
        Serial.print("white_t20 VALUE: ");
        Serial.println(fromAndroid);
      }
    }
  }
}

Your code has several println() statements for debugging. What's the last line printed, and does it always fail after that particular line?

what does this mean? To make the program readable i have only kept the code for few hours.

@ jose, ihad kep lot of print statements to find when the code sops, but unfortunately the code doesn't stop at fixed point, it stops at random.

@jsotola, I had made the program for 24 hours, which had 24 sub If statements, which would be hard to read in a post hence limited the code for couple of hours.

i think that you only posted code to one hour. please post code for three hours. there may be a way to simplify the code.

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


text:
How I can make alarm on off?
I want to do is BEEP! to show that the program is running.
#define SPKR 4 //this is the digital pin that you plugged the red       wire into

void setup()
{
   pinMode(SPKR, OUTPUT); //set the speaker as output
}

void loop() //do this over and over
{
   digitalWrite(SPKR, HIGH); //turn the speaker on
   delay(500);                     //wait for half a second
   digitalWrite(SPKR, LOW); //turn the speaker off
   delay(500);                    //wait for half a second
}

With out this any other way
I mean without repeating the code HIGH / LOW
during this beep I want do same things else

I don't understand your question. I guess English isn't your first language. Can you find another way to explain it please?

you code works well as-is with an "active buzzer" module.

The code you show will toggle the SPKR pin at a 1 Hz rate.  If you have an ordinary speaker attached, you will hear it click twice a second, but it won't generate an audible tone.
To generate a tone, use tone(pin, frequency) calls, or tone(pin, frequency, duration) calls.
For example:
void loop() {
   tone(SPKR, 400, 500); // 400 Hz tone for half second
   delay(500);           // no tone for half second
}

Note, ordinary speakers are low-impedance devices, eg 4 Ω, 8 Ω, etc.  You can use an audio transformer for impedance matching – this helps produce an adequate output volume – but lacking that, should put a resistor (eg 220 Ω) in series with the speaker to avoid over-current conditions.  AVR pins can deliver 25 mA without too much stress, and typically are rated at an absolute max of 40 mA.

authors: Инкогнито Никеев


text:
Problems creating 10Hz pulse wave
I'm trying to make a 10Hz pulse wave output at Arduino's pin 9 by using the following code I wrote:
#define F_CPU 16000000UL
#include <avr/io.h> //Defines pins, ports, etc.
#include <util/delay.h>

int main(void)
{

    DDRB |= (1<<DDD1); //Does this set port B pin 1 and is this pin 9 in UNO board?
    PORTB |= (1<<PORTB1);

    while(1){

        PORTB |= ~(1<<PORTB1);
        _delay_ms(100);
        PORTB |= (1<<PORTB1);

    }

}

I use Atmel Studio to uplaad the code and it works fine with other codes. But for some reason this code doesn't work. What can be the problem here?
Still doesnt work
edit:
#define F_CPU 16000000UL
#include <avr/io.h> //Defines pins, ports, etc.
#include <util/delay.h>

int main(void)
{

    DDRB |= (1<<DDD1);
    PORTB |= (1<<PORTB1);

    while(1){

        PORTB &= ~(1<<PORTB1);
        _delay_ms(100);
        PORTB |= (1<<PORTB1);

    }

}

You have your whole 100ms wait time while the pin is low.
You need half of it while low, half while high.
while(1){

    PORTB &= ~(1<<PORTB1);
    _delay_ms(50);
    PORTB |= (1<<PORTB1);
    _delay_ms(50); // You need a delay here too.
}

oh without the second delay it just jumps to low again. i see thanks. just curious is this a good way to obtain a very precise pulse frequency? i mean by using delay function as i did? or interrupts required? im trying to build a as precise as possible simple pulse generator.

@doncarlos no kidding, I was telling to you for a while!

@doncarlos and no, this is horrible way to do frequency generator. Use Timers and it's waveform generator modes instead.

Your code doesn't clear anything.

    PORTB |= ~(1<<PORTB1); // set everything except PORTB1 pin
    _delay_ms(100);
    PORTB |= (1<<PORTB1);  // set PORTB1 pin

And recommended tutorial: Bit manipulation (AKA "Programming 101") from the AVRFreaks.net
BTW: next issue might be "the pulse is way too fast so it seems there is none"
Try this:
while(1) {
    PINB = _BV(PINB1); // toggle pin
    _delay_ms(50);
}

Doesn't PORTB |= ~(1<<PORTB1); set PORTB1 pin to zero?

No, pipe | is logic OR, that means whenever is corresponding bit logic one, result is logic one

pulse is not fast and set to 10Hz _delay_ms(100). And I check with a scope. Theres nothing still

@doncarlos Well - there is clear bit, wait for 100ms, set bit ... and repeat..  that pause between setting and resetting bit might be even less than 200ns

   PORTB |= ~(1<<PORTB1);

change it to:
   PORTB &= ~(1<<PORTB1);

if you want to clear PB1.

I made that change but still doesnt work. Please see my edit.

@doncarlos see my "BTW" edit :D


text:
ESP8266 and Arduino integration
I am trying to upload a sketch and getting below error:
error: failed reading byte
warning: espcomm_send_command: cant receive slip payload data
warning: espcomm_sync failed
error: espcomm_open failed
error: espcomm_upload_mem failed.

Connections:
TX - TX
CH_PD - 3.3 V
RX - RX
VCC - 3.3
GPIO GND
GND - GND

Before uploading the sketch I have reset the arduino and ESP and selected board as ESP8266 and baud rate as 115200 but still getting the same error.

You don't say what you're using to program it (an FTDI board? the USB adapter on an Arduino?) but you probably want to connect
TX - RX
RX - TX


text:
Install Arduino IDE in Raspberry Pi 3 model B
I am trying to install Arduino IDE in my Raspberry Pi model 3 but it is unable to locate file path.
I use the following steps
sudo apt-get update && sudo apt-get install arduino

and in result I found this
pi@raspberrypi:~ $ sudo apt-get update && sudo apt-get install arduino
Hit:1 http://archive.raspberrypi.org/debian stretch InRelease
Ign:2 http://repository.pi4j.com wheezy InRelease
Hit:3 http://repository.pi4j.com wheezy Release
Reading package lists... Done
Reading package lists... Done
Building dependency tree
Reading state information... Done
E: Unable to locate package arduino

I am searching for a solution but not able to understand what's the problem here.
Any ideas to make it work will be helpful.

Have you tried grabbing the Linux ARM build directly from https://www.arduino.cc/en/Main/Software and installing it? Have you tried searching for the package name? apt-cache search arduino

Downloading the latest version from the arduino.cc is much better idea. If there is Arduino IDE available in the repository, it's usually super obsolete. For example version in Ubuntu repositories is 1.0.5.

Visit https://www.arduino.cc/en/Main/Software in your browser, and click the Linux ARM link under ‘Download the IDE’.
cd Downloads/
tar -xf arduino-1.8.3-linuxarm.tar.xz

Extract the file to your /opt directory, then open a Terminal and run the install.sh script to install.
sudo mv arduino-1.8.3 /opt
sudo /opt/arduino-1.8.3/install.sh

You will find Arduino IDE under Menu > Programming. Open the app to start programming your Arduino board.
Hope this helps.

worked for me! In the Arduino website you'll find two versions (32-bits and 64-bits). In my case (and it seems in the case of this example) the 32-bits worked fine. I'm using a Raspberry Pi 3B with an Arm v7.

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


text:
Not enough memory
I am making a simple calculator with Arduino Uno R3. It only has +, -, x and /.
I use 3 libraries:

This use for LCD with I2C module. Arduino-LiquidCrystal-I2C-library
This use for keypad 4x4. Chris--A/Keypad
And this: jamesgregson/expression_parser

My code:
#include "expression_parser.h"
#include <Keypad.h>
#include <Wire.h>
#include <LiquidCrystal_I2C.h>

LiquidCrystal_I2C lcd(0x3F, 16, 2);

const byte ROWS = 4;
const byte COLS = 4;

char keys[ROWS][COLS] = {
  {'1', '2', '3', '+'},
  {'4', '5', '6', '-'},
  {'7', '8', '9', '*'},
  {'.', '0', '=', '/'}
};

byte rowPins[ROWS] = {10, 9, 8, 7};
byte colPins[COLS] = {6, 5, 4, 3};

Keypad keypad = Keypad( makeKeymap(keys), rowPins, colPins, ROWS, COLS );

String s = "";
char ex[16];

void setup() {
  Serial.begin(9600);
  lcd.init();
  lcd.backlight();
  lcd.setCursor(0, 0);
}

int cur = 0;
bool enter = false;

void loop()
{
  char key = keypad.getKey();

  if ((key != '=') && (key != NO_KEY) ) {
    if (!enter) {
      Serial.println(F("key"));
      if(key=='/')
        lcd.print(F("':'"));
      else
      if (key=='*')
        lcd.print(F("'x'"));
      else
        lcd.print(F("key"));
      s = s + key;
      cur++;
      lcd.setCursor(cur, 0);
    } else {

      lcd.setCursor(0, 0);
      lcd.print("");
      enter = false;
      lcd.setCursor(0, 0);
      cur = 0;
      lcd.print(F("key"));
      s = "";
      s = s + key;
      cur++;
      lcd.setCursor(cur, 0);
    }
  } else if (key == '=') {
    enter = true;

    if ((s[0] == '=') || (s[0] == '/') || (s[0] == '*') || (s[0] == '.')) {
      lcd.setCursor(0, 1);
      lcd.print("Error");
    } else {
      lcd.setCursor(0, 1);
      lcd.print("");
      s.toCharArray(ex, 16);
      Serial.println(F("s"));
      int re = parse_expression(ex);
      String check = String(re);
      if (check.length() > 15) {
        lcd.setCursor(0, 1);
        lcd.print("Overflow");
      } else {
        Serial.println(re);
        lcd.setCursor(0, 1);
        lcd.print("=");
        lcd.print(F("re"));
      }
    }
  }
}

I ran it and got error:
Global variables use 3302 bytes (161%) of dynamic memory, leaving -1254 bytes for local variables. Maximum is 2048 bytes.
Not enough memory; see http://www.arduino.cc/en/Guide/Troubleshooting#size for tips on reducing your footprint.
Error compiling for board Arduino/Genuino Uno.
So what should I do?

the expression parser uses a lot of ram, get rid of it. You're only doing 4 basic operations, so all you need to do is a small set of IF statements and parse the numbers themselves, which arduino can do without a big lib.

The most efficient system you can use is called "Reverse Polish Notation", or RPN.  It's a stack-based system and can run very efficiently on systems with very very little memory. You just have to get used to how to enter the equations properly...

which Arduino board you are using?

Your own declared global variables do not use up much space.
Watch out for using string, this can be extended during the flow of the program thus using more.
The problem is in the libraries.
What you can do:

Leave out the include and related code per library to see which is using up a lot of global space.
When you find out which causes problems, try to follow the internals of the library to see if there is some buffered memory that you can decrease.

If not, I'm afraid the only solution is to move to an Arduino with more memory (like the Arduino Mega which has 8 KB).
With the use of PROGMEM you can save some space on
char keys[ROWS][COLS] = {
  {'1', '2', '3', '+'},
  {'4', '5', '6', '-'},
  {'7', '8', '9', '*'},
  {'.', '0', '=', '/'}
};

byte rowPins[ROWS] = {10, 9, 8, 7};
byte colPins[COLS] = {6, 5, 4, 3};

Because it will be placed in Flash instead of SRAM, but it will save you just 24 bytes.

From a cursory look at those libraries, it seems to me that the expression parser eats a lot more RAM than the two others. It contains lots of error messages and code to deal with transcendental functions: things the OP does not have use of.

Move up to a '1284P based board. They have 16K of SRAM and 12 more IO pins, will give you plenty of room to add and expand into more functions later.
I offer '1284P boards in several form factors at www.crossroadsfencing.com/BobuinoRev17/
It is easy to add to the IDE with MCUdude's MegaCore
https://github.com/MCUdude/MegaCore

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


text:
How to concatenate strings
I am new to the Arduino platform so please bear with me. I have a program to display rolling text on a LED matrix which is for the Tinyduino platform
#include "Charliplexing.h"
#include "Font.h"
#include "Arduino.h"

void setup()
{
  LedSign::Init();
}

static char test[]="HELLO";

void loop()
{
  for (int8_t x=DISPLAY_COLS, i=0;; x--) {
    LedSign::Clear();
    for (int8_t x2=x, i2=i; x2<DISPLAY_COLS;) {
      int8_t w = Font::Draw(test[i2], x2, 0);
      x2 += w, i2 = (i2+1)%strlen(test);
      if (x2 <= 0)  // off the display completely?
        x = x2, i = i2;
    }
    delay(80);
  }
}

Then I have some code to read temperature and humidity data for the same Tinyduino platform
#include <Wire.h>
#include <SI7021.h>

SI7021 sensor;

void setup()
{
  Serial.begin(115200);
  Wire.begin();
  Serial.print("Initializing sensor... ");
  if(!sensor.begin()){
    Serial.println("Sensor not found!");
    while(true);
  }
  Serial.println("Success!");
}

void loop()
{
  int celcius=sensor.getCelsiusHundredths()/100;
  int relativeHumidity=sensor.getHumidityPercent();
  Serial.print(celcius);
  Serial.print(" deg Celsius\t");
  Serial.print(relativeHumidity);
  Serial.println("% relative humidity");

  delay(500);
}

I am trying to integrate this together so that Arduino reads the temperature and humidity sensor data and then displays it on the LED matrix as text. I have some code that is integrated from the above two examples
#include "Charliplexing.h"
#include "Font.h"
#include "Arduino.h"
#include <Wire.h>
#include <SI7021.h>

SI7021 sensor;

void setup()
{
  Serial.begin(115200);
  Wire.begin();
  Serial.print("Initializing sensor... ");
  if(!sensor.begin()){
    Serial.println("Sensor not found!");
    while(true);
  }
  Serial.println("Success!");
  LedSign::Init();
}

static char test[100]="";

void loop()
{
  int celcius=sensor.getCelsiusHundredths()/100;
  int relativeHumidity=sensor.getHumidityPercent();
  test=celcius+" deg celsius"+" "+relativeHumidity+" relative humidity";

  for (int8_t x=DISPLAY_COLS, i=0;; x--) {
    LedSign::Clear();
    for (int8_t x2=x, i2=i; x2<DISPLAY_COLS;) {
      int8_t w = Font::Draw(test[i2], x2, 0);
      x2 += w, i2 = (i2+1)%strlen(test);
      if (x2 <= 0)  // off the display completely?
        x = x2, i = i2;
    }
    delay(80);
  }
  delay(500);
}

Here is the error message that the IDE throws out
test:28: error: invalid operands of types 'const char*' and 'const char [2]' to binary 'operator+'

 test=celcius+" deg celsius"+" "+relativeHumidity+" relative humidity";
                             ^

Using library LOL in folder: C:\Program Files (x86)\Arduino\libraries\LOL (legacy)
Using library Wire at version 1.0 in folder: C:\Program Files (x86)\Arduino\hardware\arduino\avr\libraries\Wire
Using library Temp in folder: C:\Program Files (x86)\Arduino\libraries\Temp (legacy)
exit status 1
invalid operands of types 'const char*' and 'const char [2]' to binary 'operator+'

Any suggestions on how to resolve this error is welcome.

Good first question!

You can use sprintf to format a string.
You have to change:
test=celcius+" deg celsius"+" "+relativeHumidity+" relative humidity";

for
sprintf(test,"%d deg celsius %d relative humidity",celcius,relativeHumidity);

I have the code working but the sensor does not refresh the data and displays it only once. Do you see any reason why that would happen

In this line there is no condition: for (int8_t x=DISPLAY_COLS, i=0;; x--). More info: https://www.tutorialspoint.com/cprogramming/c_for_loop.htm.

You cannot "add" character arrays like that. You may try to use a
String object instead, as these do support the + operator as a way
to concatenate them:
String message = (String(celcius) + " deg Celcius, "
               + relativeHumidity + " relative humidity");
const char *c_message = message.c_str();

And then you use c_message in place of your test variable.
Note that only the first element (celcius here) needs to be explicitly
converted to a String object. The other conversions happen implicitly.
Edit: Updated the code to avoid using the internal state of a
(possibly destroyed) temporary object.

-1 This results in undefined behavior.

@TomKnapen: Oops! Updated the code.


text:
Arduino Serial.println() keeps transmitting data even when conditions are imposed
I am using Arduino UNO and a bluetooth module.  I have used an if condition so that Serial.println() happens only once but it keeps on printing.  Please help. Below is the code.
//Begin CODE
char str;
String fnal;
int i;

void setup()
{
  Serial.begin(9600);
  fnal="";
  i=0;
}

void loop()
{
  i++;
  if(i<2)
  {
    Serial.print('#');
    Serial.print('1');
    delay(10);
  }
}

According to this code # and 1 should be printed only once but in serial monitor the printing continues infinitely.

It works as expected for me, and the code looks OK.  If it doesn't work for you, try printing out the value of i (Serial.println(i);) and see if you can work out what's going wrong.

In setup add a Serial.print, eg. Serial.println ("Starting"); to see if the board is resetting for some reason.

Try changing the i++; with i+=1;

The idiom i++; alters the value of i. The two forms you posted are identical in function. If you do a = i++; then a is the value of i before adding 1 to it. However 1 is added to i, whether or not you store the result. Alternatively a = ++i; makes a have the value of i after adding 1 to i.

It is definitely an overflow issue.
You declared i as int which ranges from -32768 to 32767.
I wrote this code as an experiment:
void loop() {
  unsigned long now = millis();
  i++;
  if(i==0){
    Serial.println(now);
  }
}

The result is i overflows every 264 ms, so if(i<2) will be true many times per second.
A simple solution is to put i++; inside the if instead, like this:
void loop()
{
  if(i<2)
  {
    i++;
    Serial.print('#');
    Serial.print('1');
    delay(10);
  }
}

i will stop incrementing when the value is 2.
No more overflow.

If you had put a Serial.print inside loop you would have seen the problem. Debugging displays are very helpful. Like this:
void loop()
{
  i++;
  Serial.println (i);   // <---- debugging
  if(i<2)
  {
    Serial.print('#');
    Serial.print('1');
    delay(10);
  }
}

Since you are adding 1 to i each time around the loop, how long do you think it will go before i overflows? It will go up and up, get to 32767 and then become -32768, and then count back to 0. During that time it will be less than 2, and it will do the printing of "#1".

I'll try that out Nick...I think that might have been the actual problem..I'll use a boolean variable maybe..thanks man!


text:
Why does the following code not cause the led's to flash but rather stay on continuously

int timer = 1000;
int thispin = 5;

void setup() {
  for (int thispin = 5; thispin < 8; thispin++)
    pinMode(thispin, OUTPUT);
}

void loop() {
  for (int thispin = 5; thispin < 8; thispin++)
    digitalWrite(thispin, HIGH);

  delay(timer);
  digitalWrite(thispin, LOW);

  for (int thispin = 7; thispin = 5; thispin--)
    digitalWrite(thispin, HIGH);

  delay(timer);
  digitalWrite(thispin, LOW);
}

I have the above code. I thought that how it was written would cause the led's to flash but they all stay on continuously. Could anybody help to explain what it is i have done wrong?
I am very new to this and I'm just fiddling basically trying to learn.
Thank you!

Added code tags and indentation - it should be more obvious what is done by loops and what is not executed repeatedly by loops. Also  ; thispin = 5; ... is an assigment not comparation.

you only set pin 5 LOW. it is the global thispin

if you coded the program correctly, how long do you think that the low output would last after this line? ... digitalWrite(thispin, LOW); ... in your code, what is the value of thispin?

please review the documentation of the for loop ... it does not work as you think

A = won't work. You have to change it to ==.

You'll only see OUTPUT values during the delay() calls, Everything else, including the restart of loop() is way too fast. In your code, during delay, the pins are all HIGH.

The objective of the code is not clear. It seems the idea is to repeatedly blink 3 LEDs, connected on pins 5,6 and 7. To do so, the code needs slight modification-
int timer = 1000;
int thispin = 5;

void setup() {

  for (int thispin = 5; thispin < 8; thispin++)
    pinMode(thispin, OUTPUT);
}

void loop() {

  for (int thispin = 5; thispin < 8; thispin++)
    digitalWrite(thispin, HIGH);

    delay(timer);

  for (int thispin = 5; thispin < 8; thispin++)
    digitalWrite(thispin, LOW);

    delay(timer);

}

Also, since you wanted to know why the LEDs stay ON continuously with your code-
This is because there is no delay statement after any of the digitalWrite-LOW statements. If there's no delay, the LEDs may turn off for a fraction of a millisecond, which won't be noticeable.

From the given code it is not entirely clear what you are trying to achieve.
If I understood correctly, you want the pins to light up for one second and then go out. First from 5 to 7, and then from 7 to 5.
Try the given code.
int timer = 1000;

void setup()
{
  for (int thispin = 5; thispin < 8; thispin++)
    pinMode(thispin, OUTPUT);
}

void loop()
{
  for (int thispin = 5; thispin < 8; thispin++)
  {
    digitalWrite(thispin, HIGH);
    delay(timer);
    digitalWrite(thispin, LOW);
  }

  delay(timer);

  for (int thispin = 7; thispin >= 5; thispin--)
  {
    digitalWrite(thispin, HIGH);
    delay(timer);
    digitalWrite(thispin, LOW);
  }
}

Also, using the same name for globals variable and  loop iterators is bad style.

In the last for() loop, the limit expression, thispin =5; was probably meant to say thispin <=5;. As it is written, the expression is an assignment, not a test, and it will always be true, because 1) an assignment statement is also an expression having a value equal to the value assigned; and 2) the assigned value, '5', being non-zero, is equivalent to 'true'), so this loop will never end. thispin will get decremented forever and repeatedly set pin 5 to HIGH. It leaves the other pins alone, but they were already high, and the LEDs stay lit, which is what you observed.
(There are a couple of other errors, as noted earlier by previous responders, which will also prevent your code from operating as you expected.)

Exchange the last lines:
delay(timer);
digitalWrite(thispin, LOW);

It is 2 seconds on and maybe a few hundred nanoseconds on.


text:
Everything is ready for project . I have one doubt! I am using transmitter + Arduino *Uno*..and receiver + arduino *nano* will it work?
Everything is ready for project except hardware!
I have one doubt!
I am planning to use transmitter of Arduino Uno and receiver of Arduino Nano.  Will it work? Both Uno and Nano obey for same program? (The transceivers used are  Nrf24lO1 pa+lna!)

only you know what the project is, so only you can determine if it will work

Uno and Nano have the same MCU and the same Arduino pin mapping. Nano is only a small Uno.

Yes, it will work, in much the same way that you can send an email from a Mac to a Windows PC. The type of PC doesn't matter as long as they use the same protocol. As you haven't shared any details in that direction, I would say that if you have coded correctly, then it will work.

That cannot be determined until a much better description of your project is given. The parts you named are compatible with both processors. It could fail for a simple software mistook or a bad connection. Generally speaking the UNO and Nano are interchangeable electrically but not mechanically. The nano gives you two additional analog channels. Start by getting the RF to work, this probably will be the most problematic to get going. Use seperate power supplies for the RF devices.


text:
Beginner here, trying to start learning arduino, which starter kit should I buy?
I'm really interested in arduino but I don't know much about it. I want to buy a starter kit to play with, but when I searched it on amazon, there are couple unofficial starter kit and a more expensive official one. So, can some one tell me the major difference between the unofficial starter kit and official starter kit? And which one would you recommend me to buy? Thank you!
Sorry, bonus question: why is the start kit($89) in arduino website is much cheaper than the official starter kit in amazon($120)?

I can answer the bonus question for you right now:  They're not that much different.  Look at the units.  The "more expensive" one is in Canadian dollars, the cheaper in US dollars. Do the conversion, and there's not that much difference.

You could do worse than a cheap 37-in-1 Sensor Kit from eBay and any Arduino board of your choice.
Also some Dupont Jumpers are essential.  Get a selection of M/M, M/F and F/F.

I got the 1st one, and It's of decent quality. I only wish it came with an SD breakout for logging metrics.

I tend to recommend the oomlout ARDX starter kit to students at the university I work at as it is relatively low cost, widely available, and doesn't have too much cheap filler components that you don't use...


text:
Where can i get a current Websockets Library for Arduino that will work with the Ethernet Shield
I'm trying to get a simple WebSocket client working on an Arduino Mega with an ethernet shield. I tested the ethernet on the Arduino and it's working fine. I've tried a few of different WebSocket libraries the example sketches fail to connect. I've tried them with echo.websocket.org and with two different express instances ( one running WS and one running SocketIO ). But the WebSocket connection seems to fail.
https://github.com/billroy/socket.io-arduino-client
https://github.com/krohling/ArduinoWebsocketClient
is there a preferred  library for the most recent WS standard that anyone has used with sucess recently?

I am sure all three of those libraries work fine - other wise why would they have published them? Certainly the first one in your list has commits that are very recent. It is most likely how you are using it that is failing, but you didn't bother to ask us about that, just assumed that your code is perfect but the libraries are all at fault.

I'm running the examples and not modifying the code, and they are not working, I actually haven't tried the first LIB yet, but I will now ... My assumption was that perhaps the since the WS standard changed it broke the older libraries ... my question was more, if there is a preferred lib to use when trying to implement WS on Arduino, seems like it would be a common use case. Also, I don't really know why you seem to have such an attitude about the question, I wasnt being lazy, or making assumptions

Well that's how it came across. "None of the libraries work. Where can I get a working one?" Given that there are 3 libraries (supposedly) tried and only 1 "your code", the balance of probability (3:1 against) says that it's your code that is at fault. Complaining about the libraries, therefore, smacks of arrogance and "My code is perfect!"ism.

Well then, I've tried to reword so that it does not "smack of arrogance". although I think you are reading something that not there, I just see no point in aggro comments to honest questions, even if they are bad questions, just downvote it and or vote to close it and be done with it

I have debugged both these libraries using wireshark, sending a message to a node.js ws server in my computer, and there really is some sort of problem in the handshake. The package is sent by the client and received by the host, by the connection with the ws server is never established.
Was anyone able to use them?
Is there any alternative (besides Johnny-Five)?


text:
How to disable the write protection of the USART mode register?
I have a device which transmits USART with inverted polarity, and I would like to read data from it with the help of an Arduino. I use an Arduino Due, which has a SAM3X processor, so it should be able to invert the polarity without any external hardware.
The settings accessible from the Arduino SDK are minimalistic, Serial.begin() only allows to set the baudrate and start/parity/stop, nothing else.
In the SAM3X datasheet I found the "USART Mode Register", US_MR, which dedicates bit 23 (INVDATA) to invert the polarity.

Although it seems not to be documented anywhere, I found in a forum that to access the US_MR register, I have to use UART->UART_MR. I can read that register but cannot change it. The SAM3X datasheet mentions that this register might be write protected, and that the write protection can be cleared in the US_WPMR register.
However, the Arduino SDK doesn't seem to know about this register. I tried several possibilities,
US_WPMR
UART_WPMR
WPMR
UART->US_WPMR
UART->UART_WPMR
UART->WPMR

None of which are known.
The string WPMR is nowhere to be found in any of the files in my Arduino installation folder.
EDIT:
Interestingly, the source code for the UART class doesn't contain any reference to the WPMR. It just sets the required configuration registers without bothering with it.
void UARTClass::begin( const uint32_t dwBaudRate )
{
  // Configure PMC
  pmc_enable_periph_clk( _dwId ) ;
  // Disable PDC channel
  _pUart->UART_PTCR = UART_PTCR_RXTDIS | UART_PTCR_TXTDIS ;
  // Reset and disable receiver and transmitter
  _pUart->UART_CR = UART_CR_RSTRX | UART_CR_RSTTX | UART_CR_RXDIS | UART_CR_TXDIS ;
  // Configure mode
  _pUart->UART_MR = UART_MR_PAR_NO | UART_MR_CHMODE_NORMAL ;
  // Configure baudrate (asynchronous, no oversampling)
  _pUart->UART_BRGR = (SystemCoreClock / dwBaudRate) >> 4 ;
  // Configure interrupts
  _pUart->UART_IDR = 0xFFFFFFFF;
  _pUart->UART_IER = UART_IER_RXRDY | UART_IER_OVRE | UART_IER_FRAME;
  // Enable UART interrupt in NVIC
  NVIC_EnableIRQ(_dwIrq);
  // Enable receiver and transmitter
  _pUart->UART_CR = UART_CR_RXEN | UART_CR_TXEN ;
}

However, when I try to change UART_MR, it remains the same.

Did you try USART0->US_WPMR? Couldn't you add it? The register mapping offset is 0xE4 according to the datasheet.

Under Windows, Arduino puts the source code for hardware specific stuff in User\AppData\Local\Arduino, and not in the installation folder.
/* -------- US_WPMR : (USART Offset: 0xE4) Write Protect Mode Register -------- */
#define US_WPMR_WPEN (0x1u << 0) /**< \brief (US_WPMR) Write Protect Enable */
#define US_WPMR_WPKEY_Pos 8
#define US_WPMR_WPKEY_Msk (0xffffffu << US_WPMR_WPKEY_Pos) /**< \brief (US_WPMR) Write Protect KEY */
#define US_WPMR_WPKEY(value) ((US_WPMR_WPKEY_Msk & ((value) << US_WPMR_WPKEY_Pos)))

I would guess unlocking / locking would take the format:
????->US_WPMR = (US_WPMR_WPEN | US_WPMR_WPKEY(0x555341));
????->US_WPMR = (~US_WPMR_WPEN & US_WPMR_WPKEY(0x555341));


text:
what library should I #include when using switch-case statement
I receive an error code of: 'switch' was not declared in this scope
The code is correct so I assume that the necessary library was not included.
Please tell me the correct #include to use.
swith(pwm){
  case 0:   Serial.print(pwm); Serial.print("   ");_delay_ms(2000);
            break;
  case 31:  Serial.print(pwm); Serial.print("   ");_delay_ms(100);
            break;
  case 63:  Serial.print(pwm); Serial.print("   ");_delay_ms(100);
            break;
  case 95:  Serial.print(pwm); Serial.print("   ");_delay_ms(100);
            break;
  case 127:  Serial.print(pwm); Serial.print("   ");_delay_ms(100);
            break;
  case 159:  Serial.print(pwm); Serial.print("   ");_delay_ms(100);
            break;
  case 191:  Serial.print(pwm); Serial.print("   ");_delay_ms(100);
            break;
  case 124:  Serial.print(pwm); Serial.print("   ");_delay_ms(100);
            break;
  case 156:  Serial.print(pwm); Serial.print("   ");_delay_ms(100);
            break;
  case 188:  Serial.print(pwm); Serial.print("   ");_delay_ms(100);
            break;
  case 220:  Serial.print(pwm); Serial.print("   ");_delay_ms(100);
            break;
  case 252:  Serial.print(pwm); Serial.print("   ");_delay_ms(100);
            break;
  default:  break;
}

spelling error.  switch not swith

I receive an error code of: 'switch' was not declared in this scope ... no, you don't get that error ... look at the message again ... next time copy and paste the message ... you cannot trust yourself to correctly type in what it says

It seems you have a syntax error: write switch instead of swith.


text:
Last element of a struct disappearing on write/read
I'm building a weather station with two UNOs, using NRF24l01+ radios. Communications are fine. I'm sending a struct from one to the other. The struct has three elements:
    struct weather {
      float tempData;
      float humData;
      float pressData;
    };
    weather wData = {0, 0, 0};

I then populate the struct with values from my DHT22 Temperature Sensor and my BMP085 pressure sensor.
    float c = dht.readTemperature();
    wData.tempData = (c * 9/5) + 32;
    wData.humData = dht.readHumidity();

    sensors_event_t event;
    bmp.getEvent(&event);
    wData.pressData = (0.0295 * event.pressure);

Now I send it via the NRF24L01+.
    radio.write(&wData, sizeof(wData);

On the receiving Uno I have this.
    struct weather {
      float tempData;
      float humData;
      float pressData;
    };

    weather wData = {0, 0, 0};

    radio.read( &wData, sizeof(wData) );
    Serial.println(wData.tempData);
    Serial.println(wData.humData);
    Serial.println(wData.pressData);

I get results similar to this:
    Temp = 75.43
    Hum = 35.76
    Press = 0.00

The first two are correct. The final one is not. I can change the order and the first two will always be correct, but the last element is always 0.00. For example:
   Hum = 35.76
   Press = 30.14
   Temp = 0.00

I know I'm missing something here with my code but I can't find it. Anyone have some suggestions?

read() and write() return a bool, did you try to get it and print it to Serial, just to check both functions consider everything's OK? That might help.

Also, did you check that the weather on the emiiter contained a non-0 pressure before write()?

The line with radio.write(... is missing a closing parenthesis.

read() and write() return 1. Missed the closing parenthesis while moving code here but it's there in my code.

After taking a look at the RF24 library source code, I wonder if you have changed the payload size before read or write. To know about it, you should Serial.println() of radio.getPayloadSize() in both sketches; normally that should be 32 by default, but I wonder about it...

With the struct' populated the size is 12`.

The documentation mentions "Be sure to call openWritingPipe() first" before calling write().

@brorobw, @jfpoilpret was asking about the payload size set on your radio variable, because the behavior you're seeing is consistent with writes being truncated at 8 bytes. The RD24 class truncates/pads all writes to a fixed size, so you should check what that fixed size is set to.

Modified my struct by changing the first two elements from float to int.
struct weather {
  int tempData;
  int humData;
  float pressData;
}
weather wData;

Everything transmits fine now. I don't really need the precision of a float for temperature and humidity. However, I would still like to find the problem. Could there be some problem with the size of three floats versus two ints and a float? Serial.print(sizeof(wData)) is 12 when all elements are floats and 8 when using two int and a float. My understanding is the NRF24L01+ has a transmit and receive buffer of 32 bytes.

Have you tried the opposite, ie putting 4 floats instead of just 2? Maybe transmission is done by pack of 8 bytes?

Have not tried that. Will try soon and report back.

Did you try testing with a known strings of different lengths instead of your struct.

Have note tried anything else as of yet. Work and life getting in the way!


text:
Stability issue with webserver and smartmeter logging
In the past few months I have successfully logged the data from the power and gas meter in my house to a remote web server.
Now I try to add the ability to enable and disable my doorbell over the internet.
Although it seems to work, I experience 2 problems.
Problems

Arduino freezes after a few hours
When the meter reading is transmitted, the doorbell can not be
switched.

Questions

Is there a way to give priority to control the doorbell?

and ..

is there a way to find out why the Arduino freezes after a while?

Setup:

Arduino Mega 2560 board
Ethernet shield
LCD display
Relay
light sensor(for backlight control)
serial connection to smart power/gas meter

//V1.1: Cleaned up messy code
#include <LiquidCrystal_I2C.h>
#include <Wire.h>  // Comes with Arduino IDE
LiquidCrystal_I2C lcd(0x3f, 2, 1, 0, 4, 5, 6, 7, 3, POSITIVE);
#include <AltSoftSerial.h>
#include <SPI.h>
#include <Ethernet.h>

//setup ethernet server
byte mac[] = {0xDE, 0xAD, 0xBE, 0xEF, 0xFE, 0xED}; //assign arduino mac address
byte ip[] = { 192, 168,  178, 95}; // ip in lan assigned to arduino
byte gateway[] = { 192,  168, 178,  1}; // internet access via router
byte subnet[] = {  255,  255,  255,  0}; //subnet mask
EthernetServer server(84); //server port arduino server will use
char thingSpeakAddress[] = "";
IPAddress myDns(8, 8, 8, 8);
EthernetClient client;
String writeAPIKey = "XXXMX2WYYR0EVZZZ";
String tsData = "hello"; //dummy data
String readString; //used by server to capture POST request
const int updateThingSpeakInterval = 20 * 1000; // Time interval in milliseconds to update ThingSpeak (number of seconds * 1000 = interval)
// Variable Setup
long lastConnectionTime = 0;
boolean lastConnected = false;
int failedCounter = 0;
unsigned long int updateCounter = 0; //set refresh counter to 0
//////////////////////
//slimme meter////////
/////////////////////
char c;
AltSoftSerial altSerial;
const int requestPin = 48; //data pin connected to smartmeter
char input; // incoming serial data (byte)
bool readnextLine = false;
#define BUFSIZE 75
char buffer[BUFSIZE]; //Buffer for serial data to find \n .
int bufpos = 0;
long mEVLT = 0; //Meter reading Electrics - consumption low tariff
long mEVHT = 0; //Meter reading Electrics - consumption low tariff
long mEAV = 0; //Meter reading Electrics - Actual consumption
long mG = 0; //Meter reading Gas
//unsigned long lastConnectionTime = 0;             // last time you connected to the server, in milliseconds
const unsigned long postingInterval = 10L * 1000L; // delay between updates, in milliseconds
// the "L" is needed to use long type numbers

//const unsigned long postingInterval = 10 L * 1000 L; // delay between updates, in milliseconds, the "L" is needed to use long type numbers
/////////////////////////////////////////
//photcel////////controls lcd backlight//
////////////////////////////////////////
int photocellPin = 5; // the cell and 10K pulldown are connected to a0
int photocellReading; // the analog reading from the analog resistor divider
//boolean doorbell = true;

int creset = 43; //Telling arduino that you are connecting pin 43 with reset

//////////
//setup///
//////////
void setup() {
  Wire.begin();
  digitalWrite(22, LOW);
  digitalWrite(creset, HIGH);
  pinMode(creset, OUTPUT);
  pinMode(22, OUTPUT); //pin selected to control
  pinMode(6, OUTPUT); //pin selected to control
  pinMode(7, OUTPUT); //pin selected to control
  pinMode(8, OUTPUT); //pin selected to control
  //pinMode(5, OUTPUT); //pin 5 selected to control
  Ethernet.begin(mac, ip, myDns, gateway, subnet);
  server.begin();
  Serial.begin(9600);
  altSerial.begin(9600);
  Serial.println(F("Smarthome controller")); // keep track of what is loaded
  Serial.println(F("Send a g in serial monitor to test client")); // what to do to test client
  lcd.begin(20, 4); // initialize the lcd for 16 chars 2 lines, turn on backlight
  // sensorValue = analogRead(sensorPin);
  lcd.backlight(); // finish with backlight on
  //-------- Write characters on the display ------------------
  // NOTE: Cursor Position: Lines and Characters start at 0
  lcd.setCursor(0, 0); //Start at character 4 on line 0
  lcd.print("Smarthome controller");
  delay(1000);
  lcd.setCursor(0, 1);
  lcd.print("powerd by arduino");
  delay(1000);
  lcd.print("                  ");
  lcd.setCursor(0, 2);
  lcd.print("");
  lcd.setCursor(0, 3);
  delay(1000);
  lcd.print("Slimmemeter:     ");
  //lcd.backlight(); // turn on backlight.
  lcd.setCursor(0, 2);
  lcd.print("Doorbell: onn      ");
}
void loop() {
  if (updateCounter > 400) {
    digitalWrite(creset, LOW);  // Reset arduino
  }
  // Update ThingSpeak
  if (!client.connected() && (millis() - lastConnectionTime > updateThingSpeakInterval)) {
    decodeTelegram();
  }
  // Check if Arduino Ethernet needs to be restarted
  if (failedCounter > 3) {
    startEthernet();
  }
  lastConnected = client.connected();
  EthernetClient client = server.available();
  if (client) {
    while (client.connected()) {
      if (client.available()) {
        char cl = client.read();
        //read char by char HTTP request
        if (readString.length() < 100) {
          //store characters to string
          readString += cl;
          //Serial.print(c);
        }
        //if HTTP request has ended
        if (cl == '\n') {
          ///////////////
          Serial.print(readString); //print to serial monitor for debuging
          //now output HTML data header
          if (readString.indexOf('?') >= 0) { //don't send new page
            client.println("HTTP/1.1 204 Zoomkat");
            client.println();
            client.println();
          } else {
            client.println(F("HTTP/1.1 200 OK")); //send new page on browser request
            client.println(F("Content-Type: text/html"));
            client.println();
            client.println(F(""));
            client.println(F(""));
            client.println(F("<TITLE>Smarthome</TITLE>"));
            client.println(F(""));
            client.println(F(""));
            client.println(F("
Smarthome control page
"));
            // DIY buttons
            client.println(F("Deurbel"));
            client.println(F("ON"));
            client.println(F("OFF

"));

            client.println(F("Pins"));
            client.println(F(" ALL ON"));
            client.println(F(" ALL OFF"));
            client.println(F(""));
            client.println(F(""));
            client.println(F(""));
            client.println(F(""));
          }
          delay(1);
          //stopping client
          client.stop();
          if (readString.indexOf("**secretcode**") > 0) //checks for secretkey
          {
            ///////////////////// control arduino pin
            if (readString.indexOf("on2") > 0) //checks for 2
            {
              digitalWrite(22, LOW); // set pin 5 high
              //Serial.println(F("Led 5 On"));
              //Serial.println();
              lcd.setCursor(0, 2);
              lcd.print("Doorbell: on      ");
              //doorbell = true;
            }
            if (readString.indexOf("off3") > 0) //checks for 3
            {
              digitalWrite(22, HIGH); // set pin 5 low
              //Serial.println(F("Led 5 Off"));
              //Serial.println();
              lcd.setCursor(0, 2);
              lcd.print("Doorbell: off      ");
              //doorbell = false;
            }

            //clearing string for next read
            readString = "";
          }
        }
      }
    }
  }

  //lcd.setCursor(0, 0); //Start at character 4 on line 0
  //lcd.print("SMARTHOME CONTROLLER;.");
  //String analogValue = String(analogRead(A5), DEC);
  photocellReading = analogRead(photocellPin);

  //lcd.setCursor(0, 1);
  //lcd.print(photocellReading);
  if (photocellReading < 800) {
    lcd.backlight(); // turn on backlight.
  } else {
    lcd.noBacklight(); // turn on backlight.
  }

}

////////////////////////////////////////////////////////////////////////////
//////////////////////////FUNCTIONS/////////////////////////////////////////
////////////////////////////////////////////////////////////////////////////
void updateThingSpeak(String tsData)
//void sendGET() //client function to send and receive GET data from external server.
{
  //lcd.setCursor(0, 2);
  // lcd.print("                   ");
  lcd.setCursor(13, 3);
  lcd.print("verstur");
  // delay(1000);
  if (client.connect(thingSpeakAddress, 80)) {
    client.print("GET /smarthome/log.php?stroomLaag=");
    client.print(mEVLT);
    client.print("&stroomHoog=");
    client.print(mEVHT);
    client.print("&stroomVerbruik=");
    client.print(mEAV);
    client.print("&gasStand=");
    client.print(mG);
    client.println(" HTTP/1.1");
    client.println("Host: .nl");
    client.println("User-Agent: arduino-ethernet");
    client.println("Connection: close");
    client.println();
    lastConnectionTime = millis();
    updateCounter++;
    Serial.print("Connecting to log server...");
    Serial.println(updateCounter);
    //x=x+1; //page upload counter
    // lcd.setCursor(0,3);
    // lcd.print("Data send           ");
    //delay(1000);
    lcd.setCursor(13, 3);
    //lcd.print("                    ");
    lcd.print("ok        ");
    lcd.setCursor(16, 3);
    lcd.print(updateCounter);
    if (client.connected()) {
      Serial.println("Connecting to suscesfull...");
      //Serial.println();
      failedCounter = 0;
    } else {
      failedCounter++;
      Serial.println("Connection to failed (" + String(failedCounter, DEC) + ")");
      Serial.println("connection failed");
      Serial.println();
      lcd.setCursor(13, 3);
      lcd.print("fout");
      lcd.setCursor(16, 3);
      lcd.print(String(failedCounter, DEC));
    }
  } else {
    failedCounter++;
    Serial.println("Connection to ThingSpeak Failed (" + String(failedCounter, DEC) + ")");
    Serial.println();
    lastConnectionTime = millis();
  }
  while (client.connected() && !client.available()) delay(1); //waits for data
  while (client.connected() || client.available()) { //connected or data available
    char cl = client.read(); //gets byte from ethernet buffer
    //readString += c; //places captured byte in readString
    //Serial.print(c); //print raw data
  }
  client.stop(); //stop client
  readString = ""; //clear readString variable
}

////////////////////////////////////////////////////

void startEthernet() {
  client.stop();
  Serial.println("Connecting Arduino to network...");
  Serial.println();
  delay(1000);
  // Connect to network amd obtain an IP address using DHCP
  if (Ethernet.begin(mac) == 0) {
    Serial.println("DHCP Failed, reset Arduino to try again");
    Serial.println();
  } else {
    Ethernet.begin(mac, ip, gateway, gateway, subnet);
    server.begin();
    Serial.println("Arduino connected to network using DHCP");
    Serial.println();
  }
  delay(1000);
}

////////////////////////////////////////////////////

void decodeTelegram() {
  long tl = 0;
  long tld = 0;
  if (altSerial.available()) {
    //input = altSerial.read();
    c = altSerial.read();
    // --- 7 bits instelling ---
    c &= ~(1 << 7);
    char inChar = (char) c;
    //Serial.print(c);
    input = c;
    //Serial.println(input);
    //char inChar = (char)input;
    // Fill buffer up to and including a new line (\n)
    buffer[bufpos] = input & 127;
    bufpos++;
    if (input == '\n') { // We received a new line (data up to \n)
      if (sscanf(buffer, "1-0:1.8.1(%ld.%ld", & tl, & tld) == 2) {
        tl *= 1000;
        tl += tld;
        mEVLT = tl;
      }
      // 1-0:1.8.2 = Elektra verbruik hoog tarief (DSMR v4.0)
      if (sscanf(buffer, "1-0:1.8.2(%ld.%ld", & tl, & tld) == 2) {
        tl *= 1000;
        tl += tld;
        mEVHT = tl;
      }
      // 1-0:1.7.0 = Electricity consumption actual usage (DSMR v4.0)
      if (sscanf(buffer, "1-0:1.7.0(%ld.%ld", & tl, & tld) == 2) {
        mEAV = tl + tld;
      }
      // 0-1:24.2.1 = Gas (DSMR v4.0) on Kaifa MA105 meter
      //if (strncmp(buffer, "0-1:24.2.0", strlen("0-1:24.2.1")) == 0) {
      if (sscanf(strrchr(buffer, '(') + 1, "%d.%d", & tl, & tld) == 2) {
        mG = (tl * 1000) + tld;
      }
      //}
      // Empty buffer again (whole array)
      for (int i = 0; i < 75; i++) {
        buffer[i] = 0;
      }
      bufpos = 0;
    }
    if (input == '!') { //uitroepteken geeft einde van telegram aan, dus we gaan data versturen
      // if (millis() - lastConnectionTime > postingInterval) {
      // httpRequest();
      updateThingSpeak("field1=0");
      // httpRequest();
      mEVLT = 0;
      mEVHT = 0;
      mEAV = 0;
      mG = 0;
      client.stop();
      //}
    } //Einde vraagteken detectie
    //Serial.print(c);
  } //Einde 'if AltSerial.available'
} //Einde 'decodeTelegram()' functie

I already experienced an ATmega microcontroller freeze unexpectedly, but in my case it was because of fluctuations in the power source. As you have a full Arduino board here, it should have the necessary capacitors to filter things. Though insufficient power can still be an issue even with capacitors. So, unless you power it with insufficient batteries, it's probably a bug in your code. You could add more logging and last logged message is a clue ; this requires to constantly listen on the serial port with another machine.

power consumption of the relay coil could be the problem

The Arduino is powered with 1amp adapter on the power grid

buffer[bufpos] = input & 127;
bufpos++;

Never use a buffer without a length protection.
Flag if max buffer is reached, force to never write after last position.
Like this:
if ( bufpos > MaxBuff )
{
    Serial.print("errornumber");
    bufpos = MaxBuff;
    //And force \n to finish errored message
}

Please see some comments that can help you.
Why do you use a software serial port?
This ATmega has 4 real serial ports!
delay() is dangerous in the main loop runtime. Try to use it only in setup.
Every time you call a task, be sure you will not stay there forever.
Get out of the task, if something seems to be too long time. Use millis() stamp time differences to measure time spent.
Print it if necessary on debug compiler option.
Printing on failure case do not spend MCU time if there are no errors.

I don't see any problem using delay() in program loops; if you are going to state that it is dangerous please explain why.  SoftSerial is handy  whenever you are using serial communications on the non-default serial pins, and for consistency in programming I find I tend to use it just so my code is very clear in naming pins.  millis() is great, however you must remember that adding any debugging statements like lcd.write() or Serial.write() will necessarily throw off the timing.  All that being said, can I ask what your main point is in this answer, please?

My recomendations are just to help you to find the two problems. The cpu freezes because there are ram buffer corruption. Serial hardware decreases time to process serial data and, a delay or a long loop means the system services for ethernet and serial tasks will stop

Im not sure why softserial is required, maby beqause the message from the smartpowermeter is inverted . I will try to add the buffer lenght protection and let you know te result.


text:
How to connect capacitive touch sensor to Arduino?
The capacitive touch sensor has 3 pinouts: Vin, GND, and OUT and emits an active high signal when the pad is touched. I should be routing the OUT pin to any one of the digital input pins on my Arduino Micro, correct?
Also, I need to power 2 of these capacitive touch sensors along with an IMU. How do you power multiple sensors on the Arduino Micro? There is only one GND pin and one 5 V pin. I would prefer if it could be done without a breadboard as this entire setup will be placed in a stylus.

The capacitative touch sensor has 3 pinouts: Vin, GND, and OUT and emits an active high signal when the pad is touched. I should be routing the OUT pin to any one of the digital input pins on my arduino micro, correct?

Probably, yes. Without more details about what the sensor is we can't really comment.

Also, I need to power 2 of these capacitative touch sensors along with an IMU. How do you power multiple sensors on the arduino micro? There is only one GND pin and one 5 V pin. I would prefer if it could be done without a breadboard as this entire setup will be placed in a stylus.

You can plug as many (within reason) items into the +5V and GND pins as you like. You can twist wires together, use screw terminal blocks, breadboard, solder, whatever you like, to connect the wires together to a single wire that goes to the pin.


text:
Switch case problem in Arduino code
I am trying to develop an IR remote for appliances. I have written Arduino code for this purpose. I have used switch case to determine an action from the corresponding IR decode result (HEX), but I am not getting the output.
My code is:
#include <IRremote.h>

int RECV_PIN = 6;
int led = 13;//1FE50AF
int led1 = 12;//1FED827

boolean previousState=LOW;
boolean previousState1=LOW;
boolean state;
boolean state1;
IRrecv irrecv(RECV_PIN);

decode_results results;

void setup() {
  Serial.begin(9600);
  pinMode(13,OUTPUT);
  pinMode(12,OUTPUT);
  irrecv.enableIRIn();// Start the receiver
}

void loop() {
  if (irrecv.decode(&results)) {
    Serial.println(results.value, HEX);
    switch(results.value) {
       case '0x1FE50AF':
       if (previousState == LOW) {
         state=HIGH;
         digitalWrite(led,state);
         Serial.println("LED ON");
         previousState=state;
       } else {
         state=LOW;
         digitalWrite(led,state);
         Serial.println("LED Off");
         previousState=state;
       }
       break;

       case '0x1FED827':
       if (previousState1 == LOW) {
         state=HIGH;
         digitalWrite(led1,state1);
         Serial.println("LED ON");
         previousState1=state1;
       } else {
         state1=LOW;
         digitalWrite(led1,state1);
         Serial.println("LED off");
         previousState1=state1;
       }
       break;
    }
    irrecv.resume(); // Receive the next value
  }
}

Hi, welcome to Arduino.SX. You can use { } on top of the editor bar to mark you code so they all become readable between text and codes.

Replace all:
case '0xZZZZZZZZ':

with:
case 0xZZZZZZZZ:

That's because value in decode_results structure is declared as unsigned long, 0xZZZZZZZZ is an unsigned long, but '0xZZZZZZZZ' is not (actually, it should not even compile).


text:
Can a motherboard be a simple circuit between arduino uno and a set of devices (ie: motors)
Reason for question:
My son is working on a project to build a robot controlled by an arduino uno. This question is more about terminology than process, but since terms are very important at this level, I rather ask some expert advice - I have not found any input on the internet about this!
Question:
What is the correct technical name (if any) of the circuit board that acts as the interface between the arduino-uno (a micro-controller) and the motors (the external devices)? According to the definition of a motherboard*, this "interface" circuit board would act as a very basic motherboard, as it would "allow communication" between the components, but it would not contain expansion slots, so should it be called something else?
Background on project:
The robot will be very basic. A body will be made of plastic legs and motors for joints; an Arduino-uno will provide the logic for motor movement; 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.
We are just missing the proper terminology to use for this "interface" board and I cannot find any concrete info online or on books. If I get good terms in this post, then we can do further research on those terms. Thanks.
https://en.wikipedia.org/wiki/Motherboard

"interface board" is perfectly fine terminology

On Arduino contexts, these are often called shields. I kinda dislike this, because every dev board tries to have its name (HATs, Capes, Shields, etc etc..).

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.

Thanks. This answers my questions as noted by alex.forencich and wesleylee. Note although I agree with you that we should not get too caught up in the terminology (specially as hobbyist), this is for a judged science fair project where the research paper carries more weight than the built product, so having the correct terminology is crucial. I'll tell my son to call it an interface board and to find a peer reviewed reference from the library (these kids now a days even have to add doctoral references in all research - it's good, but insane at the same time). Thanks again.

In the Arduino ecosystem these boards are called 'shields'.
Arduino describes a shield as:

Shields are boards that can be plugged on top of the Arduino PCB
  extending its capabilities.

For example, there is an Arduino Motor Shield which sounds very similar in purpose to the board that your son is making.


text:
Interfacing IMU and GPS with Arduino
I am using an Arduino UNO board and trying to interface IMU sensor (GY-521) and GPS sensor (Ublox Neo-6M) at the same time. The connections of the IMU and GPS are as follows
IMU to Arduino:
Vcc --> 5V
Gnd --> Gnd
SDA --> A4
SCL --> A5
INT --> D2
GPS to Arduino:
Vcc --> 5V
Gnd --> Gnd
Tx --> Rx
Rx --> Tx
Now when I used the IMU sensor alone and tested it with the Jeff Rowberg library, it was working fine. But as soon as I make the connections with the GPS and upload a program, the IDE gives the following error:
Arduino: 1.7.10 (Windows 7), Board: "Arduino Uno"

Build options changed, rebuilding all

Sketch uses 3,970 bytes (12%) of program storage space. Maximum is 32,256 bytes.

Global variables use 313 bytes (15%) of dynamic memory, leaving 1,735 bytes for local variables. Maximum is 2,048 bytes.

avrdude: stk500_recv(): programmer is not responding

avrdude: stk500_getsync() attempt 1 of 10: not in sync: resp=0xa5

avrdude: stk500_recv(): programmer is not responding

avrdude: stk500_getsync() attempt 2 of 10: not in sync: resp=0xa5

avrdude: stk500_recv(): programmer is not responding

avrdude: stk500_getsync() attempt 3 of 10: not in sync: resp=0xa5

avrdude: stk500_recv(): programmer is not responding

avrdude: stk500_getsync() attempt 4 of 10: not in sync: resp=0xa5

avrdude: stk500_recv(): programmer is not responding

avrdude: stk500_getsync() attempt 5 of 10: not in sync: resp=0xa5

avrdude: stk500_recv(): programmer is not responding

avrdude: stk500_getsync() attempt 6 of 10: not in sync: resp=0xa5

avrdude: stk500_recv(): programmer is not responding

avrdude: stk500_getsync() attempt 7 of 10: not in sync: resp=0xa5

avrdude: stk500_recv(): programmer is not responding

avrdude: stk500_getsync() attempt 8 of 10: not in sync: resp=0xa5

avrdude: stk500_recv(): programmer is not responding

avrdude: stk500_getsync() attempt 9 of 10: not in sync: resp=0xa5

avrdude: stk500_recv(): programmer is not responding

avrdude: stk500_getsync() attempt 10 of 10: not in sync: resp=0xa5

Problem uploading to board.  See http://www.arduino.cc/en/Guide/Troubleshooting#upload for suggestions.

  This report would have more information with
  "Show verbose output during compilation"
  enabled in File > Preferences.

I can't seem to spot the problem. Kindly help me out as I am new to the Arduino development. Thanks.

Remove the GPS from RX/TX during the sketch upload. It is confusing the USB connection. The alternative is to use SoftwareSerial for the GPS.
Cheers!

Not enough to comment yet, but to add Mikael Patel's answer, using Software Serial  might help here to take the gps off the Arduino's serial lines


text:
Automotive Lighting Control Module
I am looking for an Arduino-based solution for an automotive lighting application.
System Requirements:

Able to Operate in Automotive (Interior) Environment (12 +/- 2V DC    Voltage)
Minimum 3 12 V DC Inputs (Preferably 6)
Minimum of 3 12 V DC Outputs capable of operating standard automotive-style
relays. (Preferably 6)
Compact/Condensed Form-Factor

Finding an Arduino that runs on a 12 V power supply is simple, but finding one that can handle 12 V I/Os has proven tricky.
Using a relay shield for the outputs is straightforward enough, and would be a safe way to step up the output voltage and current (although current is of little concern, given I'm only going to powering the coil in a relay). But what to do about the inputs? I don't want a transistor on each input - that would get quite tedious and large very quickly. Using relays on both sides would work, but most shields are setup to receive coil activation signals from the Arduino and as such also can't handle 12 V inputs, so using a relay shield to step-down from 12 V to 5 V also seems problematic.
Is there an all-in-one I/O solution that can step-down incoming voltages for the board and step-up output voltages on the other side?
What are my best options? I'd prefer not to have to custom-make a shield for such a basic I/O application...
Any and all help is greatly appreciated!

I think this post is 'on-topic', but you may have to look at ways of converting 10-14V -> 5V and that might be better posted on The Electrical Engineering forum, but don't mention the "A" word, otherwise they will fling you post over here faster than you car can do a 1/4 mile :)

I understand what you mean. Converting voltage isn't foreign to me (I'm a M.E.), but I'm surprised there is not already a shield that accommodates this sort of thing. Maybe something like this? http://ledsee.com/index.php/en/arduino-modules2013-02-16-10-32-17/1-x-arduino-fet-shield-detail

A Logic Level Converter can step-down incoming voltages for the Arduino inputs and may also work to drive the relay coils. Heres an example of a 4 channel board:
https://www.sparkfun.com/products/12009
and there are also 8 channel boards:
http://www.ebay.ca/itm/8-Channel-I2C-IIC-Logic-Level-Converter-Module-Bi-Directional-for-Arduino-MF-/172424799119?hash=item282551a38f:g:6Q0AAOSwo4pYPDwg.
The boards are small and use BSS138 MOSFETs, which, according to the data sheet: http://cdn.sparkfun.com/datasheets/BreakoutBoards/BSS138.pdf can handle a maximum of 0.22A continuous current and a Drain-Source Voltage of 50V. The SparkFun link has lots of information about these devices. Normally, you would use them to translate between 5V and 3.3V but I don't see why you couldn't power the "high voltage side" with the vehicles 12 - 14V and the "low voltage side" with 5V from the Arduino.

An easy solution would be to use a 10K resistor in series between the 12V input and the Arduino input. This reduces the current down to about 1mA. The zener diode in the microcontroller would then safely limit the voltage to 5V.

simulate this circuit – Schematic created using CircuitLab
Its the nice easy compact solution you are looking for.

There is no Zener in the microcontroller, but a diode from GDN to the pin, and another diode from the pin to Vcc.

You could use a simple voltage divider on the inputs. It would take 2 resistors pre input.  That wouldn't be too huge.

I do not think a voltage divider would be sufficient for an automotive application given the likelihood of voltage fluctuations.

I see what you're saying.  But you could divide it down to 3.5 volts or maybe a little less and still rely on it reading HIGH.  So the overvoltages wouldn't get out of range as much.  You could also put a cap across to take out the big spikes.

That's a good point - what's the lower cut-off for "HIGH", just under 1V, right?

Depends on the chip.  For the 328 and the 2560 it's 0.6 * Vcc.  So right at 3V for something like an UNO at 5V.  I do know from much experience that the signal form any 3.3V device will reliably get you a HIGH.  The cutoff for LOW is 0.3*Vcc, so for an UNO at 5V that's about 1.5V.  Between 1.5V and 3.0V things aren't so well defined.


text:
Why PJ0 and PJ1 are not reporting as PCINT pins
When the sketch shown at end-of-question is compiled and uploaded to an Arduino board, it is supposed to Serial-print a list of available digital pins, showing for each pin whether it supports PWM or PCINT.  (For the latter items, it should indicate whether it has timer-supported PWM, and whether it can cause a hardware-supported pin-change-interrupt.)  For example, for an ATmega-2560 board, the program's output includes lines like
  Pin# Port Mask  PWM  PCINT
  11   PB5  0x20  PWM  PCINT5  PCINT0_vect
  46   PL3  0x08  PWM
  52   PB1  0x02       PCINT1  PCINT0_vect

Using arduino 1.6.3 on my Ubuntu 14.04 system with an ATmega-2560 board, the program's output for pins 14 and 15 is:
  14   PJ1  0x02
  15   PJ0  0x01

As I understand it, those pins should be shown⁽¹⁾ as supporting PCINT9 and PCINT10, with vector PCINT1_vect, but the program doesn't report them as such.  What is this problem due to?
⁽¹⁾See, for example, table 13.3.9, Alternate Functions of Port J, in doc2549.pdf, the spec sheet for ATmega640/1280/1281/2560/2561.  Also see Why is my interrupt code not working?.
Sketch pinsList.ino:
/*  pinsList -- JW, 4 October 2015 --
 *
 *  Displays a list of Arduino pin numbers for current kind of Arduino
 *  board, along with port codes, pin-change-interrupt numbers, and
 *  pin-change-interrupt vector numbers.
 *
 *  Here are two examples of output lines for pin 11, the first for an
 *  Uno, the second for a Mega:
 *
 *        11   PB3   0x04   PWM   PCINT3  PCINT0_vect
 *        11   PB5   0x20   PWM   PCINT5  PCINT0_vect
 */
//-----------------------------------------------------------
// Given a value with 1 bit set, return bit #.  Else return 9.
byte getBitfromBV (byte m) {
  byte b=0, v=1;
  while (v) {
    if (m==v)
      return b;
    ++b; v <<= 1;
  }
  return 9;
}
//-----------------------------------------------------------
void processPinNumber(byte pin) {
  char buffi[128];      // We create text-to-write in buffi
  byte nbuff=0;         // #chars used in buffi
  byte nPCICR;          // 0, 1, or 2 for mask-register #
  byte bitInByte;       // 0 to 7 for bit in I/O mask
  byte pinPort;         // pin's port #, in range 1 to 12
  byte PCInum;          // PCINT# if pin is a PCI pin
  char *portLet = "?ABCDEFGHIJKL";

  if (pin >= NUM_DIGITAL_PINS) return;

  pinPort = digitalPinToPort(pin); // Get port #, in range 1 to 12
  bitInByte = getBitfromBV(digitalPinToBitMask(pin));

  nbuff = snprintf(buffi, sizeof(buffi), "  %2d   P%c%d  0x%02x",
           pin, portLet[pinPort], bitInByte, 1<<bitInByte);

  // Indicate if it's a PWM pin
  if (digitalPinHasPWM(pin)) {
    nbuff += snprintf(buffi+nbuff, sizeof(buffi)-nbuff, "  PWM");
  } else {
    nbuff += snprintf(buffi+nbuff, sizeof(buffi)-nbuff, "     ");
  }

  // If it's a PCINT pin, show its PCINT number and 0, 1, 2 for its vector #
  if (digitalPinToPCICR(pin)) {      // Is it a PCint pin?
    nPCICR = digitalPinToPCICRbit(pin); // 0, 1, 2 for pin's PCICR bit#
    PCInum = nPCICR*8 + bitInByte;
    nbuff += snprintf(buffi+nbuff, sizeof(buffi)-nbuff,
             "  PCINT%d  PCINT%d_vect",  PCInum,  nPCICR);
  }
  Serial.println(buffi);
}
void setup() {
  delay(50);
  Serial.begin(115200);
  delay(50);
  while (!Serial) ;             // wait for serial stream to connect
  Serial.println("\nPin#  Port  Mask  PWM   PCINT");
  for (byte p=0; p<NUM_DIGITAL_PINS; ++p)
    processPinNumber(p);
  Serial.end();
}

void loop() {
}

Majenko was very close but seems to have missed the explanatory comment from the source code:
// (I've deliberately left out pin mapping to the Hardware USARTs - seems senseless to me)
// Pins: 10, 11, 12, 13,  50, 51, 52, 53,  62, 63, 64, 65, 66, 67, 68, 69

#define digitalPinToPCICR(p)    ( (((p) >= 10) && ((p) <= 13)) || \
                                  (((p) >= 50) && ((p) <= 53)) || \
                                  (((p) >= 62) && ((p) <= 69)) ? (&PCICR) : ((uint8_t *)0) )

Which seems like it may apply to the fact that the USART3 pins PJ1 (14) and PJ0 (15) are missing.
As for why providing mappings to the hardware USART pins "seems senseless" a little playing with git blame will show that these lines were added to this file in commit f179794  in response to issue 490:

The SoftwareSerial library defines macros that map Arduino pin numbers to the pin changes interrupts on the pins.  We should pull this up into the board-specific pin definition header file so that the SoftwareSerial library can work on any AVR for which those macros (and the pin-change interrupts) are defined.

Which is to say that David Mellis didn't write those lines for generic interrupt use as part of pins_arduino.h, but rather moved code originally written as part of the software serial library to this file to make things more portable (and, though perhaps incidentally, generally usable for other purposes).  It's not exactly clear who the original author speaking as "I" in the comment is - the Mega-specific code in question appears to come most immediately from Mikal Hart's extension of Ladyada's Uno-only interrupt soft serial code (which did not have it) but there's also a comment in that seemingly crediting Paul Stoffregen (Teensy boards) for at least some aspect of the macro...
It does kind of make sense that someone writing a software serial library could consider using it on hardware serial pins pointless.  But counterarguments could also be made - for one example, the 16u2 core either uses or has experimented with software serial at some baud rates, and for another a software serial implementation could be a plausible way of overcoming swapped RX & TX wiring, or a way of implementing inverted signalling logic when using simplified level shifters or talking to something which expects to.
Given that in its current location the code is no longer necessarily only for software serial use, it seems plausible that a carefully written and fully validated patch to make it more general might be favorably received.

And also the counterargument that software serial is not the only use for interrupts.

@IgnacioVazquez-Abrams - when the code in question was originally written, it was only for software serial and buried in that (at the time 3rd party) library.  So that would be an argument for patching it now that it is more general, but not an argument against the original decision.

It's because of this entry in the board's pins_arduino.h file:
#define digitalPinToPCICR(p)    ( (((p) >= 10) && ((p) <= 13)) || \
                                  (((p) >= 50) && ((p) <= 53)) || \
                                  (((p) >= 62) && ((p) <= 69)) ? (&PCICR) : ((uint8_t *)0) )

Basically your program isn't reporting what the pins can do - it's reporting what the Arduino system has been programmed to support for those pins.  Basically it hasn't been programmed to support PCINT on those pins.

Majenko, although I already understood that I upvoted your answer; but why aren't pins 14 and 15 listed in that macro?

Who knows? Why is anything the way it is with Arduino? Most of the time the answer is "Because the person that wrote it is clueless"...