text:
How to control 2 servos at same time in sync?
For overcoming torque issues, I have attached 2 identical servos on a certain part of my robot arm and because I saw someone do the same.
Now, while writing code I realize:
#include <Servo.h>
...
...
shoulder1.write(map(analogRead(p1), 0, 1023, 0, 179));
shoulder2.write(map(analogRead(p1), 0, 1023, 0, 179));
...

will turn shoulder1 by 20* and then shoulder2 by another 20*, ie. an overall turn of 40*; that too with too much load on servos, as the other servo would be inactive at the time first is active.
I want to achieve 20* fully-sync.ed turn on both servos, how do I accomplish this? Any arduino libraries or walkthrough?

Can I possibly move them both at the same time - something like multithreading on arduino? Here's what I tried:
void rotateTwoServoInSync(int angle) {
    for(int i = 0; i<angle; i++) {
        shoulder1.attach(9);
        shoulder1.write(i);
        shoulder1.detach();
        shoulder2.attach(10);
        shoulder2.write(i);
        shoulder2.detach();
    }
}

Will it work? Is this approach recommendable?

you do know that all of that code executes WAAAAY faster than the response time of the servos, and they will, for the most part, operate at the same time?

if you write both outputs at the same time (two lines of code sequentially) it is enough for them to operate in sync.

If you have two RC servos that are always required to move together you can simply connect both control inputs to a single output.

So do I need a NPN transistor to amplify the signal?

Nope. Just connect and drive them together.

Spehro's answer is the most obvious. But note that there is no such thing as identical servos. You may stress them if you connect them through a stiff connection.
If you want to have two mechanical parts make the same movement the proper solution is to connect them mechanically, rather than have two servos doing the same action.

analogRead() and map() are slow; only perform them once.
unsigned char rot = map(analogRead(p1), 0, 1023, 0, 179);
shoulder1.write(rot);
shoulder2.write(rot);

I will implement your advice - but still if rot is 150* then wouldn't shoulder1's 150* movement w.r.t. shoulder2's stationary position break/burn the setup?

Only if your setup is made of diamond. Otherwise it will have plenty of flexibility to handle the few hundreds of nanoseconds of difference.

I don't know if I agree to that - but torque issue is still unsolved.

Then your servos aren't identical.

To operate two or more servos at the same time you need to interpolate their movements, first moving one servo a little, then moving the next one, back and forth until all servos arrive at their destination point. I haven't seen a library yet that accomplishes this for you so you probably need to write your own routine. Here is a project where I interpolated three servos and includes the code: https://www.instructables.com/id/MonkeyBot-3-Servo-Climbing-Robot/


text:
Do multiple ultrasonic sensors need an external power source?
So maybe it's a very low class form of question, but please bear with me. I'm working on a project with 7 HC-SR04 ultrasonic sensors connected to one Arduino. I tried to unify the trigger and echo pin, but the sensing isn't good enough, so I dropped the Uno and convert it to Mega. My question is, do I need external power source for those 7 Sensors? And how do I connect all of them? Thanks

Well, according to the datasheet the "working current" is 15mA.  Even if you had all 7 working at once, which I doubt you will - you'll be working through them in sequence I guess - that would be just 105mA - way below the 800mA the Arduino's on-board regulator can supply, and only a fifth of what a USB port can provide.
The datasheet doesn't mention the quiescent (idle) current, but it will be a tiny fraction of that 15mA and so can mostly be ignored.  Running the sensors in sequence, which is the most likely scenario, would use about the same amount of current as if you had 1 sensor - or 20 sensors.  Most of the current consumption would be while you are actively producing an ultrasonic chirp.
So no, you don't need an external power supply to run them all - just take them all from the Arduino's 5V pin.

Well, I'm working on an Obstacle avoidance, but yeah, I can only make a sequential code for all of them. Is it possible to make them work all at once?
But, either way, I still didn't need the external power supply, right?
Thanks for your answer though :D

Either way it's still way below what the Arduino can supply, so no need for an extra supply, no.

You will probably not have any kind of problem with the Arduino power source, while in the test bench. When using it for the Drone/Bot you seem to be working, make sure to have a stable power source to the Arduino, and, if possible, let your sensors have their own energy input.
I had previous experiences with the sensors not working properly because the Arduino was not getting enough energy through the Arduino's pins when mounted.

source: Stack Exchange

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

sort: votes


text:
Sending serial data to Processing
I have a question about using the Arduino and Processing. I want to build a touch sensor using aluminum foil and connect it to an interface built in Processing. However i've come across a problem. I don't know how to send the serial data from the Arduino to Processing. This is the code I'm using to get the sensor value from the aluminum foil:
#include <CapacitiveSensor.h>

CapacitiveSensor   cs_4_2 = CapacitiveSensor(4,2);

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

void loop(){
  long start = millis();
  long total1 =  cs_4_2.capacitiveSensor(30);

  Serial.print(millis() - start);
  Serial.print("\t");

  Serial.print(total1);
  Serial.print("\t");
  Serial.print('\n');

  delay(100);
}

The foil is connected to dig pin 4 with a resistor of 1M in between and to dig pin 2 with a resistor of 1K. Pin 4 is the send pin, pin 2 is the receive pin. It all works just fine, in the serial monitor in the Arduino software I get the value of the time between refreshes and the sensor value. But how do I use this sensor value in a Processing sketch? I thought of maybe using Firmata on the Arduino, but then I wouldn't know how to use the CapacitiveSensor library and get the sensor values. Does anyone know how to get this to work? Help would be greatly appreciated!

Try to use this code:
// Graphing sketch

import processing.serial.*;

Serial myPort;        // The serial port
int xPos = 1;         // horizontal position of the graph

void setup () {
// set the window size:
size(400, 300);

// List all the available serial ports
println(Serial.list());
// I know that the first port in the serial list on my mac
// is always my  Arduino, so I open Serial.list()[0].
// Open whatever port is the one you're using.
myPort = new Serial(this, Serial.list()[0], 9600);
// don't generate a serialEvent() unless you get a newline character:
myPort.bufferUntil('\n');
// set inital background:
background(0);
}
void draw () {
// everything happens in the serialEvent()
}

void serialEvent (Serial myPort) {
// get the ASCII string:
String inString = myPort.readStringUntil('\n');

if (inString != null) {
// trim off any whitespace:
inString = trim(inString);
// convert to an int and map to the screen height:
float inByte = float(inString);
inByte = map(inByte, 0, 1023, 0, height);

// draw the line:
stroke(127,34,255);
line(xPos, height, xPos, height - inByte);

// at the edge of the screen, go back to the beginning:
if (xPos >= width) {
xPos = 0;
background(0);
}
else {
// increment the horizontal position:
xPos++;
}
}
}

Also look at: http://www.arduino.cc/en/Tutorial/Graph

SparkFun has a tutorial where they explain in great detail how to create a project where your Arduino communicates with Processing on your PC.

You're already half way there - you're sending the data from the Arduino.  All you need to do now is read up on how to use Serial in Processing (hint: Arduino is based on Processing, so you should already know most of it) in order to read what you're sending.

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


text:
How to make an RC mixer with the arduino
I want to make a RC mixer mixing two channels of a receiver.
What I have: a delta model plane, two servos, a receiver and a Arduino Nano.
So I'd like to mix the aileron (two channels) with the elevator(one channel).
EDIT: What I've done: I read the input of the receiver and wrote it to the servos. The problem: The servo stutters and the arduino displays false inputs.
int pin = A0;
int pin1 = A1;
unsigned long duration;
unsigned long dur;

unsigned long duration2;
unsigned long dur2;

#include <Servo.h>

Servo myservo;
Servo myservo2;

void setup()
{
  Serial.begin(9600);
  myservo.attach(9);
}

void loop()
{
  duration = pulseIn(pin, HIGH);
  dur = duration;
  Serial.println(dur);
  myservo.writeMicroseconds(dur);
  delay(50);
//  duration2 = pulseIn(pin1, HIGH);
//  dur2 = duration2-980/4-200;
//  Serial.println(dur2);
//  myservo2.write(dur2);
}

Apparently no access to google?

Can you give me a good instruction how to do that???

"This question does not show any research effort" is a reason for downvoting. Please show us what you tried and how far you got.

That is NOT how we do it. Flying a delta plane should not require anything between the receiver and servos, you just have to program the radio correctly. Almost all the popular RC radios today have built-in delta mixing. The SAFE system planes from E-Flite do the mixing on-board, but it doesn't require any additional hardware.

You do not need to use long for values from pulseIn, using int will be sufficient.
Your code is not complete, at least there is a missing '}' at the end of setup.
The slower the baud rate (9600) actually the more it interferes with timing code, to a point.  PWM is all timing code.  I would suggest 57,600.
You never set the servos to any pins.  And is using Servo lib needed? I have always used analogWrite with no problems.
You are not using parenthesis on your math (currently commented). It will not give you the result you expect. But you are somewhat on the right track, subtract 1500 from each pulse read, that will give you -/+ range. How you mix that depends on how your radio is setup (servo reversing, which channel is which). Keep in mind ailerons is 1 channel, so left aileron = -rightAileron.  Elevator up = that + elevator.  so;
aileronLeft = airleronChannel + elevatorChannel
aileronRight = -airleronChannel + elevatorChannel
You do realize this a $3 part?
update: I have always used analogWrite, but I also always use good equipment. I see cautions that cheapo servos might be damaged with analogWrite. You can read more here. It has always worked for me.

