text:
undefined reference to `PPMintIn::PPMintIn(int)'
I am making a new library that will utilize PinChangeInt's library.
My intention is to further simplify repetitive code by creating a library. (This is to allow for multiple PPM channels without rewriting a bunch of code for each channel i decide to add.)
Since i understand OOP i knew that i could go the route of make my own library.
The problem i'm having right now, is that the library is returning an undefined reference. The IDE i'm using is UECIDE with QTcreator on the side to help me with my syntax. The compiler is avr-gcc. The chip is an Arduino Uno. The problem i'm recieving is

C:...\RCRoomba_TestPulseV2.cpp.o: In function '__static_initialization_and_destruction_0':
  C:...\RCRoomba_TestPulseV2.ino:5: undefined reference to 'PPMintIn::PPMintIn(int)'
  C:...\RCRoomba_TestPulseV2.cpp.o: In function 'setup':
  C:...\RCRoomba_TestPulseV2.ino:9: undefined reference to 'PPMintIn::begin()'
  Failed linking sketch

I tried to define the variables in my h and cpp files but it doesn't seem to be fixing the problem.
Here is the .ino code.
for some reason UECIDE can't see the Pinchange and PPMint libraries
#include "arduino.h"
#include "C:\Users\User\Documents\UECIDE\libraries\PinChangeInt\PinChangeInt.h"
#include "C:\Users\User\Documents\UECIDE\libraries\PPMintIn\PPMintIn.h"

PPMintIn CH1(A0);

void setup(){
    Serial.begin(115200);
    CH1.begin();
}

void loop(){
}

Here is the .cpp code
#include "arduino.h"
#include "ppmintin.h"
#include "PinChangeInt.h"
//defined these
volatile int pwm_value = 0;
volatile int prev_time = 0;
uint8_t latest_interrupted_pin = 0;

PPMintIn::PPMintIn(int pin){
    pinMode(pin, INPUT);\
    digitalWrite(pin, HIGH);
    _pin = pin;
}

void PPMintIn::rising(){
    PPMintIn::latest_interrupted_pin = PCintPort::arduinoPin;
    PCintPort::attachInterrupt(latest_interrupted_pin, &rising, RISING);
    PPMintIn::pwm_value = micros()-PPMintIn::prev_time;
}

void PPMintIn::falling(){
    PPMintIn::latest_interrupted_pin=PCintPort::arduinoPin;
    PCintPort::attachInterrupt(latest_interrupted_pin, &rising, RISING);
    PPMintIn::pwm_value = micros()-PPMintIn::prev_time;
}

void PPMintIn::begin(){
    PCintPort::attachInterrupt(_pin, &rising, RISING);
}

void PPMintIn::getSignal(){
    return(PPMintIn::pwm_value);
}

Here is the .h code
#ifndef PPMINTIN_H
#define PPMINTIN_H

#if defined(ARDUINO) && ARDUINO >= 100
  #include "Arduino.h"
  #else
  #include "WProgram.h"
#endif
#include "PinChangeInt.h"

class PPMintIn{
public:
    PPMintIn(int pin);
    void begin();
    void getSignal();
    int _pin;
    volatile int pwm_value;
    volatile int prev_time;
    uint8_t latest_interrupted_pin;
private:
    void rising();
    void falling();
};

#endif // PPMINTIN_H

here is the full thing in github in case I didn't supply it here.
https://github.com/tisaconundrum2/PPMintIn

The IDE probably can't parse those full paths. Why are you using them instead of trusting that the IDE knows where the headers are?

because when i use the debug console included with IDE it can't find the files. It's only when i do the full paths, does it know what i want

Looking for header file C:\Users\User\Documents\Arduino\RCRoomba_TestPulseV2\libraries\PinChangeInt\PinChangeInt.h
Library.java 98 ():
Looking for header file :\Users\User\Documents\Arduino\RCRoomba_TestPulseV2\libraries\PPMintIn\PPMintIn.h
it just scrolls through this forever

http://i.imgur.com/awwtHKj.png

No, the compiler knows what you want. The IDE has no clue, so it doesn't include the libraries for compilation and linking.

the compiler does link to the library, however these libraries that it linked to are empty and have nothing in it.

I'm not sure that you understand what "linking" is. Especially given that the errors posted towards the top of this question are link errors.

Well alright, i did what you suggested, This is the outcome
http://i.imgur.com/W1gpqIh.png
And when i export both the libraries to see what's inside, they are basically empty new libraries

Now the IDE is doing the right thing. However, your "PPMintIn" library itself has errors that need to be fixed.

why is my library sitting with my INO file, i thought it should be going into the libraries folder.

You need to watch your capitalization as well - the Arduino header file is Arduino.h not arduino.h and your main header file (ppmintin.h) must have the same capitalization as your library folder (PPMintIn.h).  On operating systems with case sensitive filesystems it will completely break otherwise.

Which version of the IDE are you using, and how did you create the library in the first place?

It should be, right up until the IDE builds it. Then it copies everything into a single directory and builds it there.

http://i.imgur.com/r0BSQD5.png

Also you should take a look at this, it will tell you why you are getting some of your errors: http://arduino.stackexchange.com/questions/14480/pass-a-member-function-pointer-to-a-method-of-a-foreign-class-edb-lib

I redid all of my code, and deleted a bunch of copies of the same library. Anyways, I'm getting less errors now. That should be a good thing but i'm getting this one error
http://i.imgur.com/ZIhuule.png

which doesn't make sense to me because the function allows for ints
PPMintIn::PPMintIn(int pin){
pinMode(pin, INPUT);
digitalWrite(pin, HIGH);
_pin = pin;
}

As both Majenko and I tried to explain in Pass a member function pointer to a method of a foreign class (EDB Lib) you can't pass a class member function where a static function is expected.

Your error is on:
PCintPort::attachInterrupt(latest_interrupted_pin, &rising, RISING);

Error:
/home/nick/sketchbook/libraries/PPMintIn/ppmintin.cpp: In member function ‘void PPMintIn::rising()’:
/home/nick/sketchbook/libraries/PPMintIn/ppmintin.cpp:22: error: ISO C++ forbids taking the address of an unqualified or parenthesized non-static member function to form a pointer to member function.  Say ‘&PPMintIn::rising’

PCintPort::attachInterrupt expects a PCIntvoidFuncPtr variable:
int8_t PCintPort::attachInterrupt(uint8_t arduinoPin, PCIntvoidFuncPtr userFunc, int mode)

That is:
typedef void (*PCIntvoidFuncPtr)(void);

That is a static function (not a class function).
However you have it as a class function:
class PPMintIn{
public:
    PPMintIn(int pin);
    void begin();
    void getSignal();
    int _pin;
    volatile int pwm_value;
    volatile int prev_time;
    uint8_t latest_interrupted_pin;
private:
    void rising();
    void falling();
};

Now you can make rising and falling static but now they can't access any of the class variables (eg. pwm_value, prev_time, latest_interrupted_pin).
The whole thing needs a redesign. You could try making PPMintIn a namespace rather than a class.

Regarding one of the comments:

Unless your class implements operator() this line doesn't make sense:
chan1(15);

Please copy and paste error messages into the post, don't make people go to Imgur to find a screenshot of some text.


text:
How to change the topic_name string to PROGMEM?
I'm trying to save SRAM on my Arduino pro mini by going through some libraries. I've noticed that to use my Arduino as a ROS node the library stores the topic name and message type as constants.
class Publisher
{
public:
  Publisher( const char * topic_name, Msg * msg, int    endpoint=rosserial_msgs::TopicInfo::ID_PUBLISHER) :
    topic_(topic_name),
    msg_(msg),
    endpoint_(endpoint) {};

  int publish( const Msg * msg ) { return nh_->publish(id_, msg); };
  int getEndpointType(){ return endpoint_; }

  const char * topic_;
  Msg *msg_;
  // id_ and no_ are set by NodeHandle when we advertise
  int id_;
  NodeHandleBase_* nh_;

private:
  int endpoint_;
};

How can I store the constants to PROGMEM? Thank you

My take on this is that you cannot save more memory on topic-name nor msg parameters. Their memory usage is already optimized.
The const keyword in the constructor declaration Publisher( const char * topic_name, Msg * msg, ... just tells the compiler that the parameter won't be changed throughout their life cycle. But their values will be defined at run-time during object creation when you issue something like this:
Publisher pb = new Publisher("topic", "message", ...);

So, they cannot be put into flash memory if they are not there already. But if the strings you pass on to the constructor are already in flash, then you're already saving those bits of RAM.

Finally, I just wanted to warn you not to modify 3rd party lib code extensively without comprehensive testing, like you are trying to do. You'll start to get strange behavior in your code. The slightest and simplest of changes may have unforeseen consequences.

source: Stack Exchange

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

sort: votes


text:
Connecting to Arduino Ethernet Shield
How do I figure out how to connect to my arduino using ethernet shield?
It prints the IP in the serial monitor, but it doesn't work, and adding the port doesn't make a difference.
The client example works, so it's not broken or anything.
I'm using Arduino 1.6.5 IDE on a Mega 2560. I'm trying to run the Examples/Ethernet/WebServer example.

Please state which Arduino you have. Also which version of the IDE. You need to run one of the "server" examples, please state which example you are trying.

@NickGammon Like this?

What IP address are you using? What are you typing into your web browser? What do you see in the Serial Monitor?

@NickGammon That's in the original post: "It prints the IP in the serial monitor, but it doesn't work, and adding the port doesn't make a difference." Meaning I take the printed ip. using ip:port doesn't work either.

It prints the IP in the serial monitor - I'm not asking you to describe what you see. Please copy and paste it. What IP addresses are you using on your local LAN? For example, do you see a message like "new client"?

@NickGammon well, I meant to imply that I tried this IP and "it doesn't work". My browser gives me a 'timed out' message. I don't really know how to connect to it locally (or rather, how to find that IP) but I'm connecting to the same switch as the arduino

Your question is kind of trivial, but from what I understood you're typing the IP address (that the Arduino displays on the serial monitor)  into your browser.
First, make sure you connect your Ethernet shield to your router using an ethernet cable. (Now it's connected locally...)
Second, even if you type in your Arduino's IP address into the browser, the browser will return nothing because the Arduino simply has nothing to display, and hasn't been programmed to accept requests.
To actually have the Arduino display something you can try the Webserver example sketch or you can follow this great Tutorial that I found very useful for beginners.
BTW ports are only used to expose your Arduino to the Internet, in other words if you don't portforward to your Arduino, your Arduino won't be able to get requests from outside your local network (Wi-Fi,Ethernet).

Like I stated in the question, I'm using the webserver example sketch. I also portforwarded my arduino.

I think it would be more accurate to say that ports are used to identify the service running on the Arduino (for example to differentiate between HTTP and NTP). Port forwarding happens on the router and makes a service running on an internal host (at a private IP address such as 192.168.0.42 or 10.0.4.2) visible from the "outside world" (the WAN interface).

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


text:
Buzzer - Does the voltage change with the frequency?
So I have this project where the component "buzzer" is implementet. I was wondering if the voltage is changing along the change of frequency given to the buzzer?
Note that the project just says "buzzer" - not any more details.
Project: http://www.instructables.com/id/Arduino-Distance-Detector-with-a-Buzzer-and-LEDs/?ALLSTEPS

Please supply more details, this is just unanswerable. What project?

http://www.instructables.com/id/Arduino-Distance-Detector-with-a-Buzzer-and-LEDs/?ALLSTEPS

What voltage? The buzzer voltage? The frequency will change, not the voltage.

So the voltage in the circuit is not affected by the buzzer; say when it's on and when it's off?

The buzzer would consume some current which may lower the voltage. Why are you asking all this?

No, the frequency of the "buzzer" has no relationship to the voltage.
The duty cycle of the generated tone is proportional to the average voltage though.  Typically the duty cycle is 50% - that is it's turned on for half the time, and turned off the other half the time, to make a square wave.  This means that the average voltage is 50% of the supply voltage.
If you were to low-pass filter the signal (say through an RC filter as many people do to create a crude DAC) you would end up with a voltage around 2.5V.
Changing the frequency doesn't change the duty cycle, it only changes the audio pitch.
The only caveat to that is that if the buzzer draws more current that the IO pin (or the power supply) can source then it may cause the voltage on that IO pin to droop.  That has nothing to do with the frequency though and it would droop just the same at all frequencies.  Basically the IO pin has a small resistance to Vcc through the MOSFET that drives it internally - the higher the current the more voltage is dropped across that resistance, and the lower your resultant output voltage.  Draw too much current and the heat dissipated by that MOSFET's resistance becomes too great and damages the chip.


text:
UltraSonic sensor in rain?
I am onto a simple project with Arduino, SR04 and a buzzer for "Car reverse parking assistance". The aim here is to make a buzz when the car gets too close to the objects.
I was thinking what if it's raining when a person is driving (assuming I somehow achieved to water proof the sensor) - will the buzzer make continuous sounds?
Is there any alternative solution for ultrasonic sensors?

Try it and see? Wrap your sensor in something waterproof like a latex glove finger, and then put it in the rain. See if you get false readings. Or just take it into the shower with you. ;)

@NickGammon Wouldn't you just be sensing the distance of the latex from the sensor?

Yup, @Majenko is right!

There are special weather proof ultrasonic sensors available, like the one at the bottom of this page: http://www.futurlec.com/Ultrasonic_Sensors.shtml  Note: that is just the transducer, it needs extra circuitry to get it to work (similar to the circuit on the SR04) so don't just buy one and plug it into your Arduino then complain that it's not working.

Wouldn't you just be sensing the distance of the latex from the sensor? - possibly. That's why I suggested trying it. assuming i somehow achieved to water proof the sensor - in what way would you waterproof it without some sort of covering?

No i thought of making a case where in which drill 2 holes for trig and echo meshes and hot glue them from inside.i hope you get my point. Just like this http://www.amazon.in/Clear-Case-Arduino-UNO-Transparent/dp/B00HFSWC06?tag=googinhydr18418-21&tag=googinkenshoo-21&ascsubtag=54a371d4-b4ac-459e-b9c7-31f5e1299310&kpid=B00HFSWC06 where in they did for debug and power cords

Those sensors have a minimum range they can detect. Something like 2cm. So anything nearer than 2cm will not be detected.

@narzan I think the person asking the question was referring to water droplets in front of the sensor (assuming i somehow achieved to water proof the sensor).

oh ok :)  "1 up"

I tested the idea of covering the sensor with latex and can confirm that it does not work. :)

will the buzzer make continuous sounds

If you mean the sensor will detect the rain drops in the air
Nop it's tiny to read it in the air
But if there is drops on the sensor your sensor will not gives you the right reading
There is a water proof ultrasonic sensors available.
I am working on water level devices, after long path of searching in different ultrasonic sensors and after I tried a lot of method like using water proof Cloth, I found the best way is using water proof sensors PLUS water proof cloth.
water proof sensors work perfectly in high humidity but at the same time if there is a water drop on the sensor the reading will be different, and for that some cars manufacturers used not only one sensor, to avoid the errors. and calculate the differences.

The left car used old technology with separate sensors, but that's make errors the only good thing was to detect more things, in the next generation they mix them together.
water proof cloth will make the water drops not stuck at the sensor, but you will need to replace it every 5-6 months. "in your case because the sun will destroy the cloth" in my case and because my sensor inside tanks that's will least more.
I tried to spray the sensor with a different material to make my sensor not catch any water drops, it dose not work too.
And to make my cheap sensor water proof, I tried to use ceramic layers, and that's not work too, they use it with ultrasonic fog maker, these layers not work with cheap ultrasonic sensors, it's need a lot of power to vibrate it and different frequency. and of course you need to replace the layers "depending on the environment"
If you find ultrasonic car sensor with special material for water drops just let me know, I am searching on that too.
NOTE These days car manufacturer use different ways, in the past the cover was vibrate itself and made from aluminum, now they cover it and make different filters to ignore the plastic cover, How?! maybe it's different plastic or material maybe they find away to vibrate the plastic! sorry I could not find the secret.

thanks for sharing the information:) ,,,,As you said i will  use two sensors and compare among the data to make decisions ..

Ya that's will be more better :) you are welcome

It would probably be easier to use an IR distance sensor.  That would also be easier to waterproof.

Just a thought, a lot of cars use them, why not try your local salvage yard you may be able to get them on the cheap.

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


text:
Enabling pins of Arduino Due with direct port manipulation
I want to enable pin 13 on my SAM3X8E using direct port manipulation. On this chip the pin is bit 27 in port B, so I used PIOB->PIO_PER = 1<<27; to enable this pin, but it doesn't work. This pin keeps at 3.08V, the default value of non-initialized pins.
Here's my complete code:
#include <asf.h>

int main (void) {
  // Insert system clock initialization code here (sysclk_init()).
  board_init();
  sysclk_init();
  delay_init(sysclk_get_cpu_hz());
  PIOB->PIO_PER = 1<<27;
  PIOB->PIO_OER = 1<<27;
  while(1) {
    REG_PIOB_ODSR = 1<<27;
    delay_ms(1000);
    REG_PIOB_ODSR = 0<<27;
    delay_ms(1000);
  }
}

Can anyone tell me how I can get this to work?

I suggest the following test:  Use REG_PIOB_SODR = 1<<27; to set the bit, and  REG_PIOB_CODR = 1<<27; to clear it.  If that works ok, see about enabling synchronous data output via the port's PIO_OWSR register.  (If it doesn't work ok, perhaps review section 31.6, “I/O Lines Programming Example”, on page 629 of Atmel document 11057, the Cortex datasheet.)
Section 31.5.5, “Synchronous Data Output”, on page 623 says in part:

After reset, the synchronous data output is disabled on all the I/O lines as PIO_OWSR resets at 0x0.

I imagine that writes to REG_PIOB_SODR and  REG_PIOB_CODR should have effect after you enabled output by setting bits in PIOB->PIO_PER and PIOB->PIO_OER, which you did.  However, with the bit in PIO_OWSR being clear, synchronous data output isn't available, so writes to REG_PIOB_ODSR have no effect.

    #define Led_ON  REG_PIOB_ODSR |= 0x8000000
    #define Led_OFF REG_PIOB_ODSR &= ~0x8000000
    //for Arduino Due
    PIOB->PIO_PER |= 0x8000000;//led
    PIOB->PIO_OER |= 0x8000000;//led

And then call Led_ON and Led_OFF


text:
Problem with codebender project not compiling
I have written a codebender project which returns this error:
Oops! Looks like there was a serious issue with your project.

If you are not sure what could be wrong please contact us

/mnt/tmp/compiler.amxHJ9/files/Many Games.o: In function `gamesMaster::gamesMaster()':
Many Games.cpp:(.text._ZN11gamesMasterC2Ev+0xa): undefined reference to `vtable for gamesMaster'
Many Games.cpp:(.text._ZN11gamesMasterC2Ev+0xc): undefined reference to `vtable for gamesMaster'

