text:
Using SoftwareSerial library with EnableInterrupt
I'm working on a project that involves both serial communication and GSM transmission.
I'm using the SoftwareSerial library for RS232 communication, and GSM (SMS) transmission:

TX and RX for RS232 : Arduino Uno D3 and D4 pins
TX and RX for GSM module : Arduino Uno D7 and D8 pins

The project requires also the use of the EnableInterrupt library to enable interrupt in Arduino's analog pins, meaning that I DON'T USE EnableInterrupt for all of the Arduino's digital pins including D3, D4, D7 and D8.
However when running the program that includes the two libraries, this long error message shows up :
libraries\SoftwareSerial\SoftwareSerial.cpp.o (symbol from plugin): In function `SoftwareSerial::read()':

(.text+0x0): multiple definition of `__vector_3'

sketch\sketch_jun14a.ino.cpp.o (symbol from plugin):(.text+0x0): first defined here

libraries\SoftwareSerial\SoftwareSerial.cpp.o (symbol from plugin): In function `SoftwareSerial::read()':

(.text+0x0): multiple definition of `__vector_5'

sketch\sketch_jun14a.ino.cpp.o (symbol from plugin):(.text+0x0): first defined here

libraries\SoftwareSerial\SoftwareSerial.cpp.o (symbol from plugin): In function `SoftwareSerial::read()':

(.text+0x0): multiple definition of `__vector_4'

sketch\sketch_jun14a.ino.cpp.o (symbol from plugin):(.text+0x0): first defined here

collect2.exe: error: ld returned 1 exit status

exit status 1
Erreur de compilation pour la carte Arduino/Genuino Uno

Clearly, there is a conflict between the two libraries, Is there any solution to remove this conflict and run the two libraries together ?
Thanks in advance !

With SoftwareSerial, you can use only one RX at a time. Could you replace the Arduino Uno with a Arduino Mega 2560 ? That one has 3 spare hardware serial ports.

SoftwareSerial uses all PinChange interrupts.
EnableInterrupts uses all PinChange interrupts.

You can see the conflict.
All you can do is to modify both libraries to remove support for the interrupts you don't need it to support - that way you share out the responsibility for handling the different interrupts between the two libraries.

I would suggest using different software serial libraries and pins.  To apply this answer, I would suggest this configuration:

Connect your RS232 device to pins 0 & 1 and use Serial
Connect your GSM device to pins 8 & 9 and use AltSoftSerial (it must use those pins).

If you do not send anything to the RS232 device, you can still use Serial for debug statements.  Don't even connect the TX pin to the RS232 device.  You will have to disconnect the RX pin to upload new sketches over USB.  Or, if the RS232 device receives formatted commands, it would ignore debug statments that don't look like commands.  This has the added benefit that the Serial Monitor window will display the commands you do send to the RS232 device.
If you really need to use 3 serial ports, you will have to use this configuration:

Use Serial for whatever
Connect the RS232 or GSM device to pins 8 & 9 and use AltSoftSerial
Connect the other device to any two pins and use my NeoSWSerial.

AltSoftSerial is more efficient at transmitting than NeoSWSerial, so use AltSoftSerial for the device to which you send the most data.  NeoSWSerial is limited to baud rates 9600, 19200 and 38400, so that may be a consideration.
SoftwareSerial is a terrible choice, because it disables interrupts for long periods of time, it can only listen to one port at a time, and it cannot transmit and receive at the same time.
AltSoftSerial and NeoSWSerial do not have these limitations, and they can co-exist to give you 2 extra serial ports.  You should also be aware the NeoSWSerial disables interrupts while transmitting (not receiving).  AltSoftSerial uses one of the TIMER resources, while NeoSWSerial simply uses the millis() timer.
ADDENDUM
To answer your original question about using the EnableInterrupt library at the same time as a software serial library:
If you are using the first configuration above, AltSoftSerial will not conflict with EnableInterrupt.
If you are using the second configuration, NeoSWSerial will conflict with EnableInterrupt.  For this possibility, NeoSWSerial has an option to disable using all the Pin Change Interrupt ISRs.  Uncomment this line and call the NeoSWSerial::rxISR from the appropriate enableInterrupt() callback function:
#include <NeoSWSerial.h>
NeoSWSerial oneDevice( RX_PIN, TX_PIN );

void myISR()
{
  NeoSWSerial::rxISR( *portInputRegister( digitalPinToPort( RX_PIN ) ) );
}

void setup()
{
  enableInterrupt( RX_PIN, myISR, CHANGE );
}

This puts EnableInterrupt in charge of the ISRs.  If you want to try NeoSWSerial, it is available from the Arduino IDE Library Manager, under the menu Sketch -> Include Library -> Manage Libraries.


text:
New Language - Interfacing with AVR
So I'm taking a class where the project is to create a new embedded language. We are using OCaml for the compiler, so I was looking for a way to interface with AVR or its C library in such a way as I can write programs in my language, then compile and somehow get it on the arduino I have. I was curious if there's a library for OCaml or some sort of white paper for interfacing with the board at a high level or even at a low level where I can get this to work.

The OCAML compiler can emit C code and the Arduino IDE takes C code, so in theory it is possible.
You would need to get the OCAML runtime code ported over to the Arduino IDE. At very least, I think this would be a lot of work. At worst, the Arduino might not have enough memory to support it.

You don't need the Arduino IDE to compile Arduino code: just call avr-g++, like the IDE itself does.

I have no experience with OCaml or with writing compilers, but I would
suggest that you first learn how to program the Arduino, then teach
your compiler to do so.
You may start by using the Arduino IDE and a couple basic tutorials.
There is an option in the IDE for displaying all the commands it runs to
get your program compiled and linked. Take note of these commands, then
throw the IDE away. Alternatively, you can download one of the few
Arduino Makefiles that float around the Web.
You will see that the basic toolset you need is the following:

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

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

source: Stack Exchange

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

sort: votes


text:
Can't get my code to my OLED
I´m using Spark Fun Micro Pro board 5V:
https://learn.sparkfun.com/tutorials/pro-micro--fio-v3-hookup-guide/hardware-overview-pro-micro
and to that i´ve hooked a true color OLED from digole:
http://www.digole.com/index.php?productID=859
Got a wire from OLED "data" to Pro micro "TX"-pin.
The OLED starts up and runs the start up screen, but the sample code I uploaded won't run. And that code looks like this:(the code is pretty long, if anybody would have a simplified sample code it would be much appreciated!! To get the OLED to show a simple "Hello World" would make me a very happy man! =)
Thanks!

#ifndef DigoleSerialDisp_h
#define DigoleSerialDisp_h

#include <inttypes.h>
#include "Print.h"
#include "Wire.h"
#include "Arduino.h"

// Communication set up command

// Text function command

// Graph function command

#define Serial_UART 0
#define Serial_I2C 1
#define Serial_SPI 2
#define _TEXT_ 0
#define _GRAPH_ 1

void setup() {}

void loop () {}

class DigoleSerialDisp : public Print {

public:
#if defined(_Digole_Serial_UART_)

DigoleSerialDisp(HardwareSerial1 *s, unsigned long baud) //UART set up

{

    _mySerial = s;

    _Baud = baud;

    _Comdelay=2;

}

size_t write(uint8_t value) {
    _mySerial->write((uint8_t)value);
    return 1; // assume sucess
}

void begin(void) {

    _mySerial->begin(9600);
    _mySerial->print("SB");
    _mySerial->println(_Baud);
    delay(100);
    _mySerial->begin(_Baud);

}

 #endif

 #if defined(_Digole_Serial_I2C_)

void begin(void) {
    _myWire->begin();
}

DigoleSerialDisp(TwoWire *s, uint8_t add) //U2C set up

{

    _myWire = s;
    _I2Caddress = add;
    _Comdelay=6;

}

size_t write(uint8_t value) {

    _myWire->beginTransmission(_I2Caddress);

    _myWire->write((uint8_t)value);
    _myWire->endTransmission();

    return 1; // assume sucess

}

#endif

#if defined(_Digole_Serial_SPI_)

void begin(void) {

}

DigoleSerialDisp(uint8_t pin_data, uint8_t pin_clock, uint8_t SS) //spi set up

{

    _Clockpin = pin_clock;
    _Datapin = pin_data;
    _SSpin = SS;

    pinMode(_Clockpin, OUTPUT);
    pinMode(_Datapin, OUTPUT);
    pinMode(_SSpin, OUTPUT);

    digitalWrite(_SSpin, HIGH);
    digitalWrite(_Clockpin, LOW);
    digitalWrite(_Datapin, LOW);

    _Comdelay=6;

}

size_t write(uint8_t value) {

    digitalWrite(_SSpin, LOW);
    digitalWrite(_SSpin, LOW);
    digitalWrite(_SSpin, LOW);

    shiftOut(_Datapin, _Clockpin, MSBFIRST, value);

    digitalWrite(_SSpin, HIGH);

    return 1; // assume sucess

}

#endif

//    virtual size_t write(uint8_t);