How to disable the bad stuttering??  :( And can you say me how to use a servo with analogWrite()? Thank you!


text:
Arduino-uno sending email with Hotmail
I want to get emails read from a Hotmail account using an Arduino Uno. Is there a way to do it with SSL or is there a way to disable SSL?
#include <SPI.h>
#include <Ethernet.h>
// Use comments to enable or disable this define for debug messages
#define DEBUG_POP
// Use comments to enable or disable the deleting of the mail
#define ENABLE_DELETE_POP

// The mac address must be an unique number
// A mac generator is used:
//   http://www.miniwebtool.com/mac-address-generator/
byte mac[] = { 0xDE, 0x36, 0x5F, 0x0A, 0x19, 0x83 };
// change network settings to yours
IPAddress ip(192, 168, 1, 117);
IPAddress gateway(192, 168, 1, 1);
IPAddress subnet(255, 255, 255, 0);

// Set the server POP3 address, the port, the user and password.
// The POP3 mail server is something like this:
//     mail.yourdomain.com, pop.yourdomain.com, pop3.yourdomain.com
// Using PROGMEM for these causes a fail when trying to connect and log in.
const char pop_server[] = "pop3.live.com";
const int  pop_port = 995;
const char pop_user[] = "xxxxxx@hotmail.com";
const char pop_pass[] = "xxxxxx";

// The number of milliseconds timeout for parseInt() and find().
// The response time for the Server can still be 10 seconds.
#define POP_TIMEOUT 10
#define POP_TIMEOUT_DEFAULT 1000

EthernetClient client;

void setup()
{
    Serial.begin(9600);
    Serial.println(F("\nArduino POP3 email reader"));

    pinMode(13, OUTPUT);     // the system led is used for testing

    // When the Ethernet Shield is used, there is also a SD card connected
    // to the SPI bus. Disable the SD card with chip select at pin 4.
    pinMode(4, OUTPUT);
    digitalWrite(4, HIGH);

    // Start Ethernet. Use only the 'mac' parameter for DHCP
    // Use 'mac' and 'ip' parameters for static IP address.
    //  Ethernet.begin( mac, ip);
    //  Ethernet.begin( mac, ip, gateway, gateway, subnet);
    if (Ethernet.begin(mac) == 0)
    {
        Serial.println("Failed to configure Ethernet using DHCP.");
        // no point in carrying on, so do nothing forevermore:
        while (1);
    }
    Ethernet.begin(mac, ip, gateway, gateway, subnet);
    // print your local IP address.
    Serial.println(F("Ethernet started."));
    Serial.print(F("Local IP = "));
    Serial.println(Ethernet.localIP());

    Serial.println(F("Press 'c' to check mail."));
}

void loop()
{
    // Create a buffer to receive the commands in (that is the Subject of the mail).
    char buffer[32];

    byte inChar = Serial.read();
    if (inChar == 'c')
    {
        // The getEmail gets the text of the mail Subject into the buffer.
        // The valid number of received characters are returned.
        // If the return value is < 0, it is an error.
        int n = getEmail(buffer, sizeof(buffer));

        if (n < 0)
        {
            Serial.print(F("Email POP3 failed, error = "));
            Serial.println(n);
        }
        else
        {
            if (n == 0)
            {
                Serial.println(F("Ready, nothing to do."));
            }
            else
            {
                // 'n' is > 0, a command received.
                Serial.print(F("Email checked, Command = \""));
                Serial.print(buffer);
                Serial.println(F("\""));

                // Check the commands.
                //
                // At this moment, a single command 'L' is used to set system led on or off.
                //    L=1   (set led on)
                //    L=0   (set led off)
                if (buffer[0] == 'L' && buffer[1] == '=')
                {
                    digitalWrite(13, buffer[2] == '0' ? LOW : HIGH);
                }
            }
        }
    }
}

// getEmail
// --------
// Find an email on a mail server, using POP3.
// The Subject should start with "ARDUINO " and the text
// after that is copied into pBuf.
//
// The data in pBuf is only valid if the return value is not an error
// (an error is return value less than zero).
//
int getEmail(char *pBuf, int nBufSize)
{
    // nBytes is the number of bytes that is returned by getEmail.
    int nBytes = 0;

    // Connect to server
    // client.connect returns '1' if okay, or negative number if error.
    //    SUCCESS 1
    //    0     (error, unknown timeout, perhaps an error in the library)
    //    TIMED_OUT -1
    //    INVALID_SERVER -2
    //    TRUNCATED -3
    //    INVALID_RESPONSE -4
    //    -5    (there is no mail server at that IP address and port)
    // The string for the server must be a normal string in sram, no PROGMEM allowed.
    int nError = client.connect(pop_server, pop_port);

    // During testing, a value of zero was sometimes returned.
    // This is not according to the documentation and it is an error.
    // Therefor the non-error value '0' is turned into a negative number to
    // indicate an error.
    if (nError == 0)
        return(-200);

    // Only a value of 1 is okay.
    if (nError != 1)
        return(nError);

#ifdef DEBUG_POP
    Serial.println(F("connected"));
    //Serial.println(nError);
#endif
    // The server should respond with "+OK" and maybe more text after that.
    // Check if "+OK" can be read.
    // The parameter 'true' is to read also everything after the "+OK".
    if (!readOk(true))
        return -102;

#ifdef DEBUG_POP
    Serial.println(F("command USER"));
#endif
    client.print(F("USER "));
    client.println(pop_user);
    if (!readOk(true))
        return -103;

#ifdef DEBUG_POP
    Serial.println(F("command PASS"));
#endif
    client.print(F("PASS "));
    client.println(pop_pass);
    if (!readOk(true))
        return -104;

#ifdef DEBUG_POP
    Serial.println(F("command STAT"));
#endif
    client.println(F("STAT"));
    if (!readOk(false))
        return -105;

    // The whole line was like this: "+OK 3 15343"
    // It means that 3 emails are waiting with a total size of 15343.
    // At this moment, the "+OK" is read, but nothing else.
    // Check if there is a space after "+OK".
    char c = client.read();
    if (c != ' ')
        return -106;

    client.setTimeout(POP_TIMEOUT);       // set timeout lower for parseInt
    // Read the number of emails that are on the server.
    int nMails = client.parseInt();
    client.setTimeout(POP_TIMEOUT_DEFAULT);  // restore timeout to 1 second

    // Read the remaining of the response to STAT.
    readRemaining();

#ifdef DEBUG_POP
    Serial.print(F("Number of emails="));
    Serial.println(nMails);
#endif

    // Test if there are emails waiting.
    if (nMails == 0)
    {
        // No emails, but no error. Set buffer to empty string.
        nBytes = 0;               // the returned value
        pBuf[0] = '\0';           // set empty string
    }
    else if (nMails > 0)
    {
        // emails are waiting.
        // Scan the emails until the first is found with the keyword "ARDUINO " at the
        // beginning of the "Subject: ".

        boolean found_and_ready = false;
        for (int nMailNumber = 1; nMailNumber <= nMails && !found_and_ready; nMailNumber++)
        {
            // The command RETR <x> gets the whole mail.
            // The command TOP <x> <size> gets the header plus 'size' of the body.

#ifdef DEBUG_POP
            Serial.print(F("command TOP "));
            Serial.print(nMailNumber);
            Serial.println(F(" 0"));
#endif
            client.print(F("TOP "));
            client.print(nMailNumber);
            client.println(F(" 0"));

            // Use readOk with parameter 'false' to stop reading after "+OK".
            if (!readOk(false))
                return -107;
            // The header of the email is waiting to be read, use the Stream.find() to look for the Subject.
            // The text "Subject: " should be at the beginning of a line, but that is not tested.
            // The first found text "Subject: " is assumed to be the real subject.
            // I have checked many years of emails, and the text is always "Subject: ", and never "SUBJECT: ".
            // At the moment, it is not possible to use the F() macro for Stream.find
            // Only the email that starts with "ARDUINO " at the start of the Subject is used.

            client.setTimeout(POP_TIMEOUT);      // set short timeout for find().
            // find() returns true if found and false if not.
            boolean foundsubject = client.find("Subject: ARDUINO ");
            client.setTimeout(POP_TIMEOUT_DEFAULT);   // restore timeout to 1 second

            if (foundsubject)
            {
#ifdef DEBUG_POP
                Serial.println(F("Found an email for me"));
#endif

                // Read the remaining subject (that is the command for the Arduino) into a buffer.
                // Every line from the mail server should end with CR + LF,
                // but to be sure, both CR and LF are checked.
                // Alternative:
                //    client.readBytesUntil('\r', pBuf, nBufSize);

                // The last position in the buffer is reserved for the zero terminator.
                // So read data until (nBufSize-1).
                int i;
                for (i = 0; i < (nBufSize - 1) && client.available(); i++)
                {
                    char c = client.read();
                    if (c == '\r' || c == '\n')
                        break;
                    pBuf[i] = c;
                }
                // Add zero terminator
                pBuf[i] = '\0';
                nBytes = i;     // the number of received bytes is returned by the getEmail() function.

                // More text of the header could be following the Subject.
                // That is read and disregarded.
                readRemaining();

#ifdef DEBUG_POP
                Serial.print(F("Subject = \"ARDUINO "));
                Serial.print(pBuf);
                Serial.println(F("\""));
#endif

#ifdef ENABLE_DELETE_POP
                // Delete the just read message.
#ifdef DEBUG_POP
                Serial.print(F("command DELE "));
                Serial.println(nMailNumber);
#endif
                client.print(F("DELE "));
                client.println(nMailNumber);
                if (!readOk(true))
                    return -108;
#endif

                // Everything is okay, the mail is read and deleted.
                // Ready for now, don't process the remaining emails.
                found_and_ready = true;
            }
            else
            {
#ifdef DEBUG_POP
                Serial.println(F("No ARDUINO keyword in subject"));
#endif
                // This email has no "Subject: ARDUINO ".
                // But the remaining text has still to be read and disregarded.
                readRemaining();
            }
        }
    }

#ifdef DEBUG_POP
    Serial.println(F("Sending QUIT"));
#endif
    client.println(F("QUIT"));

    // After "QUIT", the server still respons with "+OK",
    // but after that, the connection might get lost.
    // So don't read everything after "+OK" (use parameter 'false' for readOk).
    if (!readOk(false))
        return -109;

    client.stop();

#ifdef DEBUG_POP
    Serial.println(F("normally disconnected"));
#endif

    return(nBytes);
}

// Read the response from the mail server.
// That is "+OK" if everything is okay.
// Parameter 'readAll' is to read every character after the "+OK".
boolean readOk(boolean readAll)
{
    // Check the response "+OK" from the mail server
    // In most cases that is followed by a space and more text, but not always.
    // In case of an error the text "-ERR" is received.

    int loopCount = 0;
    char bufOk[4];
    Serial.print("Connected: ");
    Serial.println(client.connected());

    Serial.print("Client Available: ");
    Serial.println(client.available());
    // Wait for response of mail server, with a timout.
    while (!client.available())
    {
        delay(1);
        loopCount++;

        // if nothing received for 10 seconds, timeout
        if (loopCount > 10000)
        {
            client.stop();
#ifdef DEBUG_POP
            Serial.println(F("\nTimeout"));
#endif
            return false;
        }
    }

    // Read the first three bytes.
    client.readBytes(bufOk, 3);

#ifdef DEBUG_POP
    Serial.write(bufOk, 3);
    Serial.println();
#endif

    // Is it "+OK" ?
    if (strncmp(bufOk, "+OK", 3) != 0)
    {
        popFail();
        return false;
    }

    // When the text after "+OK" is not needed, everything
    // else can be read and disregarded
    // (or shown in the serial monitor during debugging).
    if (readAll)
        readRemaining();

    return true;
}

void readRemaining()
{
    // This function is called after checking the "+OK".
    // It reads everything from the server, until no more text is
    // available.

    while (client.available())
    {
        char c = client.read();
#ifdef DEBUG_POP_EXTRA
        Serial.print(c);
#endif
    }
    return;
}

void popFail()
{
    int loopCount = 0;

#ifdef DEBUG_POP
    Serial.println(F("popFail"));
#endif

    while (!client.available())
    {
        delay(1);
        loopCount++;

        // if nothing received for 10 seconds, timeout
        if (loopCount > 10000)
        {
            client.stop();
#ifdef DEBUG_POP
            Serial.println(F("\nTimeout"));
#endif
            return;
        }
    }

    client.stop();

#ifdef DEBUG_POP
    Serial.println(F("disconnected due to fail"));
#endif
}

Output:
Arduino POP3 email reader
Ethernet started.
Local IP = 192.168.1.117
Press 'c' to check mail.
connected
Connected: 1
Client Active: 0

Timeout
Email POP3 failed, error = -102

Your title says it's about sending mail, while the code only contains code for receiving mail

Hotmail doesn't provide a non-encrypted POP3 service, which would normally run on port 110.
You have no choice but to use the SSL service.  However, you can't.  Or not easily.  SSL is quite a heavy protocol and it is highly doubtful the little Uno is capable of even coming close to being able to work with it.
The Due might have a chance, but again, unlikely.
You would be best off using a computer (server) to check the emails for you and provide a "digest" of information to the Uno instead.

A Due certainly has the resources (memory) to do it, though the challenge may be in finding/creating an implementation.  Something with networking on board and an existing library might be easier and more cost effective - for example, a raspberry pi (though at the cost of a more delicate writable-filesystem OS installation).  The idea of using an additional server as a proxy to help out is a good one though, if the unsecured nature of the communication to/from that server is acceptable.


text:
How to avoid pulling the RX0 pin to reset sketch
My project requires reading 5 serial devices (RFID readers) at the same time. I chose an Arduino Mega 2560 as it comes with 4 serial RX ports. For the fifth port I am using the SoftwareSerial library.
My loop() checks each Serial port to detect if an RFID tag is being read. This works perfectly.
However, I am powering the board from an wall wart. When the power is disconnected the sketch no longer runs. I must unplug RX0, plug in the power supply, and reattach RX0.
If the board ever loses power it will have to be reset manually which is not ideal.
Please help me understand Why is this happening? and how can I fix it?

My guess is that the bootloader gets activated after reset, and waits for code. I don't know how to avoid this however.

Does it sit there with an LED flashing?

If you are willing to use ISP for programming you could remove the bootloader.  Or you can modify the bootloader to time out if no valid programming operations occur, or to check an "I'm being programmed" pin.

It looks like your RFID readers are very chatty on startup, and the board is going into bootloader mode.
I'd consider either controlling the RFID reader's power using another pin (and a transistor or mosfet if the reader needs more than 20mA), or using a gate ( AND for instance, or a simple switch IC like the 4066) that you can control to disable the RX0 input until program start.
Another thing I've done in the past is multiplexed multiple serial devices to one serial input.  The RFID readers probably have outputs that indicate a card presence, so use those and a multiplexor.  When the card presence is indicated, connect that serial port using the multiplexor, read the card and act accordingly, then wait for another card detect event.

You can simply disable the bootloader rather than erasing it. Find out the current fuse settings using a fuse-detection program. Change the BOOTRST flag in the High fuse to be unchecked, referring to this page: Engbedded Atmel AVR® Fuse Calculator
Write the High fuse back. Then it will ignore the bootloader and go straight to your code. Of course, to upload a new version you will have to put the BOOTRST fuse back, or you won't be able to use the bootloader to upload a new sketch.
One way of changing the fuse is to use my Atmega chip stand-alone programmer sketch. This has an interactive "change fuses" option. To run this you just need a spare board (eg. a Uno) and 6 wires to connect the programming board to your target Mega2560.
Example wiring shown on the linked page. Note that you do not need the SD board to merely change fuses. Just the two Arduinos and the connecting wires are enough for that.
When you first run the sketch it should inform you of the current fuses. Look at the High fuse and follow my instructions above.
You should see something like this:
Entered programming mode OK.
Signature = 1E 98 01
Processor = ATmega2560
Flash memory size = 262144
LFuse = FF
HFuse = D8
EFuse = FD
Lock byte = FF
Bootloader in use: Yes

In this case the High fuse was D8, which has the bootloader enabled. Using the Fuse Calculator site we can see that it should now be D9 which disables the bootloader.

An alternative way to change the fuse is to use Avrdude, if you have a stand-alone ISP programmer handy.


text:
What protocols and tools does Arduino Due use for flashing and debugging?
I am interested in writing a simple C program outside of the Arduino IDE and respective libraries, but deploying it directly to an Arduino Due (which uses a SAM3X8E ARM MCU). I am trying to figure out what comms/serial protocols are used for:

Flashing/deploying the program to the ARM MCU; and
Connecting the program to a debugger

And, not just the protocols used, but what tools are compatible with these protocols, and henceforth, can be used for both use cases. How can I tell what my viable options are?

http://playground.arduino.cc/Bootloader/DueBootloaderExplained

The Due (more specifically the SAM3X) uses its own proprietary protocol. It's all embedded in the bootloader, which is hard wired in the ROM and can never be changed (idiotic if you ask me).
I know of two systems for communicating with it.  Atmel's SAM-BA program, and the open source BOSSA.  The command line version of BOSSA (bossac) is used by the Arduino IDE for programming.

Thanks @Majenko (+1) - a few quick followups if you don't mind: (1) Can you confirm that BOSSA/bossac can be used for both flashing and debugging? (2) If I'm understanding you correctly, the ROM (containing proprietary protocol) is a part of the MCU itself, and that's why it can't be changed, yes? And last, (3) Then how is it that BOSSA/bossac can "speak" this proprietary protocol? Did they ink a special deal with Atmel? Thanks again!

No idea, I have never tried it. 2) Yes, that's right. 3) Probably a combination of software examination, protocol decoding and reverse engineering.