What does it mean by vtable?
The code uses basic classes and inheritance.
The program is designed to select and play the game of your choice.  I have only programmed the basic structure.
Class games contains a ref to the class gamesMaster.
Class gamesMaster contains a ref to simpleTimer.
Classes playHiLow and playSimon are children of gamesMaster.
Class games handles and input and outputs, win and lose control and keeps track of lives.
Class gamesMaster handles the simpleTimer, displays a new round, checks for the correct answer, and checks if game has finished successfully.
The main() function runs a routine in the games class.
The code is listed here: https://codebender.cc/sketch:144869
class simpleTimer
{
private:
    unsigned long _previousMillis;
    unsigned long _interval;

public:
    simpleTimer()
    {

    }
    void start(float mins)
    {
        _interval = (unsigned long) (mins * 60 * 1000);
        _previousMillis = millis();
    }
    bool stillRunning()
    {
        return (millis() - _previousMillis < _interval);
    }
};

class gamesMaster
{
public:
    unsigned short lives;
    gamesMaster()
    {
        timeOutTimer = new simpleTimer();
        gameTimer = new simpleTimer();
        gameTimer->start(1.5);
        lives = 5;
    }
    void right()
    {
        Serial.println("Correct");
    }
    void wrong()
    {
        Serial.println("Wrong");
    }
    void winGame()
    {
        Serial.println("**********");
        Serial.println("* WINNER *");
        Serial.println("**********");
    }
    void loseGame()
    {
        Serial.println("\\ /          \\ /");
        Serial.println(" X    LOST    X");
        Serial.println("/ \\          / \\");
    }
    void startTimeOut(float mins)
    {
        timeOutTimer->start(mins);
    }
    bool notTimedOut()
    {
        return timeOutTimer->stillRunning();
    }
    bool gameTimerOver()
    {
        return !gameTimer->stillRunning();
    }
    simpleTimer *timeOutTimer;
    simpleTimer *gameTimer;

    virtual void setupForNewRound(void);
    virtual bool checkAnswer(unsigned short);
    virtual bool reachedEnd(void);
};

class gameHiLow: public gamesMaster
{
public:
    gameHiLow() : gamesMaster() {}
    void setupForNewRound()
    {
        Serial.println("  ->(HiLow) New round");
    }
    bool checkAnswer(unsigned short answer)
    {
        Serial.println("  ->(HiLow) Correct Answer");
        return HIGH;
    }
    bool reachedEnd()
    {
        Serial.println("  ->(HiLow) End of game");
        return HIGH;
    }
};

class gameSimon: public gamesMaster
{
public:
    gameSimon() : gamesMaster() {}
    void setupForNewRound()
    {
        Serial.println("  ->(Simon) New round");
    }
    bool checkAnswer(unsigned short answer)
    {
        Serial.println("  ->(Simon) Correct Answer");
        return HIGH;
    }
    bool reachedEnd()
    {
        Serial.println("  ->(Simon) End of game");
        return HIGH;
    }
};