    /*---------fucntions for Text and Graphic LCD adapters---------*/

void disableCursor(void) {

    Print::print("CS0");

}

void enableCursor(void) {

    Print::print("CS1");

}

void clearScreen(void) {

    Print::print("CL");

}

void setI2CAddress(uint8_t add) {

    Print::print("SI2CA");

    write(add);

    _I2Caddress = add;

}

void displayConfig(uint8_t v) {

    Print::print("DC");

    write(v);

}

//print function

size_t println(const __FlashStringHelper *v) {

    preprint();

    Print::println(v);

    Print::print("\x0dTRT");

}

size_t println(const String &v) {

    preprint();

    Print::println(v);

    Print::println("\x0dTRT");

}

size_t println(const char v[]) {

    preprint();

    Print::println(v);

    Print::println("\x0dTRT");

}

size_t println(char v) {

    preprint();

    Print::println(v);

    Print::println("\x0dTRT");

}

size_t println(unsigned char v, int base = DEC) {

    preprint();

    Print::println(v, base);

    Print::println("\x0dTRT");

}

size_t println(int v, int base = DEC) {

    preprint();

    Print::println(v, base);

    Print::println("\x0dTRT");

}

size_t println(unsigned int v, int base = DEC) {

    preprint();

    Print::println(v, base);

    Print::println("\x0dTRT");

}

size_t println(long v, int base = DEC) {

    preprint();

    Print::println(v, base);

    Print::println("\x0dTRT");

}

size_t println(unsigned long v, int base = DEC) {

    preprint();

    Print::println(v, base);

    Print::println("\x0dTRT");

}

size_t println(double v, int base = 2) {

    preprint();

    Print::println(v, base);

    Print::println("\x0dTRT");

}

size_t println(const Printable& v) {

    preprint();

    Print::println(v);

    Print::println("\x0dTRT");

}

size_t println(void) {

    Print::println("\x0dTRT");

}

size_t print(const __FlashStringHelper *v) {

    preprint();

    Print::println(v);

}

size_t print(const String &v) {

    preprint();

    Print::println(v);

}

size_t print(const char v[]) {

    preprint();

    Print::println(v);

}

size_t print(char v) {

    preprint();

    Print::println(v);

}

size_t print(unsigned char v, int base = DEC) {

    preprint();

    Print::println(v, base);

}

size_t print(int v, int base = DEC) {

    preprint();

    Print::println(v, base);

}

size_t print(unsigned int v, int base = DEC) {

    preprint();

    Print::println(v, base);

}

size_t print(long v, int base = DEC) {

    preprint();

    Print::println(v, base);

}

size_t print(unsigned long v, int base = DEC) {

    preprint();

    Print::println(v, base);

}

size_t print(double v, int base = 2) {

    preprint();

    Print::println(v, base);

}

size_t print(const Printable& v) {

    preprint();

    Print::println(v);

}

void preprint(void);

/*----------Functions for Graphic LCD/OLED adapters only---------*/

//the functions in this section compatible with u8glib

void drawBitmap(unsigned int x, unsigned int y, unsigned int w, unsigned int h, const uint8_t *bitmap);

void drawBitmap256(unsigned int x, unsigned int y, unsigned int w, unsigned int h, const uint8_t *bitmap);

void drawBitmap262K(unsigned int x, unsigned int y, unsigned int w, unsigned int h, const uint8_t *bitmap);

void setTrueColor(uint8_t r, uint8_t g, uint8_t b);

void setRot90(void);

void setRot180(void);

void setRot270(void);

void undoRotation(void);

void setRotation(uint8_t);

void setContrast(uint8_t);

void drawBox(unsigned int x, unsigned int y, unsigned int w, unsigned int h);

void drawCircle(unsigned int x, unsigned int y, unsigned int r, uint8_t = 0);

void drawDisc(unsigned int x, unsigned int y, unsigned int r);

void drawFrame(unsigned int x, unsigned int y, unsigned int w, unsigned int h);

void drawPixel(unsigned int x, unsigned int y, uint8_t = 1);

void drawLine(unsigned int x, unsigned int y, unsigned int x1, unsigned int y1);

void drawLineTo(unsigned int x, unsigned int y);

void drawHLine(unsigned int x, unsigned int y, unsigned int w);

void drawVLine(unsigned int x, unsigned int y, unsigned int h);

//-------------------------------

//special functions for our adapters

void setFont(uint8_t font); //set font, availale: 6,10,18,51,120,123, user font: 200-203

void nextTextLine(void); //got to next text line, depending on the font size

void setColor(uint8_t); //set color for graphic function

void backLightOn(void); //Turn on back light

void backLightOff(void); //Turn off back light

void directCommand(uint8_t d); //send command to LCD drectly

void directData(uint8_t d); //send data to LCD drectly

void moveArea(unsigned int x0, unsigned int y0, unsigned int x1, unsigned int y1, char xoffset, char yoffset); //move a area of screen to another place
void drawStr(unsigned int x, unsigned int y, const char *s);
void setPrintPos(unsigned int x, unsigned int y, uint8_t =0 );
void setLCDColRow(uint8_t col, uint8_t row);

void setTextPosAbs(unsigned int x, unsigned int y);
void write2B(unsigned int v);

void displayStartScreen(uint8_t m) {

    Print::print("DSS");

    write(m);

} //display start screen

void setMode(uint8_t m) {

    Print::print("DM");

    write(m);

} //set display mode

void setTextPosBack(void) {

    Print::print("ETB");

} //set text position back to previous, only one back allowed

  void setTextPosOffset(char xoffset, char yoffset) {

    Print::print("ETO");

    write(xoffset);

    write(yoffset);

}

void setLinePattern(uint8_t pattern) {

    Print::print("SLP");

    write(pattern);

 }

void setLCDChip(uint8_t chip) {      //only for universal LCD adapter

    Print::print("SLCD");

    write(chip);

 }
void setBackLight(uint8_t bl){
    Print::print("BL");

    write(bl);

}

void uploadStartScreen(int lon, const unsigned char *data); //upload start screen

void uploadUserFont(int lon, const unsigned char *data, uint8_t sect); //upload user font

void digitalOutput(uint8_t x) {Print::print("DOUT");write(x);}

private:

unsigned long _Baud;

HardwareSerial *_mySerial;

uint8_t _I2Caddress;

TwoWire *_myWire;

uint8_t _Clockpin;

uint8_t _Datapin;

uint8_t _SSpin;

uint8_t _Comdelay;

};

#endif

Are the SPI and I2C jumpers on the bottom disconnected?

@Gerben, no haven't done that.. am I supposed to solder anything or how do I disconnect the jumpers? Thx

@Gerben I´m pretty new to this, as you can imagine, but aren't the jumpers supposed to be "open" when using UART according to the OLED´s jumper chart?

That's what I was getting at. Sometimes these jumpers are soldered, or there is still some copper between them. In the latter case you have to take a knife and scrape/cut away the copper trace between the jumper. Use a multimeter to check that both jumpers are open/disconnected.

Got it to work. Found another sample code that did it! Thx for your time!!

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

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


text:
Would an infinite loop inside loop() perform faster?
When you're writing a typical sketch, you usually rely on loop() being called repeatedly for as long as the Arduino is running. Moving in and out of the loop() function must introduce a small overhead though.
To avoid that, you could presumably create your own infinite loop, like this:
void loop()
{
    while (true)
    {
        // do stuff...
    }
}

Is that a viable way to improve performance? Will it cause other problems if loop() never returns?

The part of the code on an ATmega core that does setup() and loop() is at follows:
#include <Arduino.h>

int main(void)
{
        init();

#if defined(USBCON)
        USBDevice.attach();
#endif

        setup();

        for (;;) {
                loop();
                if (serialEventRun) serialEventRun();
        }

        return 0;
}

Pretty simple, but there is the overhead of the serialEventRun(); in there.
Let's compare two simple sketches:
void setup()
{

}

volatile uint8_t x;

void loop()
{

    x = 1;

}

and
void setup()
{

}

volatile uint8_t x;

void loop()
{
    while(true)
    {
        x = 1;
    }
}

The x and volatile is just to ensure it isn't optimised out.
In the ASM produced, you get different results:

You can see the while(true) just performs a rjmp (relative jump) back a few instructions, whereas loop() performs a subtraction, comparison and call. This is 4 instructions vs 1 instruction.
To generate ASM as above, you need to use a tool called avr-objdump. This is included with avr-gcc. Location varies depending on OS so it is easiest to search for it by name.
avr-objdump can operate on .hex files, but these are missing the original source and comments. If you have just built code, you will have a .elf file that does contain this data. Again, the location of these files varies by OS - the easiest way to locate them is to turn on verbose compilation in preferences and see where the output files are being stored.
Run the command as follows:

avr-objdump -S output.elf > asm.txt

And examine the output in a text editor.

OK, but isn't there a reason for calling serialEventRun() function? What is it for?

It's part of the functionality used by HardwareSerial, not sure why it isn't taken out when Serial isn't needed.

Would be helpful to briefly explain how you generated the ASM output so people can check themselves.

@Cybergibbons it is never taken out because it is part of standard main.c used by Arduino IDE. However it does not mean that HardwareSerial library is included to your sketch; actually it is not included if you don't use it (that's why there is if (serialEventRun) in main() function. If you don't use HardwareSerial library then serialEventRun will be null, hence no call.

However HardwareSerial library gets probably included (can someone confirm that?) if you use some arduino functions like Serial.print(). In this situation, what can happen if your loop() loops forever and thus never calls serialEventRun()? I'm afraid Serial may not work in this case.

Yeah, it is part of the main.c as quoted, but I would expect it to be optimised out if not required hence I think aspects of Serial are always included. I frequently write code that will never return from loop() and don't notice issues with Serial.

@Cybergibbons, serialEventRun() calls serialEvent() for the various serial ports. By default, all of these are empty procedures, but they can be overridden by the user to do something useful if desired. If you're not overriding it, there's no need to call it.

Cybergibbons's answer describes quite nicely the assembly code generation and the differences amongst the two techniques. This is intended to be a complementary answer looking at the issue in terms of practical differences, i.e. how much of a difference either approach will make in terms of execution time.

Code Variations
I did an analysis involving the following variations:

Basic void loop() (which gets inlined on compilation)
Un-inlined void loop() (using __attribute__ ((noinline)))
Loop with while(1) (which gets optimized)
Loop with un-optimized while(1) (by adding __asm__ __volatile__("");. This is a nop instruction that prevents optimization of the loop without resulting in additional overheads of a volatile variable)
An un-inlined void loop() with optimized while(1)
An un-inlined void loop() with un-optimized while(1)

The sketches can be found here.
Experiment
I ran each of these sketches for 30 seconds, thereby accumulating 300 data points each. There was a 100 millisecond delay call in each loop (without which bad things happen).
Results
I then calculated the mean execution times of each loop, subtracted 100 milliseconds from each and then plotted the results.
http://raw2.github.com/AsheeshR/Arduino-Loop-Analysis/master/Figures/timeplot.png
Conclusion

An un-optimised while(1) loop within void loop is faster than a compiler optimised  void loop.
The time difference between the un-optimized code and default Arduino  optimized code is insignificant practically. You will be better off compiling manually using avr-gcc and using your own optimisation flags rather than depending on the Arduino IDE to help you with it (if you need microsecond optimisations).

NOTE: The actual time values are not of significance here, the difference between them is. The ~90 microseconds of execution time includes a call to Serial.println, micros and delay.

NOTE2: This was done using the Arduino IDE and the default compiler flags that it supplies.

NOTE3: Analysis (plot and calculations) was done using R.

Good work. Graph has milliseconds not microseconds but not a huge issue.

@Cybergibbons Thats quite unlikely since all measurements are in microseconds and I havent changed scales' anywhere :)


text:
Sending constant int from Arduino to PC causes error
I am using Arduino Uno Rev 3, and according to this link we can achieve 2000000 baud rate.
This problem can be easily repeated by the following code:

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

void loop() {
  int val = 234;
  Serial.println(val);
}

I am using the serial-USB cable. To read the data, I used Python pyserial (< 20 lines of code including empty lines and import lines):
import serial
import matplotlib.pyplot as plt

LEN = 10000
data = []
ser = serial.Serial('COM3', baudrate=2000000)
for i in range(LEN):
    try:
        data.append(int(ser.readline()))
    except:
        pass
ser.close()

# %% Plot data
plt.figure(figsize=(6, 4))
plt.plot(data)
plt.savefig('data.png')

Here is what I got:

Edit below
Chris mentioned a good point that it might be the high baud rate of 2,000,000 causing the instability. I did think about that when I first ran into this, but then I did a little trick: adding a sinusoid into the constant. If I do that, the weird spiking goes away! I think it indicate that this is not a high baud rate issue... Is it?
Code:
void setup() {
  Serial.begin(2000000);
}

void loop() {
  int val = 234;
  val += int(512 * (sin(float(millis()) * 0.01) + 1)) * 0.1;
  Serial.println(val);
}

Output:

Your link overlooks many potential issues, such as buffer management in the USB converter.  Just because the hardware UARTs can both divide a 16 MHz clock by 8, doesn't mean you can actually move bulk data at that rate reliably, or flush it through the USB backhaul before more comes in.  Try capturing the actual data received.

Setting a high baud rate isn't necessarily going to move your data any faster anyway - if the bottleneck is elsewhere, it may just make it less reliable.  For maximum throughput, look at a Leonardo-style board (or better yet, one of the ARM-based ones) as there, the baud rate is ignored and the USB will simply move the data as fast as the embedded processor can keep up with.

Please merge your two questions of today on this topic by editing all the content into one and deleting the other.

@ChrisStratton I thought about that too, but then if I do a little trick and add a sinusoid into it, it will transfer all right! I will update the OP now to show that.

You are probably just delaying things with the time consuming calculation, allowing time for something to catch up.  Your overall problem is that your baud rate is unreliably high for one or more of the pieces in the chain.

@ChrisStratton That makes total sense. I think you are right - would you mind posting this as an answer so I can accept it?