While documentation is nice, I disagree with the permanence of factory bootloaders being a bad thing: they make it very hard to "brick" a device, and save you from needing any special tools to initialize new chips (not that SWD/JTAG adapters are expensive).  If you decide you would prefer to have your own custom bootloader, just write one and put it in ordinary flash and make it reluctant to overwrite itself.


text:
This specific code just refuses to compile?
I've been working on some software to do REALLY basic composition of music.
Here's my code so far:
#include "notes_sharps.h"

int notes[] = {NOTE_B0,NOTE_C1,NOTE_D1,NOTE_E1,NOTE_F1,NOTE_G1,NOTE_A1,NOTE_B1,NOTE_C2,NOTE_D2,NOTE_E2,NOTE_F2,NOTE_G2,NOTE_A2,NOTE_B2,NOTE_C3,NOTE_D3,NOTE_E3,NOTE_F3,NOTE_G3,NOTE_A3,NOTE_B3,NOTE_C4,NOTE_D4,NOTE_E4,NOTE_F4,NOTE_G4,NOTE_A4,NOTE_B4,NOTE_C5,NOTE_D5,NOTE_E5,NOTE_F5,NOTE_G5,NOTE_A5,NOTE_B5,NOTE_C6,NOTE_D6,NOTE_E6,NOTE_F6,NOTE_G6,NOTE_A6,NOTE_B6,NOTE_C7,NOTE_D7,NOTE_E7,NOTE_F7,NOTE_G7,NOTE_A7,NOTE_B7,NOTE_C8,NOTE_D8};

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

  for(int i = 0; i < 51; i++){
    Serial.println("%i's sharp is %i",notes[i], notes[i]+(notes[i]*0.05937));
  }
}

void loop(){}

This code just refuses to compile, no error messages, it simply leaves my computer dormant.
Here's the log:
C:\Program Files (x86)\Arduino\hardware\tools\avr/bin/avr-g++ -c -g -Os -w -fno-exceptions -ffunction-sections -fdata-sections -fno-threadsafe-statics -MMD -mmcu=atmega328p -DF_CPU=16000000L -DARDUINO=10604 -DARDUINO_AVR_UNO -DARDUINO_ARCH_AVR -IC:\Program Files (x86)\Arduino\hardware\arduino\avr\cores\arduino -IC:\Program Files (x86)\Arduino\hardware\arduino\avr\variants\standard C:\Users\anidude\AppData\Local\Temp\build38239327143584304.tmp\sharpscalc.cpp -o C:\Users\anidude\AppData\Local\Temp\build38239327143584304.tmp\sharpscalc.cpp.o