class games
{
private:
    unsigned short _gameToPlay;
    unsigned short _levelToPlay;
    gamesMaster *myGame;
    unsigned short _getAnswer()
    {
        if (Serial.available() > 0)
        {
            int inByte = Serial.read();
            Serial.println("  ->(games) Decode Answer");

            switch (inByte)
            {
                case '<':
                    return 1;
                    break;
                case '>':
                    return 2;
                    break;
            }

        }
        return 0;

    }
    bool _respond()
    {
        unsigned short answer;
        while(myGame->notTimedOut())
        {
            if((answer = _getAnswer()) != 0)
            {
                if(myGame->checkAnswer(answer) == HIGH) return HIGH;
            }
        }
        return LOW;
    }
public:
    games(unsigned short gameToPlay, unsigned short levelToPlay)
    {
        _gameToPlay = gameToPlay;
        _levelToPlay = levelToPlay;
        switch(_gameToPlay)
        {
            case 1:
                myGame = new gameHiLow();
                Serial.println(" ->(game) play Higher or Lower Game");
                break;
            case 2:
                myGame = new gameSimon();
                Serial.println(" ->(game) play Simon Game");
                break;
        }
    }
    void play()
    {
        unsigned short answer;
        while(!myGame->gameTimerOver())
        {
            myGame->setupForNewRound();
            myGame->startTimeOut(.5);
            if(_respond() == HIGH)
            {
                myGame->right();
                if(myGame->reachedEnd())
                {
                    myGame->winGame();
                    return;
                }
            }
            else
            {
                myGame->wrong();
                if(--myGame->lives <= 0)
                {
                    myGame->loseGame();
                    return;
                }
            }
        }
        myGame->loseGame();
    }
};

//////////////////////////////////////////////////////////////////////////////////
games *game;

void setup()
{
    Serial.begin(9600);
    unsigned short gameToPlay = 1;
    unsigned short levelToPlay = 1;
    game = new games(gameToPlay, levelToPlay);
}

void loop()
{
    Serial.println("Let the games begin");
    game->play();
    Serial.println("Program Complete");
    delay(5000);
    exit(0);
}

I agree with @GeryOshlike.  But that's not the only option.
Yes, you can make them pure virtual:
virtual void setupForNewRound(void) = 0;
virtual bool checkAnswer(unsigned short) = 0;
virtual bool reachedEnd(void) = 0;

Or you can make them virtual with a default function:
virtual void setupForNewRound(void) { }
virtual bool checkAnswer(unsigned short) { return false; }
virtual bool reachedEnd(void) { return false; }

Pure virtual will complain when you compile if you haven't implemented those functions in your child class.  By providing a default function body it will not complain if you haven't implemented it, and will just use the default body.
If it's a function which you know will always have to be implemented at the child level (will always be different) then go the pure virtual route.  If it's a function that will be the same in a number of children but differ in only a few, then providing the default body and overriding with different ones when needed is the better way to go.

As discussed here
https://stackoverflow.com/questions/3065154/undefined-reference-to-vtable
declare these functions pure virtual:
virtual void setupForNewRound(void) = 0;
virtual bool checkAnswer(unsigned short) = 0;
virtual bool reachedEnd(void) = 0;


text:
Atmega328 board output voltage
I'm thinking about making my own "arduino" low power board but I have a question about the atmega328. Is the output voltage on the pins always 5v or it depends on the input voltage I gave to the atmega?
Thanks in advance.

What Majenko said. | Note that 'rolling your own' for experience and/or fun is fine BUT you can buy good quality Chinese made clones for less than the cost of the components.

@RussellMcMahon Yes, but the original and clones draw too much energy, I need something more simple that can save energy for a battery powered project. Thanks for the note anyways (:

The clones draw > minimum power only due to extra components on them Versions with no USB/serial IC are available (and even cheper) = Pro Mini. And regulator can be removed if safe Vcc can be provided. And onboard LED drive is optional. If desired all you have left is ~= uC IC and cryctal osc and current can be in the few microamps when doing nothing and not vastly more when crawling along with all or most peripherals off. There is a very good 'how to reduce '328 current draw article somewhere. Probably cited in this group and I can probably did it up.

Well, an atmega328p can run on its own internal oscillator to save even more power.. And you can integrate it directly on the board rather than using connectors, so it's more "professional"/smaller. It depends on the needs

It depends on the input voltage you give it.  If you run the ATMega328p at 3.3V then you get 3.3V out.  If you run it at 5V you get 5V out.
A word of caution about running at lower voltages:  The chip can't run as fast when it has a lower supply voltage - that's why you will see the 3.3V Arduino boards running at 8MHz (or 12MHz at a pinch).

Thanks very very very much. That's exactly what I needed to know (:


text:
First recieved packet not displayed (Arduino with MRF24j40MA)
I'm trying to make two Arduino cards communicate, one is a sender and the other only receive packet from the first one and then display them.
My problem is that the first recieved packet is not displayed unlike the other packets(displayed normally)
here's the output of my code :

Here's my code of the reciever :
void handle_rx() {

Serial.print("received a packet ");Serial.print(mrf.get_rxinfo()->frame_length, DEC);Serial.println(" bytes long");

if(mrf.get_bufferPHY()){
  Serial.println("Packet data (PHY Payload):");
  for (int i = 0; i < mrf.get_rxinfo()->frame_length; i++) {
      Serial.print(mrf.get_rxbuf()[i]);
  }
}

Serial.println("\r\nASCII data (relevant data):");
for (int i = 0; i < mrf.rx_datalength(); i++) {
    Serial.write(mrf.get_rxinfo()->rx_data[i]);
}

Serial.print("\r\nLQI/RSSI=");
Serial.print(mrf.get_rxinfo()->lqi, DEC);
Serial.print("/");
Serial.println(mrf.get_rxinfo()->rssi, DEC);
}

Here is the complete sketch:
/**
 * Example code for using a microchip mrf24j40 module to send and receive
 * packets using plain 802.15.4
 * Requirements: 3 pins for spi, 3 pins for reset, chip select and interrupt
 * notifications
 * This example file is considered to be in the public domain
 * Originally written by Karl Palsson, karlp@tweak.net.au, March 2011
 */
#include <SPI.h>
#include <mrf24j.h>

const int pin_reset = 6;
const int pin_cs = 7; // default CS pin on ATmega8/168/328
const int pin_interrupt = 2; // default interrupt pin on ATmega8/168/328

Mrf24j mrf(pin_reset, pin_cs, pin_interrupt);

long last_time;
long last_time2;
long tx_interval = 1000;

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

  mrf.reset();
  mrf.init();

  mrf.set_pan(0xcafe);
  // This is _our_ address
  mrf.address16_write(0x4201);

  // uncomment if you want to receive any packet on this channel
  //mrf.set_promiscuous(true);

  // uncomment if you want to enable PA/LNA external control
  //mrf.set_palna(true);

  // uncomment if you want to buffer all PHY Payload
  //mrf.set_bufferPHY(true);

  attachInterrupt(0, interrupt_routine, CHANGE); // interrupt 0 equivalent to pin 2(INT0) on ATmega8/168/328
  last_time = millis();
  interrupts();
}

void interrupt_routine() {
    mrf.interrupt_handler(); // mrf24 object interrupt routine
}

void loop() {
    mrf.check_flags(&handle_rx, &handle_tx);
    unsigned long current_time = millis();
    if (current_time - last_time > tx_interval) {
        last_time = current_time;
        Serial.println("txxxing...");
        mrf.send16(0x4202, "abcd");
    }
}

void handle_rx() {
    Serial.print("received a packet ");Serial.print(mrf.get_rxinfo()->frame_length, DEC);Serial.println(" bytes long");

    if(mrf.get_bufferPHY()){
      Serial.println("Packet data (PHY Payload):");
      for (int i = 0; i < mrf.get_rxinfo()->frame_length; i++) {
          Serial.print(mrf.get_rxbuf()[i]);
      }
    }

    Serial.println("\r\nASCII data (relevant data):");
    for (int i = 0; i < mrf.rx_datalength(); i++) {
        Serial.write(mrf.get_rxinfo()->rx_data[i]);
    }

    Serial.print("\r\nLQI/RSSI=");
    Serial.print(mrf.get_rxinfo()->lqi, DEC);
    Serial.print("/");
    Serial.println(mrf.get_rxinfo()->rssi, DEC);
}

void handle_tx() {
    if (mrf.get_txinfo()->tx_ok) {
        Serial.println("TX went ok, got ack");
    } else {
        Serial.print("TX failed after ");Serial.print(mrf.get_txinfo()->retries);Serial.println(" retries\n");
    }
}

There's something wrong with your code. It looks like there may be some parts missing from it.  Try reading this: http://snippets-r-us.com/

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


text:
Arduino ESP8266 receive email?
Is there a sketch that supports the receiving of email using the Arduino environment on the ESP8266? I can only find support for sending email. I know it's possible because the NodeMCU environment supports it. Any help is appreciated!

receiving e-mail as in acting as an e-mail server, or simply pulling e-mail from another server?

Pulling email from another server

In that case it depends on the interface of the other server that you are pulling the mail from - the easiest might be from a web interface, in which case something like this could work

Once you know how to connect to any server and send messages to it, retrieveing emails is just a matter of sending right messages (=commands).
Here below follows an "IMAP tutorial", i.e. guide to which commands to send to an IMAP server to search and retrieve messages.
Note: once you connect to the IMAP server, the first command to send is the login command:
foo login user password

"foo" is just a session identifier, not a keyword. "login" is the keyword.
Once you get the welcome message, you can start sending more commands:
Select the proper folder:
. SELECT "INBOX"

Look for desired message (strings are always considered substrings, so no wildcards are needed):
. SEARCH FROM "user@example.org" SUBJECT "some keywords here"

This will result in list of matching messages, with search results formatted as follows:
* SEARCH 5 10 456

This means messages n.5, n.10 and n.456 match the query.
If examining just the subject (which may contain keywords and switch as required) is not enough, the whole body can be retrieved, both marking the message as read or leaving it untouched:
. FETCH 5  BODY[TEXT]

or
. FETCH 5  BODY[TEXT].PEEK

End IMAP session with:
. logout

For experiments from Windows using telnet:
telnet mailserver.domain.com 143

Reference:
https://www.skytale.net/blog/archives/23-Manual-IMAP.html


text:
adding a dead band to my motor and gearbox
I have a motor and gearbox that has limits and a pot built in.
I have some code what drives the motor one way to when it hits its limits takes a value and drives the other way and takes a value, then map the range from 0 to 100, that all works fine.
I also have a analog input map to 0 to 100 what I would like to do is to drive the motor to where ever the analog input is at, which is what I have done with the code below but when the motor gets close it starts hunting backwards and forwards.
I tried to add some sort of dead band (where + 0.5 / where - 0.5) it just seems to just move the problem.
I did try -+ but this still did not help, so what I need to do is aim for the target value and stop then if I'm within 0.5 ether way then that is good enough.
How can I do that?
sensor       = pot on motor,
where        = 0 to 5 input,
vent1UPlim   = limits,
vent1DOWNlim = limits