Actually I'm not convinced that this relies to unstability due to the high baud rate. In that case I would expect the incorrect values to be more random. In your (initial) case, you seem to have false 0s and (I guess) 23400s which would be the right valie plus additional zero's. At least when running such a python script on a RPi, the arduino is way too fast for the python script.

So, in your initial example you could add a delay between the Serial.println()s to check...

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


text:
Running multiple motors simultaneously
I have this code for a DC motor (using this library)

#include <Arduino.h>
#include <Vnh2sp30.h>

//              ENA A   B   PWM   CS    inv
Vnh2sp30  mtrL( A0, 7,  8,  5,    A2,   0);

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

void loop() {
  if (Serial.available() > 0)   {
    String first  = Serial.readStringUntil(',');
    Serial.read();
    String second = Serial.readStringUntil(',');
    Serial.read();
    String third = Serial.readStringUntil(',');
    Serial.read();
    String echo = Serial.readString();
    Serial.println(echo);
       if(first == "start"){
                Serial.println("Starting DC motor");
                int duration = atoi(second.c_str());
                int power = atoi(third.c_str());
                int starttime = millis();
                int endtime = starttime;
                while ((endtime - starttime) <= duration) // mS
                {
                  endtime = millis();
                  mtrL.run(1023);
                }
                mtrL.stop();
                Serial.println("DONE");
       }
   }
}

Then I have this code to drive multiple stepper motors (using this library):
#include "BasicStepperDriver.h"

int incomingByte = 0;   // for incoming serial data
String readString = "";

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

void loop() {
    if (Serial.available() > 0) {
    String first  = Serial.readStringUntil(','); // start
    Serial.read();
    String second = Serial.readStringUntil(','); // motor number
    Serial.read();
    String third = Serial.readStringUntil(','); // motor steps
    Serial.read();
    String fourth = Serial.readStringUntil(','); // duration (millisec)
    Serial.read();
    String fifth = Serial.readStringUntil(','); // deg
                if(first == "start") {
                  if(second == "ALL") {
                    Serial.println("Starting stepper motor ALL");
                    int steps = atoi(third.c_str());
                    int duration = atoi(fourth.c_str());
                    int deg = atoi(fifth.c_str());

                    BasicStepperDriver stepper1(steps, DIR, STEP, ENBL);
                    stepper1.enable();
                    stepper1.setMicrostep(MICROSTEPS);
                    stepper1.setRPM(MAX_RPM);

                    BasicStepperDriver stepper2(steps, DIR_2, STEP_2, ENBL_2);
                    stepper2.enable();
                    stepper2.setMicrostep(MICROSTEPS);
                    stepper2.setRPM(MAX_RPM);

                    BasicStepperDriver stepper3(steps, DIR_3, STEP_3, ENBL_3);
                    stepper3.enable();
                    stepper3.setMicrostep(MICROSTEPS);
                    stepper3.setRPM(MAX_RPM);

                    BasicStepperDriver stepper4(steps, DIR_4, STEP_4, ENBL_4);
                    stepper4.enable();
                    stepper4.setMicrostep(MICROSTEPS);
                    stepper4.setRPM(MAX_RPM);

                    int starttime = millis();
                    int endtime = starttime;
                    while ((endtime - starttime) <= duration) // mS
                    {
                      stepper1.rotate(deg);
                      stepper2.rotate(deg);
                      stepper3.rotate(deg);
                      stepper4.rotate(deg);
                      endtime = millis();
                    }
                    stepper1.disable();
                    stepper2.disable();
                    stepper3.disable();
                    stepper4.disable();
                    Serial.println("DONE");
                  }
                }
        }
}

My goal is to merge this two codes together and still be able to run both the DC motor and one (or all) the stepper motors all together simultaneously. The first code is running on Arduino UNO and the other code runs on Arduino MEGA board and has been tested to work. The goal is to migrate the code from Arduino UNO to the MEGA board. Driving the motor for a specific time will block Arduino from executing the Stepper motors and vice versa with the DC motor. What can be done with these codes to make sure it can run the DC motor and Stepper motors at the same time?

The line while ((endtime - starttime) <= duration) // ms  is what you need to change because it keeps the loop from doing other actions while driving the motor, hence it is referred to as blocking.  The AccelStepper library mentioned by @Visual Micro uses a non-blocking approach but you need to change your approach.  Use some variable to detect the duration and let the code in loop() constantly check it each time though instead of using a while loop. That way each motor can get the attention it needs instead of taking turns.

Use the AccelStepper library along with the Adafruit MotorShield library
https://learn.adafruit.com/adafruit-motor-shield-v2-for-arduino/install-software

I don't have a adafruit motor shield just the ones from China

The library is standard. You don't need the shield. Read the AccelStepper guide and it explains how to use motors and steppers at the same time.

Would it work for ST Vnh2sp30 driver hardware? I'm not sure if the pinouts match.

I managed to compile this for Stepper motor connections, problem is with the connection to the VNH2SP30 and if it would be non-blocking.

I think you van set the pins but the point of Accel is to do non-blocking.


text:
Arduino Pro Micro, get data out of Tx pin?
I have a Sparkfun Arduino Pro Micro with an ATmega32u4 on it and a Roving Networks RN32 Bluetooth Module
Theoretically, I should be able to solder the Rx of the Bluetooth to the Tx on the arduino and vice versa and I should get serial communication over the Bluetooth.
Of course, I do not. However, as a first question: How do I get my Arduino to transmit data over the Tx pin?
I uploaded this to the Arduino with no hiccups:

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

void loop(){
  Serial.print("HelloWurld");
}

However, when I plug up my o-scope, I see no signal over the Tx line. Nada. I see data coming over the USB into the COM port on my computer, but nothing over the Tx pin.
How do I get the Arduino to put out serial data on the Tx pin?

Do you have it powered?

And is the ground on the scope connected to the Arduino's ground?

Yes, it has the +5v in and the scope is on the arduino's gnd pin. How do I push serial data over the TX (digital0) pin? I know it's a code issue

Your code seems fine

Thank you, but we are both wrong then. When I put this code on the arduino and then probe the TX pin (digital 0), I see nothing at all, it's just flat. However, on my serialport program on my windoes machine, I see the helloWurld message. I DO NOT CARE about the serialport program for now. I need to data to come out of the TX pin, NOT the USB. Does that make sense?

Have you tried pin 1?

That is the RX pin, and yes, I have tried every pin to see the outputs. All pins on the board are silent, the pins on the chip are far too small to probe, let alone solder to.

I do not have anything coming out of the TX pin. The scope is set up just fine. I am able to have the TX pin go from +5 to 0 with no problems as a sanity check. It takes about 2ms to switch in the arduino loop call. Here is the code:void setup(){      Serial.begin(9600);     pinMode(5,OUTPUT); } void loop(){     Serial.print("HelloWurld");     analogWrite(0,1);     analogWrite(0,0); } This is just gravy for pulsing the TX pin. By digital header, do you mean the pins on the side of the board, or the pins on the atmega chip itself? Thank you very much for your assistance, i do appreciate it.

Ah, this may be where confusion is coming from. This is NOT a stock UNO, this is a SparkFun board that behaves as one. I am trying to talk to SparkFun for help too. To your comment: Do you mean the ATMEGA chip's TX line then? I am trying to understand how I can have data coming out of the TX pin, not see the 5V swing, and then also have the USB transmit data to my computer. I'm sorry, I really just don't get it. Thank you very much for your help.

You appear to have a "pro micro" style board in which the USB communication is directly sourced from the main ATmega32u4 processor, rather than generated as serial data and then forwarded to a distinct USB-serial converter as on traditional Arduinos.   Your question could have been resolved much more quickly if you had clearly stated the type of board you were using in words, rather than only as a product link (so I edited that into your question).
According to the documentation for the official Arduino Pro Micro:

Serial: 0 (RX) and 1 (TX). Used to receive (RX) and transmit (TX) TTL serial data using the ATmega32U4 hardware serial capability. Note that on the Micro, the Serial class refers to USB (CDC) communication; for TTL serial on pins 0 and 1, use the Serial1 class.

Therefore to generate output on the hardware UART you will need to change all occurrences of Serial to Serial1
void setup(){
    Serial1.begin(9600);
}

void loop(){
    Serial1.print("HelloWurld");
}

The transmit data will be sourced from ATmega32u4 pin 21 which is "D1" (digital pin 1) on the headers.  If you wish to probe it, that would be the best place to do so.
If you wish to transmit data out of a different pin which is not connectied to the ATmega32u4's UART (as your example with digital pin 5 hints you might) you must instead use SoftwareSerial or similar implementation to bit-bang the serial data out of a general purpose I/O pin.
For example (inspired by this example):
SoftwareSerial mySerial(4, 5); // RX, TX

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

void loop(){
    mySerial.print("HelloWurld");
}

Well spotted, Chris! +1

oh my days... as an arduino noob this distinction between ATmeta32u4 and ATmega328 is mind bending... took me three days to figure out... fact that I was trying same code on ATmega328 code on the 32u4 didn't help. A million thanks Chris Stratton.

The bluetooth board uses 3.3V, not 5V according the datasheet.
So you'll need to shift the voltage level between it and the Arduino board (which is 5V). Note that the spec sheet shows how this can easily be done with 2 resistors (R1 and R2 in sheet typical application circuit, page 5).
Also, on the bluetooth module, the RS232 interface has 4 pins:

UART_TX
UART_RX
UART_CTS
UART_RTS

UART_CTS must be 0 to ensure the device reads incoming bytes. Normally this is done by an internal pulldown resistor, but you must ensure you did not connect that pin to +V.
Finally, ensure that the baud rate of the module is properly set to 9600 bauds, the same as in your program.

I am aware of all this, thank you still the same. However, my issue is much more basic. I need to get data out of the TX pin so that I can hook the bluetooth into that. If I can't get data out of a pin on the Arduino board, the bluetooth is useless. How do I get serial data out of the arduino board? The USB pins are sending out serial data just fine, but I cannot get other pins to output data. Do I need to solder to the USB pins in order to get data into the Bluetooth? Thank you very much for any help, I do appreciate it a ton