Are you able to upload other codes to that unit?

That's a new usage of Serial.println... I think you're mixing Serial.println(const char *) and sprintf(char *buf, const char *format, ...)

@Jasmine I can run the example toneMelody without error.

I tried it and I got a very clear error message: "fatal error: notes_sharps.h: No such file or directory". If I create the missing file, another error message, just as clear: "error: no matching function for call to ‘HardwareSerial::println(const char [17], int&, double)’".

here's the actual notes_sharps.h file
http://pastebin.com/KVahvSNx

There's nothing wrong with that file. Seems like you just put it in the wrong place and the compiler can't see it. Very common problem with using libraries - http://www.arduino.cc/en/guide/libraries

It's not actually a library. It's just a file I wrote to make my actual program look cleaner.

That IS a library. It's a trivial library, but you need to install it the same way.

As Majenko stated in the comments, your use of the println function is not valid as there exists no overload that takes char*, int, int as parameters.
You could get your program to work by replacing your println as following:
for(int i = 0; i < 51; i++){
    Serial.print(notes[i]);
    Serial.print("'s sharp is ");
    Serial.println(notes[i]+(notes[i]*0.05937));
}


text:
Problem using Ino build for 8 MHz
I want to use the Ino command line toolkit to build and upload my HEXes. It works well for the regular Arduino, however when I try to upload code to a Mini Pro 3.3V at 8 MHz, the code has the timing wrong. The serial output is garbled (I tried at different baud rates and was garbled each time) and delay(1000); seems to take double the time. I have selected the correct board (pro328 in my boards.txt), but it didn't seem to make a difference in the generated code. Has anyone used this and encountered a similar problem?

You have to set the correct value for F_CPU (i.e. 8000000).

Where should I set that value? Is it a compiler define that's not taken into account by Ino?

Normally it's set in boards.txt.

Well it is set in boards.txt if you look at the pro328 settings that I mentioned. I'd like to find out where that is used in the arduino code and how can I make sure Ino will use it.

Per the Quick start guide, Ino assumes the board is an Arduino Uno unless otherwise specified on the command line:

All examples were done in assumption that you have Arduino Uno and it is available on default port. Now consider you have Arduino Mega 2560 and it is available on port /dev/ttyACM1. We have to specify this for our build steps as command-line switches.
Board model may be set with --board-model or -m switch. Port is set with --serial-port or -p switch. So lets do it:
$ ino build -m mega2560
$ ino upload -m mega2560 -p /dev/ttyACM1
$ ino serial -p /dev/ttyACM1

For the full list of board names refer to ino build --help.

So you might be able to do this by using
$ ino build -m pro328
$ ino upload -m pro328 ...

However I don't know what options Ino includes for boards (presumably it uses the boards file), so using ino build --help should give you the information you need to select a suitable board if pro328 doesn't work.
Once that's done, the frequency setting should be taken care of for you.

The think is I use that board. I tried both in command line and in the settings file and it didn't seem to work. In the meantime I found out about platformio which I'm evaluating and on which it works correctly.

@rslite - the pro comes in both 5v 16 MHz and 3.3v 8 MHz version, to get the correct clock for the latter you will have to specify that and not the 16 MHz version.  This is exists in the current boards.txt but it is unclear what the ino syntax for it would be.

So it seems the F_CPU should be set up at compile time and I'm not sure if Ino does that or not (probably, or I'm missing something else).
However after pulling my hair for a day or so I discovered PlatformIO which has a much better functionality - my code works correctly, the lib manager is intriguing, is platform independent and seems it doesn't even require the Arduino environment to be installed (it can pull the required files itself).

authors: سيد امجد الشرع


text:
ATMega1284 and Relative Humidity libraries
I am trying to use some Relative Humidity sensors (DHT11 and DHT22) with the ATMega1284 processor on a breadboard. I use libraries from Arduino playground (dht.h), Adafruit (DHT.h) and others. Even though both sensors and libraries work fine with Arduino Uno and Mega, they fail with ATMega1284, which produces an INVALID_VALUE error.
Connections are double checked, and other libraries such as Wire, OneWire etc work fine.
Does anyone have any experience with the ATMega1284 processor, or any suggestions?

Did you try reading the libraries to see if they special case on the '328P and/or '1280?

Actually I did, but they looked quite simple, no definitions of processors there.

Are you sure you have your pin assignments correct?  The 1284 has a few different pin assignments as it isn't a standard Arduino board.  I haven't had any issues using the DHT22 with the Mighty1284 setup.

What pins are you using?

Per the library instructions, you will receive INVALID_VALUE in the following situations:

The readXX() functions return:

DHTLIB_OK (0) : if the sensor sample and its checksum is OK.
DHTLIB_ERROR_CHECKSUM (-1) : if the checksum test failed. This means that data was received but may be incorrect.
DHTLIB_ERROR_TIMEOUT (-2) : if a timeout occured, communication failed.

In case of a DHTLIB_ERROR_TIMEOUT, humidity and temperature will both get the value DHTLIB_INVALID_VALUE. In case of DHTLIB_ERROR_CHECKSUM the values of humidity and temperature are left unchanged as it is impossible to determine which byte failed in the checksum. It is up to the programmer to decide what to do. One can compare with previous value, but better reread the sensor.

So read the value returned by the read11() or read22() functions to verify that it's an DHTLIB_ERROR_TIMEOUT condition, and if so try to figure out why the library is having trouble talking to the device.

It is a DHTLIB_ERROR_TIMEOUT (-2), but I can not understand the reason.


text:
Need help rewriting a program
I can't use this program on my Arduino Uno since the max is 16 bits. I need my water pump to run for 5 min, then wait for 60 min.
int motorPin = A0;
int blinkPin = 13;

int watertime = 300000; // how long to water in miliseconds
int waittime = 3600000; // how long to wait between watering

void setup() {
    pinMode(motorPin, OUTPUT);
    pinMode(blinkPin, OUTPUT);
}

void loop() {
    digitalWrite(motorPin, HIGH);
    digitalWrite(blinkPin, HIGH);
    delay(watertime);
    digitalWrite(motorPin, LOW);
    digitalWrite(blinkPin, LOW);
    delay(waittime);
}

Changed int to:
#define watertime 300000
#define waittime 3600000

But it does not work.

Use the long type instead
long watertime = 300000; // how long to water in miliseconds
long waittime = 3600000; // how long to wait between watering

You might want to use unsigned long instead of long and qualify your literals with UL on the end (eg 3600000UL).

For any delays longer than a few seconds you really need to use a Real-Time Clock chip, like the popular DS1307 from Maxim. The Arduino's delay() function is only very roughly accurate, and even less so when used as you are using it.
If you can't get a DS1307 or something similar (there's plenty to choose from) or you Arduino has too much connected already to allow anything else to be added, you could use the Time library to simulate one.  The Time library is also useful if you do have an RTC attached.

http://playground.arduino.cc/code/time

Eh. The Arduino libraries do actually compensate for the inaccuracies in delay() et alia, but a RTC is a better call regardless.

@IgnacioVazquez-Abrams They try to compensate for the inaccuracies, but when you're running from a ceramic oscillator there's only so much you can do - and any interrupts you have occurring will break that compensation anyway.

If did not misunderstand, you want a longer delay. Why don't you use a for loop in order to obtain such a delay.
for(int i = 0; i < 50; i++) {
    delay(1000);
}

This produces 50 seconds instead of 1 second. You can replace 1000 and 50 according to your needs. This is just an example.

Maybe because delay(50000) is simpler and does the same thing.