PS. I know the map of 0 to 100 could do with being bigger but it's just easier to get my head around at the moment.
        //            pot           0-10v     ONE WAY
          if (sensorValue > (where + 0.5)) {
          if (digitalRead(vent1UPlim)==    HIGH) {
            DoneInitializationA=false;
            digitalWrite(vent1enable,      HIGH);
            delay(50);
            digitalWrite(vent1PWMA ,       HIGH);
            mydisp.drawStr(0, 2, "-close-|");
          }
          else {
            digitalWrite(vent1PWMA ,       LOW);
            delay(50);
            digitalWrite(vent1enable,      LOW);
            mydisp.drawStr(0, 2, "       |");
          }
        }
        else {
          if (!DoneInitializationA)
          {
            digitalWrite(vent1PWMA ,       LOW);
            delay(50);
            digitalWrite(vent1enable,      LOW);
            mydisp.drawStr(0, 2, "       |");
            DoneInitializationA=true;
          }
        }

           //                                   OTHER WAY
          if (sensorValue < (where - 0.5)) {
          if (digitalRead(vent1DOWNlim)==  HIGH) {
            DoneInitializationB=false;
            digitalWrite(vent1enable,      HIGH);
            delay(50);
            digitalWrite(vent1PWMB ,       HIGH);
            mydisp.drawStr(0, 2, "-open -|");
          }
          else {
            digitalWrite(vent1PWMB ,       LOW);
            delay(50);
            digitalWrite(vent1enable,      LOW);
            mydisp.drawStr(0, 2, "       |");
          }
        }
        else {
          if (!DoneInitializationB)
          {
            digitalWrite(vent1PWMB ,       LOW);
            delay(50);
            digitalWrite(vent1enable,      LOW);
            mydisp.drawStr(0, 2, "       |");
            DoneInitializationB=true;
          }
        }

I don't quite understand how your motors work: Do they keep doing the last thing they were told, or do you have to keep sending some signal to them - even to stay at the same speed?

enable the drive pull hight (vent1enble), and to drive the motor pull one pin high and to go the other way pull the other pin high (vent1PWMA or vent1PWMA)

OK, so if you do nothing, the motor keeps turning at the same rate in the same direction as before? So, doing nothing if it is near the desired sensor value is OK?

if i do nothing the motor does nothing. doing nothing near the desired value yes

The simple way is to just subtract one from the other, take the absolute value and see if it exceeds your hysteresis range.
eg.
if (abs (sensorValue - where) >= 0.5) {
  {
  // do something

  if (sensorValue > where)
    {
    // one way
    }
  else
    {
    // other way
    }
  } // end of large enough to worry about

In response to this (since deleted):

would this not have the same problem as mine as instead of hunting round its target it will just do it 0.5 away from the target?

By subtracting and taking the absolute value, we create a band of +0.5 and -0.5 where, if the sensor is in that range, we do nothing. It hasn't moved the problem because it can't move in two directions at once (both up and down).

would this not have the same problem as mine instead of hunting round its target it will just do it 0.5 away from the target? as what will drive it into the middle (the target value)?   i hope you understand what I'm trying to get to
thanks Joe


text:
Can I program the Arduino without having an actual board with the able to emulate a COM connection to the computer?
I have ordered my Arduino, but it is not going to arrive until 2 months, and I would like to be able to emulate a COM connection to the emulated Arduino. I am writing a program that listens on the com port, and would like to test it.
The program needs to run on Windows, and emulate a COM connection, and a breadboard with a LED, and motors on it.

You could use the Simulator in Atmel Studio or something like Virtual Breadboard which looks good
The Atmel Studio simulator might take a bit of work to simulate your devices but if you have 2 months then maybe that's okay :) If you want to use the simulator in Atmel Studio then you might also find the Arduino plugin for Atmel Studio useful.
I think there are quite a few other solutions if you search google.

To verify communication via COM port (to send messages as well as to receive) you can use arduino emulator from wokwi.com
with the Wokwi arduino emulator, it is easy to do the changes, add input devices as well.
To create a COM port
You just need to have a
Serial.begin(9600);
Serial.println("Text message");

you will be able to see the virtual serial window in the bottom right where you can see the messages printed out as well as you will be bale to key in the serial data you want to send to Arduino.


text:
Wifi.status() always returns WL_NO_SHIELD
I've an Arduino Mega 2560 R3 and recently bought a Wifi Shield CC3000 from ebay http://www.ebay.de/itm/201405512301
They write that the firmware has the version ServicePack 1.11.1.
The WiFi shield is connected to the Arduino and green status light is on.
I try to run this example code:
void setup() {
  //Initialize serial and wait for port to open:
  Serial.begin(9600);
  while (!Serial) {
    ; // wait for serial port to connect. Needed for Leonardo only
  }
}

// check for the presence of the shield:
if (WiFi.status() == WL_NO_SHIELD) {
  Serial.println("WiFi shield not present");
    // don't continue:
  while(true);
}
...

It seems that Wifi.status() always returns WL_NO_SHIELD.
What can I do?
Thanks for help.

Are you using a CC3000 library, or the IDE's WiFi library that is written for the Wiznet chip?

The problem is solved now.

I imported the Adafruit_CC3000 library which can be downloaded here: https://github.com/adafruit/Adafruit_CC3000_Library
I run the example but the output was chinese nonsense
Instead of
Serial.begin(115200);
I used
Serial.begin(9600);
then the examples run without any problem

Thanks @Majenko. His question was very helpful.


text:
Reversed Input Voltage Arduino Mega timeout communication with programmer error
On the barrel connector I accidentally reversed the input voltage to an Arduino Mega. The center post received ground while the outer connection received +12DVC, basically I have the Arduino -12VDC. I have since fixed this problem. When I power the Arduino with the USB I am able to program the Arduino without a problem. When I power the Arduino with the +12VDC the program still runs (confirmed by programming the blink sketch). If I have the +12VDC connected and try to program the Arduino then I get the timeout communication error.
Do I just need to re-burn the bootloader? The Arduino's symptoms match those listed here when both cables are connected: Arduino Mega timeout communication with programmer error
Is there anything else I should verify? Or is the Arduino always going to be damaged?
Also as a note I did the same thing to an Arduino Uno (same rail going to both) and the Uno has no problems when both USB and power are connected.

Don't reprogram the bootloader.
If you can upload sketches that is unnecessary.
It will probably be fiddly to identify and fix what has failed, but since you can reprogram it via USB it is still 99% working.
I suggest you get one of those USB charging wall-warts that provide 5 V, and just plug that into the USB port if you want to run it away from the PC. You know that the USB power part works.

Chances are you have blown up the circuitry that performs the switching between barrel jack and USB power sources.  As a result the USB interface chip isn't getting power when it should.
In short: "It's dead, Jim!"

It's still functional as long as I unplug the power connector before programming. It seems like it should be a small fix if I can identify the issue.

There's an op-amp and a P-channel MOSFET.  You may need to replace one or both of them.  First though diagnose the problem with a DMM.

Agreed. Trace the power with the schematic in one hand and a multimeter in the other. There's a reverse-polarity protection diode (D1) as well. 12 V shouldn't have blown that. Still, worth checking out.

The Mega has a reverse polarity protection diode (D1) on the board, so you plugging in the wrong polarity barrel didn't damage anything.
So your current problem in unrelated to this.


text:
Removing the barrel jack connector?
My project is battery powered and it has it's own usb port for charging. Can I snip off the HUGE DC barrel jack which is making it hard for me to fit this into an enclosure.
Or could that cause problems?

Have you considered using a smaller Arduino?

You'll likely do less damage de-soldering it than trying to snip it off. Use a de-soldering pump to remove as much molten solder as you can, then heat again with de-soldering braid to wick up the remainder. If the jack's solder terminals were bent over (to stabilize the part before it was soldered) you may need to straighten them with a tweezer-nosed plier. Then you should be able to lift the part off the board. Don't overheat the board or heat any other parts or solder joints than those you intend to remove.

You can remove it safely without any issues, just make sure that there are no short circuits or any other components damaged while doing so

De sdering would be safer.  You can then use the Vin pin to supply sour voltage (IIRC you can run as high as 12 volts with the uno)

Unless you have some really specific reason to use a UNO, for example using the 2nd ATMega on the board, you would be much better off with an Micro Pro.
On ebay you can find both 3.3V and 5V versions.
You can even find ones that have redundant pins, to accommodate for a permanent installation of the ISP programmer.
Even if you happen to have a shield that is compatible with the UNO pinout, you could still wire it with a flat cable and save space.
Said this, using mechanical means on a PCB is always putting at risk the tracks, which might come off.
Desoldering is better, since it's reversible.
But you might find that it takes an unusually powerful soldering iron, compared to what is used nowadays for smd components, as you will have to heat up simultaneously several large pads, which have connected large tracks and ground areas that act as heat sink.
In case you do not have desoldering braid and or pump, there's a hackish method to remove large components with multiple pads: flood them in molten solder and literally shake them off the board by hitting the workbench sideways, while the solder is still fluid.
Not nice and at risk of adding splash shorts to the board, not to mention the splash damage to the operator: it can cause burns on unprotected skin or organs.
However, if done correctly, it works without pump or braid.


text:
Using an arduino to emulate keyboard inputs
I have a shapeoko 2, and have been wanting to create a jogging pendant for it for a while.  Currently GRBL (the G code interpreter for arduino) doesn't support jogging the machine with a pendant.  I was wondering if it was possible to emulate arrow key inputs on the keyboard through an arduino.

Pretend, for a moment, that we don't know what a "shapeoko 2" is, or even what jogging a machine with a pendant entails.  Instead focus on exactly what you want to achieve from the Arduino in a more generic form.

Your answers might lie in the Arduino reference pages: https://www.arduino.cc/en/Reference/MouseKeyboard https://www.arduino.cc/en/Reference/KeyboardModifiers

Every arduino with programmable USB chip like Arduino Uno or Arduino Mega is capable of emulating any USB device.


text:
Bluetooth Trancievers for arduinos
Would it be possible to use to of these on two separate arduino's, to send and receive information? I am having difficulties understanding the chinese-english descriptions and haven't seen any documentation on doing this. There would be no phone involved. There would only be two arduino's with a Bluetooth module on each of them sending and receiving data from each other.

The boards in your link look funny.  Typical boards like this include the "bluetooth circuit" which piggy-backs onto that board, and is soldered at all those little pads.
Have a look at say, the HC-05 board ~  https://www.google.com.au/search?q=hc05+bluetooth+module&tbm=isch
It's easy to see the part that's missing from the one in your link.
For these HC-05 boards, it's possible to pair two together.  They need to be configured as "Master" and "Slave" though.  Some bluetooth boards can do slave-mode only, so be careful before you purchase.

To add to this old thread, HC-05 is not the same as HC-06.  HC-06 is a "slave only" model, like @Kingsley mentioned.


text:
Serial problem after implementing data structures
Context
I first ran a sketch (on Arduino Uno) without any custom data structure and list, so I was using a bunch of arrays, methods and other primitive variables. And it worked perfectly.
My program acts like a menu which takes serial user input to perform actions. So you could have serial input "man r+(100,0,345)". Or just "man" to set this mode active, and later "r+(100,0,345)" to actualize the data in the "r" field in the "man" instance. I use a custom data structure to manage the input (class called Mode), and a linked list (class called ModeList).
Problem
I implemented some data structures (an object and a list) to manage incoming serial data, without modifying the rest of the program. But now, serial communication is not working properly: If I add Serial.print("Allo") anywhere in the sketch, it will print spaces for a while and stop, before I send any serial data. If it is in the setup() function, it prints spaces continuously with some characters from "Allo" from time to time. There's always a different problem along those lines, depending on where I put that simple print statement.
Here follows the sketch, the header files of the Mode and ModeList classes... By the way, I suspect a memory management problem.
The sketch
#include "Mode.h"
#include "ModeList.h"

const int inputSize=12;
const int nbModes=4;
int input;
int toSet[inputSize];
int i;

char manName[3]={'m','a','n'};
char cutName[3]={'c','u','t'};
char levName[3]={'l','e','v'};
char autName[3]={'a','u','t'};

Mode m=Mode(0,manName);
Mode c=Mode(1,cutName);
Mode l=Mode(2,levName);
Mode a=Mode(3,autName);
Mode* man=&m;
Mode* cut=&c;
Mode* lev=&l;
Mode* aut=&a;
ModeList modeList=ModeList();

void setup() {
  Serial.begin(115200);
  Serial.print("Allo");
  modeList.add(man);
  modeList.add(cut);
  modeList.add(lev);
  modeList.add(aut);
  }

void loop() {
  for(int j=0;j<inputSize;j++)
  {
    toSet[j]=NULL;
  }
  i=0;
  if(Serial.available()>0)
  {
    while(Serial.available())
    {
      if(i<inputSize)
      {
        input=Serial.read();
        if(input!=' ' && input!='(' && input !=')' && input!=',' && input!='\n')
        {
          toSet[i]=input;
          i++;
        }
      }
    }
  }

  if(serialMode(man)||man->getStatus())
  {
    //Set man on
    modeList.setMode(man);

    if(toSet[3]=='r')
    {
      if(toSet[4]=='+')
      {
        //Set ypr rate
        Serial.println("Set ypr rate +");
      }
      else if(toSet[4]=='-')
      {
        //Set ypr rate
        Serial.println("Set ypr rate -");
      }
      else
      {
        //Set ypr rate
        Serial.println("Set ypr rate");
      }
    }
    else if(toSet[3]=='a')
    {
      if(toSet[4]=='+')
      {
        //Set ypr angle
        Serial.println("Set ypr angle +");
      }
      else if(toSet[4]=='-')
      {
        //Set ypr angle
        Serial.println("Set ypr angle -");
      }
      else
      {
        //Set ypr angle
        Serial.println("Set ypr angle");
      }
    }
    else if(toSet[3]=='t')
    {
      if(toSet[4]=='+')
      {
        //Set thrust
        Serial.println("Set thrust +");
      }
      else if(toSet[4]=='-')
      {
        //Set thrust
        Serial.println("Set thrust -");
      }
      else
      {
        //Set thrust
        Serial.println("Set thrust");
      }
    }
  }
  if(serialMode(cut)||cut->getStatus())
  {
    //Cut engines
    modeList.setMode(cut);
    if(serialMode(cut))
      Serial.println("Cut");
  }
  if(serialMode(lev)||lev->getStatus())
  {
    //Stabilize axes
    modeList.setMode(lev);
    if(serialMode(lev))
      Serial.println("Level");
  }
  if(serialMode(aut)||aut->getStatus())
  {
    //Set aut on
    modeList.setMode(aut);
    if(serialMode(aut))
      Serial.println("Set aut on");
    if(toSet[3]=='s')
    {
      if(toSet[4]=='+')
      {
        //Set ypr angle
        Serial.println("Set ypr angle +");
      }
      else if(toSet[4]=='-')
      {
        //Set ypr angle
        Serial.println("Set ypr angle -");
      }
      else
      {
        //Set ypr angle
        Serial.println("Set ypr angle");
      }
    }
    else if(toSet[3]=='A')
    {
      if(toSet[4]=='+')
      {
        //Set altitude
        Serial.println("Set altitude +");
      }
      else if(toSet[4]=='-')
      {
        //Set altitude
        Serial.println("Set altitude -");
      }
      else
      {
        //Set altitude
        Serial.println("Set altitude");
      }
    }
  }
  delay(10);
}

bool serialMode(Mode* inputMode)
{
  char* modeName;
  modeName=inputMode->getName();
  Serial.print("ALLO");
  if(toSet[0]==*modeName&&toSet[1]==*(modeName+1)&&toSet[2]==*(modeName+2))
  {
    Serial.print("Set ");
    for(int i=0;i<3;i++)
    {
      Serial.print(*(modeName+i));
    }
    Serial.println(" on");
    return true;
  }
  else
    return false;
}

The Mode class header
#include "Arduino.h"

class Mode
{
    public:
        Mode(int id, char* name);
        int getId();
        Mode* getNext();
        void setNext(Mode m);
        void setStatus(bool status);
        bool getStatus();
        char* getName();
    private:
        char *_name;
        int _id;
        Mode* _next;
        bool _status;
};

The ModeList class header
class ModeList
{
    public:
        void add(Mode* input);
        int get(int pos);
        ModeList();
        void setMode(Mode* inputMode);
    private:
        Mode* start;
        Mode* end;
};

If I add Serial.print("Allo") anywhere in the sketch, it will print spaces for a while and stop, before I send any serial data.

Classic symptoms of using up all available RAM.
As a workaround I would use the F() macro.
eg.
    Serial.println(F("Set ypr rate +"));

Do that in all places where you are printing string literals. That would save you a couple of hundred bytes.


text:
What is the overhead time of using Serial library compared to coding it up in AVR C (not using Arduino code)?
I am using an Arduino UNO to drive a UART throughput test and to also test the latency of the slave microcontroller.
The setup is as follows:
Arduino|---UART--------------------------|MCU2
Arduino|---FLOW_CONTROL_PIN---|MCU2
I am sending data to the MCU2 over the UART with a specified delay between writes, and in MCU2 I have a certain buffer threshold where I set an overflow pin indicator back to the Arduino (using INT0), where when the interrupt is triggered, I stop sending data (hardware based flow control).
At this point I log the amount of bytes sent and compare that to the buffer threshold level.  If the bytes sent are equal to the threshold point, I know the latency of the path (threshold-->toggle flow pin-->Arduino interrupt and stop transmit) is ok (if not, we are having latency issues and probably need to do a software based flow control). I then do the whole process again, with a shorter delay.  I then can find the delay point that will result in the fastest continuous transfer rate (this is testing throughput as well as latency of the slave MCU).
A problem can arise if the Arduino api is providing more latency than the path under test.  I believe this is most likely the case, but wanted to see if there has been any concrete numbers on the overhead of Arduino, particularly in regard to its Serial api.  I used Arduino to get something running quickly, but if it doesn't allow me to actually test the system, need to go to using all AVR C or use another MCU for the transmit side.

There's no reason to doubt the Arduino hardware. We need to put some figures on what you are experiencing, such as the baud rate and buffer sizes.
I would expect with this sort of hardware flow-control that you would potentially send a byte or so more than expected, because it takes a finite time to react to the flow-control signal. This is to be expected, particularly as the hardware has a buffer, so it can be starting to send a byte at the moment you get the signal to stop sending.
I expect you would have a leeway (say of 10 bytes) where you expect the sender to stop sending within that time.

A problem can arise if the Arduino API is providing more latency than the path under test

I'm not sure what you mean by this. However the HardwareSerial class has a 64-byte buffer (if you are using a Uno) which means you potentially have put 64 bytes into it, before noticing that the sender wants you to stop sending.
This is probably what you are experiencing. See HardwareSerial.cpp:
// Define constants and variables for buffering incoming serial data.  We're
// using a ring buffer (I think), in which head is the index of the location
// to which to write the next incoming character and tail is the index of the
// location from which to read.
#if (RAMEND < 1000)
  #define SERIAL_BUFFER_SIZE 16
#else
  #define SERIAL_BUFFER_SIZE 64
#endif

For this test you might want to edit that file and reduce that number, substantially.
Alternatively, use SoftwareSerial. I don't think that buffers writes (as it doesn't have hardware to do them in the background) so that would reduce the latency to a single byte.