So I stumbled upon this thread while having similar problem, but with HC-05 module. So because I have too much free time on my hands during finals (no I don't) I decided to create a small github repo that might help someone sometime. https://github.com/Sackhorn/HC-05-Pro-Micro-Hookup
The code is:
//Writen for pro micro
//These proved to be usefull
//http://arduino.stackexchange.com/questions/1471/arduino-pro-micro-get-data-out-of-tx-pin
//https://forum.sparkfun.com/viewtopic.php?f=32&t=38889&sid=8178cdb38005ff33cc380a5da34fb583&start=15

void setup()
{
  pinMode(9, OUTPUT);
  digitalWrite(9, HIGH);
  Serial.begin(9600);
  Serial1.begin(38400);
}

void loop()
{

  //Serial1 is the physical Serial Connections on TX and RX pins
  if (Serial1.available()) Serial.write(Serial1.read());

  // Serial is from my understanding the virtual connection with computer via USB
  if (Serial.available()) Serial1.write(Serial.read());
}

Nice use of Serial and Serial1.  I posted an edit with your code and diagram.

Just hook up the serial pins from the bluetooth module to the corresponding Pro Micro pins: TX to RX and RX to TX. I hope this can help someone.
Then look for data like this:
void setup(){
   Serial1.begin(9600); // Init Hardware Serial port on pins 0 and 1 - Bluetooth
   Serial.begin(9600); // Init Virtual Serial Port - Machine

   Keyboard.begin(); // Init HID - Keyboard
}

void loop(){
   if (Serial1.available() > 0) {

     char myData = Serial1.read()

     // Send data from Bluetooth/Sensor to the Machine - Virtual Serial Port
     Serial.println(myData);

     // Emulate HID Device - Keyboard
     if ( myData == 0x7F ) { // Detect code of android backspace key
        Keyboard.write(0xB2); //  Convert received code char to PC/Linux ascii keycode for the backspace key. This can change between different OS!
     }

     else {
        Keyboard.write(myData);
     }

   }
}

You also may want to try the "SoftwareSerial" library.  That way you can use almost any pins you want for serial comms.  As a matter of fact, you can have a couple of serial ports.
Please do read up on the SoftwareSerial library though.  It does have some restrictions.


text:
Arduino Mega with nRF24L01+ module
I am having trouble getting this module to work using the tmrh20 lib. I am using these modules with two arduino mega and a 3.3V external power supply. I also placed 10 uF in parallel with the modules power pin. I would really appreciate any comments or suggustions.
In the code below all I am trying to do is turn on a led.
Here are my pin assignment for both arduinos
CE -> 7
CSN -> 8
SCK -> 52
MOSI -> 51
MISO -> 50
IRQ -> unconnected
Transmitter
//#include <DigitalIO.h>
#include <SPI.h>
#include "RF24.h"
#include <printf.h>
RF24 radio(7,8);
const uint64_t pipe = 0xE8E8F0F0E1LL;
unsigned long msg = 375983;

void setup() {
    Serial.begin(115200);
    printf_begin();
    Serial.println("Transmitter");
    pinMode(9, INPUT);
    radio.begin();
    radio.setChannel(108);
    radio.openWritingPipe(pipe);
    radio.startListening();
    radio.printDetails();
}

void loop() {
  radio.stopListening();
  if (digitalRead(9) == HIGH)
  {
    while (!radio.write(&msg, sizeof(msg))){
      radio.write(&msg, sizeof(msg));
}
  Serial.println("Sending.....");
  }
  else {
    Serial.println("Awaiting Input....");
  }
  delay(500);

}

print detail report
STATUS = 0xff RX_DR=1 TX_DS=1 MAX_RT=1 RX_P_NO=7 TX_FULL=1
RX_ADDR_P0-1 = 0xffffffffff 0xffffffffff
RX_ADDR_P2-5 = 0x7f 0xff 0x7f 0xff
TX_ADDR = 0x0000000000
RX_PW_P0-6 = 0xff 0x7f 0xff 0x7f 0xff 0xff
EN_AA = 0xff
EN_RXADDR = 0xff
RF_CH = 0xff
RF_SETUP = 0xff
CONFIG = 0xff
DYNPD/FEATURE = 0x7f 0xff
Data Rate = 1MBPS
Model = nRF24L01
CRC Length = Disabled
PA Power = PA_MAX

Receiver
//#include <DigitalIO.h>
#include <SPI.h>
#include "RF24.h"
#include <printf.h>
RF24 radio(7,8);
const uint64_t pipe = 0xE8E8F0F0E1LL;
unsigned long msg;

void setup() {
    Serial.begin(115200);
    printf_begin();
    Serial.println("Receiver");
    pinMode(9, OUTPUT);
    radio.begin();
    radio.setChannel(108);
    radio.openReadingPipe(0,pipe);
    radio.printDetails();

}

void loop() {
   radio.startListening();
   digitalWrite(9, LOW);
  if(radio.available()){
    while(radio.available())
    {
    radio.read(&msg, sizeof(msg));
    Serial.println("Incoming...");
    delay(500);
    Serial.println(msg);
    }
  }
  else{
    Serial.println("No Msg");
  }
  radio.stopListening();
  Serial.println(msg);
  if (msg == 375983){
    digitalWrite(9, HIGH);
    Serial.println(msg);
  }
  delay(500);
}

print detail report
STATUS = 0x00 RX_DR=0 TX_DS=0 MAX_RT=0 RX_P_NO=0 TX_FULL=0
RX_ADDR_P0-1 = 0x0000000000 0x0000000000
RX_ADDR_P2-5 = 0x00 0x00 0x00 0x00
TX_ADDR = 0x0000000000
RX_PW_P0-6 = 0x00 0x00 0x00 0x00 0x00 0x00
EN_AA = 0x00
EN_RXADDR = 0x00
RF_CH = 0x00
RF_SETUP = 0x00
CONFIG = 0x00
DYNPD/FEATURE = 0x00 0x00
Data Rate = 1MBPS
Model = nRF24L01
CRC Length = Disabled
PA Power = PA_MIN

UPDATE:
Transmitter PrintDetail
STATUS       = 0x0e RX_DR=0 TX_DS=0 MAX_RT=0 RX_P_NO=7 TX_FULL=0
RX_ADDR_P0-1     = 0x00000000e1 0xc2c2c2c2c2
RX_ADDR_P2-5     = 0xc3 0xc4 0xc5 0xc6
TX_ADDR      = 0x00000000e1
RX_PW_P0-6   = 0x20 0x00 0x00 0x00 0x00 0x00
EN_AA        = 0x3f
EN_RXADDR    = 0x02
RF_CH        = 0x6c
RF_SETUP     = 0x07
CONFIG       = 0x0f
DYNPD/FEATURE    = 0x00 0x00
Data Rate    = 1MBPS
Model        = nRF24L01+
CRC Length   = 16 bits
PA Power     = PA_MAX

Results form tmrh20 Getting Started Example
First Arduino
Sent 8340224, Got response 0, Round-trip delay 547172 microseconds
Now sending
Sent 9889124, Got response 0, Round-trip delay 511072 microseconds
Now sending
Sent 11401920, Got response 0, Round-trip delay 43348 microseconds
Now sending
Sent 12446992, Got response 0, Round-trip delay 635580 microseconds
Now sending
Sent 14084352, Got response 0, Round-trip delay 1620788 microseconds
Now sending
Sent 16706968, Got response 0, Round-trip delay 1227548 microseconds
Now sending
Sent 18936340, Got response 0, Round-trip delay 145372 microseconds

Second Arduino
*** PRESS 'T' to begin transmitting to the other node

The second arduino is not printing anything on the serial monitor, no matter what I enter.

Bad wiring. Double, no, triple check the wiring and modules.

The output on both the transmitter and the receiver clearly state the nRF24 module are not properly connected and the SPI is not communicating with it.

(not enough point to comment, so here's a potential answer)
I had enormous troubles getting these things to work reliably.  I tried all kinds of caps over the power supply. In the end I went for a 1$ piggy back board that takes 5v input and regulates to 3.3V. It also has the right pin female header to fit the nfr nicely. Since then I've had no issues. I also did a bit of experimentation and found that the RX side was the side giving problems.

Number one reason they don't work is bad wiring, wrong CE/CSN or whatever and they don't work.

Well, in my case I checked the wiring several times. After obtaining the 3.3v boards, I did extensive testing to see what factor made the difference. My results are noted above. Whilst your mileage might vary, my tip for those still having issues is to try using these boards.

Yes that is one way. But it's easier to decouple with 1000uF electrolytic capacitor. Just as I did when I found my Mega's regulator noisy.

At first I tries this too, using different cap sizes, including 1000uF, but to no avail.I know that filter caps are often suggested, and maybe often work, but these boards did the trick for me.

Try these:

Set pin 9 on the TX side as a pulled-up input i.e. pinMode(9, INPUT_PULLUP);
Connect one end of the switch to GND and the other to pin 9. Then in your code, test for a button press like this: if (digitalRead(9) == LOW){...}
Use a byte array for holding the address instead of the 64-bit int you're using.
Remove the stopListening() call in your RX loop(); there is no need for it since all its doing is receiving.
Remove the 500 ms delays in the RX loop() just in the unlikely case that its causing you to lose bytes

I have implement the changes you suggested. Still does not work.

@guow3 any changes in printDetails()? Update your post if there are any changes. I also forgot to include something in my answer. Editing now...

Only the transmitter printdetail report changed. The receiver remained the same.

@guow3 have u tried using the library examples? If they work, then modify them to send your long integer instead

Updated. Note the transmitter - > first arduino, Receiver -> second arduino

I hope you are using the example as it is. Just one small change: look for the variable radioNumber near the top in the example. Set it to 1 in one Arduino and to 0 in the other Arduino. Then try again. Update your post with any new results.

I have tried this already. Thanks for your efforts and suggestions.

The output on the receiver clearly states the nRF24 module is not properly connected and the SPI is not communicating with it.

That can be caused by poor power too. But bad wiring is common too.


text:
How to properly process large arithmetic
just a question that requires a simple answer. How do I process a large number of arithmetic steps in arduino efficiently and precisely?
For example I have this code function setup:
void calc() {
  batterymoment = input*batterymass;
  totalmoment = 149650+batterymoment;
  buoyancymoment = buoyancymass*centrebuoyancy;
  wheelmoment = totalmoment - buoyancymoment;
  wheelweight = totalmass - buoyancymass;
  cgwheels = wheelmoment/wheelweight;
  maindistance = mainarm - wheelweight;
  nosedistance = wheelweight - nosearm;
  mainmass = (((wheelweight)*(1-((maindistance)/(maindistance+nosedistance))))/2);
  nosemass = (((wheelweight)*(1-((nosedistance)/(nosedistance+maindistance))))/2);
  mainmoment = mainmass*mainarm;
  nosemoment = nosemass*nosearm;
  netmoment = buoyancymoment+mainmoment+nosemoment;
  netcg = netmoment/totalmass;
  staticmargin = adc - netcg;
  answer = staticmargin/meanadc;

}

Now I've properly setup up data types for all of these variables and they are a combination of float, int and long. I don't think it's a problem with the data type. What I'm getting when I print final answer in the serial is the same number regardless the input the user enters.
I'm guessing I need to format the code in such a way that it performs each line step by step and verifies the answer before proceeding to the next arithmetic line. If so would I need a function for each arithmetic step? Or is there a simpler way to process this that I'm missing.
Any guidance is appreciated. Thanks.
Here is the code in its entirety:
unsigned long batterymoment,num1,num2,input,totalmoment;
double buoyancymoment,wheelmoment,cgwheels,mainmass,nosemass,maindistance,nosedistance;
double mainmoment,nosemoment,netmoment,netcg,staticmargin,answer;
double centrebuoyancy = 14.164;
double mainarm = 14.3;
double adc = 11.4;
double meanadc = 22.65;
double nosearm = 1.8;
int totalmass = 12404;
int batterymass = 720;
int buoyancymass = 4401;
int batteryposition,wheelweight;
boolean mySwitch = false;

void calc() {
  batterymoment = input*batterymass;
  totalmoment = 149650+batterymoment;
  buoyancymoment = buoyancymass*centrebuoyancy;
  wheelmoment = totalmoment - buoyancymoment;
  wheelweight = totalmass - buoyancymass;
  cgwheels = wheelmoment/wheelweight;
  maindistance = mainarm - wheelweight;
  nosedistance = wheelweight - nosearm;
  mainmass = (((wheelweight)*(1-((maindistance)/(maindistance+nosedistance))))/2);
  nosemass = (((wheelweight)*(1-((nosedistance)/(nosedistance+maindistance))))/2);
  mainmoment = mainmass*mainarm;
  nosemoment = nosemass*nosearm;
  netmoment = buoyancymoment+mainmoment+nosemoment;
  netcg = netmoment/totalmass;
  staticmargin = adc - netcg;
  answer = staticmargin/meanadc;
 }

void setup() {
  Serial.begin(9600);
  num1=0;
  num2=0;
  Serial.println("Enter battery position");
 }

void loop() {
  while (Serial.available()){
    batteryposition = Serial.read();
    if(batteryposition>47 && batteryposition<58){
      if(!mySwitch){
         num1=(num1*10)+(batteryposition-48);
      }else{
         num2=(num2*10)+(batteryposition-48);
        }
       }

if(batteryposition==61){
  input=num1+num2;
  calc();
  Serial.print("Static margin is: ");
  Serial.println(answer);
  num1=0;
  num1=0;
  mySwitch=false;
  }
 }
}

So depending on the user input, the calculations will change the final output answer. For example if a 5 should be entered the output should be -4.22 based on my calculations in excel.

Please do show the declarations, the actual result, and the expected result. And put some extra Serial.print("answer:");Serial.println(answer); debugging code in to help you isolate the problem.

And what does it print?  I'd put a "input=5;" in the code before calc(), and then try difft debug printing in calc() until you get something unexpected.

it prints -113.70 regardless of the input @DaveX

What I have found useful, is testing complex algorithms in a spreadsheet or small console application (even not so complex ones). Once I get them working, I convert to Arduino code, which is pretty straightforward. This is not a warranty of bug-free code but it's pretty close.

Again, do you want to clear num1 twice or did you intend to clear num2 after the processing.

You're getting the same value every time because that is the value that is being calculated.
I think you have something wrong with how you have implemented your formula.  If you start from "answer = " and repeatedly substitute the variables with the formulae or values that make up those variables you end up with this:

answer = (11.4 - (((4401 * 14.164) + ((((12404 - 4401)*(1-((14.3 - (12404 - 4401))/((14.3 - (12404 - 4401))+(12404 - 4401 - 1.8)))))/2) * 14.3) + ((((12404 - 4401)*(1-((12404 - 4401 - 1.8)/((12404 - 4401 - 1.8)+(14.3 - (12404 - 4401))))))/2) * 1.8)) / 12404)) / 22.65

There's nothing variable about that at all.
Your input value is being used to calculate batterymoment. batterymoment us being used to calculate totalmoment. totalmoment is being used to calculate wheelmoment. wheelmoment is being used to calculate cgwheels. cgwheels is never used for anything.

Per your comments, the calc() function is not acting as expected.
Change calc() to be:
void calc() {
  Serial.print("input:");Serial.println(input);
  batterymoment = input*batterymass;
  totalmoment = 149650+batterymoment;
  buoyancymoment = buoyancymass*centrebuoyancy;
  wheelmoment = totalmoment - buoyancymoment;
  wheelweight = totalmass - buoyancymass;
  cgwheels = wheelmoment/wheelweight;
  maindistance = mainarm - wheelweight;
  nosedistance = wheelweight - nosearm;
  mainmass = (((wheelweight)*(1-((maindistance)/(maindistance+nosedistance))))/2);
  nosemass = (((wheelweight)*(1-((nosedistance)/(nosedistance+maindistance))))/2);
  mainmoment = mainmass*mainarm;
  nosemoment = nosemass*nosearm;
  netmoment = buoyancymoment+mainmoment+nosemoment;
  netcg = netmoment/totalmass;
  staticmargin = adc - netcg;
  answer = staticmargin/meanadc;
  Serial.print("answer:");Serial.println(answer);
 }

and see if it gets the expected inputs and works as expected.  Then add debugging statements in-process until you discover the mismatch.
I'd turn in into more of a function, or a series of better defined functions, and then test them individually.
As your code is there is interaction between global variables, serial parsing, and calculations.  If you break it into distinct pieces, you can isolate where the problem is.


text:
Accessing digital pins from the Atmega 16u2 on the Uno
I'm running a custom firmware on the ATmega16U2 (Switch-Fightstick).
Is it possible to access the digital pins of the UNO from the ATmega16U2?

No, only the ATmega328P has access to the external pins of the Uno. You would need to write code for both the '328P and the '16U2 to communicate the pin values and changes over serial since that is the only channel connecting the MCUs.

that is not entirely true ... four of the pins are available

@jsotola: True, but none of them are the "digital" (i.e. Dn) pins of the Uno.

they are digital pins of the UNO ... use a jumper

There is a 4-pin header JP2 on the board that brings out the following pins from the '16U2
PB4, PB5, PB6, PB7

and the ICSP connector
PB1, PB2, PB3

Thank you for letting me know, although the accepted answer better suits my question. It's a bit of a hassle though that they are filled with solder by default on the UNO...


text:
Why doesn't millis() use 1 µsec or 1 msec interrupt?
Arduino millis() does not make use of one millisecond interrupt. Instead they make use of 1,024 µsec interrupts and manipulate. Any specific reason why this was implemented this way?
In one case, we can go for timer0 without prescaler and use 1 µsec interrupts. In such case, we have to use CTC mode with OCR0A=15. Inside ISR, we could update the microsecond counter and if it reaches 1,000, we could update the msec timer count. Otherwise we could go for directly 1 msec interrupt (maybe using timer0).
I wrote this code to get micros() and millis(). But there is some issue and I'm not able to get it working correctly.
#include <avr/io.h>
#include <avr/interrupt.h>

#ifndef F_CPU
#define F_CPU 16000000UL
#endif

volatile uint32_t oneMilliCounter;
volatile uint32_t oneMicroCounter;
extern void initializeTimer0CTC_Mode (void);

extern uint32_t millis(void);
extern uint32_t micros(void);

volatile uint32_t oneMilliCounter = 0;
volatile uint32_t oneMicroCounter = 0;

uint32_t millis(void) {
  uint32_t value;
  uint8_t sregCopy = SREG;
  cli();
  value = oneMilliCounter;
  SREG = sregCopy;
  sei();
  return (value);
}

uint32_t micros (void) {
  uint32_t value;
  uint8_t sregCopy = SREG;
  cli();
  value = oneMicroCounter;
  SREG = sregCopy;
  sei();
  return (value);
}

void initializeTimer0CTC_Mode (void) {
  OCR0A = 15; // Set for 1 usec.
  TCCR0A |= 1 << WGM01;  // CTC Mode
  TIMSK0 |= 1 << OCIE0A;
  TCCR0B |= (1 << CS00); // prescaler=1
}

ISR(TIMER0_COMPA_vect) {
  static uint32_t prevMicro;
  oneMicroCounter++;
  if (oneMicroCounter - prevMicro >= 1000)   {
    prevMicro = oneMicroCounter;
    oneMilliCounter++;
  }
}

int main(void) {
  DDRD |= 1 << PD3;
  initializeTimer0CTC_Mode();
  sei();
  uint32_t prevTime = micros();
  while (1) {
    uint32_t currentTime = micros();
    if (currentTime - prevTime >= 1000) {
      PORTD ^= (1 << PD3);
      prevTime = currentTime;
    }
  }
  return (0);
}

One microsecond is only 16 CPU cycles.
The CPU needs 4 cycles to prepare itself for servicing the interrupt
(save the program counter, load the interrupt vector and clear the I bit
in SREG). The interrupt vector itself is a jmp instruction that takes
2 cycles. When the ISR is done, it executes the reti instruction
(return from interrupt) that takes 4 cycles. This means you have only 6
CPU cycles left for:

saving the context, i.e. pushing to the stack any register your ISR
may modify (2 cycles per push)
doing the actual ISR work
restoring the context (2 cycles per pop)
doing also some useful work in the main program.

There is no way you can do half of this in only 6 cycles.

Edit: I did a couple of experiments to gain more insight on the cost
of running an interrupt too often.
In the first experiment, I used your initializeTimer0CTC_Mode()
function to interrupt every microsecond the following program:
// This ISR consists of a sigle `reti' instruction.
EMPTY_INTERRUPT(TIMER0_COMPA_vect);

#include <util/delay.h>

int main(void)
{
    initializeTimer0CTC_Mode();
    DDRD |= _BV(PD2);       // PD2 = digital 2 as output
    sei();
    for (;;) {
        PIND |= _BV(PD2);   // toggle PD2
        _delay_us(499.75);  // 0.5 ms - 4 cycles
    }
}

The program is meant to generate a 1 kHz signal on pin 2, and
that's exactly what it does if the sei(); statement is commented out.
With the sei(); statement, the frequency drops to 375 Hz. This
shows that processing an empty interrupt (an ISR consisting solely of
the reti instruction) costs 62.5% of the CPU power, leaving 37.5% to
the main program. 62.5% is exactly 10 out of every 16 CPU cycles,
which confirms the cycle count of the first part of this answer.
The second experiment was to compile and disassemble your ISR. Here is
what I got:
__vector_14:
    push r1
    push r0
    in   r0, 0x3f  ; 1 cycle
    push r0
    eor  r1, r1    ; 1 cycle
    push r18
    push r20
    push r21
    push r22
    push r23
    push r24
    push r25
    push r26
    push r27
; static uint32_t prevMicro;
; oneMicroCounter++;
    lds  r24, 0x0104
    lds  r25, 0x0105
    lds  r26, 0x0106
    lds  r27, 0x0107
    adiw r24, 0x01
    adc  r26, r1    ; 1 cycle
    adc  r27, r1    ; 1 cycle
    sts  0x0104, r24
    sts  0x0105, r25
    sts  0x0106, r26
    sts  0x0107, r27
; if (oneMicroCounter - prevMicro >= 1000)   {
    lds  r24, 0x0104
    lds  r25, 0x0105
    lds  r26, 0x0106
    lds  r27, 0x0107
    lds  r20, 0x0100
    lds  r21, 0x0101
    lds  r22, 0x0102
    lds  r23, 0x0103
    sub  r24, r20   ; 1 cycle
    sbc  r25, r21   ; 1 cycle
    sbc  r26, r22   ; 1 cycle
    sbc  r27, r23   ; 1 cycle
    cpi  r24, 0xE8  ; 1 cycle
    sbci r25, 0x03  ; 1 cycle
    cpc  r26, r1    ; 1 cycle
    cpc  r27, r1    ; 1 cycle
    brcs 0f  ; 1 cycle if the if() condition is true, 2 otherwise
;   prevMicro = oneMicroCounter;
    lds  r24, 0x0104
    lds  r25, 0x0105
    lds  r26, 0x0106
    lds  r27, 0x0107
    sts  0x0100, r24
    sts  0x0101, r25
    sts  0x0102, r26
    sts  0x0103, r27
;   oneMilliCounter++;
    lds  r24, 0x0108
    lds  r25, 0x0109
    lds  r26, 0x010A
    lds  r27, 0x010B
    adiw r24, 0x01
    adc  r26, r1    ; 1 cycle
    adc  r27, r1    ; 1 cycle
    sts  0x0108, r24
    sts  0x0109, r25
    sts  0x010A, r26
    sts  0x010B, r27
; } }
0:
    pop  r27
    pop  r26
    pop  r25
    pop  r24
    pop  r23
    pop  r22
    pop  r21
    pop  r20
    pop  r18
    pop  r0
    out  0x3f, r0  ; 1 cycle
    pop  r0
    pop  r1
    reti           ; 4 cycles

Unless otherwise noted in comments, every instruction of this listing
takes 2 cycles to execute. Note the large number of CPU registers saved
(push) and restored (pop), and the large number of SRAM accesses
(lds and sts): three 4-byte variables read and written back.
Counting the total number of cycles taken by this ISR is left as an
“exercise to the reader”.

... And even if you could, imagine the performance hit on your sketch. It'd be starved of CPU cycles and never be able to do anything useful...

Even if you could do what you are proposing, which you can't (see Edgar Bonet's excellent answer), imagine the performance hit running an interrupt every single microsecond would have on your code.
Every interrupt takes time away from your code.
Let's crunch some more numbers. If you wanted the millis/micros interrupt to take no more than 1% of the processing time, so it has no noticeable impact on your running code it would have to execute for only 10ns.  That's 1% of 1000ns, or 0.000001 x 0.01.
Now assume it takes 50 clock cycles for a highly optimised version of your function to operate. That's a conservative estimate. That includes the time taken to prepare for, call and return from the interrupt.
For both those to hold true you would have to be able to execute 100 x 50 instructions in a microsecond. (To fill your 1uS you should be able to run your 1% interrupt 100 times, yes?) That's 5,000 x (1/0.000001) instructions per second, or 5,000,000,000 instructions per second.
Assuming a single clock cycle for each instruction, that means your chip would have to be running at 5GHz...!
Can you see the problem?
So we scale it back to something more realistic. Maybe a 10% performance hit instead of 1%. How would that be? Well, it's simple enough to say that it would require a chip running at 10% of the speed. 500 x (1/0.000001). So 500MHz.
Still a long long way away from the 16MHz that the Arduino's ATMega runs at.
So you can see the issue.
So we choose close to 1mS instead. That gives a much lower overhead and it's something that the 16MHz Arduino can cope with.
Why 1024 and not 1000? That's simple: 1000 is base 10. We, as humans, with two hands (usually) of (normally) 5 digits on each, love base 10. We thrive in base 10.  However, computers with their 1s and 0s hate base 10. They much prefer working in base 2. It makes arithmetic really easy for them. And in interrupts we want the arithmetic to be easy.
Let's take a quick look at the maths involved and expand out the macros in the code.
Every tick the millis value is increased by MILLIS_INC, and any extra is added to a "fractional" count.  What's MILLIS_INC? It's:
#define MILLIS_INC (MICROSECONDS_PER_TIMER0_OVERFLOW / 1000)