I do not know if you plan on doing anything else on your arduino, but holding a delay inside the loop function is bad idea if you do, things need to happen outside of your code (any serial I/O for sure and others, right?).
That said, I like @zgrknr answer the best, although the others will also work. That answer allows using smaller numbers, that are easier to understand. Just make sure to keep your variables global, and not within loop or else they will get re-initialized every time.
As far as accuracy, do some real by the clock testing, and adjust your numbers, who cares if it is accurately counting as long as you can identify what numbers gives you the time period you want.
response to comment:
My firmware code looks like this, is yours different?
int main(void)
{
  init();
  initVariant();

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

  setup();

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

Serial communication with Arduino is interrupt-driven, and delay() does not block interrupts.

I believe it's better to put the Arduino to sleep instead of using the delay function.
You can use a library called Sleep_n0m1 for the purpose.
Modify your code like following.
#include <Sleep_n0m1.h>

int motorPin = A0;
int blinkPin = 13;

unsigned long watertime = 300000UL; // how long to water in miliseconds
unsigned long waittime = 3600000UL; // how long to wait between watering
Sleep sleep;

void setup()
{
    pinMode(motorPin, OUTPUT);
    pinMode(blinkPin, OUTPUT);
}

void loop()
{
    digitalWrite(motorPin, HIGH);
    digitalWrite(blinkPin, HIGH);
    sleep.pwrDownMode();
    sleep.sleepDelay(watertime);
    digitalWrite(motorPin, LOW);
    digitalWrite(blinkPin, LOW);
    sleep.pwrDownMode();
    sleep.sleepDelay(waittime);
}

Hope this would solve the problem.


text:
How to program thresholds?
Hello guys (and gals)!
I'm trying to figure out how to program thresholds using my arduino board.
Essentially, to make this as simple as possible, this is what I have going on.
I am sampling a value every one second, I am taking the value and trying to make certain actions occur based on when this value crosses certain thresholds.
The value read every second will be a value between 0-150.
The thresholds will work something like this:
If value crosses over 20 and becomes 20 or higher, do an action.
If value crosses over 20 and becomes 19.9 or less, do a different action.
And then do the same for a threshold at 30, 40, 50, and 65.
I would need to have it so that if it reads a value of 15, and then a second later, reads a value of 23, it does an action. But if it reads 23, and then reads 24 a next, it needs to not do anything because it hasn't crossed over from one threshold to another. I only want an action to perform if a threshold is crossed either by increasing or decreasing past it.
So again, to reiterate;
If first value read is 34, and second is 42, do an action.
If first value is read at 57, and second at 44, do an action.
If first value is 24, and second value is 26, do nothing. (no threshold was crossed)
The next part would be figured out if a threshold was crossed twice, or more, to do that action twice or more times.
Any advice on how to code this?
Thanks in advance.

Store the previous value.

Thanks again for your contributions.
I've gone ahead and decided to go with the following code. Its purpose is to turn vol up or down based on current car MPH. I choose to define brackets that cover a range of values. When one bracket ends, another begins. I've also set the previous bracket to current bracket at the end of each loop so that the application knows where it was previously, so that if it hops above or goes under a defined bracket, it does the desired action.
I've used a random generator to supply the MPH for testing purposes for now and commented out a few things that disturbed the testing process. If you'd like to critique this code to make is better, please let me know.
Note: I've also borrowed some of this code from another individual (Matthew McMillan, http://matthewcmcmillan.blogspot.com) who wanted to figure out how to convert a vehicle speed sensor wire info into MPH. I needed this code in order to make use of the vehicle's speed.
#include <SPI.h>
#include <Wire.h>

const int lightPin = 0;
const int hardwareCounterPin = 5;
const int samplePeriod = 1000; //in milliseconds
const float pulsesPerMile = 4000; // this is pulses per mile for Toyota. Other cars are different.
const float convertMph = pulsesPerMile/3600;
unsigned int count;
float mph;
unsigned int imph;
int roundedMph;
int previousMph;
int prevCount;

// Declare brackets
const int BracketA = 1;
const int BracketB = 2;
const int BracketC = 3;
const int BracketD = 4;
const int BracketE = 5;
const int BracketF = 6;

// Initialize Previous and Current Brackets
int PreviousBracket = 1;
int CurrentBracket = 1;

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

  TCCR1A = 0; //Configure hardware counter
  TCNT1 = 0;  // Reset hardware counter to zero
}

void loop() {

  /////////////////////////////////////////////////////////////
  // This uses the hardware pulse counter on the Arduino.
  // Currently it collects samples for one second.
  //
  bitSet(TCCR1B, CS12); // start counting pulses
  bitSet(TCCR1B, CS11); // Clock on rising edge
  delay(samplePeriod); // Allow pulse counter to collect for samplePeriod
  TCCR1B = 0; // stop counting
  count = TCNT1; // Store the hardware counter in a variable
  TCNT1 = 0;     // Reset hardware counter to zero
  mph = (count/convertMph)*10; // Convert pulse count into mph.
  imph = (unsigned int) mph; // Cast to integer. 10x allows retaining 10th of mph resolution.

  int x = imph / 10;
  int y = imph % 10;

  // Round to whole mile per hour
  //if(y >= 5){
  //  roundedMph = x + 1;
  //}else{
  //  roundedMph = x;
 // }

  //Code to write your own MPH for testing purposes.
  //if (Serial.available() > 0) {
                // read the incoming byte:
               // roundedMph = Serial.read();
               //}

  //If mph is less than 1mph just show 0mph.
  //Readings of 0.9mph or lower are some what erratic and can
  //occasionally be triggered by electrical noise.
  //if(x == 0){
  //  roundedMph = 0;
 // }

  roundedMph = random(1,80);

  // Don't display mph readings that are more than 50 mph higher than the
  // previous reading because it is probably a spurious reading.
  // Accelerating 50mph in one second is rocketship fast so it is probably
  // not real.
  if((roundedMph - previousMph) > 50){
    roundedMph = previousMph;
  }

  //Place the gatherered MPH value into a bracket
  //---------------------------------------------
  if(roundedMph >= 0 && roundedMph < 20) {
   CurrentBracket = BracketA;  //Value1
   Serial.println("I Choose Bracket A");
    }

  if(roundedMph >= 20 && roundedMph < 30) {
   CurrentBracket = BracketB;  //Value2
   Serial.println("I Choose Bracket B");
    }

  if(roundedMph >= 30 && roundedMph < 40) {
   CurrentBracket = BracketC;  //Value3
   Serial.println("I Choose Bracket C");
    }

  if(roundedMph >= 40 && roundedMph < 50) {
   CurrentBracket = BracketD;  //Value4
   Serial.println("I Choose Bracket D");
    }

  if(roundedMph >= 50 && roundedMph < 65) {
   CurrentBracket = BracketE;  //Value5
   Serial.println("I Choose Bracket E");
    }

  if(roundedMph >= 65) {
   CurrentBracket = BracketF;  //Value6
   Serial.println("I Choose Bracket F");
    }

 //Decide if bracket stayed the same, went up, or down.
 //---------------------------------------------------
 if(CurrentBracket == PreviousBracket) {
 //Do Nothing
 Serial.println("Nothing Changed");
 }

if(CurrentBracket > PreviousBracket) {
 //Command for Vol Up
 int VolUp;
 VolUp = CurrentBracket - PreviousBracket;
Serial.println("Volume Went Up One by ");
Serial.println(VolUp);
delay(2000); // Delay to not change Vol to fast if near threshold
}

if(CurrentBracket < PreviousBracket) {
  //Command for Vol Down
  int VolDown;
  VolDown = PreviousBracket - CurrentBracket;
 Serial.println("Volume Went Down One by ");
 Serial.println(VolDown);
 delay(2000); // Delay to not change Vol to fast if near threshold
 }
  previousMph = roundedMph; // Set previousMph for use in next loop.
  PreviousBracket = CurrentBracket; //Set PreviousBracket for use in next loop.
}

The way you described it, the first and good solution I can approach it is state machine.
You have a lot of thresholds to check and very specific details such as going up at some level and doing something or nothing depending on the level.
What I advise you is creating the state machine for you code setting up all the thresholds and saving the actual state of your system into a variable. After you have this set up, coding is just a matter of switch/cases or if statements.
For example. The first part is to check if it goes until 20 and then keep with at least 20.
switch (state) {
    case 1:
        if (value >= 20 && value < 30)
             state = 2;
        break;
     case 2:
        if (value < 20)
             state = 1;  // initial state
        else if (value >= 20 && value < 30)
             state = 3; // or call a function
        break;
     case 3:
          doSomething();
          break;
}

And you could have some delay or timer interrupt to check the value each 1s and repeat the state machine again and again. If you change or read the value inside an interrupt function call, make sure you declare the variable as volatile otherwise the compiler will optimize it and your machine won't work properly.
This way you can expand the idea and have all the thresholds set up.

That code is faulty – as it stands, once the state changes to 3, it stays at 3 no matter what value occurs.  Also, when state is 1, a value of 30 or more doesn't get processed.  So for example the sequence 15, 35, 15 results in no actions occurring.

Good point, @jwpat. Well, inside the function doSomething, there could be a verification and then decide which state to go in sequence. This code is just a start point where someone could develop their own code. The user has to make sure it checks every single situation to make sure it'll work properly.

It's always a good idea to add a Serial.print() and else/default to be notified via serial if any values go over/under your radar, especially as a beginner.


text:
How can I programming detect that a Bulb/LED is ON/OFF or a circuit is working as expected using Arduino?
I've created a circuit to turn on bulb using GSM module and Arduino. I want a mechanism(or programming) to know whether the bulb is on or off or fused. I've tried taking the input from the pins. But it only tells whether the pin is on or off but not the circuit as a whole.

You could measure current (perhaps as voltage across a small shunt resistor inline with the load).  Or you could use a photocell or other light detector.

This can be done using a few methods.  The simplest and least expensive option is to measure the current consumption of the device you want to verify correct operation of, and see if it's using enough, but not too much, current.
For instance, the following would work well in the arduino case of using an LED:

simulate this circuit – Schematic created using CircuitLab
Connect the Power to 5V or to the pin you're controlling the LED with. Connect the Sense to an analog input such as A0.
If the LED isn't installed, or is broken as an open circuit, the sense would register 5V.  If the LED is broken as a shorted element, the sense would register 0v. If the LED is operating correctly, you would sense the voltage drop of the LED (which varies according to the LED's design), but it would be well above 0V and well below 5V.
For bulbs and other loads, use a much smaller resister for R1 (so the resistor doesn't affect the load as much) and it would be considered a current shunt.  Knowing the resister value, and the voltage at the Sense location will give you a current value using Current = Voltage / Resistance. Again, the load should be drawing current within an acceptable range during proper operation.  If it's not drawing enough current, or too much current, it may not be operating correctly.
This won't tell you if the LED is on, however it's a very reliable method to discover if it's working correctly, and you'll probably never run into a situation where the correct LED is installed and in the right current range, but not emitting light.

Yes, though putting the sense resistor on the ground side can let you measure with a lower reference on the ADC which helps if the resistor is small in value, and if it is protected with a diode clamp in case the load open-circuits can let you measure the current on loads supplied from a higher voltage than the ATmega.

@ChrisStratton Correct, but it also messes with shared grounds and can be confusing for electronics beginners. Consider, instead, trying to determine if a zigbee or bluetooth radio is operating correctly.  As it transmits its ground would be bouncing relative to the Arduino's ground, messing up communications.  I wouldn't recommend it to an arduino beginner generally, and specifically in this case where the voltage is known to be lower than the analog input, the circuit requires a resistor, and in the vast majority of beginner LED designs the resistor is always high side - not that it matters.


text:
Disturbed digital out at 4Mhz on Arduino NANO
I've written a simple program - it generates signals over Port D at 4 MHz:
#include <Arduino.h>

int main(void) {

    DDRD = B11111111;
    PORTD = B00000000;

    while (true) {
        PORTD = 0;
        PORTD = 5;
        PORTD = 10;
        PORTD = 15;
        PORTD = 20;
        PORTD = 25;
        PORTD = 30;
        PORTD = 35;
        PORTD = 40;
    }
    return 0;
}

and this is the signal coming out on D4:

I've modified the program by inserting NOP after each assignment to POTRD:
#define NOP __asm__ __volatile__ ("nop\n\t")

int main(void) {

    DDRD = B11111111;
    PORTD = B00000000;

    while (true) {
        PORTD = 0;NOP;
        PORTD = 5;NOP;
        PORTD = 10;NOP;
        PORTD = 15;NOP;
        PORTD = 20;NOP;
        PORTD = 25;NOP;
        PORTD = 30;NOP;
        PORTD = 35;NOP;
        PORTD = 40;NOP;
    }
    return 0;
}

and now signal looks fine, but frequency is limited to 800 KHz:

What is the reason for interference at 4 MHz? Is there a limitation to maximal frequency on digital out? I do not really need it for some particular project, just wanted to know it.
I've asked this question on stackoverflow, but then I've discovered this dedicated forum so... I've decided to try it out ;)

Set your scope mode to Single instead of Normal and the “interference” will magically disappear.

This is correct... could you explain the reason for this?

Your scope synchronizes on the rising edges, but since those are unequally spaced, it gets out of sync with the full period of the signal. By adding a few nops you reached a lucky synchronization in your second version of the code. In Single mode it only displays a single trace, so synchronization is not an issue.

Could you paste your comment as an answer ? - thank you !

Try running avr-objdump -S /tmp/sketchname.elf and look at the generated assembler code. You'll see how many operations certain code requires.

While not the cause of what you are seeing, you should also know that unless you disable it the Arduino has a timer interrupt running in the background which will slightly disturb operations like this.

This is not a limitation of the Arduino: you can toggle a pin on every clock cycle. It's a synchronization problem between the generated signal and the triggering of the scope. Your scope displays several traces superimposed, and it synchronizes them on the rising edges, but since those are unequally spaced, it gets out of sync with the full period of the signal. By adding a few nops you reached a lucky synchronization in your second version of the code.
The simplest solution is to set the scope mode to Single instead of Normal. Then it only displays a single trace and synchronization is not an issue anymore.
Another option would be to use one of the bits of PORTD as a trigger
signal. This bit should cycle only once inside the loop. PD5 should
work in the current version of your code. Configure the scope for
external trigger and feed this signal into its TRIG input.

Thank you - correct trigger solves my problem:


text:
Can I change the USB device name of Arduino?
I have several Arduinos connected to my Windows PC, and they appear as follows:

COM7 (Arduino Uno)
  COM11 (Arduino Uno)
  COM13 (Arduino Uno)

So there's no way to tell which is which, and when I want to upload a sketch to one, I have to unplug the others to make sure my code goes to the right one.
Is there a way to change the "Arduino Uno" description?
(I found a similar question but that was about Mac specifically).

You'll have to change the firmware on the usb to serial chip (atmega16u2)

And modify the driver to include the new name.

Here is the current link from @Gerben's Comment https://github.com/arduino/ArduinoCore-avr/blob/1.8.1/firmwares/atmegaxxu2/arduino-usbserial/Descriptors.c#L220

You'll have to change the software on the Arduino USB chip itself, and you may need to modify the drivers for the Arduino USB interface on the computer side.  It's not trivial, and probably not worth it.
However, Windows attempts to use the same serial port for the same devices in the same USB positions, so if you figure out which is which (blinking the LED at different frequencies) then you can mark the USB port itself with the com number that Windows uses when you plug an arduino into it.
If you use a hub, and you move that hub to a different port, the com numbers will change, but if you keep it in the same port, then it too will try to have them match what they have been in the past.
It's an annoyance, but it's a design decision by arduino.cc.  The old FTDI chips kept their assigned com port numbers because they have individual serial numbers and windows would attempt to reassign the same com port to the same chip each time it was plugged in, regardless of its location.  When Arduino.cc moved to a programmed MCU for the USB interface, they chose not to provide USB serial numbers, and thus windows has little option but to try to keep things straight by determining the location in the USB hierarchy that the device is connected, and try to keep com port assignments the same using that method.

"... they chose not to provide USB serial numbers ..." Oh wow. Was any rationale ever given for this?

@IgnacioVazquez-Abrams I've not seen any information from them on this issue.  They probably don't think it's important (the majority of users don't need it) and it does increase the cost as they not only have to program the chips individually, but track arduino serial numbers in some sort of coordinated fashion to avoid duplication. Given the number of knock-offs in addition to the licensed variants, it's a problem not worth tackling without good reason.

I have never tried it, but I suspect using zadig might work;
http://zadig.akeo.ie/
It lets you pick the driver and name for WinUSB and LibUSB devices.  Uninstall any existing driver first. And remember to pick the driver you wish to use when it asks. Also it is not real apparent, but you can edit the name of the device as it installs the driver.
Let us know if it works


text:
Difference between Arduino.cc and Arduino.org
Recently I have noticed that there are two arduino sites, arduino.cc and arduino.org.  They both have the Arduino logo and both sell what seems to be official Arduino boards. Also, arduino.org came out with the Arduino Zero board first. What is the deal here? Has Arduino partnered with another site? Any ideas appreciated.

Does arduino llc or .cc endorse products that are labeled such as UNO, but were made by others who are selling experiment kits with things like MAX7219 and 5461BS anode LED digit displays that are not compatible with each other? Or is this one of the issues that the arduino group together is trying to decide what to do with? The kit work, but some of the stuff isn't compatible with each other, according to the tutorials on the web.

ok understand the situation. QUestion is I have a Arduino motor shield with arduino.org stamped on it. I have a schematic for a board that was downloaded from the Arduino.cc web site. The two do not match and the .org board I have is not working the way it should. Anyone have any experience with this situation?

The short of it is that there was a falling out within the Arduino people and now there are two groups laying claim to the "Arduino" name.
Arduino LLC runs arduino.cc. They are the steward of the Arduino IDE and libraries and own the "Arduino" trademark in the United States, and also owns the "Genuino" trademark outside of the United States. Arduino SRL (fka Smart Projects SRL) is the company that assembles(assembled) the majority of Arduino boards for Arduino LLC, runs arduino.org, and owns the "Arduino" trademark inside Italy and all of the other countries they have registered the "Arduino" trademark.
Arduino SRL recently decided that they are no longer beholden to Arduino LLC and has stopped paying licensing fees for using the Arduino name. Whether this is justified or not has not been fully tested in court yet.

Story morality: don't make business with your friends, or do it properly, as you would with anybody else. Sad but true.

This is a sum up from Massimo Banzi: http://makezine.com/2015/03/19/massimo-banzi-fighting-for-arduino/

"are the creator of the Arduino IDE"  is too kind, and not quite factual. They are the original people who took Wiring project, marketed it better, then pretended like Wiring never existed. Of course the Wiring people did the same from the Processing project for the IDE.

They have the exact same logo. That's weird. @user6569 I don't think they pretended like it never existed or that you're giving them credit for their tons of original contributions/content. They did create the Arduino IDE. Like every other piece of software, literature, math, and science, it stands on the shoulders of its predecessors.

This article can explain it better than I could paraphrase:
http://hackaday.com/2015/02/25/arduino-v-arduino/
Relevant excerpt:

Arduino LLC [arduino.cc] is the company founded by Massimo Banzi, David Cuartielles, David Mellis, Tom Igoe and Gianluca Martino in 2009 and is the owner of the Arduino trademark and gave us the designs, software, and community support that’s gotten the Arduino where it is. The boards were manufactured by a spinoff company, Smart Projects Srl, founded by the same Gianluca Martino. So far, so good.
Things got ugly in November when Martino ... renamed Smart Projects to Arduino Srl and registered arduino.org
According to this Italian Wired article, the cause of the split is that Banzi and the other three wanted to internationalize the brand and license production to other firms freely, while Martino ... [wanted] to list on the stock market and keep all production strictly in the Italian factory.

Please take a look at The Untold History of Arduino.

Update on the situation: on October 1st, 2016 a blog post at arduino.cc "Two Arduinos become one" announced that an agreement was found between arduino.cc and arduino.org. Two key points:

the creation of a foundation
the creation of a holding.

About the holding:

At the end of 2016, the newly created “Arduino Holding” will become the single point of contact for the wholesale distribution of all current and future products, and will continue to bring tremendous innovations to the market.

About the foundation:

In addition, Arduino will form a not-for-profit “Arduino Foundation” responsible for maintaining the open-source Arduino desktop IDE, and continuing to foster the open-source movement by providing support for a variety of scholarships, community and developer initiatives.

arduino.org is not only boards assembler, but is also who designs and engineers the arduino boards. They own the arduino trademark all over the world, except the USA, therefore arduino.cc owns the trademark only in the USA.

No; arduino.cc designs the boards and owns the tradmark everywhere except Italy.  arduino.org justmanufactures the boards (and owns the trademark in Italy) and recently forked Arduino's GitHub repo, registered the domain arduino.org, and is now pretending that they are the only ones who design and make Arduinos and that arduino.cc is an impostor.

@NobodyNada I'm sorry but you are wrong about the boards manufacturing. arduino srl or arduino.org came from Smart Projects, and Smart Projects is the company who always designs and engineers arduino boards.

.org owns the trademark all over the world except USA, just take a look at arduino.cc web site and you can see Arduino Only USA and Genuino Outside USA.
I never heard that arduino.org said that .cc is an impostor on the contrary .org always thanks to arudino project founders for their work.
often people see only what they want to see and say things influencing people. (sorry for this last non-technical line but I have read around the web a lot of things that are untrue and unfounded accusations)

@ThomasCeleron But still both could have instead improved Wiring.