I believe this is most likely the case, but wanted to see if there has been any concrete numbers on the overhead of Arduino, particularly in regard to its Serial API.

It's not an overhead, it's a design issue. If you do what I suggested it should work fine.

What I mean by Arduino API overhead is the fact that the actual hardware interface is substantially abstracted away from the register level implementation ...

Well, not really. When you write a byte it puts it into a circular buffer, as you would expect. When the hardware is free to output another byte (generally called by an interrupt) it outputs it. What else could it do?
However you are absolutely free to address the hardware registers yourself and not use HardwareSerial.
To keep things simple though, what you really need to do here is not buffer because that makes reacting to the flow-control flag somewhat slow. And here is how to do it:
Serial.write ('a');  // or whatever
Serial.flush ();  // wait until everything is sent

Now you have thrown away the buffering, and you can just send at the rate that the hardware can (probably slightly less).

what I mean by Arduino API overhead is the fact that the actual hardware interface is substantially abstracted away from the register level implementation.  I have noticed substantial speedup when I go from the Arduino API to coding it all up myself at a register level (i.e. digitalWrite() vs setting up PORTnx/DDnx/PINnx, etc.) and want to make sure that any overhead involved with using the API is not significantly going to effect my results.

@ryeager: Buffering and overhead are two different things. digitalWrite() has a big overhead and no buffering, while your issue with HardwareSerial seems to be about buffering.

See additional couple of paragraphs in reply.


text:
RTC resets when power is off
I have a few RTC modules with a batteries. All of them have this same issue with my project.
They work fine when connected via USB. But if I disconnect the power then reconnect they reset to Jan 1 2000.
I've read several posts about similar problems. But, none seem to apply.
Here is my code:
#include <SFE_MicroOLED.h>  // Include the SFE_MicroOLED library
#include <SPI.h>
#include <SD.h>
#include "Wire.h"
#include <RTClib.h>
RTC_DS1307 RTC;
#define BUTTON_PIN       0 // Button
#define LONGPRESS_LEN    25  // Min nr of loops for a long press
#define DELAY            20  // Delay per loop in ms

enum { EV_NONE=0, EV_SHORTPRESS, EV_LONGPRESS };

boolean button_was_pressed; // previous state
int button_pressed_counter; // press running duration

byte zero = 0x00; //workaround for issue #527

char* modes[]={"Walk", "Bike", "Subway", "Train", "Bus", "X-Bus", "Waiting", "Other"};
byte mode=0;
int modeRead;

// Chip Select for SD
#define chipSelect 10

//MicroOLED oled(PIN_RESET, PIN_DC, PIN_CS);
MicroOLED oled(9, 8, 5); // SPI declaration