So let's expand that out - what's MICROSECONDS_PER_TIMER0_OVERFLOW?
#define MICROSECONDS_PER_TIMER0_OVERFLOW (clockCyclesToMicroseconds(64 * 256))

And what's clockCyclesToMicroseconds?
#define clockCyclesToMicroseconds(a) ( (a) / clockCyclesPerMicrosecond() )

What's clockCyclesPerMicrosecond()?
#define clockCyclesPerMicrosecond() ( F_CPU / 1000000L )

And, of course, F_CPU is (typically) 16,000,000.
So now we can put it all together.
#define MILLIS_INC (MICROSECONDS_PER_TIMER0_OVERFLOW / 1000)
becomes:

#define MILLIS_INC ((clockCyclesToMicroseconds(64 * 256)) / 1000)
which becomes:

#define MILLIS_INC (((64 * 256)/clocksPerMicrosecond()) / 1000)

Which in turn becomes:
#define MILLIS_INC (((64 * 256)/(F_CPU/1000000L)) / 1000)

Which finally turns into:
#define MILLIS_INC (((64 * 256)/(16000000/1000000L)) / 1000)

So reduce those down a little:
#define MILLIS_INC ((16384 / 16) / 1000)

And finally:
#define MILLIS_INC (1.024)

And since we're talking integers here that is automatically truncated (by the compiler, not at runtime, so it's essentially "free") to 1.
But what about the 0.024ms...? That's simple. The "Fractional" amount is added to another counter - but not as 0.024 - instead as a FRACT_INC amount, which is calculated as ((MICROSECONDS_PER_TIMER0_OVERFLOW % 1000) >> 3). That's 1024 % 100, or just 24, but then that's right shifted 3 times.  That becomes 3. And when that count hits another limit it loops round and adds one to the millis count.  That limit is FRACT_MAX, which is 1000 >> 3 or 125.
All nice and simple and straight forward. Variables, like the fractional count, are kept to just 8 bits (which is what you want on an 8 bit CPU...) and the majority of calculations are done by the compiler, not at runtime by the CPU.  Everything else is simple addition / subtraction and comparisons. Very light. And it runs often enough to be good enough for the majority of uses. And given that, because it's just a timer interrupt and is subject to collision with other interrupts, and can't run when interrupts are disabled, it's only a rough figure anyway. Even the act of reading millis() can slow down the counting of milliseconds, since it disables interrupts while the value of the count is retreived (a so called "critical section").
And yes, it could be tweaked to run at precisely 1000uS intervals and do away with the fractional component - but why bother when it's never going to be that accurate anyway? Also the added complexity of calculating what 1000uS is for a timer configuration when you consider the vast array of speeds that Arduinos could potentially run at (16MHz for an Uno, 8MHz for the 3.3V boards, 1MHz for the default internal oscillator...) it's far simpler to say "This is what it ticks at, and this is the number of milliseconds per tick, with this bit left over" which is calculated at compile time, instead of having to work out prescalers and overflow counts, etc.