text:
Arduino SoftwareServo by example
I am interested in writing a simple Arduino program that will turn a servo back and forth (180 degrees each time) continuously.
I am looking at these servos and am planning on following this example.
Being so new to Arduino, I first wanted to confirm that the SoftwareServo library in that example will drive those particular servos. If it will not, then can someone begin by explaining to me why these servos are incompatible with the lib?
Assuming they are compatible, I am looking at the main example on that page (comments stripped out for brevity):
#include <SoftwareServo.h>

SoftwareServo myservo;

int potpin = 0;
int val;

void setup() {
    myservo.attach(2);
}

void loop() {
    val = analogRead(potpin);
    val = map(val, 0, 1023, 0, 179);
    myservo.write(val);
    delay(15);

    SoftwareServo::refresh();
}

My concerns:

There seem to be 3 pins involved here: a potentiometer pin (0), an analog pin (val) and a servo pin (2). What is the purpose of each of these pins, and is this 3-pin wiring common across all/most servos?
Is there anything "wrong" with defining myservo.attach(2); up above the setup function, and leave the setup function an empty no-op function?
Where does the map(...) function come from? If it was defined inside SoftwareServo I would have expected its usage to be something like SoftwareServo::map(...), etc.
Why do we need the delay after calling myservo.write(val);? What would happen if this delay wasn't in there?
According to that link, calling SoftwareServo::refresh() once every 50ms is necessary in order to: "keep your servos updating." But what does this mean, really? Updating to what?!?

There seem to be 3 pins involved here: a potentiometer pin (0), an analog pin (val) and a servo pin (2). What is the purpose of each of these pins, and is this 3-pin wiring common across all/most servos?

No, there is only 2 pins.  The value of the potentiometer attached to pin 0 is read and stored in the variable val.  That is then used to set the angle of the servo motor on pin 2.

Is there anything "wrong" with defining myservo.attach(2); up above the setup function, and leave the setup function an empty no-op function?

Yes.  It'll never get called.  setup() is the first function to be called and its purpose is to perform any initialization routines, such as attaching the servo code to the pin the servo is connected to.  So you have to call that either from setup() or from a function which setup() itself calls.

Where does the map(...) function come from? If it was defined inside SoftwareServo I would have expected its usage to be something like SoftwareServo::map(...), etc.

map() is part of the standard Arduino API.  http://www.arduino.cc/en/Reference/Map

Why do we need the delay after calling myservo.write(val);? What would happen if this delay wasn't in there?

You don't need the delay() call, but you don't want to set the value of the servo too rapidly.  You really want to allow at least one PWM cycle between each call to ensure the values have been set properly.

According to that link, calling SoftwareServo::refresh() once every 50ms is necessary in order to: "keep your servos updating." But what does this mean, really? Updating to what?!?

SoftwareServo is just what it says - a piece of software.  You have to run that software for it to work, and the refresh() function is that bit that you run.  If you don't call that then the PWM signal for the servo will never get generated and nothing will happen.
Oh, and yes those little servos should be fine.

1- there is only two pins a servo pin which is D2 and an analog pin which is A0. D2 pin for writing analog value to servo. D2 pin is used for getting analog pin value.
2- map function is a default function like sin, cos or digitalRead so library inport not necesary.
3- delay function and waiting 50ms is used to wait servo response time. if you change servo angle too quickly servo will not respond accurately


text:
Measure SRAM usage
I am using an Arduino with 2048 bytes of SRAM. I have a complex project so that it is no longer obvious how much SRAM it would use in total (there is not one large dominant object but many different routines, many libraries most of which I have not written myself etc. Each of these uses some small buffers, global variables etc.).
Can I determine how much SRAM I have left in the live system?

In the preferences set the compiler to verbose output. You'll get a message like Global variables use 9 bytes of dynamic memory.

It's already set to verbose (Show verbose output during compilation) but there is no such output?

@Gerben: this only tells you the amount of static RAM usage, i.e. the data and bss sections of the memory. When the program runs, it will also consume memory in the stack, and possibly in the heap. You can estimate the amount of free memory by looking at the gap between the heap and the stack, at runtime.

Expanding on my previous comment... The RAM memory map of an AVR-based
Arduino looks like this:
┌──────┬─────┬──────┬──────────┬───────┐
│ data │ bss │ heap │→  free  ←│ stack │
└──────┴─────┴──────┴──────────┴───────┘

The data and bss sections are fixed, and their size can be known at
compile time. However, the stack and the heap grow and shrink
dynamically as the program runs. You can estimate the amount of free
memory at run time by measuring the gap between the heap and the stack.
The result may be pessimistic if the heap contains usable holes.
Here you have:

a very simple function that does exactly that, and
a more complex version that also counts the holes in the heap.


text:
Adafruit CC3000 Wifi Shield on IRQ 2?
I'm using an AdaFruit CC3000 Wifi shield as an HTTP server with an Arduino Uno.
I have a script which works fine -- logs into my Wifi and listens for connections as it should.
However, I want to use an infrared library which writes to the CC33000 default IRQ 3, so to avoid conflict I change the following setting:
#define ADAFRUIT_CC3000_IRQ   3  // MUST be an interrupt pin!

to the only other Interrupt pin
#define ADAFRUIT_CC3000_IRQ   2  // MUST be an interrupt pin!

The device hangs at "Initializing" .. or at least I see neither of the subsequent lines in the following code on my serial monitor:
Serial.println(F("\nInitializing..."));
  if (!cc3000.begin())
  {
    Serial.println(F("Couldn't begin()! Check your wiring?"));
    while(1);
  }

  Serial.print(F("\nAttempting to connect to ")); Serial.println(WLAN_SSID);
  if (!cc3000.connectToAP(WLAN_SSID, WLAN_PASS, WLAN_SECURITY)) {
    Serial.println(F("Failed!"));
    while(1);
  }

I've stripped everything back down to just the example code for HTTPServer to ensure it's not a conflict with my own code or the IR Library. I've changed the setting from 2 to 0 and 1 thinking there was some confusion over literal IRQs vs Pins, but those settings generate the "Couldn't begin" error trap.
Is there any other setting that I need to vary in order to get the CC3000 to opearate on IRQ 2 or is this a hardware bug and I'm out of luck if I want to use Pin 3?

It is a "hardware bug" as you so aptly put it. As far as I know, the only way to get the CC3000 board to use pin 2 as the IRQ is to physically rewire the connections. I did exactly that on my board and it works without a problem, leaving pin 3 free to use for whatever else you want. You can see what I did here.
It basically involves cutting the trace wire and running a jumper cable between the holes next to the pins.
The important thing to understand perhaps is that pins 2 and 3 are available to use for IRQ on the Mega and Uno, but it is an actual dedicated pin on the CC3000, hence why you have to go to this effort to change it. Also remember that once you have cut the trace to pin 3 it becomes an open/free pin and is no longer connected to the wifi shield. By the sounds of your requirements this shouldn't matter, but it is still useful to know.
If you haven't already, I recommend that you read the documentation for the CC3000 board, as it really helped me understand the irritating intricacies.
But yeah, if you choose to follow this and reroute the pin, it works perfectly. Hope this helps, even if it is a bit late.

Thanks, bladepanthera! I ended up figuring out how to switch the IR Library I was using to another pin, and that solved the immediate problem for me, but it's really good to know this for future reference and I hope it saves others some hair-pulling.


text:
Programming question for Time Arduino
Can you program a sketch so that if the time is between 1m and 10m then it will reset itself?
Reset I found already, it is the if that I don't know.

Are you trying to reset your board every 1 minute? Because when it sees that time is a bit more than 1 minute it will reset. Is that what you mean?

Are you struggling with if() statements?

You can use the timer interrupts. For example:
#define F_CPU   16000000UL
#include <avr/delay.h>
#include <avr/io.h>
#include <string.h>
#include <avr/interrupt.h>
...
ISR(TIMER1_COMPA_vect)
{

  //do something every seconds when interrupt is raised.

}
void setup()
{
/*the following code will setup timer register to generate interrupt
  when 15624 is reached, at a clock frequency of 16 MHz and 1024 prescaler. This means that     every second an interrupt is generated
*/
  cli();          // disable global interrupts
  TCCR1A = 0;     // set entire TCCR1A register to 0
  TCCR1B = 0;     // same for TCCR1B

  // set compare match register to desired timer count:
  OCR1A = 15624;
  // turn on CTC mode:
  TCCR1B |= (1 << WGM12);
  // Set CS10 and CS12 bits for 1024 prescaler:
  TCCR1B |= (1 << CS10);
  TCCR1B |= (1 << CS12);
  // enable timer compare interrupt:
  TIMSK1 |= (1 << OCIE1A);
  sei();          // enable global interrupts
}

The code works on Arduino Uno. You should calculate the value of OCR1A for your frequency.


text:
Multithreading Leds and Joystick
I'm trying to made a program that turn on and turn off leds with an input and send the coordinates of joystick, but, in the loop, the arduino makes one at a time, and i want make this in the same time. How can i make that?

It isn't clear what you're asking. Can you describe what you've already tried? One processor can only do one thing at a time but it can do things in very a fast sequence, as long as the individual tasks have not (or only very short) delays. Have you tried to do this?

I tried to sent an input to control the leds and send at the same time one joystick, but, the loop is something like this:
loop() {
controlleds();
joystickevent();
}
but he runs, controlleds first, and joystickevent next, i want at the same time.

My answer to question 9752 shows code to handle multiple actions independently.