void setup()
{
    pinMode(BUTTON_PIN, INPUT);
    digitalWrite(BUTTON_PIN, HIGH); // pull-up
    Serial.begin(9600);
    button_was_pressed = false;
    button_pressed_counter = 0;

    SD.begin(chipSelect);

    Wire.begin();
    RTC.begin();
    //RTC.adjust(DateTime(__DATE__, __TIME__));

    oled.begin();    // Initialize the OLED
    oled.clear(PAGE);     // Clear the screen
    oled.setFontType(1);  // Set font to type 0
    oled.setCursor(0, 0); // Set cursor to top-left
    oled.println(F("co'mute"));
    oled.display();  // Display what's in the buffer
}

int handle_button()
{
    int event;
    int button_now_pressed = !digitalRead(BUTTON_PIN); // pin low -> pressed

    if (!button_now_pressed && button_was_pressed) {
        if (button_pressed_counter < LONGPRESS_LEN)
            event = EV_SHORTPRESS;
        else
            event = EV_LONGPRESS;
    }
    else
        event = EV_NONE;

    if (button_now_pressed)
        ++button_pressed_counter;
    else
        button_pressed_counter = 0;

    button_was_pressed = button_now_pressed;
    return event;
}

void printDate ()
{
    oled.clear(PAGE);     // Clear the screen
    oled.setFontType(0);  // Set font to type 0
    oled.setCursor(0, 0); // Set cursor to top-left

    DateTime now = RTC.now();

    oled.print(now.year(), DEC);
    oled.print('/');
    oled.print(now.month(), DEC);
    oled.print('/');
    oled.print(now.day(), DEC);
    oled.print(' ');
    oled.print(now.hour(), DEC);
    oled.print(':');
    if (now.minute()<10) {
        oled.print("0");
    }
    oled.print(now.minute(), DEC);
    oled.print(':');
    if (now.second()<10) {
        oled.print("0");
    }
    oled.print(now.second(), DEC);
    oled.println();
    oled.setFontType(1);  // Set font to type 0
    oled.println(modes[mode]);
    oled.display();   // Display what's in the buffer (splashscreen)
}

void writeFile()
{
    File dataFile = SD.open("datalog.txt", FILE_WRITE);
    // If the file is available, write to it:
    if (dataFile) {
        DateTime now = RTC.now();
        //print the date EG   3/1/11 23:59:59
        dataFile.print(now.year(), DEC);
        dataFile.print('/');
        dataFile.print(now.month(), DEC);
        dataFile.print('/');
        dataFile.print(now.day(), DEC);

        printDate ();
        oled.print("*SAVED*");
        oled.display();
        delay(3000);
    }
}

void loop()          // run over and over again
{
    // handle button
    boolean event = handle_button();

    // do other things
    switch (event) {
        case EV_NONE:
        oled.print(".");
        break;

        case EV_SHORTPRESS:
        oled.print("S");
        //modeRead = analogRead(0);    // read the value from the sensor
        writeFile();
        break;

        case EV_LONGPRESS:
        oled.print("L");
        break;
    }

    static int counter = 0;
    if ((++counter & 0X016) == 0) {
        printDate ();
    }
    modeRead = analogRead(A0);    // read the value from the sensor
    delay(DELAY);

    int c=1020/(sizeof(modes)/sizeof(modes[0]));
    for (int i = 0; i < c; i++) {
        if (i*c < modeRead && (i+1)*c < modeRead) {
            mode = i;
        }
    }
}

In this diagram the "pressure sensor" is really a OLED that operates via MOSI and MISO.

Have you checked the voltage of the RTC battery?

Yes. I've also tried multiple RTC modules that I know work in other projects.

Initial value should be 1 jan 2000, not 2002, according to the datasheet.

Wow!  Spaghetti!  Is your ruler broken or something?!

byte zero = 0x00; //workaround for issue #527 - oh, aye.

yeah it's jan 2000 not 2002

Your schematic doesn't match your code.  Weirdness involving S1 shorting D0 to ground, MOSI/MISO/CLK on A1/A2/A3 vs D11/D12/D13, Code says D10 is chip select for SD board, while schematic shows D7 ... Uh... The RTCLib library will expect to use the chips TWI (I2C) pins (D11/D12/D13), which you're not hooked to.  That would explain the constant zero results from the RTC.

best schematic ever! tnks for share

First off, you should simplify your circuit to only keep the RTC and check if the problem is still here. Also, it would be useful if you could provide the exact reference of the RTC breakout(s) you use, or event just a picture. I am not sure all breakouts include a battery cell to keep time running when chip is not powered.

The RTC board has a battery holder and requires the button battery to be fitted in order to retain the time and date value. As shown in the Datasheet, this battery is for the RTC chip only.

The Adafruit board requires a CR1220 button battery.

The Adafruit webpage mentions the following:

Note: This product does not come with a CR1220 coin cell battery.

(Providing that it works when the Arduino is powered up) It sounds as if the battery for the RTC is either:

not present
not connected (not inserted correctly or not making proper connection)
inserted upside down
a track on the PCB is broken or shorted
the battery is flat

The battery should be inserted so that the flat + side is UP. I suggest that you use a DMM to measure the RTC battery voltage at the RTC IC. Place your +ve probe on pin 3 of the IC and the -ve probe on pin 4. It should read slightly above 3.0 Volts.
I also recommend that you disconnect all of the other periferals so that you just have the RCT connected to the Arduino. Then use a known working program such as the one in the Adafruit tutorial to verify that your RTC is working correctly. You should be able to disconnect the USB and then reconnect it and find that the RTC is still holding the correct time.
RTC DS1307 Datasheet
Adafruit RTC Product
Adafruit RTC Tutorial


text:
Which device to use to measure AC current using Arduino?
I'm building a home automation product and want to measure AC current using Arduino (as of now). I've used ACS712 5A Hall Effect Current module but there's a lot of electrical noise and also the accuracy is not good. There's a lot of deflection in value when no current passes through it. I want to pack the whole kit in a box. So how to make sure that there will be no magnetic interference?
Can you suggest some other module to use for the same? Also that can last long enough.

Some sort of Current Transformer usually does the trick.  You run the AC line (not the neutral) through a ferrite core and it converts current into an output voltage.  You can find them packaged like this one with a web search.


text:
expected initializer before void arduino
When I try to compile the following code in Arduino ,I get the error "expected initializer before 'void'".How can I get the code to work?
  void setup() {
  Serial.begin(9600);
}

float area = 0.0f,pre_area = 0.0f,tarea = 0.0f,rarea = 0.0f;
int x = 0,pre_x = 0,t = 0,pre_t = 0;

long unsigned int t

void loop()
{
  x = analogRead(A0);
  t = millis();
  float diff_t = (float)(t - pre_t)/1000.0f;
  area = (0.5 * (pre_x + x) * diff_t) + pre_area;

  Serial.print(area);
  analogWrite(DAC0, area);
  pre_x = x;
  pre_area = area;
  pre_time = t;
}

Now that the question is answered please flag it as answered

You add the semicolon that is missing at the end of long unsigned int t

Amongst other things. ;)

Why have you written t = 0 here and declared it again below??
int x = 0,pre_x = 0,t = 0,pre_t = 0;

Semi Colon Missing
long unsigned int t;

Where have you declared pre_time??
  pre_time = t;

long unsigned int t

No semicolon.

Plus, make up your mind what type "t" is:
int x = 0,pre_x = 0,t = 0,pre_t = 0;
long unsigned int t;

Is it int or long unsigned int?

How can I get the code to work?

Avoid C++ syntax errors.


text:
How to use the additional SPIs on Arduino Due
According to the following image it is possible to use a second SPI bus on the Arduino Due by using Serial1 and SCL1 as SCK0 for SPI (or Serial2 and SCK1).

source
However I did not find the code necessary to set up the additional SPI interfaces. I would prefer using these SPI interfaces as they are accessible on the stacking headers in contrast to the default SPI.
Additionally can a SD-Card be accessed using these SPI buses while still using the corresponding Arduino Library?

Have you quantified how harder it would be to not use the library?

I think the information you are looking for can be found at https://www.arduino.cc/en/Reference/DueExtendedSPI
There are two other alternatives that I can see: if your device supports slave select (which I think they are supposed to), then you can use a different pin to select either device 1 or device 2 (or 3...).
The other options is that if you can connect the clock to only one slave at a time (again, with another pin), you should get the same result - you should be able to use a MOSFET between the Arduino's clock-out and the slave's clock-in, and hook the MOSFET's gate to a spare pin; repeat the procedure, using a separate MOSFET, connected to a different spare pin, to the second slave; then bring one or the other "spare pin" high, to select which way the clock goes. If a slave does not receive a clock, it will not listen for incoming signal. This last one I dreamed up; I don't know if it will work.


text:
Unable to add multiple potentiometer in Midi controller
I am building a simple arduino based midi controller to send cc midi messages. However I am able to send messages only through A0 (analog input).. Any help on this will be appreciated,..
    #include <MIDI.h>
int pot[] = {A0,A1,A2};
int AnaPinsNum = 3;
int potIn[] = {0,0,0};
int analogValue = 0;

int lastAnalogValue[] = {0,0,0};

 void setup()
 {
  MIDI.begin(4);
  // 115200 hairless MIDI
  Serial.begin(115200);
  int i;
  for (i = 0; i < 3; i++);
 }
 void loop() {

  int i;
  for (i = 0; i < AnaPinsNum; i++)

  potIn[i] = analogRead(pot[i])/8;

  // potentiometer could be too sensitive and
  // give different (+-1) values.
  // send CC only when the difference between last value
  // is more than 1
  if ((potIn[i]-lastAnalogValue[i]) > 1 || (potIn[i]-lastAnalogValue[i]) < -1) {
    // value changed?
    if (potIn[i] != lastAnalogValue[i]) {
      // send serial value (ControlNumber 1, ControlValue = analogValue, Channel 1)
      // more info: http://arduinomidilib.sourceforge.net/a00001.html
      MIDI.sendControlChange(1, potIn[i], 1);
      lastAnalogValue[i] = potIn[i];
    }
  }

}

Perhaps you want to send your values on different channels, or different controllers, instead of all on the same channel/controller combination...?

for (i = 0; i < 3; i++); - what is that line intended to do?

Yes I want to send different CC messages with different channel/value etc. in different inputs

Your logic is flawed here:
  int i;
  for (i = 0; i < AnaPinsNum; i++)
    potIn[i] = analogRead(pot[i]) / 8;

  // potentiometer could be too sensitive and
  // give different (+-1) values.
  // send CC only when the difference between last value
  // is more than 1
  if ((potIn[i] - lastAnalogValue[i]) > 1 || (potIn[i] - lastAnalogValue[i]) < -1) {
    // value changed?
    if (potIn[i] != lastAnalogValue[i]) {
      // send serial value (ControlNumber 1, ControlValue = analogValue, Channel 1)
      // more info: http://arduinomidilib.sourceforge.net/a00001.html
      MIDI.sendControlChange(1, potIn[i], 1);
      lastAnalogValue[i] = potIn[i];
      }
    }