Using CTC mode would mean you can't use pin 9 as a PWM pin anymore.
Also, setting OCR0A to 15, would mean PWM on pin 10 could only have 15 different PWM values.
So, in essence, pins 9 and 10 can't be used for PWM.

Got it. So in addition to timer, we could get 1Hz (approximate) PWM with duty cycle decided by OCR0A/OCR0B on OC0A/OC0B

Not on OC0A, since you can't change OCR0A without changing the frequency.

You could instead try and use the more capable timer1. You can then use ICR1 to set the TOP. That you can still use OCR1A and OCR1B to set the duty cycle. Though you'd have to change the analogWrite function, to map the 0..255 value to the 0..ICR1 value. (and not use any of the libraries that use timer1, like the servo library)

I think you meant 1kHz, not 1Hz.

Yes, I meant 1KHz. Thanks for correcting. But I just checked ans saw that duty cycle can be changed (Not the frequency) on OC0A. Below is the code outline. First line is inside setup() function:
TCCR0A|=(1<<COM0A1)|(1<<COM0A0);
void loop() {
unsigned int cnt;
for(cnt=0;cnt<255;cnt+=50)
{
OCR0A=cnt;
_delay_ms(1000);
}
    }

Then what was OCR0A=15; supposed to do in your original code?

No, ignore original code. To conclude based on your answer: If we use OCR0A for timer delay, using PWM tied to OCR0A will be difficult (But we can get 50% duty cycle). Otherwise we can control duty cycle though we cannot change frequency.


text:
Using millis() to toggle an LED every 500 milliseconds
I thought the code below would toggle an LED every 500 milliseconds. But it does not work. I'm not able to catch the mistake, which must be very silly.
void setup() {
  pinMode(3, OUTPUT);
}

void loop() {
  unsigned long cnt=millis();
  if(!(cnt % 500)) {
    PORTD^= (1<<PD3);
  }
}

Anyhow the code below works. But why not the previous code?
void loop() {
  static unsigned long prev=0;
  // Note: First time case is not handled. As soon as we want to toggle,
  // we must store millis() in prev. In this case this happens after reset and may not be an issue.
  unsigned long current = millis();
  if((unsigned long)(current - prev) >= 500) {
    PORTD^= (1<<PD3);
    prev = current;
  }
}

A further problem with the first example, not yet mentioned, is that the if() logic is reversed. if( !(cnt % 500) ) is equivalent to if( (cnt % 500) != 0 ), which is true for 499 values and false for only one. The "!" creates the opposite effect to what was wanted.

if (!(millis() % 500)) ...

There are two issues with this. The first, and most obvious, is that the
condition will be true for a full millisecond. During that millisecond
you will be toggling the LED on and off very fast. Whether you end up
doing an odd or even number of toggles is anyone's guess.
The second and less obvious problem is that millis() skips some
values. Roughly one integer every 42 is skipped over. This is because
the millis() counter is incremented once every 1024 µs, getting
24 µs late on each increment. Once all those delays add up to a
full millisecond, millis() catches up by incrementing the counter by
two milliseconds instead of one. This is why you should never condition
something on millis() having one specific value.
The almost correct solution to this problem is shown in Juraj's answer:

if (millis() > next) ...

This is not quite correct because it fails each time millis() rolls
over back to zero. The correct solution is
static unsigned long last;
if (millis() - last >= 500) {
    last += 500;
    ...
}

Because the subtraction follows the rules of modular arithmetic, this is
guaranteed to work across the rollover events.

the overrun is after 49 days. if the sketch has restart scheduled every day the the subtraction is unnecessary

@Juraj: Scheduling restarts is a very contrived way of avoiding the rollover “issue”, which is a non-issue to start with if you do the arithmetic properly.

if it has scheduled restart for other reasons

@Juraj Then when those restarts stop... suddenly you have an unexpected, bizarre situation.

You're in good company with scheduled reboots! https://www.theguardian.com/business/2015/may/01/us-aviation-authority-boeing-787-dreamliner-bug-could-cause-loss-of-control And if you forget it's just a trivial complete electric shutdown of Boeing’s 787 and [potential] “loss of control” of the aircraft.

And don't forget, this is the same crowd that asks people to put timers on their routers so they reboot once a month.

initialize variable last

@Juraj: It's static, therefore it's initialized by the rules of the language. You can add = 0 if you don't trust the language, or = -500 if you want the first iteration to start right away, or even = millis() - 500 if your setup() takes an insanely long time.

Your timing doesn't work, because it has a low probability to read a millisecond that is an exact multiple of 500.
Do it this way:
  static unsigned long next = millis();
  if (millis() - next > 500) {
    next += 500;

void loop() {
  unsigned long cnt=millis();
  if(!(cnt % 500)) {
    PORTD^= (1<<PD3);
  }
}

At every iteration, cnt is set with the number of milliseconds elapsed since you turned on the Arduino... So this is not gonna work. At all. What you need is two variables. One that holds the last millis() count when you blinked the LED, and for the current millis() count:
unsigned long lastCount;
void setup() {
  pinMode(3, OUTPUT);
  lastCount=millis();
}

void loop() {
  unsigned long cnt=millis();
  if((cnt-lastCount)>499) {
    PORTD^= (1<<PD3);
    lastCount=cnt;
  }
}

I always use this
if((millis()/500)%2==0))
{
    PORTD |= (1<<PD3);
}
else
{
    PORTD &= ~(1<<PD3);
}

It first divides millis by 500ms. So you get the number of 500ms chucks (since the Arduino started). Then you check to see if this number is even. If so, turn the led pin on. Else turn the led pin off.

Division is a computationally expensive operation on most embedded micros.  You should avoid it if possible.


text:
Arduino Analog Input: why the weird fluctuation?
I am using an Arduino Uno. analogRead(A0) (or whichever channel I use) returns 0 when it is grounded with Arduino Gnd, and 1023 when connected to Arduino 5v. But when I connect it to a current sensor (ACS712) it is always fluctuating like this:

0, 0, 0, 0, 0, 0, 1023, 1023, 1023, 1023, 1023, 441, 446, 0, 0, 0, 0, 1023, 1023...

I also tried it with a potentiometer (10K) and analog joystick: the results are the same. I tried changing different power supplies (both Arduino's and the sensor's (ACS712, potentiometer, joystick)). I even tested it on an Arduino Mega, but no luck. Such extreme fluctuation are making no sense to me. Kindly help me what could be the issue.
My wiring diagram is attached to this post. And I use an external supply to the ACS712. Is it possible that Static electricity is causing this issue?
Code:
void setup() {
  Serial.begin(9600);
}