One way to do this is to use the millis() function.
millis() returns the current value of a timer that is incremented once per millisecond (hence the function name). You can compare the value of millis() at some past time with the current value to determine how many milliseconds have passed. By having multiple compare registers you can have multiple independent delays operating. (There is also micros() which increments at the 1 uS rate (with a "granularity" of 4uS on some processors).
This code is an example only. It MAY run but has not been tested and probably contains silly mistakes which do not affect its example purposes.
A function ToggleLED(n) is assumed which toggles the specified LED n from 1->0 or 0->1  as required.
LED1 will flash 200 mS on, 200 mS off, ...
LED2 will flash 333 mS on, 333 mS off, ...
The two loops are essentially independent.

unsigned long delay1; delay2;

void setup(){

int FlashTime1 = 200; / LED 1 will have a 200 on 200 off cycle
int FlashTime2 = 333; / LED 2 will have a 333 on 333 off cycle

delay1 = millis() + FlashTime1;  / Init LED timers
delay2 = millis() + Flashtime2;
}

void loop()
{
  if (millis() == delay1){ / Not until delay expired.

    ToggleLED(1);
    delay1= millis() + FlashTime1; / Reinit flash timer}

  if (millis() == delay2){

       ToggleLED(2);
       delay2= millis() + FlashTime2;}

}

the loop is something like this:
loop() {
controlleds();
joystickevent();
}

but he runs, controlleds first, and joystickevent next, i want at the
  same time.

There are typically two ways to read a simple potentiometer joystick: Connect it in a voltage divider and measure the analog voltage; and connect it in an R-C circuit and measure the time for the capacitor to charge.
The first way is faster and you should not be able to notice the time difference between controlling the LEDs and reading the joystick.
The second way takes longer and you might be able to notice. If this is how your joystick controller works, you would need to separately start the joystick reading, continue to poll the buttons control the LEDs, and check whether the joystick reading is ready yet. The joystick routine must not delay, waiting for the measurement to finish.


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/


text:
Arduino: Put Data in Other File
The below code starts off with lots of data in the beginning, distracting the reader from the actual code.  What is the best practice to clean this up:
#include <Wire.h>
// For LED Backpack
#include "Adafruit_LEDBackpack.h"
#include "Adafruit_GFX.h"
// For LCD Shield
#include <Adafruit_MCP23017.h>
#include <Adafruit_RGBLCDShield.h>

// For pixel Units, such as hero
#include <Unit.h>

Adafruit_BicolorMatrix matrix = Adafruit_BicolorMatrix();
Adafruit_RGBLCDShield lcd = Adafruit_RGBLCDShield();

Unit *hero;
boolean doesNeedRedraw = true;
boolean textNeedsRedraw = true;
int8_t lastButtonPress = 0;
int8_t frame = 0;

void setup() {
  /* Important Setup Routine */
}

static const uint8_t PROGMEM
  smile_bmp[] =
  { B00111100,
    B01000010,
    B10100101,
    B10000001,
    B10100101,
    B10011001,
    B01000010,
    B00111100 },
  neutral_bmp[] =
  { B00111100,
    B01000010,
    B10100101,
    B10000001,
    B10111101,
    B10000001,
    B01000010,
    B00111100 },
  frown_bmp[] =
  { B00111100,
    B01000010,
    B10100101,
    B10000001,
    B10011001,
    B10100101,
    B01000010,
    B00111100 },
  walls_bmp[] =
  { B10100000,
    B10110000,
    B10010000,
    B11011100,
    B01000100,
    B01110100,
    B00010100,
    B00011100 };

void loop() {
  /* Important Main Loop Routine */
}

Who is your reader? What is the propose of cleaning your code? What is the skill level of the reader?

One way to clean that up is to create a "Globals.inc" file and cut and paste all of your globals into there.  After that's done, simply include the globals file from your main .ino file with #include "Globals.inc"
(Main.ino)
#include <Wire.h>
// For LED Backpack
#include "Adafruit_LEDBackpack.h"
#include "Adafruit_GFX.h"
// For LCD Shield
#include <Adafruit_MCP23017.h>
#include <Adafruit_RGBLCDShield.h>

// For pixel Units, such as hero
#include <Unit.h>

#include "Globals.inc"

void setup() {
  /* Important Setup Routine */
}

void loop() {
  /* Important Main Loop Routine */
}

(Globals.inc)
Adafruit_BicolorMatrix matrix = Adafruit_BicolorMatrix();
Adafruit_RGBLCDShield lcd = Adafruit_RGBLCDShield();

Unit *hero;
boolean doesNeedRedraw = true;
boolean textNeedsRedraw = true;
int8_t lastButtonPress = 0;
// 0-255
uint8_t frame = 0;

static const uint8_t PROGMEM
  smile_bmp[] =
  { B00111100,
    B01000010,
    B10100101,
    B10000001,
    B10100101,
    B10011001,
    B01000010,
    B00111100 },
  neutral_bmp[] =
  { B00111100,
    B01000010,
    B10100101,
    B10000001,
    B10111101,
    B10000001,
    B01000010,
    B00111100 },
  frown_bmp[] =
  { B00111100,
    B01000010,
    B10100101,
    B10000001,
    B10011001,
    B10100101,
    B01000010,
    B00111100 },
  walls_bmp[] =
  { B10100000,
    B10110000,
    B10010000,
    B11011100,
    B01000100,
    B01110100,
    B00010100,
    B00011100 };

I wouldn't use the .h extension, as this is usually used for header files which have a connection to a .cpp or .c file with the same name.

Thanks, I will edit it the answer.  I take it that it should be a .cpp extension instead of .h extension?

.cpp is a possibility. Personally I prefer .inc

There is actually not a lot wrong with the way the code is.  You are writing / using embedded code. It is not expected to be some planned out UML model, and does not need to look like it is.
If you just want less lines, start by converting your binary data to hex. Otherwise the answer of a global.h is valid (and I would still convert binary to hex). You could easily shrink 24 lines down to 3.
If you could use a real IDE navigation would be unimportant, but since Arduino chose not to use a standard build process it takes extra effort (but still worth it). You could also switch to native AVR (and easily use a real IDE), which is what I plan to do as soon as the proof of concept is finished.

I'm developing from a command line basis as that I'm a rails developer and have learned how powerful the CLI approach can be.  I found something called platformio which compiles and uploads source code to an arduino, and can even be set to compile for additional boards too based on a configuration file.  You might wanna check platformio out after AVR.  Another benefit is library management.

Interesting. I had not heard of it. I bookmarked it and will look at it, thanks. Best case is Atmel comes out with a new Studio that uses the new VS 2015 stuff soon. Until then I limp around using both VS 2015 and Arduino IDE at the same time (external editor setting). It is livable. CLI vs GUI is a preference, nothing more.


text:
Blinking LEDs as fast as possible at different rates.
I'm trying to use the Arduino Uno to make a strip of LEDs blink as fast as they can while still blinking at different rates. I am able to get them blinking at different rates but the blinking is very slow:
#include <Adafruit_DotStar.h>
#include <SPI.h>         // COMMENT OUT THIS LINE FOR GEMMA OR TRINKET

#define NUMPIXELS 144 // Number of LEDs in strip

// Here's how to control the LEDs from any two pins:
#define DATAPIN    11
#define CLOCKPIN   13
Adafruit_DotStar strip = Adafruit_DotStar(NUMPIXELS, DATAPIN, CLOCKPIN);

void setup() {
strip.begin(); // Initialize pins for output
strip.show();  // Turn all LEDs off ASAP
}

  int brightness = 1; //Setting brightness of all LEDs

   void loop() {

  for(int i=1; i<6; i++)
//This loop is here so the number i can be used below to get different blink     //rates for the 3 LEDs blink at the same time
  {
    if(i%2==0){

    strip.setPixelColor(0, brightness, brightness, brightness);
    }
    else
    {strip.setPixelColor(0, 0);
    }
    //Sets blink rate of first LED, will be the fastest

    if(i%3==0){

    strip.setPixelColor(1, brightness, brightness, brightness);
    }
    else
    {strip.setPixelColor(1, 0);
    }
     //Sets blink rate of second LED

    if(i%4==0){

    strip.setPixelColor(2, brightness, brightness, brightness);
    }
    else
    {strip.setPixelColor(2, 0);
    }
     //Sets blink rate of third LED

   strip.show();
  }
  }

I thought I would be able to make them blink as fast as possible by using the micro() function as my counter instead of the i in the for loop, but this led to strange behavior:
#include <Adafruit_DotStar.h>
#include <SPI.h>

#define NUMPIXELS 144 // Number of LEDs in strip

// Here's how to control the LEDs from any two pins:
#define DATAPIN    11
#define CLOCKPIN   13
Adafruit_DotStar strip = Adafruit_DotStar(NUMPIXELS, DATAPIN, CLOCKPIN);

void setup() {

  strip.begin(); // Initialize pins for output
  strip.show();  // Turn all LEDs off ASAP

  Serial.begin(9600);
}

int brightness = 1;

void loop() {

    int time = micros();

    if(time%2==0){

    strip.setPixelColor(0, brightness, brightness, brightness);
    }
    else
    {strip.setPixelColor(0, 0);
    }

  if(time%3==0){
    strip.setPixelColor(1, brightness, brightness, brightness);
    }
    else
    {strip.setPixelColor(1, 0);
    }

   if(time%4==0){
    strip.setPixelColor(1, brightness, brightness, brightness);
    }
    else
    {strip.setPixelColor(2, 0);
    }

   strip.show();
}

This led to the first LED appearing on (good, presumably I wouldn't be able to see it blinking) and the second blinking at a rate I could see (I shouldn't be able to see this) and the third LED is not on at all.
Can anyone see the mistake I'm making? Am I using the micro() function right?
Thank you!

1 microsecond is only 16 clock-cycles. Your loop function will take a lot more that 1 microsecond to complete. Instead just declare int time=0; outside the loop and increment this variable at the end of the loop function (time=time+1). That way you don't skip any values for time.

Thank you. So basically I can't make my fastest blinking LED blink at half the frequency of the clock in the Arduino? I'm limited by how fast the loop can execute. Thanks a lot :)

Blinking an led at 8Mhz is useless (human eye can see anything faster than 150hz), and probably impossible (due to gate capacitance of the output pins)