The first three lines read all three analog pins:
  int i;
  for (i = 0; i < AnaPinsNum; i++)

    potIn[i] = analogRead(pot[i]) / 8;

However then, outside the loop, you are using the value of i which will now be 4, and outside the array bounds. You need to bracket the whole lot, eg.
  int i;
  for (i = 0; i < AnaPinsNum; i++)
    {   // <------------------------------- add this
    potIn[i] = analogRead(pot[i]) / 8;

    // potentiometer could be too sensitive and
    // give different (+-1) values.
    // send CC only when the difference between last value
    // is more than 1
    if ((potIn[i] - lastAnalogValue[i]) > 1 || (potIn[i] - lastAnalogValue[i]) < -1)
      {
      // value changed?
      if (potIn[i] != lastAnalogValue[i])
        {
        // send serial value (ControlNumber 1, ControlValue = analogValue, Channel 1)
        // more info: http://arduinomidilib.sourceforge.net/a00001.html
        MIDI.sendControlChange(1, potIn[i], 1);
        lastAnalogValue[i] = potIn[i];
        }  // end of not same as before
      }   // end of value changed
    }   // <----------------- add this

If pot one is sending out Controller number 1 and channel number 1, 2nd pot should send Controller number 2 and channel no 2.

If I understand your question correctly:
Change:
MIDI.sendControlChange(1, potIn[i], 1);

to:
MIDI.sendControlChange(i, potIn[i], i);

Thanks Nick Gammon for the help..I am able to solve the input issue but I am still unable to send different MIDI messages through different input.. For ex if 1st pot is sending value 49 as expression value the next pot should send 50...like different expression value/channel message etc...in the increment of 1

if 1st pot is sending value 49 as expression value - I'm sorry, I don't understand that.

I want to send  values on different channels, or different controllers, instead of all on the same channel/controller.. Right now all the pots are sending out same Messages. I want different pots different messages..

If pot one is sending out Controller number 1 and channel number 1, 2nd pot should send Controller number 2 and channel no 2..

See amended answer.

OK got it. I have made the changes and it works

Sorry Sir.. I have accepted!!


text:
How do I save IR codes from my LG Air Conditioner remote and replay them?
I am currently using the following code

#include <IRremote.h>

int RECV_PIN = 11;
IRrecv irrecv(RECV_PIN);
decode_results results;

void setup()
{
 Serial.begin(9600);
 irrecv.enableIRIn(); // Start the receiver
}

void loop()
{
 if (irrecv.decode(&results))
  {
   Serial.println(results.value, HEX);
   irrecv.resume(); // Receive the next value
  }
 }

The Serial Monitor is always returning "FFFFFFFF" no matter which button I press.
So I am unable to replicate the signal.
Seems that the IR library doesn't support my LG remote.
How do I save and replicate the signal in this case?

Try irrecv.decodeLG(&results)

@Gerben Can you be more specific? Where do I put the line of code?

I tried if (irrecv.decodeLG(&results)) and am getting the following error msg while complilng.

In file included from sketch_aug26c.ino:1:0:
C:\Users\Sravan\Documents\Arduino\libraries\Arduino-IRremote-master/IRremote.h: In function 'void loop()':
C:\Users\Sravan\Documents\Arduino\libraries\Arduino-IRremote-master/IRremote.h:224:10: error: 'bool IRrecv::decodeLG(decode_results*)' is private
bool  decodeLG         (decode_results *results) ;
^
sketch_aug26c:15: error: within this context
within this context

Sorry. That indeed won't work. Add Serial.println(results.decode_type); to get some additional information.

Perhaps it is wired wrongly? Please test with some other device, like your TV, to confirm the hardware part is OK.

@NickGammon No, it is wired correctly. Other remotes including my LG DVD player remote work.

@Gerben I'm getting 11 when I try Serial.println(results.decode_type);

It seems to think it's a SANYO remote. Try looking into recording the raw ir signal. https://gist.github.com/jeje/3027236

@Gerben I'm getting the following text in serial port IR code recorded! Recorded 58 intervals. Sending recorded IR signal! Sending recorded IR signal! Sending recorded IR signal!

You have to modify the code to suit your needs.

@Gerben I am a noob and I don't know what code I have to modify. Sorry. But here is some more info. The remote seems to send not only the power on signal each time it's powered on, but also temperature and other info. I have no idea how to get the raw codes and decode them.

You have to just collect a lot of these signals, then paste them into a text file in hex format, 20-30 collected signals may be enough. Then you start looking for patterns in the collected signals. After you have found the repeating pattern and formatted it so that every repeat is on a new line you should convert the hex into decimal and ascii and see if you can see where is the temperature and other data is. You can also upload it to pastebin and tell us what button did you press with each IR code you received.

@Wally: Did you solve it? I've got the same problem, IRrecvDumpV2 always reads FFFF FFFF from LG air conditioner remote, no matter which key. Also identifies it as Sanyo.


text:
Arduino Program uses less RAM then expected and doesn't run
I am trying to make a program for my Arduino that will run 4 motors with random actions (forward,backward,left,right) and execution is determined by a random number generator. When I compile there is no errors, and The COM port is connected correctly to my Arduino Mega, but when it uploads the log says this:
Sketch uses 668 bytes (0%) of program storage space. Maximum is 253,952 bytes.

Global variables use 9 bytes (0%) of dynamic memory, leaving 8,183 bytes for local variables. Maximum is 8,192 bytes.

That means only 677 B is being used, but the Arduino file is 6 KB. I know that the program gets somewhat smaller when it is compiled, but not ten times smaller.
What's happening here?
EDIT
// Arduino pins for the shift register
#define MOTORLATCH 12
#define MOTORCLK 4
#define MOTORENABLE 7
#define MOTORDATA 8

// 8 bit bus

#define MOTOR1_A 2
#define MOTOR1_B 3
#define MOTOR2_A 1
#define MOTOR2_B 4
#define MOTOR3_A 5
#define MOTOR3_B 7
#define MOTOR4_A 0
#define MOTOR4_B 6

// Motor pins:

#define MOTOR1_PWM 11
#define MOTOR2_PWM 3
#define MOTOR3_PWM 6
#define MOTOR4_PWM 5

// LED Pins

#define led_r 22
#define led_l 23

// Actions

#define RIGHT 0
#define LEFT 1
#define FORWARD 2
#define STOP 3

// Codes for the motor function.
#define GO 1
#define REVERSE 2
#define BRAKE 3
#define RELEASE 4

// Probability

#define rProb 5
#define lProb 5
#define fProb 88
#define stopProb 2

// other globals

#define defSpd 255

void setup() {}

void execute(int action) {

 if (action == FORWARD) {

  motor(1,FORWARD,defSpd);
  motor(2,FORWARD,defSpd);
  motor(3,FORWARD,defSpd);
  motor(4,FORWARD,defSpd);

  digitalWrite(led_r, LOW);
  digitalWrite(led_l, LOW);
 } else if (action == RIGHT) {

  motor(1,REVERSE,defSpd);
  motor(2,REVERSE,defSpd);
  motor(3,FORWARD,defSpd);
  motor(4,FORWARD,defSpd);

  digitalWrite(led_l, LOW);
  digitalWrite(led_r, HIGH);
  delay(150);

 } else if (action == LEFT) {

  motor(1,FORWARD,defSpd);
  motor(2,FORWARD,defSpd);
  motor(3,REVERSE,defSpd);
  motor(4,REVERSE,defSpd);

  digitalWrite(led_l, HIGH);
  digitalWrite(led_r, LOW);

  delay(150);

 } else if (action == STOP) {

  motor(1,BRAKE,defSpd);
  motor(2,BRAKE,defSpd);
  motor(3,BRAKE,defSpd);
  motor(4,BRAKE,defSpd);

  digitalWrite(led_r, HIGH);
  digitalWrite(led_l, HIGH);

  delay(1000);

 }

}

void loop() {
  // put your main code here, to run repeatedly:

  // Random action
  int i = (1, 101);

  if (i > 0 && i <= rProb) {

    execute(RIGHT);

  } else if (i > rProb && i <= rProb + lProb) {

    execute(LEFT);

  } else if (i > rProb + lProb && i <= rProb + lProb + fProb) {

    execute(FORWARD);

  } else if (i > rProb + lProb + fProb && i <= rProb + lProb + fProb + stopProb) {

    execute(STOP);

  }

}

void motor(int nMotor, int command, int speed)
{
  int motorA, motorB;

  if (nMotor >= 1 && nMotor <= 4)
  {
    switch (nMotor)
    {
    case 1:
      motorA   = MOTOR1_A;
      motorB   = MOTOR1_B;
      break;
    case 2:
      motorA   = MOTOR2_A;
      motorB   = MOTOR2_B;
      break;
    case 3:
      motorA   = MOTOR3_A;
      motorB   = MOTOR3_B;
      break;
    case 4:
      motorA   = MOTOR4_A;
      motorB   = MOTOR4_B;
      break;
    default:
      break;
    }

    switch (command)
    {
    case GO:
      motor_output (motorA, HIGH, speed);
      motor_output (motorB, LOW, -1);     // -1: no PWM set
      break;
    case REVERSE:
      motor_output (motorA, LOW, speed);
      motor_output (motorB, HIGH, -1);    // -1: no PWM set
      break;
    case BRAKE:
      // The AdaFruit library didn't implement a brake.
      // The L293D motor driver ic doesn't have a good
      // brake anyway.
      // It uses transistors inside, and not mosfets.
      // Some use a software break, by using a short
      // reverse voltage.
      // This brake will try to brake, by enabling
      // the output and by pulling both outputs to ground.
      // But it isn't a good break.
      motor_output (motorA, LOW, 255); // 255: fully on.
      motor_output (motorB, LOW, -1);  // -1: no PWM set
      break;
    case RELEASE:
      motor_output (motorA, LOW, 0);  // 0: output floating.
      motor_output (motorB, LOW, -1); // -1: no PWM set
      break;
    default:
      break;
    }
  }
}

void motor_output (int output, int high_low, int speed)
{
  int motorPWM;

  switch (output)
  {
  case MOTOR1_A:
  case MOTOR1_B:
    motorPWM = MOTOR1_PWM;
    break;
  case MOTOR2_A:
  case MOTOR2_B:
    motorPWM = MOTOR2_PWM;
    break;
  case MOTOR3_A:
  case MOTOR3_B:
    motorPWM = MOTOR3_PWM;
    break;
  case MOTOR4_A:
  case MOTOR4_B:
    motorPWM = MOTOR4_PWM;
    break;
  default:
    // Use speed as error flag, -3333 = invalid output.
    speed = -3333;
    break;
  }

  if (speed != -3333)
  {
    // Set the direction with the shift register
    // on the MotorShield, even if the speed = -1.
    // In that case the direction will be set, but
    // not the PWM.
    shiftWrite(output, high_low);

    // set PWM only if it is valid
    if (speed >= 0 && speed <= 255)
    {
      analogWrite(motorPWM, speed);
    }
  }
}