void loop() {
  float value = analogRead(A0);
  Serial.print("Raw:");
  Serial.println(value);
  delay(500);
}

Thanks.

please add a schematic of your connections

You say you are supplying the ACS712 from an external supply.  Do you have the Arduino ground and the external supply ground connected?  A full schematic would be more useful because possibly the problem is not in the part shown.

Maybe you are just measuring an AC current, in which case the “fluctuations” are normal and expected.

@Mark Smith I am not using Arduino Gnd ACS712 is using Gnd from External PowerSupply....From Arduino I am only using its Analog Pin 0

@Edgar Bonet I am using DC supply as current source to ACS712

You need to connect together the grounds from your external power supply and the Arduino.
At the moment the two devices are floating - there's no commonly-agreed 0v point.

You are awesome...Thanks for your help much appreciated. Solved my problem

I had a similar issue with fluctuating values. Make sure you are setting in your code the analog PIN as INPUT pin. On some boards you have to specify it explicitly, like this:
pinMode(A1, INPUT);


text:
Fatal Exception Error on ESP8266 + Arduino
When I was trying to blink an LED using ESP8266, I had an issue with it. After successfully uploaded the code (https://diyhacking.com/esp8266-tutorial/), the blue LED stayed on & when I opened the serial monitor using Arduino IDE 1.6.12, I only saw "Fatal Exception" error (showed in the picture). I couldn't see how the code works and the worst thing was I couldn't even try the AT command.
The connections:
Arduino <--->   ESP8266 (ESP-07)
Tx  <--->   Tx
Rx  <--->   Rx
GND <--->   GPIO0
GND <--->   GND
3.3v<--->   CH_PD
3.3v<--->   VCC
            GPIO2 -> LED

I have been trying to troubleshoot this issue but haven't got the solution yet. I am afraid there is an issue with the firmware or the worst situation, I spoiled my ESP8266.

GPIO_0 is connected to GND only while programming/uploading code; for normal operation it should be (at least initially) connected to VCC(3.3v).
I believe the same goes for GPIO_02.
Try connecting them both to VCC and then connect GPIO_2 to the LED.

don't forget to add a resistor for your LED :)
220 should be more than enough.

I have tried your solution yet the result is still the same. perhaps I am just going to get the new one

Looking at your serial monitor window it shows "Geuino Uno". I think you forgot to change the target of the compiler to "Generic ESP8266" like shown in the how-to and you probably uploaded bad code to your module.

I used the correct board "Generic ESP8266"

If you are getting fatal error exception like this:
Exception (3):
epc1=0x401003e9 epc2=0x00000000 epc3=0x00000000 excvaddr=0x4000cbd9 depc=0x00000000

In infinite loop in your Serial Monitor of the Arduino IDE then go to this link, download the software, and follow the procedure and erase the flash memory to solve the error.
This does not solve fatal error that occurs due to your program but in case your device goes in such condition that it can't be able to access program memory then it will work and try at least one time to solve the problem.
This is the procedure to hard reset the NodeMCU (https://www.youtube.com/watch?v=MHrm7axsImI&t=146s):

Install latest Python version in your PC. (https://www.python.org/downloads)
Open cmd prompt as administrator.
Go to C:\Program Files or C:\Program Files (x86)->python (your version)->Script. For this type cd c:\Program Files (x86)\python(your version)\Script then press enter.
Type pip install esptool.
Download ESPlorer.zip (v 0.2.0-rc6) from https://esp8266.ru/esplorer
Extract the downloaded file.
Open the executable jar file.
Go to NodeMcu firmware site (https://github.com/nodemcu/nodemcu-firmware/releases) and download file (nodemcu_float_0.9.6-dev_20150704.bin) and copy this file into the C:\Program Files (x86)/python(your version)/Script folder.
Now in cmd prompt just type:
esptool.py --port COM(your port no.) --baud 115200 erase_flash

And press enter.

Note: you can see your NodeMCU board's port number in Device Manager .


text:
Output specific value using port manipulation
How can I output a specific value on a pin using port manipulation?
Example: I want to use this code but without any arduino functions, just with port manipulation:
for (int i = 0; i < 255; i++){
analogWrite(11, i); //write the i value to pin 11
}

I want to replace the analogWrite function with register manipulation. Is that possible?

Of course, how do you think analogWrite does it?

@NickGammon Alright, I made some quick research and I am back from where I started. I must actually generate a PWM on that PIN and change the duty cycle acordingly ( basically what analogWrite does). Am I right?

Have you read the ATmega328 datasheet? This is where you have to start. Taking a look at the implementation of analogWrite() might help too.

The analogWrite function is just an interface to setting up the hardware timers to do PWM (pulse-width modulation). I have a page about timers which you may find helpful.
Depending on which pin you want to output the PWM to, the registers will be slightly different. Here is one example from my page:
const byte OUTPUT_PIN = 3;  // Timer 2 "B" output: OC2B

const byte n = 224;  // for example, 1.111 kHz

void setup()
 {
  pinMode (OUTPUT_PIN, OUTPUT);

  TCCR2A = bit (WGM20) | bit (WGM21) | bit (COM2B1); // fast PWM, clear OC2A on compare
  TCCR2B = bit (WGM22) | bit (CS22);         // fast PWM, prescaler of 64
  OCR2A =  n;                                // from table
  OCR2B = ((n + 1) / 2) - 1;                 // 50% duty cycle
  }  // end of setup

void loop() { }

How can I output a specific value on a pin ?

I should point out that the only values you can output are +5V or 0V. There is no provision for outputting (say) 3.7V. The only way you can sort-of do this is by using PWM and then running the result through an RC filter. There is an example on my page about op amps.
An example circuit could be:

This uses a resistor and capacitor to filter out the "ripple" in the PWM, giving you a reasonably smooth output voltage, proportional to the PWM duty cycle.
For a larger range of output values a rail-to-rail op-amp would be preferable.


text:
ESP-01 won't start correctly
I'm trying to connect my Arduino Uno to an ESP-01 module, but I can't get it to start correctly. All I can get out from the ESP-01 is an "invalid" message when it is enabled. Can anyone please help? Additional information can be found below.
Here's my configuration:

Arduino connected to a computer via USB cable (serial connection working)
ESP-01 connected to the same UART connection, TX from Arduino is lowered to 3,3V with resistors
ESP-01 powered with external battery + capacitor to ensure sufficient current
I've tried all different configurations with GPIO0 and GPIO2 connecting them to ground and 3,3V, with and without resistors.
I've tried 3 different ESP modules

Here's how things work:

Arduino sends back every received UART transmission so that I can monitor the whole thing.
I can send messages to Arduino from a terminal on the PC and Arduino responds.
I can send messages from Arduino by pressing a button and the messages can be seen on the terminal.
When I send AT\r\n from Arduino I can read it on the terminal but nothing happens on the ESP-01.
When I send exactly the same message from the terminal, the blue light on ESP flashes but there is no response from the ESP. Arduino sends that message back to terminal of course.
When I connect CH_PD to 3,3V the ESP gives a message: Ai-Thinker Technology Co. Ltd.
invalid
The baud rate is correct (115200) since I can only read that invalid message on this rate

Sharing the hardware UART between the terminal and the ESP generally does not work well. You'll be much better off to add a SoftwareSerial port on another pair of pins to talk the the ESP.

This is one of the common problem that you have got.... If I am not wrong then you are unable to upload program to the esp.... I have a solution please  try that it may work for you...... Start the uploading process and unplug the power and plug the gpio 0 to groung and when you see the green to be complete plug the power and at the same time unplug gpio 0.... It may not work at first try... But keep trying, this method worked for me


text:
Why does my Arduino IDE hang/crash so often?
I've traditionally used a text editor with avr-gcc and makefiles for working with Arduino boards. I'm now trying to develop projects for the wider Arduino user-base, so I am trying to use the Arduino libraries and common IDEs for ease of use.
I started using Stino, but then found out that the Arduino IDE has some toolchain "quirks" that mean I will need to test everything in Arduino IDE expressly.
Since starting to use it more, I have found it frequently hangs or crashes. The triggers for this are:

Creating a new sketch takes about 15s, and shows me the OS X beach
ball.
Saving a sketch takes about 15s.
Going to File->Examples frequently crashes the IDE - I need to force quit.
Going to
File->Sketchbook always crashes the IDE.
It sometimes randomly hangs.

I don't have any other stability issues and other Java based IDEs like Pycharm work flawlessly.
I have installed numerous libraries, including the entire Teensyduino suite (which is a lot of libraries!). Outside of that, no changes have been made.
Is this a common issue? Is there any logging or anyway I can try and work out what is causing this issue?
This is happening with:
 - Arduino 1.05
 - Arduino 1.55
I have tried uninstalling and reinstalling.

I think the best way to report and have this issues fixed is by opening an issue on arduino's github https://github.com/arduino/Arduino/issues

I find it's sometimes a little slow to startup on my Mac, but I don't remember seeing any hangs/crashes like you describe. Which version of OS X are you running?

Mavericks, latest update.

I've only been using the arduino software package on Mac for less than a year. I've never used it on windows. I've run it under ML and now mavericks. In that time I have never had the arduino IDE crash. I habitually leave it open for days only restarting (or open and run a new instance) as needed. Have you made any hardware mods to it as in added boards or any tweaking?

Are you using up much RAM? What are the specs of your computer?

It's a late 2013 Macbook Pro with 16GB. Mavericks always reports all RAM used, but memory pressure is low and I have headroom to run several VMs and much more complex IDEs.

Are you using the new version 1.5.6-r2? Many things are said to have been improved compared to the previous 1.0.5-r2 version. Given that I am on Win only, I cannot confirm those slow experiences.

Should this question be closed? This has all the makings of a bug, and we are not a bug tracking site.

It can be, but the question "Is there any logging or anyway I can try and work out what is causing this issue?" hasn't been answered.

Just report it to Arduino.
You don't really have any other option. I've been waiting to answer this question until I was sure that no one here knew the answer. You don't really have any other option.
This seems like a bug. We're not Arduino developers or a bug tracking site. We can only do so much here. Even if it was confirmed a bug and we fixed it, there's only so much that can be done without submitting a report.

BEFORE YOU SUBMIT A REPORT:

I'd try copying out the libraries from Arduino. So many libraries
might make Arduino IDE somewhat heavier. I don't know if it'll really
affect the sluggishness but it's worth a shot.
The only other thing that I can think of, besides RAM (which you
already said wasn't an issue) and the libraries, is some sort of
cache/temporary file. Try reinstalling Arduino, even if you haven't,
and also I'd try using the beta 1.5.6-r2
version. It has to be pretty
stable for it to be the only version that supports the YUN and DUE.
Both have been out for a considerable amount of time with this
software, so I'd imagine that it's pretty stable minus a few issues.

Many things are said to have been improved compared to the previous 1.0.5-r2 version.

It'd be stupid not to try the newer version.

I've just tried 1.5.6-r2 and the same issue exists (it wasn't listed as the beta on the downloads page when the question was initially asked). Nothing in the release notes suggests that any IDE changes have been made between 1.5.5 and 1.5.6-r2 though.

I guess the bigger part of the question is "Is there any logging?". Without any detail to go on, the bug report will be lost in the thousands of others.

@Cybergibbons Have you tried my other ideas? Temporarily removing the libraries?

Yes, no difference.

For debug and logging you can use the Mac Console app, it will show any errors that come up from the App. You might need to filter for Arduino App related messages though.


text:
Arduino stops working after some receivings from RF
I made a sketch that receives an rgb code from a remote Arduino using nrf24l01 and while it works for the first receivings then it stops working. I placed a testing Serial.println in the loop to test if Arduino stops to work completely or it doesn't receive any other data. Finally, I understood that it continues to work but it doesnt receive more data. Bellow is my code:

#include <RF24Network.h>
#include <RF24Network_config.h>
#include <Sync.h>

#include  <TimerOne.h>
#include <SPI.h>
//#include <nRF24L01.h>
#include <RF24.h>
RF24 radio(8,10);
RF24Network network(radio);
volatile int i=0;
volatile int d=0;     // Variable to use as a counter
volatile boolean zero_cross=0;  // Boolean to store a "switch" to tell us if we have crossed zero
int AC_pin= 4;    // Output to Opto Triac pin
int dim = 0;  // Dimming level (0-128)  0 = ON, 128 = OFF
int freqStep = 65;

struct payload_rgb
{
  unsigned int red;
  unsigned int green;
  unsigned int blue;
};
struct payload_lightuv
{
  unsigned int light;
  unsigned int uv;
};
RF24NetworkHeader header;
payload_rgb payloadrgb;
payload_lightuv payloadl;
void setup() {
  // put your setup code here, to run once:
  pinMode(AC_pin, OUTPUT);// Set AC Load pin as output
  pinMode(9, OUTPUT);// Set AC Load pin as output
  pinMode(5, OUTPUT);
  pinMode(6, OUTPUT);
  attachInterrupt(0, zero_cross_detect, RISING);  // Choose the zero cross interrupt # from the table above
  Timer1.initialize(freqStep);                      // Initialize TimerOne library for the freq we need
  Timer1.attachInterrupt(dim_check, freqStep);
  Serial.begin(115200);
  radio.begin();
  network.begin(90,01);
}

void loop() {
  network.update();
  while ( network.available() )
  {
    Serial.println("Rec");

    network.peek(header);
    if(header.type=='r'){
      network.read(header,&payloadrgb,sizeof(payloadrgb));
      analogWrite(6,payloadrgb.red);
      analogWrite(9,payloadrgb.green);
      analogWrite(5,payloadrgb.blue);
    }
    if(header.type=='l'){
      network.read(header,&payloadl,sizeof(payloadl));
      dim=payloadl.light;
    }
}
Serial.println("!"); //this is the test println
}
void zero_cross_detect() {
  zero_cross = true;               // set the boolean to true to tell our dimming function that a zero cross has occured
  i=0;
  digitalWrite(AC_pin, LOW);       // turn off TRIAC (and AC)
}
void dim_check() {
  if(zero_cross == true) {
    if(i>=dim) {
      digitalWrite(AC_pin, HIGH); // turn on light
      i=0;  // reset time step counter
      zero_cross = false; //reset zero cross detection
    }
    else {
      i++; // increment time step counter
    }
  }
}}

Additionally, this Arduino controls an ac dimmer. Bu I have not done it yet.
How can I fix the problem without removing any feature?

Is it maybe running out of memory? I am not familiar with network.read but does this memory get free'd ?

Why network.read should use memory? The only thing that uses memory are the variables and structures. And even if it used, shouldn't the arduino stop completely?

I think it would have to buffer that input and if it is allocating memory each time and not cleaning up, maybe its running out. But this is just a guess. ..."If you run out of SRAM, your program may fail in unexpected ways; it will appear to upload successfully, but not run, or run strangely"...http://www.arduino.cc/en/Tutorial/Memory

So that would be library's problem?

It's not likely, I thought there was something that you needed to call to free it but it doesn't seem to be the case. Don't you need to declare the variables that are modified in the interrupts as volatile?

Will that solve the problem?

Try reducing memory footprint, see if that helps.

Try resetting the nrfs with the below answer: https://arduino.stackexchange.com/a/54604/35167

See this. https://arduino.stackexchange.com/questions/55042/how-to-automatically-reset-the-nrf24l01-with-code


text:
DB:NO RESP Using inet.httpPOST on loop()
I'm using SIM900 module + arduino uno + gsmlib.org library.
I'd like to send a string to endpoint on my API , and it worked correctly for the first time when I using inet.httpPOST function in setup(), but... in loop(), when I call that function again, it doesn't work. On serial monitor I get:
ATT: ERROR
RIC:
ERROR
DB:STARTING NEW CONNECTION
ATT: SHUT OK
RIC:
SHUT OK
DB:SHUTTED OK
ATT: OK
RIC:
OK
DB:APN OK
ATT: OK
RIC:
OK
DB:CONNECTION OK
ATT: ERROR
RIC:
xxx.xxx.xxx.xxx

DB:ASSIGNED AN IP
status=ATTACHED

http://api.com.br/mystring

ATT: OK
RIC:
OK
DB:RECVD CMD
ATT: CONNECT OK
RIC:
OK
ATT: OK
RIC:
CONNECT OK
DB:OK TCP
ATT: >
RIC:
>
DB:>
ATT: SEND OK
RIC:
SEND OK

DB:SENT

http://api.com.br/mystring

ATT: OK
RIC:
xxx.xxx.xxx.xxx
ERROR
ALREADY CONNECT
DB:NOT CONN
ATT: OK
RIC:
ERROR

ALREADY CONNECT
DB:NOT CONN
ATT: OK
RIC:
ERROR

ALREADY CONNECT
DB:NOT CONN

How can I send data to my API continuously on loop() Could someone help me?
Following is my code (SOLVED):
#include <SoftwareSerial.h>
#include <TinyGPS++.h>
#include <inetGSM.h>

InetGSM inet;
TinyGPSPlus gps;
SoftwareSerial serialGps(11, 10);

/**
    setup
*/
void setup() {
  // Serial connection.
  Serial.begin(19200);
  Serial.println(F("Starting App Arduino"));

  // Turn on GPRS
  powerUpGprs();

  // Start configuration of shield SIM900 with baudrate and  connect to internet.
  if (gsm.begin(9600)) {
    Serial.println(F("\nstatus=READY"));

  // Start configuration of shield GPS NEO-6M with baudrate.
  serialGps.begin(9600);

  // Mensure and show memory usage
  Serial.println(F("\nMemory usage"));
  Serial.print(freeRam());
}

/**
   loop
*/
 void loop() {
  serialGps.listen();
  while (serialGps.available() > 0)  {
    if (gps.encode(serialGps.read())) {
      // Get GPS position and send To API
      gsm.listen();
      // if sim900 started, connect to internet
      Serial.print(F("\r\n"));
      Serial.print(F(" CONNECT TO INTERNET \r\n"));

      // GPRS attach, put in order APN, username and password.
      if (inet.attachGPRS("zap.com.br", "zap", "zap"))
        Serial.println("status=ATTACHED");
      else Serial.println("status=ERROR");
      delay(1000);
      // Read IP address.
      gsm.SimpleWriteln("AT+CIFSR");

      Serial.print(F("\r\n\r\n"));
      Serial.print(F(" GET GEOLOCATION & SEND TO API \r\n"));
      // get geolocation
      String geo;
      geo.concat("lat=" + String(gps.location.lat(), 6));
      geo.concat("&lng=" + String(gps.location.lng(), 6));
      geo.concat("&spd=" + String(gps.speed.kmph()));
      geo.concat("&gps.uuid=1");
      // send2Api
      Serial.println(geo.c_str());
      Serial.print(F("\n"));
      gsm.SimpleWriteln("AT+CIFSR");
      inet.httpPOST("api.com.br", 80, "/geolocations", geo.c_str(), "", 100);
    }
  }
}

/**
   mensure memory usage
*/
int freeRam() {
  extern int __heap_start, *__brkval;
  int v;
  return (int) &v - (__brkval == 0 ? (int) &__heap_start : (int) __brkval);
}

/**
   Power up
*/
void powerUpGprs() {
  pinMode(9, OUTPUT);
  delay(100);
  digitalWrite(9, HIGH);
  Serial.println(F("\nPower Up SIM900!"));
}

Thank You!!!

Like I told you before, you have 2 instances of SoftwareSerial active, but you're allowed to listen to only one at a time (implementation rules). So you have to alternate between calling listen() on each instance; any data arriving at any port while its not the active port will be discarded. inet.httpPOST() worked in setup() because you called the function before begin()ing serialGps. Calling serialGps.begin() immediately made serialGps the active port, severing communication with the modem.

Add this line to SIM900.h in the library, under the public methods:
void listen();

Add this method to SIM900.cpp:
void SIMCOM900::listen(){
   _cell.listen();
}

Save the files and add gsm.listen() right before gsm.SimpleWriteln("AT+CIFSR"); in loop().
Re-initialize GPRS, like you did in setup() with attachGprs(), right after gsm.listen() in loop().
Make serialGps.listen() the last  statement in loop() immediately after the inet.httpPOST() call. Use braces to enclose the body of the while loop.

Hopefully this should solve your problem.

Wow, I had forgotten it, in fact now I got it.
Ok I made the update on libraries SIM900.h and SIM900.cpp  but now he sent only once.
http://api.com.br/geolocations
DB:>
ATT: SEND OK
RIC:
SEND OK
DB:SENT
http://api.com.br/geolocations
ATT: OK
RIC:
ERROR
ALREADY CONNECT
DB:NOT CONN
ATT: OK
RIC:
ERROR

@RobsonFagundes i think i know why... i will edit my post.

@RobsonFagundes if it still doesnt work, update the code in your question. Also show the results you're getting at the server

I update the code and results on my question.

@RobsonFagundes i edited my answer already. Read the last step again and try it

continues to send only once...

@RobsonFagundes place it immediately after the inet.httpPOST in loop()

@RobsonFagundes did it finally work? If it didnt, try attachGprs() again, right after gsm.listen(), just like u did in setup()

I tried add attachGprs() with loop and WORKS!
Too bad it takes about 20 seconds for each post. I still need to reduce this time. But the important thing that worked! I'm so excited. Thank you without your help I would be lost!
You Rock @TisteAndii!!!

@RobsonFagundes cool...you're welcome...do u mean it takes 20 secs for the inet.httpPOST alone, or does it include the GPRS attach and so on?

I solved.... my solution https://github.com/robsonfagundes/Arduino-GprsSIM900andGpsNEO-6M
I made example to help other developers who are facing the same problem or a similar problem with Gprs SIM900 and Gps NEO-6M working together.

I had similar problem. I have added gsm.begin() method at the end of the loop, and it has solved my problem!!
Seems like you can't send multiple http requests with single gsm session.
Relevant parts of setup() and loop() methods are shown below:
void setup()
{

Serial.begin(9600);
Serial.println("GSM Shield testing.");

if (gsm.begin(2400)){
  Serial.println("\nstatus=READY");
  started=true;
}
else Serial.println("\nstatus=IDLE");

}

void loop()

{
   if(started){
      if(inet.attachGPRS("internet.wind","",""))
        Serial.println("status=ATTACHED");
      else
        Serial.println("status=ERROR");

      if(inet.httpPOST(server,port, path,parameters,msg, 50)){
          Serial.println("Data sent to server succesfully!");
      }
      else{
        Serial.println("Failed to send data to the server");
      }
 }

 if (gsm.begin(2400)){
  Serial.println("\nstatus=READY");
  started=true;
}
else Serial.println("\nstatus=IDLE");

};

No, your premise here is wrong.  You should be properly managing the instance you have, not creating new ones.