text:
Why is my class losing a field in the middle of a method
I have a class with a byte (stripLength) that seems to just disappear in the middle of the frameStep() method. I'm not especially skilled with C++ (or non-VM languages in general), but I believe it's only written or modified at the initialization of the class. What am I doing wrong?
BugFinding.ino
#define PIN 11
#define NUM_LEDS 100
#define WAIT 5
#define TAIL_LENGTH 40

#include "Libraries/Adafruit_NeoPixel.h"
#include "LightingStrip.h"

Adafruit_NeoPixel strip = Adafruit_NeoPixel(NUM_LEDS, PIN, NEO_RGB + NEO_KHZ800);
LightingStrip lightStrip = LightingStrip(strip, NUM_LEDS, 20);

void setup() {
    Serial.begin(9600);
    strip.begin();
    strip.show();
    Serial.println("BugFinding");
    lightStrip.setColors();
}

void loop() {
    Serial.println("loop");
    lightStrip.frameStep();
    lightStrip.write();
    delay(WAIT);
}

LightingStrip.h
#ifndef LIGHTINGSTRIP_H_
#define LIGHTINGSTRIP_H_

#include "Libraries/Adafruit_NeoPixel.h"

class LightingStrip {
    public:
        LightingStrip(Adafruit_NeoPixel ledStrip, uint8_t stripLength, uint8_t lengthOfTail);
        void frameStep();
        void write();
        void setColors();
    protected:
        Adafruit_NeoPixel strip;
        uint8_t mode;
        uint8_t frame;
        uint8_t colorFrame;
        uint8_t stripLength;
        uint8_t tailLength;
        uint32_t buf[];
        uint32_t colors[7];
        uint8_t currentColor[3];

        void cycleStep();
};

#endif /* LIGHTINGSTRIP_H_ */

LightingStrip.cpp
#include "LightingStrip.h"
#include "Libraries/Adafruit_NeoPixel.h"

LightingStrip::LightingStrip(Adafruit_NeoPixel ledStrip, uint8_t length, uint8_t lengthOfTail) {
    strip = ledStrip;
    stripLength = length;
    tailLength = lengthOfTail;

    buf[stripLength] = {0};
    colorFrame = 0;

    cycleStep();
}

void LightingStrip::setColors(){
    //colors = uint8_t[8][3];
    colors[0] = strip.Color(255, 120,   0); // Orange
    Serial.println("Color 0: " + String(colors[0]));
    Serial.println("Color 0: " + String(strip.Color(255, 120,   0)));
    Serial.println("stripLength: " + String(this->stripLength));
    colors[1] = strip.Color(  0, 255,   0); // Green
    Serial.println("setColors");
    Serial.println("stripLength: " + String(stripLength));
}

void LightingStrip::cycleStep(){
    frame = 0;
    colorFrame++;
}

void LightingStrip::frameStep(){
    Serial.println("frameStep");
    Serial.println("Color 0: " + String(colors[0]));
    int16_t j;
    Serial.println("frame: " + String(frame));
    Serial.println("colorFrame: " + String(colorFrame));
    Serial.println("stripLength 1: " + String(stripLength));
    if(frame > stripLength + tailLength)
        cycleStep();
    Serial.println("stripLength 1.2: " + String(stripLength));

    for(j=0; j<stripLength; j++){
        buf[j] = strip.Color(255,255,255);
    }
    Serial.println("stripLength 2: " + String(stripLength));
    for(j=frame; j>0 && frame-j<=stripLength; j--){
        if(j>stripLength) continue;
        buf[j] = colors[colorFrame];
        Serial.print("j: " + String(j));
        Serial.print(" color: " + String(colors[colorFrame]));
        Serial.println();
    }
    Serial.println("stripLength 3: " + String(stripLength));
    Serial.println("stripLength 4: " + String(stripLength + tailLength));
    Serial.println("stripLength 5: " + String(stripLength));

    frame++;
}
void LightingStrip::write(){
    Serial.println("write");
    Serial.println("stripLength: " + String(stripLength));

    int16_t j;

    for(j=0; j<stripLength; j++){
        Serial.print(" j: " + String(j));
        strip.setPixelColor(j, buf[j]);
    }
    Serial.println();
    Serial.println(String(buf[0]));
    Serial.println(String(strip.getPixelColor(0)));
    strip.show();
}

Serial Output:
BugFinding
Color 0: 16742400
Color 0: 16742400
stripLength: 100
setColors
stripLength: 100
loop
frameStep
Color 0: 16742400
frame: 0
colorFrame: 1
stripLength 1: 100
stripLength 1.2: 100

Have you checked for memory error? You are using a lot of Strings and if you are using an Arduino Uno (Nano, etc) there might be some memory issues with only 2K byte available. Start by removing all the "literal string" + String(value) and replacing them with multiple println() lines.

It looks like you're right. I'm running out of memory in general. If you'll make this an answer, I'll mark it as correct.

At first glance this looks like a sketch with typical memory (heap) issues. When using a lot of string literals, String variables and expressions heap memory becomes fragmented or simple exhausted.
Some programming rules to avoid this:

If possible use the macro F() with string literals. Typically F() should be used when printing a string.
If possible do not use String especially when there is limited amount of SRAM. Remember that ATmega328 based boards such as Arduino Uno, Nano, etc, have only 2 Kbyte SRAM.
Avoid String expressions especially in Serial print statements. Use several print statements instead.

Applying these programming rules to some of the statements in the code above:
Serial.println("frameStep");
Serial.println("Color 0: " + String(colors[0]));
Serial.println("frame: " + String(frame));

Becomes:
Serial.println(F("frameStep"));
Serial.print(F("Color 0: "));
Serial.println(colors[0]);
Serial.print(F("frame: "));
Serial.println(frame);

With no String expressions, and a lot less memory used.
Cheers!
PS: As @MarkSmith points out there is also a pure allocation error. The statement below in the LightingStrip constructor:
buf[stripLength] = {0};

Does not mean allocate and assign. It means element stripLength is assigned the value of the pointer to an array with the single value zero. Guess that the compiler is also warning about this. The value of buf is random as it is not initiated. Assigning an element in the buf will write to a random position.

I think what you mean by stripLength "disappearing" is that your stripLength 2 trace does not appear. This is going to be because you never reach this point in the code.
Look at buf: it's defined as an array in the .h file, but you don't ever allocate any memory for it. buf[stripLength] = {0} doesn't do what you think it does. It puts a 0 into element 100, which at that point is going to trash over some memory you don't mean to write to. When you write to every element in the loop, you're going to trash over lots of memory you didn't mean to.  You want something like
buf = (uint32_t*) malloc(stripLength*sizeof(uint32_t));

Remember to free it again in the destructor.
(Full disclosure: I'm writing this on my phone and I can't remember or test whether it's legal syntax to do this with your array defined (in the .h) as uint32_t buf[]. It's more common, and certainly legal, to use uint32_t* buf.)


text:
The easiest and most time efficent way to connect to the internet regardless of the cost
I am working on my graduation Project. I want to use the cayenne (mydevices) platform to control my Arduino. Mainly I want to be able to control a servo Motor through the Cayenne app and I want to use a gyro sensor that would also control the servo using the app after obtaining the readings from the sensor. The Options are:
1- Yun arduino
2- Arduino Ethernet
3- Arduino uno (which I currently have) + Arduino Ethernet shield or arduino wifi shield
Cayenne (mydevices) APP supports all of the above Options
What is the easiest to implement? I have short time period and working on the mechanical design for the Project in the same time.
Your help is appreciated

Option 2 and 3 are kind of the same, as the Arduino Ethernet has the same components as the Ethernet shield. The ethernetShieldV2 has a slightly newer chip on it, but I don't expect that much difference. The Yun might be easier, but the problem is that not a lot of people have used it, so there aren't a lot of tutorial online. So I'd probably go with  option 2 or 3. Unless you need HTTPS for the Cayenne API.

Guess there are a few more requirements such as bandwidth, message/protocol frequency, motor control speed, etc. Also available libraries and support.

What about the ESP8266 or a raspberry pi

If you want to stick with Arduino (instead of SBC), I suggest you use Arduino Yun.
The Linux side of the Yun will provide very much greater scope for web programming compared to Arduino+Ethernet shield. There also a bridge library to communicate with the Yun.

The Arduino Uno and Arduino Ethernet are very simple to program, to connect it to the Internet.
I never used the Yun Arduino, but it seems a little bit harder.

source: Stack Exchange

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

authors: Вадим Чеховский

sort: votes


text:
LED Blinking Using Push button
Whenever I upload the following program I am getting error message
showing "expected initializer before interval".
Kindly Help me to solve out this probleme.
const byte button=2;
const byte LED=10;
bool blinking =false;//defines when blinking should occur
unsigned long blink Interval=250;// number of milliseconds for blink
unsigned long currentMillis;// variables to track millis()
unsigned long previousMillis;
void setup()
{
    pinMode(button,INPUT);
    pinMode(LED,OUTPUT);
}
void loop()
{
    // this code  blinks the LED
    if(blinking) {
        currentMillis =millis();// better to store in variable, for less jitter

        if((unsignedlong)(currentMillis-previousMillis) >=blinkInterval) { // enough time passed yet?
            digitalWrite(LED,!digitalRead(LED)); // shortcut to toggle the LED
            previousMillis =currentMillis;// sets the time we wait "from"
        }
    } else {
        digitalWrite(LED,LOW); // force LED off when not blinking
    }

    int reading=digitalRead(button);
    delay(50); // crude de-bouncing

    if(reading==LOW) // buttons with pull-up are pressed when LOW
    { blinking =true; }// start blinking
    else
    { blinking =false; }// stop blinking
}

The fully working sketch
const byte button=2;
const byte LED=10;
bool blinking =false;
unsigned long blinkInterval=250;
unsigned long currentMillis;
unsigned long previousMillis;
void setup()
{
    pinMode(button,INPUT);
    pinMode(LED,OUTPUT);
}
void loop()
{

    if(blinking) {
        currentMillis =millis();

        unsigned long blinkInterval=100;
        if((unsigned long)(currentMillis-previousMillis) >= blinkInterval) {
            digitalWrite(LED,!digitalRead(LED)); LED
            previousMillis =currentMillis;
        }
    } else {
        digitalWrite(LED,LOW);
    }

    int reading=digitalRead(button);
    delay(100);

    if(reading==LOW)
    { blinking =true; }
    else
    { blinking =false; }
}

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

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