void shiftWrite(int output, int high_low)
{
  static int latch_copy;
  static int shift_register_initialized = false;

  // Do the initialization on the fly,
  // at the first time it is used.
  if (!shift_register_initialized)
  {
    // Set pins for shift register to output
    pinMode(MOTORLATCH, OUTPUT);
    pinMode(MOTORENABLE, OUTPUT);
    pinMode(MOTORDATA, OUTPUT);
    pinMode(MOTORCLK, OUTPUT);

    // Set pins for shift register to default value (low);
    digitalWrite(MOTORDATA, LOW);
    digitalWrite(MOTORLATCH, LOW);
    digitalWrite(MOTORCLK, LOW);
    // Enable the shift register, set Enable pin Low.
    digitalWrite(MOTORENABLE, LOW);

    // start with all outputs (of the shift register) low
    latch_copy = 0;

    shift_register_initialized = true;
  }

  // The defines HIGH and LOW are 1 and 0.
  // So this is valid.
  bitWrite(latch_copy, output, high_low);

  // Use the default Arduino 'shiftOut()' function to
  // shift the bits with the MOTORCLK as clock pulse.
  // The 74HC595 shiftregister wants the MSB first.
  // After that, generate a latch pulse with MOTORLATCH.
  shiftOut(MOTORDATA, MOTORCLK, MSBFIRST, latch_copy);
  delayMicroseconds(5);    // For safety, not really needed.
  digitalWrite(MOTORLATCH, HIGH);
  delayMicroseconds(5);    // For safety, not really needed.
  digitalWrite(MOTORLATCH, LOW);
}

Let me look in my crystal ball....  Ah yes, bits are being optimized out because you haven't written your software right.   Post your code, the others here aren't psychic!

@Majenko Code added.

What is:
// Random action
int i = (1, 101);

supposed to achieve?
/tmp/untitled1/untitled1.ino: In function 'void loop()':
/tmp/untitled1/untitled1.ino:110:13: warning: left operand of comma operator has no effect [-Wunused-value]

Ergo, i is always going to be 101.  So all the if constructs will be false, so they get optimized out (they are all constants).  Because of that the other functions are never getting called, so they are optimized out.
So you are left with next to nothing.
I think you may have missed the word random out from there...

Program size: 2798 bytes
Memory size: 17 bytes
Compilation took 0.227 seconds

I believe I saw in some docs that (min,max) could be used to generate random numbers. Obviously not. Thanks!

@GalenNare Only as parameters to the random() function.


text:
Why should a pin be set as an input if it can read input when set as output?
I recently created a circuit to read the value from two sets of buttons using only two analog pins. It involves setting one pin HIGH and reading the input on the other pin and then swapping. With both pins set to OUTPUT I can still read in values with analogRead() without having to keep switching pin modes.
My question is why is that the case? What is the point of setting a pin to INPUT if OUTPUT can still read in values? Are there any disadvantages of doing so?

Just don't expect this to work when changing to some other board. E.g. the Due or Teensy. Other than that there's probably no disadvantage.

The reason for this is because analogRead() has absolutely nothing to do with what mode the pin is in.  That mode only has any meaning in the scope of digital operations - i.e., when using digitalRead() and digitalWrite().  When using analogRead() the Arduino code switches the pin into analog mode first and then reads from it.

Why do the digital operations require a pin mode to be set while analog pins do not?

Because the digital operations are different to the analog operations.  When you do an analogRead the IO pin is isolated from the digital IO circuitry, so the pin mode (which affects the digital IO circuitry) has absolutely no effect on the operation.

It's like your car keys.  You use them for your car, but you don't use them for your bike, yet both of them are in the garage, and they both come out of the same doorway.

My question is why is that the case? What is the point of setting a pin to INPUT if OUTPUT can still read in values? Are there any disadvantages of doing so?

If you do a digitalRead you can read the current latched state of an output pin (it doesn't change it to input). In other words, you read what was last written to it.
If you do a digitalWrite of HIGH to an input pin it sets the internal pull-up. If you write LOW it disables the internal pull-up. If it switched it to output for you, you wouldn't be able to enable or disable the pull-up. (Note: this applies to older versions of the IDE, newer ones have a pinMode setting of INPUT_PULLUP).

What is the point of setting a pin to INPUT if OUTPUT can still read in values?

That certainly won't work with digitalRead because you are writing a value to the pin in OUTPUT mode, so you will merely read back what you are writing. In other words, you have activated the driver transistors, which will override whatever value you are trying to read.

Because I/O pins can be used for either digital input or digital output and can be switched to perform in a given direction. Some of the pins also have an analog capability, either A-to-D conversion (input) or PWM (kind of a psuedo-analog output) but only in one direction permanently assigned by the hardware and therefore not switchable from one to the other.

It is good practice to define them, especially if you program something other then an arduino. For example a port pin on the PCF8574 (Peripheral device) is written as a 1 so you can read it, it has a small internal pull up. If you pull it low in this condition you will read a zero. If you write a zero you will always read a zero. Driving it to a 1 when set to zero can destroy the part. This configuration is also used on microcontrollers. There are hundreds of different port configurations and programming options, it is best to read the data and understand it first otherwise you may be purchasing another.


text:
Is it possible to setup a system based on Arduino Due running QNX?
I would like to create some QNX applications and test them in a hardware different than my virtual machine. Since Arduino Due board is based on the Atmel SAM3X8E ARM Cortex-M3 CPU and QNX® Neutrino® RTOS supports that processor, I was wondering if it is possible make them work together.
What would be the challenges to make it work?

Since Arduino Due board is based on the Atmel SAM3X8E ARM Cortex-M3 CPU and QNX® Neutrino® RTOS supports that processor, I was wondering if it is possible make them work together.

Does QNX really support ARM Cortex-M3? I believe that is not possible as the processor does not have the necessary hardware support.

Please see the BSP list.
Cheers!

Typically the challenge in porting a new OS to a board is to configure stuff like:

system clock (to drive the scheduler of the OS at the right frequence)
board specific I/O
components that are not part of the SoC (but iirc DUE doesn't have any of these)
individual HW blocks (like on which serial port redirect the character interface, if your application has any)
wakeup sources, in case you have/want low power modes and you need the board to wake up when something specific happens

None of these are impossible tasks and they are all good to learn more about the system, but otoh it's unlikely you can rush through them.
The good news is that probably you will not need them all and not immediately.
But some you will have to perform and they will require understanding how your OS works and having the technical reference manual of your board and SoC.

I guess you are talking in general as QNX is not directly open-source??


text:
Arduino as ISP with serial monitor for ATmega328
I have an ATmeg328 TQFP on a board (in system). I use an Arduino Uno as an ISP to programm the chip. However, i would like to use Serial Communication with the chip through the Arduino board.

Is this possible?
If yes, how can i realize this?

EDIT: i have the tx and RX pins not available. The chip is on a board. With through arduino board, I mean that I would like to use the miso mosi sck pins to do this.

What do you mean "through the Arduino board" exactly?

The target chip is connected via ISP to an Arduino Uno. I want to use serial monitor to display information from the target chip, but the chip's only connection is through the Arduino.

Sure, it is possible - you can readily build additional functionality into the Arduiono-as-ISP sketch to accomplish run-time communication with the firmware, potentially including bridging between SPI and asynchronous serial.  But you will have to decide for yourself what exactly is required, and come up with some scheme for switching the interface Arduino between ISP vs. communication-bridge mode.

Using an "FTDI cable" and bootloader may be a little more straight forward. Worst case you can set up the Arduino to act like an FTDI cable after you've burnt the bootloader.

Just burn the arduino bootloader to your tqfp. Then connect the tx and rx on the tqfp to the tx and rx on your arduino, and pull the reset line on the arduino low.
Downside is you have to do a manual reset on the tqfp before programming. If you have an Uno you could remove the atmega from the socket, and connect the reset on the uno to the reset on the tqfp.
Another option is to connect the TX on the tqfp to the TX pin on the Arduino using a resistor. But for this to work you have to modify the ArduinoISP sketch to make it release TX pin (UCSRnB &= ~_BV(UCSRnB);) and set it to input. And reverse it when data is received on the RX. Not trivial, and only works one way (tqfp to PC).

Thanks for the answer, but i don't want to use tx & rx pins

In addition to my previous comment-suggestion that you could implement communication over SPI by adding functionality to both the ISP sketch and the target program, it now occurs to me that another approach would be to implement software serial functionality on both, assigned to some of the pins used for ISP during that process.

as here? Nick Gammon has a sketch which includes an ISP with serial control. Sketch is available on GitHub here


text:
Arduino loses its program under unusual conditions
I have a pretty complicated setup: an ATMEGA328p chip (found in the Uno, Duemilanove, etc.) on a Diavolino board (from EvilMadScientist) running at 8 MHz (instead of the normal 16 MHz).  This should be basically the same thing as the 3.3V arduino pro from the code's point of view.  On top of this is a custom shield including a bunch of digital and analog devices with SPI, I2C, and serial interfaces.
This is supposed to run for days or weeks at a time.  In normal conditions--on the ground outside--it does fine.  However, in two recent tests, it lost its program and stopped working.  One of these was in a cold low-pressure chamber (-40 C/F).  The other was outside mounted on a flying quadcopter.  Reprogramming it fixed the problem; before reprogramming, neither a reset nor power-cycling would get any response from it.
Has anyone ever heard of an arduino bricking itself like that?  My best idea for how this could happen is that somehow the chip was put into a state where it treated incoming serial data as a new program to run.  Also, I'm speculating that connections between the two boards could have been disrupted by thermal contraction or vibration in those tests.
Thanks for any help!

Are you using the watchdog timer at all? It would be virtually impossible for random serial data to be treated as new code.

According to the datasheet it will operate at between -40 °C and 85 °C. -40 C/F - I'm not familiar with the temperature unit "C/F".

Did you disable brownout detection?

C/F just meant it's at both -40 C and -40 F because those are the same.  I don't know anything about the watchdog timer, so I would assume I'm not using it.

And, I did not disable brownout detection.

I would suggest that you reproduce the issue and then use a device capable of reading the flash, to confirm that it's still identical to the .hex file that was used to program the board.
I know that the AVRDragon can do it and maybe also cheaper USB ISP programmers can do it too.
But it seems that you are not alone.
Flash memories like those used in uC work by trapping electrons in wells of charge, so that they pseudo-permanently affect the silicon.
Very low temperatures can change the properties of the insulation, letting many more electrons than usual to escape.
Try to wrap the board in a thermal airtight insulator, possibly providing local heating. That should solve your problems.

Thanks!  Any idea how the quadcopter failure could have happened?  Could vibration somehow cause a similar effect?

I doubt vibration is the cause. Do you have any strong electromagnetic field nearby the processor or any of the cables? Or, more likely, it's a different problem.

Yes, the quadcopter has four brushless motors and two radio transmitters.  Could interference from those really disrupt the flash memory?

As I wrote, most likely not.
But can you reproduce the problem with the quadcopter?
Because it should be easy to remove each potential source of disruption (motors, radios) and see if the memory is still corrupted/wiped.