text:
Arduino WiFi shield working intermittently, "WiFi Shield not present"
I am trying to use the official arduino wifi shield, It works occasionally, but most of the time (when running the WiFi web server example code, or my derivitave program, it outputs WiFi shield not present on the terminal. I have tried updating the firmware several times, but it has not fixed the problem. Is the wifi shield always this unreliable? What can I do to fix it?

Are you using a Uno rev3? See https://www.arduino.cc/en/Main/arduinoBoardUno for differences between Revs-1/2/3

yes, I got an r3 Uno just for use with this project (although I also got it intermittently working with an r2 uno (using wires to compensate for missing pins, before the firmware update).

also, it seems to be getting worse, I haven't been able to get it to detect the shield at all for the last hour :(

Ok, what are you powering the setup from? The other main possibility I can think of is that the WiFi shield is drawing too much power for your USB port (some PCs can limit to 100mA). You could try a wall adapter.

I am using a USB port, but it was able to power a 60 LED strip with the arduino, It also does not work with a wall adapter. Could the LED strip (of which I intended only a few LEDs are lit (but all of which briefly lit accidentally) at a time have damaged the wifi module?

How did you wire the LED strip? If it was in series it would explain a lot, and the WiFi could possibly have received to much current.

I connected the led strip's Power to the arduino's Vin and Ground. It is the led strip here https://www.sparkfun.com/products/12021 .

Let us continue this discussion in chat.

It seems to not be letting me post in the chat :( (it say you must be logged in (which I obviously am))

It's because of your low reputation. Don't worry about it, a mod will probably clean this up later.

I'm running out of ideas. The next thing I'd try is taking a multimeter to the pins and checking each one is making a good connection. Give the boards a gentle shake between tests to see if it's intermittent.

ok, I will try that. so you don't think that connecting the LEDs to Vin for power would harm it?

the multimeter shows that the pins are connected, shaking the boards did not help.

Connecting the LEDs to Vin while powered from the USB is not good.  You are feeding power backwards through the 5V regulator.  You should be running the LEDs from the +5V pin of the Arduino.

I'm afraid I'm out of ideas. I'll take a look at the software and library and see if anything jumps out, but I think you need someone with more experience of the shield.

@Majenko, thanks for the warning, I intended to be using the Vin while powering the arduino and leds from a 7V wall adapter, and meant to (but forgot) switch it to the +5V pin when using usb. Do you think that could have damaged the wifi shield? How much power can the 5V regulator output? Could I leave the LEDs on the 5V pin all the time?

@ForgeMonkey, thanks for your help anyway :) .

@PatrickL It won't have damaged the WiFi shield, no.  The 5V regulator has a limit of 800mA, though the lack of proper heatsinking limits it to around 500mA before it gets too hot.

@Majenko, The 800 (or 500 unheatsinked) mA limit of the regulator is why I used the Vin pin, my power source can provide 7V at 2 Amps, which is enough to power half of the LED strip at full brightness white, or more of it when not full brightness or white. Although I suppose I should use the 5V pin (and limit the number of lit LEDs) when connected to the USB port.

There is another limit, which is the diode that is inline with the barrel jack.  That typically has a 1A limit, as do the physical pin connectors of the headers.  To power more than that you should run your LEDs direct from the 7V supply external to the arduino.

@Majenko Ah, I guess I need to rethink more of the design of this project then. :(

Be sure the shield is not shorting out on the metal USB socket on the Arduino board. I don't know if this is still an issue but I've seen many Arduino boards with black electric tape on the top of the USB socket to insulate it from shorting out the shield.


text:
How to develop or edit an Arduino library?
I'm not sure if I should split this question in two.
I had to edit some libraries and I plan to make some myself but didn't try yet.
Editing a library seems very laborious comared to editing a sketch.
I have to use an external editor and then compile on the Arduino IDE with the help of a test sketch.
I wish to use the Arduino IDE to edit the libraries but it seems it is not easy, maybe in future reales it is supported.
The libraries used to be on %home%/Arduino/libraries/etc. but now I have to edit some located at %appdata%\Arduino15\packages\esp8266\hardware\esp8266\1.6.5-947-g39819f0\libraries and it seems these packages might get updated so maybe it is not a good idea to edit them there but I am not sure.
What about GitHub and conflicts? I clone the library and edit it but then I have two versions and you can't choose one of them. So I have to delete the original from the arduino instalation or wherever it is to avoid the conflict.
I also wish to post the progress to GitHub and maybe receive collaboration there. Do you have any hint about the clone process or something to avoid any trouble with it?
And what about the .h/.o? Arduino precompile the headers on startup so if I edit a .h I have to find and delete the .o or restart the IDE.
How do you do all of this? Is there any trick that helps?
Thank you.

I know this http://playground.arduino.cc/Main/CustomizeArduinoIDE (very raw information, just a specification) and this http://forum.arduino.cc/index.php?topic=37294.0 (old).

I'm not accepting any answer because they are only focused on versioning/git/github fork->edit->share and I am very interested on all the things that I have to do to make the development. Any good editor if Arduino IDE is not an option? Why is not an option? Where should I place the git clone to override any other version of the library? or should I delete them? That kind of things. Thank you.

There is one component of your question that remains unanswered:

I wish to use the Arduino IDE to edit the libraries but it seems it is not easy, maybe in future reales it is supported.
Any good editor if Arduino IDE is not an option? Why is not an option?

The rest of your questions already have good answers so I'll limit myself to explaining how the Arduino IDE 1.6.5-r4 and newer can be used to edit libraries:
Copy the library you want to modify to {sketchbook folder}/libraries or create a new folder at that location if you're writing a library from scratch. You can find the location of {sketchbook folder} at File > Preferences > Sketchbook location.
Create a file that matches the folder name that contains the source files with the .ino extension. For example:
{sketchbook folder}
|_libraries
  |_FooBar
    |_FooBar.ino
    |_FooBar.h
    |_FooBar.cpp

or:
{sketchbook folder}
|_libraries
  |_FooBar
    |_library.properties
    |_src
      |_src.ino
      |_FooBar.h
      |_FooBar.cpp

This dummy .ino file is necessary in order to open the library source files in the Arduino IDE but will not actually be used as part of the library. You can leave it blank. I like to use this file as a "to-do" list for my development work. I add this filename to .git/info/exclude so that it will not be tracked as part of the repository. It's also possible to use this file as a sketch to test the library with. Just remember to use the local file include style:

#include "FooBar.h"

Note that you will only be able to edit the files that are in the same folder as the .ino file via the Arduino IDE. Luckily most Arduino libraries place all their source files in a single folder so this is not much of a limitation. If you wanted to edit a library that has source files in multiple folders you could always put a dummy .ino file in each folder and open them in separate IDE windows.
Add a file named .development to the library root folder. This is necessary because normally the Arduino IDE does not allow saving to the library folders or the examples folder to prevent accidental modification of the example sketches. Using Windows Explorer (and possibly others), you will find that you are not allowed to create files that start with a dot. You can create the .development file using a text editor or the command line. The contents of the file don't matter, only the presence of the file. Note that you should not publish the .development file to repositories that will be included in the Arduino IDE Library Manager as the file will cause the library to be skipped by the job that fetches releases. I also add this filename to .git/info/exclude.
If the library does not already contain one, add a library.properties file to the library root folder. You can find the correct format of this file in the Arduino Library Specification:
https://github.com/arduino/Arduino/wiki/Arduino-IDE-1.5:-Library-specification#libraryproperties-file-format
Now the structure of the example libraries above would look like this:
{sketchbook folder}
|_libraries
  |_FooBar
    |_.development
    |_FooBar.ino
    |_FooBar.h
    |_FooBar.cpp
    |_library.properties

or:
{sketchbook folder}
|_libraries
  |_FooBar
    |_.development
    |_library.properties
    |_src
      |_src.ino
      |_FooBar.h
      |_FooBar.cpp

Restart the Arduino IDE if it's running.
After doing this, when you open any of the source files of the library with the Arduino IDE, all source files in the folder will be opened and you can edit and save them as you would a sketch.

I'm not accepting any answer because they are only focused on versioning/git/github fork->edit->share and I am very interested on all the things that I have to do to make the development.

I will run through the basics of making a library. It's really quite simple, and they persist through upgrades to the IDE.
Let's imagine I have a useful function (or lots of functions) that I want to use in lots of sketches. For example, something that blinks an LED:
void blinkLED (const byte which, const int times)
  {
  for (int i = 0; i < times; i++)
    {
    digitalWrite (which, HIGH);
    delay (500);
    digitalWrite (which, LOW);
    delay (500);
    }  // end of for loop
  } // end of blinkLED

And some test code:
void setup ()
  {
  Serial.begin (115200);
  Serial.println ();
  pinMode (13, OUTPUT);
  blinkLED (13, 5);
  }  // end of setup

void loop ()
  {
  }  // end of loop

Make a library
To turn that into a library we need three steps:

Make a folder for the library. This should be placed inside the libraries folder in your sketchbook folder. This folder:

In my case: /home/nick/sketchbook/libraries. It does not go into anywhere associated with the IDE download.

but now I have to edit some located at %appdata%\Arduino15\packages\esp8266\hardware\esp8266\1.6.5-947-g39819f0\libraries

No, not there.
I will call my library blinkLED. So I make that folder, which is now: /home/nick/sketchbook/libraries/blinkLED

Make a function prototype for any functions your library is going to "expose" to the end-user, and put that into a .h file, like this:
blinkLED.h
#include <Arduino.h>

void blinkLED (const byte which, const int times);

Important: You must include <Arduino.h> as in the example, or you will get compile errors.

Put the C++ code into a .cpp file, like this:
blinkLED.cpp
#include <blinkLED.h>

void blinkLED (const byte which, const int times)
  {
  for (int i = 0; i < times; i++)
    {
    digitalWrite (which, HIGH);
    delay (500);
    digitalWrite (which, LOW);
    delay (500);
    }  // end of for loop
  } // end of blinkLED

Important: You must include the .h file created in step 2, as in the example, or you will get compile errors.

That's it! Restart the IDE now so it notices the new folder with the library in it.
Now our test sketch can just use the new library.
#include <blinkLED.h>

void setup ()
  {
  Serial.begin (115200);
  Serial.println ();
  pinMode (13, OUTPUT);
  blinkLED (13, 5);
  }  // end of setup

void loop ()
  {
  }  // end of loop

Testing
For testing I just keep the library files open in a separate text editor (I am using Geany these days, but whatever your favourite editor is).
You can make changes to the library source and save them. You do not need to restart the IDE if you do this. It will always pick up the latest version.
In the IDE you alter your calling code, upload and test. It is really quite fast and simple.

Git
Once you have put a bit of work into your library you probably want to put it under source control. Using a terminal/command window, navigate to the library folder and put it into a Git repository:
git init
git add *.cpp
git add *.h
git commit -m "Initial commit"

This is the common process for all open source projects, not just arduino (example using github svn)
1. Fork a project
When you fork a project, you create a separate "project" of your own from the original project on the SVN.
2. Clone your project
Clone your fork down to your local directory so you can make changes and use it.
git clone https://github.com/<your-repo>/<project>

3. Push changes up
Push your changes up to your repo regularly. At this point your changes are not affecting the original project in any way.
git push -u origin <branch>

4. Pull updates from the original project
The original author(s) can make changes and improve his/her code. You can make sure your fork is up-to-date by pulling/merging those updates into your fork.
git pull https://github.com/<original-author>/<repo> <branch>

Some time there will be conflicts, which are normal since your changes and the author's may collide. You'll be prompted to fix the conflicts before committing your changes.
<<<<<<< HEAD
    # this portion is your code at the current HEAD
=======
    # this portion is the one from the original branch master
>>>>>>> master

You'll have to fix the conflict manually by either accepting your change and deleting the master's or deleting your change, and get rid of the marks before committing to your svn.
4. Creat a pull request
After using your supercharged version of the project for a while, you think it might be useful for others. To contribute, you create a pull request to the original author. It works similar to you pulling in his changes, just he will review your changes then merge in.
All the while, others can do all these with your project too!
To edit the project/make changes, you can use any editor to open your local project, code away, save it and commit. It is not ideal to use Arduino IDE since it is an environment to run the code (but otherwise possible).

I am going to split my answer into 2 parts
1. Editing an Arduino library:
It doesn't matter how you edit your library, you can do it in notepad for all I care. It just doesn't matter.
2. Version Control:
Git is a version control software used to track software/code changes and ensure that people don't screw up the files by adding code that's not tested.
If you want to contribute to a certain library here is what you need to do
Step 1: create a github.com account since most people host it there
Step 2: fork the required library, this basically creates a clone of the library in your account.
Step 3: clone the forked repo from your account to your computer. So now you have the files on your computer to mess around
Step 4: create a branch a branch is your personal workspace to mess around as you wish. The advantage of have a branch is that if you screw up.  You could always go to the main branch (master) and start over :)
Step 5: once you are done editing and testing and are sure the file is perfect, you commit your changes and then you create **pull request ** with the original author so  that he can review your work and if he is happy will accept your change and merge it to master.
Note: read about adding remote to your git repo and fetching from remote repo, once you understand these basics you will understand the power of git :)


text:
Is there any problem about calling if (Serial) many times?
I am trying to debug a problem that I think may be related to the debug code itself and I tried to use theese macros:
#define DEBUG_PRINT(x) { if (Serial) { Serial.print(x);} }
#define DEBUG_PRINTLN(x) { if (Serial) { Serial.println(x);} }

That works a bit but everything starts running really slow and my sketch get to hung up quite fast. Maybe it is timing related but does not seems like that.
if I change that by this the problem is gone:
#define DEBUG_PRINT(x) { if (true) { Serial.print(x);} }
#define DEBUG_PRINTLN(x) { if (true) { Serial.println(x);} }

I'm using Arduino Pro Micro (Leonardo).
Is there any problem about calling if (Serial) so many times?
Full sketch here

There is no problem, no, but yes it will slow you down.
This is the source code to the boolean operator for the Serial constructor for CDC:
Serial_::operator bool() {
    bool result = false;
    if (_usbLineInfo.lineState > 0)
        result = true;
    delay(10);
    return result;
}

As you can see from that all it does is check the value of a variable.  However it also imposes a 10ms delay¹.  Personally I'd have written it as:
Serial_::operator bool() {
    return (_usbLineInfo.lineState > 0);
}

And on top of that I'd have made it inline.
You might want to experiment by editing CDC.cpp to replace the bool operator with that smaller, leaner, code and see if it improves things (or breaks them completely)².
Edit: I have submitted a pull request to the Arduino GIT repository with a better method of monitoring the line state and imposing the delay(10) when it is actually needed rather than at every call to the bool operator regardless of need.

https://github.com/arduino/Arduino/pull/3624

¹ This is done to allow the port to complete opening at the PC end before data is allowed to be sent.  A better system would only perform the delay() at the moment of port opening rather than every call to the operator.
² Note that this would remove the delay which may be a bad thing as you may lose the first few bytes of the first debug message.  A better system is in the pull request mentioned in the edit to this answer.

However, if the check is false it imposes a 10ms delay. - it always imposes a 10 ms delay.

@NickGammon That's true.  I misread "result = " as "return".  Easily done.

Maybe someone else can come up with a reason for having that delay in there because I sure as hell can't. - I suspect that they expect it to be called once (as per the usual examples of doing it after Serial.begin()) and they found by testing that if it only just became ready you might miss a character or two, so they threw in a delay as well. Or maybe they are trying to not lock up the CPU in a tight loop, in which case an else might have been handy. It's hard to know what they were thinking.

delay() is a tight loop, so that kind of negates your second point.  As for your first I for one am always in the habit (when used in setup) of adding my own delay.  Note that other systems (like chipKIT) don't impose that 10ms delay on you since it really is pointless.

Good point about the delay. :) Yes, it's not like the processor is asleep or anything. It must be my first point then.

There is a comment in the code right before Serial_::operator bool(): “We add a short delay before returning to fix a bug observed by Federico where the port is configured (lineState != 0) but not quite opened.”

@EdgarBonet Then they should be doing it more intelligently - i.e., only impose the delay when the line state transitions from == 0 to > 0 rather than every time the function is called regardless.

@EdgarBonet I have submitted a pull request with a better system for monitoring the line state to the Arduino repository: https://github.com/arduino/Arduino/pull/3624

The real flaw is testing if Serial is available all the time. For one thing, that wouldn't work on a Uno etc. How about something like this?
// make true to debug, false to not
#define DEBUG true

// conditional debugging
#if DEBUG

  #define beginDebug()  do { Serial.begin (115200); while (!Serial) { } } while (0)
  #define Trace(x)      Serial.print   (x)
  #define Trace2(x,y)   Serial.print   (x,y)
  #define Traceln(x)    Serial.println (x)
  #define Traceln2(x,y) Serial.println (x,y)
  #define TraceFunc()   do { Serial.print (F("In function: ")); Serial.println (__PRETTY_FUNCTION__); } while (0)

#else
  #define beginDebug()  ((void) 0)
  #define Trace(x)      ((void) 0)
  #define Trace2(x,y)   ((void) 0)
  #define Traceln(x)    ((void) 0)
  #define Traceln2(x,y) ((void) 0)
  #define TraceFunc()   ((void) 0)
#endif // DEBUG

long counter;
unsigned long start;

void setup() {
  start = micros ();

  beginDebug ();
  Traceln (F("Commenced debugging!"));
  TraceFunc ();  // show current function name

}  // end of setup

void foo ()
  {
  TraceFunc (); // show current function name
  }

void loop()
{

  counter++;
  if (counter == 100000)
  {
    Traceln (F("100000 reached."));
    Trace (F("took "));
    Traceln (micros () - start);
    counter = 0;
    foo ();
  }  // end of if

}  // end of loop

That only does the Serial.begin() once, and the test for waiting for Serial to become available once.
Then, depending on the DEBUG define, the debugging code is executed or not. The fancy ((void) 0) calls get optimized away completely by the compiler if DEBUG is false, thus making them have no effect if debugging is off (which wouldn't apply to your code).

(Edited to add)

As you can deduce from my macros I wanted to debug IF the serial port is connected. I don't want to wait for it to be connected.

Well it wasn't immediately obvious from your code. In that case I suggest you test in the main loop function every second or so, to see if Serial is true. If so, set a flag. Test that flag in your debug function. That way you aren't slowing down every single Serial.print by 10 ms.
Like this amended code:
// make true to debug, false to not
#define DEBUG true

// conditional debugging
#if DEBUG

  #define beginDebug()  do { Serial.begin (115200); } while (0)
  #define Trace(x)      do { if (serialConnected) Serial.print   (x); }     while (0)
  #define Trace2(x,y)   do { if (serialConnected) Serial.print   (x, y); }  while (0)
  #define Traceln(x)    do { if (serialConnected) Serial.println (x); }     while (0)
  #define Traceln2(x,y) do { if (serialConnected) Serial.println (x, y); }  while (0)
  #define TraceFunc()   do { if (serialConnected) { Serial.print (F("In function: ")); Serial.println (__PRETTY_FUNCTION__);} } while (0)

#else
  #define beginDebug()  ((void) 0)
  #define Trace(x)      ((void) 0)
  #define Trace2(x,y)   ((void) 0)
  #define Traceln(x)    ((void) 0)
  #define Traceln2(x,y) ((void) 0)
  #define TraceFunc()   ((void) 0)
#endif // DEBUG

const byte LED = 13;

bool serialConnected;
unsigned long timeSerialLastTested;

long counter;
unsigned long start;

void setup() {
  start = micros ();

  beginDebug ();
  Traceln (F("Commenced debugging!"));
  TraceFunc ();  // show current function name

  pinMode (LED, OUTPUT);
}  // end of setup

void foo ()
  {
  TraceFunc (); // show current function name
  }

void loop()
{

  // every second, see if the Serial port is available
  if (millis () - timeSerialLastTested >= 1000)
    {
    timeSerialLastTested = millis ();
    serialConnected = Serial;
    digitalWrite (LED, !digitalRead (LED));  // blink LED
    }

  counter++;
  if (counter == 100000)
  {
    Traceln (F("100000 reached."));
    Trace (F("took "));
    Traceln (micros () - start);
    counter = 0;
    foo ();
  }  // end of if

}  // end of loop

As you can deduce from my macros I wanted to debug IF the serial port is connected. I don't want to wait for it to be connected.

You might have mentioned that. Intentions aren't always obvious from code. See amended reply above.

That helps on the delay but I think it does not work. Maybe Windows 10 reports the port to be open all the time or something. I'll have to put on a led or something to tell me when Serial reports true.

Honestly, I think trying to see if you are connected is not a particularly good idea. If you want to debug some of the time, have a switch you can press if you want to turn it on.


text:
Calculate burden resistor value of current transformer and measure ac current with arduino
I Want to measure AC current with current transformer but i dont know exact value of burden resistor or calculation formula...i want to measure current of borewell pump. company specified pump as 1.5Hp power.

There is no "You need X resistor for Y transformer". The resistor you choose depends on what current range you are working with and what voltage range you want that to be expressed as.
That transformer is a 100:5 (or more properly a 20:1) ratio.  That means for every 20A going through it you get 1A out.
That output current is then passed through a burden resistor and you measure the voltage across that resistor.
If you are, for example, working with sensing up to 1A current then the maximum current you'd get out of it would be 1/20A, or 50mA.  If you want that to be expressed reliably within the range of a 5V ADC then you would:

Work from the mid-range of the ADC as 0V to give ±2.5V (assuming AC)
Calculate the resistor that gives 2.5V across it when 50mA is passed through it
Pick the next-lowest common resistor value.
Reverse the calculation to get the voltage range you now have.

In this example, R=V/I, so 2.5/0.05 = 50Ω.  50Ω resistors aren't common, but 47Ω ones are, so you'd pick that.
Then reversing it gives V=IR = 0.05 * 47 = ±2.35V
Give it a 2.5V offset to the ADC and you can now read points on a sinewave between 0.15V and 4.85V at 1A sensed current.

Thanks for answer..I want to measure about 5 to 6 amps of current with this transformer. Then what value of resistor is required for this??

Have you tried doing the maths?

What if you want to measure the whole 5 amps. With the 5v from Arduino its giving me 1 ohm. Is there a power rating I need to worry about in the burden resistor?

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


text:
Make 3 servos move like a wave
I am having some trouble programming 3 servos to move like a wave.  So, for instance, all my servos start at 90 degrees. I want my first servo to move and when it reaches 135 degrees I want my second servo to move, with the first, then when it reaches 135 degrees I want my third servo to move, with the first and the second. Then go backwards. Does that make sense?
Here is what I have so far.
#include <Servo.h>

//Create servo object to control a servo
Servo left;
Servo middle;
Servo right;

//Variables to store the servo position
int post = 180;
int post2 = 90;
int back = 90;
int forward = 135;

int firstTriggerAngle = 135;
int secondTriggerAngle = 180;

//Delay
int mid = 4;

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

  //Attaches the servos on the pins of the arduino to the servo object
  left.attach(4);
  middle.attach(3);
  right.attach(2);

  //Starting position
  left.write(back);
  middle.write(back);
  right.write(back);
}

void loop()
{
  for (int i=back; i>=forward; i+=1)
  {
    left.write(i);
    if( i > firstTriggerAngle)
    {
      post = map(i, 90, 135, 135, 90);
      middle.write(post);
    }
    if(post > secondTriggerAngle)
    {
      post2 = map(post, 90, 135, 135, 90);  // depends on the angles you use
      right.write(post2);
    }
    delay(mid);
 }
}

The easiest way is to define how many degrees you want to move totally .
In your case it is 180 steps (from 90 to 180, which is 90 steps, and 180 to 90, which is another 90 steps).
Than use a for loop with a 180 step-counter and make 3 simple formulas to map the 180 possible degrees to the wanted servo position.
So the first formula will look like (step 0..90 -> move from 90 to 180, step 90..180-> move 180 to 0).
int calcServo1(int step)
{
    if (step < 90)
    {
        return 90 + step;
    }
    else
    {
        return 270 - step; // 180 - (step - 90);
    }
}

For the second it should be:

step is 0..45: first iteration: 90, otherwise 135..90
step is 45..135: 90..180
step is 135..180: 180..135

The code will be something like:
int calcServoPos2(int iteration, int step)
{
    if (step < 45)
    {
        if (iteration == 0)
        {
            return 90;
        }
        else
        {
            return 135 - step;
        }
   else if (step < 135)
   {
         return step + 45;
   }
   else
   {
       return step - 45; //  step - 180 + 135
   }
}

Servo 3 I will leave up to you.
From your main loop you call the positions:
 int iteration = 0;

 while (loop)
 {
      for (int step = 0; step < 180; step++)
      {
         int servo1pos = CalcServo1(iteration, step);
         servo1.write(servo1pos);

         int servo2pos = CalcServo2(iteration, step);
         servo2.write(servo2pos);

         int servo3pos = CalcServo2(iteration, step);
         servo3.write(servo3pos);

         delay(mid);
     }
     iteration++;
  }

Ok. So I only want to move between 90 and 180. Then 180 back to 90 continuously till I disconnect the battery. Is what you're saying still valid? Also these separate codes, they need to be inside my for loop, correct? And why is there a ? in between 180 and pos?

you have in total 180 'steps' ... from 90 to 180 (90 steps) and from 180 to 90 (another 90 steps).
You can better call the function FROM your main loop, but not put them inside... I also will remove the ? operator (that might be a bit misleading), but it is not more than a shortened if x { } else { }


text:
Arduino GSM shield code help
Trying to run the below code but getting the following error message:

exit status 1 expected unqualified-id before '==' token

Code is as follows:
==============================================
= Arduino SOS CAll sim900 shield Project =
= with Arduino =
= http://www.mrmodder.com =
==============================================
#include "SIM900.h"
#include <SoftwareSerial.h>
#include "call.h"

#define ACTIVE LOW

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

CallGSM call;
boolean started=false;
int buttonState = 1;
const int buttonPin = 7; // the number of the pushbutton pin
boolean calling = false;

void setup()
{

Serial.begin(9600);
pinMode(ledPin,OUTPUT);
pinMode(buttonPin, INPUT);
digitalWrite(buttonPin,HIGH);
if (gsm.begin(9600))
{
Serial.println("\nstatus=READY");
started=true;
}
else
Serial.println("\nstatus=IDLE");
}

void loop()
{
buttonState = digitalRead(buttonPin);
if (buttonState == ACTIVE) {
if(calling)
{
digitalWrite(ledPin,LOW);
calling = false;
call.HangUp();
delay(1000);
}else
{
calling = true;
digitalWrite(ledPin, HIGH);
delay(1000);
call.Call("+300000000000"); //Insert telephone number here

}

https://mrmodder.com/make-a-call-using-gsm-module-arduino/
Have a GSM shield and trying to call a preset number using the above tutorial but I cant get the code to run properly

This is where the problem is:
==============================================
= Arduino SOS CAll sim900 shield Project =
= with Arduino =
= http://www.mrmodder.com =
==============================================
COMMENT THIS WHOLE TEXT using
/* [insert text here] */


text:
USB Communication like serial RS232 with an Attiny
Basically I want to use an Attiny running an Arduino boot loader as an usb device. I'm not sure how to even start or what phrases to search for.
So here's what I ultimately wish to do.

Load a listener like that of an RS232 serial communication program
trigger pin states based on received commands
plug the Attiny directly into a windows environment USB port for
communication.

I understand that this will require some kind of driver to do this but i don't know what. I do have experience with serial port communication using Visual Studio C# as well.
Assuming what I would like to do is possible, im looking for pointers in how to make the Attiny can be seen by windows.

How far have you got? Do you have the Attiny plugged in and ready to go? Are you able to find and run an example program which, say, prints something to the serial port, and run a terminal on the PC and view the output? That's how I'd start.

Which ATTiny? If you want to add USB, you'll likely drop in an usb-uart chip, like the CH340G or a FTDI chip. But UART may need a more accurate crystal. So you'll be wasting 2pins for the crystal and another 2 for the uart.. Which won't leave a lot for the rest.

You could try using an 32u4 which have built-in USB.

So far I have basically gotten no where. Mostly because I just don't know where to start. using serial im good to go. its the USB idea that has me stuck. Comments so far have given me some insight though.so there's a place to start looking.  What i have are some 84s and 45's that i wanted to use one or the other for this.. I assumed that i could load some kind of usb driver onto the chip to let me communicate with it directly.

How integrated do you want to make it. Do you need a USB driver at all? Could you use an FTDI adapter, treat it as a serial device and send text commands to it? Come up with a simple protocol, similar to AT commands for example?

@MarkSmith I was hoping to utilize USB drivers to have windows recognize it as a device. As st2000 suggested, An Adifruit Trinket as a fake USB Serial might be the answer. Im familiar with windows serial communication so that might just be better than re-inventing the wheel.

You may want to take a look at V-USB, a software-only USB Device library. It is used, among other projects, by USBasp, a very cheap ISP programmer.

Generally there are (or could be many) USB Devices and (only one controlling) USB Host.  The differences are discussed in this stackexchange.com question. Briefly, USB Hosts are usually very complex hardware and software devices that may know about many many different types of peripherals.  They are usually only found on computers.  USB Devices are usually dedicated peripherals.  They only need to know about them selves.  Many people do not realize that there are many protocols built into USB.  These are normally called Device Classes.  The USB Serial Protocol (or CDC) is one of dozens of Device Classes.
So, assuming you want a build a Serial Port USD Device, you would first need a processor with built in USB Device hardware.  (There are likely some project out in the wild that have implemented this feature using software. It might be a good experience.  But for practical purposes it is usually better to use hardware for this.)  The next feature you need to implement is a software USB Device driver.  This is not trivial.  But is much simpler than the USB Host software.  The next feature you need to implement the serial protocol inside the USB protocol.
In the real world, the USB code, even for a USB Device, is complex enough that most developers use the USB code provided by the processor manufacturer.  This is very common as most manufacturers want you to use their hardware and provide the USB code for free. Here is Atmel's support page for CDC USB (serial port) support. (Of course, Atmel makes the processor found in most Arduino boards.)
Thus far this answer has been general and is likely difficult to implement in a practical sense.  A more turn key solution is to use an existing platform which contains a USB CDC Device. The Arduino Uno comes in several versions.  One has a USB CDC chip made by FTDI.  Another has a 2nd processor programmed specifically to handle USB CDC type communications. Either version provides a USB CDC interface used for programming.  I believe this web page explains how you can also use this port to communicate with your sketch.

You didn't say what arduino you are using.  If this link helps, I can add it to the above answer to make it more specific.

sounds like I want some kind of usb device. Based on what you have said what I was hoping to do was turn something like an Attiny84 into a usb device. Then use custom win32 software to tell it to specify analog pin voltages to control MOSFET transistors.
It sounds like i might need a different MCU or to add an additional USB device chip.
Can you recommend any beginner articles on arduino usb device development ? a 32u4 was suggested. Ill do a little looking into that too.

I had a glance at the Trinket link you posted. At a glance it looks like it just may do everything i need it to for my project. Thank you for that suggestion. I am still curious about learning to make a USB Device if you have any suggestions there.

Sorry my turn around was so long.  Busy days.  I'll try and flesh out the answer.  As for USB, on stackexchange.com opinions are usually frowned upon.  Regardless, this is the book I use.

authors: Вячеслав Глушак


text:
Arduino and industrial stepper driver
For a project I need to use an industrial stepper driver with an arduino. There it is: http://www.omc-stepperonline.com/bipolar-stepper-motor-driver-max-4a-current-40vdc-input-16-subdivision-st6600-p-246.html
The motor: https://prototypes.haydonkerk.com/ecatalog/hybrid-linear-actuators/en/linear-actuator-57F42-3.25-099#
I'm not familiar with this driver, so can I use it with the Arduino Stepper Library?
I didn't see a lot of tutorial for this driver compared to many other popular driver.
Thanks!

Absolutely you can. Looking at the picture, this is set up for bipolar and a unipolar motor. There you have to wire according to the wire diagram.

Thanks! But I'm not sure with the configuration of the function ''Stepper(steps, pin1, pin2, pin3, pin4)''. Which pin goes to Pul, Dir and Ena?

I have no idea what do you mean by Pul, Dir and Ena

I have not read deep into it , but It looks like this driver has logic attached to it. IT is really not a good driver to be used with you arduino since  it defeats the purpose to get the experience the programing the logic from the Arduino IDE.  Get a Darlington chip or just create your own with transistors and diodes.


text:
Where are the Special Function Registers located? (Atmega 328)
I'd like to program my Arduino using Assembler. We have to learn this at college.
The problem is that I can find a documentation for the instruction set but I can't find the Special Function Registers.
Something like this would be great or similar to make a sheet like this by myself.

http://playground.arduino.cc/Main/AVR?

Well at least there is "AVR" in the heading. But not more... I know this site and I couldn't find what I search. I have shown an example. Where can I find something like this??

Read the whole thing, I think it might be pertinent. As they say, "Do not judge the book by its cover!".

https://www.arduino.cc/en/Reference/PortManipulation This is what I found (some time ago). But it seems that this is only relevant for the pins. I need "direct" access to the whole atmega not through c functions.

All the registers are given in great detail in the datasheet for the chip.

Chapter 36

Note that C functions already do access the "whole Atmega", you don't need assembly to do that. The only way to do what you want is to read the whole datasheet from the start and ensure you understand it (it may take several reads until you really udnerstand it, this is never an easy read for anyone). From the lack of details in your question, this is the only good advice you'll be able to get.

The Port Registers Arduino tutorial really shows you the most “direct” way to access the SFRs. If you write something like PORTB |= bit(PB5); and disassemble the resulting binary, you will see the compiler translates that statement into a single sbi machine instruction.

There are several options for programming the AVR in assembly, but since
you have an Arduino and the Arduino IDE bundles the gcc toolchain, using
this toolchain is probably the easiest way. Besides, if you learn
assembly in the GNU syntax, you will be able to use it together with C++
and the Arduino libraries.
The gnu compiler will run through the C preprocessor any assembly
program having the .S extension (in uppercase). You would then start
your program with
#include <avr/io.h>

in order to get all the SFR definitions from avr-libc. That include file
is intended to work both in C and in assembly. The SFRs so declared
should be considered as opaque identifiers. To get their addresses, you
should use the macros _SFR_IO_ADDR() or _SFR_MEM_ADDR(). I
personally find those names too cumbersome to type, so I tend to
define my own shortcuts.
Just to get you started, here is a minimal “blinky” program in assembly
for the Arduino Uno (ATmega328P with the LED on PB5):
; Blinky in assembly.

#include <avr/io.h>
#define io(reg) _SFR_IO_ADDR(reg)

.global main
main:
    sbi io(DDRB), PB5  ; PB5 as output
0:  sbi io(PINB), PB5  ; toggle PB5

    ; delay 16 * 65536 * 5 cycles ~ 0.31 s
    ldi  r26, 16
1:  sbiw r24, 1
    sbci r26, 0
    brne 1b

    rjmp 0b ; restart

Where are the Special Function Registers located? (Atmega 328)

Please see Chap. 36 Register Summary, pp. 612, in
http://www.atmel.com/Images/Atmel-8271-8-bit-AVR-Microcontroller-ATmega48A-48PA-88A-88PA-168A-168PA-328-328P_datasheet_Complete.pdf
The registers are available "by name" in the AVR IO header files.
Cheers!


text:
SPI Overflow in 328 slave with i2c sensor
I am working on creating sensor poller that is going to be polling multiple sensors and then, on request, provides its data to the master.
The master polls the slave (SPI) at 50hz and the slave is polling it's sensor (BNO055) (I2C) at 100hz.
The transaction works most of the time but every once in a while it returns an overflow.
Any ideas why this might occur?
Slave code:
/*************************************************************************
 *
 * objeeAirlines
 * __________________
 *
 *  Written by Julian Blanco
 *
 *  Spi slave code written by
    Nick Gammon
    February 2011
 */

#include "Adafruit_BNO055.h"

float yawInput=0;
float yawOffset=0;
float pitchInput=0;
float rollInput=0;

int calibration=0;

volatile byte command = 0;
Adafruit_BNO055 bno = Adafruit_BNO055();

void setup (void)
{

  if(!bno.begin())while(1){};
  bno.setExtCrystalUse(true);
  // have to send on master in, *slave out*
  pinMode(MISO, OUTPUT);
  // turn on SPI in slave mode
  SPCR |= _BV(SPE);
  // turn on interrupts
  SPCR |= _BV(SPIE);
}  // end of setup

// SPI interrupt routine
ISR (SPI_STC_vect)
{
  union first_union{
    float f;
    byte b[4];}
  data;

  byte c = SPDR;

  data.f = yawInput;

  command = c;

  switch (command)
  {
  // no command? then this is the command
  case 0:

    SPDR = 0;
    break;

  // incoming byte, return byte result
  case 'a':

    SPDR = data.b[0];
    break;

  // incoming byte, return byte result
  case 'b':

    SPDR = data.b[1];
    break;

  // incoming byte, return byte result
  case 'c':

    SPDR = data.b[2];
    break;

  // incoming byte, return byte result
  case 'd':

    SPDR = data.b[3];
    break;

  } // end of switch

}  // end of interrupt service routine (ISR) SPI_STC_vect
float tiempo=millis();
void loop (void)
{

  // if SPI not active, clear current command
  if (digitalRead (SS) == HIGH) command = 0;

    if(millis()>(tiempo+10))
    {
      tiempo=millis();
      SampleGyro(bno);
    }

}  // end of loop

void SampleGyro(Adafruit_BNO055 &gyroIMU){
    /* Display the floating  point data */
    imu::Vector<3> euler = gyroIMU.getVector(Adafruit_BNO055::VECTOR_EULER);
    yawInput=euler.x()-yawOffset;

    if (yawInput >= 360)
    {
          yawInput -= 360;
        }
    else
    {if (yawInput < 0)yawInput += 360;
    }
    pitchInput=euler.y();
    //rollInput=fmod((euler.z()+(360+90)), 360)-180;
    rollInput=euler.z();
    uint8_t system, gyro, accel, mag = 0;
    gyroIMU.getCalibration(&system, &gyro, &accel, &mag);
    calibration=system;
}

Master Code:
#include <SPI.h>

#define SS 10
void setup (void)
{
    pinMode(MOSI, OUTPUT);
    pinMode(MISO, INPUT);
    pinMode(SCK, OUTPUT);
    pinMode(SS, OUTPUT);

  Serial.begin (115200);
  Serial.println ();

  digitalWrite(SS, HIGH);

  SPI.begin ();

  SPI.setClockDivider(SPI_CLOCK_DIV8);
}

  byte transferAndWait (const byte what)
{
  byte a = SPI.transfer (what);
  delayMicroseconds (10);
  return a;
}

  union first_union{
    float f;
    byte b[4];}
  data;

void loop (void)
{

  digitalWrite(SS, LOW);

  transferAndWait ('a');

  data.b[0] = transferAndWait ('b');
  data.b[1] = transferAndWait ('c');
  data.b[2] = transferAndWait ('d');
  data.b[3] = transferAndWait (0);

  digitalWrite(SS, HIGH);

  Serial.print("data.f = ");Serial.println(data.f);

  //Serial.print("data.b[0] = ");Serial.println(data.b[0]);
  //Serial.print("data.b[1] = ");Serial.println(data.b[1]);
  //Serial.print("data.b[2] = ");Serial.println(data.b[2]);
  //Serial.print("data.b[3] = ");Serial.println(data.b[3]);

  delay(10);
}

Try reducing the SPI clock and/or increasing the micro seconds delay in transferAndWait (10 us is not very much).

Thanks for responding, but no dice, halved the speed of the spi bus and doubled the delay, same results, 97%ish success with the occasional ovf

Why "float tiempo"? Why not "unsigned long"?

Good catch, fixed

Might need to mention that the Arduino millis() ISR/Timer is not accurate. It is a bit slow and will actually to a double increment from time to time.

It is likely that your SPI interrupt on the slave is firing in the middle of updating your global yawInput variable. This would cause the value to be partially updated when you send it back to the master. You might even be sending part of the old value and part of the new value back to the master. It depends on when the interrupts fire.
You need to lock your SampleGyro function somehow. The easiest way would be to disable interrupts when modifying any interrupt accessible variables (i.e. yawInput).
Something like this should tell you if the interrupt timing is the issue:
void SampleGyro(Adafruit_BNO055 &gyroIMU){
    /* Display the floating  point data */
    imu::Vector<3> euler = gyroIMU.getVector(Adafruit_BNO055::VECTOR_EULER);
    uint8_t system, gyro, accel, mag = 0;
    gyroIMU.getCalibration(&system, &gyro, &accel, &mag);

    // Disable interrupts while modifying the global variable
    noInterrupts()
    yawInput=euler.x()-yawOffset;
    if (yawInput >= 360) {
          yawInput -= 360;
    } else if (yawInput < 0) {
          yawInput += 360;
    }
    pitchInput=euler.y();
    //rollInput=fmod((euler.z()+(360+90)), 360)-180;
    rollInput=euler.z();
    calibration=system;
    // re-enable interrupts once your global variable
    // modification is done.
    interrupts();
}

It's also worth noting that you want to put as little code between the noInterrupts() and interrupts() calls as possible. Things like I2C and SPI and basically any other communication will likely not work inside of that block. I rearranged your SampleGyro function to put all calls to the gyro outside of the lock. This is to prevent the sensor reading from failing.

Getting closer but no dice, see photo


text:
Is new without a delete acceptable?
I know it is not a good practice to use the new command to dynamically create data, however, if I would never use the delete, would it result in memory gaps/other problems?
Background
The reason I need to create instances dynamically, is that I want to test my application first on a PC. And I want for several classes to have more properties for the PC version than for the Arduino version (for example, to store names, or information for the PC GUI to display). The PC version classes will be inherited from the Arduino (real) classes, but with added properties.
In some classes I need to build up a list, and I cannot use a type with hardcoded values to fill an array.
Example:
I have a LightSetup class that has a list of Pars (which are LED lights):
class LightSetup
{
protected:
    Par* _pars[NR_OF_PARS];

Par is the Arduino/real version, to fill in these I need:
LightSetup::LightSetup()
{
    for (int n = 0; n < NR_OF_PARS; n++)
    {
        _pars[n] = new Par(1 + 8 * n);
    }
}

In the PC version, instead of new Par, I use new TestPar.
And in the header I cannot define it without a pointer like this:
    Par _pars[NR_OF_PARS];

Otherwise it cannot contain TestPar instances.

You could avoid the new-delete-heap-issue by using a template class. Here is an example: https://github.com/mikaelpatel/Cosa/blob/master/cores/cosa/Cosa/IOBuffer.hh#L29

@MikaelPatel Thanks for this comment, it also sounds like a good idea ... forgot about templates (having used it 20 years ago for the last time ;-) ).

Another example is this GPIO template class that compile digitalRead/Write to a single instruction: https://github.com/mikaelpatel/Arduino-GPIO/blob/master/src/Hardware/AVR/GPIO.h

I have to say, when I first read the title I was pretty set on the answer being "It is never acceptable" but you have given me an interesting scenario to think about.  It's an unusual case but valid.

@MikaelPatel Thanks ... I need to check into this better, looks very useful.

@KellyS.French Actually I came to the idea, because in of my professional projects we instantiated all objects beforehand, not for delete/memory gap problems, but because of performance (no creation of new objects during the  critical execution parts).

Here is another example: Java allows you to pre-allocate a block of memory (starting heap size?) at load-time for exactly the same reason, to cut down on memory allocation during execution. This would actually make for a good general StackOverflow question for the general case and I'd encourage you to post about it.

@KellyS.French Thanks for that, although I cannot use Java for Arduino (at least not in the Arduino IDE).

Sure. Using new or malloc to set things up initially is really no different to static allocations. There is nothing inherently bad with using malloc or new, only in using it repeatedly with free or delete.
Allocating a block of heap memory and keeping it allocated for the rest of eternity does not cause heap fragmentation. It's only repeated allocation and deallocation of variable sizes (such as String causes) that start to create problems. Allocating at the start of your program and leaving it allocated, as long as you don't allocate too much, of course, is not a problem.

Thanks for the confirmation.  The only disadvantage I can see is that the used memory is not calculated to the global variables in the Arduino IDE.

Yup. Hence the nudge to watch out that you don't allocate too much :)

Maybe I will for debugging purposes show the amount of reserved memory after the new statements.

In the destructor you would need
LightSetup::~LightSetup()
{
    for (int n = 0; n < NR_OF_PARS; n++)
    {
        delete _pars[n];
    }
}

and every time you replace a _pars you need to delete the old one. This can be done automatically by using unique_ptr.
However for your purpose it sounds like a #if is better suited to differentiate at compile time which type you actually store inside that array.
#if ON_ARDUINO
    Par _pars[NR_OF_PARS];
#else
    TestPar _pars[NR_OF_PARS];
#endif

Well, the destructor will never be called, since in my Arduino application the loop will run forever, so it's not an issue. But I upvoted it for the last part, maybe that's even better than the new command (although it clutters up code a bit). However, if this is the only change, it is easier. Thanks

I agree with @ratchet on the #if as the case you describe isn't about dynamic typing but rather a difference in platforms. Unless you need the same binary to run on both platforms (if even possible) you would be better served by conditional compilation. This also removes the need to bother with a destructor.


text:
avrdude: stk500_getsync(): not in sync: resp=0xyy ... where to find the response values?
Last week I retried some of my Arduinos and one Mega was working without a problem, but two Uno's didn't work anymore. The error I got was something like:
avrdude: stk500_getsync(): not in sync: resp=0xyy

Where yy where all different kind of values (I cannot copy/paste it as I'm not near the Arduino's).
Does anybody know where to find a document what the response values mean?

They don't mean anything.
AVRDude sends a packet, and expects a certain response. When it gets something that it's not expecting it tells you it's "out of sync", and tells you what the actual response was it got. That is, what byte it received over the serial port.  That could be something that your sketch is sending, or complete garbage if you're communicating with a floating serial input, or anything at all.

Thanks, no wonder I couldn't found an 'error table'  ... I would hope it would mean something more useful ... in that case I try it on another computer and otherwise I have some dead Uno's.

Are they real ones? Or the dreaded CH340G?

One is a real one (even with a removable DIP Atmel) and the other is a CH340G.

Step one of diagnosis is to try a loopback test. Hold the board in RESET, and connect pin 0 to pin 1. Try and communicate and see if what you send is echoed back.

Good advice thanks ... I will try it (probably in weekend, not much home until that time).


text:
Two devices on one UART/Serial
I'm using an Arduino Mega which has 4 RX/TX UARTS/serials.
3 RX's of them I use for MIDI In
2 TX's of them I use for MIDI Out (maybe later a DMX out too)
One I use currently for debugging. On the other hand, in the future I want:

Using an ESP8266 WIFI which also seems to use an UART (both RX/TX)

Of course I can remove the debugging RX/TX, but maybe some more additions are needed and for the first RX/TX I need to remove the RX each time I upload (so I rather leave it for debugging).
I was wondering, is it possible to share an UART if I don't use the WIFI module and MIDI port at the same time?

It's certainly possible to multiplex a UART port, yes, though you will need extra hardware to do it. You will need:

A multiplexer to select between the two RX lines and feed the right one to the Arduino's RX pin
A demultiplexer to select which of the devices to send the Arduino's TX pin to.

"Analog" (de)multiplexers (e.g., CD4052) may be the simplest option since they can work in both directions. Another alternative would be combinations of tri-state buffers and glue logic to control them.

You could simply send the TX to both devices. If one is always going to be missing it doesn't matter what the data line to it is doing. Rx it depends whether these are TTL level signals or not. If they are TTL straight from the devices and one one device is ever fitted you can wire them together. As soon as you have a level shiftier or buffer on the signal then you need a Mux.

If there is only one physical device connected at a time then yes you can just wire direct.

I don't know if e.g. a WIFI ESP8226 is considered as physically connected (I guess it is) ... the MIDI cable is not, but I rather don't want to be rely on a user having to remove the cable (also the MIDI in is transferred through an opto coupler which is physically connected to an RX pin).
However, it's ok to know there is a solution (for now). I just don't want to think further into a direction that is absolutely impossible from the start.
(background: now I use or plan to use an SD card to move from a PC from the Arduino every time, but later a WIFI module is more convenient).

If your application can tolerate the limitations of SoftwareSerial, it's the easiest way to add a port. The terminal may be the better candidate for it.

SoftwareSerial is the absolute worst alternative.  It disables interrupts for an entire character time (1ms @ 9600) when transmitting OR receiving (it can't do both at the same time, either).  If the baud rates don't match, this would cause all the other UARTS to lose characters.  If he must use a software serial port (not that I suggest that), use AltSoftSerial instead!

The original SoftwareSerial hasn't been in the core library for quite some time. Since v1.0, SoftwareSerial has been replaced by http://arduiniana.org/libraries/newsoftserial/ which addresses some, if not all, of those shortcomings. The different software implementations come with their ownabilities and limitations (AltSS is tied to fixed pins, f/ex). And do note that I alluded to the limitations of software implementations.

Nope.  Those are the current problems.  Look at the SoftwareSerial::recv method, which is called from the ISR: it has a for loop.  The ::write method is very similar.  :(

I am not a favorite for using SoftwareSerial, only for debugging it might be 'acceptable', but in that case I probably rather try to wire another Arduino only for that purpose.

Consider running the RX and TX of the first UART to the common terminals of an On-Off-On DPDT switch or relay.  Calling the On positions A and B, connect the A terminals to RX and TX of one device, and the B terminals to RX and TX of another device.  Use position A for the first device,  position B for the second device, and the Off position for program loading.
It isn't clear to me whether your debugging is via USB serial or via a separate device. In the former case, a DPST switch would be adequate.  Also, two SPDT's could be used in place of a DPDT if you wish to switch RX and TX separately, or four SPST switches can be used if you have nothing better.
This is premised on the idea that during development you need to be able to send/receive debugging IO.  I don't know how to interpret your
“don't want to be rely on a user having to remove the cable”  phrase, but suppose a user-cabled setup won't need debug-channel switching.

This should be possible (at least for two of the UARTs, since I need the other exclusively and simultaneously). I am debugging it now via the USB serial (but afaik, I have to keep that RX/TX free, at least while downloading, maybe nothing to do with debugging). And the SPDT/DPDT could be used for two UART 'inputs'.  And I mean with user in this case myself (as the debugger). Sorry for being unclear,


text:
Resistors/capacitor used in connecting 23LC1024 SRAM 1 Mbit
Yesterday I received by 23LC1024 SRAM with 1 Mbit memory.
I tried to search for some libraries and ways how to connect it.
So I searched around on internet first for the connections and saw some different ways of doing it, especially regarding the pullup resistors.
E.g. in Example1 two resistors are mentioned for pin 3 and 7.
In Example 2 only one resistor is used.
In YouTube example 3 three resistors and a capacitor is used. See around 5:25.
My questions:

Is one of those three better (and why)?
Is the capacitor in the youtube example 3 connected to GND or 5v? I cannot map the schema with the breadboard since the capacitor should run between +5 and GND but I don't see the +5 or GND connection (depending on where the capacitor is connected to which I cannot see or deduce).

Btw, I got it working with the 2 resistor solution but just wondering if example 1 is good enough or example 3 is better.

It's better to use external pull-up resistor at least on CS. It's because MCU pins are configured as INPUTs without pull-ups just after the startup/restart before it gets into the setup().
Also I'd recommend decoupling capacitor as close as possible to the SRAM power supply pins (between Vcc and Gnd). You can google what the decoupling capacitors are (they are also called bypass capacitors).
Edit: First two examples are supposed to be on bread board. So it's not so hard just rewire it, if you have to use for example /HOLD too. However the third example is soldered on prototype board and therfore it's not so easy to rewire it. That's why NU and /HOLD inputs are connected to the Vcc through 10k resistor. If you have to use /HOLD in the future, it's easier to just solder new connection, than rewire hardwired connection to the Vcc.
About decoupling caps - there are even sockets with builtin cap:

thank you very much ... some more reading to do, thanks for the right naming/functionality of the capacitors. In the example of the youtube video (3th example) at 5:25, pins 1 and 3 (and 7) have a resistor and the capacitor is going from those resistors to either GND or +5v (I cannot see) but in the schematics the pins 1, 3, 7 and 8 all goes to the capacitor from +5 to GND so I do not see how the schematics and the breadboard map? Can you explain this?

@MichelKeijzers Updated. Btw, it's even more difficult if you have custom board :D

Thank you again KIIV .. for the coming months I will stay away from prototype boards probably ... so I will use the breadboard solution I have now, but add the capacitor on the breadboard as in example 3. Still not sure exactly how to place the capacitor in my case, however, I will first read and maybe it gets clear automatically.

@MichelKeijzers Like this: http://i.imgur.com/vRvhIhy.png (it's pretty much the same for 8pins chips)

Thanks ... so in my case in http://www.bing.com/images/search?view=detailV2&ccid=%2f7BbflDG&id=B3D333677F7B9C059EC35C0294DFAEA2F33F7015&q=23lc1024&simid=607995735057761174&selectedIndex=11&ajaxhist=0 I have to put e.g. a 0.1nF between pins 4 and 8?

Ah That is really clear (the pic you added). I guess always (or mostly) pins 4 and 8 are +5V and GND (or at least the two opposite pins) ... I just have a few ICs yet, so I haven't noticed it.


text:
What options do I have to get 5v on my current project?
I'm very new to arduino and have started work on my first project, a simple little web server. I'm using a NodeMCU with an sd card module and screen. The issue is that in order to power my sd card module, I need to input 5V which the MCU doesn't provide.
In order to work around this I'm simply using an arduino nano as a power supply to pass into the vin input on the mcu.
What options do I have to exclude the need for the nano? Is there a simple module I can buy that acts as a power supply for 5v?
Any help would be great, thanks!

what's your existing power source?

SD cards usually use around 3.3V. Get a module that doesn't need 5V.

SD cards require 3.3V. Usually, to connect them to an Arduino running at 5V you need to get a level converter. However in your case it sounds like you are making work for yourself:
3.3V <--> 5V <--> 3.3V

in order to power my sd card module, I need to input 5V

Which SD card module? Maybe you don't need a "module".

To supplement; if you don’t have a level converter on hand, have a look at this diagram:
http://homediyelectronics.com/projects/arduino/seriallevelconverter/
Just test it on a breadboard, and if Vcc, Rx and Tx are within 10% of 3.3V, solder it to a bit of perfboard. Haven’t needed to build one myself, since these come in tiny SMD packages which cost almost nothing:
https://rover.ebay.com/rover/0/0/0?mpre=https%3A%2F%2Fwww.ebay.com%2Fulk%2Fitm%2F202151474158
... Are you sure your SD module isn’t 5V tolerant? All mine step down 5V to ~3.3V.


text:
Connection between ATTiny85 and RaspberryPi3 with nRF24L01+
I'm hoping someone can help me since I've been struggling with this all weekend. I've got 2 nRF24L01+ breakout cards and I'm trying to send data from a ATTiny85 to a Raspberry Pi 3.
My setup is (the attiny85 breadboard has a 3.3V power supply):

And the code I'm testing is for the ATTiny85:
#define CE_PIN 3
#define CSN_PIN 4

#include "RF24.h"

RF24 radio(CE_PIN, CSN_PIN);

const byte addr[6] = "00001";
int count = 0;

void setup() {
  radio.begin();
  radio.openWritingPipe(addr);
  radio.setPALevel(RF24_PA_MIN);
  radio.stopListening();
}

void loop(void){
  radio.write( &count, sizeof(count) );
  count++;
  delay(1000);
}

And for the Raspberry Pi 3:
#include <cstdlib>
#include <iostream>
#include <sstream>
#include <string>
#include <unistd.h>
#include <RF24/RF24.h>

using namespace std;

// Setup for GPIO 22 CE and CE0 CSN with SPI Speed @ 8Mhz
RF24 radio(RPI_V2_GPIO_P1_22, RPI_V2_GPIO_P1_24, BCM2835_SPI_SPEED_8MHZ);

// Radio pipe addresses for the 2 nodes to communicate.
const uint8_t addr[6] = "00001";

int main(int argc, char** argv){
  radio.begin();
  radio.setPALevel(RF24_PA_MIN);
  radio.openReadingPipe(1, addr);
  radio.startListening();

  // Dump the configuration of the rf unit for debugging
  radio.printDetails();

  int count = 0;

  while (1)
  {
    while ( radio.available() )
    {
      radio.read( &count, sizeof(count) );
      printf("Count: %d\n", count);
    }
    sleep(1);
  }

  return 0;
}

Double check MISO/MOSI on ATtiny. They are DO and DI not MISO and MOSI (which are used when programming).

Double check what about them? As far as I understand,  the RF24 library supports the attiny's USI for SPI

You might have got the wiring wrong; NRF24/MISO => ATtiny85/DI (Pin 5), MOSI => DO (Pin 6).

@MikaelPatel thanks! That looks like it could be the problem. I have been going off the chip pinout from the datasheet (MOSI pin 5, MISO to pin 6). However, I see now that http://tmrh20.github.io/RF24/ATTiny.html has them listed the other way around, like you say.
I'll test when I get home tonight.

Yes, USI uses DO(utput) and DI(nput). The MISO/MOSI are for programming only.

As Mikael Patel pointed out, my MOSI and MISO pins were switched.
On the pinout for the ATtiny85, the MOSI and MISO pins are for when the chip is a slave (i.e. programming). DO and DI and used for output as SPI master.


text:
two dimensional array with 3 characters per entry?
my plan is to create a two dimensional array with 3 characters in each cell.
what i have tried:
char keys[3][8][8] = {
  {' ','4','5','6','x','/',' ',' '},
  {'x10','7','8','9',' ',' ',' ',' '},
  {'.','rcl','eng','(',')','sd','m+','^2'},
  {'0','(-)','..,,','hyp','sin','cos','tan','hyp'},
  {' ','br','wur','^2','^x','log','ln',' '},
  {' ',' ',' ',' ',' ','mode','log',' '},
  {'=',' ',' ',' ',' ',' ','^3',' '},
  {'=','1','2','3','+','-',' ',' '}
};

unfortunatelly this gives me the error:

error: too many initializers for 'char [3][8][8]'

so what is wrong?

error: too many initializers for 'char [3][8][8]'

The order is wrong:
char keys[8][8][3]

But then some of the literals are larger than int and give a warning as they are truncated.
Easiest is to define as string literals:
const char* keys[8][8] = {
  {" ","4","5","6","x","/"," "," "},
  {"x10","7","8","9"," "," "," "," "},
  {".","rcl","eng","(",")","sd","m+","^2"},
  {"0","(-)","..,,","hyp","sin","cos","tan","hyp"},
  {" ","br","wur","^2","^x","log","ln"," "},
  {" "," "," "," "," ","mode","log"," "},
  {"="," "," "," "," "," ","^3"," "},
  {"=","1","2","3","+","-"," "," "}
};

This can be further improved (stored in program memory, etc).
Cheers!


text:
Serial Communication Issue with Telit LE910 LTE Modem
I have a project that uses a Telit LE910 4G LTE Modem to allow me some basic monitoring via SMS and HTTP POST to Exosite.
I can connect to a Exosite server with and send a successful HTTP GET request to pull a UNIX timestamp (as a test).
Problem
The problem lies with receiving.  The information received cuts off halfway through the HTTP headers, before reaching the body of the information.
This image shows what prints out on the Serial monitor:

This image shows what the expected result should be:

And this image shows the code the executes to send the request:

The result is the same with PrintModemResponse() and with GetModemResponse().  Additionally, I have the same issue with receiving SMS messages.  The data appears to cut off partway through the expected response.  The modem serial (SW_Serial) baud rate is set to 115200.
Question
Am I doing something wrong with reading the Serial information from the modem?  Am I hitting a timeout of some sort?

First, please don't post screen images.  Just select the text and paste it into your questions.  You can copy code from the editor or messages from the Serial Monitor window.  Paste into your post, select the section again, and press ctrl-K to format it as a code block in your question (like below).

Am I doing something wrong with reading the Serial information from the modem?

Yes, you are using delay to "wait" for the response to appear.

Am I hitting a timeout of some sort?

In a way.  The input buffer only has room for 64 characters.  If you don't read any of them because you're blocked at a delay statement, the 65th character (and all others) will be ignored.  These answer your specific questions.

Further Suggestions:
To fix the real problem, not just the symptoms, you will have to change your sketch structure.
There are many ways to implement this in a non-blocking way (i.e., without using delay).  I prefer Finite-state Machines; there are many good tutorials for this  technique (e.g., Nick Gammon's site).
Although it's not as flexible, you could also use your own while loop for each response, with a timeout.  Here's a simple example that reads one line.
char resp[20];
char resp_Len = 0;
const uint32_t TIMEOUT_MS = 5000UL; // 5 seconds

AltSoftSerial modem_port; // pins 8 & 9 ONLY

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

void loop()
{
  uint32_t startTime = millis();
  while (millis() - startTime < TIMEOUT_MS) {
    if (modem_port.available()) {
      char c = modem_port.read();
      if (c == '\n') {
        resp[ respLen ] = '\0'; // NUL terminate
        respLen = 0; // reset for another line
        break;

      } else if (respLen < sizeof(resp)-1) { // Room for more?
        resp[ respLen++ ] = c; // accumulate one more character
      }
    }
  }

  Serial.print( F("Response = '") ); // F macro saves RAM
  Serial.print( resp );
  Serial.println( '\'' );
}

But when the response is long (hundreds of bytes), you may not have sufficient RAM to save the whole response, and then parse it.  You MUST use an FSM to parse the bytes as they are received.
For your application, you should skip all the stuff at the front and watch for the "Content-type:" pattern and the two newlines, then save the next line (as above) for parsing:
enum state_t { SKIP_TO_CONTENT_TYPE, SKIP_TO_EMPTY_LINE, SAVING_TIMESTAMP };
state_t state = SKIPPING
uint8_t index = 0;

const char ContentType[] = "Content_type:";

bool watchForTimestamp()
{
  if (modem_port.available()) {
    char c = modem_port.read();

    // Handle this one character, based on our current "state"

    switch (state) {
      case SKIP_TO_CONTENT_TYPE:
        if (c == '\n')
          index = 0;

        else if ((index < sizeof(ContentType) && (c == ContentType[ index ])) {
          // next char matches
          index++;

          if (index == sizeof(ContentType)) {
            // All matched!
            state = SKIP_TO_EMPTY_LINE;
            index = 0;
          }
        }
        break;

      case SKIP_TO_EMPTY_LINE:
        if (c == '\n') {
          index++; // this counts newlines since "Content-type:"

          if (index == 2) {
            state = SAVING_TIMESTAMP;
            index = 0;
          }
        }
        break;

      case SAVING_TIMESTAMP:
            ... Hint: something like the line-saving technique above.
        if (something) {
          return true;
        }
        break;
    }
  }

  return false;
}

Some part of loop will just call waitForTimestamp over and over:
void loop()
{
    ...

  bool gotResponse = false;
  state = SKIP_TO_CONTENT_TYPE;

  while (millis() - startTime < TIMESTAMP_TIMEOUT) {
    gotResponse = waitForTimeStamp();
    if (gotResponse) {
      // parse the timestamp from the resp array
         ...
      break;
    }
  }

  if (gotResponse) {
    Serial.print( F("Timestamp = ") );
    Serial.print( resp );
    // now you can parse the small response array
       ...

  } else {
    Serial.println( F("Didn't receive timestamp!") );
     ... other error code
  }
}

This may be a "main" FSM for loop, with a nested FSM for parsing the HTTP response.  The rest is up to you.  :)
BTW, SoftwareSerial is very inefficient.  It cannot send and receive at the same time, and it disables interrupts for long periods of time.
If you can use pins 8 & 9, you should use AltSoftSerial instead.  It is very efficient.
If you can't switch to those pins, you could use NeoSWSerial if the modem is running at 9600, 19200 or 38400.

Thank you for your response.  I will do some research into FSM and your suggestions and attempt to incorporate them.  I guess the trick will be in the loop, catching the response before it fills the buffer.
Just for clarification, I am using a hardware UART for the modem (defined as SW_Serial, SW for Skywire) at 115200 baud.  Thank you for the suggestion of AltSoftSerial though, may come in handy for other projects.

At the modem's default baud rate of 115200, I found I needed to check SW_Serial for data so frequently that it was basically blocking code in and of itself.  I found two alternatives:  The first is to implement flow control, which I have not done but may look into should the need arise.  The second was easier for me, and it was to just modify the HardwareSerial.h header file and up the buffer to 256 bytes.  This should be more than enough for my purposes.


text:
difference between output pin high and 5v pin
So this might be a total noob question (which admittedly I am) I have a Motor, if I connect it to GND and the 5V output it runs. Ok so far. But if I connect it to GND and a pin set to OUTPUT and HIGH nothing happens. My multimeter reads 5V for both setups, so if 5V come to the motor one way or the other why does one work and one not?

That's probably caused by the motor's current consumption. The 5V pin can deliver much more current than the output pin in high state. If you want to switch the motor on/off by software, you need a "hardware driver" for the motor, in the simplest case a power transistor.

So you mean it is an Amper difference between the pins do you know what the limit for the output pins are

40mA per IO pin.

Be careful! You should't connect anything to the arduino pins, because you will burn them! It's better to use a transistor as @rolf said. Also add a resistance between the pin and the base of the transistor.

That is what I always suspected. Transistors are not anything.


text:
can i unplug my Arduino project when i'm done installing the libraries and it still work the way it did when it is plugged in
can i unplug my Arduino project when i'm done installing the libraries and it still work the way it did when it is plugged in

Unplug it from what? Your question is a bit vague. Do you mean unplug the USB cable from your PC? It won't "still work" unless you plug in a different power source.

like what type of of power source can use. i apologize for not being clear enough but i am new at this and don't even know where to start. i don't even have my equipment yet.  but thank you for being able to answer my question.

As st2000 said, the program resides in program memory (firmware if you like) and stays there until replaced, even with the power off. Whether it works "the same way" depends a bit on other factors (eg. do you use the USB for sending messages?) but in principle it should still work.

Once you compile and upload your arduino sketch and any libraries it uses, your code is stored in nonvolatile memory inside the processor. You can unplug your arduino and power it up later and it will run your code again with out any help from your computer.


text:
Arduino Uno VIN 2A
Trying to get started with the Arduino, so I'm trying to do something kinda simple. I'm following this tutorial: Build Your Own Dynamic Ambient Lighting For A Media Center
However, I'm still confused about one, most likely simple and self-explainatory, thing:
Take a look at this image - is that DC connector on the bottom left the one that's one my Arduino? Do I simply have to connect the 12V wire from the RGB LED stripe to Vin?
After using google for a bit, I read this: the diode and trace width are other limiting factors. The diode is rated at 1 amp and the board traces can't handle much above 2 amp.
Does that mean I can only use 1A because of the diode? If so, why does it matter how much the board traces can handle?
I'm trying to power a 12V 2A RGB LED stripe.
I'd appreciate your help and I hope this is the correct subreddit to ask that. :S

No, that connector is a completely separate one.
You can connect a power supply to the on-board power socket of the Arduino and take power out from the VIN pin to power other things.  However the total current that is used by both the Arduino and whatever you power from it cannot exceed 1A.
So to have more than 1A available you have to have the power connected externally to the Arduino. That doesn't mean that the Arduino can't share that power, just that the Arduino can't provide that power.
You can connect the +12V of the LED strip to VIN on the Arduino as long as the 12V power supply is connected to the LED strip not to the Arduino - that way the power for the Arduino comes from your external circuit.

It will be dangerous to take 12V from VIN pin. Please have a look at following picture. That is the diode you mentioned. the diode can burn out if the current get exceeded.

there are three ways to solve this.

Use two different supplies. Use a 6V battery(or 5V USB power) to power arduino and 12v supply for LED strip. You should connect both grounds( grounds of supplies)

Solder a wire from bottom(from the point shown in picture) of arduino board for 12v
connect 12v power directly to VIN (not by using power jack)


text:
Arduino which library for led 4x20
I am having an Arduino Uno and I want to add a LCD to it. My LCD is a C2042A with I2C shield on it. I tried the LiquidCrystal_I2C library but it doesnt work. I am not getting any errors the LCD is just not showing the text. I just used the example code 'Hello World' from the library. I only changed the adress from 0x27 to 0x63 because I found that with the I2C scanner.
So all in all the LCD is connected right. It shows I2C mode which is also fine and it is find by the I2C Scanner code. Which library do I have to use that it will work? http://www.wentztech.com/filevault/Electronics/Arduino/

Do you see white squares on the first line, but not the second? If not, you have to adjust the contrast with the potentiometer.

No when you turn the LED on it shows the standart text: LCD03 REVISION9 (next line) I2CMODE @ 0xC6

0x63 is the correct address - the module is at 0xC6 which is the 8-bit equivalent of 0x63 (0x63 shifted left once for the read/write bit to be added).
The LCD03 uses its own custom I2C protocol, not compatible with the "normal" I2C LCD library. Instead you have to use their own special commands.
The commands are detailed here: http://www.robot-electronics.co.uk/htm/Lcd03tech.htm
There may be a library available that wraps those commands, I don't know, but you can just use the Wire library to send the commands you need to send.

ok that looks complicated can you write an example code how to for example turn the blacklight off with the wire library?


text:
Arduino round to nearest 0.5
I am having a double value for example: 34.26 or 11.92 or 2.51. It should be rounded to the nearest 0.5 so 1.34 -> 1.50 and 32.78 -> 33 and 21.09 -> 21.00
How do to do this?

I'd suggest not even using floats. 0.5 = 50, 1.34 = 134, 32.78=3278, should make the calculations faster/more efficient.

Also, let's say you have 134, you can do 134%50, which will return 34 and then you can check if it's above 24 (under = round to 0) and above 74 (under is round to 50) and else you round to 100.

It is a very bad idea to use float.
That being said. multiply by 2 and do a standard round.
Then divide back by 2.
For example:
1.34     *2 = 2.68
round(2.68) = 3
3        /2 = 1.5

and
32.78    *2 = 65.56
round(65.56)= 66
66       /2 = 33

The multiply by 2 is actually very clever I already felt like such a simple way should exist.

Commonly used for nearest 0.10 and 0.05 in cash registers, too (using 10, 20).

I made a little algorithm from the first thing that popped into my mind.
I'm using integers, since I believe it works better as floats.
For example, you can represent euro's (with floating points) by expressing them in cents.
unsigned int roundToFifty(unsigned int nonRound){
    unsigned int rest = nonRound % 50;
    unsigned int fits = floor(nonRound / 50);
    unsigned int add = 0;
    if(rest >= 25){
        if(rest >= 75){
            add = 100
        }else{
            add = 50
        }
    }
    return fits*50+add
}

I actually think the algorithm is a tad weird and something simpler/more effective could also exist. It was just the first thing that popped into my mind.

float i=1.5237475984328953;
#include "math.h"
void setup()
{
 Serial.begin(9600);
}

void loop() {
 Serial.println(i,6);
 float price = i*1000;
 Serial.println(price,2);

 float roundNearest = roundf(i*1000) ; // x 100 for two decimal place
  roundNearest = roundNearest/1000;
 Serial.println(roundNearest,6);

 price = (roundNearest*1000);
 Serial.println(price,2);
 while(1){}
}

you u can use roundf()
like in this video Demo Video


text:
How to read differential TTL signal from encoder using Arduino?
I am using Arduino UNO/ MEGA to read the incremental encoder pulses (Baumer encoder EIL580). Currently, I am using it in single-ended mode (reading A,B and Z outputs) as I am not sure how to read the differential signal in Arduino (A, Ainv, B, Binv, Z, Zinv) as it would improve the reliability of the data. Is there any addon shield or circuitry to interface this signal with Arduino?

Differential signals are used to reduce or cancel common noise from long cables.  Usually Arduino projects are small and everything is in close proximity.  Is the encoder far away from the Arduino.  That is, are the cables long?

It looks to me like something similar to RS485 (I have a page about that here).
You could use a chip like the LTC1480 to take the A+ and A- inputs and convert them to TTL levels.
I haven't tried it with your encoder but in principle it should work. (You would need two chips if you want to handle A+/A- and B+/B-. Or three if you want to handle R+/R- as well). Still, it's about a $6 chip.

I've had succes with the MAX485 chips, I believe they are pin compatible with the (one of the most common) LTC chips. The max485 may be cheaper (especially from ebay, but they may be counterfeit and not work as well).


text:
How to splice into existing buttons?
I want to control a kettle. It has 4 buttons and a digital disply of the temp. I would like the buttons and disply to remain functional. I just want to make the buttons remoteky pressabke. The buttons are at 5v. There is an almost bread‐board like set of little sockets where they connect to the higher voltage part of the kettle. (Where I see the kettle's built in relay, that powers the buttons and displsy.)k
If I have a 2nd set of wires to my arduino feed into these sockets would there be an issue with the signal from arduino going to the buttons?
Also, I think I might need a relay if I later adapt this for spark/particle core because it is 3.3v is there such a relay?

It might be useful to post a photo of the circuit board/connections.

From safe to less safe, use an opto-isolator; transitor; resistor; direct connection.


text:
Understanding SevSeg
I need to write a library for a display I created with eight segments. So, I decided to try to use SevSeg (https://github.com/DeanIsMe/SevSeg) as a starting off point. It can't be that different, right?
Well, I think I have hit a roadblock that indicates I must basically do everything from scratch. Here is how the information on what segments correspond to letters are stored in SevSeg:
 // The codes below indicate which segments must be
//illuminated to display each number.

static const byte digitCodeMap[] = {
  //     GFEDCBA  Segments      7-segment map:
  B00111111, // 0   "0"          AAA
  B00000110, // 1   "1"         F   B
  B01011011, // 2   "2"         F   B
  B01001111, // 3   "3"          GGG
  B01100110, // 4   "4"         E   C
  B01101101, // 5   "5"         E   C
  B01111101, // 6   "6"          DDD
  B00000111, // 7   "7"
  B01111111, // 8   "8"
  B01101111, // 9   "9"
  B01110111, // 65  'A'
  B01111100, // 66  'b'
  B00111001, // 67  'C'
  B01011110, // 68  'd'
  B01111001, // 69  'E'
  B01110001, // 70  'F'
  B00111101, // 71  'G'
  B01110110, // 72  'H'
  B00000110, // 73  'I'
  B00001110, // 74  'J'
  B01110110, // 75  'K'  Same as 'H'
  B00111000, // 76  'L'
  B00000000, // 77  'M'  NO DISPLAY
  B01010100, // 78  'n'
  B00111111, // 79  'O'
  B01110011, // 80  'P'
  B01100111, // 81  'q'
  B01010000, // 82  'r'
  B01101101, // 83  'S'
  B01111000, // 84  't'
  B00111110, // 85  'U'
  B00111110, // 86  'V'  Same as 'U'
  B00000000, // 87  'W'  NO DISPLAY
  B01110110, // 88  'X'  Same as 'H'
  B01101110, // 89  'y'
  B01011011, // 90  'Z'  Same as '2'
  B00000000, // 32  ' '  BLANK
  B01000000, // 45  '-'  DASH
};

As you can see this is a one dimensional array of 8-byte binaries that encode the segment. I don't understand the purpose of the B0 at the beginning of each byte. Could I use the 0 column to encode my eighth segment?
Am I right to assume this will change everything about the code and maybe I should start from scratch with a 2-D array?
This is roughly what I want:
//  ABCDEFGH  Segments      8-segment map:
  11000011, // 0   "0"       A BBBBB H
  10000000, // 1   "1"       A C   D H
  01011010, // 2   "2"       A C   D H
  11101010, // 3   "3"       A  C D  H
  00110101, // 4   "4"       A  E F  H
  01011010, // 5   "5"       A E   F H
  11101110, // 6   "6"       A E   F H
  01011000, // 7   "7"       A GGGGG H
  01111110, // 8   "8"
  01100101, // 9   "9"
  11111101, // 10  "A"
  10001110, // 11  "b"
  11000010, // 12  "C"
  00001111, // 13  "d"

What data type should I use for the array? Would byte work since I'm not using the B0?
Thanks.

I don't understand the purpose of the B0 at the beginning of each byte.

That's just Arduino's rather weird way of doing binary constants. For example, in the file binary.h are lines and lines of stuff like this:
#define B1011 11
#define B01011 11
#define B001011 11
#define B0001011 11
#define B00001011 11
#define B1100 12
#define B01100 12
#define B001100 12
#define B0001100 12
#define B00001100 12

A better way is to use standard C++ constants, eg.
0b00001100

instead of:
B00001100

Could I use the 0 column to encode my eighth segment?

Yes, they are just bytes, so you can use all 8 bits.


text:
just a silly doubt about glowing an LED
what will happen if i insert the anode of a LED to pin 12 and cathode of the LED to pin 11 and set pin 12 to high and pin 11 to low,will the led glow??

This will answer all your questions: https://hackingmajenkoblog.wordpress.com/2017/03/20/what-exactly-is-a-gpio-pin/

What will happen is you will damage your LED and/or your Arduino since you haven't mentioned a current-limiting resistor (220 ohms could well be suitable).
However the general concept is perfectly sound. You could, for example, have two LEDs, wired in opposite directions. By bringing one pin LOW and the other HIGH, one LED would light up, and by reversing the output to the pins the other LED would light up. If both pins were either HIGH or LOW then neither LED would light up, as there would be no voltage difference between the leads.
There is a calculator for LED resistors.

Yes it will, try it. This is one of the way to use a LED as a light sensor and light source by connecting it to two different Digital pins.
Ref.: https://playground.arduino.cc/Learning/LEDSensor